Related
My Dear Buddies,
I need your help to make captcha case sensitive phpfox,
i want to make captcha not case sensitive in my phpfox site. please help me.
i can not find code for change case sensitivity in phpfox captcha module, and there is no any settings in phpfox backend for that so ple help me.
here is code of
captcha.class.php
<?php
/**
* [PHPFOX_HEADER]
*/
defined('PHPFOX') or exit('NO DICE!');
/**
*
*
* #copyright [PHPFOX_COPYRIGHT]
* #author Raymond Benc
* #package Module_Captcha
* #version $Id: captcha.class.php 6005 2013-06-06 14:12:12Z Raymond_Benc $
*/
class Captcha_Service_Captcha extends Phpfox_Service
{
private $_oSession;
/**
* Class constructor
*/
public function __construct()
{
$this->_oSession = Phpfox::getService('log.session');
}
public function checkHash($sCode = null)
{
if (Phpfox::getParam('captcha.recaptcha'))
{
require_once(PHPFOX_DIR_LIB . 'recaptcha' . PHPFOX_DS . 'recaptchalib.php');
if (isset($_POST["recaptcha_response_field"]))
{
$oResp = recaptcha_check_answer(Phpfox::getParam('captcha.recaptcha_private_key'), $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);
if ($oResp->is_valid){
return true;
}else{
return false;
}
}
return false;
}
if (Phpfox::getParam('core.store_only_users_in_session'))
{
$oSession = Phpfox::getLib('session');
$sSessionHash = $oSession->get('sessionhash');
$aRow = $this->database()->select('*')
->from(Phpfox::getT('log_session'))
->where('session_hash = \'' . $this->database()->escape($sSessionHash) . '\'')
->execute('getSlaveRow');
if (isset($aRow['session_hash']) && $this->_getHash(strtolower($sCode), $aRow['session_hash']) == $aRow['captcha_hash'])
{
return true;
}
}
else
{
if ($this->_getHash(strtolower($sCode), $this->_oSession->getSessionId()) == $this->_oSession->get('captcha_hash'))
{
return true;
}
}
return false;
}
public function setHash($sCode)
{
if (Phpfox::getParam('core.store_only_users_in_session'))
{
$oRequest = Phpfox_Request::instance();
$oSession = Phpfox::getLib('session');
$sSessionHash = $oSession->get('sessionhash');
$bCreate = true;
if (!empty($sSessionHash))
{
$bCreate = false;
$aRow = $this->database()->select('*')
->from(Phpfox::getT('log_session'))
->where('session_hash = \'' . $this->database()->escape($sSessionHash) . '\'')
->execute('getSlaveRow');
if (isset($aRow['session_hash']))
{
$this->database()->update(Phpfox::getT('log_session'), array('captcha_hash' => $this->_getHash($sCode, $sSessionHash)), "session_hash = '" . $sSessionHash . "'");
}
else
{
$bCreate = true;
}
}
if ($bCreate)
{
$sSessionHash = $oRequest->getSessionHash();
$this->database()->insert(Phpfox::getT('log_session'), array(
'session_hash' => $sSessionHash,
'id_hash' => $oRequest->getIdHash(),
'captcha_hash' => $this->_getHash($sCode, $sSessionHash),
'user_id' => Phpfox::getUserId(),
'last_activity' => PHPFOX_TIME,
'location' => '',
'is_forum' => '0',
'forum_id' => 0,
'im_hide' => 0,
'ip_address' => '',
'user_agent' => ''
)
);
$oSession->set('sessionhash', $sSessionHash);
}
}
else
{
$iId = $this->_oSession->getSessionId();
$this->database()->update(Phpfox::getT('log_session'), array('captcha_hash' => $this->_getHash($sCode, $iId)), "session_hash = '" . $iId . "'");
}
}
public function displayCaptcha($sText)
{
((Phpfox::getParam('captcha.captcha_use_font') && function_exists('imagettftext')) ? $this->_writeFromFont($sText) : $this->_writeFromString($sText));
ob_clean();
header("X-Content-Encoded-By: phpFox " . PhpFox::getVersion());
header("Pragma: no-cache");
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Content-Type: image/jpeg');
imagejpeg($this->_hImg);
imagedestroy($this->_hImg);
}
public function generateCode($sCharacters)
{
$sPossible = Phpfox::getParam('captcha.captcha_code');
$sCode = '';
$i = 0;
while ($i < $sCharacters)
{
$sCode .= substr($sPossible, mt_rand(0, strlen($sPossible)-1), 1);
$i++;
}
return strtolower($sCode);
}
/**
* If a call is made to an unknown method attempt to connect
* it to a specific plug-in with the same name thus allowing
* plug-in developers the ability to extend classes.
*
* #param string $sMethod is the name of the method
* #param array $aArguments is the array of arguments of being passed
*/
public function __call($sMethod, $aArguments)
{
/**
* Check if such a plug-in exists and if it does call it.
*/
if ($sPlugin = Phpfox_Plugin::get('captcha.service_captcha__call'))
{
return eval($sPlugin);
}
/**
* No method or plug-in found we must throw a error.
*/
Phpfox_Error::trigger('Call to undefined method ' . __CLASS__ . '::' . $sMethod . '()', E_USER_ERROR);
}
private function _getHash($sCode, $sSalt)
{
return md5(md5($sCode) . $sSalt);
}
private function _writeFromFont($sText)
{
$iString = strlen($sText);
$iWidth = (($iString + 5) * 10 * 2);
$iHeight = 45;
$iTextSize = 20;
$sFont = Phpfox::getParam('core.dir_static') . 'image/font/' . Phpfox::getParam('captcha.captcha_font');
if (!file_exists($sFont))
{
return $this->_writeFromString($sText);
}
$this->_imageCreate($iWidth, $iHeight);
$nBgColor = imageColorAllocate($this->_hImg, 255, 255, 255);
$nTxtColor = imageColorAllocate($this->_hImg, 0, 0, 0);
if (!($aBox = #imagettfbbox($iTextSize, 0, $sFont, $sText)))
{
return $this->_writeFromString($sText);
}
//Find out the width and height of the text box
$iTextW = $aBox[2] - $aBox[0];
$iTextH = $aBox[5] - $aBox[3];
if (function_exists('imagefilledellipse'))
{
$nNoiseColor = imagecolorallocate($this->_hImg, 207, 181, 181);
for ($i = 0; $i < ($iWidth*$iHeight) / 3; $i++)
{
imagefilledellipse($this->_hImg, mt_rand(0, $iWidth), mt_rand(0, $iHeight), 1, 1, $nNoiseColor);
}
}
$iImageLineColor = imagecolorallocate($this->_hImg, 207, 181, 181);
for ($i = 0; $i < ($iWidth*$iHeight) / 150; $i++)
{
imageline($this->_hImg, mt_rand(0, $iWidth), mt_rand(0, $iHeight), mt_rand(0, $iWidth), mt_rand(0, $iHeight), $iImageLineColor);
}
// Calculate the positions
$positionLeft = (($iWidth - $iTextW) / 2) - (20 + $iString);
$positionTop = (($iHeight - $iTextH) / 2);
for ($i = 0; $i < $iString; $i++)
{
if (!#imagettftext($this->_hImg, $iTextSize, 0, $positionLeft, 30, $nTxtColor, $sFont, $sText[$i]))
{
return $this->_writeFromString($sText);
}
$positionLeft += 20;
}
}
private function _writeFromString($sText)
{
$iString = strlen($sText);
$iWidth = (($iString + 5) * 6.4 * 2);
$iHeight = 40;
$this->_imageCreate($iWidth, $iHeight);
$nBgColor = imageColorAllocate($this->_hImg, 255, 255, 255);
$nTxtColor = imageColorAllocate($this->_hImg, 0, 0, 0);
$positionLeft = 20;
for ($i = 0; $i < $iString; $i++)
{
imagestring($this->_hImg, 5, $positionLeft, 12, $sText[$i], $nTxtColor);
$positionLeft += 15;
}
}
private function _imageCreate($iWidth, $iHeight)
{
$this->_hImg = imageCreate($iWidth, $iHeight);
}
}
?>
You need to remove all the code that use strtolower().
Here the fixed code:
<?php
/**
* [PHPFOX_HEADER]
*/
defined('PHPFOX') or exit('NO DICE!');
/**
*
*
* #copyright [PHPFOX_COPYRIGHT]
* #author Raymond Benc
* #package Module_Captcha
* #version $Id: captcha.class.php 6005 2013-06-06 14:12:12Z Raymond_Benc $
*/
class Captcha_Service_Captcha extends Phpfox_Service
{
private $_oSession;
/**
* Class constructor
*/
public function __construct()
{
$this->_oSession = Phpfox::getService('log.session');
}
public function checkHash($sCode = null)
{
if (Phpfox::getParam('captcha.recaptcha'))
{
require_once(PHPFOX_DIR_LIB . 'recaptcha' . PHPFOX_DS . 'recaptchalib.php');
if (isset($_POST["recaptcha_response_field"]))
{
$oResp = recaptcha_check_answer(Phpfox::getParam('captcha.recaptcha_private_key'), $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);
if ($oResp->is_valid){
return true;
}else{
return false;
}
}
return false;
}
if (Phpfox::getParam('core.store_only_users_in_session'))
{
$oSession = Phpfox::getLib('session');
$sSessionHash = $oSession->get('sessionhash');
$aRow = $this->database()->select('*')
->from(Phpfox::getT('log_session'))
->where('session_hash = \'' . $this->database()->escape($sSessionHash) . '\'')
->execute('getSlaveRow');
if (isset($aRow['session_hash']) && $this->_getHash($sCode, $aRow['session_hash']) == $aRow['captcha_hash'])
{
return true;
}
}
else
{
if ($this->_getHash($sCode, $this->_oSession->getSessionId()) == $this->_oSession->get('captcha_hash'))
{
return true;
}
}
return false;
}
public function setHash($sCode)
{
if (Phpfox::getParam('core.store_only_users_in_session'))
{
$oRequest = Phpfox_Request::instance();
$oSession = Phpfox::getLib('session');
$sSessionHash = $oSession->get('sessionhash');
$bCreate = true;
if (!empty($sSessionHash))
{
$bCreate = false;
$aRow = $this->database()->select('*')
->from(Phpfox::getT('log_session'))
->where('session_hash = \'' . $this->database()->escape($sSessionHash) . '\'')
->execute('getSlaveRow');
if (isset($aRow['session_hash']))
{
$this->database()->update(Phpfox::getT('log_session'), array('captcha_hash' => $this->_getHash($sCode, $sSessionHash)), "session_hash = '" . $sSessionHash . "'");
}
else
{
$bCreate = true;
}
}
if ($bCreate)
{
$sSessionHash = $oRequest->getSessionHash();
$this->database()->insert(Phpfox::getT('log_session'), array(
'session_hash' => $sSessionHash,
'id_hash' => $oRequest->getIdHash(),
'captcha_hash' => $this->_getHash($sCode, $sSessionHash),
'user_id' => Phpfox::getUserId(),
'last_activity' => PHPFOX_TIME,
'location' => '',
'is_forum' => '0',
'forum_id' => 0,
'im_hide' => 0,
'ip_address' => '',
'user_agent' => ''
)
);
$oSession->set('sessionhash', $sSessionHash);
}
}
else
{
$iId = $this->_oSession->getSessionId();
$this->database()->update(Phpfox::getT('log_session'), array('captcha_hash' => $this->_getHash($sCode, $iId)), "session_hash = '" . $iId . "'");
}
}
public function displayCaptcha($sText)
{
((Phpfox::getParam('captcha.captcha_use_font') && function_exists('imagettftext')) ? $this->_writeFromFont($sText) : $this->_writeFromString($sText));
ob_clean();
header("X-Content-Encoded-By: phpFox " . PhpFox::getVersion());
header("Pragma: no-cache");
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Content-Type: image/jpeg');
imagejpeg($this->_hImg);
imagedestroy($this->_hImg);
}
public function generateCode($sCharacters)
{
$sPossible = Phpfox::getParam('captcha.captcha_code');
$sCode = '';
$i = 0;
while ($i < $sCharacters)
{
$sCode .= substr($sPossible, mt_rand(0, strlen($sPossible)-1), 1);
$i++;
}
return $sCode;
}
/**
* If a call is made to an unknown method attempt to connect
* it to a specific plug-in with the same name thus allowing
* plug-in developers the ability to extend classes.
*
* #param string $sMethod is the name of the method
* #param array $aArguments is the array of arguments of being passed
*/
public function __call($sMethod, $aArguments)
{
/**
* Check if such a plug-in exists and if it does call it.
*/
if ($sPlugin = Phpfox_Plugin::get('captcha.service_captcha__call'))
{
return eval($sPlugin);
}
/**
* No method or plug-in found we must throw a error.
*/
Phpfox_Error::trigger('Call to undefined method ' . __CLASS__ . '::' . $sMethod . '()', E_USER_ERROR);
}
private function _getHash($sCode, $sSalt)
{
return md5(md5($sCode) . $sSalt);
}
private function _writeFromFont($sText)
{
$iString = strlen($sText);
$iWidth = (($iString + 5) * 10 * 2);
$iHeight = 45;
$iTextSize = 20;
$sFont = Phpfox::getParam('core.dir_static') . 'image/font/' . Phpfox::getParam('captcha.captcha_font');
if (!file_exists($sFont))
{
return $this->_writeFromString($sText);
}
$this->_imageCreate($iWidth, $iHeight);
$nBgColor = imageColorAllocate($this->_hImg, 255, 255, 255);
$nTxtColor = imageColorAllocate($this->_hImg, 0, 0, 0);
if (!($aBox = #imagettfbbox($iTextSize, 0, $sFont, $sText)))
{
return $this->_writeFromString($sText);
}
//Find out the width and height of the text box
$iTextW = $aBox[2] - $aBox[0];
$iTextH = $aBox[5] - $aBox[3];
if (function_exists('imagefilledellipse'))
{
$nNoiseColor = imagecolorallocate($this->_hImg, 207, 181, 181);
for ($i = 0; $i < ($iWidth*$iHeight) / 3; $i++)
{
imagefilledellipse($this->_hImg, mt_rand(0, $iWidth), mt_rand(0, $iHeight), 1, 1, $nNoiseColor);
}
}
$iImageLineColor = imagecolorallocate($this->_hImg, 207, 181, 181);
for ($i = 0; $i < ($iWidth*$iHeight) / 150; $i++)
{
imageline($this->_hImg, mt_rand(0, $iWidth), mt_rand(0, $iHeight), mt_rand(0, $iWidth), mt_rand(0, $iHeight), $iImageLineColor);
}
// Calculate the positions
$positionLeft = (($iWidth - $iTextW) / 2) - (20 + $iString);
$positionTop = (($iHeight - $iTextH) / 2);
for ($i = 0; $i < $iString; $i++)
{
if (!#imagettftext($this->_hImg, $iTextSize, 0, $positionLeft, 30, $nTxtColor, $sFont, $sText[$i]))
{
return $this->_writeFromString($sText);
}
$positionLeft += 20;
}
}
private function _writeFromString($sText)
{
$iString = strlen($sText);
$iWidth = (($iString + 5) * 6.4 * 2);
$iHeight = 40;
$this->_imageCreate($iWidth, $iHeight);
$nBgColor = imageColorAllocate($this->_hImg, 255, 255, 255);
$nTxtColor = imageColorAllocate($this->_hImg, 0, 0, 0);
$positionLeft = 20;
for ($i = 0; $i < $iString; $i++)
{
imagestring($this->_hImg, 5, $positionLeft, 12, $sText[$i], $nTxtColor);
$positionLeft += 15;
}
}
private function _imageCreate($iWidth, $iHeight)
{
$this->_hImg = imageCreate($iWidth, $iHeight);
}
}
?>
You may run into a problem or it could be your solution. Remember, the collation on your database also needs to be taken in consideration. If you are using utf8_general_ci then the ci means that it is case insensitive so no matter what you do on the code side, the database does not care if its upper or lower case. Test that on your search bar, look for some string, lets say a user, John Smith, and then search for the same string as john smith... If the search produces the same result, then your database doesn't care about case sensitive search. I don´t know where your captcha saves its answers, but if it does save them on the database, and its matching your questions in it, then it may not care if it is upper or lower case.
Just a reminder. You need to test that in your own enviroment.
how can I rename or copy multiple files (with different name without numbers like "jhf.mp4" "JJHGF.flv" ..) to one name with numbers like (input_01.mp4 input_02 ....) (order by case) by batch file by giving just path of (folder files) to batch file or dropping the files to it (patch file).
-- MEAN USING VARIABLE OR (dropping with %*) .
Note 1: I need this technique for encoding animes with X264 if any other good ideas I'll be happy to hear it.
Note 2: I'm using Windows 10.
I think you can solve this problem using WSHost-scripts. WSHost-system should be preinstalled on any modern Windows computer.
I designed a system of utilities to tackle your problem:
build-mapping-to-normalized-filenames.js
map-filenames.js
cleanup.cmd
before.cmd
after.cmd
You can find source code for 3-4-5 at the bottom of this answer, and for 1-2 - in separate answers (there is a limit of characters per answer).
1 and 2 are workhorses of this system. Powerful but not user-friendly. Yes you can use them as stand-alone utilities if you understand what input they use.
3-4-5 - are glue that bind this system and expose user-friendly controls.
This system is dependent on absolute paths. But all absolute paths are set as variables at the start of 3-4-5 - so if you want to reorganize system - you need change things there and only there.
This is how it should be deployed at filesystem:
folders:
C:\1\ <- this is the root of system
C:\1\aOrig <- folder for original files
C:\1\norm\ <- folder with files that are part of this system + temp folders
C:\1\norm\backend <- place for non-user-friendly utilities
files:
C:\1\norm\backend\build-mapping-to-normalized-filenames.js
C:\1\norm\backend\map-filenames.js
C:\1\norm\after.cmd
C:\1\norm\before.cmd
C:\1\norm\cleanup.cmd
+files: (these are example international filesnames that you can use for playground to check how system works to make yourserf familiar with it)
C:\1\aOrig\English.txt <- test files, you could add unique content to each
C:\1\aOrig\Русский.txt
C:\1\aOrig\العربية.txt
C:\1\aOrig\ܐܪܡܝܐ.txt
C:\1\aOrig\中文.txt
C:\1\aOrig\日本語.txt
How to use it:
You open your console and go to dir **C:\1\norm**
You call programs in this order:
cleanup.cmd
before.cmd
What happened now is that two interesting temp folders are created:
C:\1\norm\bTemp <- here are normalized files.
C:\1\norm\mappingTemp <- it contains a file with mapping between original and normalized names.
What you must do now - is to process files in C:\1\norm\bTemp - that special processing you mentioned before. Right now for the purposes of learning, you can manually change extensions and contents.
after.cmd
cleanup.cmd
And that's it.
So, if we condence it that's your typical session here, plain and simple -
cleanup.cmd
before.cmd
..do your stuff with files at "C:\1\norm\bTemp"...
after.cmd
cleanup.cmd
Also, you don't need command line to use those - you can open **C:\1\norm** in Explorer and double click those utilities in the order that I explained above - cleanup-before-(..manually do your work with bTemp..)-after-cleanup
Listing for program cleanup.cmd :
#ECHO OFF
:: name of this script...
:: useful for debugging...
SET me=%~nx0
:: aOrig - directory that contains source files...
:: bTemp - temporary working directory...
:: mTemp - temporary directory for mapping.txt...
SET aOrig=C:\1\aOrig
SET bTemp=C:\1\norm\bTemp
SET mTemp=C:\1\norm\mappingTemp
:: Removing temporary folders...
:: Be warned - this RD is working
:: in quiet mode /Q - so it wouldn't ask you politely
:: about del y/n - thus, please make shure that
:: %aOrig% doesn't point to anything
:: important for your personal data or system...
IF EXIST "%bTemp%" RD /S /Q "%bTemp%"
IF EXIST "%mTemp%" RD /S /Q "%mTemp%"
IF %ERRORLEVEL% NEQ 0 (
ECHO Script %me% failed on step cleanup-1: [Removing temporary folders]...
ECHO Error: %ERRORLEVEL%
EXIT /B 1
)
:: Successfully finished
ECHO.
ECHO Script %me% successfully finished!
Listing for program before.cmd :
#ECHO OFF
:: name of this script...
:: useful for debugging...
SET me=%~nx0
:: aOrig - directory that contains original files...
:: bTemp - temporary working directory...
:: mTemp - temporary directory for mapping.txt...
SET aOrig=C:\1\aOrig
SET bTemp=C:\1\norm\bTemp
SET mTemp=C:\1\norm\mappingTemp
:: scriptBuild - name of .js-script for building a map
:: from original to normalized filenames...
:: scriptMapFi - name of .js-script interpreting
:: mapping file that was build by scriptBuild...
:: mappingFile - path for file that will contain mapping between
:: original filenames and normalized filenames...
SET scriptBuild=C:\1\norm\backend\build-mapping-to-normalized-filenames.js
SET scriptMapFi=C:\1\norm\backend\map-filenames.js
SET mappingFile=C:\1\norm\mappingTemp\mapping.txt
:: creating temporary folders...
IF NOT EXIST "%bTemp%" MKDIR "%bTemp%"
IF NOT EXIST "%mTemp%" MKDIR "%mTemp%"
IF %ERRORLEVEL% NEQ 0 (
ECHO Script %me% failed on step before-1: [Creating temporary folders]...
ECHO Error: %ERRORLEVEL%
EXIT /B 1
)
:: now we run build-mapping-to-normalized-filenames.js ...
:: that //U thing is important...
CSCRIPT //U //NoLogo "%scriptBuild%" "%aOrig%" 0 1 > "%mappingFile%"
IF %ERRORLEVEL% NEQ 0 (
ECHO Script %me% failed on step before-2: [Building a list of normalized filenames]...
ECHO Error: %ERRORLEVEL%
EXIT /B 1
)
:: now we run map-filenames.js ...
:: that //U thing is important...
CSCRIPT //U //NoLogo "%scriptMapFi%" "%aOrig%" "%bTemp%" /NotTraining < "%mappingFile%"
IF %ERRORLEVEL% NEQ 0 (
ECHO Script %me% failed on step before-3: [Copy files while simultaneously changing their names to normalised form]...
ECHO Error: %ERRORLEVEL%
EXIT /B 1
)
:: Successfully finished
ECHO.
ECHO Script %me% successfully finished!
Listing for program after.cmd :
#ECHO OFF
:: name of this script...
:: useful for debugging...
SET me=%~nx0
:: aOrig - directory that contains original files...
:: bTemp - temporary working directory...
:: mTemp - temporary directory for mapping.txt...
SET aOrig=C:\1\aOrig
SET bTemp=C:\1\norm\bTemp
SET mTemp=C:\1\norm\mappingTemp
:: scriptBuild - name of .js-script for building a map
:: from original to normalized filenames...
:: scriptMapFi - name of .js-script interpreting
:: mapping file that was build by scriptBuild...
:: mappingFile - path for file that will contain mapping between
:: original filenames and normalized filenames...
SET scriptBuild=C:\1\norm\backend\build-mapping-to-normalized-filenames.js
SET scriptMapFi=C:\1\norm\backend\map-filenames.js
SET mappingFile=C:\1\norm\mappingTemp\mapping.txt
:: Removing files in original folder...
:: Not recursive
:: Be warned - this DEL is working
:: in quiet mode /Q - so it wouldn't ask you politely
:: about del y/n - thus, please make shure that
:: %aOrig% doesn't point to anything
:: important for your personal data or system...
IF EXIST "%aOrig%" DEL /Q "%aOrig%"
IF %ERRORLEVEL% NEQ 0 (
ECHO Script %me% failed on step after-1: [Removing files from original folder]...
ECHO Error: %ERRORLEVEL%
EXIT /B 1
)
:: now we run map-filenames.js ...
:: that //U thing is important...
CSCRIPT //U //NoLogo "%scriptMapFi%" "%bTemp%" "%aOrig%" /NotTraining /MapFrom2To1 /ResultExtension:2 /FuzzyExtensionsFrom < "%mappingFile%"
IF %ERRORLEVEL% NEQ 0 (
ECHO Script %me% failed on step after-2: [Copy files while simultaneously changing their names to normalised form]...
ECHO Error: %ERRORLEVEL%
EXIT /B 1
)
:: Successfully finished
ECHO.
ECHO Script %me% successfully finished!
Listing for program build-mapping-to-normalized-filenames.js :
// - - - - -
// #magicVars #config
// Purpose of basicOptions: organize set of most basic settings
// into a compact object package
var basicOptions = {
// Fist things first -
// "scriptName" will be important for error messages.
// Because when you debug a pipeline of scripts, it is always
// crucial to know - which program in pipeline of 10 utilities
// throws that cryptic stderr message "error: not enough arguments".
// I mean huh? Was that calc-tool.js? Or sort-tool.js? Go figure...
scriptName: WScript.ScriptName.toString(),
// What kind of End Of Line sequence
// (they call it New Line sometimes too)
// you prefer when using outputToolbox?
eolStdOut: '\r\n',
eolStdErr: '\r\n',
// Those are all possible errorCodes that this script
// was designed to fail with.
// You can define other error codes.
// Those SHOULD be integer (not strings).
// Code noErrors = 0 is indication that script finished without errors.
errorCodes: {
noErrors: 0,
badArguments: 1,
badGettingFileList: 2
}
};
// - - - - -
// thisOptions
// Purpose of thisOptions: organize set of hard-coded
// normalisation settings
// into a compact object package
var thisOptions = {
normNameBefore: 'input_',
normNameAfter: ''
}
// - - - - -
// outputToolbox depends on
// basicOptions && WScript
// Purpose of outputToolbox: organize in one group
// functions that are used to
// output chars or messages to stdout or stderr
var outputToolbox = {
// Syntactic sugar for printing exact set of chars to stdout.
print: function( data ) {
// For this script to output UTF characters correctly, program must
// run under /U switch - like
// cscript /U //NoLogo program-name-here.js arg1 arg2
WScript.StdOut.Write( data );
},
// Syntactic sugar for printing one line to stdout.
// terminated with your preferred line-terminator.
printLine: function( data ) {
outputToolbox.print( data );
outputToolbox.print( basicOptions.eolStdOut );
},
// Syntactic sugar for printing exact set of chars to stderr.
printErr: function( data ) {
WScript.StdErr.Write( data );
},
// Syntactic sugar for printing one line to stderr
// terminated with your preferred line-terminator.
printErrLine: function( data ) {
outputToolbox.printErr( data );
outputToolbox.printErr( basicOptions.eolStdErr );
},
// Syntactic sugar for printing one line to stderr
// prepended with meaningful script name (that is useful for debug)
// terminated with your preferred line-terminator.
printErrMessage: function( data ) {
outputToolbox.printErr( basicOptions.scriptName + ' failed' );
outputToolbox.printErr( data );
outputToolbox.printErr( basicOptions.eolStdErr );
},
// Syntactic sugar for printing one line to stderr
// prepended with meaningful script name (that is useful for debug)
// terminated with your preferred line-terminator.
printErrWarning: function( data ) {
outputToolbox.printErr( 'Warning for ' + basicOptions.scriptName + ': ' );
outputToolbox.printErr( data );
outputToolbox.printErr( basicOptions.eolStdErr );
},
// Syntactic sugar for printing Error objects
// catched by throw...catch construction
printErrCatchedErr: function( e ) {
outputToolbox.printErrMessage(
' - catched error details - ' + e.name + ': ' + e.message
);
}
};
// - - - - -
// flowToolbox depends on
// WScript
// Purpose of flowToolbox: organize in one group
// functions that are used to
// control general flow of program
var flowToolbox = {
// Shortcut to kill this script.
// When invoked it stops execution.
die: function ( code ) {
if ( typeof code === 'undefined' ) {
code = 0;
}
WScript.Quit(code);
}
};
// - - - - -
// Here is a cleaner alternative: we pollute only name $b.
// Not so easy to type but later, you can easily find all code calls
// dependant on functions from 'basis'.
// '$b' stands for 'library-b' or more exactly - "library named 'basis'"
var $b = {};
$b.print = outputToolbox.print;
$b.printLine = outputToolbox.printLine;
$b.printErr = outputToolbox.printErr;
$b.printErrLine = outputToolbox.printErrLine;
$b.printErrMessage = outputToolbox.printErrMessage;
$b.printErrWarning = outputToolbox.printErrWarning;
$b.die = flowToolbox.die;
// ^ You can use those as functions now
// - - - - -
// $fileListToolbox
// depends on WScript && ActiveXObject( "Scripting.FileSystemObject" ) && $b
var $fileListToolbox = {
/*
* Input:
* any gibberish that is acceptable
* for your local version of
* Scripting.FileSystemObject
* - like
* getFileListForFolder( 'C:\' );
* getFileListForFolder( 'C:\abc' );
* getFileListForFolder( './' );
* getFileListForFolder( './abc/../abc/..' );
*
* Output:
* aFileList with format:
* empty array
* or
* array of oFileData
* oFileData has format:
* {
* fileNameBase: ...[string],
* fileNameExtension: ...[string],
* parentAbsolutePath: ...[string]
* }
*/
getFileListForFolder: function( folderSpec )
{
var aResult = [];
var fso = new ActiveXObject( "Scripting.FileSystemObject" );
if ( !fso.FolderExists( folderSpec ) ) {
$b.printErrMessage(' folder="' + folderSpec + '" doesn\'t exist');
$b.die( basicOptions.errorCodes.badGettingFileList );
}
var folder = fso.GetFolder( folderSpec );
var files = new Enumerator( folder.files );
for ( ; !files.atEnd(); files.moveNext() ) {
var thisFileItem = files.item();
aResult.push({
fileNameBase: fso.GetBaseName( thisFileItem ),
fileNameExtension: fso.GetExtensionName( thisFileItem ),
parentAbsolutePath: (
fso.GetParentFolderName(
fso.GetAbsolutePathName( thisFileItem )
)
)
});
}
return( aResult );
},
/*
* Purpose:
* Sort files by fileNameBase
*
* Input:
* aFileList
* - format is the same
* as for function $fileListToolbox.getFileListForFolder
*
* Output:
* - format is the same
* as for function $fileListToolbox.getFileListForFolder
*/
sortFileListByFileNameBaseAsc: function( aFileList ) {
var fSort = function( a, b ) {
if ( a.fileNameBase > b.fileNameBase ) {
return 1;
}
if ( a.fileNameBase < b.fileNameBase ) {
return -1;
}
return 0;
}
return aFileList.sort( fSort );
},
/*
* Purpose:
* Tool for displaying contents of fileList
*
* Input:
* aFileList
* - format is the same
* as for function $fileListToolbox.getFileListForFolder
*
* Sideeffects:
* Prints aFileList to the stdout stream
*/
printFileList: function( aFileList, callbackPrintLine ) {
if ( typeof callbackPrintLine === 'undefined' ) {
return;
}
var i;
var L = aFileList.length;
var elem;
for ( i = 0; i < L; i++ ) {
elem = aFileList[i];
callbackPrintLine();
callbackPrintLine( 'i: ' + i );
callbackPrintLine( 'fileNameBase: ' + elem.fileNameBase );
callbackPrintLine( 'fileNameExtension: ' + elem.fileNameExtension );
callbackPrintLine( 'parentAbsolutePath: ' + elem.parentAbsolutePath );
}
}
};
/*
// basic test:
$fileListToolbox.printFileList(
$fileListToolbox.sortFileListByFileNameBaseAsc(
$fileListToolbox.getFileListForFolder( 'bTmp' )
),
$b.printLine
);
*/
// - - - - -
// $mappingEngine
var $mappingEngine = {
// this is a relic from a more complex fileformat...
printHeader: function(
functionPrintChars
) {
},
printBasicFilePair: function(
functionPrintChars,
aFileNameBase, aFileNameExtension,
bFileNameBase, bFileNameExtension
) {
var eol = '\r\n';
if ( aFileNameBase.match( /[\r\n]/ ) !== null ) {
throw new Error(
'error: bad input: aFileNameBase contains end of line symbols'
);
}
if ( bFileNameBase.match( /[\r\n]/ ) !== null ) {
throw new Error(
'error: bad input: bFileNameBase contains end of line symbols'
);
}
if ( aFileNameExtension.match( /[\r\n]/ ) !== null ) {
throw new Error(
'error: bad input: aFileNameExtension contains end of line symbols'
);
}
if ( bFileNameExtension.match( /[\r\n]/ ) !== null ) {
throw new Error(
'error: bad input: bFileNameExtension contains end of line symbols'
);
}
var ar = [
'id:1',
'baseName:' + aFileNameBase,
'extensionName:' + aFileNameExtension,
'id:2',
'baseName:' + bFileNameBase,
'extensionName:' + bFileNameExtension,
':',
''
];
functionPrintChars( ar.join( eol ) );
}
};
/*
//basic test:
$mappingEngine.printHeader( $b.print );
$mappingEngine.printBasicFilePair( $b.print, 'abcdef', 'ext', 'input_001', 'txt' );
$mappingEngine.printBasicFilePair( $b.print, 'ghijkl', 'jpg', 'input_002', 'png' );
*/
// it should print to output:
/*
id:1
baseName:abcdef
extensionName:ext
id:2
baseName:input_001
extensionName:txt
:
id:1
baseName:ghijkl
extensionName:jpg
id:2
baseName:input_002
extensionName:png
:
*/
// - - - - -
function generateFAddLeadingZeroes( minimumLength, startFrom ) {
if ( typeof minimumLength === 'undefined' ) {
minimumLength = 0;
}
if ( typeof startFrom === 'undefined' ) {
startFrom = 0;
}
minimumLength = parseInt( minimumLength ) - 1;
startFrom = parseInt( startFrom );
var fAddLeadingZeroes = function( i, L ) {
i += startFrom;
L += startFrom - 1;
var sResult = i.toString();
if ( minimumLength > 0 ) {
var level = 0;
var tmpL = L;
while (
( tmpL = parseInt( tmpL / 10 ) ) >= 1
) {
++level;
}
level = Math.max( level, minimumLength );
var iLength = sResult.length;
while ( iLength <= level-- ) {
sResult = '0' + sResult;
}
}
return sResult;
}
return fAddLeadingZeroes;
}
// - - - - -
var $thisArguments = {
getArgumentsObj: function() {
return WScript.Arguments;
// mockup for tests in browser
/*
var testArr = [1,2,3,4,5];
var mockupArguments = function( i ) {
return testArr[i];
};
mockupArguments.length = testArr.length;
return mockupArguments;
*/
},
printErrorMessageAndDie: function( meaningfulPart ) {
$b.printErrMessage(
' - problem when ' +
'parsing command-line arguments (options): ' +
''
);
$b.die( basicOptions.errorCodes.badArguments );
},
getArgumentsDummy: function() {
return {
folder: 'C:\abc',
minNOfDigits: 0,
countStart: 1
};
},
print: function( argumentsObject ) {
$b.printErrLine( 'folder: ' + argumentsObject.folder );
$b.printErrLine( 'minNOfDigits: ' + argumentsObject.minNOfDigits );
$b.printErrLine( 'countStart: ' + argumentsObject.countStart );
},
// We don't use any flags it this script...
/*
isThereAFlagInArguments: function( inString ) {
var normalizedEthalon = inString.toString().toLowerCase();
var objArgs = $thisArguments.getArgumentsObj();
var i;
var L = objArgs.length;
for ( i = 2; i < L; i++ ) {
var normalizedArgument = objArgs( i ).toString().toLowerCase();
if ( normalizedEthalon === normalizedArgument ) {
return true;
}
}
return false;
},
*/
getArguments: {
folder: function() {
var rR = '';
var objArgs = $thisArguments.getArgumentsObj();
if ( objArgs.length < 1 ) {
$b.printErrMessage(
' - reason: not enough arguments, ' +
'you MUST to provide at least 1 argument, ' +
'but ammount of arguments you provided ' +
'only: ' + objArgs.length
);
$b.die( basicOptions.errorCodes.badArguments );
}
rR = objArgs(0);
var fso = new ActiveXObject("Scripting.FileSystemObject");
rR = fso.GetAbsolutePathName( rR );
return rR;
},
minNOfDigits: function() {
var rR = '0';
var objArgs = $thisArguments.getArgumentsObj();
if ( objArgs.length >= 2 ) {
rR = objArgs(1);
}
var intRR = parseInt( rR );
// test for NaN
if ( intRR !== intRR ) {
$b.printErrMessage(
' - reason: bad argument 2, ' +
'you MUST to provide non-negative integer, ' +
'but you provided non-integer: ' +
'[' + ( typeof rR ) + ']' +
' "' + rR + '"' +
''
);
$b.die( basicOptions.errorCodes.badArguments );
}
// test for negative
if ( intRR < 0 ) {
$b.printErrMessage(
' - reason: bad argument 2, ' +
'you MUST to provide non-negative integer, ' +
'but you provided negtive integer: ' +
'[' + ( typeof rR ) + ']' +
' "' + rR + '"' +
''
);
$b.die( basicOptions.errorCodes.badArguments );
}
rR = intRR;
return rR;
},
countStart: function() {
var rR = '1';
var objArgs = $thisArguments.getArgumentsObj();
if ( objArgs.length >= 3 ) {
rR = objArgs(2);
}
var intRR = parseInt( rR );
// test for NaN
if ( intRR !== intRR ) {
$b.printErrMessage(
' - reason: bad argument 3, ' +
'you MUST to provide non-negative integer, ' +
'but you provided non-integer: ' +
'[' + ( typeof rR ) + ']' +
' "' + rR + '"' +
''
);
$b.die( basicOptions.errorCodes.badArguments );
}
// test for negative
if ( intRR < 0 ) {
$b.printErrMessage(
' - reason: bad argument 3, ' +
'you MUST to provide non-negative integer, ' +
'but you provided negtive integer: ' +
'[' + ( typeof rR ) + ']' +
' "' + rR + '"' +
''
);
$b.die( basicOptions.errorCodes.badArguments );
}
rR = intRR;
return rR;
}
},
getArgumentsAll: function() {
var $get = $thisArguments.getArguments;
var rR = {
folder: $get.folder(),
minNOfDigits: $get.minNOfDigits(),
countStart: $get.countStart()
};
return rR;
}
};
var $a = $thisArguments;
// - - - - -
function main() {
var $inputOptions = $a.getArgumentsAll();
$b.printErrLine();
$b.printErrLine(
'Arguments for ' + basicOptions.scriptName +
' are interpreted this way:'
);
$a.print( $inputOptions );
$b.printErrLine();
try {
var aFileList = $fileListToolbox.getFileListForFolder( $inputOptions.folder );
} catch (e) {
$b.printErrMessage(
' - problems while trying ' +
'to get list of files from folder: ' +
$inputOptions.folder
);
$b.die( basicOptions.errorCodes.badGettingFileList );
return;
}
aFileList = $fileListToolbox.sortFileListByFileNameBaseAsc( aFileList );
// addLeadingZeroes
// is a function now.
// You can see what arguments it requires
// and output it produces in source for
// generateFAddLeadingZeroes
// function.
var addLeadingZeroes = generateFAddLeadingZeroes(
$inputOptions.minNOfDigits,
$inputOptions.countStart
);
var normNameBefore = thisOptions.normNameBefore;
var normNameAfter = thisOptions.normNameAfter;
var i;
var L = aFileList.length;
for ( i = 0; i < L; i++ ) {
var elem = aFileList[i];
var aBase = elem.fileNameBase;
var aExtension = elem.fileNameExtension;
var count = addLeadingZeroes( i, L );
var bBase = normNameBefore + count + normNameAfter;
var bExtension = aExtension;
$mappingEngine.printBasicFilePair(
$b.print,
aBase, aExtension,
bBase, bExtension
);
}
$b.printErr( 'Script ' + basicOptions.scriptName + ' - finished!' );
};
main();
Listing for program map-filenames.js :
// - - - - -
// #magicVars #config
// Purpose of basicOptions: organize set of most basic settings
// into a compact object package
var basicOptions = {
// Fist things first -
// "scriptName" will be important for error messages.
// Because when you debug a pipeline of scripts, it is always
// crucial to know - which program in pipeline of 10 utilities
// throws that cryptic stderr message "error: not enough arguments".
// I mean huh? Was that calc-tool.js? Or sort-tool.js? Go figure...
scriptName: WScript.ScriptName.toString(),
// What kind of End Of Line sequence
// (they call it New Line sometimes too)
// you prefer when using outputToolbox?
eolStdOut: '\r\n',
eolStdErr: '\r\n',
// Those are all possible errorCodes that this script
// was designed to fail with.
// You can define other error codes.
// Those SHOULD be integer (not strings).
// Code noErrors = 0 is indication that script finished without errors.
errorCodes: {
noErrors: 0,
badArguments: 1,
badCopy: 2,
badParsing: 3,
badGettingFileList: 4
}
};
// - - - - -
// - - - - -
// outputToolbox depends on
// basicOptions && WScript
// Purpose of outputToolbox: organize in one group
// functions that are used to
// output chars or messages to stdout or stderr
var outputToolbox = {
// Syntactic sugar for printing exact set of chars to stdout.
print: function( data ) {
// For this script to output UTF characters correctly, program must
// run under /U switch - like
// cscript /U //NoLogo program-name-here.js arg1 arg2
WScript.StdOut.Write( data );
},
// Syntactic sugar for printing one line to stdout.
// terminated with your preferred line-terminator.
printLine: function( data ) {
outputToolbox.print( data );
outputToolbox.print( basicOptions.eolStdOut );
},
// Syntactic sugar for printing exact set of chars to stderr.
printErr: function( data ) {
WScript.StdErr.Write( data );
},
// Syntactic sugar for printing one line to stderr
// terminated with your preferred line-terminator.
printErrLine: function( data ) {
outputToolbox.printErr( data );
outputToolbox.printErr( basicOptions.eolStdErr );
},
// Syntactic sugar for printing one line to stderr
// prepended with meaningful script name (that is useful for debug)
// terminated with your preferred line-terminator.
printErrMessage: function( data ) {
outputToolbox.printErr( basicOptions.scriptName + ' failed' );
outputToolbox.printErr( data );
outputToolbox.printErr( basicOptions.eolStdErr );
},
// Syntactic sugar for printing one line to stderr
// prepended with meaningful script name (that is useful for debug)
// terminated with your preferred line-terminator.
printErrWarning: function( data ) {
outputToolbox.printErr( 'Warning for ' + basicOptions.scriptName + ': ' );
outputToolbox.printErr( data );
outputToolbox.printErr( basicOptions.eolStdErr );
},
// Syntactic sugar for printing Error objects
// catched by throw...catch construction
printErrCatchedErr: function( e ) {
outputToolbox.printErrMessage(
' - catched error details - ' + e.name + ': ' + e.message
);
}
};
// - - - - -
// flowToolbox depends on
// WScript
// Purpose of flowToolbox: organize in one group
// functions that are used to
// control general flow of program
var flowToolbox = {
// Shortcut to kill this script.
// When invoked it stops execution.
die: function ( code ) {
if ( typeof code === 'undefined' ) {
code = 0;
}
WScript.Quit(code);
}
};
// - - - - -
// Here is a cleaner alternative: we pollute only name $b.
// Not so easy to type but later, you can easily find all code calls
// dependant on functions from 'basis'.
// '$b' stands for 'library-b' or more exactly - "library named 'basis'"
var $b = {};
$b.print = outputToolbox.print;
$b.printLine = outputToolbox.printLine;
$b.printErr = outputToolbox.printErr;
$b.printErrLine = outputToolbox.printErrLine;
$b.printErrMessage = outputToolbox.printErrMessage;
$b.printErrWarning = outputToolbox.printErrWarning;
$b.die = flowToolbox.die;
// ^ You can use those as functions now
// - - - - -
// $fileListToolbox
// depends on WScript && ActiveXObject( "Scripting.FileSystemObject" ) && $b
var $fileListToolbox = {
/*
* Input:
* any gibberish that is acceptable
* for your local version of
* Scripting.FileSystemObject
* - like
* getFileListForFolder( 'C:\' );
* getFileListForFolder( 'C:\abc' );
* getFileListForFolder( './' );
* getFileListForFolder( './abc/../abc/..' );
*
* Output:
* aFileList with format:
* empty array
* or
* array of oFileData
* oFileData has format:
* {
* fileNameBase: ...[string],
* fileNameExtension: ...[string],
* parentAbsolutePath: ...[string]
* }
*/
getFileListForFolder: function( folderSpec )
{
var aResult = [];
var fso = new ActiveXObject( "Scripting.FileSystemObject" );
if ( !fso.FolderExists( folderSpec ) ) {
$b.printErrMessage(' folder="' + folderSpec + '" doesn\'t exist');
$b.die( basicOptions.errorCodes.badGettingFileList );
}
var folder = fso.GetFolder( folderSpec );
var files = new Enumerator( folder.files );
for ( ; !files.atEnd(); files.moveNext() ) {
var thisFileItem = files.item();
aResult.push({
fileNameBase: fso.GetBaseName( thisFileItem ),
fileNameExtension: fso.GetExtensionName( thisFileItem ),
parentAbsolutePath: (
fso.GetParentFolderName(
fso.GetAbsolutePathName( thisFileItem )
)
)
});
}
return( aResult );
},
/*
* Purpose:
* Sort files by fileNameBase
*
* Input:
* aFileList
* - format is the same
* as for function $fileListToolbox.getFileListForFolder
*
* Output:
* - format is the same
* as for function $fileListToolbox.getFileListForFolder
*/
sortFileListByFileNameBaseAsc: function( aFileList ) {
var fSort = function( a, b ) {
if ( a.fileNameBase > b.fileNameBase ) {
return 1;
}
if ( a.fileNameBase < b.fileNameBase ) {
return -1;
}
return 0;
}
return aFileList.sort( fSort );
},
/*
Output:
false
when no results
oFileData
when result found
*/
getAnyFileWithBaseName: function( baseName, aFileList ) {
var i;
var L = aFileList.length;
for ( i = 0; i < L; i++ ) {
var a = aFileList[i];
if ( a.fileNameBase === baseName ) {
return a;
}
}
return false;
},
/*
* Purpose:
* Tool for displaying contents of fileList
*
* Input:
* aFileList
* - format is the same
* as for function $fileListToolbox.getFileListForFolder
*
* Sideeffects:
* Prints aFileList to the stdout stream
*/
printFileList: function( aFileList, callbackPrintLine ) {
if ( typeof callbackPrintLine === 'undefined' ) {
return;
}
var i;
var L = aFileList.length;
var elem;
for ( i = 0; i < L; i++ ) {
elem = aFileList[i];
callbackPrintLine();
callbackPrintLine( 'i: ' + i );
callbackPrintLine( 'fileNameBase: ' + elem.fileNameBase );
callbackPrintLine( 'fileNameExtension: ' + elem.fileNameExtension );
callbackPrintLine( 'parentAbsolutePath: ' + elem.parentAbsolutePath );
}
}
};
/*
// basic test:
$fileListToolbox.printFileList(
$fileListToolbox.sortFileListByFileNameBaseAsc(
$fileListToolbox.getFileListForFolder( 'bTmp' )
),
$b.printLine
);
*/
/*
// test for fuzzy search only by file base name:
$fileListToolbox.printFileList(
$fileListToolbox.sortFileListByFileNameBaseAsc(
$fileListToolbox.getFileListForFolder( 'bTmp' )
),
$b.printLine
);
var fuzzy = $fileListToolbox.getAnyFileWithBaseName(
'input_1',
$fileListToolbox.getFileListForFolder( 'bTmp' )
);
$b.printLine( 'fuzzy.fileNameBase: ' + fuzzy.fileNameBase );
$b.printLine( 'fuzzy.fileNameExtension: ' + fuzzy.fileNameExtension );
*/
// $streamToolbox
var $streamToolbox = {
// when end of line returns '' (aka empty string)
getChar: function() {
if ( WScript.StdIn.AtEndOfStream ) {
return '';
}
return WScript.StdIn.Read(1);
},
// tests show that for Windows 7 it understands terminators
// CRLF or LF-only
// when end of line returns '' (aka empty string)
getLine: function() {
if ( WScript.StdIn.AtEndOfStream ) {
return '';
}
return WScript.StdIn.ReadLine();
}
}
var $s = $streamToolbox;
// it could be used like that:
/*
var piece;
while ( ( piece = $s.getLine() ) !== '' ) {
$b.printLine( 'piece: ' + '>' + piece + '<' );
}
*/
// $thisArguments
var $thisArguments = {
getArgumentsObj: function() {
return WScript.Arguments;
// mockup for tests in browser
/*
var testArr = [1,2,3,4,5];
var mockupArguments = function( i ) {
return testArr[i];
};
mockupArguments.length = testArr.length;
return mockupArguments;
*/
},
printErrorMessageAndDie: function( meaningfulPart ) {
$b.printErrMessage(
' - problem when ' +
'parsing command-line arguments (options): ' +
''
);
$b.die( basicOptions.errorCodes.badArguments );
},
getArgumentsDummy: function() {
return {
direction: 'from-id-2-to-id-1',
resultExtension: 'auto',
folderFrom: 'C:\abc',
folderTo: 'D:\abc',
mode: 'training',
modeForExtensionFrom: 'strict'
};
},
print: function( argumentsObject ) {
$b.printErrLine( 'folderFrom: ' + argumentsObject.folderFrom );
$b.printErrLine( 'folderTo: ' + argumentsObject.folderTo );
$b.printErrLine( 'direction: ' + argumentsObject.direction );
$b.printErrLine( 'resultExtension: ' + argumentsObject.resultExtension );
$b.printErrLine( 'mode: ' + argumentsObject.mode );
$b.printErrLine( 'modeForExtensionFrom: ' + argumentsObject.modeForExtensionFrom );
},
isThereAFlagInArguments: function( inString ) {
var normalizedEthalon = inString.toString().toLowerCase();
var objArgs = $thisArguments.getArgumentsObj();
var i;
var L = objArgs.length;
for ( i = 2; i < L; i++ ) {
var normalizedArgument = objArgs( i ).toString().toLowerCase();
if ( normalizedEthalon === normalizedArgument ) {
return true;
}
}
return false;
},
getArguments: {
folderFrom: function() {
var rR = '';
var objArgs = $thisArguments.getArgumentsObj();
if ( objArgs.length < 2 ) {
$b.printErrMessage(
' - reason: not enough arguments, ' +
'you MUST to provide at least 2 arguments, ' +
'but ammount of arguments you provided ' +
'is only: ' + objArgs.length
);
$b.die( basicOptions.errorCodes.badArguments );
}
rR = objArgs(0);
var fso = new ActiveXObject("Scripting.FileSystemObject");
rR = fso.GetAbsolutePathName( rR );
return rR;
},
folderTo: function() {
var rR = '';
var objArgs = $thisArguments.getArgumentsObj();
if ( objArgs.length < 2 ) {
$b.printErrMessage(
' - reason: not enough arguments, ' +
'you MUST to provide at least 2 arguments, ' +
'but ammount of arguments you provided ' +
'is only: ' + objArgs.length
);
$b.die( basicOptions.errorCodes.badArguments );
}
rR = objArgs(1);
var fso = new ActiveXObject("Scripting.FileSystemObject");
rR = fso.GetAbsolutePathName( rR );
return rR;
},
direction: function() {
var rR = 'from-id-1-to-id-2';
var hasFlag = $thisArguments.isThereAFlagInArguments;
if ( hasFlag( '/MapFrom2To1' ) ) {
rR = 'from-id-2-to-id-1';
}
return rR;
},
resultExtension: function() {
var rR = 'auto';
var hasFlag = $thisArguments.isThereAFlagInArguments;
if ( hasFlag( '/ResultExtension:none' ) ) {
rR = 'none';
}
if ( hasFlag( '/ResultExtension:21' ) ) {
rR = '21';
}
if ( hasFlag( '/ResultExtension:12' ) ) {
rR = '12';
}
if ( hasFlag( '/ResultExtension:2' ) ) {
rR = '2';
}
if ( hasFlag( '/ResultExtension:1' ) ) {
rR = '1';
}
return rR;
},
mode: function() {
var rR = 'training';
var hasFlag = $thisArguments.isThereAFlagInArguments;
if ( hasFlag( '/NotTraining' ) ) {
rR = 'not-training';
}
return rR;
},
modeForExtensionFrom: function() {
var rR = 'strict';
var hasFlag = $thisArguments.isThereAFlagInArguments;
if ( hasFlag( '/FuzzyExtensionsFrom' ) ) {
rR = 'fuzzy';
}
return rR;
}
},
getArgumentsAll: function() {
var $get = $thisArguments.getArguments;
var rR = {
folderFrom: $get.folderFrom(),
folderTo: $get.folderTo(),
direction: $get.direction(),
resultExtension: $get.resultExtension(),
mode: $get.mode(),
modeForExtensionFrom: $get.modeForExtensionFrom()
};
return rR;
}
};
var $a = $thisArguments;
//you can use it like this:
/*
var $inputOptions = $a.getArgumentsAll()
$a.print( $inputOptions );
*/
// $parser
// mockup options for separate testing
/*
var basicOptions = {
errorCodes: {
badParsing: 3
}
};
var $b = {
printErrMessage: function( a ) { console.log(a); },
die: function() { throw new Error(); }
};
*/
var $parser = {};
$parser.generateDummyLineReader = function( textBlock ) {
var lines = textBlock.split( '\r\n' );
var i = -1;
var L = lines.length;
var f = function() {
i++;
if ( i >= L ) {
return '';
}
return lines[i];
}
return f;
}
$parser.generateDummyInputOptions = function() {
return {
direction: '1-to-2',
resultExtension: '12',
folderFrom: 'C:\abc',
folderTo: 'D:\abc'
}
}
$parser.generateDummyMappingLineReader = function() {
return $parser.generateDummyLineReader(
[
'id:1',
'baseName:abcdef',
'extensionName:ext',
'id:2',
'baseName:input_001',
'extensionName:txt',
':',
'id:1',
'baseName:ghijkl',
'extensionName:jpg',
'id:2',
'baseName:input_002',
'extensionName:png',
':'
].join('\r\n')
);
}
/*
Remark:
functionReadNextLine
must be iterator that returns '' (aka empty string)
when stream of lines ends
functionForEachBlockDo must have
those arguments:
- id1Base
- id1Ext
- id2Base
- id2Ext
- $inputOptions
- functionCopyFile
$inputOptions must have properties
(wherever it mentioned in this block of comments):
- direction
- resultExtension
- folderFrom
- folderTo
functionCopyFile must have these arguments
- folderFrom
- fileFrom
- folderTo
- fileTo
*/
$parser.parseLinesAndForEachBlockDo = function(
functionReadNextLine,
functionForEachBlockDo,
$inputOptions,
functionCopyFile
) {
var buffer = null;
var nOfLine = 0;
var states = [
'waitingForId1',
'waitingForId2',
'waitingForBase',
'waitingForExtension',
'waitingForEndOfGroup'
];
function printErrorMessageAndDie( meaningfulPart ) {
$b.printErrMessage(
' - problem when parsing line ' + nOfLine + ': ' +
'[' + typeof line + ']' +
'"' + line + '"' +
meaningfulPart +
''
);
$b.die( basicOptions.errorCodes.badParsing );
}
var state = 'waitingForId1';
var line;
while (
( line = functionReadNextLine() ) !== ''
) {
++nOfLine;
var arOrNull = line.match( /^([a-zA-Z0-9-]*):(.*)$/ );
if (
( arOrNull === null )
) {
printErrorMessageAndDie(
'every line in mapping must be either' +
'"key:value" or ":"'
);
}
var key = arOrNull[1];
var value = arOrNull[2];
if (
( value.match( '\r' ) !== null )
) {
printErrorMessageAndDie(
'if line is ' +
'"key:value" ' +
'then it MUST NOT contain \r (CR) symbols ' +
'exept in terminator'
);
}
if ( state === 'waitingForId1' ) {
if (
( key === 'id' )
&&
( value === '1' )
) {
buffer = {};
buffer.nowGroup = {
id: 1
};
state = 'waitingForBase';
continue;
} else {
printErrorMessageAndDie(
'but this line must be "id:1"'
);
}
}
if ( state === 'waitingForBase' ) {
if (
( key === 'baseName' )
) {
buffer.nowGroup.base = value;
state = 'waitingForExtension';
continue;
} else {
printErrorMessageAndDie(
'but this line must be "baseName:...anything-here..."'
);
}
}
if ( state === 'waitingForExtension' ) {
if (
( key === 'extensionName' )
) {
buffer.nowGroup.ext = value;
if ( buffer.nowGroup.id === 1 ) {
state = 'waitingForId2';
} else {
state = 'waitingForEndOfGroup';
}
continue;
} else {
printErrorMessageAndDie(
'but this line must be "extensionName:...anything-here..."'
);
}
}
if ( state === 'waitingForId2' ) {
if (
( key === 'id' )
&&
( value === '2' )
) {
buffer.group1 = {
base: buffer.nowGroup.base,
ext: buffer.nowGroup.ext
}
buffer.nowGroup = {
id: 2
};
state = 'waitingForBase';
continue;
} else {
printErrorMessageAndDie(
'but this line must be "id:2"'
);
}
}
if ( state === 'waitingForEndOfGroup' ) {
if (
( key === '' )
&&
( value === '' )
) {
buffer.group2 = {
base: buffer.nowGroup.base,
ext: buffer.nowGroup.ext
}
functionForEachBlockDo(
buffer.group1.base,
buffer.group1.ext,
buffer.group2.base,
buffer.group2.ext,
$inputOptions,
functionCopyFile
);
buffer = null;
state = 'waitingForId1';
continue;
} else {
printErrorMessageAndDie(
'but this line must be ":"'
);
}
}
}
if ( buffer !== null ) {
printErrorMessageAndDie(
'dangling state (not all properties group are defined) - ' + state
);
}
}
/*
// test
// can be tested in for browser with only $parser object
$parser.parseLinesAndForEachBlockDo(
$parser.generateDummyMappingLineReader(),
function( a, b, c, d ) {
console.log( 'a:', a, 'b:', b, 'c:', c, 'd:', d );
}
);
*/
/*
Remark:
$inputOptions must have properties:
- direction
- resultExtension
- folderFrom
- folderTo
*/
$parser.reactionOnGoodParsedBlock = function(
id1Base, id1Ext,
id2Base, id2Ext,
$inputOptions,
functionCopyFile
) {
function glueExtensionToFileName(
fileName, extension
) {
fileName = fileName.toString();
extension = extension.toString();
if ( extension.length > 0 ) {
extension = '.' + extension;
}
return fileName + extension;
}
var folderFrom = $inputOptions.folderFrom;
var folderTo = $inputOptions.folderTo;
if ( $inputOptions.modeForExtensionFrom === 'fuzzy' ) {
var tmpFromBase = id1Base;
if ( $inputOptions.direction == 'from-id-2-to-id-1' ) {
tmpFromBase = id2Base;
}
var fuzzyFile = $fileListToolbox.getAnyFileWithBaseName(
tmpFromBase,
$fileListToolbox.getFileListForFolder( folderFrom )
);
if ( fuzzyFile !== false ) {
if ( $inputOptions.direction == 'from-id-2-to-id-1' ) {
id2Ext = fuzzyFile.fileNameExtension;
} else {
id1Ext = fuzzyFile.fileNameExtension;
}
}
}
var fromSet = { base: id1Base, ext: id1Ext };
var toSet = { base: id2Base, ext: id2Ext };
if ( $inputOptions.direction == 'from-id-2-to-id-1' ) {
fromSet = { base: id2Base, ext: id2Ext };
toSet = { base: id1Base, ext: id1Ext };
}
if ( $inputOptions.resultExtension === '21' ) {
toSet.ext = glueExtensionToFileName( id2Ext, id1Ext );
}
if ( $inputOptions.resultExtension === '12' ) {
toSet.ext = glueExtensionToFileName( id1Ext, id2Ext );
}
if ( $inputOptions.resultExtension === '2' ) {
toSet.ext = id2Ext;
}
if ( $inputOptions.resultExtension === '1' ) {
toSet.ext = id1Ext;
}
if ( $inputOptions.resultExtension === 'none' ) {
toSet.ext = '';
}
var fileFrom = glueExtensionToFileName( fromSet.base, fromSet.ext );
var fileTo = glueExtensionToFileName( toSet.base, toSet.ext );
functionCopyFile(
folderFrom, fileFrom,
folderTo, fileTo
);
}
/*
// test
// can be tested in for browser with only $parser object
$parser.reactionOnGoodParsedBlock(
'originalA', 'extA',
'originalB', 'extB',
{
direction: 'from-id-2-to-id-1',
resultExtension: 'auto',
folderFrom: 'C:\abc',
folderTo: 'D:\abc'
},
function(
folderFrom, fileFrom,
folderTo, fileTo
) {
console.log(
'folderFrom:', folderFrom,
'fileFrom:', fileFrom,
'folderTo:', folderTo,
'fileTo:', fileTo
);
}
);
// expected result:
// folderFrom: C:abc fileFrom: originalA.extA folderTo: D:abc fileTo: originalB.extB
*/
var $copyFileToolbox = {
copyFileTraining: function(
folderFrom, fileFrom,
folderTo, fileTo
) {
var fso = new ActiveXObject( "Scripting.FileSystemObject" );
if ( !fso.FolderExists( folderFrom ) ) {
$b.printErrWarning('folderFrom="' + folderFrom + '" doesn\'t exist');
}
if ( !fso.FolderExists( folderTo ) ) {
$b.printErrWarning('folderTo="' + folderTo + '" doesn\'t exist');
}
var pathFrom = fso.BuildPath( folderFrom, fileFrom );
var pathTo = fso.BuildPath( folderTo, fileTo );
if ( !fso.FileExists( pathFrom ) ) {
$b.printErrLine();
$b.printErrWarning('no source file found, script looking for it at pathFrom="' + pathFrom + '" - this file doesn\'t exist');
}
if ( fso.FileExists( pathTo ) ) {
$b.printErrLine();
$b.printErrWarning('be advised - there was found a file at destination for copy command, and in "NotTraining" mode you will overwrite file at pathTo="' + pathTo + '"');
}
$b.printLine( '' );
$b.printLine( 'Training mode: you ask to copy file' );
$b.printLine( 'from: ' + pathFrom );
$b.printLine( '\\/' );
$b.printLine( 'to: ' + pathTo );
},
copyFile: function(
folderFrom, fileFrom,
folderTo, fileTo
) {
var fso = new ActiveXObject( "Scripting.FileSystemObject" );
if ( !fso.FolderExists( folderFrom ) ) {
$b.printErrMessage(' folderFrom="' + folderFrom + '" doesn\'t exist');
$b.die( basicOptions.errorCodes.badCopy );
}
if ( !fso.FolderExists( folderTo ) ) {
$b.printErrMessage (' folderTo="' + folderTo + '" doesn\'t exist');
$b.die( basicOptions.errorCodes.badCopy );
}
var pathFrom = fso.BuildPath( folderFrom, fileFrom );
var pathTo = fso.BuildPath( folderTo, fileTo );
if ( !fso.FileExists( pathFrom ) ) {
$b.printErrMessage(' no source file found, script looking for it at pathFrom="' + pathFrom + '" doesn\'t exist');
$b.die( basicOptions.errorCodes.badCopy );
}
fso.copyFile( pathFrom, pathTo, true );
}
}
var $c = $copyFileToolbox;
// you can use it as:
/*
$c.copyFileTraining(
'./', '123.txt',
'b', '345.txt'
);
*/
// you will have a lot of problems testing if filename is unicode
// only way that I found for Windows 7 is to pass filename as stdin
// from some file (perhaps any streaming from file works ok here...)
// and yes, test shows that it works...
function main() {
var $inputOptions = $a.getArgumentsAll();
$b.printErrLine();
$b.printErrLine(
'Arguments for ' + basicOptions.scriptName +
' are interpreted this way:'
);
$a.print( $inputOptions );
$b.printErrLine();
var fCopyFile = $c.copyFileTraining;
if ( $inputOptions.mode === 'not-training' ) {
fCopyFile = $c.copyFile;
}
/*
var fuzzy = $fileListToolbox.getAnyFileWithBaseName(
'input_1',
$fileListToolbox.getFileListForFolder( 'bTmp' )
);
*/
$parser.parseLinesAndForEachBlockDo(
$s.getLine,
$parser.reactionOnGoodParsedBlock,
$inputOptions,
fCopyFile
);
$b.printErr( 'Script ' + basicOptions.scriptName + ' - finished!' );
};
main();
Trying to get DataTables to work with PDO. I found this script online and it works fine, BUT, when I set ATTR_EMULATE_PREPARES to false the search capability does not work and reports back this error.
I cannot view the json response as there is none to view when this error happens, however, in all other cases other than using the search the json is returned properly and it works perfectly fine. Since the error only happens when emulation is set to false I am thinking this has something to do with binding? I cannot figure this one out as I don't see anything wrong that is sticking out at me.
Also, I am not looking to turn on emulation as a solution either. Help would be very appreciated.
the get in firebug:
http://www.example.com/assets/data-tables/test-pdo.php?sEcho=3&iColumns=4&sColumns=&iDisplayStart=0&iDisplayLength=10&mDataProp_0=0&mDataProp_1=1&mDataProp_2=2&mDataProp_3=3&sSearch=d&bRegex=false&sSearch_0=&bRegex_0=false&bSearchable_0=true&sSearch_1=&bRegex_1=false&bSearchable_1=true&sSearch_2=&bRegex_2=false&bSearchable_2=true&sSearch_3=&bRegex_3=false&bSearchable_3=true&iSortCol_0=2&sSortDir_0=asc&iSortingCols=1&bSortable_0=false&bSortable_1=true&bSortable_2=true&bSortable_3=true&_=1388479579319
Error in firebug:
<br />
<b>Fatal error</b>: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number' in /home/test/public_html/assets/data-tables/test-pdo.php:107
Stack trace:
#0 /home/test/public_html/assets/data-tables/test-pdo.php(107): PDOStatement->execute()
#1 /home/test/public_html/assets/data-tables/test-pdo.php(155): TableData->get('accounts', 'account_id', Array)
#2 {main}
thrown in <b>/home/test/public_html/assets/data-tables/test-pdo.php</b> on line <b>107</b><br />
db connection:
$db = new PDO("mysql:host=$db_host;dbname=$db_database;charset=utf8", $db_user, $db_pass, array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_PERSISTENT => true));
processing:
<?php
/*
* Script: DataTables server-side script for PHP and MySQL
* Copyright: 2012 - John Becker, Beckersoft, Inc.
* Copyright: 2010 - Allan Jardine
* License: GPL v2 or BSD (3-point)
*/
define('INCLUDE_CHECK',true);
// These files can be included only if INCLUDE_CHECK is defined
require '/home/test/public_html/assets/functions/connect.php';
//inject db connection into class
class TableData {
/** #var \PDO */
protected $_db;
public function __construct(\PDO $_db) {
$this->_db = $_db;
}
public function get($table, $index_column, $columns) {
// Paging
$sLimit = "";
if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' ) {
$sLimit = "LIMIT ".intval( $_GET['iDisplayStart'] ).", ".intval( $_GET['iDisplayLength'] );
}
// Ordering
$sOrder = "";
if ( isset( $_GET['iSortCol_0'] ) ) {
$sOrder = "ORDER BY ";
for ( $i=0 ; $i<intval( $_GET['iSortingCols'] ) ; $i++ ) {
if ( $_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true" ) {
$sortDir = (strcasecmp($_GET['sSortDir_'.$i], 'ASC') == 0) ? 'ASC' : 'DESC';
$sOrder .= "`".$columns[ intval( $_GET['iSortCol_'.$i] ) ]."` ". $sortDir .", ";
}
}
$sOrder = substr_replace( $sOrder, "", -2 );
if ( $sOrder == "ORDER BY" ) {
$sOrder = "";
}
}
/*
* Filtering
* NOTE this does not match the built-in DataTables filtering which does it
* word by word on any field. It's possible to do here, but concerned about efficiency
* on very large tables, and MySQL's regex functionality is very limited
*/
//need this change to only show correct responses from db
//$test = 100;
//$sWhere = ""; OR $sWhere = "WHERE account_id < ".$test;
$sWhere = "";
if ( isset($_GET['sSearch']) && $_GET['sSearch'] != "" ) {
// changes for correct display from db plus searching
if ($sWhere == ""){
$sWhere = "WHERE (";
}
else {
$sWhere .= " AND (";
}
//$sWhere = "WHERE (";
for ( $i=0 ; $i<count($columns) ; $i++ ) {
if ( isset($_GET['bSearchable_'.$i]) && $_GET['bSearchable_'.$i] == "true" ) {
$sWhere .= "`".$columns[$i]."` LIKE :search OR ";
}
}
$sWhere = substr_replace( $sWhere, "", -3 );
$sWhere .= ')';
}
// Individual column filtering
for ( $i=0 ; $i<count($columns) ; $i++ ) {
if ( isset($_GET['bSearchable_'.$i]) && $_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != '' ) {
if ( $sWhere == "" ) {
$sWhere = "WHERE ";
}
else {
$sWhere .= " AND ";
}
$sWhere .= "`".$columns[$i]."` LIKE :search".$i." ";
}
}
// SQL queries get data to display
$sQuery = "SELECT SQL_CALC_FOUND_ROWS `".str_replace(" , ", " ", implode("`, `", $columns))."` FROM `".$table."` ".$sWhere." ".$sOrder." ".$sLimit;
$statement = $this->_db->prepare($sQuery);
// Bind parameters
if ( isset($_GET['sSearch']) && $_GET['sSearch'] != "" ) {
$statement->bindValue(':search', '%'.$_GET['sSearch'].'%', PDO::PARAM_STR);
}
for ( $i=0 ; $i<count($columns) ; $i++ ) {
if ( isset($_GET['bSearchable_'.$i]) && $_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != '' ) {
$statement->bindValue(':search'.$i, '%'.$_GET['sSearch_'.$i].'%', PDO::PARAM_STR);
}
}
$statement->execute();
$rResult = $statement->fetchAll();
$iFilteredTotal = current($this->_db->query('SELECT FOUND_ROWS()')->fetch());
// Get total number of rows in table
$sQuery = "SELECT COUNT(`".$index_column."`) FROM `".$table."`";
//$sQuery = "SELECT COUNT(`".$index_column."`) FROM `".$table."` WHERE account_id < 100";
$iTotal = current($this->_db->query($sQuery)->fetch());
// Output
$output = array(
"sEcho" => intval($_GET['sEcho']),
"iTotalRecords" => $iTotal,
"iTotalDisplayRecords" => $iFilteredTotal,
"aaData" => array()
);
// Return array of values
foreach($rResult as $aRow) {
$row = array();
for ( $i = 0; $i < count($columns); $i++ ) {
//else if ( $aColumns[$i] != ' ' )
if ( $columns[$i] != ' ' )
{
/* General output */
//if column is empty give it n/a
$row[] = ($aRow[ $columns[$i] ]=="") ? 'n/a' : $aRow[ $columns[$i] ];
}
}
$output['aaData'][] = $row;
}
echo json_encode( $output );
}
}
header('Pragma: no-cache');
header('Cache-Control: no-store, no-cache, must-revalidate');
// Create instance of TableData class
$table_data = new TableData($db);
// Get the data
//$table_data->get('table_name', 'index_column', array('column1', 'column2', 'columnN'));
$table_data->get('accounts', 'account_id', array('account_id', 'account_username', 'account_password', 'account_email'));
?>
I doubt that anyone will be interested, but I finally figured this out. The script was trying to use the same binding, :search, multiple times in the statement.
Even though it will always be the same actual value the error was being thrown as it was the same binding. How I did not see this earlier I do not know, but it is obvious to me now.
//$sWhere .= "`".$columns[$i]."` LIKE :search OR ";
$sWhere .= "`".$columns[$i]."` LIKE :searchm".$i." OR ";
// Bind parameters
//if ( isset($_GET['sSearch']) && $_GET['sSearch'] != "" ) {
// $statement->bindValue(':search', '%'.$_GET['sSearch'].'%', PDO::PARAM_STR);
//}
if ( isset($_GET['sSearch']) && $_GET['sSearch'] != "" ) {
for ( $i=0 ; $i<count($columns) ; $i++ ) {
$statement->bindValue(':searchm'.$i, '%'.$_GET['sSearch'].'%', PDO::PARAM_STR);
}
}
I need to select all text-objects with a size between two values, for example 12 and 14pt (including 12.1, 12.2 etc). Is this at all possible?
This seems to be the candidate for a script. Try this:
function selectTextWhosePointSizeIs ( minPointSize, maxPointSize )
{
var doc, tfs, i = 0, n = 0, selectionArray = [];
if ( !app.documents.length ) { return; }
doc = app.activeDocument;
tfs = doc.textFrames;
n = tfs.length;
if ( !n ){ return; }
if ( isNaN ( minPointSize ) )
{
alert(minPointSize + " is not a valid number" );
return;
}
else if ( isNaN ( maxPointSize ) )
{
alert(maxPointSize + " is not a valid number" );
return;
}
else if ( minPointSize > maxPointSize )
{
alert(minPointSize + " can't be greater than "+ maxPointSize);
return;
}
for ( i = 0 ; i < n ; i++ )
{
if ( tfs[i].textRange.size >= minPointSize && tfs[i].textRange.size <= maxPointSize )
{
selectionArray [ selectionArray.length ] = tfs[i];
}
}
if ( selectionArray.length )
{
app.selection = selectionArray;
}
else
{
alert("Nothing found in this range.");
}
}
selectTextWhosePointSizeIs ( 12, 14 );
Hope it helps,
Loic
I created a database for a volunteers list. Then a form to pull out the personal info for volunteers who signed up to volunteer for particular tasks. I'm a beginner with php, and I have looked all over for an answer and tried multiple ways of doing it, but alas, no luck.
Here is the critical code I am currently struggling with:
if(isset($_POST['planning']) && $_POST['planning'] == '1')
{ $result1 = mysql_query("SELECT * FROM volunteers WHERE planning = '1'");}
if(isset($_POST['signatures']) && $_POST['signatures'] == '1')
{ $result2 = mysql_query("SELECT * FROM volunteers WHERE signatures = '1'");
$newresult1 = array_merge($result1, $result2);}
if(isset($_POST['canvassing']) && $_POST['canvassing'] == '1')
{ $result3 = mysql_query("SELECT * FROM volunteers WHERE canvassing = '1'");
$newresult2 = array_merge($newresult1, $result3);}
if(isset($_POST['phone_bank']) && $_POST['phone_bank'] == '1')
{ $result4 = mysql_query("SELECT * FROM volunteers WHERE phone_bank = '1'");
$newresult3 = array_merge($newresult2, $result4);}
if(isset($_POST['media']) && $_POST['media'] == '1')
{ $result5 = mysql_query("SELECT * FROM volunteers WHERE media = '1'"); $newresult4 =
array_merge($newresult3, $result5);}
if(isset($_POST['press_releases']) && $_POST['press_releases'] == '1')
{ $result6 = mysql_query("SELECT * FROM volunteers WHERE press_releases = '1'");
$newresult5 = array_merge($newresult4, $result6);}
if(isset($_POST['volunteer_coordinator']) && $_POST['volunteer_coordinator'] == '1')
{ $result7 = mysql_query("SELECT * FROM volunteers WHERE volunteer_coordinator =
'1'");
$newresult6 = array_merge($newresult5, $result7);}
if(isset($_POST['speaker']) && $_POST['speaker'] == '1')
{ $result8 = mysql_query("SELECT * FROM volunteers WHERE speaker = '1'"); $newresult7
= array_merge($newresult6, $result8);}
if(isset($_POST['house_parties']) && $_POST['house_parties'] == '1')
{ $result9 = mysql_query("SELECT * FROM volunteers WHERE house_parties = '1'");
$newresult8 = array_merge($newresult7, $result9);}
if(isset($_POST['web_page']) && $_POST['web_page'] == '1')
{ $result10 = mysql_query("SELECT * FROM volunteers WHERE web_page = '1'");
$newresult9
= array_merge($newresult8, $result10);}
if(isset($_POST['other']) && $_POST['other'] == '1')
{ $result11 = mysql_query("SELECT * FROM volunteers WHERE other = '1'"); $newresult10
= array_merge($newresult9, $result11);}
$newresult10 = array_unique($newresult10);
while($row = mysql_fetch_array($newresult10)) {
echo $row['first_name'] . " " . $row['last_name'];
echo " ";
echo $row['email'];
echo " ";
echo $row['phone'];
echo "<br />";
I much appreciated any suggestions.
You could write it so that it's more like this
[EDIT]-------- I think this is what your looking for
$postVars = array(
"canvassing"=>"1",
"other"=>"1"
//and you would go on post name valid post value
);
//start the query
$query="SELECT * FROM volunteers WHERE ";
//loop thru the posibable post vars and check and add to the query
$andcount=0;
foreach($postVars as $name=>$value){
if(isset($_POST[$name]) && $_POST[$name] == $value){
if($andcount>0)$query.=" AND ";
$query.=" ".$name."= '".mysql_real_escape_string($value)."'";
$andcount++;
}
}
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
echo $row['first_name'] . " " . $row['last_name'];
echo " ";
echo $row['email'];
echo " ";
echo $row['phone'];
echo "<br />";
}