- Home
- About
- Testimonials
- Demos
- Download
- Documentation
- Blogs
- Forum
- Support

Packages:
default
System
System.Caching
System.Collections
System.Data
System.Data.ActiveRecord
System.Data.ActiveRecord.Relations
System.Data.ActiveRecord.Scaffold
System.Data.ActiveReecord.Scaffold.InputBuilder
System.Data.Commom.Sqlite
System.Data.Common
System.Data.Common.Mssql
System.Data.Common.Mysql
System.Data.Common.Oracle
System.Data.Common.Pgsql
System.Data.Common.Sqlite
System.Data.DataGateway
System.Data.SqlMap
System.Data.SqlMap.Configuration
System.Data.SqlMap.Statements
System.Exceptions
System.I18N
System.IO
System.Security
System.Util
System.Web
System.Web.Services
System.Web.UI
System.Web.UI.ActiveControls
System.Web.UI.WebControls
System.Web.UI.WebControls.assets
System.Xml
Classes:
IDataSource
IItemDataRenderer
IRepeatInfoUser
TActiveFileUpload
TBaseDataList
TBaseValidator
TBoundColumn
TBulletedList
TBulletedListDisplayMode
TBulletedListEventParameter
TBulletStyle
TButton
TButtonColumn
TButtonColumnType
TButtonType
TCaptcha
TCaptchaValidator
TCheckBox
TCheckBoxColumn
TCheckBoxList
TCircleHotSpot
TClientScript
TClientScriptLoader
TClientSideValidationSummaryOptions
TColorPicker
TColorPickerClientSide
TColorPickerMode
TCompareValidator
TCompleteWizardStep
TConditional
TContent
TContentDirection
TContentPlaceHolder
TCustomValidator
TDataBoundControl
TDataGrid
TDataGridColumn
TDataGridColumnCollection
TDataGridCommandEventParameter
TDataGridItem
TDataGridItemCollection
TDataGridItemEventParameter
TDataGridItemRenderer
TDataGridPageChangedEventParameter
TDataGridPager
TDataGridPagerButtonType
TDataGridPagerEventParameter
TDataGridPagerMode
TDataGridPagerPosition
TDataGridPagerStyle
TDataGridSortCommandEventParameter
TDataList
TDataListCommandEventParameter
TDataListItem
TDataListItemCollection
TDataListItemEventParameter
TDataListItemRenderer
TDataRenderer
TDataSourceControl
TDataSourceSelectParameters
TDataSourceView
TDataTypeValidator
TDatePicker
TDatePickerClientScript
TDatePickerInputMode
TDatePickerMode
TDatePickerPositionMode
TDisplayStyle
TDraggable
TDropContainer
TDropDownList
TDropDownListColumn
TEditCommandColumn
TEmailAddressValidator
TExpression
TFileUpload
TFont
THiddenField
THorizontalAlign
THotSpot
THotSpotCollection
THotSpotMode
THtmlArea
THtmlElement
THyperLink
THyperLinkColumn
TImage
TImageButton
TImageClickEventParameter
TImageMap
TImageMapEventParameter
TInlineFrame
TInlineFrameAlign
TInlineFrameScrollBars
TItemDataRenderer
TJavascriptLogger
TKeyboard
TLabel
TLinkButton
TListBox
TListControl
TListControlValidator
TListItem
TListItemCollection
TListItemType
TListSelectionMode
TLiteral
TLiteralColumn
TMarkdown
TMetaTag
TMetaTagCollection
TMultiView
TOutputCache
TOutputCacheCalculateKeyEventParameter
TOutputCacheCheckDependencyEventParameter
TPager
TPagerButtonType
TPagerMode
TPagerPageChangedEventParameter
TPanel
TPanelStyle
TPlaceHolder
TPolygonHotSpot
TRadioButton
TRadioButtonList
TRangeValidationDataType
TRangeValidator
TRatingList
TReadOnlyDataSource
TReadOnlyDataSourceView
TRectangleHotSpot
TRegularExpressionValidator
TRepeatDirection
TRepeater
TRepeaterCommandEventParameter
TRepeaterItem
TRepeaterItemCollection
TRepeaterItemEventParameter
TRepeaterItemRenderer
TRepeatInfo
TRepeatLayout
TRequiredFieldValidator
TSafeHtml
TScrollBars
TServerValidateEventParameter
TSlider
TSliderClientScript
TSliderDirection
TStatements
TStyle
TStyleSheet
TTable
TTableCaptionAlign
TTableCell
TTableCellCollection
TTableFooterRow
TTableGridLines
TTableHeaderCell
TTableHeaderRow
TTableHeaderScope
TTableItemStyle
TTableRow
TTableRowCollection
TTableRowSection
TTableStyle
TTabPanel
TTabView
TTabViewCollection
TTemplateColumn
TTemplatedWizardStep
TTextAlign
TTextBox
TTextBoxAutoCompleteType
TTextBoxMode
TTextHighlighter
TTextHighlighterLineNumberStyle
TValidationCompareOperator
TValidationDataType
TValidationSummary
TValidationSummaryDisplayMode
TValidationSummaryDisplayStyle
TValidatorClientSide
TValidatorDisplayStyle
TVerticalAlign
TView
TViewCollection
TWebControl
TWebControlAdapter
TWizard
TWizardFinishNavigationTemplate
TWizardNavigationButtonStyle
TWizardNavigationButtonType
TWizardNavigationContainer
TWizardNavigationEventParameter
TWizardNavigationTemplate
TWizardSideBarListItemTemplate
TWizardSideBarTemplate
TWizardStartNavigationTemplate
TWizardStep
TWizardStepCollection
TWizardStepNavigationTemplate
TWizardStepType
TXmlTransform

Keyword

# Class TCaptcha

    TComponent
       |
       --TApplicationComponent
          |
          --TControl
             |
             --TWebControl
                |
                --TImage
                   |
                   --TCaptcha

TCaptcha class.

TCaptcha displays a CAPTCHA (a token displayed as an image) that can be used to determine if the input is entered by a real user instead of some program.

Unlike other CAPTCHA scripts, TCaptcha does not need session or cookie.

The token (a string consisting of alphanumeric characters) displayed is automatically generated and can be configured in several ways. To specify the length of characters in the token, set MinTokenLength and MaxTokenLength. To use case-insensitive comparison and generate upper-case-only token, set CaseSensitive to false. Advanced users can try to set TokenAlphabet, which specifies what characters can appear in tokens.

The validation of the token is related with two properties: TestLimit and TokenExpiry. The former specifies how many times a token can be tested with on the server side, and the latter says when a generated token will expire.

To specify the appearance of the generated token image, set TokenImageTheme to be an integer between 0 and 63. And to adjust the generated image size, set TokenFontSize (you may also set TWebControl::setWidth, but the scaled image may not look good.) By setting ChangingTokenBackground to true, the image background of the token will be variating even though the token is the same during postbacks.

Upon postback, user input can be validated by calling validate(). The TCaptchaValidator control can also be used to do validation, which provides client-side validation besides the server-side validation. By default, the token will remain the same during multiple postbacks. A new one can be generated by calling regenerateToken() manually.

The following template shows a typical use of TCaptcha control:

     <com:TCaptcha ID="Captcha" />
     <com:TTextBox ID="Input" />
     <com:TCaptchaValidator CaptchaControl="Captcha"
                            ControlToValidate="Input"
                            ErrorMessage="You are challenged!" />

Since: 3.1.1
Author: Qiang Xue <qiang.xue@gmail.com>

Constants Inherited From TControl

AUTOMATIC_ID_PREFIX, CLIENT_ID_SEPARATOR, CS_CHILD_INITIALIZED, CS_CONSTRUCTED, CS_INITIALIZED, CS_LOADED, CS_PRERENDERED, CS_STATE_LOADED, ID_FORMAT, ID_SEPARATOR, IS_CHILD_CREATED, IS_CREATING_CHILD, IS_DISABLE_THEMING, IS_DISABLE_VIEWSTATE, IS_ID_SET, IS_SKIN_APPLIED, IS_STYLESHEET_APPLIED, RF_ADAPTER, RF_AUTO_BINDINGS, RF_CHILD_STATE, RF_CONTROLS, RF_CONTROLSTATE, RF_DATA_BINDINGS, RF_EVENTS, RF_NAMED_CONTROLS, RF_NAMED_CONTROLS_ID, RF_NAMED_OBJECTS, RF_SKIN_ID,

Method Summary
boolean | checkRequirements () Checks the requirements needed for generating CAPTCHA images.
protected string | generatePrivateKeyFile () Generates a file with a randomly generated private key.
protected string | generateRandomKey ()
protected string | generateToken ( string $publicKey, string $privateKey, integer $alphabet, boolean $tokenLength, mixed $caseSensitive) Generates the token.
protected string | getCaptchaScriptFile ()
boolean | getCaseSensitive ()
boolean | getChangingTokenBackground ()
protected void | getFontFile ()
boolean | getIsTokenExpired ()
integer | getMaxTokenLength ()
integer | getMinTokenLength ()
string | getPrivateKey ()
string | getPublicKey ()
integer | getTestLimit ()
string | getToken ()
string | getTokenAlphabet ()
integer | getTokenExpiry ()
integer | getTokenFontSize ()
protected string | getTokenImageOptions ()
integer | getTokenImageTheme ()
protected integer | getTokenLength ()
protected string | hash2string ( string $hex, string $alphabet) Converts a hash string into a string with characters consisting of alphanumeric characters.
void | onPreRender ( mixed $param) Configures the image URL that shows the token.
void | regenerateToken () Regenerates the token to be displayed.
void | setCaseSensitive ( boolean $value)
void | setChangingTokenBackground ( boolean $value)
void | setMaxTokenLength ( integer $value)
void | setMinTokenLength ( integer $value)
void | setPublicKey ( string $value)
void | setTestLimit ( integer $value)
void | setTokenAlphabet ( string $value)
void | setTokenExpiry ( integer $value)
void | setTokenFontSize ( integer $value) Sets the font size used for displaying the token in an image.
void | setTokenImageTheme ( integer $value) Sets the theme of the token image.
boolean | validate ( string $input) Validates a user input with the token.

Methods Inherited From TImage
TImage::addAttributesToRender(), TImage::getAlternateText(), TImage::getData(), TImage::getDescriptionUrl(), TImage::getImageAlign(), TImage::getImageUrl(), TImage::getTagName(), TImage::renderContents(), TImage::setAlternateText(), TImage::setData(), TImage::setDescriptionUrl(), TImage::setImageAlign(), TImage::setImageUrl()

Methods Inherited From TWebControl

TWebControl::addAttributesToRender(), TWebControl::clearStyle(), TWebControl::copyBaseAttributes(), TWebControl::createStyle(), TWebControl::getAccessKey(), TWebControl::getBackColor(), TWebControl::getBorderColor(), TWebControl::getBorderStyle(), TWebControl::getBorderWidth(), TWebControl::getCssClass(), TWebControl::getDisplay(), TWebControl::getFont(), TWebControl::getForeColor(), TWebControl::getHasStyle(), TWebControl::getHeight(), TWebControl::getStyle(), TWebControl::getTabIndex(), TWebControl::getTagName(), TWebControl::getToolTip(), TWebControl::getWidth(), TWebControl::render(), TWebControl::renderBeginTag(), TWebControl::renderContents(), TWebControl::renderEndTag(), TWebControl::setAccessKey(), TWebControl::setBackColor(), TWebControl::setBorderColor(), TWebControl::setBorderStyle(), TWebControl::setBorderWidth(), TWebControl::setCssClass(), TWebControl::setDisplay(), TWebControl::setForeColor(), TWebControl::setHeight(), TWebControl::setStyle(), TWebControl::setTabIndex(), TWebControl::setToolTip(), TWebControl::setWidth()

Methods Inherited From TControl

TControl::addedControl(), TControl::addParsedObject(), TControl::addToPostDataLoader(), TControl::applyStyleSheetSkin(), TControl::autoBindProperty(), TControl::autoDataBindProperties(), TControl::bindProperty(), TControl::broadcastEvent(), TControl::bubbleEvent(), TControl::clearChildState(), TControl::clearControlState(), TControl::clearNamingContainer(), TControl::clearViewState(), TControl::convertUniqueIdToClientId(), TControl::createChildControls(), TControl::createControlCollection(), TControl::dataBind(), TControl::dataBindChildren(), TControl::dataBindProperties(), TControl::ensureChildControls(), TControl::findControl(), TControl::findControlsByID(), TControl::findControlsByType(), TControl::focus(), TControl::getAdapter(), TControl::getAllowChildControls(), TControl::getAttribute(), TControl::getAttributes(), TControl::getChildControlsCreated(), TControl::getClientID(), TControl::getControls(), TControl::getControlStage(), TControl::getControlState(), TControl::getCustomData(), TControl::getEnabled(), TControl::getEnableTheming(), TControl::getEnableViewState(), TControl::getHasAdapter(), TControl::getHasAttributes(), TControl::getHasChildInitialized(), TControl::getHasControls(), TControl::getHasInitialized(), TControl::getHasLoaded(), TControl::getHasLoadedPostData(), TControl::getHasPreRendered(), TControl::getID(), TControl::getNamingContainer(), TControl::getPage(), TControl::getParent(), TControl::getRegisteredObject(), TControl::getSkinID(), TControl::getSourceTemplateControl(), TControl::getTemplateControl(), TControl::getUniqueID(), TControl::getViewState(), TControl::getVisible(), TControl::hasAttribute(), TControl::initRecursive(), TControl::isDescendentOf(), TControl::isObjectRegistered(), TControl::loadRecursive(), TControl::loadState(), TControl::loadStateRecursive(), TControl::onDataBinding(), TControl::onInit(), TControl::onLoad(), TControl::onPreRender(), TControl::onUnload(), TControl::preRenderRecursive(), TControl::raiseBubbleEvent(), TControl::registerObject(), TControl::removeAttribute(), TControl::removedControl(), TControl::render(), TControl::renderChildren(), TControl::renderControl(), TControl::saveState(), TControl::saveStateRecursive(), TControl::setAdapter(), TControl::setAttribute(), TControl::setChildControlsCreated(), TControl::setControlStage(), TControl::setControlState(), TControl::setCustomData(), TControl::setEnabled(), TControl::setEnableTheming(), TControl::setEnableViewState(), TControl::setID(), TControl::setPage(), TControl::setSkinID(), TControl::setTemplateControl(), TControl::setViewState(), TControl::setVisible(), TControl::trackViewState(), TControl::traverseChildControls(), TControl::unbindProperty(), TControl::unloadRecursive(), TControl::unregisterObject(), TControl::__get()

Methods Inherited From TApplicationComponent
TApplicationComponent::getApplication(), TApplicationComponent::getRequest(), TApplicationComponent::getResponse(), TApplicationComponent::getService(), TApplicationComponent::getSession(), TApplicationComponent::getUser(), TApplicationComponent::publishAsset(), TApplicationComponent::publishFilePath()

Methods Inherited From TComponent

TComponent::addParsedObject(), TComponent::attachEventHandler(), TComponent::canGetProperty(), TComponent::canSetProperty(), TComponent::createdOnTemplate(), TComponent::detachEventHandler(), TComponent::evaluateExpression(), TComponent::evaluateStatements(), TComponent::getEventHandlers(), TComponent::getSubProperty(), TComponent::hasEvent(), TComponent::hasEventHandler(), TComponent::hasProperty(), TComponent::raiseEvent(), TComponent::setSubProperty(), TComponent::__get(), TComponent::__set()

Constant Summary
int | MAX_TOKEN_LENGTH |
int | MIN_TOKEN_LENGTH |

Method Details

## checkRequirements

public boolean checkRequirements | ()

Checks the requirements needed for generating CAPTCHA images.

TCaptach requires GD2 with TrueType font support and PNG image support.

Output
boolean | whether the requirements are satisfied.
Exception

## generatePrivateKeyFile

protected string generatePrivateKeyFile | ()

Generates a file with a randomly generated private key.

Output
string | the path of the file keeping the private key
Exception

## generateRandomKey

protected string generateRandomKey | ()

Output
string | a randomly generated key
Exception

## generateToken

protected string generateToken | (string $publicKey , string $privateKey , integer $alphabet , boolean $tokenLength , mixed $caseSensitive )

Generates the token.

Input
string | $publicKey | public key
string | $privateKey | private key
integer | $alphabet | the length of the token
boolean | $tokenLength | whether the token is case sensitive
mixed | $caseSensitive |
Output
string | the token generated.
Exception

## getCaptchaScriptFile

protected string getCaptchaScriptFile | ()

Output
string | the file path of the PHP script generating the token image
Exception

## getCaseSensitive

public boolean getCaseSensitive | ()

Output
boolean | whether the token should be treated as case-sensitive. Defaults to true.
Exception

## getChangingTokenBackground

public boolean getChangingTokenBackground | ()

Output
boolean | whether the background of the token image should be variated during postbacks. Defaults to false.
Exception

## getFontFile

protected void getFontFile | ()

Output
Exception

## getIsTokenExpired

public boolean getIsTokenExpired | ()

Output
boolean | whether the currently generated token has expired.
Exception

## getMaxTokenLength

public integer getMaxTokenLength | ()

Output
integer | the maximum length of the token. Defaults to 6.
Exception

## getMinTokenLength

public integer getMinTokenLength | ()

Output
integer | the minimum length of the token. Defaults to 4.
Exception

## getPrivateKey

public string getPrivateKey | ()

Output
string | the private key used for generating the token. This is randomly generated and kept in a file for persistency.
Exception

## getPublicKey

public string getPublicKey | ()

Output
string | the public key used for generating the token. A random one will be generated and returned if this is not set.
Exception

## getTestLimit

public integer getTestLimit | ()

Output
integer | how many times a generated token can be tested. Defaults to 5.
Exception

## getToken

public string getToken | ()

Output
string | the token that will be displayed
Exception

## getTokenAlphabet

public string getTokenAlphabet | ()

Output
string | the characters that may appear in the token. Defaults to '234578adefhijmnrtABDEFGHJLMNRT'.
Exception

## getTokenExpiry

public integer getTokenExpiry | ()

Output
integer | the number of seconds that a generated token will remain valid. Defaults to 600 seconds (10 minutes).
Exception

## getTokenFontSize

public integer getTokenFontSize | ()

Output
integer | the font size used for displaying the token in an image. Defaults to 30.
Exception

## getTokenImageOptions

protected string getTokenImageOptions | ()

Output
string | the options to be passed to the token image generator
Exception

## getTokenImageTheme

public integer getTokenImageTheme | ()

Output
integer | the theme of the token image. Defaults to 0.
Exception

## getTokenLength

protected integer getTokenLength | ()

Output
integer | the length of the token to be generated.
Exception

## hash2string

protected string hash2string | (string $hex , string $alphabet )

Converts a hash string into a string with characters consisting of alphanumeric characters.

Input
string | $hex | the hexadecimal representation of the hash string
string | $alphabet | the alphabet used to represent the converted string. If empty, it means '234578adefhijmnrtwyABDEFGHIJLMNQRTWY', which excludes those confusing characters.
Output
string | the converted string
Exception

## onPreRender

public void onPreRender | (mixed $param )

Configures the image URL that shows the token.

Input
mixed | $param | event parameter
Output
Exception

## regenerateToken

public void regenerateToken | ()

Regenerates the token to be displayed.

By default, a token, once generated, will remain the same during the following page postbacks. Calling this method will generate a new token.

Output
Exception

## setCaseSensitive

public void setCaseSensitive | (boolean $value )

Input
boolean | $value | whether the token should be treated as case-sensitive. If false, only upper-case letters will appear in the token.
Output
Exception

## setChangingTokenBackground

public void setChangingTokenBackground | (boolean $value )

Input
boolean | $value | whether the background of the token image should be variated during postbacks.
Output
Exception

## setMaxTokenLength

public void setMaxTokenLength | (integer $value )

Input
integer | $value | the maximum length of the token. It must be between 2 and 40.
Output
Exception

## setMinTokenLength

public void setMinTokenLength | (integer $value )

Input
integer | $value | the minimum length of the token. It must be between 2 and 40.
Output
Exception

## setPublicKey

public void setPublicKey | (string $value )

Input
string | $value | the public key used for generating the token. A random one will be generated if this is not set.
Output
Exception

## setTestLimit

public void setTestLimit | (integer $value )

Input
integer | $value | how many times a generated token can be tested. For unlimited tests, set it to 0.
Output
Exception

## setTokenAlphabet

public void setTokenAlphabet | (string $value )

Input
string | $value | the characters that may appear in the token. At least 2 characters must be specified.
Output
Exception

## setTokenExpiry

public void setTokenExpiry | (integer $value )

Input
integer | $value | the number of seconds that a generated token will remain valid. A value smaller than 1 means the token will not expire.
Output
Exception

## setTokenFontSize

public void setTokenFontSize | (integer $value )

Sets the font size used for displaying the token in an image.

This property affects the generated token image size. The image width is proportional to this font size.

Input
integer | $value | the font size used for displaying the token in an image. It must be an integer between 20 and 100.
Output
Exception

## setTokenImageTheme

public void setTokenImageTheme | (integer $value )

Sets the theme of the token image.

You may test each theme to find out the one you like the most. Below is the explanation of the theme value: It is treated as a 5-bit integer. Each bit toggles a specific feature of the image. Bit 0 (the least significant): whether the image is opaque (1) or transparent (0). Bit 1: whether we should add white noise to the image (1) or not (0). Bit 2: whether we should add a grid to the image (1) or not (0). Bit 3: whether we should add some scribbles to the image (1) or not (0). Bit 4: whether the image background should be morphed (1) or not (0). Bit 5: whether the token text should cast a shadow (1) or not (0).

Input
integer | $value | the theme of the token image. It must be an integer between 0 and 63.
Output
Exception

## validate

public boolean validate | (string $input )

Validates a user input with the token.

Input
string | $input | user input
Output
boolean | if the user input is not the same as the token.
Exception

Constant Details

### MAX_TOKEN_LENGTH

#### Type:

int

#### Value:

40

### MIN_TOKEN_LENGTH

#### Type:

int

#### Value:

2