<?php
	function fo3_date( $format , $time = null ) {
		if (!isset( $time )) $time = fo3_time();
		return date( $format , $time );
	}

	function fo3_global_numformat_function_callback( $string ) {
		return number_format( $string , 0 , "." , " " );
	}

	function fo3_time() {
		return time()+FNTH_get_timewarp();
	}

	function fo3_nextday( $offset = 0 ) {
		$curtime = fo3_time();
		$tm = localtime( $curtime , true );
		return $offset + mktime(
			0 , 0 , 0 ,
			$tm["tm_mon"]+1,
			$tm["tm_mday"],
			$tm["tm_year"]+1900 );
	}

	function fo3_convert_YmdHis_to_unix( $string ) {
		$year = substr( $string , 0 , 4 );
		$month = substr( $string , 5 , 2 );
		$day = substr( $string , 8 , 2 );
		$hour = substr( $string , 11 , 2 );
		$min = substr( $string , 14 , 2 );
		$sec = substr( $string , 17 , 2 );
		return mktime( $hour , $min , $sec , $month , $day , $year );
	}

	function fo3_is_email_valid( $email ) {
		$isValid = true;
		$atIndex = strrpos($email, "@");
		if (is_bool($atIndex) && !$atIndex) {
			$isValid = false;
		} else {
			$domain = substr($email, $atIndex+1);
			$local = substr($email, 0, $atIndex);
			$localLen = strlen($local);
			$domainLen = strlen($domain);
			if ($localLen < 1 || $localLen > 64) {
				// local part length exceeded
				$isValid = false;
			} else if ($domainLen < 1 || $domainLen > 255) {
				// domain part length exceeded
				$isValid = false;
			} else if ($local[0] == '.' || $local[$localLen-1] == '.') {
				// local part starts or ends with '.'
				$isValid = false;
			} else if (preg_match('/\\.\\./', $local)) {
				// local part has two consecutive dots
				$isValid = false;
			} else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)) {
				// character not valid in domain part
				$isValid = false;
			} else if (preg_match('/\\.\\./', $domain)) {
				// domain part has two consecutive dots
				$isValid = false;
			} else if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',str_replace("\\\\","",$local))) {
				// character not valid in local part unless 
				// local part is quoted
				if (!preg_match('/^"(\\\\"|[^"])+"$/',str_replace("\\\\","",$local))) {
					$isValid = false;
				}
			} else if (strpos( $domain , "." )===false) {
				// nincs is pont benne egyaltalan
				$isValid = false;
			}
			/* FIXME - kiszedni tesztek vegen
			if ($isValid && !(checkdnsrr($domain,"MX") ||  checkdnsrr($domain,"A"))) {
				// domain not found in DNS
				$isValid = false;
			}
			*/
		}
		return $isValid;
	}

	function fo3_xlat_horvert( $data , $cols = 4 ) {
		$retval = array();
		$len = count( $data );
		if (!$len) return $retval;
		$colsize = (int)($len/$cols);
		$mod = $len%$cols;

		// temp
		foreach ($data as $id => $d) $temp[] = array( "id" => $id , "val" => $d );
		// slice into columns
		$c = array();
		$o = 0;
		for ($x=0;$x<$cols;$x++) {
			$c[$x]=array();
			$ac=($x<$mod) ? $colsize+1 : $colsize;
			for ($i=0;$i<$ac;$i++) {
				if ($o>=$len) break;
				$c[$x][]=$temp[$o];$o++;
			}
		}
		// merge columns back
		$ac=($mod) ? $colsize + 1 : $colsize;
		for ($y=0;$y<$ac;$y++) for ($x=0;$x<$cols;$x++)
			if (isset( $c[$x][$y] )) $retval[$c[$x][$y]["id"]]=$c[$x][$y]["val"];
		return $retval;
	}

	function fo3_equ_delimiters( $s ) {
		$s = trim( str_replace(
			array( "+","\\","&","-",",",".",";",":","!","?","(",")","/","\r","\n" ),
			array( " "," " ," "," "," "," "," "," "," "," "," "," "," "," " ," "  ),$s ));
		while (strpos( $s , "  " )!==false) $s = str_replace( "  " , " " , $s );
		return $s;
	}

	function fo3_generate_alias( $s , $num = 1 , $lowercase = true ) {
		$s = FNTH_strdeacute( $s );
		if ($lowercase) $s = FNTH_strtolower( $s );
		$s = fo3_equ_delimiters( $s );
		$retval = str_replace( " " , "-" , $s );
		if ($num>1) $retval.=sprintf( "-%d" , $num );
		return $retval;
	}
	
	function fo3_add_js_var( $key , $value ) {
		if (!isset( $GLOBALS["fo3_js_vars"] )) $GLOBALS["fo3_js_vars"]=array();
		$GLOBALS["fo3_js_vars"][$key]=$value;
	}

	function fo3_render_js_variables() {
		if (!isset( $GLOBALS["fo3_js_vars"] )) return false;
		$retval = "";
		$retval.="\naJSVars = new Object();\n";
		foreach ($GLOBALS["fo3_js_vars"] as $k => $v)
			$retval.=sprintf( "aJSVars.%s='%s';\n" , $k , $v );
		return $retval;
	}

	function fo3_exit() {
		exit();
	}

	function fo3_pwgen() {
		$index = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
		$len = strlen( $index );
		$retval = "";
		for ($i=0;$i<8;$i++)
			$retval.=substr( $index , rand()%$len , 1 );
		return $retval;
	}

	function fo3_use_global_css( $name ) {
		$uid = "global_css_".$name;
		FNTHPage::setPageCSSHead( $uid , ( $GLOBALS["site_www"]."/design/rp/css/globals/".$name ) );
	}

	function fo3_model( $model ) {
		require_once( $GLOBALS["site_root"] . "/includes/models/" . $model . ".inc.php" );
	}

	function fo3_render_job_recipients( $data , $showcustom = false , $allcustom = false ) {
		fo3_model( "Member" );
		$retval = "";
		switch ($data["type"]) {
		case "all": return __("recipients_All");
		case "freelancers": return __("recipients_Freelancers");
		case "agencies": return __("recipients_Agencies");
		case "custom":
			$retval=__("recipients_Custom");
			$mm = new MemberModel();
			$ds = $mm->getMembersFromMemberIds( array_values( $data["custom_recipients"] ) );
			if ($showcustom) {
				if (!empty( $ds )) {
					$retval.= "<ul class=\"recipients\">";
					if ($allcustom) {
						foreach ($ds as $member) {
							// TODO english name on english page
							$retval.=sprintf( "<li>%s</li>" , $member["user_name"] );
						}
					} else {
						$mmm = new MyMemberModel();
						$found = false;
						foreach ($ds as $member) {
							if ($member["member_id"]==$mmm->getLoggedInMemberId() ) {
								$retval.=sprintf( "<li>%s</li>" , $member["user_name"] );
								$found = true;
							}
						}
						$num = ($found) ? count($ds)-1 : count( $ds );
						if ($num)
							$retval.=sprintf( "<li>%d %s</li>" , $num , __("other_recipients") );
					}
					$retval.="</ul>";
				}
			} else {
				if (!empty( $ds ))
					$retval.=sprintf( " (%d)" , count($ds) );
			}
			return $retval;
		}
		return $retval;
	}

	function fo3_log( $str ) {
		$x = fopen( "/tmp/fordit.log" , "a" );
		if (!$x) return;
		$s = sprintf( "%s: %s\n" , fo3_date("Y-m-d H:i:s") , $str );
		fputs( $x , $s );
		fclose( $x );
	}

	function fo3_get_mimetype_icon_path( $mimetype ) {
		switch ($mimetype) {
		case "audio/mpeg":
		case "audio/mpg":
		case "audio/wav":
		case "audio/wave":
			$r="wave";break;
		case "image/gif":
		case "image/tiff":
		case "image/jpeg":
		case "image/tga":
		case "image/bmp":
			$r="image";break;
		case "message/rfc822":
			$r="email";break;
		case "application/pdf":
			$r="pdf";break;
		case "application/msword":
			$r="word";break;
		case "application/vnd.ms-excel":
			$r="excel";break;
		default:
			$r="text";break;
		}
		return sprintf( "%s/images/icons/app/%s.png" , $GLOBALS["site_www"] , $r );
	}

	function fo3_render_boolean_yesno( $val ) {
		return ($val=="t") ? __("_yes_") : __("_no_");
	}

	function __unserialize($sObject) {
		$__ret = trim( $sObject );
		// $__ret =preg_replace('!s:(\d+):"(.*?)";!e', "'s:'.strlen('$2').':\"$2\";'", $sObject );
		return unserialize($__ret);
	}
	
	function fo3_format_tstamp_to_screen( $s ) {
		return str_replace( "-" , "." , substr( $s , 0 , 19 ) );
	}

	function fo3_format_date_to_screen( $s ) {
		return substr( fo3_format_tstamp_to_screen( $s ) , 0 , 10 );
	}

	function fo3_format_textual_date_to_screen( $s ) {
		$im = substr( $s , 5 , 2 );
		switch ($im) {
		default:
			FNTH_da( $s );
		case "01": $m="január";break;
		case "02": $m="február";break;
		case "03": $m="március";break;
		case "04": $m="április";break;
		case "05": $m="május";break;
		case "06": $m="június";break;
		case "07": $m="július";break;
		case "08": $m="augusztus";break;
		case "09": $m="szeptember";break;
		case "10": $m="október";break;
		case "11": $m="november";break;
		case "12": $m="december";break;
		}
		return sprintf( "%04d. %s %d.",
			substr( $s , 0 , 4 ),
			$m,
			(int) substr( $s , 8 , 10 ) );
	}
	
	function fo3_format_date_break( $s ) {
		$d = explode( " " , $s );
		// $d[0]=sprintf( "<b>%s</b>" , $d[0] );
		return implode( "<br/>" , $d );
	}
	
	function fo3_format_timestamp_to_screen( $s , $break = false ) {
		$retval =substr( fo3_format_tstamp_to_screen( $s ) , 0 , 19 );
		if ($break) $retval = fo3_format_date_break( $retval );
		return $retval;
	}
	
	function fo3_format_datetime_to_screen( $s , $break = false ) {
		$retval = substr( fo3_format_tstamp_to_screen( $s ) , 0 , 16 );
		if ($break) $retval = fo3_format_date_break( $retval );
		return $retval;
	}

	function fo3_get_language_editor_mode( $filter_admin = false ) {
		if (!isset( $_COOKIE["language_editor_mode"] )) return false;
		if (!$_COOKIE["language_editor_mode"]) return false;
		return true;
	}

	function fo3_set_language_editor_mode( $val = false ) {
		setcookie( "language_editor_mode" , $val , 0 , "/" );
	}

	function fo3_fullurl( $url ) {
		if (substr( $url , 0 , 7 )=="http://") return $url;
		return "http://".$_SERVER["SERVER_NAME"].$url;
	}

	function fo3_render_yesno_from_db( $v ) {
		return ($v=="t") ? __("_yes_") : __("_no_");
	}

	function fo3_generate_unique_alias( $str , $is_used_callback = "" , $params = null ) {
		$num = 0;
		$used = true;
		while ($used) {
			$num++;
			$lowercase = (isset( $params["lowercase"] )) ? $params["lowercase"] : true;
			$alias = fo3_generate_alias( $str , $num , $lowercase );
			if (is_array( $is_used_callback )) {
				$obj = $is_used_callback[0];
				$meth = $is_used_callback[1];
				$used = $obj->$meth( $alias , $params );
			} else if (!empty( $is_used_callback )) {
				$used = $is_used_callback( $alias , $params );
			} else $used = false;
		}
		return $alias;
	}

	function fo3_get_remote_ipaddress() {
		if (!isset( $_SERVER["REMOTE_ADDR"] )) return "-";
		return $_SERVER["REMOTE_ADDR"];
	}

	function fo3_set_meta_description( $desc ) { $GLOBALS["fo3_meta_description"]=$desc; }
	function fo3_get_meta_description( ) { return $GLOBALS["fo3_meta_description"]; }

	function fo3_set_meta_keywords( $keywords ) { $GLOBALS["fo3_meta_keywords"]=$keywords; }
	function fo3_get_meta_keywords( ) { return $GLOBALS["fo3_meta_keywords"]; }
	function fo3_set_page_title( $title ) { $GLOBALS["fo3_page_title"]=$title; }
	function fo3_get_page_title( ) { return $GLOBALS["fo3_page_title"]; }

	function fo3_form_change_warning( $form = "" , $extra_callback = "" ) {
		FNTHPage::setPageHead( "form_change_warning_js",FNTH_embed_js_file( $GLOBALS["site_www"]."/design/rp/js/form_change_warning.js" ) );
		fo3_add_js_langdef( "Form_is_modified" );
		if (empty( $form )) return;
		$call = sprintf( "FormChangeWarning(%s%s);",$form,
			(!empty( $extra_callback )) ? ",".$extra_callback : "" );
		FNTHPage::addUniquePageFullInit( $call );
	}

	function fo3_object_change_warning( $objid = "" , $extra_message , $dirty_default = true ) {
		FNTHPage::setPageHead( "form_change_warning_js",FNTH_embed_js_file( $GLOBALS["site_www"]."/design/rp/js/form_change_warning.js" ) );
		$call = sprintf( "ObjectChangeWarning('%s','%s',%s);",$objid , $extra_message,
			($dirty_default) ? "true" : "false" );
		FNTHPage::addUniquePageFullInit( $call );
	}

	function fo3_get_http_referer_uri( ) {
		if (!isset( $_SESSION["http_referer"] )) return "";
		return $_SESSION["http_referer"];
	}

	function fo3_break_contact( $str , $last = 0 ) {
		if (!$last) {
			$last = strlen( $str ) - 20;
			if ($last<10) $last=10;
			if ($last>20) $last=20;
		}
		return "..." . substr( $str , -$last );
	}

	function fo3_break_email( $str ) {
		$pos = strpos( $str , "@" );
		if ($pos===false) return fo3_break_contact( $str );
		$e1 = substr( $str , 0 , $pos );
		$e2 = substr( $str , $pos + 1 );
		return str_repeat( "*" , strlen( $e1 ) ) . "@" . $e2;
	}

	function fo3_break_phone( $str , $c = 5 ) {
		$len = strlen( $str );
		$e1 = substr( $str , 0 , $len - $c );
		$e2 = substr( $str , $len-$c );
		// $e1 = str_replace( array( "0","1","2","3","4","5","6","7","8","9" ) , array( "*","*","*","*","*","*","*","*","*","*" ) , $e1 );
		$e1 = str_repeat( "*" , strlen( $e1 ) );
		return $e1.$e2;
	}
	
	function fo3_break_url( $str ) {
		if (empty( $str )) return "";
		return fo3_break_contact( $str , 8 );
		return "http://".fo3_break_contact( $str );
	}	

?>
