Clean a value for use in class / id

@since 2.0.0

@param      $input
@param bool  $noarray
@param bool  $db_field

@return mixed|string
487643
public static function clean( $input, $noarray = false, $db_field = false ) {

		$output = trim( (string) $input );

		$output = str_replace( '--1', 'podsfixtemp1', $output );
		$output = str_replace( '__1', 'podsfixtemp2', $output );

		if ( false !== $noarray ) {
			$output = preg_replace( '/\[podsfixtemp\d+\]/', '-', $output );
			$output = preg_replace( '/\[\d*\]/', '-', $output );
		}

		$output = str_replace( array( '[', ']' ), '-', $output );

		$output = pods_clean_name( $output );

		$output = preg_replace( '/([^a-z0-9\-_])/', '', $output );
		$output = preg_replace( '/(_){2,}/', '_', $output );
		$output = preg_replace( '/(-){2,}/', '-', $output );

		if ( true !== $db_field ) {
			$output = str_replace( '_', '-', $output );
		}

		$output = rtrim( $output, '-' );

		$output = str_replace( 'podsfixtemp1', '--1', $output );
		$output = str_replace( 'podsfixtemp2', '__1', $output );

		return $output;
	}
1252052
protected function _insert($postdata, $no_processing = false, $no_processing_fields = array())
    {
        if (!$postdata)
        {
            self::error('$postdata array is empty');
        }
        $set = array();
        $db = Fruit_db::get_instance($this->connection);
        $fields = array_merge($this->fields, $this->hidden_fields);
        $fk_queries = array();
        foreach ($postdata as $key => $val)
        {
            if (isset($fields[$key]) && !isset($this->locked_fields[$key]) && !isset($this->custom_fields[$key]))
            {
                if (isset($this->field_type[$key]))
                {
                    switch ($this->field_type[$key])
                    {
                        case 'password':
                            if (trim($val) == '')
                            {
                                continue 2;
                            }
                            elseif ($this->defaults[$key])
                            {
                                $val = hash($this->defaults[$key], $val);
                            }
                            break;
                        case 'fk_relation': //
                            continue 2;
                            break;
                    }
                }

                $set[$fields[$key]['table']]['`' . $fields[$key]['field'] . '`'] = $this->prepare_query_field($val, $key, 'create');

                /*if (is_array($val))
                {
                $set[$fields[$key]['table']]['`' . $fields[$key]['field'] . '`'] = $db->escape(implode(',', $val), false, $this->
                field_type[$key], $this->field_null[$key], isset($this->bit_field[$key]));
                }
                elseif (isset($this->point_field[$key]))
                {
                $set[$fields[$key]['table']]['`' . $fields[$key]['field'] . '`'] = 'Point(' . $db->escape($val, true, 'point', $this->
                field_null[$key], isset($this->bit_field[$key])) . ')';
                }
                elseif (isset($this->float_field[$key]))
                {

                }
                elseif (isset($this->float_field[$key]))
                {

                }
                else
                $set[$fields[$key]['table']]['`' . $fields[$key]['field'] . '`'] = ((isset($this->no_quotes[$key]) && isset($this->
                pass_var['create'][$key])) ? $db->escape($val, true) : $db->escape($val, false, $this->field_type[$key], $this->
                field_null[$key], isset($this->bit_field[$key])));*/
            }
            elseif ($no_processing)
            {
                /*$set[$no_processing_fields[$key]['table']]['`' . $no_processing_fields[$key]['field'] . '`'] = ((isset($this->no_quotes[$key]) &&
                isset($this->pass_var['create'][$key])) ? $db->escape($val, true) : $db->escape($val, false, $this->field_type[$key], $this->
                field_null[$key], isset($this->bit_field[$key])));*/
                $set[$no_processing_fields[$key]['table']]['`' . $no_processing_fields[$key]['field'] . '`'] = $this->
                    prepare_query_field($val, $key, 'create', true);
            }
        }
        //$keys = array_keys($set[$this->table]);
        if (!$set)
        {
            self::error('Nothing to insert');
        }
        if (!$this->primary_ai && !isset($postdata[$this->table . '.' . $this->primary_key]))
        {
            self::error('Can\'t insert a row. No primary value.');
        }
        if (!$this->demo_mode)
            $db->query('INSERT INTO `' . $this->table . '` (' . implode(',', array_keys($set[$this->table])) . ') VALUES (' .
                implode(',', $set[$this->table]) . ')');
        if ($this->primary_ai)
        {
            $ins_id = $db->insert_id();
            $set[$this->table]['`' . $this->primary_key . '`'] = $ins_id;
            $postdata[$this->table . '.' . $this->primary_key] = $ins_id;
        }
        else
        {
            $ins_id = $postdata[$this->table . '.' . $this->primary_key];
        }
        if ($this->join)
        {
            foreach ($this->join as $alias => $param)
            {
                $set[$alias]['`' . $param['join_field'] . '`'] = $set[$param['table']]['`' . $param['field'] . '`'];
                if (!$this->demo_mode && !$param['not_insert'])
                {
                    $db->query("INSERT INTO `{$param['join_table']}` (" . implode(',', array_keys($set[$alias])) . ") VALUES (" . implode(',',
                        $set[$alias]) . ")");
                }
            }
        }

        if ($this->fk_relation)
        {
            foreach ($this->fk_relation as $fk)
            {
                $field = $fk['table'] . '.' . $fk['field'];
                if (array_key_exists($fk['alias'], $postdata) && array_key_exists($field, $postdata))
                {
                    $in_val = $db->escape($postdata[$field], false, $this->field_type[$field], $this->field_null[$field], isset($this->
                        bit_field[$field]));
                    $db->query('DELETE FROM `' . $fk['fk_table'] . '` WHERE `' . $fk['in_fk_field'] . '` = ' . $in_val);
                    $fkids = $this->parse_comma_separated($postdata[$fk['alias']]);
                    if ($fkids)
                    {
                        $ins_vals = array();
                        $ins_keys = array();
                        $ins_add = array();
                        if ($fk['add_data'])
                        {
                            foreach ($fk['add_data'] as $add_key => $add_val)
                            {
                                $ins_keys[] = '`' . $add_key . '`';
                                $ins_add[] = $db->escape($add_val);
                            }
                        }
                        $ins_add[] = /*$db->escape(*/ $in_val /*)*/;
                        $ins_keys[] = '`' . $fk['in_fk_field'] . '`';
                        $ins_keys[] = '`' . $fk['out_fk_field'] . '`';
                        foreach ($fkids as $fkid)
                        {
                            $ins_vals[] = '(' . implode(',', $ins_add) . ',' . $db->escape($fkid) . ')';
                        }
                        $db->query('INSERT INTO `' . $fk['fk_table'] . '` (' . implode(',', $ins_keys) . ') VALUES ' . implode(',', $ins_vals));
                    }
                }
            }
        }

        unset($set, $postdata);
        return $ins_id;
    }
1050124
protected function deleteLinkedFieldValues($field_id)
    {
        $sql = 'DELETE fvt
                FROM field_value_translation AS fvt
                WHERE fvt.field_value_id IN (SELECT DISTINCT(fv.field_value_id)
                FROM field_value AS fv
                INNER JOIN field_value AS fv2
                ON (fv.field_value_id = fv2.field_value_id)
                WHERE fv.field_id = ?)';

        return (bool) $this->db->run($sql, array($field_id))->rowCount();
    }
830622
protected static function cleanRecord($record = [], $include = '*', $id_field = null)
    {
        if ($record instanceof BSONDocument) {
            $record = $record->getArrayCopy();
        } elseif (is_object($record)) {
            $record = (array)$record; // std object
        }
        $out = parent::cleanRecord($record, $include, $id_field);

        return static::fromMongoObjects($out);
    }
1155309
static public function replaceArrayKeyWithArray($arr = [],$field = '')
    {
        $newArr = [];
        if($arr){
            foreach ($arr as $value) {
                $newArr[$value[$field]][] = $value;
            }
        }
        return $newArr;
    }
57323
function _query($sql,$inputarr=false)
	{
		if (is_array($sql)) {
			$stmt = $sql[1];
		} else {
			$stmt = $this->_connectionID->prepare($sql);
		}
		#adodb_backtrace();
		#var_dump($this->_bindInputArray);
		if ($stmt) {
			$this->_driver->debug = $this->debug;
			if ($inputarr) {
				$ok = $stmt->execute($inputarr);
			}
			else {
				$ok = $stmt->execute();
			}
		}


		$this->_errormsg = false;
		$this->_errorno = false;

		if ($ok) {
			$this->_stmt = $stmt;
			return $stmt;
		}

		if ($stmt) {

			$arr = $stmt->errorinfo();
			if ((integer)$arr[1]) {
				$this->_errormsg = $arr[2];
				$this->_errorno = $arr[1];
			}

		} else {
			$this->_errormsg = false;
			$this->_errorno = false;
		}
		return false;
	}
535643
private function _clean_input_data($str) {
		if (is_array($str)) {
			$new_array = array();
			foreach ($str as $key => $val) {
				$new_array[$this->_clean_input_keys($key)] = $this->_clean_input_data($val);
			}
			return $new_array;
		}
		
		/*
		 * We strip slashes if magic quotes is on to keep things consistent
		 * NOTE: In PHP 5.4 get_magic_quotes_gpc() will always return 0 and it
		 * will probably not exist in future versions at all.
		 */
		if (get_magic_quotes_gpc()) {
			$str = stripslashes($str);
		}
		
		// Remove control characters
		$str = Security::remove_invisible_characters($str);
		
		// Should we filter the input data?
		if ($this->_enable_xss === TRUE) {
			$str = Security::xss_clean($str);
		}
		
		// Standardize newlines if needed
		if ($this->_standardize_newlines == TRUE) {
			if (strpos($str, "\r") !== FALSE) {
				$str = str_replace(array("\r\n", "\r", "\r\n\n"), PHP_EOL, $str);
			}
		}
		
		return $str;
	}
651212
protected function cleanArray($input)
	{
		// add to the cleaned list when object
		if (is_object($input))
		{
			$this->parent->isClean($input);
		}

		foreach ($input as $k => $v)
		{
			$input[$k] = $this->clean($v);
		}

		return $input;
	}
1131118
static function input_attr(&$attr)
	{
	    $str = " ";
        if(!empty($attr) && is_array($attr))
        {
            foreach($attr as $key=>$value)
            {
                $str .= "$key=\"$value\" ";
            }
        }
        return $str;
	}
1239632
function _query($sql,$inputarr=false)
	{
	GLOBAL $php_errormsg;
		if (isset($php_errormsg)) $php_errormsg = '';
		$this->_error = '';

		if ($inputarr) {
			if (is_array($sql)) {
				$stmtid = $sql[1];
			} else {
				$stmtid = odbc_prepare($this->_connectionID,$sql);

				if ($stmtid == false) {
					$this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';
					return false;
				}
			}

			if (! odbc_execute($stmtid,$inputarr)) {
				//@odbc_free_result($stmtid);
				if ($this->_haserrorfunctions) {
					$this->_errorMsg = odbc_errormsg();
					$this->_errorCode = odbc_error();
				}
				return false;
			}

		} else if (is_array($sql)) {
			$stmtid = $sql[1];
			if (!odbc_execute($stmtid)) {
				//@odbc_free_result($stmtid);
				if ($this->_haserrorfunctions) {
					$this->_errorMsg = odbc_errormsg();
					$this->_errorCode = odbc_error();
				}
				return false;
			}
		} else
			$stmtid = odbc_exec($this->_connectionID,$sql);

		$this->_lastAffectedRows = 0;
		if ($stmtid) {
			if (@odbc_num_fields($stmtid) == 0) {
				$this->_lastAffectedRows = odbc_num_rows($stmtid);
				$stmtid = true;
			} else {
				$this->_lastAffectedRows = 0;
				odbc_binmode($stmtid,$this->binmode);
				odbc_longreadlen($stmtid,$this->maxblobsize);
			}

			if ($this->_haserrorfunctions) {
				$this->_errorMsg = '';
				$this->_errorCode = 0;
			} else
				$this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';
		} else {
			if ($this->_haserrorfunctions) {
				$this->_errorMsg = odbc_errormsg();
				$this->_errorCode = odbc_error();
			} else
				$this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';
		}
		return $stmtid;
	}
693331
public function getValue($value = '', $field = 'id', $fieldOutput = '')
    {
        if (!is_array($fieldOutput)) {
            $fieldOutput = [$fieldOutput];
        }
        $db = $this->db->select($fieldOutput)->from($this->table);
        if (is_array($value) && count($value) > 0) {
            foreach ($value as $column => $column_value) {
                if (is_array($column_value)) {
                    $db->whereIn($column, $column_value);
                } else {
                    $db->where($column, self::OPERATOR_EQUAL_TO, $column_value);
                }
            }
        } else {
            $db->where($field, self::OPERATOR_EQUAL_TO, $value);
        }
        $result = $db->execute()->fetch();

        $this->debug->debug(__FUNCTION__, 'GET Result => ' . json_encode($result));
        if (isset($result->$fieldOutput)) {
            return $result->$fieldOutput;
        } else {
            return NULL;
        }
    }
954095
public function validate(array &$input, $fields=null, $ref=null, &$errCount=0) {
		$data	= array();
// 		$class = $this->class;
// 		debug('validate() - $fields', $fields);
// 		debug('validate() - $ref', $ref);
		foreach( $this->fields as $fieldName => &$fData ) {
			try {
				if( $fields !== NULL && !in_array($fieldName, $fields) ) {
// 					debug('Field not in $fields array');
					unset($input[$fieldName]);
					// If updating, we do not modify a field not in $fields
					// If creating, we set to default a field not in $fields
					if( $ref ) { continue; }
				}
				if( !$fData->writable ) { continue; }
				if( !isset($input[$fieldName]) ) {
					$input[$fieldName] = null;
				}
// 				debug('validate() - '.$fieldName, $input[$fieldName]);
				$this->validateFieldValue($fieldName, $input[$fieldName], $input, $ref);
// 				if( isset($ref) ) {
// 					debug("Ref -> $fieldName => ", $ref->getValue($fieldName));
// 					debug("New value", $uInputData[$fieldName]);
// 				}
// 				debug('Current value ? '.$ref->getValue($fieldName));
				// PHP does not make difference between 0 and NULL, so every non-null value is different from null.
				if( !isset($ref) || ($ref->getValue($fieldName) === NULL XOR $input[$fieldName] === NULL) || $input[$fieldName] != $ref->getValue($fieldName) ) {
					$data[$fieldName] = $input[$fieldName];
				}

			} catch( UserException $e ) {
				$errCount++;
				if( isset($this->class) ) {
					$c	= $this->class;
					$c::reportException($e);
				} else {
					reportError($e);
// 					throw $e;
				}
			}
		}
		return $data;
	}
279959
public function deleteJournalEntry(array $input, $openTransaction = true, $databaseConnectionName = null, $organizationId = null, $loggedUserId = null)
	{
    $count = 0;
    $periodIsClosed = false;

    if(empty($organizationId))
    {
      $organizationId = $this->AuthenticationManager->getCurrentUserOrganizationId();
    }

    if(empty($loggedUserId))
    {
      $loggedUserId = $this->AuthenticationManager->getLoggedUserId();
    }

    $this->beginTransaction($openTransaction, $databaseConnectionName);

    try
		// /$this->DB->transaction(function() use ($input, &$count, &$status, &$periodIsClosed, &$Period)
		{
      foreach ($input['id'] as $key => $id)
			{
        $count++;
        $JournalEntry = $this->JournalEntry->byId($id);

        if($count == 1)
        {
          $JournalVoucher = $this->JournalVoucher->byId($JournalEntry->journal_voucher_id);
          $Period = $this->Period->byId($JournalVoucher->period_id);

          if($Period->is_closed)
          {
            return json_encode(array('success' => false, 'info' => $this->Lang->get('decima-accounting::journal-management.closedPeriodValidationMessage2', array('period' => $this->Lang->get('decima-accounting::period-management.' . $Period->month)))));
          }

          $JournalVoucher = $this->JournalVoucher->byId($JournalEntry->journal_voucher_id);
          $Journal = $this->Journal->create(array('journalized_id' => $JournalEntry->journal_voucher_id, 'journalized_type' => $this->JournalVoucher->getTable(), 'user_id' => $loggedUserId, 'organization_id' => $organizationId));
        }

        $this->Journal->attachDetail($Journal->id, array('note' => $this->Lang->get('decima-accounting::journal-management.journalEntryDeletedJournal', array('number' => $JournalVoucher->number)), $Journal));
      }

      $this->JournalEntry->delete($input['id']);

      $status = $this->updateJournalVoucherStatus($JournalVoucher->id, $Journal, $JournalVoucher, null, $databaseConnectionName);

      $this->commit($openTransaction);
    }
    catch (\Exception $e)
    {
      $this->rollBack($openTransaction);

      throw $e;
    }
    catch (\Throwable $e)
    {
      $this->rollBack($openTransaction);

      throw $e;
    }
    // });

    return json_encode(array('success' => $this->Lang->get('form.defaultSuccessDeleteMessage'), 'status' => $status, 'statusLabel' => $this->Lang->get('decima-accounting::journal-management.' . $status)));
  }
818884
public static function clean($input)
    {
        // handle input of type array
        if (is_array($input)) {
            foreach ($input as $idx => $val) {
                $input[$idx] = self::clean($val);
            }
            return $input;
        }

        if (!is_string($input) || $input == '') {
            return $input;
        }

        // iconv/mbstring are much faster (especially with long strings)
        if (function_exists('mb_convert_encoding')) {
            $msch = mb_substitute_character();
            mb_substitute_character('none');
            $res = mb_convert_encoding($input, 'UTF-8', 'UTF-8');
            mb_substitute_character($msch);

            if ($res !== false) {
                return $res;
            }
        }

        if (function_exists('iconv')) {
            if (($res = @iconv('UTF-8', 'UTF-8//IGNORE', $input)) !== false) {
                return $res;
            }
        }

        $seq    = '';
        $out    = '';
        $regexp = '/^('.
//          '[\x00-\x7F]'.                                  // UTF8-1
            '|[\xC2-\xDF][\x80-\xBF]'.                      // UTF8-2
            '|\xE0[\xA0-\xBF][\x80-\xBF]'.                  // UTF8-3
            '|[\xE1-\xEC][\x80-\xBF][\x80-\xBF]'.           // UTF8-3
            '|\xED[\x80-\x9F][\x80-\xBF]'.                  // UTF8-3
            '|[\xEE-\xEF][\x80-\xBF][\x80-\xBF]'.           // UTF8-3
            '|\xF0[\x90-\xBF][\x80-\xBF][\x80-\xBF]'.       // UTF8-4
            '|[\xF1-\xF3][\x80-\xBF][\x80-\xBF][\x80-\xBF]'.// UTF8-4
            '|\xF4[\x80-\x8F][\x80-\xBF][\x80-\xBF]'.       // UTF8-4
            ')$/';

        for ($i = 0, $len = strlen($input); $i < $len; $i++) {
            $chr = $input[$i];
            $ord = ord($chr);

            // 1-byte character
            if ($ord <= 0x7F) {
                if ($seq !== '') {
                    $out .= preg_match($regexp, $seq) ? $seq : '';
                    $seq = '';
                }

                $out .= $chr;
            }
            // first byte of multibyte sequence
            else if ($ord >= 0xC0) {
                if ($seq !== '') {
                    $out .= preg_match($regexp, $seq) ? $seq : '';
                    $seq = '';
                }

                $seq = $chr;
            }
            // next byte of multibyte sequence
            else if ($seq !== '') {
                $seq .= $chr;
            }
        }

        if ($seq !== '') {
            $out .= preg_match($regexp, $seq) ? $seq : '';
        }

        return $out;
    }
1144346
public function validate( $input ) 
    {
        if ( !is_array( $input ) ) 
        {
            throw new phpillowValidationException( 
                "Field is not an array",
                array()
            );
        }

        // Reuse the parent object validator foreach of the embedded objects
        foreach( $input as $key => $object ) 
        {
            $input[$key] = parent::validate( $object );
        }

        return $input;
    }
9947
protected function cleanString($input)
	{
		return htmlentities(
			$input,
			$this->parent->getConfig('htmlentities_flags', ENT_QUOTES),
			$this->parent->getConfig('htmlentities_encoding', 'UTF-8'),
			$this->parent->getConfig('htmlentities_double_encode', false)
		);
	}
220627
function _query($sql,$inputarr=false)
	{
		$rez = $this->_connectionID->query($sql);
		if ($rez === false) {
			$this->_errorNo = $this->_connectionID->lastErrorCode();
		}
		// If no data was returned, we don't need to create a real recordset
		elseif ($rez->numColumns() == 0) {
			$rez->finalize();
			$rez = true;
		}

		return $rez;
	}