D3.js Cubism.js ... beautifull work.
I tried use Cubism.js with own data source, with need display multiple horizon graphs synchronized.
Interval for update is very short (< 1s), that's why I need get values from data source in batch - all at one call.
Decision, if load newest data is made on comparing requested START,STOP with stored lastSTART,lastSTOP.
It's working in my code, but I don't know, how correctly call data update CALLBACK functions for each horizon graph.
At display is updated only last graph.
Can anybody help me solve this problem ?
Code:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:svg="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:lang="sk">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta charset="utf-8"/>
<title>DRI_realtimeSeries</title>
<link type="text/css" rel="stylesheet" href="./style.css"/>
<script src="./d3.v2.js"></script>
<!-- <script src="./d3.js"></script> problem with d3.CSV !!!! -->
<script src="./cubism.v1.js"></script>
</head>
<body>
<div id="view"></div>
<script id="JSON" type="text/javascript">//<![CDATA[
var context = cubism.context()
.serverDelay(1 * 1000)
.clientDelay(1 * 1000)
.step(1000)
;
var horizon = context.horizon();
var metrics = [ "en", "es", "de", "fr"];
var lastStart = null, lastStop = null;
var callArr = {};
var horizon = context.horizon()
.metric(function(d) {
return context.metric(
function(start, stop, step, callback) {
callArr[md] = callback;
if ((+lastStart != +start) || (+lastStop != +stop)) {
lastStart = +start; lastStop = +stop;
d3.json("http://localhost/COMPONENTS/Cubism/DRI_data.php"
+ "?expression=" + encodeURIComponent("sum(request.eq(language,'" + md + "'))")
+ "&list=" + encodeURIComponent(JSON.stringify(metrics))
+ "&start=" + d3.time.format.iso(start) //cubism_cubeFormatDate(start)
+ "&stop=" + d3.time.format.iso(stop) //cubism_cubeFormatDate(stop)
+ "&step=" + step,
function(data) {
{"en":[ {"time":"2012-10-24T14:47:53.000Z","value":-37},
{"time":"2012-10-24T14:47:54.000Z","value":115},
{"time":"2012-10-24T14:47:55.000Z","value":100},
....
{"time":"2012-10-24T14:48:00.000Z","value":94}
],
"es":[ {"time":"2012-10-24T14:47:53.000Z","value":32},
....
{"time":"2012-10-24T14:48:00.000Z","value":0}
],
....
}
for (var imd in callArr) {
if (callArr.hasOwnProperty(imd)) {
var callbackI = callArr[imd];
//HERE is something WRONG
if (!data) { return callbackI(new Error("unable to load data")); };
callbackI( null, data[imd].map( function(d) { return d.value; } ));
}
}
}
);
}
}, md=d );
}
);
d3.select("body").selectAll(".horizon")
.data(metrics)
.enter().append("div")
.attr("class", "horizon")
.call(horizon);
//]]></script>
</body>
</html>
PHP backend:
Only for simulation purposes - return JSON object with named arrays of timestamped values
maybe similarly like a Cube.js
<?php
//default:
$GP = array('list' => '["all"]');
if (isset($_POST['expression'])) $GP['expression'] =$_POST['expression']; elseif (isset($_GET['expression'])) $GP['expression'] =$_GET['expression'];
if (isset($_POST['start'])) $GP['start'] =$_POST['start']; elseif (isset($_GET['start'])) $GP['start'] =$_GET['start'];
if (isset($_POST['stop'])) $GP['stop'] =$_POST['stop']; elseif (isset($_GET['stop'])) $GP['stop'] =$_GET['stop'];
if (isset($_POST['step'])) $GP['step'] =$_POST['step']; elseif (isset($_GET['step'])) $GP['step'] =$_GET['step'];
if (isset($_POST['list'])) $GP['list'] =$_POST['list']; elseif (isset($_GET['list'])) $GP['list'] =$_GET['list'];
if ( ! ( isset($GP['expression']) && isset($GP['start']) && isset($GP['stop']) && isset($GP['step']) ) ) {
exit;
}
$iso_format = "%Y-%m-%dT%H:%M:%S.%LZ";
$start = umktime(strptime($GP['start'], $iso_format));
$stop = umktime(strptime($GP['stop' ], $iso_format));
$step = $GP['step' ]; //milisecs
$GP['list'] = json_decode($GP['list']); if (! $GP['list']) { exit;}
$cnt = count($GP['list']);
$larray = array();
for($i = 0; $i < $cnt; $i++) {
$rarray = array();
for ($dt = $start; $dt <= $stop; $dt+= ($step/1000.)) {
$rarray[] =
array(
"time"=> strftime("%Y-%m-%dT%H:%M:%S",$dt).sprintf(".%03dZ",($dt - (int)$dt)*1000),
"value"=> rand(-50,150)
);
}
$larray[$GP['list'][$i]] = $rarray;
}
echo json_encode($cnt == 1 ? $rarray : $larray);
function umktime($u_tm_arr) {
//int mktime ([ int $hour = date("H") [, int $minute = date("i") [, int $second = date("s") [, int $month = date("n") [, int $day = date("j") [, int $year = date("Y") [, int $is_dst = -1 ]]]]]]] )
$mkt = mktime( $u_tm_arr['tm_hour'],$u_tm_arr['tm_min'],$u_tm_arr['tm_sec'],$u_tm_arr['tm_mon'] + 1,$u_tm_arr['tm_mday'],($u_tm_arr['tm_year'] + 1900) - 2000 );
$mkt = (float)$mkt;
if (isset($u_tm_arr['tm_msec'])) { $mkt += (((float)$u_tm_arr['tm_msec'])/1000) ; }
return $mkt;
}
//Windows strptime
function strptime($date, $format) {
$masks = array( '%d' => '(?P<d>[0-9]{2})', '%m' => '(?P<m>[0-9]{2})', '%Y' => '(?P<Y>[0-9]{4})',
'%H' => '(?P<H>[0-9]{2})', '%M' => '(?P<M>[0-9]{2})', '%S' => '(?P<S>[0-9]{2})', // usw..
'%L' => '(?P<L>[0-9]{3})', '%u' => '(?P<u>[0-9]{3})',
);
$rexep = "#".strtr(preg_quote($format), $masks)."#";
if(!preg_match($rexep, $date, $out)) {
return false;
}
$ret = array( "tm_sec" => (int) $out['S'], "tm_min" => (int) $out['M'], "tm_hour" => (int) $out['H'],
"tm_mday" => (int) $out['d'], "tm_mon" => $out['m']?$out['m']-1:0, "tm_year" => $out['Y'] > 1900 ? $out['Y'] - 1900 : 0,
"tm_msec" => (int) (isset($out['u']) ? $out['u'] : (isset($out['L']) ? $out['L'] : 0) ),
);
return $ret;
}
?>
Related
This is my ajax code which fetches all data from data and display in the table, but when I input an alphabet in search-box, it again fetches complete data inside the table
<script>
$(document).ready(function(){
load_data();
function load_data(query)
{
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "<?php echo base_url() ?>Appconfig/get_masteradmin_data?query="+query,true);
xhttp.onload= function()
{
if (xhttp.status >=200 && xhttp.status <400)
{
var data= JSON.parse(xhttp.responseText);
var html = '';
var i;
for(i=0; i<data.length; i++){
html +='<tr>'+
'<td>'+data[i].full_name+'</td>'+
'<td>'+data[i].username+'</td>'+
'<td>'+data[i].designation+'</td>'+
'<td>'+data[i].department+'</td>'+
'<td>'+data[i].official_mobile_no+'</td>'+
'<td>'+data[i].official_email_id+'</td>'+
'<td>'+data[i].select_user_type+'</td>'+
'<td>'+data[i].permission+'</td>'+
'</tr>';
}
showdata.insertAdjacentHTML('beforeend',html);
}
else
{
console.log("Try again after some time");
}
};
xhttp.send();
}
$('#search').keyup(function(){
var search = $(this).val();
//console.log(search);
if(search != '')
{
load_data(search);
}
else
{
load_data();
}
});
});
</script>
This is my model for fetching data from my mongodb collection.
public function get_masteradmin_data($query)
{
$mongo = new \MongoDB\Driver\Manager('mongodb://localhost:27017');
$query= '';
//$filter = ['full_name' => 'www'];
$regex = new MongoDB\BSON\Regex ($query);
$filter = ['full_name'=>$regex,];
$options =[
'projection' => [
'_id' => 0,
'full_name' => 1,
'username' => 1,
'designation'=> 1,
'department'=> 1,
'official_mobile_no'=> 1,
'official_email_id'=> 1,
'select_user_type'=> 1,
'permission'=> 1,
],
'sort' => [
'_id' => -1
],
];
$query = new MongoDB\Driver\Query($filter, $options);
//$readPreference = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY);
$result = $mongo->executeQuery('justrack_db.master_admin', $query);
$res = array();
foreach($result as $r)
{
$res[] = $r;
}
return json_encode($res,true);
//return $res;
}
This is my controller for displaying data. I am not sure, but I think there is some issue in my controller, as I tried to echo $query but it shows nothing. I am not able to understand how to fix this.
public function get_masteradmin_data()
{
$query = '';
$this->load->model('AppconfigModel');
$this->master_admin();
if($this->input->post('query'))
{
$query = $this->input->post('query');
}
$result= $this->AppconfigModel->get_masteradmin_data($query);
echo ($result);
}
I tried this to search dom elements and display matching rows,but it doesnt work in some columns like duration and bytes.It works for elements which repeat for example if there are 507 value twice in bytes it works but dont work for 411. I am reading file contents and tabulating it, then need to sort rows when header is clicked and apply a filter.
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<head>
<style type="text/css">
body
{
font-family: Arial;
font-size: 10pt;
}
table
{
border: 1px solid #ccc;
margin: auto;
empty-cells: hide;
}
table th
{
background-color: GREY;
color: #333;
font-weight: bold;
cursor:pointer;
}
table th, table td
{
padding: 5px;
border: 1px solid #ccc;
border-color: #ccc;
}
#sear
{
background-color: black;
height:30px;
width:105%;
align : center;
}
tr:nth-child(even) {
background-color: #f2f2f2
}
tr:hover {
background-color: silver;
}
</style>
<meta name="viewport" content="width=device-width,height=device-height, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div id="sear" align = center>
<input type="text" id="filter" placeholder="Search" title="Type a name" >
</div>
<div id="demo" align = center >
</div>
<script>
window.onload = function() {
var demo = document.getElementById("demo");
if(window.XMLHttpRequest){
var xhttp = new XMLHttpRequest();
}
else{
var xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200 || this.status == 0) {
var responseText= xhttp.responseText;
//alert(responseText);
// console.log(this.responseText);
document.getElementById("filter").onkeyup = filterRows;
var ROW_DELIMITER = "\n", CELL_DELIMITER = " ";
var tableObj = { headers: ["Time", "Duration", "Client address", "Result codes", "Bytes", "request method", "URL", "user",
"Hierarchy code", "Type"],
rows: []
};
}
function convert(responseText) {
tableObj.rows = convertToArray(responseText);
buildTable(tableObj.headers, tableObj.rows);
};
function convertToArray(text) {
return text.split(ROW_DELIMITER).map(function(row) {
return row.split(CELL_DELIMITER);
});
}
function filterRows() {
var input = this;
var rows = tableObj.rows.filter(function(row) {
var matches = row.filter(function(cell) {
return cell.toUpperCase().indexOf(input.value.toUpperCase()) > -1;
});
return matches.length > 0;
});
buildTable(tableObj.headers, rows);
}
function sortRows() {
var index = this.dataset.index;
tableObj.rows.sort(function(rowA, rowB) {
var textA = rowA[index].toUpperCase(), textB = rowB[index].toUpperCase();
if (textA < textB) {
return -1;
}
if (textA > textB) {
return 1;
}
return 0;
});
buildTable(tableObj.headers, tableObj.rows);
}
function buildTable(headers, rows) {
var table = document.createElement('table');
var tr = document.createElement('tr');
table.appendChild(tr);
for (var i = 0; i < headers.length; i++) {
th = document.createElement('th');
tr.appendChild(th);
th.innerHTML = headers[i];
th.onclick = sortRows;
th.dataset.index = i;
}
for (var j = 0; j < rows.length-1; j++) {
tr = document.createElement('tr');
table.appendChild(tr);
tr.dataset.index = j;
for (var k = 0; k < rows[j].length ; k++) {
var td = document.createElement('td');
/* if(k==0)
{
var d = new Date( rows[j][k]* 1000),
yyyy = d.getFullYear(),
mm = ('0' + (d.getMonth() + 1)).slice(-2),
dd = ('0' + d.getDate()).slice(-2),
hh = d.getHours(),
h = hh,
min = ('0' + d.getMinutes()).slice(-2),
ampm = 'AM',
time;
if (hh > 12) {
h = hh - 12;
ampm = 'PM';
} else if (hh === 12) {
h = 12;
ampm = 'PM';
} else if (hh == 0) {
h = 12;
}
rows[j][k] = dd + '.' + mm + '.' + yyyy + ', ' + h + ':' + min + ' ' + ampm;
}
*/
tr.appendChild(td);
td.innerHTML = rows[j][k];
td.dataset.index = k;
}
}
demo.innerHTML = '';
demo.appendChild(table);
}
convert(responseText);
};
xhttp.open("GET", "sample.txt", true);
xhttp.send(null);
};
</script>
</body>
</html>
Here is the updated code:
window.onload = function() {
var demo = document.getElementById("demo");
if (window.XMLHttpRequest) {
var xhttp = new XMLHttpRequest();
} else {
var xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200 || this.status == 0) {
var responseText = xhttp.responseText;
console.log(this.responseText);
document.getElementById("filter").onkeyup = filterRows;
var ROW_DELIMITER = "\n",
CELL_DELIMITER = " ";
var tableObj = {
headers: ["Time", "Duration", "Client address", "Result codes", "Bytes", "request method", "URL", "user", "Hierarchy code", "Type"],
rows: []
};
}
function convert(responseText) {
if(responseText!='' && typeof responseText != 'undefined'){
tableObj.rows = convertToArray(responseText);
buildTable(tableObj.headers, tableObj.rows);
}
};
function convertToArray(text) {
return text.split(ROW_DELIMITER).map(function(row) {
return row.split(CELL_DELIMITER);
});
}
function filterRows() {
var input = this;
var rows = tableObj.rows.filter(function(row) {
var matches = row.filter(function(cell) {
//console.log(cell.toUpperCase())
// console.log(input.value.toUpperCase())
// console.log(cell.toUpperCase().indexOf(input.value.toUpperCase()))
return cell.toUpperCase().indexOf(input.value.toUpperCase()) > -1;
});
return matches.length > 0;
});
buildTable(tableObj.headers, rows);
}
function sortRows() {
var index = this.dataset.index;
tableObj.rows.sort(function(rowA, rowB) {
var textA = rowA[index].toUpperCase(),
textB = rowB[index].toUpperCase();
if (textA < textB) {
return -1;
}
if (textA > textB) {
return 1;
}
return 0;
});
buildTable(tableObj.headers, tableObj.rows);
}
function buildTable(headers, rows) {
var table = document.createElement('table');
var tr = document.createElement('tr');
table.appendChild(tr);
for (var i = 0; i < headers.length; i++) {
th = document.createElement('th');
tr.appendChild(th);
th.innerHTML = headers[i];
th.onclick = sortRows;
th.dataset.index = i;
}
for (var j = 0; j <= rows.length - 1; j++) {
tr = document.createElement('tr');
table.appendChild(tr);
tr.dataset.index = j;
for (var k = 0; k < rows[j].length; k++) {
var td = document.createElement('td');
tr.appendChild(td);
td.innerHTML = rows[j][k];
td.dataset.index = k;
}
}
demo.innerHTML = '';
demo.appendChild(table);
}
convert(responseText);
};
xhttp.open("GET", "sample.txt", true);
xhttp.send(null);
};
#(Html.Kendo().Grid<Tracker.TMS.BE.uspTMSSelectAreas_Result>()
.Name("AvailableAreas")
.Groupable()
.Sortable()
.Filterable()
.Scrollable()
.Selectable(s => s.Mode(GridSelectionMode.Multiple))
.Columns(columns =>
{
columns.Bound(e => e.CustomerVehicleID).Visible(false);
columns.Bound(e => e.AreaID).Visible(false);
columns.Bound(e => e.AreaType).Title("Area Type").Width(100);
columns.Bound(e => e.SubType).Title("Sub Type").Width(100);
columns.Bound(e => e.AreaName).Title("Area Name");
})
.Resizable(resize => resize.Columns(true))
.Pageable(page => page.Enabled(false)).NoRecords("No records found.")
.Events(e => e.Change("availableAreaSelected"))
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("GetAvailableAreas", "Vehicle").Data("filterAreas"))))
Grid column resizing does not work in IE in Kendo UI version 2016.2.607. Please use another version, or the following workaround, which overrides the client-side Grid object prototype:
http://dojo.telerik.com/AzaKu/2
kendo.ui.Grid.fn._positionColumnResizeHandle = function() {
function cursor(context, value) {
$('th, th .k-grid-filter, th .k-link', context)
.add(document.body)
.css('cursor', value);
}
var NS = ".kendoGrid",
that = this,
isRtl = kendo.support.isRtl(that.element),
indicatorWidth = that.options.columnResizeHandleWidth,
lockedHead = that.lockedHeader ? that.lockedHeader.find("thead:first") : $();
that.thead.add(lockedHead).on("mousemove" + NS, "th", function(e) {
var th = $(this);
if (th.hasClass("k-group-cell") || th.hasClass("k-hierarchy-cell")) {
return;
}
function getPageZoomStyle() {
var docZoom = parseFloat($(document.documentElement).css("zoom"));
if (isNaN(docZoom)) {
docZoom = 1;
}
var bodyZoom = parseFloat($(document.body).css("zoom"));
if (isNaN(bodyZoom)) {
bodyZoom = 1;
}
return docZoom * bodyZoom;
}
var clientX = e.clientX / getPageZoomStyle(),
winScrollLeft = $(window).scrollLeft(),
position = th.offset().left + (!isRtl ? this.offsetWidth : 0);
if (clientX + winScrollLeft > position - indicatorWidth && clientX + winScrollLeft < position + indicatorWidth) {
that._createResizeHandle(th.closest("div"), th);
} else if (that.resizeHandle) {
that.resizeHandle.hide();
} else {
cursor(that.wrapper, "");
}
});
}
Slight modification to #dimodi's answer since in ie if the body zoom is set to 1 then
$(document.body).css("zoom")
will return 100% and not 1, this will prevent the users from resizing
kendo.ui.Grid.fn._positionColumnResizeHandle = function() {
function cursor(context, value) {
$('th, th .k-grid-filter, th .k-link', context)
.add(document.body)
.css('cursor', value);
}
var NS = ".kendoGrid",
that = this,
isRtl = kendo.support.isRtl(that.element),
indicatorWidth = that.options.columnResizeHandleWidth,
lockedHead = that.lockedHeader ? that.lockedHeader.find("thead:first") : $();
that.thead.add(lockedHead).on("mousemove" + NS, "th", function(e) {
var th = $(this);
if (th.hasClass("k-group-cell") || th.hasClass("k-hierarchy-cell")) {
return;
}
function getPageZoomStyle() {
var docZoom = parseFloat($(document.documentElement).css("zoom"));
if (isNaN(docZoom)) {
docZoom = 1;
}
var bodyZoom = parseFloat($(document.body).css("zoom"));
if (isNaN(bodyZoom)) {
bodyZoom = 1;
}
else if (bodyZoom>=100 && (browser.msie || browser.edge)) {
bodyZoom = bodyZoom/100;
}
return docZoom * bodyZoom;
}
var clientX = e.clientX / getPageZoomStyle(),
winScrollLeft = $(window).scrollLeft(),
position = th.offset().left + (!isRtl ? this.offsetWidth : 0);
if (clientX + winScrollLeft > position - indicatorWidth && clientX + winScrollLeft < position + indicatorWidth) {
that._createResizeHandle(th.closest("div"), th);
} else if (that.resizeHandle) {
that.resizeHandle.hide();
} else {
cursor(that.wrapper, "");
}
});
}
My model has an event_datetime field which I want to set on the form using datetime select fields. Rails has datetime_select which outputs the following and saves to a MySQL datetime column.
Must default to the current date and work on a shared add/edit form.
No javascript datepickers please.
Add this to you
{{ Form::datetime('event_date') }}
And place this macro into some autoloaded file (or view file)
Form::macro('datetime', function($name) {
$years = value(function() {
$startYear = (int) date('Y');
$endYear = $startYear - 5;
$years = ['' => 'year'];
for($year = $startYear; $year > $endYear; $year--) {
$years[ $year ] = $year;
};
return $years;
});
$months = value(function() {
$months = ['' => 'month'];
for($month = 1; $month < 13; $month++) {
$timestamp = strtotime(date('Y'). '-'.$month.'-13');
$months[ $month ] = strftime('%B', $timestamp);
}
return $months;
});
$days = value(function() {
$days = ['' => 'day'];
for($day = 1; $day < 32; $day++) {
$days[ $day ] = $day;
}
return $days;
});
$hours = value(function() {
$hours = ['' => 'hour'];
for($hour = 0; $hour < 24; $hour++) {
$hours[ $hour ] = $hour;
}
return $hours;
});
$minutes = value(function() {
$minutes = ['' => 'minute'];
for($minute = 0; $minute < 60; $minute++) {
$minutes[ $minute ] = $minute;
}
return $minutes;
});
return Form::select($name.'[year]', $years) .
Form::select($name.'[month]', $months) .
Form::select($name.'[day]', $days) . ' - ' .
Form::select($name.'[hour]', $hours) .
Form::select($name.'[minute]', $minutes);
});
I followed this page, and the code is not working as it should in my project. I've tried to find other tutorial on how to execute what I need, however, it does not work as it should in my project either. Is anyone able to direct me to a tutorial that explains in a detailed fashion on how to use Captcha plug-in properly in CodeIgniter?
Controller:
<?php
class Prova extends Controller
{
function prova()
{
parent :: Controller();
$this -> load -> plugin( 'captcha' );
$this->load->library('validation');
$rules['user'] = "required";
$rules['captcha'] = "required|callback_captcha_check";
$this->validation->set_rules($rules);
$fields['user'] = 'Username';
$fields['captcha'] = 'codice';
$this->validation->set_fields($fields);
if ($this->validation->run() == FALSE)
{
$expiration = time()-300; // Two hour limit
$this->db->query("DELETE FROM captcha WHERE captcha_time < ".$expiration);
$vals = array(
//'word' => 'Random word',
'img_path' => './tmp/captcha/',
'img_url' => base_url().'tmp/captcha/',
'font_path' => './system/fonts/texb.ttf',
'img_width' => '100',
'img_height' => '30',
'expiration' => '3600'
);
$cap = $this->captcha->create_captcha($vals);
//
$dati['image']= $cap['image'];
//mette nel db
$data = array(
'captcha_id' => '',
'captcha_time' => $cap['time'],
'ip_address' => $this->input->ip_address(),
'word' => $cap['word']
);
$query = $this->db->insert_string('captcha', $data);
$this->db->query($query);
$this->load->view('captcha',$data);
}else{
echo "Captcha can't be made";
}
return $cap ['image'];
}
function captcha_check()
{
// Then see if a captcha exists:
$exp=time()-600;
$sql = "SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip_address = ? AND captcha_time > ?";
$binds = array($this->input->post('captcha'), $this->input->ip_address(), $exp);
$query = $this->db->query($sql, $binds);
$row = $query->row();
if ($row->count == 0)
{
$this->validation->set_message('_captcha_check', 'Codice di controllo non valido');
return FALSE;
}else{
return TRUE;
}
}
}
View:
<html>
<head>
<title>My Form</title>
</head>
<body>
<?=$this->validation->error_string; ?>
<?=form_open('XXXXXXXXX type your controller'); ?>
<h5>Username</h5>
<?=$this->validation->user_error; ?>
<input type="text" name="user" value="<?php echo ($this->validation->user) ;?>" size="50" />
<br/>
<?=$image;?>
<br/>
<?=$this->validation->captcha_error; ?>
<input type="text" name="captcha" value="" />
<br/>
<div><input type="submit" value="Submit" /></div>
</form>
</body>
</html>
Captcha:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 4.3.2 or newer
*
* #package CodeIgniter
* #author ExpressionEngine Dev Team
* #copyright Copyright (c) 2008, EllisLab, Inc.
* #license http://codeigniter.com/user_guide/license.html
* #link http://codeigniter.com
* #since Version 1.0
* #filesource
*/
// ------------------------------------------------------------------------
/*
Instructions:
Load the plugin using:
$this->load->plugin('captcha');
Once loaded you can generate a captcha like this:
$vals = array(
'word' => 'Random word',
'img_path' => './captcha/',
'img_url' => 'http://example.com/captcha/',
'font_path' => './system/fonts/texb.ttf',
'img_width' => '150',
'img_height' => 30,
'expiration' => 7200
);
$cap = create_captcha($vals);
echo $cap['image'];
NOTES:
The captcha function requires the GD image library.
Only the img_path and img_url are required.
If a "word" is not supplied, the function will generate a random
ASCII string. You might put together your own word library that
you can draw randomly from.
If you do not specify a path to a TRUE TYPE font, the native ugly GD
font will be used.
The "captcha" folder must be writable (666, or 777)
The "expiration" (in seconds) signifies how long an image will
remain in the captcha folder before it will be deleted. The default
is two hours.
RETURNED DATA
The create_captcha() function returns an associative array with this data:
[array]
(
'image' => IMAGE TAG
'time' => TIMESTAMP (in microtime)
'word' => CAPTCHA WORD
)
The "image" is the actual image tag:
<img src="http://example.com/captcha/12345.jpg" width="140" height="50" />
The "time" is the micro timestamp used as the image name without the file
extension. It will be a number like this: 1139612155.3422
The "word" is the word that appears in the captcha image, which if not
supplied to the function, will be a random string.
ADDING A DATABASE
In order for the captcha function to prevent someone from posting, you will need
to add the information returned from create_captcha() function to your database.
Then, when the data from the form is submitted by the user you will need to verify
that the data exists in the database and has not expired.
Here is a table prototype:
CREATE TABLE captcha (
captcha_id bigint(13) unsigned NOT NULL auto_increment,
captcha_time int(10) unsigned NOT NULL,
ip_address varchar(16) default '0' NOT NULL,
word varchar(20) NOT NULL,
PRIMARY KEY `captcha_id` (`captcha_id`),
KEY `word` (`word`)
)
Here is an example of usage with a DB.
On the page where the captcha will be shown you'll have something like this:
$this->load->plugin('captcha');
$vals = array(
'img_path' => './captcha/',
'img_url' => 'http://example.com/captcha/'
);
$cap = create_captcha($vals);
$data = array(
'captcha_id' => '',
'captcha_time' => $cap['time'],
'ip_address' => $this->input->ip_address(),
'word' => $cap['word']
);
$query = $this->db->insert_string('captcha', $data);
$this->db->query($query);
echo 'Submit the word you see below:';
echo $cap['image'];
echo '<input type="text" name="captcha" value="" />';
Then, on the page that accepts the submission you'll have something like this:
// First, delete old captchas
$expiration = time()-7200; // Two hour limit
$DB->query("DELETE FROM captcha WHERE captcha_time < ".$expiration);
// Then see if a captcha exists:
$sql = "SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip_address = ? AND date > ?";
$binds = array($_POST['captcha'], $this->input->ip_address(), $expiration);
$query = $this->db->query($sql, $binds);
$row = $query->row();
if ($row->count == 0)
{
echo "You must submit the word that appears in the image";
}
*/
/**
|==========================================================
| Create Captcha
|==========================================================
|
*/
function create_captcha($data = '', $img_path = '', $img_url = '', $font_path = '')
{
$defaults = array('word' => '', 'img_path' => '', 'img_url' => '', 'img_width' => '150', 'img_height' => '30', 'font_path' => '', 'expiration' => 7200);
foreach ($defaults as $key => $val)
{
if ( ! is_array($data))
{
if ( ! isset($$key) OR $$key == '')
{
$$key = $val;
}
}
else
{
$$key = ( ! isset($data[$key])) ? $val : $data[$key];
}
}
if ($img_path == '' OR $img_url == '')
{
return FALSE;
}
if ( ! #is_dir($img_path))
{
return FALSE;
}
if ( ! is_really_writable($img_path))
{
return FALSE;
}
if ( ! extension_loaded('gd'))
{
return FALSE;
}
// -----------------------------------
// Remove old images
// -----------------------------------
list($usec, $sec) = explode(" ", microtime());
$now = ((float)$usec + (float)$sec);
$current_dir = #opendir($img_path);
while($filename = #readdir($current_dir))
{
if ($filename != "." and $filename != ".." and $filename != "index.html")
{
$name = str_replace(".jpg", "", $filename);
if (($name + $expiration) < $now)
{
#unlink($img_path.$filename);
}
}
}
#closedir($current_dir);
// -----------------------------------
// Do we have a "word" yet?
// -----------------------------------
if ($word == '')
{
$pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$str = '';
for ($i = 0; $i < 8; $i++)
{
$str .= substr($pool, mt_rand(0, strlen($pool) -1), 1);
}
$word = $str;
}
// -----------------------------------
// Determine angle and position
// -----------------------------------
$length = strlen($word);
$angle = ($length >= 6) ? rand(-($length-6), ($length-6)) : 0;
$x_axis = rand(6, (360/$length)-16);
$y_axis = ($angle >= 0 ) ? rand($img_height, $img_width) : rand(6, $img_height);
// -----------------------------------
// Create image
// -----------------------------------
// PHP.net recommends imagecreatetruecolor(), but it isn't always available
if (function_exists('imagecreatetruecolor'))
{
$im = imagecreatetruecolor($img_width, $img_height);
}
else
{
$im = imagecreate($img_width, $img_height);
}
// -----------------------------------
// Assign colors
// -----------------------------------
$bg_color = imagecolorallocate ($im, 255, 255, 255);
$border_color = imagecolorallocate ($im, 153, 102, 102);
$text_color = imagecolorallocate ($im, 204, 153, 153);
$grid_color = imagecolorallocate($im, 255, 182, 182);
$shadow_color = imagecolorallocate($im, 255, 240, 240);
// -----------------------------------
// Create the rectangle
// -----------------------------------
ImageFilledRectangle($im, 0, 0, $img_width, $img_height, $bg_color);
// -----------------------------------
// Create the spiral pattern
// -----------------------------------
$theta = 1;
$thetac = 7;
$radius = 16;
$circles = 20;
$points = 32;
for ($i = 0; $i < ($circles * $points) - 1; $i++)
{
$theta = $theta + $thetac;
$rad = $radius * ($i / $points );
$x = ($rad * cos($theta)) + $x_axis;
$y = ($rad * sin($theta)) + $y_axis;
$theta = $theta + $thetac;
$rad1 = $radius * (($i + 1) / $points);
$x1 = ($rad1 * cos($theta)) + $x_axis;
$y1 = ($rad1 * sin($theta )) + $y_axis;
imageline($im, $x, $y, $x1, $y1, $grid_color);
$theta = $theta - $thetac;
}
// -----------------------------------
// Write the text
// -----------------------------------
$use_font = ($font_path != '' AND file_exists($font_path) AND function_exists('imagettftext')) ? TRUE : FALSE;
if ($use_font == FALSE)
{
$font_size = 5;
$x = rand(0, $img_width/($length/3));
$y = 0;
}
else
{
$font_size = 16;
$x = rand(0, $img_width/($length/1.5));
$y = $font_size+2;
}
for ($i = 0; $i < strlen($word); $i++)
{
if ($use_font == FALSE)
{
$y = rand(0 , $img_height/2);
imagestring($im, $font_size, $x, $y, substr($word, $i, 1), $text_color);
$x += ($font_size*2);
}
else
{
$y = rand($img_height/2, $img_height-3);
imagettftext($im, $font_size, $angle, $x, $y, $text_color, $font_path, substr($word, $i, 1));
$x += $font_size;
}
}
// -----------------------------------
// Create the border
// -----------------------------------
imagerectangle($im, 0, 0, $img_width-1, $img_height-1, $border_color);
// -----------------------------------
// Generate the image
// -----------------------------------
$img_name = $now.'.jpg';
ImageJPEG($im, $img_path.$img_name);
$img = "<img src=\"$img_url$img_name\" width=\"$img_width\" height=\"$img_height\" style=\"border:0;\" alt=\" \" />";
ImageDestroy($im);
return array('word' => $word, 'time' => $now, 'image' => $img);
}
/* End of file captcha_pi.php */
/* Location: ./system/plugins/captcha_pi.php */
The whole tutorial is in the captcha_pi file. The captcha tutorial in the wiki works on a different script (a class).
try this, CodeIgniter Captcha User Guide