Location: PHPKode > scripts > Combo Validation > combo-validation/lib/common.inc.php
<?php
/**
 * 
 * @package    Library
 * @author Sina Salek <sina.salek.ws>
 * @revision hide@address.com/02/17 16:51:04
 * @revisionRange 139:140
 * @modified Modified
 */
 
/**
* 
*/
class cmfcString {
   
    /*
    $replacements['00username00']='jafar gholi';
    */
    //last name : replace_variables
    function replaceVariables($replacements,$text) {
        foreach ($replacements as $needle=>$replacement) {
            $text=str_replace($needle,$replacement,$text);
        }
        return $text;
    }
    
     
    /**
    * 
    * @previousNames is_email_valid
    */
    function isEmailValid($mailAddress) {
        if (preg_match("/^[0-9a-z]+(([\.\-_])[0-9a-z]+)*@[0-9a-z]+(([\.\-])[0-9a-z-]+)*\.[a-z]{2,4}$/i", $mailAddress)) {
            return true;
        } else {
            return false;
        }    
    }
    
}


class cmfcArray {
    
    function inArrayWildcard($needle, $haystack) {
        return true;
        #this function allows wildcards in the array to be searched
        foreach ($haystack as $value) {
            if (true === fnmatch($value, $needle)) {
                return true;
            }
        }
        return false;
    }
    
    
    /**
    * only works with 2 dimentional array;
    * @param array
    * @param array $value = array ('key'=>'id','value'=>5)
    * @previousNames cmfcGetArrayKeyByValue
    */
    function getKeyByValue($arr,$value) {
        $n=-1;
        foreach ($arr as $aKey=>$aItem) {
            $n++;
            //if (!isset($akey)) $aKey=$n;
            if (!is_array($aItem)) {
                if ($Item==$value) return $aKey;
            } else {
                if ($aItem[$value['key']]==$value['value']) {
                    return $aKey;
                }
            }
        }
    }
    
    
    /**
    * only works with 2 dimentional array;
    * @param array
    * @param array $value = array ('key'=>'id','value'=>5)
    * @previousNames cmfcGetArrayKeyByValue
    */
    function getKeyByValueWildcard($arr,$value,$multiValue=false) {
        $n=-1;
        foreach ($arr as $aKey=>$aItem) {
            $n++;
            //if (!isset($akey)) $aKey=$n;
            if (!is_array($aItem)) {
                if ($Item==$value) return $aKey;
            } else {
                if (fnmatch($value['value'],$aItem[$value['key']])===true) {
                    if($multiValue)
                        $aKeyArray[]=$aKey;
                    else
                        return $aKey;
                }
            }
        }
        return $aKeyArray;
    }
    
    
    
    /**
    * 
    * @previousNames array_key_insensitive
    */
    function keyInsensitive($needle, $haystick) {
       foreach($haystick as $key => $val) {
           if (strtolower($needle) == strtolower($key)) {
               return($key);
           }
       }
       return(false);
    }
    
    
    /**
    * 
    *
    * Similar to array_merge_recursive but keyed-valued are always overwritten.
    * Priority goes to the 2nd array.
    *
    * @static yes
    * @public yes
    * @param $paArray1 array
    * @param $paArray2 array
    * @return array
    */
    function mergeRecursive($paArray1, $paArray2)
    {
       if (!is_array($paArray1) or !is_array($paArray2)) { return $paArray2; }
       foreach ($paArray2 AS $sKey2 => $sValue2)
       {
           $paArray1[$sKey2] = cmfcArray::mergeRecursive(@$paArray1[$sKey2], $sValue2);
       }
       return $paArray1;
    }
    
    
    /**
    * <code>
    * $arr=array(
    *     'level1'=>array(
    *         'level2'=>5
    *     )
    * )
    * cmfcArray::getArrayValueByPath($arr,array('level1','level2'))
    * </code>
    * result is "5"
    * @param $arr array
    * @param $path array
    * return variant //false on invalid path
    */
    function getValueByPath($arr,$path) {
        $r=$arr;
        if (!is_array($path)) return false;
        foreach ($path as $key) {
            if (isset($r[$key]))
                $r=$r[$key];
            else
                return false;
        }
        return $r;
    }
    
    
    /**
    * <code>
    * $arr=array(
    *     'level1'=>array(
    *         'level2'=>5
    *     )
    * )
    * cmfcArray::setValueByPath($arr,array('level1','level2'),12)
    * //value of level2 array is now "12"
    * </code>
    * @author Sina Salek <sina.salek.ws>
    * @param array
    * @param array
    * @param variant
    * @param boolean
    * @return variant //false on invalid path
    * @previousNames arrayPath,cmfArrayPath
    */
    function setValueByPath($arr,$path,$value,$createPath=false) {
        if ($createPath)
            $r=&$arr;
        else    
            $r=$arr;
        if (!is_array($path)) return false;
        foreach ($path as $key) {
            if ($createPath and !isset($r[$key])) {
                $r[$key]='';
            }
            if (isset($r[$key])) {
                $r=&$r[$key];
            } else {
                return false;
            }
        }

        $r=$value;
        
        return $r;
    }
    
   
    
    
    /**
     * set the pointer of an array to the given key
     * 
     * @author Sina Salek <sina.salek.ws>
     * @param array:pointer $array
     * @param variant $key
     * @return unknown
     * @previousNames array_set_current,cmfArraySetCurrent
     */
    function setCurrent(&$array, $key)
    {
       reset($array);
       while (current($array)!==FALSE){
           if (key($array) == $key) {
               break;
           }
           next($array);
       }
       return current($array);
    }
    
    
    /**
    * 
    *converts this :
    * <code>
    * Array (
    *   [image] => Array (
    *       [name] => Array (
    *           [1] => Array (
    *               [columns] => Array (
    *                   [file_name] => Water lilies.jpg
    *                )
    *            )
    *       )
    *    )
    * )
    * </code>
    *    to :
    * <code>
    * array(5) { [0]=> string(5) "image" [1]=> string(4) "name" [2]=> int(1) [3]=> string(7) "columns" [4]=> string(9) "file_name" }
    * </code>
    *
    * @previousNames convertNestedArrayToFlatArray,cmfConvertNestedArrayToFlatArray
    */
    function convertToSimilarFlatArray($myArray) {
        $currArr=$myArray;
        while (is_array($currArr)) {
                $path[]=key($currArr);
                $currArr=reset($currArr);
        };
        return $path;
    }
    
    
    /**
    * flatten multidimensional array to one dimension
    * preserves keys by generating a key for the flattened array which consists of the
    * key-path of the multidimensional array separated by $Separator
    * usage: array convertToFlatArray( array Array [, string Separator] )
    * 
    * convert this
    * <code>
    * $arr=array(
    *     'a'=>1,
    *     'b'=>array(
    *         'ba'=>2,
    *         'bb'=>3
    *     )
    * )
    * </code>
    * to :
    * <code>
    * array(
    *     'a'=>1,
    *     'b.ba'=>2,
    *     'b.bb'=>3
    * )
    * </code>
    * 
    */
    function convertToFlatArray($Array,$Separator='.',$FlattenedKey='') {        
        $FlattenedArray=Array();
        foreach($Array as $Key => $Value) {
            if(is_Array($Value)) {
                $_FlattenedKey=(strlen($FlattenedKey)>0?$FlattenedKey.$Separator:"").$Key;
                  $FlattenedArray=array_merge(
                      $FlattenedArray,
                    cmfcArray::convertToFlatArray($Value,$Separator,$_FlattenedKey)
                );                
            } else {
                $_FlattenedKey=(strlen($FlattenedKey)>0?$FlattenedKey.$Separator:"").$Key;
                $FlattenedArray[$_FlattenedKey]=$Value;
            }
        }
        return $FlattenedArray;
    }
    
    

    /**
     * if key does not exist in array, compiler get an Notice or Warning message, this function is for preventing this kind of messages
     * $key is an variant, you can use it in three way
     * Description :
     * $key=$index
     * //$key='index1,index2,98';
     * $key=array($index1,$index2,$index3);
     *
     * @param array $array
     * @param variant $key
     * @return variant
     * @previousNames array_value,cmfArrayValue
     */
    function getValue($array,$key)
    {
        $result=null;
        if (isset($array))
            if (!empty($array) and is_array($array))
            {
                if (!is_array($key))
                {
                    if (array_key_exists($key,$array)) { $result=$array[$key]; }
                } else
                {
                    $result=$array;
                    foreach ($key as $k)
                        if (array_key_exists($k,$result)) { $result=$result[$k];}
                    else { $result=null; break;}
                }
            }
        return $result;
    }
    
    
    /**
    * @previousNames arrayPath,cmfArrayPath
    */
    function &path(&$array,$path,$createIfNotExists=false) {
            if(!is_array($array)) {
                    trigger_error('array_path(): First argument should be an array', E_USER_WARNING);
            }
            settype($path, 'array');

            $offset =& $array;
            foreach ($path as $index) {
                    if (!isset($offset[$index])) {
                            if ($createIfNotExists)
                                    $offset[$index]='';
                            else {
                                    trigger_error("Undefined offset: $index");
                                    return false;
                            }
                    }
                    $offset =& $offset[$index];
            }
            return $offset;
    }

}




class cmfcHtml {
        
    
    
    function printr($var, $echo = true){
        if (!$var)
            $var = 'Empty/False/Null';

        if ($echo){
            echo '<pre dir="ltr" style="text-align:left; background:#FFCC99; color:#000000; font-family:Verdana, Arial, Helvetica, sans-serif; overflow:auto">'.print_r($var, true).'</pre>';
        } else return print_r($var, true);
    }
    
        
    
    /**
    * Convert PHP data structure to Javascript
    */
    function phpToJavascript($var, $tabs = 0,$singleLine=false) {
        if (is_numeric($var)) {
            return $var;
        }
        
        if (is_bool($var)) {
            return ($var===true)?'true':'false';
        }

        if (is_string($var)) {
            return "'" . cmfcHtml::javascriptEncode($var) . "'";
        }

        if (is_array($var)) {
            $useObject = false;

            if ($singleLine==true) $newLineChar=''; else $newLineChar="\n";
            
            foreach(array_keys($var) as $k) {
                if(!is_numeric($k)) $useObject = true;
            }
            
            $js = array();
            foreach($var as $k => $v) {
                $i = "";
                if($useObject) {
                    if(preg_match('#^[a-zA-Z]+[a-zA-Z0-9]*$#', $k)) {
                        if (in_array(strtolower($k),array('function')))
                            $k="'$k'";
                        $i .= "$k: ";
                    } else {
                        $i .= "'$k': ";
                    }
                }

                $i .= cmfcHtml::phpToJavascript($v, $tabs + 1,$singleLine);
                $js[] = $i;
            }
            
            if ($singleLine) $tabs=0;
        
            if($useObject) {
                $ret = "{"."$newLineChar" . cmfcHtml::javascriptTabify(implode(",$newLineChar", $js), $tabs) . "$newLineChar"."}";
            } else {
                $ret = "[$newLineChar" . cmfcHtml::javascriptTabify(implode(",$newLineChar", $js), $tabs) . "$newLineChar]";
            }
            return $ret;
        }

        return 'null';
    }


    /**
    * Like htmlspecialchars() except for javascript strings.
    */
    function javascriptEncode($string) {
        static $strings = "\\,\",',%,&,<,>,{,},@,\n,\r";
        
        if(!is_array($strings)) {
            $tr = array();
            foreach(explode(',', $strings) as $chr) {
                $tr[$chr] = sprintf('\x%02X', ord($chr));
            }
            $strings = $tr;
        }
        
        return strtr($string, $strings);
    }

    /**
    * Just space-tab indent some text
    */
    function javascriptTabify($text, $tabs) {
        if($text) {
            return str_repeat("  ", $tabs) . preg_replace('/\n(.)/', "\n" . str_repeat("  ", $tabs) . "\$1", $text);
        }
    }
    
    
    /**
    * convert php value to javascript
    * @param variant $var
    * @param interger $tab //number of tab chars for indent
    * @param boolean $singleLine //result as single line
    */
    function phpParamToJs($var,$tabs = 0,$singleLine=true) {
        //if (is_string($var)) return $var;
        return cmfcHtml::phpToJavascript($var,0,true);
    }
    
    /**
    * convert php values to javascript
    * @param variant $var
    */
    function phpParamsToJs($vars) {
        foreach ($vars as $key=>$var) {
            $vars[$key]=cmfcHtml::phpParamToJs($var);
        }
        return $vars;
    }
    
    /**
    * fixing javascript incompatibility with number as array key
    * @param string $array
    */
    function getJavascriptCompatibleArray($array) {
        $result=array();
        foreach ($array as $key=>$value) {
            $key="_$key";
            $result[$key]=$value;
        }
        
        return $result;
    }
    /**
    * @shortName getJsCAK
    */
    function getJavascriptCompatibleArrayKey($key) {
        if (is_numeric($key)) $key="_$key";
        $key=cmfcHtml::phpParamToJs($key);
        return $key;
    }
    
    /**
    * short name version of getJavascriptCompatibleArrayKey()
    * @fullName getJavascriptCompatibleArrayKey
    */
    function getJsCAK($key) {
        return cmfcHtml::getJavascriptCompatibleArrayKey($key);
    }
      
    
    /**
    * convert 'row[1][columns][name]' to array('row','1','columns','name')
    * @param $name string
    * return array
    */
    function fieldNameToArrayPath($name) {
        preg_match_all('/[^\\[\\]]+/', $name, $result, PREG_PATTERN_ORDER);
        return $result = $result[0];
    }
    
    /**
    * @example
    * <code>
    *     fieldNamePrependBaseName('row[1][columns][name]','headName');
    *     //result is 'headerName[row][1][columns][name]'
    * </code>
    * 
    * @param string $name
    * @param string $baseName
    * return array
    */
    function fieldNamePrependBaseName($name,$baseName) {
        $name = preg_replace('/^([^\\[\\]]+)(.*)/', $baseName.'[$1]$2', $name);
        return $name;
    }
    
    
    /**
    * get 'row[1][columns][name]' as name
    * @param $name string
    * return array
    */
    function getFieldNameHeadName($name) {
        if (preg_match('/\\[([^\\[\\]]+)\\]$/', $name, $regs)) {
            $name = $regs[1];
        }    
        return $name;
    }
    
        
    
    /**
    * merges $_FILES with $_POST for simplicity
    * WARNING : it has a bug when there is more than file field!!
    * @previousNames mergePhpFilesAndPhpPost,cmfMergePhpFilesAndPhpPost
    */
    function mergePhpFilesAndPhpPost($phpFiles,$phpPost,$keepPostValue=false) {
            $result=array();
            foreach ($phpFiles as $baseName=>$fileInfo) {
                    foreach ($fileInfo as $infoName=>$info) {
                            $result[$infoName][$baseName]=$info;
                            $infoPath=cmfcArray::convertToSimilarFlatArray($result[$infoName]);
                            $fileInfoValue=&cmfArrayPath($result[$infoName],$infoPath);
                            //--(BEGIN)-->Merging

                            $infoPath=cmfcArray::convertToSimilarFlatArray($result[$infoName]);
                            //var_dump($infoPath);echo '<br/>';
                            $fileInfoValue=&cmfcArray::Path($result[$infoName],$infoPath);

                            $postInfoValue=&cmfArrayPath($phpPost,$infoPath,true);
                            if ($keepPostValue) {
                                    $fileInfoValue['value']=$postInfoValue;
                                    $postInfoValue[$infoName]=$fileInfoValue;
                            } else {
                                    $postInfoValue[$infoName]=$fileInfoValue;
                            }
                            //--(END)-->Meging
                    }
            }
            echo '<pre>';print_r($result);echo '</pre>';
            return $phpPost;
    }

    /**
    * @previousNames cmfMakePhpFilesLikePhpPost,makePhpFilesLikePhpPost
    */
    function makePhpFilesLikePhpPost($phpFiles) {
            $result=array();
            foreach ($phpFiles as $baseName=>$fileInfo) {
                    foreach ($fileInfo as $infoName=>$info) {
                            $result[$infoName][$baseName]=$info;
                    }
            }
            return $result;
    }
}




class cmfcClass {
    /** 
    * If You Want to have just variables of end class, not variables of end class and its parents, this function is your solution    
    * @return array
    */

    function getObjectVars(&$obj)
    {
        $parent_object_vars=get_class_vars(get_parent_class($obj));
        $object_vars=get_object_vars($obj);
        foreach ($parent_object_vars as $key=>$value)
            foreach ($object_vars as $_key=>$_value)
                if ($key==$_key) { unset($object_vars[$_key]);  break; }
        return $object_vars;
    }    
}



/**
* for backward compatibility with php4 :
*     - rename array_merge() to cmfcPhp4::array_merge()
*     - get_class() to cmfcPhp4::get_class()
*     - get_parent_class() to cmfcPhp4::get_parent_class()
*     - get_class_methods() to cmfcPhp4::get_class_methods()
*     - strrpos() to cmfcPhp4::get_parent_class()
*     - strripos() to cmfcPhp4::strripos()
*     - ip2long() to cmfcPhp4::ip2long()
*    - $this=$object does not allowed anymore
*    - now are case-sensitive
*        __CLASS__, __METHOD__, and __FUNCTION__
*     - An object with no properties is no longer considered "empty"
*/
class cmfcPhp4 {
    /**
    * as of php5 was changed to accept only arrays. 
    * If a non-array variable is passed, a E_WARNING will be thrown for every such parameter. 
    * Be careful because your code may start emitting E_WARNING out of the blue. 
    * 
    * @changelog
    *     - tested
    */
    function array_merge() {
        $args = func_get_args();
        foreach ($args as $k=>$value) {
            if (!is_array($value)) $value=array();
            $args[$k]=$value;
        }
        return call_user_func_array("array_merge", $args);
    }
    
    /**
    * as of php5 return the name of the classes/methods as they were declared (
    * case-sensitive) which may lead to problems in older scripts that rely
    * on the previous behaviour (the class/method name was always returned lowercased).
    * A possible solution is to search for those functions in all your scripts and use strtolower(). 
    */
    function get_class() {
        $args = func_get_args();
        return strtolower(call_user_func_array("get_class", $args));
    }

    /**
    * as of php5 return the name of the classes/methods as they were declared (
    * case-sensitive) which may lead to problems in older scripts that rely
    * on the previous behaviour (the class/method name was always returned lowercased).
    * A possible solution is to search for those functions in all your scripts and use strtolower(). 
    */    
    function get_parent_class() {
        $args = func_get_args();
        return strtolower(call_user_func_array("get_parent_class", $args));
    }
    
    /**
    * as of php5 return the name of the classes/methods as they were declared (
    * case-sensitive) which may lead to problems in older scripts that rely
    * on the previous behaviour (the class/method name was always returned lowercased).
    * A possible solution is to search for those functions in all your scripts and use strtolower(). 
    */
    function get_class_methods() {
        $args = func_get_args();
        $result=call_user_func_array("get_class_methods", $args);
        if (is_array($result))
            foreach ($result as $key=>$value) {
                $result[$key]=strtolower($value);
            }
        return $result;
    }
    
    /**
    * as of php5 now use the entire string as a needle.
    */
    function strrpos ($haystack, $needle, $offset)
    {
        $size = strlen ($haystack);
        $pos = strpos (strrev($haystack), strrev($needle), $size - $offset);
      
        if ($pos === false)
            return false;
      
        return $size - $pos - strlen($needle);
    }
    
    /**
    * as of php5 now use the entire string as a needle.
    */
    function strripos($haystack, $needle, $offset=0) {
        if($offset<0){
            $temp_cut = strrev(  substr( $haystack, 0, abs($offset) )  );
        }
        else{
            $temp_cut = strrev(  substr( $haystack, $offset )  );
        }
        $pos = strlen($haystack) - (strpos($temp_cut, strrev($needle)) + $offset + strlen($needle));
        if ($pos == strlen($haystack)) { $pos = 0; }
       
        if(strpos($temp_cut, strrev($needle))===false){
             return false;
        }
        else return $pos;
    }/* endfunction strripos*/
    
    /**
    * as of php5 now returns FALSE when an invalid IP address is passed as 
    * argument to the function, and no longer -1.
    */
    function ip2long() {
        $args = func_get_args();
        $result=call_user_func_array("ip2long", $args);
        if ($result===false) $result=-1;
        return $result;
    }
    
    /**
    * as of php5 An object with no properties is no longer considered "empty" 
    * @note does not work
    */
    function _empty($var) {
        if (is_object($var) and empty($var)===false) {
            //if (empty(get_object_vars($var)))
                
        }
    }

}

class cmfcUrl {
    /**
    * @desc exclude a query string variable and its value from REQUEST_URI
    * @param array('qsvn1','qsvn2')
    */
    function excludeQueryStringVars($qsVars,$resourceType='get') {
        //([^\?]*)\?(([^&=]*)=([^&=]*)&?)*
        if ($resourceType=='request_uri') {
            if (preg_match('/([^\\?]*)\\?(([^&=]*)=([^&=]*)&?)*/', $_SERVER['REQUEST_URI'], $regs)) {
                $result = $regs[1];
            } else {
                $result = "";
            }
        } elseif ($resourceType=='get') {
            $get=$_GET;
            foreach ($qsVars as $qsVar) {
                unset($get[$qsVar]);
            }
            return cmfcUrl::arrayToQueryString($get);
        }
        
        trigger_error('$resourceType parameter only accept ("get","request_uri") but you entered "'.$resourceType.'"',E_USER_ERROR);
    }
    
    /**
    * @previousNames : glArrayToQueryString , cmfcArrayToQueryString
    */
    function arrayToQueryString($varArray,$mainName=null) {
        if (is_array($varArray)) {
            $result='';
            foreach ($varArray as $name=>$value) {
                //if (!empty($parentName)) {$name=$parentName.'['.$name.']';}
                if (!is_array($value)) {
                    $value=urlencode($value);
                    if (empty($mainName))
                        $result.="$name=$value&";
                    else
                        $result.="$mainName"."[$name]=$value&";
                } else {
                    if (!empty($mainName))
                        $name=$mainName.'['.$name.']';
                    $result.=cmfcUrl::arrayToQueryString($value,$name);
                }
            }
        }
        return $result;
    }
    
    /**
    * @previousNames : is_valid_url , cmfIsValidUrl
    */
    function isValid($url) {
            if (preg_match ('/^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i', $url))
                    return true;
            else
                    return false;
    }
}
?>
Return current item: Combo Validation