7520dd10 by Jeff Balicki

password protect

Signed-off-by: Jeff <jeff@gotenzing.com>
1 parent 25937757
Showing 557 changed files with 4833 additions and 0 deletions
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2012 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
require_once('CFDBTransform.php');
class AverageField implements CFDBTransform {
/**
* @var string field holding the value
*/
var $valueField;
/**
* @var string field to group by
*/
var $groupByField;
/**
* @var array of $groupByField => sum
*/
var $sums = array();
/**
* @var array of $groupByField => count
*/
var $counts = array();
function __construct($valueField, $groupByField = null) {
$this->valueField = $valueField;
$this->groupByField = $groupByField;
}
public function addEntry(&$entry) {
if (array_key_exists($this->valueField, $entry) && is_numeric($entry[$this->valueField])) {
$value = $entry[$this->valueField];
$groupByName = empty($this->groupByField) ? $this->valueField : $entry[$this->groupByField];
if ($value !== null && $value !== '') {
if (!array_key_exists($groupByName, $this->sums)) {
$this->sums[$groupByName] = $value;
$this->counts[$groupByName] = 1;
} else {
$this->sums[$groupByName] += $value;
$this->counts[$groupByName]++;
}
}
}
}
public function getTransformedData() {
$data = array();
foreach (array_keys($this->sums) as $name) {
$average = $this->sums[$name] / $this->counts[$name];
if (empty($this->groupByField)) {
$data[] = array($this->valueField => $average);
} else {
$data[] = array($this->groupByField => $name, $this->valueField => $average);
}
}
return $data;
}
}
\ No newline at end of file
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2012 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
require_once('CFDBTransform.php');
/**
* Subclass this class and override getTransformedData() to return different data
*/
class BaseTransform implements CFDBTransform {
var $data = array();
public function addEntry(&$entry) {
$this->data[] = $entry;
}
public function getTransformedData() {
return $this->data;
}
}
\ No newline at end of file
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2012 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
require_once('CF7DBOptionsManager.php');
/**
* The methods in this class are used to track whether or not the plugin has been installed.
* It writes a value in options to indicate that this plugin is installed.
*
* @author Michael Simpson
*/
abstract class CF7DBInstallIndicator extends CF7DBOptionsManager {
const optionInstalled = '_installed';
const optionVersion = '_version';
/**
* @return bool indicating if the plugin is installed already
*/
public function isInstalled() {
return $this->getOption(self::optionInstalled) == true;
}
/**
* Note in DB that the plugin is installed
* @return null
*/
protected function markAsInstalled() {
return $this->updateOption(self::optionInstalled, true);
}
/**
* Note in DB that the plugin is uninstalled
* @return bool returned form delete_option.
* true implies the plugin was installed at the time of this call,
* false implies it was not.
*/
protected function markAsUnInstalled() {
return $this->deleteOption(self::optionInstalled);
}
/**
* Set a version string in the options. This is useful if you install upgrade and
* need to check if an older version was installed to see if you need to do certain
* upgrade housekeeping (e.g. changes to DB schema).
* @return string|null value of the version
*/
protected function getVersionSaved() {
return $this->getOption(self::optionVersion);
}
/**
* Set a version string in the options.
* need to check if
* @param $version string best practice: use a dot-delimited string like '1.2.3' so version strings can be easily
* compared using version_compare (http://php.net/manual/en/function.version-compare.php)
* @return null
*/
protected function setVersionSaved($version) {
return $this->updateOption(self::optionVersion, $version);
}
/**
* @abstract
* @return string name of the main plugin file that has the header section with
* "Plugin Name", "Version", "Description", "Text Domain", etc.
*/
protected abstract function getMainPluginFileName();
/**
* Get a value for input key in the header section of main plugin file.
* E.g. "Plugin Name", "Version", "Description", "Text Domain", etc.
* @param $key string header value name
* @return string if found, otherwise null
*/
public function getPluginHeaderValue($key) {
// Read the string from the comment header of the main plugin file
$data = file_get_contents($this->getPluginDir() . DIRECTORY_SEPARATOR . $this->getMainPluginFileName());
$match = array();
preg_match('/' . $key . ':\s*(\S+)/', $data, $match);
if (count($match) >= 1) {
return $match[1];
}
return null;
}
/**
* If your subclass of this class lives in a different directory,
* override this method with the exact same code. Since __FILE__ will
* be different, you will then get the right dir returned.
* @return string
*/
protected function getPluginDir() {
return dirname(__FILE__);
}
/**
* Version of this code.
* Best practice: define version strings to be easily compared using version_compare()
* (http://php.net/manual/en/function.version-compare.php)
* NOTE: You should manually make this match the SVN tag for your main plugin file 'Version' release and 'Stable tag' in readme.txt
* @return string
*/
public function getVersion() {
return $this->getPluginHeaderValue('Version');
}
/**
* Useful when checking for upgrades, can tell if the currently installed version is earlier than the
* newly installed code. This case indicates that an upgrade has been installed and this is the first time it
* has been activated, so any upgrade actions should be taken.
* @return bool true if the version saved in the options is earlier than the version declared in getVersion().
* true indicates that new code is installed and this is the first time it is activated, so upgrade actions
* should be taken. Assumes that version string comparable by version_compare, examples: '1', '1.1', '1.1.1', '2.0', etc.
*/
public function isInstalledCodeAnUpgrade() {
return $this->isSavedVersionLessThan($this->getVersion());
}
/**
* Used to see if the installed code is an earlier version than the input version
* @param $aVersion string
* @return bool true if the saved version is earlier (by natural order) than the input version
*/
public function isSavedVersionLessThan($aVersion) {
return $this->isVersionLessThan($this->getVersionSaved(), $aVersion);
}
/**
* Used to see if the installed code is the same or earlier than the input version.
* Useful when checking for an upgrade. If you haven't specified the number of the newer version yet,
* but the last version (installed) was 2.3 (for example) you could check if
* For example, $this->isSavedVersionLessThanEqual('2.3') == true indicates that the saved version is not upgraded
* past 2.3 yet and therefore you would perform some appropriate upgrade action.
* @param $aVersion string
* @return bool true if the saved version is earlier (by natural order) than the input version
*/
public function isSavedVersionLessThanEqual($aVersion) {
return $this->isVersionLessThanEqual($this->getVersionSaved(), $aVersion);
}
/**
* @param $version1 string a version string such as '1', '1.1', '1.1.1', '2.0', etc.
* @param $version2 string a version string such as '1', '1.1', '1.1.1', '2.0', etc.
* @return bool true if version_compare of $versions1 and $version2 shows $version1 as the same or earlier
*/
public function isVersionLessThanEqual($version1, $version2) {
return (version_compare($version1, $version2) <= 0);
}
/**
* @param $version1 string a version string such as '1', '1.1', '1.1.1', '2.0', etc.
* @param $version2 string a version string such as '1', '1.1', '1.1.1', '2.0', etc.
* @return bool true if version_compare of $versions1 and $version2 shows $version1 as earlier
*/
public function isVersionLessThan($version1, $version2) {
return (version_compare($version1, $version2) < 0);
}
/**
* Record the installed version to options.
* This helps track was version is installed so when an upgrade is installed, it should call this when finished
* upgrading to record the new current version
* @param $version string optional version string. If not set, uses $this->getVersion()
* @return void
*/
protected function saveInstalledVersion($version = null) {
if (!$version) {
$version = $this->getVersion();
}
if ($version) {
$this->setVersionSaved($version);
}
}
}
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2014 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
require_once('CFDBDeobfuscate.php');
class CF7DBPluginExporter {
static function doExportFromPost() {
// Consolidate GET and POST parameters. Allow GET to override POST.
$params = array_merge($_POST, $_GET);
// print_r($params);
foreach ($params as $key => $value) {
if (is_string($value)) {
$params[$key] = stripslashes($value);
}
}
// Assumes coming from CF7DBPlugin::whatsInTheDBPage()
$key = '3fde789a'; //substr($_COOKIE['PHPSESSID'], - 5); // session_id() doesn't work
if (isset($params['guser'])) {
$params['guser'] = CFDBDeobfuscate::deobfuscateHexString($params['guser'], $key);
}
if (isset($params['gpwd'])) {
$params['gpwd'] = CFDBDeobfuscate::deobfuscateHexString($params['gpwd'], $key);
}
if (!isset($params['enc'])) {
$params['enc'] = 'CSVUTF8';
}
if (!isset($params['form'])) {
$params['form'] = '';
}
CF7DBPluginExporter::export(
$params['form'],
$params['enc'],
$params);
}
static function export($formName, $encoding, $options) {
switch ($encoding) {
case 'HTML':
require_once('ExportToHtmlTable.php');
$exporter = new ExportToHtmlTable();
$exporter->export($formName, $options);
break;
case 'HTMLBOM': // IQY callback
require_once('ExportToHtmlTable.php');
$exporter = new ExportToHtmlTable();
$exporter->setUseBom(true);
$exporter->export($formName, $options);
break;
case 'DT':
require_once('ExportToHtmlTable.php');
if (!is_array($options)) {
$options = array();
}
$options['useDT'] = true;
if (!isset($options['printScripts'])) {
$options['printScripts'] = true;
}
if (!isset($options['printStyles'])) {
$options['printStyles'] = 'true';
}
$exporter = new ExportToHtmlTable();
$exporter->export($formName, $options);
break;
case 'HTMLTemplate':
require_once('ExportToHtmlTemplate.php');
$exporter = new ExportToHtmlTemplate();
$exporter->export($formName, $options);
break;
case 'IQY':
require_once('ExportToIqy.php');
$exporter = new ExportToIqy();
$exporter->export($formName, $options);
break;
case 'CSVUTF8BOM':
$options['unbuffered'] = 'true';
require_once('ExportToCsvUtf8.php');
$exporter = new ExportToCsvUtf8();
$exporter->setUseBom(true);
$exporter->export($formName, $options);
break;
case 'TSVUTF16LEBOM':
$options['unbuffered'] = 'true';
require_once('ExportToCsvUtf16le.php');
$exporter = new ExportToCsvUtf16le();
$exporter->export($formName, $options);
break;
case 'GLD':
require_once('ExportToGoogleLiveData.php');
$exporter = new ExportToGoogleLiveData();
$exporter->export($formName, $options);
break;
case 'GSS':
$options['unbuffered'] = 'true';
require_once('ExportToGoogleSS.php');
$exporter = new ExportToGoogleSS();
$exporter->export($formName, $options);
break;
case 'JSON':
require_once('ExportToJson.php');
$exporter = new ExportToJson();
$exporter->export($formName, $options);
break;
case 'VALUE':
require_once('ExportToValue.php');
$exporter = new ExportToValue();
$exporter->export($formName, $options);
break;
case 'COUNT':
require_once('ExportToValue.php');
if (!is_array($options)) {
$options = array();
}
$options['function'] = 'count';
unset($options['show']);
unset($options['hide']);
$exporter = new ExportToValue();
$exporter->export($formName, $options);
break;
case 'CSVSJIS':
require_once('ExportToCsvUtf8.php');
$exporter = new ExportToCsvUtf8();
$exporter->setUseBom(false);
$exporter->setUseShiftJIS(true);
$exporter->export($formName, $options);
break;
case 'RSS':
require_once('ExportToRSS.php');
$exporter = new ExportToRSS();
$exporter->export($formName, $options);
break;
case 'ENTRY':
require_once('ExportEntry.php');
$exporter = new ExportEntry();
$exporter->export($formName, $options);
break;
case 'CSVUTF8':
default:
require_once('ExportToCsvUtf8.php');
$exporter = new ExportToCsvUtf8();
$exporter->setUseBom(false);
$exporter->export($formName, $options);
break;
}
}
}
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2012 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
require_once('CF7DBInstallIndicator.php');
/**
* All the basic plugin life cycle functionality is implemented herein.
* A Plugin is expected to subclass this class and override method to inject
* its own specific behaviors.
*
* @author Michael Simpson
*/
abstract class CF7DBPluginLifeCycle extends CF7DBInstallIndicator {
public function install() {
// Initialize Plugin Options
$this->initOptions();
// Initialize DB Tables used by the plugin
$this->installDatabaseTables();
// Other Plugin initialization - for the plugin writer to override as needed
$this->otherInstall();
// Record the installed version
$this->saveInstalledVersion();
// To avoid running install() more then once
$this->markAsInstalled();
}
public function uninstall() {
$this->otherUninstall();
$this->unInstallDatabaseTables();
$this->deleteSavedOptions();
$this->markAsUnInstalled();
}
/**
* Perform any version-upgrade activities prior to activation (e.g. database changes)
* @return void
*/
public function upgrade() {
}
public function activate() {
}
public function deactivate() {
}
protected function initOptions() {
}
public function addActionsAndFilters() {
}
protected function installDatabaseTables() {
}
protected function unInstallDatabaseTables() {
}
protected function otherInstall() {
}
protected function otherUninstall() {
}
/**
* Puts the configuration page in the Plugins menu by default.
* Override to put it elsewhere or create a set of submenus
* Override with an empty implementation if you don't want a configuration page
* @return void
*/
public function addSettingsSubMenuPage() {
$this->addSettingsSubMenuPageToPluginsMenu();
//$this->addSettingsSubMenuPageToSettingsMenu();
}
protected function requireExtraPluginFiles() {
require_once(ABSPATH . 'wp-includes/pluggable.php');
require_once(ABSPATH . 'wp-admin/includes/plugin.php');
}
protected function addSettingsSubMenuPageToPluginsMenu() {
$this->requireExtraPluginFiles();
$displayName = $this->getPluginDisplayName();
add_submenu_page('plugins.php',
$displayName,
$displayName,
'manage_options',
get_class($this) . 'Settings',
array(&$this, 'settingsPage'));
}
protected function addSettingsSubMenuPageToSettingsMenu() {
$this->requireExtraPluginFiles();
$displayName = $this->getPluginDisplayName();
add_options_page($displayName,
$displayName,
'manage_options',
get_class($this) . 'Settings',
array(&$this, 'settingsPage'));
}
/**
* @param $name string name of a database table
* @return string input prefixed with the Wordpress DB table prefix
* plus the prefix for this plugin to avoid table name collisions
*/
protected function prefixTableName($name) {
global $wpdb;
return $wpdb->prefix . $this->prefix($name);
}
}
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2012 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
function CF7DBPlugin_init($file) {
require_once('CF7DBPlugin.php');
$aPlugin = new CF7DBPlugin();
// Install the plugin
// NOTE: this file gets run each time you *activate* the plugin.
// So in WP when you "install" the plugin, all that does it dump its files in the plugin-templates directory
// but it does not call any of its code.
// So here, the plugin tracks whether or not it has run its install operation, and we ensure it is run only once
// on the first activation
if (!$aPlugin->isInstalled()) {
$aPlugin->install();
}
else {
// Perform any version-upgrade activities prior to activation (e.g. database changes)
$aPlugin->upgrade();
}
// Add callbacks to hooks
$aPlugin->addActionsAndFilters();
if (!$file) {
$file = __FILE__;
}
// Register the Plugin Activation Hook
register_activation_hook($file, array(&$aPlugin, 'activate'));
// Register the Plugin Deactivation Hook
register_deactivation_hook($file, array(&$aPlugin, 'deactivate'));
}
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2014 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
require_once('CFDBDataIterator.php');
abstract class CFDBAbstractQueryResultsIterator extends CFDBDataIterator {
/**
* @var string
*/
var $submitTimeKeyName;
/**
* @var int
*/
var $limitEnd;
/**
* @var int
*/
var $idx;
/**
* @var int
*/
var $limitStart;
/**
* @var array
*/
var $columns;
/**
* @var CF7DBPlugin
*/
var $plugin;
/**
* @var CFDBEvaluator|CFDBFilterParser|CFDBSearchEvaluator
*/
var $rowFilter;
/**
* @var array
*/
// var $fileColumns;
/**
* @var bool
*/
var $onFirstRow = false;
/**
* Execute the query
* @param $sql string query
* @param $queryOptions array associative
* @return void
*/
abstract public function queryDataSource(&$sql, $queryOptions);
/**
* Get the next row from query results
* @return array associative
*/
abstract public function fetchRow();
/**
* If you do not iterate over all the rows returned, be sure to call this function
* on all remaining rows to free resources.
* @return void
*/
abstract public function freeResult();
/**
* @param $sql string
* @param $rowFilter CFDBEvaluator|CFDBFilterParser|CFDBSearchEvaluator
* @param $queryOptions array
*/
public function query(&$sql, $rowFilter, $queryOptions = array()) {
$this->rowFilter = $rowFilter;
$this->row = null;
$this->plugin = new CF7DBPlugin();
$this->submitTimeKeyName = isset($queryOptions['submitTimeKeyName']) ? $queryOptions['submitTimeKeyName'] : null;
if (isset($queryOptions['limit'])) {
$limitVals = explode(',', $queryOptions['limit']);
if (isset($limitVals[1])) {
$this->limitStart = trim($limitVals[0]);
$this->limitEnd = (int) $this->limitStart + (int) trim($limitVals[1]);
} else if (isset($limitVals[0])) {
$this->limitEnd = trim($limitVals[0]);
}
}
$this->idx = -1;
$this->queryDataSource($sql, $queryOptions);
$this->columns = array();
$this->row = $this->fetchRow();
if ($this->row) {
foreach (array_keys($this->row) as $aCol) {
// hide this metadata column
if ('fields_with_file' != $aCol) {
$this->columns[] = $aCol;
$this->displayColumns[] = $aCol;
}
}
$this->onFirstRow = true;
} else {
$this->onFirstRow = false;
}
}
/**
* Fetch next row into variable
* @return bool if next row exists
*/
public function nextRow() {
while (true) {
if (!$this->onFirstRow) {
$this->row = $this->fetchRow();
}
$this->onFirstRow = false;
if (!$this->row) {
$this->freeResult();
return false;
}
// Format the date
if (!isset($this->row['submit_time']) &&
isset($this->row['Submitted']) && is_numeric($this->row['Submitted'])) {
$submitTime = $this->row['Submitted'];
$this->row['submit_time'] = $submitTime;
$this->row['Submitted'] = $this->plugin->formatDate($submitTime);
}
// Determine if row is filtered
if ($this->rowFilter) {
$match = $this->rowFilter->evaluate($this->row);
if (!$match) {
continue;
}
}
$this->idx += 1;
if ($this->limitStart && $this->idx < $this->limitStart) {
continue;
}
if ($this->limitEnd && $this->idx >= $this->limitEnd) {
while ($this->row = $this->fetchRow()) ;
$this->freeResult();
$this->row = null;
return false;
}
// Keep the unformatted submitTime if needed
if (isset($submitTime) && $this->submitTimeKeyName) {
$this->row[$this->submitTimeKeyName] = $submitTime;
}
break;
}
if (!$this->row) {
$this->freeResult();
}
return $this->row ? true : false;
}
}
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2012 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
class CFDBCheckZendFramework {
/**
* Checks for the existence of the Zend Framework. If not found, prints out some (hopefully) helpful information
* @return bool true if Zend is found, *but* if not found calls wp_die()
*/
public static function checkIncludeZend() {
if (!(include 'Zend/Loader.php')) {
ob_start();
?>
<h1>Missing Zend Framework</h1>
<p>
This function requires part of the Zend framework that interacts with Google. <br/>
It appears that either:
</p>
<ol>
<li>The Zend Framework is not on the include_path or</li>
<li>You do not have the Zend Framework installed</li>
</ol>
<p>
<code>include_path="<?php echo(ini_get('include_path'));?>"</code><br/>
<code>php.ini file is
"<?php $phpInfo = CFDBCheckZendFramework::getPhpInfo(); echo($phpInfo['Loaded Configuration File']);?>
"</code><br/>
</p>
<ol>
<li>locate the the <span style="font-weight: bold;">Zend</span> directory on your computer</li>
<li>If found, here is one way to put it on the include path</li>
<ol>
<li style="list-style: lower-roman">copy the <span style="font-weight: bold;">php.ini</span> file to your WordPress installation to
<span style="font-weight: bold;">[wp-dir]/wp-content/plugins/contact-form-7-to-database-extension/php.ini</span>
</li>
<li style="list-style: lower-roman">add a line to this new file:<br/>
<code>include_path="<?php echo(ini_get('include_path') . PATH_SEPARATOR . "[Zend-parent-directory]");?>"</code>
</li>
</ol>
<li>If not found, install and configure Zend version 1.11.11 (or contact or administrator or host provider)<br/>
See: <a target="_blank" href="http://code.google.com/apis/gdata/articles/php_client_lib.html">Getting
Started
with the Google Data PHP Client Library</a><br/>
To download the part of Zend 1.11.11 required, see: <a target="_blank"
href="http://framework.zend.com/download/gdata/">Zend
GData</a>
</li>
</ol>
<?php
$errorHtml = ob_get_contents();
ob_end_clean();
include_once('CFDBDie.php');
CFDBDie::wp_die($errorHtml,
__('Missing Zend Framework', 'contact-form-7-to-database-extension'),
array('response' => 200, 'back_link' => true));
// Doesn't actually return because we call wp_die
return false;
}
return true;
}
/**
* Taken from: http://www.php.net/manual/en/function.phpinfo.php#87214
* @return array key => array(values) from phpinfo call
*/
private static function getPhpInfo() {
ob_start();
phpinfo(INFO_GENERAL);
$phpinfo = array('phpinfo' => array());
if (preg_match_all('#(?:<h2>(?:<a name=".*?">)?(.*?)(?:</a>)?</h2>)|(?:<tr(?: class=".*?")?><t[hd](?: class=".*?")?>(.*?)\s*</t[hd]>(?:<t[hd](?: class=".*?")?>(.*?)\s*</t[hd]>(?:<t[hd](?: class=".*?")?>(.*?)\s*</t[hd]>)?)?</tr>)#s', ob_get_clean(), $matches, PREG_SET_ORDER))
foreach ($matches as $match)
if (strlen($match[1]))
$phpinfo[$match[1]] = array();
elseif (isset($match[3]))
$phpinfo[end(array_keys($phpinfo))][$match[2]] = isset($match[4]) ? array($match[3], $match[4]) : $match[3];
else
$phpinfo[end(array_keys($phpinfo))][] = $match[2];
return $phpinfo['phpinfo'];
}
}
\ No newline at end of file
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2015 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
require_once('CF7DBPlugin.php');
class CFDBCleanupData {
/**
* @var CF7DBPlugin
*/
var $plugin;
/**
* @param $plugin CF7DBPlugin
*/
function __construct($plugin) {
$this->plugin = $plugin;
}
/**
* Fix entries from different forms with same submit_time
* @return int number of items fixed in the DB
*/
public function cleanupForms() {
global $wpdb;
$table = $this->plugin->getSubmitsTableName();
$sql = sprintf('select * from (select submit_time, count(form_name) as count
from (
select distinct submit_time, form_name from %s) t group by submit_time
) u where count > 1', $table);
$results = $wpdb->get_results($sql, ARRAY_A);
//print_r($results); // debug
if (!$results) {
return 0;
}
$stSql = "select distinct submit_time, form_name from $table where submit_time = %F";
$inDBSql = "select count(submit_time) from $table where submit_time = %F";
$updateSql = "update $table set submit_time = %F where submit_time = %F and form_name = %s";
$count = 0;
foreach ($results as $row) {
$stResults = $wpdb->get_results($wpdb->prepare($stSql, $row['submit_time']), ARRAY_A);
$idx = 0;
foreach ($stResults as $stResult) {
if ($idx++ == 0) {
continue;
}
$newST = $stResult['submit_time'];
while (true) {
$newST = $newST + 0.0001; // Get new submit time
$inDbAlready = $wpdb->get_var($wpdb->prepare($inDBSql, $newST));
if (!$inDbAlready) {
$wpdb->query($wpdb->prepare($updateSql, $newST, $stResult['submit_time'], $stResult['form_name']));
++$count;
break;
}
}
}
}
return $count;
}
public function deleteEmptyEntries() {
$table = $this->plugin->getSubmitsTableName();
global $wpdb;
return $wpdb->query("DELETE FROM $table WHERE field_name = '' AND field_value = ''");
}
/**
* Fix entries in the same form with duplicate submit_time values
* return int
*/
public function cleanupEntries() {
$count = 0;
$table = $this->plugin->getSubmitsTableName();
$dupSql =
"SELECT DISTINCT b.submit_time FROM (
SELECT a.submit_time, a.form_name, a.field_name, count(a.field_value) AS count
FROM $table a
GROUP BY a.submit_time, a.submit_time, a.form_name, a.field_name) b
WHERE b.count > 1";
$deleteWithFieldOrder = "DELETE FROM $table WHERE submit_time = %F AND form_name = %s AND field_name = %s AND field_value = %s AND field_order = %d LIMIT 1";
$deleteNoFieldOrder = "DELETE FROM $table WHERE submit_time = %F AND form_name = %s AND field_name = %s AND field_value = %s AND field_order IS NULL LIMIT 1";
$updateWithFieldOrder = "UPDATE $table SET submit_time = %F WHERE submit_time = %F AND form_name = %s AND field_name = %s AND field_value = %s AND field_order = %d LIMIT 1";
$updateNoFieldOrder = "UPDATE $table SET submit_time = %F WHERE submit_time = %F AND form_name = %s AND field_name = %s AND field_value = %s AND field_order IS NULL LIMIT 1";
$submitTimes = array();
global $wpdb;
$results = $wpdb->get_results($dupSql, ARRAY_A);
foreach ($results as $row) {
$submitTimes[] = $row['submit_time'];
}
$stSql = "SELECT * FROM $table WHERE submit_time = %F";
foreach ($submitTimes as $st) {
$data = array();
$entryNum = 0;
$data[$entryNum] = array();
$results = $wpdb->get_results($wpdb->prepare($stSql, $st));
foreach ($results as $row) {
foreach ($data[$entryNum] as $entry) {
if ($entry->field_name == $row->field_name) {
$entryNum++;
break;
}
}
$data[$entryNum][] = $row;
}
foreach ($data as $idx => $entry) {
//print "\n\n";
//print_r($entry); // debug
$diff = false;
if ($idx > 0) {
// If the entries are identical, delete one.
foreach ($entry as $field) {
$diff = false;
foreach($data[0] as $firstEntryRow) {
if ($field->field_name == $firstEntryRow->field_name) {
if ($field->field_value != $firstEntryRow->field_value) {
$diff = true;
break;
}
}
}
if ($diff) {
break;
}
}
if (!$diff) {
foreach ($entry as $field) {
// Delete duplicate entries
$deleteSql = is_numeric($field->field_order) ?
$wpdb->prepare($deleteWithFieldOrder, $field->submit_time, $field->form_name, $field->field_name, $field->field_value, intval($field->field_order)) :
$wpdb->prepare($deleteNoFieldOrder, $field->submit_time, $field->form_name, $field->field_name, $field->field_value);
//echo "$deleteSql\n"; // debug
$wpdb->query($deleteSql);
}
++$count;
} else {
$newST = $this->getNewSubmitTime($entry[0]->submit_time + 0.0001 * $idx);
foreach ($entry as $field) {
// Give different entries a slightly different submit_time
$updateSql = is_numeric($field->field_order) ?
$wpdb->prepare($updateWithFieldOrder, $newST, $field->submit_time, $field->form_name, $field->field_name, $field->field_value, intval($field->field_order)) :
$wpdb->prepare($updateNoFieldOrder, $newST, $field->submit_time, $field->form_name, $field->field_name, $field->field_value);
//echo "$updateSql\n"; // debug
$wpdb->query($updateSql);
}
++$count;
}
}
}
}
return $count;
}
public function getNewSubmitTime($submitTime) {
global $wpdb;
$table = $this->plugin->getSubmitsTableName();
$inDBSql = 'select count(submit_time) from ' . $table . ' where submit_time = %F';
while (true) {
$submitTime = $submitTime + 0.0001; // Propose new submit time
$inDbAlready = $wpdb->get_var($wpdb->prepare($inDBSql, $submitTime));
if (!$inDbAlready) {
break;
}
}
return $submitTime;
}
}
\ No newline at end of file
<?php
/*
"Contact Form to Database" Copyright (C) 2013 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
include_once('CFDBEvaluator.php');
class CFDBCompositeEvaluator implements CFDBEvaluator {
/**
* @var CFDBEvaluator[]
*/
var $evaluators;
/**
* @param $evaluators CFDBEvaluator[]
*/
public function setEvaluators($evaluators) {
$this->evaluators = $evaluators;
}
public function evaluate(&$data) {
if (is_array($this->evaluators)) {
foreach ($this->evaluators as $anEvaluator) {
if (!$anEvaluator->evaluate($data)) {
return false;
}
}
}
return true;
}
}
\ No newline at end of file
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2014 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
abstract class CFDBDataIterator {
/**
* @var array[name=>value]
*/
var $row;
/**
* @var array
*/
var $displayColumns = array();
/**
* @return array[string]
*/
public function getDisplayColumns() {
return $this->displayColumns;
}
/**
* Fetch next row into variable
* @return bool if next row exists
*/
public abstract function nextRow();
// /**
// * @return array[name=>value]
// */
// public function &getRow() {
// return $this->row;
// }
}
\ No newline at end of file
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2014 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
require_once('CFDBDataIterator.php');
abstract class CFDBDataIteratorDecorator extends CFDBDataIterator {
/**
* @var CFDBDataIterator
*/
var $source;
/**
* @param $source CFDBDataIterator
*/
public function setSource($source) {
$this->source = $source;
}
public function getDisplayColumns() {
if (empty($this->displayColumns)) {
return $this->source->getDisplayColumns();
}
return $this->displayColumns;
}
}
\ No newline at end of file
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2014 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
interface CFDBDateFormatter {
/**
* Format input date string
* @param $time int same as returned from PHP time()
* @return string formatted date according to saved options
*/
public function formatDate($time);
}
\ No newline at end of file
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2014 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
class CFDBDeobfuscate {
// Taken from http://ditio.net/2008/11/04/php-string-to-hex-and-hex-to-string-functions/
static function hexToStr($hex) {
$string = '';
for ($i = 0; $i < strlen($hex) - 1; $i += 2) {
$string .= chr(hexdec($hex[$i] . $hex[$i + 1]));
}
return $string;
}
static function deobfuscateHexString($hex, $key) {
return CFDBDeobfuscate::deobfuscateString(CFDBDeobfuscate::hexToStr($hex), $key);
}
static function deobfuscateString($string, $key) {
return mcrypt_decrypt(MCRYPT_3DES, $key, $string, 'ecb');
}
}
\ No newline at end of file
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2012 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
class CFDBDie {
/**
* Why this function? It is meant to do what wp_die() does. But in
* Ajax mode, wp_die just does die(-1). But in this plugin we are leveraging
* Ajax mode to put in URL hooks to do exports. So it is not really making a in-page
* call to the url, the full page is navigating to it, then it downloads a CSV file for
* example. So if there are errors we want the wp_die() error page. So this
* function is a copy of wp_die without the Ajax mode check.
* @static
* @param string $message HTML
* @param string $title HTML Title
* @param array $args see wp_die
* @return void
*/
static function wp_die($message, $title = '', $args = array()) {
// Code copied from wp_die without it stopping due to AJAX
if ( function_exists( 'apply_filters' ) ) {
$function = apply_filters( 'wp_die_handler', '_default_wp_die_handler');
} else {
$function = '_default_wp_die_handler';
}
call_user_func( $function, $message, $title, $args );
}
}
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2015 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
require_once('CFDBDateFormatter.php');
class CFDBErrorLog {
/**
* @var String path to file to write
*/
var $outputFilePath;
/**
* @var String email address
*/
var $emailAddress;
/**
* @var CFDBDateFormatter
*/
var $dateFormatter;
function __construct($dateFormatter = null, $destination = null) {
$this->dateFormatter = $dateFormatter;
if ($destination) {
if ($this->isEmailAddress($destination)) {
$this->emailAddress = $destination;
} else {
$this->outputFilePath = $destination;
}
}
}
/**
* @param $message String
*/
public function log($message) {
$date = time();
if ($this->dateFormatter) {
$date = $this->dateFormatter->formatDate($date);
}
$fullMessage = sprintf("CFDB Error (%s): %s\n", $date, $message);
if ($this->outputFilePath) {
error_log($fullMessage, 3, $this->outputFilePath);
} else if ($this->emailAddress) {
error_log($fullMessage, 1, $this->emailAddress);
} else {
error_log($fullMessage, 0);
}
}
/**
* @param $ex Exception
*/
public function logException($ex) {
$message = sprintf("%s\n\tat %s:%s\n%s", $ex->getMessage(),
$ex->getFile(), $ex->getLine(),
"\t" . str_replace("\n", "\n\t", $ex->getTraceAsString()));
$this->log($message);
}
public function isEmailAddress($email) {
$pattern = '/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}/';
return (bool)preg_match($pattern, $email);
}
/**
* @return String
*/
public function getOutputFilePath() {
return $this->outputFilePath;
}
/**
* @return String
*/
public function getEmailAddress() {
return $this->emailAddress;
}
}
\ No newline at end of file
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2012 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
interface CFDBEvaluator {
/**
* Evaluate expression against input data
* @param $data array [ key => value]
* @return boolean result of evaluating $data against expression
*/
public function evaluate(&$data);
}
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2012 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
interface CFDBExport {
/**
* @abstract
* @param $formName string
* @param $options array of option_name => option_value
* @return void
*/
public function export($formName, $options = null);
}
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2012 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
/**
* This class is an API for accessing a form and looping through its contents.
* Common shortcode options can be used to show/hide columns, search/filter fields, limit, orderby etc.
* Set them in the input $options array.
* Example code:
* <code>
* // Email all the "Mike"'s
* require_once(ABSPATH . 'wp-content/plugins/contact-form-7-to-database-extension/CFDBFormIterator.php');
* $exp = new CFDBFormIterator();
* $exp->export('my-form', new array('show' => 'name,email', 'search' => 'mike'));
* while ($row = $exp->nextRow()) {
* wp_mail($row['email'], 'Hello ' . $row['name], 'How are you doing?');
* }
*
* </code>
*/
require_once('ExportBase.php');
require_once('CFDBExport.php');
class CFDBFormIterator extends ExportBase implements CFDBExport {
/**
* @var string
*/
var $formName;
/**
* @var CF7DBPlugin
*/
var $plugin;
/**
* Intended to be used by people who what to programmatically loop over the rows
* of a form.
* @param $formName string
* @param $options array of option_name => option_value
* @return void
*/
public function export($formName, $options = null) {
$this->formName = $formName;
$this->setOptions($options);
$this->setCommonOptions();
$this->setDataIterator($formName);
}
/**
* @return array|bool associative array of the row values or false if no more row exists
*/
public function nextRow() {
if ($this->dataIterator->nextRow()) {
$row = array();
$row['submit_time'] = $this->dataIterator->row['submit_time'];
$fields_with_file = null;
if (isset($this->dataIterator->row['fields_with_file']) &&
$this->dataIterator->row['fields_with_file'] != null) {
$fields_with_file = explode(',', $this->dataIterator->row['fields_with_file']);
if ($this->plugin == null) {
require_once('CF7DBPlugin.php');
$this->plugin = new CF7DBPlugin();
}
}
foreach ($this->dataIterator->getDisplayColumns() as $aCol) {
$row[$aCol] = $this->dataIterator->row[$aCol];
if ($aCol == 'filter'){
$row[$aCol] = urldecode($row[$aCol]);
$row[$aCol] = urlencode($row[$aCol]);
}
// If it is a file, add in the URL for it by creating a field name appended with '_URL'
if ($fields_with_file && in_array($aCol, $fields_with_file)) {
$row[$aCol . '_URL'] = $this->plugin->getFileUrl($row['submit_time'], $this->formName, $aCol);
}
}
return $row;
}
else {
return false;
}
}
}
<?php
/*
"Contact Form to Database" Copyright (C) 2013 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
class CFDBFunctionEvaluator {
/**
* @var CFDBValueConverter callback that can be used to pre-process values in the filter string
* passed into parse($filterString).
* For example, a function might take the value '$user_email' and replace it with an actual email address
* just prior to checking it against input data in call evaluate($data)
*/
var $compValuePreprocessor;
/**
* @param $compValuePreprocessor CFDBValueConverter
*/
public function setCompValuePreprocessor($compValuePreprocessor) {
$this->compValuePreprocessor = $compValuePreprocessor;
}
/**
* @param $functionArray array ['function name', 'param1', 'param2', ...]
* @param $data array [name => value]
* @return mixed
*/
public function evaluateFunction($functionArray, &$data) {
$functionName = array_shift($functionArray);
for ($i = 0; $i < count($functionArray); $i++) {
$functionArray[$i] = $this->preprocessValues($functionArray[$i]);
// See if the parameter is a field name that can be dereferenced.
$functionArray[$i] = isset($data[$functionArray[$i]]) ?
$data[$functionArray[$i]] :
$functionArray[$i];
// Dereference PHP Constants
if (defined($functionArray[$i])) {
$functionArray[$i] = constant($functionArray[$i]);
}
}
if (empty($functionArray)) {
// If function has no parameters, pass in the whole form entry associative array
$functionArray[] = &$data;
}
return call_user_func_array($functionName, $functionArray);
}
/**
* @param $text string
* @return mixed
*/
public function preprocessValues($text) {
if ($this->compValuePreprocessor) {
try {
$text = $this->compValuePreprocessor->convert($text);
} catch (Exception $ex) {
trigger_error($ex, E_USER_NOTICE);
}
}
return $text;
}
}
\ No newline at end of file
/*
"Contact Form to Database" Copyright (C) 2011-2014 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
/* This is a script to be used with a Google Spreadsheet to make it dynamically load data (similar to Excel IQuery)
Instructions:
1. Create a new Google Spreadsheet
2. Go to Tools menu -> Script Editor...
3. Click Spreadsheet
4. Copy the text from this file and paste it into the Google script editor.
5. Save and close the script editor.
6. Click on a cell A1 in the Spreadsheet (or any cell)
7. Enter in the cell the formula:
=cfdbdata("site_url", "form_name", "user", "password")
Where the parameters are (be sure to quote them):
site_url: the URL of you site, e.g. "http://www.mywordpress.com"
form_name: name of the form
user: your login name on your WordPress site
pwd: password
*/
/**
* Use this function in your spreadsheet to fetch saved form data from your WordPress Site
* @param site_url your top level WordPress site URL
* @param form_name name of the WordPress form to fetch data from
* @param user login name to your WordPress site. User must have permission to view form data
* @param password WordPress site password. If your site_url is "http" and not "https" then
* beware that your password is being sent unencrypted from a Google server to your WordPress server.
* Also beware that others who can view this code in your Google Spreadsheet can see this password.
* @param "option_name1", "option_value1", "option_name2", "option_value2", ... (optional param pairs).
* These are CFDB option such as "filter", "name=Smith", "show", "first_name,last_name"
* These should come in pairs.
* @returns {*} Your WordPress saved form data in a format suitable for Google Spreadsheet to display.
* String error message if there is an error logging into the WordPress site
*/
function cfdbdata(site_url, form_name, user, password /*, [option_name, option_value] ... */) {
var param_array = [];
param_array.push("action=cfdb-login");
param_array.push("username=" + encodeURI(user));
param_array.push("password=" + encodeURI(password));
param_array.push("cfdb-action=cfdb-export");
param_array.push("enc=JSON");
param_array.push("format=array");
param_array.push("form=" + encodeURI(form_name));
var args = arg_slice(arguments, 4);
args = process_name_value_args(args);
param_array = param_array.concat(args);
return fetch_json_url(site_url, param_array);
}
function fetch_json_url(site_url, param_array) {
var url = site_url + "/wp-admin/admin-ajax.php";
var payload = param_array.join("&");
var response = UrlFetchApp.fetch(url, { method: "post", payload: payload });
var content = response.getContentText();
if (content.indexOf("<strong>ERROR") == 0) {
// If error message is returned, just return that as the content
return content;
}
//Logger.log(content); // For Debugging
return JSON.parse(content);
}
/**
* @deprecated for backward compatibility. Use cfdbdata() instead.
*/
function CF7ToDBData(site_url, form_name, search, user, password) {
if (search != "") {
return cfdbdata(site_url, form_name, user, password, "search", search);
}
return cfdbdata(site_url, form_name, user, password);
}
/**
* "slice" function for varargs Argument object
* @param args Argument object
* @param position int > 0 indicating the slice position
* @returns {Array} of args from the slide index to the end.
* Returns empty array if slice position exceeds length of args
*/
function arg_slice(args, position) {
var array = [];
if (args.length > position) {
for (var i = position; i < args.length; i++) {
array.push(args[i]);
}
}
return array;
}
/**
* Converts array like ['a', '1', 'b', '2'] to ['a=1', 'b=2']
* where each value is made to be URI-encoded.
* Purpose of this is to transform and array of name,value arguments
* into HTTP GET/POST parameters
* @param array Array like ['a', '1', 'b', '2']
* @returns {Array} like ['a=1', 'b=2'].
* where each value (a, 1, b, 2) are URL-Encoded
* If there is an odd number of arguments then the last one is dropped
* (expecting pairs of name,value)
*/
function process_name_value_args(array) {
var name_value_array = [];
var flag = true;
var name = null;
for (var i = 0; i < array.length; i++) {
if (flag) {
name = array[i];
} else {
name_value_array.push(encodeURI(name) + "=" + encodeURI(array[i]));
}
flag = !flag;
}
return name_value_array;
}
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2012 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
header("Content-Type: text/plain");
readfile('CFDBGoogleSSLiveData.js');
?>
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2015 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
class CFDBIntegrationCalderaForms {
/**
* @var CF7DBPlugin
*/
var $plugin;
/**
* @param $plugin CF7DBPlugin
*/
function __construct($plugin) {
$this->plugin = $plugin;
}
public function registerHooks() {
// http://docs.calderaforms.com/caldera_forms_submit_post_process_end/
add_action('caldera_forms_submit_post_process_end', array(&$this, 'saveFormData'), 10, 3);
}
/**
* @param $form array
* @param $referrer array
* @param $process_id string
* @return bool
*/
public function saveFormData($form, $referrer, $process_id) {
try {
// debug
// $this->plugin->getErrorLog()->log('$form: ' . print_r($form, true));
// $this->plugin->getErrorLog()->log('$referrer: ' . print_r($referrer, true));
// $this->plugin->getErrorLog()->log('$process_id: ' . print_r($process_id, true));
// global $processed_data;
// $this->plugin->getErrorLog()->log('$processed_data: ' . print_r($processed_data, true));
$data = $this->convertData($form);
return $this->plugin->saveFormData($data);
} catch (Exception $ex) {
$this->plugin->getErrorLog()->logException($ex);
}
return true;
}
/**
* @param $form array
* @return null|object
*/
public function convertData($form) {
global $processed_data;
if (is_array($form) && is_array($processed_data)) {
$title = $form['name'];
$postedData = array();
$uploadedFiles = array();
$results = $processed_data[$form['ID']];
foreach ($results as $field_id => $field_value) {
if (!array_key_exists($field_id, $form['fields'])) {
// ignore non-field entries _entry_id and _entry_token
continue;
}
$field_name = $form['fields'][$field_id]['label'];
$is_file = $form['fields'][$field_id]['type'] == 'file';
if (is_array($field_value)) {
$postedData[$field_name] = implode(',', $field_value);
} else if ($is_file && $field_value != null) {
// $field_value is a URL to the file like
// http://SITE.com/wp-content/uploads/2015/05/my_file.png
$postedData[$field_name] = basename($field_value);
$path = get_home_path() . $this->getUrlWithoutSchemeHostAndPort($field_value);
$uploadedFiles[$field_name] = $path;
} else {
$postedData[$field_name] = $field_value;
}
}
return (object)array(
'title' => $title,
'posted_data' => $postedData,
'uploaded_files' => $uploadedFiles);
}
return null;
}
/**
* Return the end part of a URL minus the "http://host:port" part
* @param $url string
* @return string|null
*/
public function getUrlWithoutSchemeHostAndPort($url) {
$matches = array();
preg_match('#^http(s)?://[^/]+(.*)#', $url, $matches);
if (count($matches) >= 3) {
return $matches[2];
}
return null;
}
}
\ No newline at end of file
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2015 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
class CFDBIntegrationContactForm7 {
/**
* @var CF7DBPlugin
*/
var $plugin;
/**
* @param $plugin CF7DBPlugin
*/
function __construct($plugin) {
$this->plugin = $plugin;
}
public function registerHooks() {
add_action('wpcf7_before_send_mail', array(&$this, 'saveFormData'));
// Generate submit_time for CF7 mail. Some people complain this causes an error
// so this is now optional and off by default. Seems to be related to CF7
// checking its data against blacklist
if ($this->plugin->getOption('GenerateSubmitTimeInCF7Email', 'false') == 'true') {
add_action('wpcf7_posted_data', array(&$this, 'generateSubmitTimeForCF7'));
}
}
/**
* Callback from Contact Form 7. CF7 passes an object with the posted data which is inserted into the database
* by this function.
* @param $cf7 WPCF7_ContactForm
* @return bool
*/
public function saveFormData($cf7) {
try {
$data = $this->convertData($cf7);
return $this->plugin->saveFormData($data);
} catch (Exception $ex) {
$this->plugin->getErrorLog()->logException($ex);
}
return true;
}
/**
* @param $cf7 WPCF7_ContactForm
* @return object
*/
public function convertData($cf7) {
if (!isset($cf7->posted_data) && class_exists('WPCF7_Submission')) {
// Contact Form 7 version 3.9 removed $cf7->posted_data and now
// we have to retrieve it from an API
$submission = WPCF7_Submission::get_instance();
if ($submission) {
$data = array();
$data['title'] = $cf7->title();
$data['posted_data'] = $submission->get_posted_data();
$data['uploaded_files'] = $submission->uploaded_files();
$data['WPCF7_ContactForm'] = $cf7;
return (object) $data;
}
}
return $cf7;
}
/**
* Generate the submit_time and submit_url so they can be added to CF7 mail
* @param $posted_data array
* @return array
*/
public function generateSubmitTimeForCF7($posted_data) {
try {
$time = $this->plugin->generateSubmitTime();
$posted_data['submit_time'] = $time;
// No longer generating submit_url because it seems to cause CF7 to think it is
// a spam submission and it drops it.
// $url = get_admin_url() . sprintf('admin.php?page=%s&submit_time=%s',
//
// $this->getDBPageSlug(),
// $time);
// $posted_data['submit_url'] = $url;
} catch (Exception $ex) {
$this->plugin->getErrorLog()->logException($ex);
}
return $posted_data;
}
}
\ No newline at end of file
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2015 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
class CFDBIntegrationEnfoldTheme {
/**
* @var CF7DBPlugin
*/
var $plugin;
/**
* @param $plugin CF7DBPlugin
*/
function __construct($plugin) {
$this->plugin = $plugin;
}
public function registerHooks() {
add_filter('avf_form_send', array(&$this, 'saveFormData'), 10, 3);
}
public function saveFormData($bool, $new_post, $form_params) {
// $msg = '$new_post=' . print_r($new_post, true) . "\n" .
// '$form_params=' . print_r($form_params, true);
// $this->plugin->getErrorLog()->log($msg);
try {
if (is_array($new_post)) {
$postedData = array();
foreach ($new_post as $key => $value) {
$postedData[$key] = urldecode($value);
}
$title = 'Enfold';
if (is_array($form_params) &&
isset($form_params['heading']) &&
$form_params['heading']
) {
$title = strip_tags($form_params['heading']);
}
$data = (object)array(
'title' => $title,
'posted_data' => $postedData,
'uploaded_files' => array());
$this->plugin->saveFormData($data);
}
} catch (Exception $ex) {
$this->plugin->getErrorLog()->logException($ex);
}
return true;
}
}
\ No newline at end of file
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2015 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
class CFDBIntegrationFSCF {
/**
* @var CF7DBPlugin
*/
var $plugin;
/**
* @param $plugin CF7DBPlugin
*/
function __construct($plugin) {
$this->plugin = $plugin;
}
public function registerHooks() {
add_action('fsctf_mail_sent', array(&$this->plugin, 'saveFormData'));
add_action('fsctf_menu_links', array(&$this, 'fscfMenuLinks'));
}
/**
* Function courtesy of Mike Challis, author of Fast Secure Contact Form.
* Displays Admin Panel links in FSCF plugin menu
* @return void
*/
public function fscfMenuLinks() {
$displayName = $this->plugin->getPluginDisplayName();
echo '
<p>
' . $displayName .
' | <a href="admin.php?page=' . $this->plugin->getDBPageSlug() . '">' .
__('Database', 'contact-form-7-to-database-extension') .
'</a> | <a href="admin.php?page=CF7DBPluginSettings">' .
__('Database Options', 'contact-form-7-to-database-extension') .
'</a> | <a href="admin.php?page=' . $this->plugin->getShortCodeBuilderPageSlug() . '">' .
__('Build Short Code', 'contact-form-7-to-database-extension') .
'</a> | <a href="http://cfdbplugin.com/">' .
__('Reference', 'contact-form-7-to-database-extension') . '</a>
</p>
';
}
}
\ No newline at end of file
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2015 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
class CFDBIntegrationGravityForms {
/**
* @var CF7DBPlugin
*/
var $plugin;
/**
* @param $plugin CF7DBPlugin
*/
function __construct($plugin) {
$this->plugin = $plugin;
}
public function registerHooks() {
add_action('gform_after_submission', array(&$this, 'saveFormData'), 10, 2);
}
public function saveFormData($entry, $form) {
try {
$data = $this->convertData($entry, $form);
return $this->plugin->saveFormData($data);
} catch (Exception $ex) {
$this->plugin->getErrorLog()->logException($ex);
}
return true;
}
/**
* http://www.gravityhelp.com/documentation/page/Gform_after_submission
* @param $entry Entry Object The entry that was just created.
* http://www.gravityhelp.com/documentation/page/Entry_Object
* @param $form Form Object The current form
* http://www.gravityhelp.com/documentation/page/Form_Object
* @return object
*/
public function convertData($entry, $form) {
//$errorLog = $this->plugin->getErrorLog();
//$errorLog->log('Form Definition: ' . print_r($form, true)); // debug
//$errorLog->log('Entry Definition: ' . print_r($entry, true)); // debug
$postedData = array();
$uploadFiles = array();
// Iterate through the field definitions and get their values
if (!is_array($form['fields'])) {
return true;
}
foreach ($form['fields'] as $field) {
// Gravity Forms 1.8.5 $field was an array
// Gravity Forms 1.9.1.2 $field is an object
if (is_object($field)) {
$field = (array)$field;
}
$fieldName = $field['label'];
if (!empty($field['inputs']) && is_array($field['inputs'])) {
if ($field['type'] == 'checkbox') {
// This is a multi-input field
if (!isset($postedData[$fieldName]) || $postedData[$fieldName] === '') { // handle duplicate empty hidden fields
$values = array();
foreach ($field['inputs'] as $input) {
$inputId = strval($input['id']); // Need string value of number like '1.3'
if (!empty($entry[$inputId])) {
$values[] = $entry[$inputId];
}
}
$postedData[$fieldName] = implode(',', $values);
}
} else {
foreach ($field['inputs'] as $input) {
$inputId = strval($input['id']); // Need string value of number like '1.3'
$label = $input['label']; // Assumption: all inputs have diff labels
$effectiveFieldName = $fieldName;
if (!empty($label)) {
$effectiveFieldName = $fieldName . ' ' . $label;
}
if (!isset($postedData[$effectiveFieldName]) || $postedData[$effectiveFieldName] === '') { // handle duplicate empty hidden fields
$postedData[$effectiveFieldName] = $entry[$inputId];
}
}
}
} else {
$fieldId = $field['id'];
switch ($field['type']) {
case 'list' :
$list = unserialize($entry[$fieldId]);
if ($list) {
// $list may be a list of strings or
// or in the case of Gravity Form List with columns,
/*
Array
(
[0] => Array
(
[Column 1] => hi
[Column 2] => there
[Column 3] => howdy
)
)
*/
if (! empty($list) && is_array($list[0])) {
$colMatrix = array();
foreach ($list as $colArray) {
$colList = array();
foreach ($colArray as $colKey => $colValue) {
$colList[] = $colKey . '=' . $colValue;
}
$colMatrix[] = implode('|', $colList);
}
$postedData[$fieldName] = implode("\n", $colMatrix);
} else {
$postedData[$fieldName] = implode('|', $list);
}
} else {
if (!isset($postedData[$fieldName]) || $postedData[$fieldName] === '') { // handle duplicate empty hidden fields
// List - value is serialized array
$valueArray = @unserialize($entry[$fieldId]);
if (is_array($valueArray)) {
//$postedData[$fieldName] = '';
// Array of (Array of column-name => value)
$tmpArray = array();
foreach ($valueArray as $listArray) {
$tmpArray[] = implode(',', array_values($listArray));
}
$postedData[$fieldName] = implode('|', $tmpArray);
} else {
$postedData[$fieldName] = $entry[$fieldId];
}
}
}
break;
case 'fileupload':
if (!isset($postedData[$fieldName]) || $postedData[$fieldName] === '') { // handle duplicate empty hidden fields
// File Upload - value is file URL
// http://<SITE>/wp-content/uploads/gravity_forms/<PATH>/<FILE>
$url = $entry[$fieldId];
$fileName = basename($url);
$postedData[$fieldName] = $fileName;
$filePath = ABSPATH . substr($url, strlen(get_site_url()));
$uploadFiles[$fieldName] = $filePath;
}
break;
default:
if (!isset($postedData[$fieldName]) || $postedData[$fieldName] === '') { // handle duplicate empty hidden fields
$postedData[$fieldName] = $entry[$fieldId];
}
break;
}
}
}
// Other form metadata
$paymentMetaData = array(
//'currency',
'payment_status', 'payment_date',
'transaction_id', 'payment_amount', 'payment_method',
'is_fulfilled', 'transaction_type');
foreach ($paymentMetaData as $pmt) {
$hasPaymentInfo = false;
if (!empty($entry[$pmt])) {
$postedData[$pmt] = $entry[$pmt];
$hasPaymentInfo = true;
}
if ($hasPaymentInfo && !empty($entry['currency'])) {
// It seems currency is always set but only meaningful
// if the other payment info is set.
$postedData['currency'] = $entry['currency'];
}
}
return (object)array(
'title' => $form['title'],
'posted_data' => $postedData,
'uploaded_files' => $uploadFiles);
}
}
\ No newline at end of file
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2015 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
class CFDBIntegrationJetPack {
/**
* @var CF7DBPlugin
*/
var $plugin;
/**
* @param $plugin CF7DBPlugin
*/
function __construct($plugin) {
$this->plugin = $plugin;
}
public function registerHooks() {
add_action('grunion_pre_message_sent', array(&$this, 'saveFormData'), 10, 3);
}
/**
* @param $post_id int
* @param $all_values array
* @param $extra_values array
* @return object
*/
public function saveFormData($post_id, $all_values, $extra_values) {
try {
$data = $this->convertData($post_id, $all_values);
return $this->plugin->saveFormData($data);
} catch (Exception $ex) {
$this->plugin->getErrorLog()->logException($ex);
}
return true;
}
public function convertData($post_id, $all_values) {
// $errorLog = $this->plugin->getErrorLog();
// $errorLog->log('POST=' . print_r($_POST, true));
// $errorLog->log('$all_values=' . print_r($all_values, true));
// $errorLog->log('$extra_values=' . print_r($extra_values, true));
$title = 'JetPack Contact Form';
if (isset($_POST['contact-form-id'])) {
$title .= ' ' . $_POST['contact-form-id'];
//$all_values['contact-form-id'] = $_POST['contact-form-id'];
}
else {
$title .= ' ' . $post_id;
}
$all_values['post_id'] = $post_id;
return (object) array(
'title' => $title,
'posted_data' => $all_values,
'uploaded_files' => null);
}
}
\ No newline at end of file
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2015 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
class CFDBIntegrationNinjaForms {
/**
* @var CF7DBPlugin
*/
var $plugin;
/**
* @param $plugin CF7DBPlugin
*/
function __construct($plugin) {
$this->plugin = $plugin;
}
public function registerHooks() {
// http://docs.ninjaforms.com/article/106-ninjaformspostprocess
add_action('init', array(&$this, 'registerHook2'));
}
public function registerHook2() {
add_action('ninja_forms_post_process', array(&$this, 'saveFormData'));
}
/**
* @return bool
*/
public function saveFormData() {
try {
$data = $this->convertData();
return $this->plugin->saveFormData($data);
} catch (Exception $ex) {
$this->plugin->getErrorLog()->logException($ex);
}
return true;
}
/**
* @return object
*/
public function convertData() {
/**
* @global $ninja_forms_processing Ninja_Forms_Processing
*/
global $ninja_forms_processing;
// $this->plugin->getErrorLog()->log(
// print_r($ninja_forms_processing, true)); // debug
$postedData = array();
$uploadFiles = array();
// Get all the user submitted values
$submitted_field_ids = array_keys($ninja_forms_processing->get_all_submitted_fields());
$all_fields = $ninja_forms_processing->get_all_fields();
if (is_array($all_fields)) {
foreach ($all_fields as $field_id => $user_value) {
if (in_array($field_id, $submitted_field_ids)) {
if ($ninja_forms_processing->get_field_setting($field_id, 'type') == '_honeypot') {
continue;
}
$field_name = $ninja_forms_processing->get_field_setting($field_id, 'label');
if (is_array($user_value)) {
$postedData[$field_name] = implode(',', $user_value);
} else {
$postedData[$field_name] = $user_value;
}
}
}
}
$formTitle = 'Ninja Form';
if (isset($ninja_forms_processing->data['form']['form_title'])) {
$formTitle = $ninja_forms_processing->data['form']['form_title'];
}
return (object)array(
'title' => $formTitle,
'posted_data' => $postedData,
'uploaded_files' => $uploadFiles);
}
}
\ No newline at end of file
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2015 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
class CFDBIntegrationQuform {
/**
* @var CF7DBPlugin
*/
var $plugin;
/**
* @param $plugin CF7DBPlugin
*/
function __construct($plugin) {
$this->plugin = $plugin;
}
public function registerHooks() {
// http://support.themecatcher.net/quform-wordpress/guides/hooks/iphorm_post_process
add_action('iphorm_post_process', array(&$this, 'saveFormData'), 10, 1);
}
/**
* @param $form iPhorm
* @return bool
*/
public function saveFormData($form) {
try {
$data = $this->convertData($form);
return $this->plugin->saveFormData($data);
} catch (Exception $ex) {
$this->plugin->getErrorLog()->logException($ex);
}
return true;
}
/**
* @param $form iPhorm
* @return object
*/
public function convertData($form) {
// http://support.themecatcher.net/quform-wordpress/guides/basic/getting-form-values
$allValues = $form->getValues();
// $this->plugin->getErrorLog()->log(
// print_r($form, true));
if (is_array($allValues)) {
$postedData = array();
$uploadFiles = array();
foreach ($allValues as $fieldId => $value) {
// $fieldId is something like "iphorm_2_1"
// get the human-readable field label
$fieldName = $fieldId; //iPhorm_Element
$element = $form->getElement($fieldId);
if (is_object($element)) {
$fieldName = $element->getLabel();
}
if (is_array($value)) {
if (array_key_exists('day', $value)) {
$postedData[$fieldName] = sprintf('%s-%s-%s', $value['year'], $value['month'], $value['day']);
} else if (array_key_exists('hour', $value)) {
$postedData[$fieldName] = sprintf('%s:%s %s', $value['hour'], $value['minute'], $value['ampm']);
} else if (array_key_exists(0, $value)) {
if (is_array($value[0])) {
// file upload
foreach ($value as $upload) {
$postedData[$fieldName] = $upload['text'];
$uploadFiles[$fieldName] = $upload['fullPath'];
}
} else {
$postedData[$fieldName] = implode(',', array_values($value));
}
}
} else {
$postedData[$fieldName] = $value;
}
}
return (object)array(
'title' => $form->getName(),
'posted_data' => $postedData,
'uploaded_files' => $uploadFiles);
}
}
}
\ No newline at end of file
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2015 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
class CFDBIntegrationWRContactForm {
/**
* @var CF7DBPlugin
*/
var $plugin;
/**
* @param $plugin CF7DBPlugin
*/
function __construct($plugin) {
$this->plugin = $plugin;
}
public function registerHooks() {
add_action('wr_contactform_before_save_form', array(&$this, 'saveFormData'), 10, 7);
}
/**
* @param $dataForms array
* @param $postID array
* @param $post array
* @param $submissionsData array
* @param $dataContentEmail array
* @param $nameFileByIdentifier array
* @param $requiredField array
* @param $fileAttach array
* @return bool
*/
public function saveFormData($dataForms, $postID, $post, $submissionsData, $dataContentEmail,
$nameFileByIdentifier, $requiredField, $fileAttach) {
try {
$data = $this->convertData($dataForms, $postID, $post, $submissionsData, $dataContentEmail,
$nameFileByIdentifier, $requiredField, $fileAttach);
return $this->plugin->saveFormData($data);
} catch (Exception $ex) {
$this->plugin->getErrorLog()->logException($ex);
}
return true;
}
public function convertData($dataForms, $postID, $post, $submissionsData, $dataContentEmail,
$nameFileByIdentifier, $requiredField, $fileAttach) {
$postedData = array();
$uploadFiles = array();
foreach ($dataContentEmail as $fieldKey => $fieldValue) {
$fieldName = $nameFileByIdentifier[$fieldKey];
if (strpos($fieldKey, 'file_upload_') === 0) {
// Handle upload files
$filePath = $this->parseFileUrl($fieldValue);
if ($filePath) {
$uploadFiles[$fieldName] = $filePath;
}
}
$fieldValue = trim(preg_replace('#<[^>]+>#', ' ', $fieldValue));
$postedData[$fieldName] = $fieldValue;
}
$data = (object)array(
'title' => get_the_title($postID),
'posted_data' => $postedData,
'uploaded_files' => $uploadFiles);
return $data;
}
/**
* @param $fileUrl
* @return string
*/
public function parseFileUrl($fileUrl) {
$href = array();
preg_match('#<a href=\"([^\"]*)/wp-content/([^\"]*)\">(.*)</a>#iU', $fileUrl, $href);
if (count($href) >= 3) {
// [0] => <a href="http://www.site.com/wp-content/uploads/2015/08/Amazon-icon1.png">Amazon.png</a>
// [1] => http://www.site.com
// [2] => uploads/2015/08/Amazon-icon1.png
// [3] => Amazon.png
$wpContentDirPath = dirname(dirname(dirname(__FILE__)));
return $wpContentDirPath . DIRECTORY_SEPARATOR . $href[2];
}
return null;
}
}
\ No newline at end of file
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2014 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
require_once('CFDBFunctionEvaluator.php');
abstract class CFDBParserBase {
/**
* @var CFDBFunctionEvaluator
*/
var $functionEvaluator;
/**
* @var CFDBPermittedFunctions
*/
var $permittedFilterFunctions;
public function __construct() {
$this->functionEvaluator = new CFDBFunctionEvaluator();
}
public abstract function parse($string);
/**
* @param $converter CFDBValueConverter
* @return void
*/
public function setComparisonValuePreprocessor($converter) {
$this->functionEvaluator->setCompValuePreprocessor($converter);
}
/**
* @param $cFDBPermittedFilterFunctions CFDBPermittedFunctions
* @return void
*/
public function setPermittedFilterFunctions($cFDBPermittedFilterFunctions) {
$this->permittedFilterFunctions = $cFDBPermittedFilterFunctions;
}
/**
* To prevent a security hole, not all functions are permitted
* @param $functionName string
* @return bool
*/
public function functionIsPermitted($functionName) {
if ($this->permittedFilterFunctions) {
return $this->permittedFilterFunctions->isFunctionPermitted($functionName);
}
return true;
}
public function parseValidFunction($filterString) {
$parsed = $this->parseFunction($filterString);
if (is_array($parsed)) {
if (!is_callable($parsed[0]) || !$this->functionIsPermitted($parsed[0])) {
return $filterString;
}
}
return $parsed;
}
public function parseValidFunctionOrClassTransform($transString) {
$parsed = $this->parseFunction($transString);
if (!is_array($parsed)) {
return $parsed;
}
if (class_exists($parsed[0])) {
return $parsed;
}
$isFunction = is_callable($parsed[0]);
$isPermitted = $this->functionIsPermitted($parsed[0]);
if ($isFunction && $isPermitted) {
return $parsed;
}
return $transString;
}
/**
* @param $filterString string
* @return string|array if a function like "funct(arg1, arg2, ...)" then returns array['funct', arg1, arg2, ...]
* otherwise just returns the string passed in
*/
public function parseFunction($filterString) {
$matches = array();
// Parse function name
if (preg_match('/^(\w+)\((.*)\)$/', trim($filterString), $matches)) {
$functionArray = array();
$functionArray[] = $matches[1]; // function name
// Parse function parameters
$matches[2] = trim($matches[2]);
if ($matches[2] != '') {
$paramMatches = explode(',', $matches[2]);
foreach ($paramMatches as $param) {
$param = trim($param);
$param = stripslashes($param);
$param = $this->unSingleQuoteString($param);
if ($param != '') {
$functionArray[] = $param;
}
}
}
return $functionArray;
}
return $filterString;
}
/**
* @param $string string
* @return string
*/
public function unSingleQuoteString($string) {
$matches = array();
if (preg_match("/'(.*)'/", $string, $matches)) {
return $matches[1];
}
return $string;
}
/**
* @param $string
* @return array
*/
public function parseORs($string) {
return preg_split('/\|\|/', $string, -1, PREG_SPLIT_NO_EMPTY);
}
/**
* @param $string
* @return array
*/
public function parseANDs($string) {
// Deal with various && encoding problems
$string = html_entity_decode($string);
$retVal = preg_split('/&&/', $string, -1, PREG_SPLIT_NO_EMPTY);
//echo "<pre>Parsed '$filterString' into " . print_r($retVal, true) . '</pre>';
return $retVal;
}
public function setTimezone() {
static $timezoneNotSet = true;
if ($timezoneNotSet && function_exists('get_option')) {
$tz = get_option('CF7DBPlugin_Timezone'); // see CFDBPlugin->setTimezone()
if (!$tz) {
$tz = get_option('timezone_string');
}
if ($tz) {
date_default_timezone_set($tz);
}
$timezoneNotSet = false;
}
}
}
\ No newline at end of file
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2014 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @singleton
*/
class CFDBPermittedFunctions {
var $permitAllFunctions = false;
var $permittedFunctions;
static $defaultPermitted = array(
// PHP functions
'addcslashes',
'addslashes',
'chop',
'chr',
'count_chars',
'localeconv',
'ltrim',
'md5',
'money_format',
'nl2br',
'number_format',
'rtrim',
'sha1',
'str_ireplace',
'str_pad',
'str_repeat',
'str_replace',
'str_shuffle',
'str_word_count',
'strcasecmp',
'strchr',
'strcmp',
'strcoll',
'strcspn',
'strip_tags',
'stripcslashes',
'stripos',
'strlen',
'strnatcasecmp',
'strnatcmp',
'strncasecmp',
'strncmp',
'strpbrk',
'strpos',
'strspn',
'strrev',
'strstr',
'strtok',
'strtolower',
'strtoupper',
'strtr',
'substr',
'substr_compare',
'substr_count',
'substr_replace',
'trim',
'ucfirst',
'ucwords',
'wordwrap',
'date',
'microtime',
'strtotime',
'idate',
'gmstrftime',
'mktime',
'strftime',
'time',
'intval',
'boolval',
'floatval',
'strval',
'bcmul',
'bcdiv',
'abs',
'acos',
'acoh',
'asin',
'asinh',
'atan2',
'atan',
'atanh',
'base_convert',
'bindec',
'ceil',
'cos',
'cosh',
'decbin',
'dechex',
'decoct',
'deg2rad',
'exp',
'expm1',
'floor',
'fmod',
'getrandmax',
'hexdec',
'hypot',
'intdiv',
'is_finite',
'is_infinite',
'is_nan',
'lcg_value',
'log10',
'log1p',
'log',
'max',
'min',
'mb_strtolower',
'mb_check_encoding',
'mb_convert_case',
'mb_convert_encoding',
'mb_convert_kana',
'mb_decode_numericentity',
'mb_detect_encoding',
'mb_detect_order',
'mb_encode_numericentity',
'mb_ereg_match',
'mb_ereg_replace',
'mb_ereg_search_getpos',
'mb_ereg_search_pos',
'mb_ereg_search',
'mb_ereg',
'mb_eregi_replace',
'mb_eregi',
'mb_internal_encoding',
'mb_language',
'mb_preferred_mime_name',
'mb_regex_encoding',
'mb_regex_set_options',
'mb_strcut',
'mb_strimwidth',
'mb_stripos',
'mb_stristr',
'mb_strlen',
'mb_strpos',
'mb_strrchr',
'mb_strrichr',
'mb_strripos',
'mb_strstr',
'mb_strtolower',
'mb_strtoupper',
'mb_strwidth',
'mb_substr_count',
'mb_substr',
'mt_getrandmax',
'mt_rand',
'mt_srand',
'octdec',
'pi',
'pow',
'rad2deg',
'rand',
'round',
'sin',
'sqrt',
'srand',
'tan',
'tanh',
// WordPress-defined functions
'human_time_diff',
'current_time',
// CFDB-defined functions
'concat',
'sum',
'multiply'
);
public function init() {
$this->permittedFunctions = CFDBPermittedFunctions::$defaultPermitted;
}
public static function getInstance() {
static $inst = null;
if ($inst === null) {
$inst = new CFDBPermittedFunctions();
$inst->init();
}
return $inst;
}
public function setPermitAllFunctions($trueOrFalse) {
$this->permitAllFunctions = $trueOrFalse;
}
public function isFunctionPermitted($functionName) {
if ($this->permitAllFunctions === true) {
return true;
} else {
return in_array($functionName, $this->permittedFunctions);
}
}
public function addPermittedFunction($functionName) {
if ($functionName && !in_array($functionName, $this->permittedFunctions)) {
$this->permittedFunctions[] = $functionName;
}
}
}
/**
* A function wrapper to register function names in a CFDBPermittedFunctions singleton
* @param $function_name
*/
function cfdb_register_function($function_name) {
CFDBPermittedFunctions::getInstance()->addPermittedFunction($function_name);
}
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2013 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
require_once('CFDBAbstractQueryResultsIterator.php');
class CFDBQueryResultIterator extends CFDBAbstractQueryResultsIterator {
/**
* @var resource|mysqli_result
*/
var $results;
/**
* @var boolean
*/
var $useMysqli;
/**
* If you do not iterate over all the rows returned, be sure to call this function
* on all remaining rows to free resources.
* @return void
*/
public function freeResult() {
if ($this->results) {
if ($this->useMysqli) {
mysqli_free_result($this->results);
} else {
mysql_free_result($this->results);
}
$this->results = null;
}
}
/**
* @return array associative
*/
public function fetchRow() {
if ($this->useMysqli) {
return mysqli_fetch_assoc($this->results);
} else {
return mysql_fetch_assoc($this->results);
}
}
public function hasResults() {
return !empty($this->results);
}
/**
* @param $sql
* @param $queryOptions
* @return void
*/
public function queryDataSource(&$sql, $queryOptions) {
// For performance reasons, we bypass $wpdb so we can call mysql_unbuffered_query
$this->useMysqli = $this->shouldUseMySqli();
$con = null;
if ($this->useMysqli) {
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (!$con) {
trigger_error("MySQL Connection failed: " . mysqli_error($con), E_USER_NOTICE);
return;
}
} else {
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD, true);
if (!$con) {
trigger_error("MySQL Connection failed: " . mysql_error($con), E_USER_NOTICE);
return;
}
}
// Target charset is in wp-config.php DB_CHARSET
if (defined('DB_CHARSET')) {
if (DB_CHARSET != '') {
global $wpdb;
if (method_exists($wpdb, 'set_charset')) {
$collate = null;
if (defined('DB_COLLATE')) {
if (DB_COLLATE != '') {
$collate = DB_COLLATE;
}
}
$wpdb->set_charset($con, DB_CHARSET, $collate);
} else {
$setCharset = 'SET NAMES \'' . DB_CHARSET . '\'';
if (defined('DB_COLLATE')) {
if (DB_COLLATE != '') {
$setCharset = $setCharset . ' COLLATE \'' . DB_COLLATE . '\'';
}
}
if ($this->useMysqli) {
mysqli_query($con, $setCharset);
} else {
mysql_query($setCharset, $con);
}
}
}
}
if (!$this->useMysqli) {
if (!mysql_select_db(DB_NAME, $con)) {
trigger_error('MySQL DB Select failed: ' . mysql_error(), E_USER_NOTICE);
return;
}
}
if (isset($queryOptions['unbuffered']) && $queryOptions['unbuffered'] === 'true') {
// FYI: using mysql_unbuffered_query disrupted nested shortcodes if the nested one does a query also
if ($this->useMysqli) {
$this->results = mysqli_query($con, $sql, MYSQLI_USE_RESULT);
if (!$this->results) {
trigger_error('mysqli_query failed: ' . mysql_error(), E_USER_NOTICE);
return;
}
} else {
$this->results = mysql_unbuffered_query($sql, $con);
if (!$this->results) {
trigger_error('mysql_unbuffered_query failed: ' . mysql_error(), E_USER_NOTICE);
return;
}
}
} else {
if ($this->useMysqli) {
$this->results = @mysqli_query($con, $sql);
if (!$this->results) {
trigger_error('mysqli_query failed. Try adding <code>unbuffered="true"</code> to your short code. <br/>' . mysql_error(), E_USER_WARNING);
return;
}
} else {
$this->results = @mysql_query($sql, $con);
if (!$this->results) {
trigger_error('mysql_query failed. Try adding <code>unbuffered="true"</code> to your short code. <br/>' . mysql_error(), E_USER_WARNING);
return;
}
}
}
}
public function shouldUseMySqli() {
// This code taken from wp-db.php and adapted
$use_mysqli = false;
if ( function_exists( 'mysqli_connect' ) ) {
if ( defined( 'WP_USE_EXT_MYSQL' ) ) {
$use_mysqli = ! WP_USE_EXT_MYSQL;
} elseif ( version_compare( phpversion(), '5.5', '>=' ) || ! function_exists( 'mysql_connect' ) ) {
$use_mysqli = true;
} elseif ( false !== strpos( $GLOBALS['wp_version'], '-' ) ) {
$use_mysqli = true;
}
}
return $use_mysqli;
}
}
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2014 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
require_once('CFDBWpdbResultIterator.php');
require_once('CFDBWpdbUnbufferedResultIterator.php');
/**
* @singleton
*/
class CFDBQueryResultIteratorFactory {
/**
* @var CFDBAbstractQueryResultsIterator mock instance
*/
var $mock;
public static function getInstance() {
static $inst = null;
if ($inst === null) {
$inst = new CFDBQueryResultIteratorFactory();
}
return $inst;
}
/**
* @param $mock CFDBAbstractQueryResultsIterator mock for CFDBQueryResultIterator
*/
public function setQueryResultsIteratorMock($mock) {
$this->mock = $mock;
}
public function clearMock() {
$this->mock = null;
}
/**
* Factory method for getting a new CFDBQueryResultIterator or mock.
* @param $unbuffered bool
* @return CFDBAbstractQueryResultsIterator (or mock)
*/
public function newQueryIterator($unbuffered = false) {
if ($this->mock) {
return $this->mock;
}
if ($unbuffered) {
return new CFDBWpdbUnbufferedResultIterator;
} else {
return new CFDBWpdbResultIterator;
}
}
}
\ No newline at end of file
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2012 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
include_once('CFDBEvaluator.php');
class CFDBSearchEvaluator implements CFDBEvaluator {
var $search;
public function setSearch($search) {
$this->search = strtolower($search);
}
/**
* Evaluate expression against input data. This is intended to mimic the search field on DataTables
* @param $data array [ key => value]
* @return boolean result of evaluating $data against expression
*/
public function evaluate(&$data) {
if (!$this->search) {
return true;
}
foreach ($data as $key => $value) {
// Any field can match, case insensitive
if (false !== strrpos(strtolower($value), $this->search)) {
return true;
}
}
return false;
}
}
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2013 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
class CFDBShortCodeContentParser {
const BEFORE_START_DELIMITER = '{{BEFORE}}';
const BEFORE_END_DELIMITER = '{{/BEFORE}}';
const AFTER_START_DELIMITER = '{{AFTER}}';
const AFTER_END_DELIMITER = '{{/AFTER}}';
/**
* @param $content string
* @return array[$before, $template, $after]
*/
public function parseBeforeContentAfter($content) {
$before = null;
$startDelimiter = self::BEFORE_START_DELIMITER;
$endDelimiter = self::BEFORE_END_DELIMITER;
$startDelimiterStartPos = strpos($content, $startDelimiter);
$endDelimiterStartPos = strpos($content, $endDelimiter);
if ($startDelimiterStartPos !== false &&
$endDelimiterStartPos !== false &&
$startDelimiterStartPos < $endDelimiterStartPos) {
$startDelimiterEndPos = $startDelimiterStartPos + strlen($startDelimiter);
$endDelimiterEndPos = $endDelimiterStartPos + strlen($endDelimiter);
$before = substr($content, $startDelimiterEndPos, $endDelimiterStartPos - $startDelimiterEndPos);
$content = substr($content, $endDelimiterEndPos, strlen($content) - $startDelimiterEndPos);
}
$after = null;
$startDelimiter = self::AFTER_START_DELIMITER;
$endDelimiter = self::AFTER_END_DELIMITER;
$startDelimiterStartPos = strpos($content, $startDelimiter);
$endDelimiterStartPos = strpos($content, $endDelimiter);
if ($startDelimiterStartPos !== false &&
$endDelimiterStartPos !== false &&
$startDelimiterStartPos < $endDelimiterStartPos) {
$startDelimiterEndPos = $startDelimiterStartPos + strlen($startDelimiter);
$after = substr($content, $startDelimiterEndPos, $endDelimiterStartPos - $startDelimiterEndPos);
$content = substr($content, 0, $startDelimiterStartPos);
}
return array($before, $content, $after);
}
}
\ No newline at end of file
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2012 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
require_once('ShortCodeLoader.php');
class CFDBShortCodeSaveFormMakerSubmission extends ShortCodeLoader {
const FORM_TITLE_FIELD = 'form_title';
const DEFAULT_FORM_TITLE = 'Form Maker';
/**
* @param $atts array (associative) of shortcode inputs
* @param $content string inner content of short code
* @return string shortcode content
*/
public function handleShortcode($atts, $content = null) {
// echo '<pre>';
// print_r($_POST);
// echo "\n";
// print_r($_FILES);
// echo '</pre>';
if (is_array($_POST) && !empty($_POST)) {
$title = isset($_POST[self::FORM_TITLE_FIELD]) ? $_POST[self::FORM_TITLE_FIELD] : self::DEFAULT_FORM_TITLE;
$posted_data = array();
$uploaded_files = array();
// Get posted values
foreach ($_POST as $key => $val) {
$posted_data[$key] = $val;
}
// Deal with upload files
// $_FILES = Array (
// [your-upload] => Array
// (
// [name] => readme.txt
// [type] => text/plain
// [tmp_name] => /tmp/php3tQ1zg
// [error] => 0
// [size] => 1557
// )
//)
if (is_array($_FILES) && !empty($_FILES)) {
foreach ($_FILES as $key => $file) {
if (is_uploaded_file($file['tmp_name'])) {
$posted_data[$key] = $file['name'];
$uploaded_files[$key] = $file['tmp_name'];
}
}
}
// Prepare data structure for call to hook
$data = (object)array('title' => $title,
'posted_data' => $posted_data,
'uploaded_files' => $uploaded_files);
// Call hook to submit data
do_action_ref_array('cfdb_submit', array(&$data));
}
}
}
\ No newline at end of file
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2012 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
require_once('ShortCodeLoader.php');
class CFDBShortCodeSavePostData extends ShortCodeLoader {
const FORM_TITLE_FIELD = 'form_title';
/**
* @param $atts array of short code attributes
* @param $content string not used
* @return void
*/
public function handleShortcode($atts, $content = null) {
$atts = $this->decodeAttributes($atts);
if (is_array($atts) && isset($atts['debug']) && $atts['debug'] == 'true') {
echo '<pre>';
print_r($_POST);
echo "\n";
print_r($_FILES);
echo '</pre>';
}
if (is_array($_POST) && !empty($_POST)) {
$title = isset($_POST[self::FORM_TITLE_FIELD]) ? $_POST[self::FORM_TITLE_FIELD] : 'Untitled';
$posted_data = array();
$uploaded_files = array();
// Get posted values
foreach ($_POST as $key => $val) {
if ($key != self::FORM_TITLE_FIELD) {
$posted_data[$key] = $val;
}
}
// Deal with upload files
// $_FILES = Array (
// [your-upload] => Array
// (
// [name] => readme.txt
// [type] => text/plain
// [tmp_name] => /tmp/php3tQ1zg
// [error] => 0
// [size] => 1557
// )
//)
if (is_array($_FILES) && !empty($_FILES)) {
foreach ($_FILES as $key => $file) {
if (is_uploaded_file($file['tmp_name'])) {
$posted_data[$key] = $file['name'];
$uploaded_files[$key] = $file['tmp_name'];
}
}
}
// Prepare data structure for call to hook
$data = (object)array('title' => $title,
'posted_data' => $posted_data,
'uploaded_files' => $uploaded_files);
// Call hook to submit data
do_action_ref_array('cfdb_submit', array(&$data));
}
}
}
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2012 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
require_once('CFDBShortcodeValue.php');
class CFDBShortcodeCount extends CFDBShortcodeValue {
public function handleShortcode($atts, $content = null) {
$atts = $this->decodeAttributes($atts);
$atts['content'] = $content;
$atts['function'] = 'count';
unset($atts['show']);
unset($atts['hide']);
return parent::handleShortcode($atts, $content);
}
}
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2013 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
require_once('ShortCodeScriptLoader.php');
class CFDBShortcodeDataTable extends ShortCodeScriptLoader {
public function handleShortcode($atts, $content = null) {
$atts['content'] = $content;
$atts['useDT'] = true;
require_once('CFDBShortcodeTable.php');
$sc = new CFDBShortcodeTable();
return $sc->handleShortcode($atts, $content);
}
public function register($shortcodeName) {
parent::register($shortcodeName);
// Unfortunately, can't put styles in the footer so we have to always add this style sheet
// There is an article about how one might go about this here:
// http://beerpla.net/2010/01/13/wordpress-plugin-development-how-to-include-css-and-javascript-conditionally-and-only-when-needed-by-the-posts/
// But it appears to expects posts on the page and I'm concerned it will not work in all cases
// Just enqueuing it causes problems in some pages. Need a targeted way to do this.
// wp_enqueue_style('datatables-demo', 'http://www.datatables.net/release-datatables/media/css/demo_table.css');
}
public function addScript() {
// wp_register_style('datatables-demo', 'http://www.datatables.net/release-datatables/media/css/demo_table.css');
// wp_print_styles('datatables-demo');
// wp_register_script('datatables', 'http://www.datatables.net/release-datatables/media/js/jquery.dataTables.js', array('jquery'), false, true);
wp_enqueue_script('datatables', plugins_url('/', __FILE__) . 'DataTables/media/js/jquery.dataTables.min.js', array('jquery'));
do_action_ref_array('cfdb_edit_enqueue', array());
wp_print_scripts('datatables');
}
}
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2012 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
require_once('ShortCodeLoader.php');
class CFDBShortcodeExportUrl extends ShortCodeLoader {
/**
* @param $atts array of short code attributes
* @param $content string not used
* @return string export link
*/
public function handleShortcode($atts, $content = null) {
$atts = $this->decodeAttributes($atts);
$params = array();
$params[] = admin_url('admin-ajax.php');
$params[] = '?action=cfdb-export';
$special = array('urlonly', 'linktext', 'role');
foreach ($atts as $key => $value) {
if (!in_array($key, $special)) {
$params[] = sprintf('&%s=%s', urlencode($key), urlencode($value));
} else if ($key == 'role') {
require_once('CF7DBPlugin.php');
$plugin = new CF7DBPlugin();
$isAuth = $plugin->isUserRoleEqualOrBetterThan($value);
if (!$isAuth) {
// Not authorized. Print no link.
return '';
}
}
}
$url = implode($params);
if (isset($atts['urlonly']) && $atts['urlonly'] == 'true') {
return $url;
}
$linkText = __('Export', 'contact-form-7-to-database-extension');
if (isset($atts['linktext'])) {
$linkText = $atts['linktext'];
}
return sprintf('<a href="%s">%s</a>', $url, $linkText);
}
}
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2012 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
require_once('ShortCodeLoader.php');
class CFDBShortcodeHtml extends ShortCodeLoader {
/**
* @param $atts array of short code attributes
* @param $content string contents inside the shortcode tag
* @return string value submitted to a form field as selected by $atts. See ExportToValue.php
*/
public function handleShortcode($atts, $content = null) {
if ($content && isset($atts['form'])) {
$atts = $this->decodeAttributes($atts);
$atts['fromshortcode'] = true;
$atts['content'] = $content;
require_once('ExportToHtmlTemplate.php');
$export = new ExportToHtmlTemplate();
return $export->export($atts['form'], $atts);
}
return '';
}
}
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2012 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
require_once('ShortCodeLoader.php');
class CFDBShortcodeJson extends ShortCodeLoader {
/**
* @param $atts array of short code attributes
* @param $content string inner content of short code
* @return string JSON. See ExportToJson.php
*/
public function handleShortcode($atts, $content = null) {
if (isset($atts['form'])) {
$atts = $this->decodeAttributes($atts);
$atts['content'] = $content;
$atts['html'] = true;
$atts['fromshortcode'] = true;
require_once('ExportToJson.php');
$export = new ExportToJson();
return $export->export($atts['form'], $atts);
}
return '';
}
}
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2012 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
require_once('ShortCodeLoader.php');
class CFDBShortcodeTable extends ShortCodeLoader {
/**
* Shortcode callback for writing the table of form data. Can be put in a page or post to show that data.
* Shortcode options:
* [cfdb-table form="your-form"] (shows the whole table with default options)
* Controlling the Display: Apply your CSS to the table; set the table's 'class' or 'id' attribute:
* [cfdb-table form="your-form" class="css_class"] (outputs <table class="css_class"> (default: class="cf7-db-table")
* [cfdb-table form="your-form" id="css_id"] (outputs <table id="css_id"> (no default id)
* [cfdb-table form="your-form" id="css_id" class="css_class"] (outputs <table id="css_id" class="css_class">
* Filtering Columns:
* [cfdb-table form="your-form" show="field1,field2,field3"] (optionally show selected fields)
* [cfdb-table form="your-form" hide="field1,field2,field3"] (optionally hide selected fields)
* [cfdb-table form="your-form" show="f1,f2,f3" hide="f1"] (hide trumps show)
* Filtering Rows:
* [cfdb-table form="your-form" filter="field1=value1"] (show only rows where field1=value1)
* [cfdb-table form="your-form" filter="field1!=value1"] (show only rows where field1!=value1)
* [cfdb-table form="your-form" filter="field1=value1&&field2!=value2"] (Logical AND the filters using '&&')
* [cfdb-table form="your-form" filter="field1=value1||field2!=value2"] (Logical OR the filters using '||')
* [cfdb-table form="your-form" filter="field1=value1&&field2!=value2||field3=value3&&field4=value4"] (Mixed &&, ||)
* @param $atts array of short code attributes
* @param $content string inner content of short code
* @return string HTML output of shortcode
*/
public function handleShortcode($atts, $content = null) {
if (isset($atts['form'])) {
$atts = $this->decodeAttributes($atts);
$atts['content'] = $content;
$atts['canDelete'] = false;
$atts['fromshortcode'] = true;
require_once('ExportToHtmlTable.php');
$export = new ExportToHtmlTable();
return $export->export($atts['form'], $atts);
}
return '';
}
}
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2012 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
require_once('ShortCodeLoader.php');
class CFDBShortcodeValue extends ShortCodeLoader {
/**
* @param $atts array of short code attributes
* @param $content string short code inner content
* @return string value submitted to a form field as selected by $atts. See ExportToValue.php
*/
public function handleShortcode($atts, $content = null) {
if (isset($atts['form'])) {
$atts = $this->decodeAttributes($atts);
$atts['content'] = $content;
$atts['fromshortcode'] = true;
require_once('ExportToValue.php');
$export = new ExportToValue();
return $export->export($atts['form'], $atts);
}
return '';
}
}
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2014 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Interface CFDBTransform for user-defined classes that can be used to transform data
* as it is returned from the database but before it is is formatted for display.
* See: short code "trans" option.
*/
interface CFDBTransform {
/**
* @param $entry array associative array of a single for entry
* @return void
*/
public function addEntry(&$entry);
/**
* Call this when done adding entries. Apply transform across all entered data,
* then return the entire set. The returned set may be entirely different data than
* what was input (e.g. statistics)
* @return array of associative of array of data.
*/
public function getTransformedData();
}
\ No newline at end of file
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2014 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
//require_once('CFDBTransform.php');
require_once('CFDBDataIteratorDecorator.php');
class CFDBTransformByClassIterator extends CFDBDataIteratorDecorator {
/**
* @var CFDBTransform
*/
var $transformObject;
/**
* @var array[array[name=>value], ...] transformed data set
*/
var $transformedData;
/**
* @var int
*/
var $count;
/**
* @var int
*/
var $idx;
/**
* @param $transformObject CFDBTransform interface but allow for duck-typing
*/
public function setTransformObject($transformObject) {
$this->transformObject = $transformObject;
}
/**
* Fetch next row into variable
* @return bool if next row exists
*/
public function nextRow() {
if (!$this->transformedData) {
$this->initData();
$this->idx = 0;
return $this->count > 0;
} else {
if (++$this->idx < $this->count) {
$this->row =& $this->transformedData[$this->idx];
return true;
} else {
return false;
}
}
}
/**
* @return bool
*/
protected function initData() {
if ($this->transformedData) {
return; // Already initialized
}
// Loop the entire $source data set and transform it.
while ($this->source->nextRow()) {
$this->transformObject->addEntry($this->source->row);
}
// Transform the data
$this->transformedData = $this->transformObject->getTransformedData();
// Init count for iteration
$this->count = count($this->transformedData);
if ($this->count > 0) {
$this->idx = -1; // nextRow will ++ it
$this->row =& $this->transformedData[0];
}
}
public function getDisplayColumns() {
if (empty($this->displayColumns)) {
$sourceDisplayCols = parent::getDisplayColumns(); // gets form source transform
$this->fixDisplayColumns($sourceDisplayCols);
return $this->displayColumns;
}
return $this->displayColumns;
}
protected function fixDisplayColumns($sourceDisplayCols) {
if (empty($this->transformedData)) {
$this->initData();
}
if (!empty($this->displayColumns)) {
return;
}
$dataCols = null;
if ($this->transformedData == null ||
!isset($this->transformedData[0]) ||
!is_array($this->transformedData[0])) {
$dataCols = array();
} else {
$dataCols = array_keys($this->transformedData[0]);
}
$newDisplayColumns = array();
foreach ($sourceDisplayCols as $col) {
if (in_array($col, $dataCols)) {
$newDisplayColumns[] = $col;
}
}
// Ignore metadata columns for purposes of determining display columns)
$metadataCols = array('fields_with_file', 'submit_time', 'Submit_Time_Key');
foreach ($dataCols as $col) {
if (!in_array($col, $metadataCols) && !in_array($col, $newDisplayColumns)) {
$newDisplayColumns[] = $col;
}
}
$this->displayColumns = $newDisplayColumns;
}
}
\ No newline at end of file
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2014 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
require_once('CFDBDataIteratorDecorator.php');
class CFDBTransformByFunctionIterator extends CFDBDataIteratorDecorator {
/**
* @var array
*/
var $functionArray;
/**
* @var CFDBFunctionEvaluator
*/
var $functionEvaluator;
/**
* @var string name of field to assign the returned value of the function
*/
var $fieldToAssign;
/**
* @param array $functionArray [function_name, arg1, arg2, ...]
*/
public function setFunctionArray($functionArray) {
$this->functionArray = $functionArray;
}
/**
* @param $functionEvaluator CFDBFunctionEvaluator
*/
public function setFunctionEvaluator($functionEvaluator) {
$this->functionEvaluator = $functionEvaluator;
}
/**
* @param string $fieldToAssign
*/
public function setFieldToAssign($fieldToAssign) {
$this->fieldToAssign = $fieldToAssign;
}
/**
* Fetch next row into variable
* @return bool if next row exists
*/
public function nextRow() {
if ($this->source->nextRow()) {
$this->row =& $this->source->row;
if (empty($this->displayColumns) && !empty($this->source->displayColumns)) {
$this->displayColumns = $this->source->displayColumns;
}
$origKeys = array_keys($this->row);
$functionReturn = $this->functionEvaluator->evaluateFunction($this->functionArray, $this->row);
if ($this->fieldToAssign) {
$this->source->row[$this->fieldToAssign] = $functionReturn;
if (!in_array($this->fieldToAssign, $this->displayColumns)) {
$this->displayColumns[] = $this->fieldToAssign;
}
} else if ($functionReturn === null || is_array($functionReturn)) {
// $functionReturn when a reference was passed in and row may be modified
// New row returned
if (is_array($functionReturn)) {
// function returns new array for the entry
$this->source->row = $functionReturn;
$this->row =& $this->source->row;
}
// Reconcile display columns
// 1. Check for the addition of new columns to add to displays
$newFieldsSeen = array();
$newKeys = array_keys($this->row);
$addedKeys = array_diff($newKeys, $origKeys);
if (!empty($addedKeys)) {
foreach ($addedKeys as $add) {
if (!in_array($add, $this->displayColumns)) {
$this->displayColumns[] = $add;
$newFieldsSeen[] = $add;
}
}
}
// 2. Remove display columns that no longer exist
$updatedDisplays = array();
foreach($this->displayColumns as $aDisplay) {
if (in_array($aDisplay, $newKeys) || in_array($aDisplay, $newFieldsSeen)) {
$updatedDisplays[] = $aDisplay;
}
}
$this->displayColumns = $updatedDisplays;
}
return true;
}
return false;
}
public function getDisplayColumns() {
if (empty($this->displayColumns)) {
$cols = $this->source->getDisplayColumns();
if ($this->fieldToAssign && !in_array($this->fieldToAssign, $cols)) {
$cols[] = $this->fieldToAssign;
return $cols;
}
}
return $this->displayColumns;
}
}
\ No newline at end of file
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2014 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
require_once('CFDBAbstractQueryResultsIterator.php');
require_once('CFDBDataIteratorDecorator.php');
class CFDBTransformEndpoint extends CFDBDataIteratorDecorator {
/**
* @var CFDBTransformEndpointQueryResultsIterator
*/
var $postProcessor;
function __construct() {
$this->postProcessor = new CFDBTransformEndpointQueryResultsIterator($this);
}
/**
* Fetch next row into variable
* @return bool if next row exists
*/
public function nextRow() {
if ($this->postProcessor->nextRow()) {
$this->row =& $this->source->row;
if (empty($this->displayColumns)) {
$this->displayColumns =& $this->source->displayColumns;
}
return true;
} else {
$this->row = null;
return false;
}
}
/**
* @return CFDBTransformEndpointQueryResultsIterator
*/
public function getPostProcessor() {
return $this->postProcessor;
}
}
class CFDBTransformEndpointQueryResultsIterator extends CFDBAbstractQueryResultsIterator {
/**
* @var CFDBTransformEndpoint
*/
var $endPoint;
function __construct($endPoint) {
$this->endPoint = $endPoint;
}
/**
* Execute the query
* @param $sql string query
* @param $queryOptions array associative
* @return void
*/
public function queryDataSource(&$sql, $queryOptions) {
// Do nothing. Data is in $this->$endPoint->source
}
/**
* Get the next row from query results
* @return array associative
*/
public function fetchRow() {
if($this->endPoint->source->nextRow()) {
return $this->endPoint->source->row;
}
return null;
}
/**
* @return boolean
*/
public function hasResults() {
// this is called by nextRow() in superclass
// return true and let next row sort it out
return true;
}
/**
* If you do not iterate over all the rows returned, be sure to call this function
* on all remaining rows to free resources.
* @return void
*/
public function freeResult() {
// Do nothing
}
}
\ No newline at end of file
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2014 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
require_once('CFDBParserBase.php');
require_once('CFDBTransformByFunctionIterator.php');
require_once('CFDBTransformByClassIterator.php');
require_once('CFDBTransformEndpoint.php');
// Includes these just to have them as known classes in case they are in the transform.
require_once('SortByField.php');
require_once('SortByMultiField.php');
require_once('NaturalSortByField.php');
require_once('NaturalSortByMultiField.php');
require_once('SortByDateField.php');
require_once('SummationRow.php');
require_once('CountField.php');
require_once('SumField.php');
require_once('MinField.php');
require_once('MaxField.php');
require_once('AverageField.php');
require_once('TotalField.php');
require_once('cfdb-transform-functions.php');
class CFDBTransformParser extends CFDBParserBase {
var $tree = array();
/**
* @var array[CFDBDataIterator]
*/
var $transformIterators = array();
public function getExpressionTree() {
return $this->tree;
}
public function parse($string) {
$arrayOfANDedStrings = $this->parseANDs($string); // e.g. "xx=yy()&&zz()" -> ["xx=yy(a,b,c)", "zz"]
foreach ($arrayOfANDedStrings as $expressionString) {
$rawExpression = $this->parseExpression(trim($expressionString)); // e.g. ["xx" "=" "yy(a,b,c)"] or ["zz"]
if (empty($rawExpression)) {
continue;
}
$expression = array();
$function = null;
if (count($rawExpression) >= 3) { // e.g. ["xx" "=" "yy(a,b,c)"]
$expression[] = trim($rawExpression[0]); // field name
$expression[] = trim($rawExpression[1]); // =
$function = trim($rawExpression[2]); // function call
} else {
$function = trim($rawExpression[0]); // function call
}
$function = $this->parseValidFunctionOrClassTransform($function); // ["zz(a,b,c)"] -> ["zz", "a", "b", "c"]
if (is_array($function)) {
$expression = array_merge($expression, $function);
} else {
$expression[] = $function;
}
$this->tree[] = $expression;
}
}
/**
* Parse a comparison expression into its three components
* @param $comparisonExpression string in the form 'value1' . 'operator' . 'value2' where
* operator is a php comparison operator or '='
* @return array of string [ value1, operator, value2 ]
*/
public function parseExpression($comparisonExpression) {
return preg_split('/(=)/', $comparisonExpression, -1,
PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
}
public function setupTransforms() {
if ($this->tree) {
/** @var $previousTransformIterator CFDBDataIteratorDecorator */
$previousTransformIterator = null;
foreach ($this->tree as $transformArray) {
// [field, =, func, a1, a2, ...] or [func] or [class] or [class, a1, a2, ...]
$transform = null;
if (!empty($transformArray)) {
$transform = null;
if (class_exists($transformArray[0])) {
$reflect = new ReflectionClass($transformArray[0]);
$args = array_slice($transformArray, 1);
$instance = $reflect->newInstanceArgs($args);
$transform = new CFDBTransformByClassIterator();
/** @var $instance CFDBTransform */
$transform->setTransformObject($instance);
} else {
// assume it is a function
$transform = new CFDBTransformByFunctionIterator();
$transform->setFunctionEvaluator($this->functionEvaluator);
if (count($transformArray) > 1 && $transformArray[1] == '=') {
// [field_name, =, function_name, arg1, arg2, ...]
$transform->setFieldToAssign($transformArray[0]);
$transform->setFunctionArray(array_slice($transformArray, 2));
} else {
// [function_name, arg1, arg2, ...]
$transform->setFunctionArray($transformArray);
}
}
// Set the data source for each transform as the previous transform
// to set up a pipeline/decorator pattern.
// The first transform is left with null data source to be hooked up later
// to query results.
$transform->setSource($previousTransformIterator); // is null for first one
$previousTransformIterator = $transform;
$this->transformIterators[] = $transform;
}
}
if ($previousTransformIterator) {
// Stick a CFDBTransformEndpoint at the end of the list of transforms
$transform = new CFDBTransformEndpoint();
$transform->setSource($previousTransformIterator);
$this->transformIterators[] = $transform;
}
}
}
/**
* @param $dataSource CFDBDataIterator
*/
public function setDataSource($dataSource) {
if (count($this->transformIterators) > 0) {
$this->transformIterators[0]->setSource($dataSource);
}
}
/**
* @return CFDBDataIteratorDecorator
*/
public function getIterator() {
return end($this->transformIterators);
}
}
\ No newline at end of file
<?php
/*
"Contact Form to Database" Copyright (C) 2011-2012 Michael Simpson (email : michael.d.simpson@gmail.com)
This file is part of Contact Form to Database.
Contact Form to Database is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Contact Form to Database is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Contact Form to Database.
If not, see <http://www.gnu.org/licenses/>.
*/
interface CFDBValueConverter {
/**
* @abstract
* @param $value mixed object to convert
* @return mixed converted value
*/
public function convert($value);
}
This diff could not be displayed because it is too large.