Headers already sent... where? [duplicate] - php

This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 9 years ago.
Does anyone see how headers could be sent in this script? I am using this script to validate a form. As a result it is causing headers to be sent so when I try to direct a user after implementing this script it causes the normal "Warning: Cannot modify header information - headers already sent" message. Here is the script:
<?php
class ValidatorObj
{
var $variable_name;
var $validator_string;
var $error_string;
}
/**
* Base class for custom validation objects
**/
class CustomValidator
{
function DoValidate(&$formars,&$error_hash)
{
return true;
}
}
/** Default error messages*/
define("E_VAL_REQUIRED_VALUE","Please enter the value for %s");
define("E_VAL_MAXLEN_EXCEEDED","Maximum length exceeded for %s.");
define("E_VAL_MINLEN_CHECK_FAILED","Please enter input with length more than %d for %s");
define("E_VAL_ALNUM_CHECK_FAILED","Please provide an alpha-numeric input for %s");
define("E_VAL_ALNUM_S_CHECK_FAILED","Please provide an alpha-numeric input for %s");
define("E_VAL_NUM_CHECK_FAILED","Please provide numeric input for %s");
define("E_VAL_ALPHA_CHECK_FAILED","Please provide alphabetic input for %s");
define("E_VAL_ALPHA_S_CHECK_FAILED","Please provide alphabetic input for %s");
define("E_VAL_EMAIL_CHECK_FAILED","Please provide a valida email address");
define("E_VAL_LESSTHAN_CHECK_FAILED","Enter a value less than %f for %s");
define("E_VAL_GREATERTHAN_CHECK_FAILED","Enter a value greater than %f for %s");
define("E_VAL_REGEXP_CHECK_FAILED","Please provide a valid input for %s");
define("E_VAL_DONTSEL_CHECK_FAILED","Wrong option selected for %s");
define("E_VAL_SELMIN_CHECK_FAILED","Please select minimum %d options for %s");
define("E_VAL_SELONE_CHECK_FAILED","Please select an option for %s");
define("E_VAL_EQELMNT_CHECK_FAILED","Value of %s should be same as that of %s");
define("E_VAL_NEELMNT_CHECK_FAILED","Value of %s should not be same as that of %s");
class FormValidator
{
var $validator_array;
var $error_hash;
var $custom_validators;
function FormValidator()
{
$this->validator_array = array();
$this->error_hash = array();
$this->custom_validators=array();
}
function AddCustomValidator(&$customv)
{
array_push($this->custom_validators,$customv);
}
function addValidation($variable,$validator,$error)
{
$validator_obj = new ValidatorObj();
$validator_obj->variable_name = $variable;
$validator_obj->validator_string = $validator;
$validator_obj->error_string = $error;
array_push($this->validator_array,$validator_obj);
}
function GetErrors()
{
return $this->error_hash;
}
function ValidateForm()
{
$bret = true;
$error_string="";
$error_to_display = "";
if(strcmp($_SERVER['REQUEST_METHOD'],'POST')==0)
{
$form_variables = $_POST;
}
else
{
$form_variables = $_GET;
}
$vcount = count($this->validator_array);
foreach($this->validator_array as $val_obj)
{
if(!$this->ValidateObject($val_obj,$form_variables,$error_string))
{
$bret = false;
$this->error_hash[$val_obj->variable_name] = $error_string;
}
}
if(true == $bret && count($this->custom_validators) > 0)
{
foreach( $this->custom_validators as $custom_val)
{
if(false == $custom_val->DoValidate($form_variables,$this->error_hash))
{
$bret = false;
}
}
}
return $bret;
}
function ValidateObject($validatorobj,$formvariables,&$error_string)
{
$bret = true;
$splitted = explode("=",$validatorobj->validator_string);
$command = $splitted[0];
$command_value = '';
if(isset($splitted[1]) && strlen($splitted[1])>0)
{
$command_value = $splitted[1];
}
$default_error_message="";
$input_value ="";
if(isset($formvariables[$validatorobj->variable_name]))
{
$input_value = $formvariables[$validatorobj->variable_name];
}
$bret = $this->ValidateCommand($command,$command_value,$input_value,
$default_error_message,
$validatorobj->variable_name,
$formvariables);
if(false == $bret)
{
if(isset($validatorobj->error_string) &&
strlen($validatorobj->error_string)>0)
{
$error_string = $validatorobj->error_string;
}
else
{
$error_string = $default_error_message;
}
}//if
return $bret;
}
function validate_req($input_value, &$default_error_message,$variable_name)
{
$bret = true;
if(!isset($input_value) ||
strlen($input_value) <=0)
{
$bret=false;
$default_error_message = sprintf(E_VAL_REQUIRED_VALUE,$variable_name);
}
return $bret;
}
function validate_maxlen($input_value,$max_len,$variable_name,&$default_error_message)
{
$bret = true;
if(isset($input_value) )
{
$input_length = strlen($input_value);
if($input_length > $max_len)
{
$bret=false;
$default_error_message = sprintf(E_VAL_MAXLEN_EXCEEDED,$variable_name);
}
}
return $bret;
}
function validate_minlen($input_value,$min_len,$variable_name,&$default_error_message)
{
$bret = true;
if(isset($input_value) )
{
$input_length = strlen($input_value);
if($input_length < $min_len)
{
$bret=false;
$default_error_message = sprintf(E_VAL_MINLEN_CHECK_FAILED,$min_len,$variable_name);
}
}
return $bret;
}
function test_datatype($input_value,$reg_exp)
{
if(ereg($reg_exp,$input_value))
{
return false;
}
return true;
}
function validate_email($email)
{
return eregi("^[_\.0-9a-zA-Z-]+#([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$", $email);
}
function validate_for_numeric_input($input_value,&$validation_success)
{
$more_validations=true;
$validation_success = true;
if(strlen($input_value)>0)
{
if(false == is_numeric($input_value))
{
$validation_success = false;
$more_validations=false;
}
}
else
{
$more_validations=false;
}
return $more_validations;
}
function validate_lessthan($command_value,$input_value,
$variable_name,&$default_error_message)
{
$bret = true;
if(false == $this->validate_for_numeric_input($input_value,
$bret))
{
return $bret;
}
if($bret)
{
$lessthan = doubleval($command_value);
$float_inputval = doubleval($input_value);
if($float_inputval >= $lessthan)
{
$default_error_message = sprintf(E_VAL_LESSTHAN_CHECK_FAILED,
$lessthan,
$variable_name);
$bret = false;
}//if
}
return $bret ;
}
function validate_greaterthan($command_value,$input_value,$variable_name,&$default_error_message)
{
$bret = true;
if(false == $this->validate_for_numeric_input($input_value,$bret))
{
return $bret;
}
if($bret)
{
$greaterthan = doubleval($command_value);
$float_inputval = doubleval($input_value);
if($float_inputval <= $greaterthan)
{
$default_error_message = sprintf(E_VAL_GREATERTHAN_CHECK_FAILED,
$greaterthan,
$variable_name);
$bret = false;
}//if
}
return $bret ;
}
function validate_select($input_value,$command_value,&$default_error_message,$variable_name)
{
$bret=false;
if(is_array($input_value))
{
foreach($input_value as $value)
{
if($value == $command_value)
{
$bret=true;
break;
}
}
}
else
{
if($command_value == $input_value)
{
$bret=true;
}
}
if(false == $bret)
{
$default_error_message = sprintf(E_VAL_SHOULD_SEL_CHECK_FAILED,
$command_value,$variable_name);
}
return $bret;
}
function validate_dontselect($input_value,$command_value,&$default_error_message,$variable_name)
{
$bret=true;
if(is_array($input_value))
{
foreach($input_value as $value)
{
if($value == $command_value)
{
$bret=false;
$default_error_message = sprintf(E_VAL_DONTSEL_CHECK_FAILED,$variable_name);
break;
}
}
}
else
{
if($command_value == $input_value)
{
$bret=false;
$default_error_message = sprintf(E_VAL_DONTSEL_CHECK_FAILED,$variable_name);
}
}
return $bret;
}
function ValidateCommand($command,$command_value,$input_value,&$default_error_message,$variable_name,$formvariables)
{
$bret=true;
switch($command)
{
case 'req':
{
$bret = $this->validate_req($input_value, $default_error_message,$variable_name);
break;
}
case 'maxlen':
{
$max_len = intval($command_value);
$bret = $this->validate_maxlen($input_value,$max_len,$variable_name,
$default_error_message);
break;
}
case 'minlen':
{
$min_len = intval($command_value);
$bret = $this->validate_minlen($input_value,$min_len,$variable_name,
$default_error_message);
break;
}
case 'alnum':
{
$bret= $this->test_datatype($input_value,"[^A-Za-z0-9]");
if(false == $bret)
{
$default_error_message = sprintf(E_VAL_ALNUM_CHECK_FAILED,$variable_name);
}
break;
}
case 'alnum_s':
{
$bret= $this->test_datatype($input_value,"[^A-Za-z0-9 ]");
if(false == $bret)
{
$default_error_message = sprintf(E_VAL_ALNUM_S_CHECK_FAILED,$variable_name);
}
break;
}
case 'num':
case 'numeric':
{
$bret= $this->test_datatype($input_value,"[^0-9]");
if(false == $bret)
{
$default_error_message = sprintf(E_VAL_NUM_CHECK_FAILED,$variable_name);
}
break;
}
case 'alpha':
{
$bret= $this->test_datatype($input_value,"[^A-Za-z]");
if(false == $bret)
{
$default_error_message = sprintf(E_VAL_ALPHA_CHECK_FAILED,$variable_name);
}
break;
}
case 'alpha_s':
{
$bret= $this->test_datatype($input_value,"[^A-Za-z ]");
if(false == $bret)
{
$default_error_message = sprintf(E_VAL_ALPHA_S_CHECK_FAILED,$variable_name);
}
break;
}
case 'email':
{
if(isset($input_value) && strlen($input_value)>0)
{
$bret= $this->validate_email($input_value);
if(false == $bret)
{
$default_error_message = E_VAL_EMAIL_CHECK_FAILED;
}
}
break;
}
case "lt":
case "lessthan":
{
$bret = $this->validate_lessthan($command_value,
$input_value,
$variable_name,
$default_error_message);
break;
}
case "gt":
case "greaterthan":
{
$bret = $this->validate_greaterthan($command_value,
$input_value,
$variable_name,
$default_error_message);
break;
}
case "regexp":
{
if(isset($input_value) && strlen($input_value)>0)
{
if(!preg_match("$command_value",$input_value))
{
$bret=false;
$default_error_message = sprintf(E_VAL_REGEXP_CHECK_FAILED,$variable_name);
}
}
break;
}
case "dontselect":
case "dontselectchk":
case "dontselectradio":
{
$bret = $this->validate_dontselect($input_value,
$command_value,
$default_error_message,
$variable_name);
break;
}//case
case "shouldselchk":
case "selectradio":
{
$bret = $this->validate_select($input_value,
$command_value,
$default_error_message,
$variable_name);
break;
}//case
case "selmin":
{
$min_count = intval($command_value);
if(isset($input_value))
{
if($min_count > 1)
{
$bret = (count($input_value) >= $min_count )?true:false;
}
else
{
$bret = true;
}
}
else
{
$bret= false;
$default_error_message = sprintf(E_VAL_SELMIN_CHECK_FAILED,$min_count,$variable_name);
}
break;
}//case
case "selone":
{
if(false == isset($input_value)||
strlen($input_value)<=0)
{
$bret= false;
$default_error_message = sprintf(E_VAL_SELONE_CHECK_FAILED,$variable_name);
}
break;
}
case "eqelmnt":
{
if(isset($formvariables[$command_value]) &&
strcmp($input_value,$formvariables[$command_value])==0 )
{
$bret=true;
}
else
{
$bret= false;
$default_error_message = sprintf(E_VAL_EQELMNT_CHECK_FAILED,$variable_name,$command_value);
}
break;
}
case "neelmnt":
{
if(isset($formvariables[$command_value]) &&
strcmp($input_value,$formvariables[$command_value]) !=0 )
{
$bret=true;
}
else
{
$bret= false;
$default_error_message = sprintf(E_VAL_NEELMNT_CHECK_FAILED,$variable_name,$command_value);
}
break;
}
}//switch
return $bret;
}//validdate command
}?>

after .the }?>
if you select all (Ctrl+A) you will see the white space proceeding the ?>

There is likely whitespace after the closing ?> tag. It's become quite common practice to leave off the ending ?> tag to prevent this exactly issue. But that can only be done in files that contain only code in classes, no procedural code.

To add on to RobertPitt, if your file is solely PHP only, add the <?php at the start, and remove the ?> to prevent careless whitespaces at the back.

Related

PHP Form Validation - Deprecated Function eregi()

I've just raised a separate question on a problem with an enquiry form that had a deprecated eregi PHP function. Unfortunately, there's another file I missed that validates the form which is riddled with them :(
Here's the code below:
/* ERRORS */
function error($str) // private
{
$this->error = true;
$this->error_string .= $str;
}
/* VALIDATE FIELD AGAINST TYPE */
function checkit($value, $type) // private
{
$length = "";
if (eregi("^MIN[0-9]+$", $type)) {
$tmp = explode(":", $type);
$length = $tmp[1];
$type = "MINLENGTH";
}
if (eregi("^MAX[0-9]+$", $type)) {
$tmp = explode(":", $type);
$length = $tmp[1];
$type = "MAXLENGTH";
}
switch ($type) {
case "NOT_EMPTY":
$this->error_tmp = "string cannot be empty";
return $this->not_empty($value);
break;
case "MINLENGTH":
if (strlen($value) < $length) {
$this->error_tmp = "string to short";
return false;
} else {
return true;
}
break;
case "MAXLENGTH":
if (strlen($value) > $length) {
$this->error_tmp = "string to long";
return false;
} else {
return true;
}
break;
case "ALPHA":
$exp = "^[a-z]+$";
if ($this->not_empty($value) && eregi($exp, $value)) {
return true;
} else {
$this->error_tmp = "string not alpha";
return false;
}
break;
case "ALPHASPACE":
$exp = "^[a-z ]+$";
if ($this->not_empty($value) && eregi($exp, $value)) {
return true;
} else {
$this->error_tmp = "string not alphaspace";
return false;
}
break;
case "ALPHANUM":
$exp = "^[a-z0-9]+$";
if ($this->not_empty($value) && eregi($exp, $value)) {
return true;
} else {
$this->error_tmp = "string not alphanum";
return false;
}
break;
case "ALPHANUMSPACE":
$exp = "^[a-z0-9 ]+$";
if ($this->not_empty($value) && eregi($exp, $value)) {
return true;
} else {
$this->error_tmp = "string not alphanumspace";
return false;
}
break;
case "NUMERIC":
$exp = "^[0-9]+$";
if ($this->not_empty($value) && eregi($exp, $value)) {
return true;
} else {
$this->error_tmp = "string not numeric";
return false;
}
break;
case "NUMERICPLUS":
$exp = "^[0-9+-.]+$";
if ($this->not_empty($value) && eregi($exp, $value)) {
return true;
} else {
$this->error_tmp = "string not numericplus";
return false;
}
break;
case "EMAIL":
$exp = "^[A-Z0-9._%-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$";
if ($this->not_empty($value) && eregi($exp, $value)) {
return true;
} else {
$this->error_tmp = "not a valid email";
return false;
}
break;
case "YYYYMMDD":
$exp = "^(19|20)[0-9][0-9][- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$";
if ($this->not_empty($value) && eregi($exp, $value)) {
return true;
} else {
$this->error_tmp = "string not YYYYMMDD";
return false;
}
break;
case "DDMMYYYY":
$exp = "^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)[0-9][0-9]$";
if ($this->not_empty($value) && eregi($exp, $value)) {
return true;
} else {
$this->error_tmp = "string not DDMMYYYY";
return false;
}
break;
case "MMDDYYYY":
$exp = "^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)[0-9][0-9]$";
if ($this->not_empty($value) && eregi($exp, $value)) {
return true;
} else {
$this->error_tmp = "string not MMDDYYYY";
return false;
}
break;
default:
if ($this->not_empty($value) && $this->regex($type, $value)) {
return true;
} else {
$this->error_tmp = "string not valid";
return false;
}
}
}
/* NOT_EMPTY */
function not_empty($value) // private
{
if (trim($value) == "") {
return false;
} else {
return true;
}
}
/* REGULAR EXPRESSION */
function regex($regex, $value) // private
{
$the_regex = 'ereg("' . $regex . '", "' . $value . '")';
$the_code = '<?php if(' . $the_regex . ') { return true; } else { return false; } ?>';
if (!eval('?>' . $the_code . '<?php ')) {
return false;
} else {
return true;
}
}
}
Are there too many to change?
I hope someone can help?
Thanks in advance, kind regards
Brian
Regex has the "case-insensitive" way to match a string. If you put the letter "i" at the end of the regular expression, the function preg_match() will match the string even if you are searching a lowercase sentence in an uppercase string.
In the case ALPHA, you can use this regular expression:
$exp = "/^[a-z]+$/i";
instead of
$exp = "^[a-z]+$";
Using this, you can change the PHP functions from eregi($exp, $value) to preg_match($exp, $value), which will return TRUE if there are matches.
You can read the related documentation of preg_match() function here: https://www.php.net/manual/en/function.preg-match.php
Andrea

Illegal string offset 'formId' in repeater gravityform

PLease Help me,
I have this errors
Warning: Illegal string offset 'formId' in
C:\xampp\htdocs\wp-content\plugins\repeater-add-on-for-gravity-forms\class-gf-field-repeater.php
on line 287
Warning: Illegal string offset 'children' in
C:\xampp\htdocs\wp-content\plugins\repeater-add-on-for-gravity-forms\class-gf-field-repeater.php
on line 291
...
if (empty($value)) {
$value['formId'] = $form_id;
if (!empty($repeater_start)) { $value['start'] = $repeater_start; }
if (!empty($repeater_min)) { $value['min'] = $repeater_min; }
if (!empty($repeater_max)) { $value['max'] = $repeater_max; }
if (!empty($repeater_children)) { $value['children'] = $repeater_children; }
$value = json_encode($value);
}
...
Hi I solved adding $value = array() in line 287.
if (empty($value)) {
$value = array();
$value['formId'] = $form_id;
if (!empty($repeater_start)) { $value['start'] = $repeater_start; }
if (!empty($repeater_min)) { $value['min'] = $repeater_min; }
if (!empty($repeater_max)) { $value['max'] = $repeater_max; }
if (!empty($repeater_children)) { $value['children'] = $repeater_children; }
$value = json_encode($value);
}
That's work for me, I hope it could help you.
<?php
class GF_Field_Repeater extends GF_Field {
public $type = 'repeater';
public static function init_admin() {
$admin_page = rgget('page');
if ($admin_page == 'gf_edit_forms' && !empty($_GET['id'])) {
add_action('gform_field_standard_settings' , array('GF_Field_Repeater', 'gform_standard_settings'), 10, 2);
add_action('gform_field_appearance_settings' , array('GF_Field_Repeater', 'gform_appearance_settings'), 10, 2);
add_action('gform_editor_js_set_default_values', array('GF_Field_Repeater', 'gform_set_defaults'));
add_action('gform_editor_js', array('GF_Field_Repeater', 'gform_editor'));
add_filter('gform_tooltips', array('GF_Field_Repeater', 'gform_tooltips'));
}
if ($admin_page == 'gf_entries') {
add_filter('gform_form_post_get_meta', array('GF_Field_Repeater', 'gform_hide_children'));
}
}
public static function init_frontend() {
add_action('gform_form_args', array('GF_Field_Repeater', 'gform_disable_ajax'));
add_action('gform_enqueue_scripts', array('GF_Field_Repeater', 'gform_enqueue_scripts'), 10, 2);
add_filter('gform_pre_render', array('GF_Field_Repeater', 'gform_unhide_children_validation'));
add_filter('gform_pre_validation', array('GF_Field_Repeater', 'gform_bypass_children_validation'));
}
public static function gform_enqueue_scripts($form, $is_ajax) {
if (!empty($form)) {
if (GF_Field_Repeater::get_field_index($form) !== false) {
wp_enqueue_script('gforms_repeater_postcapture_js', plugins_url('js/jquery.postcapture.min.js', __FILE__), array('jquery'), '0.0.1');
wp_enqueue_script('gforms_repeater_js', plugins_url('js/gf-repeater.min.js', __FILE__), array('jquery'), GF_REPEATER_VERSION);
wp_enqueue_style('gforms_repeater_css', plugins_url('css/gf-repeater.css', __FILE__), array(), GF_REPEATER_VERSION);
}
}
}
public function get_form_editor_field_title() {
return 'Repeater';
}
public function get_form_editor_field_settings() {
return array(
'admin_label_setting',
'css_class_setting',
'description_setting',
'error_message_setting',
'label_setting',
'prepopulate_field_setting'
);
}
public static function gform_set_defaults() {
echo "
case \"repeater\" :
field.label = \"Repeater\";
break;
";
}
public static function gform_standard_settings($position, $form_id) {
if ($position == 1600) {
echo "<li class=\"repeater_settings field_setting\">
<label for=\"field_repeater_start\">Start ";
gform_tooltip('form_field_repeater_start');
echo " </label>
<input type=\"number\" id=\"field_repeater_start\" min=\"1\" value=\"1\" onchange=\"SetFieldProperty('start', this.value);\">
</li>";
echo "<li class=\"repeater_settings field_setting\">
<label for=\"field_repeater_min\">Min ";
gform_tooltip('form_field_repeater_min');
echo " </label>
<input type=\"number\" id=\"field_repeater_min\" min=\"1\" value=\"1\" onchange=\"SetFieldProperty('min', this.value);\">
</li>";
echo "<li class=\"repeater_settings field_setting\">
<label for=\"field_repeater_max\">Max ";
gform_tooltip('form_field_repeater_max');
echo " </label>
<input type=\"number\" id=\"field_repeater_max\" min=\"1\" onchange=\"SetFieldProperty('max', this.value);\">
</li>";
}
}
public static function gform_appearance_settings($position, $form_id) {
if ($position == 400) {
echo "<li class=\"repeater_settings field_setting\">
<input type=\"checkbox\" id=\"field_repeater_hideLabel\" onchange=\"SetFieldProperty('hideLabel', this.checked);\">
<label for=\"field_repeater_hideLabel\" class=\"inline\">Hide Label & Description ";
gform_tooltip('form_field_repeater_hideLabel');
echo " </label>
</li>";
}
}
public static function gform_editor() {
echo "<script type=\"text/javascript\">
fieldSettings['repeater'] += ', .repeater_settings';
jQuery(document).bind('gform_load_field_settings', function(event, field, form){
jQuery('#field_repeater_start').val(field['start']);
jQuery('#field_repeater_min').val(field['min']);
jQuery('#field_repeater_max').val(field['max']);
jQuery('#field_repeater_hideLabel').prop('checked', field['hideLabel']);
});
</script>";
}
public static function gform_tooltips($tooltips) {
$tooltips['form_field_repeater_start'] = "The number of times the repeater will be repeated when the form is rendered. Leaving this field blank or setting it to a number higher than the maximum number is the same as setting it to 1.";
$tooltips['form_field_repeater_min'] = "The minimum number of times the repeater is allowed to be repeated. Leaving this field blank or setting it to a number higher than the maximum field is the same as setting it to 1.";
$tooltips['form_field_repeater_max'] = "The maximum number of times the repeater is allowed to be repeated. Leaving this field blank or setting it to a number lower than the minimum field is the same as setting it to unlimited.";
$tooltips['form_field_repeater_hideLabel'] = "If this is checked, the repeater label and description will not be shown to users on the form.";
return $tooltips;
}
function validate($value, $form) {
$repeater_required = $this->repeaterRequiredChildren;
if (!empty($repeater_required)) {
$dataArray = json_decode($value, true);
foreach ($form['fields'] as $key=>$value) {
$fieldKeys[$value['id']] = $key;
if (is_array($value['inputs'])) {
foreach ($value['inputs'] as $inputKey=>$inputValue) {
$inputKeys[$value['id']][$inputValue['id']] = $inputKey;
}
}
}
if ($dataArray['repeatCount'] < $this->min) {
$this->failed_validation = true;
$this->validation_message = "A minimum number of ".$this->min." is required.";
return;
}
if ($this->max && $dataArray['repeatCount'] > $this->max) {
$this->failed_validation = true;
$this->validation_message = "A maximum number of ".$this->max." is allowed.";
return;
}
for ($i = 1; $i < $dataArray['repeatCount'] + 1; $i++) {
foreach ($dataArray['children'] as $field_id=>$field) {
$inputNames = $field['inputs'];
$repeatSkips = $field['conditionalLogic']['skip'];
if (!is_array($inputNames)) { continue; }
if (is_array($repeatSkips)) {
if (in_array($i, $repeatSkips) || in_array('all', $repeatSkips)) { continue; }
}
foreach ($inputNames as $inputName) {
if (is_array($inputName)) { $inputName = reset($inputName); }
if (substr($inputName, -2) == '[]') {
$getInputName = substr($inputName, 0, strlen($inputName) - 2).'-'.$dataArray['repeaterId'].'-'.$i;
} else {
$getInputName = $inputName.'-'.$dataArray['repeaterId'].'-'.$i;
}
$getInputName = str_replace('.', '_', strval($getInputName));
$getInputData = rgpost($getInputName);
$getInputIdNum = preg_split("/(_|-)/", $getInputName);
if (in_array($getInputIdNum[1], $repeater_required)) {
$fieldKey = $fieldKeys[$getInputIdNum[1]];
$fieldType = $form['fields'][$fieldKey]['type'];
$failedValidation = false;
switch($fieldType) {
case 'name':
$requiredIDs = array(3, 6);
if (in_array($getInputIdNum[2], $requiredIDs) && empty($getInputData)) { $failedValidation = true; }
break;
case 'address':
$skipIDs = array(2);
if (!in_array($getInputIdNum[2], $skipIDs) && empty($getInputData)) { $failedValidation = true; }
break;
default:
if (empty($getInputData)) { $failedValidation = true; }
}
if ($failedValidation) {
$this->failed_validation = true;
if ($this->errorMessage) { $this->validation_message = $this->errorMessage; } else { $this->validation_message = "A required field was left blank."; }
return;
}
}
}
}
}
}
}
public function get_field_content($value, $force_frontend_label, $form) {
if (is_admin()) {
$admin_buttons = $this->get_admin_buttons();
$field_content = "{$admin_buttons}
<div class=\"gf-pagebreak-first gf-pagebreak-container gf-repeater gf-repeater-start\">
<div class=\"gf-pagebreak-text-before\">begin repeater</div>
<div class=\"gf-pagebreak-text-main\"><span>REPEATER</span></div>
<div class=\"gf-pagebreak-text-after\">top of repeater</div>
</div>";
} else {
$field_label = $this->get_field_label($force_frontend_label, $value);
$description = $this->get_description($this->description, 'gsection_description gf_repeater_description');
$hide_label = $this->hideLabel;
$validation_message = ( $this->failed_validation && ! empty( $this->validation_message ) ) ? sprintf( "<div class='gfield_description validation_message'>%s</div>", $this->validation_message ) : '';
if (!empty($field_label)) { $field_label = "<h2 class='gf_repeater_title'>{$field_label}</h2>"; } else { $field_label = ''; }
if ($hide_label) { $field_label = ''; $description = ''; }
$field_content = "<div class=\"ginput_container ginput_container_repeater\">{$field_label}{FIELD}</div>{$description}{$validation_message}";
}
return $field_content;
}
public function get_field_input($form, $value = '', $entry = null) {
if (is_admin()) {
return '';
} else {
$form_id = $form['id'];
$is_entry_detail = $this->is_entry_detail();
$is_form_editor = $this->is_form_editor();
$id = (int) $this->id;
$field_id = $is_entry_detail || $is_form_editor || $form_id == 0 ? "input_$id" : 'input_' . $form_id . "_$id";
$tabindex = $this->get_tabindex();
$repeater_parem = $this->inputName;
$repeater_start = $this->start;
$repeater_min = $this->min;
$repeater_max = $this->max;
$repeater_required = $this->repeaterRequiredChildren;
$repeater_children = $this->repeaterChildren;
if (!empty($repeater_parem)) {
$repeater_parem_value = GFFormsModel::get_parameter_value($repeater_parem, $value, $this);
if (!empty($repeater_parem_value)) { $repeater_start = $repeater_parem_value; }
}
if (!empty($repeater_children)) {
$repeater_children_info = array();
$repeater_parems = GF_Field_Repeater::get_children_parem_values($form, $repeater_children);
foreach($repeater_children as $repeater_child) {
$repeater_children_info[$repeater_child] = array();
$repeater_child_field_index = GF_Field_Repeater::get_field_index($form, 'id', $repeater_child);
if (!empty($repeater_required)) {
if (in_array($repeater_child, $repeater_required)) {
$repeater_children_info[$repeater_child]['required'] = true;
}
}
if (!empty($repeater_parems)) {
if (array_key_exists($repeater_child, $repeater_parems)) {
$repeater_children_info[$repeater_child]['prePopulate'] = $repeater_parems[$repeater_child];
}
}
if ($repeater_child_field_index !== false) {
if ($form['fields'][$repeater_child_field_index]['inputMask']) {
$repeater_children_info[$repeater_child]['inputMask'] = $form['fields'][$repeater_child_field_index]['inputMaskValue'];
} elseif ($form['fields'][$repeater_child_field_index]['type'] == 'phone' && $form['fields'][$repeater_child_field_index]['phoneFormat'] = 'standard') {
$repeater_children_info[$repeater_child]['inputMask'] = "(999) 999-9999";
}
if ($form['fields'][$repeater_child_field_index]['conditionalLogic']) {
$repeater_children_info[$repeater_child]['conditionalLogic'] = $form['fields'][$repeater_child_field_index]['conditionalLogic'];
}
}
}
$repeater_children = $repeater_children_info;
}
if (empty($value)) {
$value['formId'] = $form_id;
if (!empty($repeater_start)) { $value['start'] = $repeater_start; }
if (!empty($repeater_min)) { $value['min'] = $repeater_min; }
if (!empty($repeater_max)) { $value['max'] = $repeater_max; }
if (!empty($repeater_children)) { $value['children'] = $repeater_children; }
$value = json_encode($value);
}
return sprintf("<input name='input_%d' id='%s' type='hidden' class='gform_repeater' value='%s' %s />", $id, $field_id, $value, $tabindex);
}
}
public function get_value_save_entry($value, $form, $input_name, $lead_id, $lead) {
$dataArray = json_decode($value, true);
$value = Array();
for ($i = 1; $i < $dataArray['repeatCount'] + 1; $i++) {
foreach ($dataArray['children'] as $field_id=>$field) {
$inputData = Array();
if (array_key_exists('inputs', $field)) {
$inputNames = $field['inputs'];
$repeatSkips = $field['conditionalLogic']['skip'];
if (is_array($repeatSkips)) {
if (in_array($i, $repeatSkips) || in_array('all', $repeatSkips)) { continue; }
}
if (is_array($inputNames)) {
foreach ($inputNames as $inputName) {
if (substr($inputName, -2) == '[]') {
$getInputName = substr($inputName, 0, strlen($inputName) - 2).'-'.$dataArray['repeaterId'].'-'.$i;
} else {
$getInputName = $inputName.'-'.$dataArray['repeaterId'].'-'.$i;
}
$getInputData = rgpost(str_replace('.', '_', strval($getInputName)));
if (!empty($getInputData)) {
if (is_array($getInputData)) {
foreach ($getInputData as $theInputData) {
$inputData[] = $theInputData;
}
} else {
$inputData[] = $getInputData;
}
}
}
}
} else {
if (GF_Field_Repeater::get_field_type($form, $field_id) == 'section') { $inputData = '[gfRepeater-section]'; }
}
$childValue[$field_id] = $inputData;
}
$value[$i] = $childValue;
}
return maybe_serialize($value);
}
public function get_value_entry_list($value, $entry, $field_id, $columns, $form) {
if (empty($value)) {
return '';
} else {
$dataArray = GFFormsModel::unserialize($value);
$arrayCount = count($dataArray);
if ($arrayCount > 1) { $returnText = $arrayCount.' entries'; } else { $returnText = $arrayCount.' entry'; }
return $returnText;
}
}
public function get_value_entry_detail($value, $currency = '', $use_text = false, $format = 'html', $media = 'screen') {
if (empty($value)) {
return '';
} else {
$dataArray = GFFormsModel::unserialize($value);
$arrayCount = count($dataArray);
$output = "\n";
$count = 0;
$repeatCount = 0;
$display_empty_fields = rgget('gf_display_empty_fields', $_COOKIE);
$form_id = $this->formId;
$get_form = GFFormsModel::get_form_meta_by_id($form_id);
$form = $get_form[0];
foreach ($dataArray as $key=>$value) {
$repeatCount++;
$tableContents = '';
if (!empty($value) && !is_array($value)) {
$save_value = $value;
unset($value);
$value[0] = $save_value;
}
foreach ($value as $childKey=>$childValue) {
$count++;
$childValueOutput = '';
if (empty($display_empty_fields) && count($childValue) == 0) { continue; }
if (is_numeric($childKey)) {
$field_index = GF_Field_Repeater::get_field_index($form, 'id', $childKey);
if ($field_index === false) { continue; }
$entry_title = $form['fields'][$field_index]['label'];
} else {
$entry_title = $childKey;
}
$entry_title = str_replace('[gfRepeater-count]', $repeatCount, $entry_title);
if ($format == 'html') {
if ($childValue == '[gfRepeater-section]') {
if ($media == 'email') {
$tableStyling = ' style="font-size:14px;font-weight:bold;background-color:#eee;border-bottom:1px solid #dfdfdf;padding:7px 7px"';
} else {
$tableStyling = ' class="entry-view-section-break"';
}
} else {
if ($media == 'email') {
$tableStyling = ' style="background-color:#EAF2FA;font-family:sans-serif;font-size:12px;font-weight:bold"';
} else {
$tableStyling = ' class="entry-view-field-name"';
}
}
$tableContents .= "<tr>\n<td colspan=\"2\"".$tableStyling.">".$entry_title."</td>\n</tr>\n";
} else {
$tableContents .= $entry_title.": ";
}
if (is_array($childValue)) {
if (count($childValue) == 1) {
$childValueOutput = $childValue[0];
} elseif (count($childValue) > 1) {
if ($format == 'html') {
if ($media == 'email') {
$childValueOutput = "<ul style=\"list-style:none;margin:0;padding:0;\">\n";
} else {
$childValueOutput = "<ul>\n";
}
}
foreach ($childValue as $childValueData) {
if ($format == 'html') {
$childValueOutput .= "<li>".$childValueData."</li>";
} else {
$childValueOutput .= $childValueData."\n";
}
}
if ($format == 'html') { $childValueOutput .= "</ul>\n"; }
}
if ($media == 'email') { $tableStyling = ''; } else { $tableStyling = ' class=\"entry-view-field-value\"'; }
if ($format == 'html') {
$tableContents .= "<tr>\n<td colspan=\"2\"".$tableStyling.">".$childValueOutput."</td>\n</tr>\n";
} else {
$tableContents .= $childValueOutput."\n";
}
}
}
if (!empty($tableContents)) {
if ($format == 'html') {
if ($media == 'email') { $tableStyling = ' width="100%" border="0" cellpadding="5" bgcolor="#FFFFFF"'; } else { $tableStyling = ' class="widefat fixed entry-detail-view"'; }
$output .= "<table cellspacing=\"0\"".$tableStyling.">\n";
$output .= $tableContents;
$output .= "</table>\n";
} else {
$output .= $tableContents."\n";
}
}
}
}
if ($count !== 0) {
if ($format == 'text') { $output = rtrim($output); }
return $output;
} else { return ''; }
}
public function get_value_merge_tag($value, $input_id, $entry, $form, $modifier, $raw_value, $url_encode, $esc_html, $format, $nl2br) {
$output = GF_Field_Repeater::get_value_entry_detail($raw_value, '', false, $format, 'email');
$output = preg_replace("/[\r\n]+/", "\n", $output);
return trim($output);
}
public function get_value_export($entry, $input_id = '', $use_text = false, $is_csv = false) {
if (empty($input_id)) { $input_id = $this->id; }
$output = rgar($entry, $input_id);
$output = GF_Field_Repeater::get_value_entry_detail($output, '', false, 'text', 'email');
$output = preg_replace("/[\r\n]+/", ", ", trim($output));
return $output;
}
public static function gform_hide_children($form) {
$form_id = $form['id'];
$repeaterChildren = Array();
$grid_modified = false;
$grid_meta = GFFormsModel::get_grid_column_meta($form_id);
foreach($form['fields'] as $key=>$field) {
if ($field->type == 'repeater') {
if (is_array($field->repeaterChildren)) { $repeaterChildren = array_merge($repeaterChildren, $field->repeaterChildren); }
} elseif ($field->type == 'repeater-end') { array_push($repeaterChildren, $field->id); }
if (!empty($repeaterChildren)) {
if (in_array($field->id, $repeaterChildren)) {
unset($form['fields'][$key]);
if (is_array($grid_meta)) {
$grid_pos = array_search($field->id, $grid_meta);
if ($grid_pos) {
$grid_modified = true;
unset($grid_meta[$grid_pos]);
}
}
}
}
}
if ($grid_modified) { GFFormsModel::update_grid_column_meta($form_id, $grid_meta); }
$form['fields'] = array_values($form['fields']);
return $form;
}
public static function gform_disable_ajax($args) {
$get_form = GFFormsModel::get_form_meta_by_id($args['form_id']);
$form = reset($get_form);
if (GF_Field_Repeater::get_field_index($form) !== false) {
$args['ajax'] = false;
}
return $args;
}
public static function gform_bypass_children_validation($form) {
if (GF_Field_Repeater::get_field_index($form) === false) { return $form; }
$repeaterChildren = Array();
foreach($form['fields'] as $key=>$field) {
if ($field->type == 'repeater') {
if (is_array($field->repeaterChildren)) { $repeaterChildren = array_merge($repeaterChildren, $field->repeaterChildren); }
}
if (!empty($repeaterChildren)) {
if (in_array($field->id, $repeaterChildren) && !$field->adminOnly) {
$form['fields'][$key]['adminOnly'] = true;
$form['fields'][$key]['repeaterChildValidationHidden'] = true;
}
}
}
return $form;
}
public static function gform_unhide_children_validation($form) {
if (GF_Field_Repeater::get_field_index($form) === false) { return $form; }
foreach($form['fields'] as $key=>$field) {
if ($field->repeaterChildValidationHidden) {
$form['fields'][$key]['adminOnly'] = false;
$form['fields'][$key]['repeaterChildValidationHidden'] = false;
}
}
return $form;
}
public static function get_field_index($form, $key = 'type', $value = 'repeater') {
if (is_array($form)) {
if (!array_key_exists('fields', $form)) { return false; }
} else { return false; }
foreach ($form['fields'] as $field_key=>$field_value) {
if (is_object($field_value)) {
if (property_exists($field_value, $key)) {
if ($field_value[$key] == $value) { return $field_key; }
}
}
}
return false;
}
public static function get_field_type($form, $id) {
$field_index = GF_Field_Repeater::get_field_index($form, 'id', $id);
if ($field_index !== false) { return $form['fields'][$field_index]['type']; }
return false;
}
public static function get_children_parems($form, $children_ids) {
foreach($form['fields'] as $key=>$value) {
if (in_array($value['id'], $children_ids)) {
if ($value['inputName']) {
$parems[$value['id']] = $value['inputName'];
} elseif ($value['inputs']) {
foreach($value['inputs'] as $key=>$value) {
if ($value['name']) { $parems[$value['id']] = $value['name']; }
}
}
}
}
if (!empty($parems)) { return $parems; } else { return false; }
}
public static function get_children_parem_values($form, $children_ids) {
global $wp_filter;
$children_parems = GF_Field_Repeater::get_children_parems($form, $children_ids);
if (empty($children_parems)) { return false; }
// Check the URL first
foreach($_GET as $url_key=>$url_value) {
$key = array_search($url_key, $children_parems);
if ($key !== false) {
$parems[$key][0] = $url_value;
} else {
$split_key = preg_split('/\D+\K/', $url_key);
$key = array_search($split_key[0], $children_parems);
if ($key !== false) { $parems[$key][$split_key[1]] = $url_value; }
}
}
// Then check the filters
foreach($wp_filter as $key=>$value) {
$split_key = preg_split('/^gform_field_value_+\K/', $key);
if (!empty($split_key[1])) {
$key1 = array_search($split_key[1], $children_parems);
if ($key1 !== false) {
$parems[$key1][0] = apply_filters($key, '');
} else {
$split_key2 = preg_split('/\D+\K/', $split_key[1]);
$key2 = array_search($split_key2[0], $children_parems);
if ($key2 !== false) { $parems[$key2][$split_key2[1]] = apply_filters($key, ''); }
}
}
}
if (!empty($parems)) { return $parems; } else { return false; }
}
}
GF_Fields::register(new GF_Field_Repeater());

php whois stopped working on another server

I am using this whois class, it works fine on one server but it does not work properly on another server with the same PHP version 5.4, on first server it returns domain name status correctly, but on the other one it returns just one status: "domain name is not available" while the domain name is actually available.
<?
class Whois_domain {
var $possible_tlds;
var $whois_server;
var $free_string;
var $whois_param;
var $domain;
var $tld;
var $compl_domain;
var $full_info;
var $msg;
var $info;
var $os_system = "linux"; // switch between "linux" and "win"
function Whois_domain() {
$this->info = "";
$this->msg = "";
}
function process() {
if ($this->create_domain()) {
if ($this->full_info == "yes") {
$this->get_domain_info();
} else {
if ($this->check_only() == 1) {
$this->msg = "The domain name: <b>".$this->compl_domain."</b> is free.";
return true;
} elseif ($this->check_only() == 0) {
$this->msg = "The domain name: <b>".$this->compl_domain."</b> is not available";
return false;
} else {
$this->msg = "There was something wrong, try it again.";
}
}
} else {
$this->msg = "Only letters, numbers and hyphens (-) are valid!";
}
}
function check_entry() {
if (preg_match("/^([a-z0-9]+(\-?[a-z0-9]*)){2,63}$/i", $this->domain)) {
return true;
} else {
return false;
}
}
function create_tld_select() {
$menu = "<select name=\"tld\" style=\"margin-left:0;\">\n";
foreach ($this->possible_tlds as $val) {
$menu .= " <option value=\"".$val."\"";
$menu .= (isset($_POST['tld']) && $_POST['tld'] == $val) ? " selected=\"selected\">" : ">";
$menu .= $val."</option>\n";
}
$menu .= "</select>\n";
return $menu;
}
function create_domain() {
if ($this->check_entry()) {
$this->domain = strtolower($this->domain);
$this->compl_domain = $this->domain.".".$this->tld;
return true;
} else {
return false;
}
}
function check_only() {
$data = $this->get_whois_data();
if (is_array($data)) {
$found = 0;
foreach ($data as $val) {
if (eregi($this->free_string, $val)) {
$found = 1;
}
}
return $found;
} else {
$this->msg = "Error, please try it again.";
}
}
function get_domain_info() {
if ($this->create_domain()) {
$data = ($this->tld == "nl") ? $this->get_whois_data(true) : $this->get_whois_data();
if (is_array($data)) {
foreach ($data as $val) {
if (eregi($this->free_string, $val)) {
$this->msg = "The domain name: <b>".$this->compl_domain."</b> is free.";
$this->info = "";
break;
}
$this->info .= $val;
}
} else {
$this->msg = "Error, please try it again.";
}
} else {
$this->msg = "Only letters, numbers and hyphens (-) are valid!";
}
}
function get_whois_data($empty_param = false) {
// the parameter is new since version 1.20 and is used for .nl (dutch) domains only
if ($empty_param) {
$this->whois_param = "";
}
if ($this->tld == "de") $this->os_system = "win"; // this tld must be queried with fsock otherwise it will not work
if ($this->os_system == "win") {
$connection = #fsockopen($this->whois_server, 43);
if (!$connection) {
unset($connection);
$this->msg = "Can't connect to the server!";
return;
} else {
sleep(2);
fputs($connection, $this->whois_param.$this->compl_domain."\r\n");
while (!feof($connection)) {
$buffer[] = fgets($connection, 4096);
}
fclose($connection);
}
} else {
$string = "whois -h ".$this->whois_server." \"".$this->whois_param.$this->compl_domain."\"";
$string = str_replace (";", "", $string).";";
exec($string, $buffer);
}
if (isset($buffer)) {
//print_r($buffer);
return $buffer;
} else {
$this->msg = "Can't retrieve data from the server!";
}
}
}
?>
I changed files permissions and php versions on the other server, but still the same.
This has been solved, it was fsockopen restrictions on the server, it is fine now.

Argument 1 passed to something::__construct must be

i am working on an addon, but i got a problem
[22:03:08] [CRITICAL]: "Could not pass event 'pocketmine\event\player\PlayerInteractEvent' to 'MTeamPvP v1.0.0 Beta': Argument 1 passed to MCrafters\TeamPvP\GameManager::__construct() must be an instance of MCrafters\TeamPvP\TeamPvP, none given, called in C:\Users\USER\Desktop\Taha\FlashCraft PE\lobby 1\plugins\DevTools\src\MCrafters\TeamPvP\TeamPvP.php on line 120 and defined on MCrafters\TeamPvP\TeamPvP
[22:03:08] [NOTICE]: InvalidArgumentException: "Argument 1 passed to MCrafters\TeamPvP\GameManager::__construct() must be an instance of MCrafters\TeamPvP\TeamPvP, none given, called in C:\Users\USER\Desktop\Taha\FlashCraft PE\lobby 1\plugins\DevTools\src\MCrafters\TeamPvP\TeamPvP.php on line 120 and defined" (E_RECOVERABLE_ERROR) in "/DevTools/src/MCrafters/TeamPvP/GameManager" at line 13
also sorry for the different error broadcasting
code : (please don't care about the other classes except GameManager and TeamPvP)
TeamPvP.php:
<?php
namespace MCrafters\TeamPvP;
use pocketmine\plugin\PluginBase;
use pocketmine\utils\TextFormat as Color;
use pocketmine\utils\Config;
use pocketmine\event\Listener;
use pocketmine\event\entity\EntityDamageEvent;
use pocketmine\event\entity\EntityDamageByEntityEvent;
use pocketmine\event\player\PlayerInteractEvent;
use pocketmine\event\player\PlayerDeathEvent;
use pocketmine\math\Vector3;
use pocketmine\level\Position;
use pocketmine\command\Command;
use pocketmine\command\CommandSender;
use pocketmine\Player;
use pocketmine\block\Block;
use pocketmine\item\Item;
use pocketmine\block\WallSign;
use pocketmine\block\PostSign;
use pocketmine\scheduler\ServerScheduler;
class TeamPvP extends PluginBase implements Listener
{
// Teams
public $reds = [];
public $blues = [];
public $gameStarted = false;
public $yml;
public function onEnable()
{
// Initializing config files
$this->saveResource("config.yml");
$yml = new Config($this->getDataFolder() . "config.yml", Config::YAML);
$this->yml = $yml->getAll();
$this->getLogger()->debug("Config files have been saved!");
$this->getServer()->getScheduler()->scheduleRepeatingTask(new Tasks\SignUpdaterTask($this), 15);
$this->getServer()->getPluginManager()->registerEvents($this, $this);
$this->getServer()->getLogger()->info(Color::BOLD . Color::GOLD . "M" . Color::AQUA . "TeamPvP " . Color::GREEN . "Enabled" . Color::RED . "!");
}
public function isFriend($p1, $p2)
{
if ($this->getTeam($p1) === $this->getTeam($p2) && $this->getTeam($p1) !== false) {
return true;
} else {
return false;
}
}
// isFriend
public function getTeam($p)
{
if (in_array($p, $this->reds)) {
return "red";
} elseif (in_array($p, $this->blues)) {
return "blue";
} else {
return false;
}
}
public function setTeam($p, $team)
{
if (strtolower($team) === "red") {
if (count($this->reds) < 5) {
if ($this->getTeam($p) === "blue") {
unset($this->blues[array_search($p, $this->blues)]);
}
array_push($this->reds, $p);
$this->getServer()->getPlayer($p)->setNameTag("§c§l" . $p);
$this->getServer()->getPlayer($p)->teleport(new Vector3($this->yml["waiting_x"], $this->yml["waiting_y"], $this->yml["waiting_z"]));
return true;
} elseif (count($this->blues) < 5) {
$this->setTeam($p, "blue");
} else {
return false;
}
} elseif (strtolower($team) === "blue") {
if (count($this->blues) < 5) {
if ($this->getTeam($p) === "red") {
unset($this->reds[array_search($p, $this->reds)]);
}
array_push($this->blues, $p);
$this->getServer()->getPlayer($p)->setNameTag("§b§l" . $p);
$this->getServer()->getPlayer($p)->teleport(new Vector3($this->yml["waiting_x"], $this->yml["waiting_y"], $this->yml["waiting_z"]));
return true;
} elseif (count($this->reds) < 5) {
$this->setTeam($p, "red");
} else {
return false;
}
}
}
public function removeFromTeam($p, $team)
{
if (strtolower($team) == "red") {
unset($this->reds[array_search($p, $this->reds)]);
return true;
} elseif (strtolower($team) == "blue") {
unset($this->blues[array_search($p, $this->blues)]);
return true;
}
}
public function onInteract(PlayerInteractEvent $event)
{
$p = $event->getPlayer();
$teams = array("red", "blue");
if ($event->getBlock()->getX() === $this->yml["sign_join_x"] && $event->getBlock()->getY() === $this->yml["sign_join_y"] && $event->getBlock()->getZ() === $this->yml["sign_join_z"]) {
if (count($this->blues) < 5 && count($this->reds) < 5) {
$this->setTeam($p->getName(), $teams[array_rand($teams, 1)]);
$s = new GameManager();
$s->run();
} else {
$p->sendMessage($this->yml["teams_are_full_message"]);
}
}
}
public function onEntityDamage(EntityDamageEvent $event)
{
if ($event instanceof EntityDamageByEntityEvent) {
if ($event->getEntity() instanceof Player) {
if ($this->isFriend($event->getDamager()->getName(), $event->getEntity()->getName()) && $this->gameStarted == true) {
$event->setCancelled(true);
$event->getDamager()->sendMessage(str_replace("{player}", $event->getPlayer()->getName(), $this->yml["hit_same_team_message"]));
}
if ($this->isFriend($event->getDamager()->getName(), $event->getEntity()->getName())) {
$event->setCancelled(true);
}
}
}
}
public function onDeath(PlayerDeathEvent $event)
{
if ($this->getTeam($event->getEntity()->getName()) == "red" && $this->gameStarted == true) {
$this->removeFromTeam($event->getEntity()->getName(), "red");
$event->getEntity()->teleport($this->getServer()->getLevelByName($this->yml["spawn_level"])->getSafeSpawn());
} elseif ($this->getTeam($event->getEntity()->getName()) == "blue" && $this->gameStarted == true) {
$this->removeFromTeam($event->getEntity()->getName(), "blue");
$event->getEntity()->teleport($this->getServer()->getLevelByName($this->yml["spawn_level"])->getSafeSpawn());
}
foreach ($this->blues as $b) {
foreach ($this->reds as $r) {
if (count($this->reds) == 0 && $this->gameStarted == true) {
$this->getServer()->getPlayer($b)->getInventory()->clearAll();
$this->removeFromTeam($b, "blue");
$this->getServer()->getPlayer($b)->teleport($this->getServer()->getLevelByName($this->yml["spawn_level"])->getSafeSpawn());
$this->getServer()->broadcastMessage("Blue Team won TeamPvP!");
} elseif (count($this->blues) == 0 && $this->gameStarted == true) {
$this->getServer()->getPlayer($r)->getInventory()->clearAll();
$this->removeFromTeam($r, "red");
$this->getServer()->getPlayer($r)->teleport($this->getServer()->getLevelByName($this->yml["spawn_level"])->getSafeSpawn());
}
}
}
}
}//class
GameManager.php :
<?php
namespace MCrafters\TeamPvP;
use pocketmine\scheduler\ServerScheduler as Tasks;
class GameManager
{
public $reds;
public $blues;
public $gst;
public $gwt;
public function __construct(\MCrafters\TeamPvP\TeamPvP $plugin)
{
parent::__construct($plugin);
$this->plugin = $plugin;
}
public function run()
{
$this->reds = $this->plugin->reds;
$this->blues = $this->plugin->blues;
if (count($this->reds) < 5 && count($this->blues) < 5) {
$this->gst = Tasks::scheduleRepeatingTask(new Tasks\GameStartTask($this), 20)->getTaskId();
Tasks::cancelTask($this->gwt);
} else {
$this->gwt = Tasks::scheduleRepeatingTask(new Tasks\GameWaitingTask($this), 15)->getTaskId();
}
}
}
namespace correct, class and file name correct, and all other functions from other classes have nothing to do with this :) check the line where there is GameManager::run() in TeamPvP class.
i already know there is one about this, but i didn't understand it.
Thank You for your help.
You have a type hint
public function __construct(\MCrafters\TeamPvP\TeamPvP $plugin)
{
parent::__construct($plugin);
$this->plugin = $plugin;
}
So when you go to instantiate MCrafters\TeamPvP\GameManager you have to pass it an instance of \MCrafters\TeamPvP\TeamPvP
$team = new \MCrafters\TeamPvP\TeamPvP();
$manager = new \MCrafters\TeamPvP\GameManager($team)

which is more efficient, simple or nested condition using IF()

I'm newbie, and just want to asking about programming stuff. I hope you guys help me getting understand :)
which is more efficient in coding and performance between this two function?
first function using nested condition, and second function using simple condition,
which is better to be implemented?
function optionOne()
{
$a = getData();
$return = array();
if ($a === false) {
$return['error'] = true;
} else {
$b = getValue();
if ($b === false) {
$return['error'] = true;
} else {
$c = getVar();
if ($c === false) {
$return['error'] = true;
} else {
$return['error'] = false;
$return['message'] = 'congrat!';
}
}
}
return $return;
}
function optionTwo()
{
$return = array();
$a = getData();
if ($a === false) {
$return['error'] = true;
return $return;
}
$b = getValue();
if ($b === false) {
$return['error'] = true;
return $return;
}
$c = getVar();
if ($c === false) {
$return['error'] = true;
return $return;
} else {
$return['error'] = false;
$return['message'] = 'congrat!';
}
return $return;
}
thank you before guys,
function option()
{
$return=array();
$return['error'] = true;
switch(getData()){
case false:
return $return;
break;
case true:
if(getValue()==false){return $return;}
else{
if(getVar()==false){return $return;}
else{
$return['error'] = false;
$return['message'] = 'congrat!';}
}
break;
default:
return 'getData() return null value';
break;
}
}
i was tried to applied the switch method to your function, as one of your option too
A neater option would be to make the 3 functions throw an exception when there's an error instead of returning boolean false. That's what exceptions are for anyway. Then in your function you can just wrap the calls in a try-catch block.
function option {
$return = array();
try {
$a = getData();
$b = getValue();
$c = getVar();
$return['error'] = false;
$return['message'] = 'congrat!';
} catch(Exception e) {
$return['error'] = true;
}
return $return;
}

Categories