<?php

/**
 * Description of Common
 *  TODO: Extra: rename common class methods
* @author Mohammed Osman  <osmancode@gmail.com>
 */
class Common {

    /**
     * Function: sanitize
     * Returns a sanitized string, typically for URLs.
     *
     * Parameters:
     *     $string - The string to sanitize.
     *     $force_lowercase - Force the string to lowercase?
     *     $anal - If set to *true*, will remove all non-alphanumeric characters.
     */
    public static function sanitize($string, $force_lowercase = true, $anal = false, $replace = '-') {
        $clean = strip_tags($string);
        $strip = array("~", "`", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "=", "+", "[", "{", "]",
            "}", "\\", "|", ";", ":", "\"", "'", "&#8216;", "&#8217;", "&#8220;", "&#8221;", "&#8211;", "&#8212;",
            "â€”", "â€“", ",", "<", ".", ">", "/", "?", '-');
        $clean = trim(str_replace($strip, $replace, $clean));
        $clean = preg_replace('/[^\p{Arabic}\da-z-]/ui', $replace, $clean);
        $clean = preg_replace('/\s+/', $replace, $clean);
        $clean = preg_replace('/' . $replace . '+/', $replace, $clean);

        $clean = ($anal) ? preg_replace("/[^a-zA-Z0-9]/", "", $clean) : $clean;

        $clean = trim($clean, $replace);

        return ($force_lowercase) ?
                (function_exists('mb_strtolower')) ?
                        mb_strtolower($clean, 'UTF-8') :
                        strtolower($clean) :
                $clean;
    }

    /**
     * 
     * @param type $string
     * @param type $your_desired_width
     * @return type
     */
    public static function tokenTruncate($string, $your_desired_width) {
        $parts = preg_split('/([\s\n\r]+)/', $string, null, PREG_SPLIT_DELIM_CAPTURE);
        $parts_count = count($parts);

        $length = 0;
        $last_part = 0;
        for (; $last_part < $parts_count; ++$last_part) {

            $length += mb_strlen($parts[$last_part], 'utf-8');
            if ($length > $your_desired_width) {
                break;
            }
        }

        return implode(array_slice($parts, 0, $last_part));
    }

    /**
     * Returns user ip address behind proxy ip address
     * @return type
     */
    public static function getUserIP() {
        $client = @$_SERVER['HTTP_CLIENT_IP'];
        $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
        $remote = $_SERVER['REMOTE_ADDR'];

        if (filter_var($client, FILTER_VALIDATE_IP)) {
            $ip = $client;
        } elseif (filter_var($forward, FILTER_VALIDATE_IP)) {
            $ip = $forward;
        } else {
            $ip = $remote;
        }

        if ($ip === '::1') {
            $ip = '127.0.0.1';
        }

        return $ip;
    }

}