Single point for mitigating csv injection vulnerabilities

https://www.owasp.org/index.php/CSV_Injection

@param string $input
@return string
516708
protected function filterCsvInjection($input)
    {
        // Try to prevent csv injection
        $dangers = ['=', '+', '-', '@'];
        
        // Trim leading spaces for our test
        $trimmed = trim($input);
        
        if (strlen($trimmed)>1 && in_array($trimmed[0], $dangers)) {
            return "'" . $input;
        }  else {
            return $input;
        }
    }
560484
public function serialise($input)
    {
        $writer = Writer::createFromString('');

        if (is_array(reset($input))) {
            $writer->insertOne(array_keys(reset($input)));
        } else {
            $writer->insertOne(array_keys($input));
        }

        if (is_array(reset($input))) {
            $writer->insertAll($input);
        } else {
            $writer->insertOne($input);
        }

        return $writer->__toString();
    }
895281
public function convertFromPositive($input)
    {
        $matches = [];

        if (
            !preg_match(
                '
                /^0*(?<carets>\\^*)(?<alpha>[A-Z]*)(?<year>\d+)$/',
                $input,
                $matches
            )
        ) {
            return null;
        }

        if ($matches['alpha'] === '') {
            return $matches['year'];
        }

        if ($matches['carets'] === '') {
            $expectedLength = ord($matches['alpha']) - static::ORD_START + 5;
        } else {
            $len = strlen($matches['carets']);

            $expectedLength = 0;

            for ($i=0; $i < $len; $i++) {
                $expectedLength = $expectedLength * 26;
                $expectedLength += ord($matches['alpha'][$i]) - static::ORD_START;
                $expectedLength++;
            }

            $expectedLength += 30;
        }

        return str_pad($matches['year'], $expectedLength, '0', STR_PAD_RIGHT);
    }
885022
protected static function decodePart($input)
    {
        $n = static::INITIAL_N;
        $i = 0;
        $bias = static::INITIAL_BIAS;
        $output = '';

        $pos = strrpos($input, static::DELIMITER);

        if ($pos !== false) {
            $output = substr($input, 0, $pos++);
        } else {
            $pos = 0;
        }

        $outputLength = strlen($output);
        $inputLength = strlen($input);
        $res = array();

        while ($pos < $inputLength) {
            $oldi = $i;
            $w = 1;

            for ($k = static::BASE;; $k += static::BASE) {
                $digit = static::$decodeTable[$input[$pos++]];
                $i = $i + ($digit * $w);
                $t = static::calculateThreshold($k, $bias);

                if ($digit < $t) {
                    break;
                }

                $w = $w * (static::BASE - $t);
            }

            $bias = static::adapt($i - $oldi, ++$outputLength, ($oldi === 0));
            $n = $n + (int) ($i / $outputLength);
            $i = $i % ($outputLength);

            if ($n < 0x80) {
                $cp = chr($n);
            } elseif ($n <= 0x7FF) {
                $cp = chr(($n >> 6) + 0xC0) . chr(($n & 0x3F) + 0x80);
            } elseif ($n <= 0xFFFF) {
                $cp = chr(($n >> 12) + 0xE0) . chr((($n >> 6) & 0x3F) + 0x80) . chr(($n & 0x3F) + 0x80);
            } elseif ($n <= 0x10FFFF) {
                $cp = chr(($n >> 18) + 0xF0) . chr((($n >> 12) & 0x3F) + 0x80)
                    . chr((($n >> 6) & 0x3F) + 0x80) . chr(($n & 0x3F) + 0x80);
            } else {
                throw new Exception("Invalid UTF-8");
            }

            $output = substr($output, 0, $i) . $cp . substr($output, $i, $outputLength - 1);

            $i += strlen($cp);
        }

        return $output;
    }
538165
protected function _decodePart($input)
    {
        $n = static::INITIAL_N;
        $i = 0;
        $bias = static::INITIAL_BIAS;
        $output = '';

        $pos = strrpos($input, static::DELIMITER);
        if ($pos !== false) {
            $output = substr($input, 0, $pos++);
        } else {
            $pos = 0;
        }

        $outputLength = strlen($output);
        $inputLength = strlen($input);

        /* Punycode lookup is case-insensitive. */
        $input = Horde_String::lower($input);

        while ($pos < $inputLength) {
            $oldi = $i;
            $w = 1;

            for ($k = static::BASE; ; $k += static::BASE) {
                $digit = static::$_decodeTable[$input[$pos++]];
                $i = $i + ($digit * $w);
                $t = $this->_calculateThreshold($k, $bias);

                if ($digit < $t) {
                    break;
                }

                $w = $w * (static::BASE - $t);
            }

            $bias = $this->_adapt($i - $oldi, ++$outputLength, ($oldi === 0));
            $n = $n + (int) ($i / $outputLength);
            $i = $i % ($outputLength);

            $output = Horde_String::substr($output, 0, $i, 'UTF-8') .
                $this->_codePointToChar($n) .
                Horde_String::substr($output, $i, $outputLength - 1, 'UTF-8');

            ++$i;
        }

        return $output;
    }
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)
		);
	}
1363139
public static function unpad(string $input): string
    {
        // Determine the padding size by converting the final byte of the  
        // input to its decimal value
        $padsize = \ord(Str::substr($input, -1));

        // Return string minus the padding amount
        return Str::substr($input, 0, Str::strlen($input) - $padsize);
    }
1141631
function sanitize( $input ) {
		$options = [];

		if ( ! is_array( $input ) ) {
			$input = [];
		}

		if ( property_exists( $this, 'booleans' ) ) {
			foreach ( $this->booleans as $key ) {
				if ( empty( $input[ $key ] ) ) {
					$options[ $key ] = 0;
				} else {
					$options[ $key ] = 1;
				}
			}
		}

		if ( property_exists( $this, 'strings' ) ) {
			foreach ( $this->strings as $key ) {
				if ( empty( $input[ $key ] ) ) {
					unset( $options[ $key ] );
				} else {
					$options[ $key ] = sanitize_text_field( $input[ $key ] );
				}
			}
		}

		if ( property_exists( $this, 'urls' ) ) {
			foreach ( $this->urls as $key ) {
				if ( empty( $input[ $key ] ) ) {
					unset( $options[ $key ] );
				} else {
					$value = trim( strip_tags( stripslashes( $input[ $key ] ) ) );
					if ( $value ) {
						$options[ $key ] = \Pressbooks\Sanitize\canonicalize_url( $value );
					} else {
						unset( $options[ $key ] );
					}
				}
			}
		}

		if ( property_exists( $this, 'integers' ) ) {
			foreach ( $this->integers as $key ) {
				if ( empty( $input[ $key ] ) ) {
					unset( $options[ $key ] );
				} else {
					$options[ $key ] = absint( $input[ $key ] );
				}
			}
		}

		if ( property_exists( $this, 'floats' ) ) {
			foreach ( $this->floats as $key ) {
				if ( empty( $input[ $key ] ) ) {
					unset( $options[ $key ] );
				} else {
					$options[ $key ] = filter_var( $input[ $key ], FILTER_VALIDATE_FLOAT );
				}
			}
		}

		if ( property_exists( $this, 'predefined' ) ) {
			foreach ( $this->predefined as $key ) {
				if ( empty( $input[ $key ] ) ) {
					unset( $options[ $key ] );
				} else {
					$options[ $key ] = $input[ $key ];
				}
			}
		}

		return $options;
	}
407979
protected function cleanupLigatures($input)
    {
        $mapping = [
            'ﬀ' => 'ff',
            'ﬁ' => 'fi',
            'ﬂ' => 'fl',
            'ﬃ' => 'ffi',
            'ﬄ' => 'ffl',
            'ﬅ' => 'ft',
            'ﬆ' => 'st'
        ];

        return str_replace(array_keys($mapping), array_values($mapping), $input);
    }
912576
protected function _unserialize($input)
	{
		$data = @unserialize($input);

		if (is_array($data))
		{
			foreach ($data as $key => $val)
			{
				if (is_string($val))
				{
					$data[$key] = str_replace('{{slash}}', '\\', $val);
				}
			}

			return $data;
		}

		elseif ($data === false)
		{
			is_string($input) and $data = array($input);
		}

		return (is_string($data)) ? str_replace('{{slash}}', '\\', $data) : $data;
	}
469944
public function encrypt($input)
    {
        if (! $input) {
            return $input;
        }

        $methods = $this->getEncryptionMethods();
        $method  = reset($methods);
        $mkey    = key($methods);

        if ('mcrypt' == $method) {
            $result = $this->encryptMcrypt($input);
        } elseif ('null' == $method) {
            $result = $input;
        } else {
            $result = $this->encryptOpenSsl($input, $method);
        }

        return ":$mkey:" . base64_encode($result);
    }
707762
public function cleanURL( $input ) {
		// scheme and www
		$url = preg_replace( '/^((https?:|ftp:)?(\/\/))?(www\.)?/', '', $input );
		// fragment
		$url = preg_replace( '/#.*/', '', $url );
		// trailing slash
		$url = preg_replace( '{/$}', '', $url );

		return $url;
	}
1278464
public function decrypt($input)
    {
        // Decode the IV + data
        $input = base64_decode($input);
        // Remove the IV
        $iv = substr($input, 0, Cipher::IV_SIZE);
        // Return Decrypted Data
        return openssl_decrypt(substr($input, Cipher::IV_SIZE), "AES-256-CBC", $this->secretKey, 0, $iv);
    }
1317407
public static function base64encode($input) {
        return strtr(base64_encode($input), key(self::$urlSafe), current(self::$urlSafe));
    }
707241
protected function convertToValidCharacters(string $input): string
    {
        $converted = preg_replace(
            '/[\\p{C}\\p{Z}\\p{M}]+/u',
            '',
            \Normalizer::normalize(str_replace('～', '〜', $input), \Normalizer::FORM_KC)
        );
        if ($this->isRegExp($converted)) {
            $converted = trim($converted, '/');
        }
        return $converted;
    }
959326
public function wrap(array $input)
    {
        $out = [];
        foreach ($input as $line) {
            foreach ($this->chunk($line) as $new) {
                $out[] = $new;
            }
        }
        return $out;
    }
62007
public static function urlsafeB64Decode(string $input): string
    {
        $remainder = strlen($input) % 4;
        if ($remainder) {
            $padlen = 4 - $remainder;
            $input .= str_repeat('=', $padlen);
        }

        return base64_decode(strtr($input, '-_', '+/'));
    }