Skip to content

Commit 3af694e

Browse files
committed
Added support of nodejs instead of V8js
fixes #29 Set version to 0.6.8
1 parent 2ae9d2f commit 3af694e

15 files changed

+307
-225
lines changed

ajax/getFormValidations.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@
4545
$is_createitem = 0; // by default
4646

4747
$obj = getItemForItemtype( $_GET['name'] );
48-
if ($obj) {
48+
if ($obj && method_exists($obj, 'getType')) {
4949
if ($_GET['id'] > 0) {
5050
$obj->getFromDB( $_GET['id'] );
5151
$entity_restrict = 0; // by default if $obj doesn't have entities_id in table

formvalidation.xml

+1-1
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
</authors>
2626
<versions>
2727
<version>
28-
<num>0.6.3</num>
28+
<num>0.6.8</num>
2929
<compatibility>9.4</compatibility>
3030
</version>
3131
<version>

front/config.form.php

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<?php
2+
3+
include ("../../../inc/includes.php");
4+
// No autoload when plugin is not activated
5+
//require_once('../inc/config.class.php');
6+
7+
$config = new PluginFormvalidationConfig();
8+
if (isset($_REQUEST["update"])) {
9+
$config->check($_REQUEST['id'], UPDATE);
10+
$config->update($_REQUEST);
11+
12+
Html::back();
13+
}
14+
Html::redirect($CFG_GLPI["root_doc"]."/front/config.form.php?forcetab=".
15+
urlencode('PluginFormvalidationConfig$1'));

inc/config.class.php

+49
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
class PluginFormvalidationConfig extends CommonDBTM {
3030

3131
static private $_instance = null;
32+
static $rightname = 'config';
3233

3334
/**
3435
* Singleton for the unique config record
@@ -44,5 +45,53 @@ static function getInstance() {
4445
}
4546
return self::$_instance;
4647
}
48+
49+
50+
51+
function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) {
52+
global $LANG;
53+
54+
if ($item->getType()=='Config') {
55+
return "Formvalidation";
56+
}
57+
return '';
58+
}
59+
60+
61+
static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0) {
62+
63+
if ($item->getType()=='Config') {
64+
self::showConfigForm($item);
65+
}
66+
return true;
67+
}
68+
69+
static function showConfigForm($item) {
70+
global $LANG, $DB;
71+
72+
$config = self::getInstance();
73+
74+
$config->showFormHeader();
75+
76+
echo "<tr class='tab_bg_1'>";
77+
echo "<td colspan=2>".__("css mandatory","formvalidation")."</td><td colspan=2>";
78+
echo "<input type='text' name='css_mandatory' value='".$config->fields['css_mandatory']."'>";
79+
echo "</td></tr>\n";
80+
81+
echo "<tr class='tab_bg_1'>";
82+
echo "<td colspan=2>".__("css error","formvalidation")."</td><td colspan=2>";
83+
echo "<input type='text' name='css_error' value='".$config->fields['css_error']."'>";
84+
echo "</td></tr>\n";
85+
86+
if(!extension_loaded('v8js')) {
87+
echo "<tr class='tab_bg_1'>";
88+
echo "<td colspan=2>".__("nodejs path for massive action validation","formvalidation")."</td><td colspan=2>";
89+
echo "<input type='text' name='js_path' value='".$config->fields['js_path']."'>";
90+
echo "</td></tr>\n";
91+
}
92+
$config->showFormButtons(['candel'=>false]);
93+
94+
return false;
95+
}
4796
}
4897

inc/field.class.php

+3-2
Original file line numberDiff line numberDiff line change
@@ -130,8 +130,9 @@ function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) {
130130
switch ($item->getType()) {
131131
case 'PluginFormvalidationForm' :
132132
if ($_SESSION['glpishow_count_on_tabs']) {
133-
$nb = $dbu->countElementsInTable('glpi_plugin_formvalidation_fields',
134-
"`forms_id` = '".$item->getID()."'");
133+
//$nb = $dbu->countElementsInTable('glpi_plugin_formvalidation_fields',
134+
// "`forms_id` = '".$item->getID()."'");
135+
$nb = $dbu->countElementsInTable('glpi_plugin_formvalidation_fields', ['forms_id' => $item->getID()]);
135136
}
136137
return self::createTabEntry(PluginFormvalidationField::getTypeName(Session::getPluralNumber()), $nb);
137138

inc/form.class.php

+17-13
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,7 @@ static function getDataForPage(PluginFormvalidationPage $page, &$members, &$ids,
169169

170170
// All group members
171171
$res = $DB->request([
172-
'SELECT DISTINCT' => 'glpi_plugin_formvalidation_forms',
172+
'SELECT DISTINCT' => 'glpi_plugin_formvalidation_forms.id',
173173
'FIELDS' => [
174174
'glpi_plugin_formvalidation_forms.id AS linkID',
175175
'glpi_plugin_formvalidation_forms.name',
@@ -227,6 +227,7 @@ static function getDataForPage(PluginFormvalidationPage $page, &$members, &$ids,
227227
static function showForPage(PluginFormvalidationPage $page) {
228228
global $DB, $LANG, $CFG_GLPI;
229229

230+
$config = PluginFormvalidationConfig::getInstance();
230231
$ID = $page->getID();
231232
if (!PluginFormvalidationForm::canView()
232233
|| !$page->can($ID, READ)) {
@@ -316,10 +317,11 @@ static function showForPage(PluginFormvalidationPage $page) {
316317
$header_end .= "<th>".__('CSS selector', 'formvalidation')."</th>";
317318
$header_end .= "<th>".__('Active')."</th>";
318319
$header_end .= "<th>".__('Item creation', 'formvalidation')."</th>";
319-
if (extension_loaded('v8js')) {
320+
//if (extension_loaded('v8js')) {
321+
if(extension_loaded('v8js') || file_exists($config->fields['js_path'])) {
320322
$header_end .= "<th>".__('Massive actions', 'formvalidation')."</th>";
321323
} else {
322-
$header_end .= "<th>".__('Massive actions (Not available as V8JS is not loaded)', 'formvalidation')."</th>";
324+
$header_end .= "<th>".__('Massive actions (Not available as node.js and v8js are not installed/enabled)', 'formvalidation')."</th>";
323325
}
324326
$header_end .= "</tr>";
325327
echo $header_begin.$header_top.$header_end;
@@ -400,7 +402,7 @@ function defineTabs($options = []) {
400402

401403
function showForm ($ID, $options = ['candel'=>false]) {
402404
global $DB, $CFG_GLPI, $LANG;
403-
405+
$config = PluginFormvalidationConfig::getInstance();
404406
if ($ID > 0) {
405407
$this->check($ID, READ);
406408
}
@@ -413,22 +415,22 @@ function showForm ($ID, $options = ['candel'=>false]) {
413415
$this->showFormHeader($options);
414416

415417
echo "<tr class='tab_bg_1'>";
416-
echo "<td>".__("Name")."&nbsp;:</td>";
418+
echo "<td>".__("Name")."</td>";
417419
echo "<td><input type='text' size='50' maxlength=250 name='name' value='".htmlentities($this->fields["name"], ENT_QUOTES)."'></td>";
418-
echo "<td rowspan='5' class='middle'>".__("Comments")."&nbsp;:</td>";
420+
echo "<td rowspan='5' class='middle'>".__("Comments")."</td>";
419421
echo "<td class='center middle' rowspan='5'><textarea cols='40' rows='5' name='comment' >".htmlentities($this->fields["comment"], ENT_QUOTES)."</textarea></td>";
420422
echo "</tr>";
421423

422424
echo "<tr class='tab_bg_1'>";
423-
echo "<td >".__("Active")."&nbsp;:</td>";
425+
echo "<td >".__("Active")."</td>";
424426
echo "<td>";
425427
Html::showCheckbox(['name' => 'is_active',
426428
'checked' => $this->fields["is_active"]
427429
]);
428430
echo "</td></tr>";
429431

430432
echo "<tr class='tab_bg_1'>";
431-
echo "<td >".__("For item creation")."&nbsp;:</td>";
433+
echo "<td >".__("For item creation")."</td>";
432434
echo "<td>";
433435
Html::showCheckbox(['name' => 'is_createitem',
434436
'checked' => $this->fields["is_createitem"]
@@ -441,21 +443,23 @@ function showForm ($ID, $options = ['candel'=>false]) {
441443
echo "</tr>";
442444

443445
echo "<tr class='tab_bg_1'>";
444-
echo "<td >".__("Formula (left empty to default to <b><i>true</i></b>)", 'formvalidation')."&nbsp;:</td>";
446+
echo "<td >".__("Formula (left empty to default to <b><i>true</i></b>)", 'formvalidation')."</td>";
445447
echo "<td><input type='text' size='50' maxlength=1000 name='formula' value='".htmlentities($this->fields["formula"], ENT_QUOTES)."'></td>";
446448
echo "</tr>";
447449

448450
echo "<tr>";
449451
$v8js = extension_loaded('v8js');
450-
if ($v8js) {
451-
echo "<td >".__("Validate massive actions")."&nbsp;:</td>";
452+
$node = file_exists($config->fields['js_path']);
453+
//if ($v8js) {
454+
if($v8js ||$node) {
455+
echo "<td >".__("Validate massive actions")."</td>";
452456
} else {
453-
echo "<td >".__("Massive actions (Not available as V8JS is not loaded)")."&nbsp;:</td>";
457+
echo "<td >".__("Massive actions (Will not work if node.js or v8js are not installed/enabled)")."</td>";
454458
}
455459
echo "<td>";
456460
Html::showCheckbox(['name' => 'use_for_massiveaction',
457461
'checked' => $this->fields["use_for_massiveaction"],
458-
'readonly' => !$v8js
462+
'readonly' => false
459463
]);
460464

461465
echo "</td></tr>";

inc/hook.class.php

+35-100
Original file line numberDiff line numberDiff line change
@@ -24,92 +24,6 @@ static public function plugin_post_item_form_formvalidation($parm) {
2424
}
2525
}
2626

27-
const HELPER_FUNCTIONS = <<<'EOT'
28-
//------------------------------------------
29-
// helper function to verify if a string
30-
// is really a date
31-
// uses the datepicker JQuery plugin
32-
//------------------------------------------
33-
function isValidDate(string) {
34-
try {
35-
if (string.length == 0) {
36-
return false;
37-
}
38-
$.datepicker.parseDate($('.hasDatepicker').datepicker('option', 'dateFormat'), string);
39-
return true;
40-
} catch (e) {
41-
return false;
42-
}
43-
}
44-
45-
//------------------------------------------
46-
// helper function to verify a if a string
47-
// is really a time from 00:00[:00] to 23:59[:59]
48-
//------------------------------------------
49-
function isValidTime(str) {
50-
return /^(?:[0-1]\d|2[0-3]):[0-5]\d(?::[0-5]\d)?$/.test(str);
51-
}
52-
53-
//------------------------------------------
54-
// helper function to verify a if a string
55-
// is really an integer
56-
//------------------------------------------
57-
function isValidInteger(str) {
58-
return /^\d+$/.test(str);
59-
}
60-
61-
//------------------------------------------
62-
// helper function to count words in a given string
63-
// returns quantity of words
64-
//------------------------------------------
65-
function countWords(str) {
66-
return str.split(/\W+/).length;
67-
}
68-
69-
//------------------------------------------
70-
// helper function to verify a if a string
71-
// is really an IPV4 address
72-
// uses the datapicker JQuery plugin
73-
//------------------------------------------
74-
function isValidIPv4(ipaddress) {
75-
return /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(ipaddress) ;
76-
}
77-
78-
79-
//------------------------------------------
80-
// helper function to verify a if a string
81-
// is really an IPV6 address
82-
// uses the datapicker JQuery plugin
83-
//------------------------------------------
84-
function isValidIPv6(ipaddress) {
85-
return /^((?:[0-9A-Fa-f]{1,4}))((?::[0-9A-Fa-f]{1,4}))*::((?:[0-9A-Fa-f]{1,4}))((?::[0-9A-Fa-f]{1,4}))*|((?:[0-9A-Fa-f]{1,4}))((?::[0-9A-Fa-f]{1,4})){7}$/.test(ipaddress);
86-
}
87-
88-
//------------------------------------------
89-
// helper function to verify a if a string
90-
// is really an email address
91-
// will use the input type=email if it exists (HTML5)
92-
// otherwise will use a basic verification.
93-
//------------------------------------------
94-
function isValidEmail(value) {
95-
var input = document.createElement("input");
96-
97-
input.type = "email";
98-
input.value = value;
99-
100-
return typeof input.checkValidity == "function" ? input.checkValidity() : /^\S+@\S+\.\S+$/.test(value);
101-
}
102-
103-
//------------------------------------------
104-
// helper function to verify a if a string
105-
// is really a MAC address
106-
//------------------------------------------
107-
function isValidMacAddress(str) {
108-
return /^[\da-f]{2}([:-])(?:[\da-f]{2}\1){4}[\da-f]{2}$/i.test(str);
109-
}
110-
111-
EOT;
112-
11327
/**
11428
* Summary of plugin_pre_item_update_formvalidation
11529
* @param mixed $parm the object that is going to be updated
@@ -118,6 +32,8 @@ function isValidMacAddress(str) {
11832
static public function plugin_pre_item_update_formvalidation($parm) {
11933
global $DB;
12034

35+
$config = PluginFormvalidationConfig::getInstance();
36+
$path = $config->fields["js_path"];
12137
// to be executed only for massive actions
12238
if (strstr($_SERVER['PHP_SELF'], "/front/massiveaction.php")) {
12339
$ret=[];
@@ -167,19 +83,19 @@ static public function plugin_pre_item_update_formvalidation($parm) {
16783
]
16884
]
16985
];
170-
86+
17187
if (!empty($input)) {
17288
$key = array_keys($input);
17389
$query2['WHERE']['AND']["glpi_plugin_formvalidation_fields.css_selector_value"] = ['LIKE', '%'.$key[0].'%'];
17490
}
17591

17692
foreach ($DB->request( $query2) as $form) {
177-
foreach ($DB->request('glpi_plugin_formvalidation_fields', ['forms_id' => $form['id']]) as $field) {
93+
foreach ($DB->request('glpi_plugin_formvalidation_fields', ['AND' => ['forms_id' => $form['id'], 'is_active' => 1]]) as $field) {
17894
$matches = [];
17995
if (preg_match('/\[(name|id\^)=\\\\{0,1}"(?<name>[a-z_\-0-9]+)\\\\{0,1}"\]/i', $field['css_selector_value'], $matches)) {
180-
$fieldnames[$field['id']]=$matches['name'];
181-
$formulas[$field['id']]=($field['formula'] ? $field['formula'] : '#>0 || #!=""');
182-
$fieldtitles[$field['id']]=$field['name'];
96+
$fieldnames[$field['id']] = trim($matches['name'], "_");
97+
$formulas[$field['id']] = ($field['formula'] ? $field['formula'] : '#>0 || #!=""');
98+
$fieldtitles[$field['id']] = $field['name'];
18399
}
184100
}
185101

@@ -196,21 +112,40 @@ static public function plugin_pre_item_update_formvalidation($parm) {
196112
} else {
197113
$regex = '/#'.$valnum.'\b/i';
198114
}
199-
//$formulaJS[$fieldnum] = preg_replace( $regex, '"'.Toolbox::addslashes_deep( $val ).'"', $formulaJS[$fieldnum] ) ;
200-
$formulaJS[$fieldnum] = preg_replace( $regex, "PHP.val[$valnum]", $formulaJS[$fieldnum] );
115+
$formulaJS[$fieldnum] = preg_replace( $regex, '"'.$values[$valnum].'"', $formulaJS[$fieldnum] );
201116
}
202117
}
203118

204-
$v8 = new V8Js();
205-
$v8->val = $values;
206119
$ret=[];
120+
$helpers = file_get_contents(__DIR__ . "/../js/helpers_function.js.tpl");
121+
$helpers = str_replace('$dateFormat', 'YYYY-MM-DD', $helpers);
122+
$moment = file_get_contents(GLPI_ROOT."/lib/moment.min.js");
207123
foreach ($formulaJS as $index => $formula) {
208124
try {
209-
if (!$v8->executeString(self::HELPER_FUNCTIONS."
210-
exec = $formula;
211-
" ) ) {
212-
Session::addMessageAfterRedirect( __('Mandatory fields or wrong value: ').__($fieldtitles[$index]), true, ERROR );
213-
$ret[]=$fieldnames[$index];
125+
if (extension_loaded('v8js')) {
126+
$v8 = new V8Js();
127+
if (!$v8->executeString($moment."\n".$helpers."\n
128+
exec = $formula;" )
129+
) {
130+
Session::addMessageAfterRedirect( __('Mandatory fields or wrong value: ').__($fieldtitles[$index]), true, ERROR );
131+
$ret[] = $fieldnames[$index];
132+
}
133+
} else {
134+
if (file_exists($path)) {
135+
$tmpfile = tempnam(GLPI_ROOT.'/files/_tmp', 'tmp');
136+
$handle = fopen($tmpfile, "w");
137+
fwrite($handle, "var moment = require('../../lib/moment.min.js');\n".$helpers."\nif($formula){console.log(1);}else{console.log(0);}");
138+
fclose($handle);
139+
$valid = exec("\"$path\" \"$tmpfile\"");
140+
if ($valid == 0 || is_null($valid)) {
141+
Session::addMessageAfterRedirect( __('Mandatory fields or wrong value: ').__($fieldtitles[$index]), true, ERROR );
142+
$ret[] = $fieldnames[$index];
143+
}
144+
unlink($tmpfile);
145+
} else {
146+
Session::addMessageAfterRedirect( __('The field was not updated because node.js and v8js are not installed/enabled. Contact your system administrator'), true, ERROR );
147+
$ret[] = $fieldnames[$index];
148+
}
214149
}
215150
} catch (Exception $ex) {
216151
Session::addMessageAfterRedirect( __('Error: ').__($ex->message), false, ERROR );

0 commit comments

Comments
 (0)