<?php
function con(){
global $globalConfig;
$db=new DB($globalConfig['dbase'], $globalConfig['dbhost'],$globalConfig['dbuser'], $globalConfig['dbpass']);
return $db;
}
// debug message: 1 = info 2 = congratulation 3 = error
function debug_message($message, $kind, $width = false){
	if(!$width){
		$width = '80';
	}
	switch($kind){
		case 1:
			$message_box = '<div class="note" align="center" style="padding:6px;" style="margin:20px auto ; padding: 0 .7em; width:'.$width.'%;"> 
<p align="center">'.$message.'</p>
</div>';
		break;
		
		case 2:
			$message_box = '<div class="congratulation" align="center" style="margin:20px auto ; padding: 0 .7em; width:'.$width.'%;"> 
<p align="center">'.$message.'</p>
</div>';
		break;

		case 3:
			$message_box = '<div class="warning" align="center" style="margin:20px auto ; padding: 0 .7em; width:'.$width.'%;"> 
<p align="center">'.$message.'</p>
</div>';
		break;
	}
return $message_box;
}

function show_error($error){
global $globalConfig;

switch((int)$error){
	
		case 1:
			$message =$globalConfig['errorNoCookies'];
		break;
		
		case 2:
			$message =$globalConfig['errorDelay'];
		break;
		
		case 3:
			$message =$globalConfig['errorNoAdmin'];
		break;
		
		case 4:
			$message =$globalConfig['errorNoGroup'];
		break;
		
		case 5:
			$message =$globalConfig['errorNoLogin'];
		break;		
		
		case 6:
			$message =$globalConfig['errorInvalid'];
		break;
		
	
	}
return '<div dir="rtl" style="color:red; background-color:#FFC4C4; width:100%; border-bottom:1px solid #F30; border-top:1px solid #F30; font-size:11px; font-weight:normal; text-align:right;"><img src="images/alert.png" align="top"> '.$message.'</div>';
}
//download
function download_file($id,$tableid,$nametable,$file,$sorce){
      $query="select * from $nametable where $tableid=$id";
      $result=mysql_query($query) or die ("Bad Query<br>".$query);  
      $row=mysql_fetch_array($result);
	  $filename=$row[$file];
          //  $filename = realpath($filename);
            $file_extension = strtolower(substr(strrchr($filename,"."),1));
			switch ($file_extension) {
                case "pdf": $ctype="application/pdf"; break;
                case "exe": $ctype="application/octet-stream"; break;
                case "zip": $ctype="application/zip"; break;
                case "doc": $ctype="application/msword"; break;
                case "doc": case "docx":
                case "doc": $ctype="application/msword"; break;
			    case "xls": $ctype="application/vnd.ms-excel"; break;
                case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
                case "gif": $ctype="image/gif"; break;
                case "png": $ctype="image/png"; break;
                case "jpe": case "jpeg":
                case "jpg": $ctype="image/jpg"; break;
                default: $ctype="application/force-download";
            }
			header("Pragma: public");
            header("Expires: 0");
            header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
            header("Cache-Control: private",false);
            header("Content-Type: $ctype");
            header("Content-Disposition: attachment; filename=\"".basename($filename)."\";");
            header("Content-Transfer-Encoding: binary");
            header("Content-Length: ".@filesize('adminsms2010/upfiles/'.$filename));
            set_time_limit(0);
            @readfile("$sorce/$filename") or die("File not found.");
//download			
	  }
// send mail
function send_mail($user_id, $subject, $message){
	$db = con();
	$from = 'chitasms-Group';
	$email = 'info@chitasms.com';
	$sql = $db->query("select email from u_users where ID = '".(int)$user_id."'");
	$res = $db->fetchNextArray($sql);
	$to = $res['email'];
	$header  = "MIME-Version: 1.0\r\n";
	$header .= "Content-type: text/html; charset=utf-8\r\n";
	$header .= "To: ".$to."\r\n";
	$header .= "From: ".$from." <".$email.">\r\n";
	$header .= "Cc: \r\n";
	$message .='<br><span style="font-family:Tahoma, Arial; font-size:12px;">'.date("l d F Y").'</span>';
	mail($to, $subject, $message, $header);
}
//==========================================================
// send mail test email
function send_mail_test($code,$email_recpies){
	$db = con();
	$from = 'chitasms';
	$email = 'info@chitasms.com';
	$to = $email_recpies;
	$header  = "MIME-Version: 1.0\r\n";
	$header .= "Content-type: text/html; charset=utf-8\r\n";
	$header .= "To: ".$to."\r\n";
	$header .= "From: ".$from." <".$email.">\r\n";
	$header .= "Cc: \r\n";
	$subject = 'ارسال اس ام اس رایگان';
	$message .='<div style="direction:rtl;text-align:right;">با سلام <br/>برای ارسال پیامک تستی روی لینک زیر کلیک کنید<br/><a href="http://chitasms.com/test_sending.php?act=second_step&code='.$code.'">http://chitasms.com/test_sending.php?act=second_step&code='.$code.'</a><br/>با تشکر تیم چیتا اس ام اس<br><span style="font-family:Tahoma, Arial; font-size:12px;">'.date("l d F Y").'</span>';
	mail($to, $subject, $message, $header);
}
//name user==================================================
function name_user($ID){
	global $db;
      $query="select * from u_users where ID='".(int)$ID."'";
      $result=$db->query($query) ;  
      $row=$db->fetchNextArray($result);
	  return '<b>'.$row['userName'];
}
//====================================================
	function get_years ($selected, $name = 'year') {
		$from = 1391;
		$to = 1300;
		$text = '<select name="'.$name.'">';
		$text .= '<option value="0">سال</option>';
		for ($i=$from;$i>=$to; $i--) {
		$selected_text = '';
			if ($i == $selected) $selected_text = 'selected="selected"';
			if (($i == 1389) && ($selected == '')) $selected = 'selected="selected"';
			$text .= '<option value="'.$i.'" '.$selected_text.'>'.$i.'</option>';
		}
		$text .= '</select>';
	return $text;
	}
//====================================================
	function get_years2 ($selected, $name = 'year') {
		$from = 1391;
		$to = 1390;
		$text = '<select name="'.$name.'">';
		$text .= '<option value="0">سال</option>';
		for ($i=$from;$i>=$to; $i--) {
		$selected_text = '';
			if ($i == $selected) $selected_text = 'selected="selected"';
			if (($i == 1390) && ($selected == '')) $selected = 'selected="selected"';
			$text .= '<option value="'.$i.'" '.$selected_text.'>'.$i.'</option>';
		}
		$text .= '</select>';
	return $text;
	}
//====================================================
	function get_monthes ($selected, $name = 'month') {
		$from = 1;
		$to = 12;
		$text = '<select name="'.$name.'">';
		$text .= '<option value="0">ماه</option>';
		for ($i=$from;$i<=$to; $i++) {
		$selected_text = '';
			if ($i == $selected) $selected_text = 'selected="selected"';
			$text .= '<option value="'.$i.'" '.$selected_text.'>'.$i.'</option>';
		}
		$text .= '</select>';
	return $text;
	}
//====================================================
	function get_days ($selected, $name = 'day') {
		$from = 1;
		$to = 31;
		$text = '<select name="'.$name.'">';
		$text .= '<option value="0">روز</option>';
		for ($i=$from;$i<=$to; $i++) {
		$selected_text = '';
			if ($i == $selected) $selected_text = 'selected="selected"';
			$text .= '<option value="'.$i.'" '.$selected_text.'>'.$i.'</option>';
		}
		$text .= '</select>';
	return $text;
	}
//====================================================
	function get_hours ($selected, $name = 'hour') {
		$from = 1;
		$to = 24;
		$text = '<select name="'.$name.'">';
		for ($i=$from;$i<=$to; $i++) {
		$selected_text = '';
			if ($i == $selected) $selected_text = 'selected="selected"';
			$text .= '<option value="'.$i.'" '.$selected_text.'>'.$i.'</option>';
		}
		$text .= '</select>';
	return $text;
	}
//====================================================
	function get_minutes ($selected, $name = 'minute') {
		$from = 0;
		$to = 59;
		$text = '<select name="'.$name.'">';
		for ($i=$from;$i<=$to; $i++) {
		$selected_text = '';
			if ($i == $selected) $selected_text = 'selected="selected"';
			$text .= '<option value="'.$i.'" '.$selected_text.'>'.$i.'</option>';
		}
		$text .= '</select>';
	return $text;
	}
//====================================================
	function get_credit_amount($user_id){
		$db = con();
		$sql = $db->query("select amount from credit where user_id='".(int)$user_id."'");
		$res = $db->fetchNextArray($sql);
		
	return $res['amount'];
	}
//====================================================
	function get_credit_amount_majazi($user_id){
		$db = con();
		$credit=0;
		$sql = $db->query("select credit from sms_records where user_id='".(int)$user_id."' ");
		while($res = $db->fetchNextArray($sql)){
			$credit = $credit+$res['credit'];
		}
			return $credit;
	}
//====================================================
function get_credit_amount_majazi_smsID($smsID){
		$db = con();
		$credit=0;
		$sql = $db->query("select credit from sms_records where smsID='".(int)$smsID."' ");
		$res = $db->fetchNextArray($sql);
		$credit = $res['credit'];
		return $credit;
}		
//====================================================
	function decrease_from_credit_amount($user_id, $amount) {
		$db = con();
		$sql = $db->execute("update credit SET amount = amount - ".(int)$amount." where user_id='".(int)$user_id."'");
	return true;
	}
//====================================================
	function increase_credit_amount($user_id, $amount) {
		$db = con();
		$sql = $db->execute("update credit SET amount = amount + ".(int)$amount." where user_id='".(int)$user_id."'");
	return true;
	}
//====================================================
	function get_bank_amount($user_id){
		$db = con();
		$sql = $db->query("select amount from bank where user_id='".(int)$user_id."'");
		$res = $db->fetchNextArray($sql);
		
	return $res['amount'];
	}
//====================================================
	function decrease_from_bank_amount($user_id, $amount) {
		$db = con();
		$sql = $db->execute("update bank SET amount = amount - ".(int)$amount." where user_id='".(int)$user_id."'");
	return true;
	}
//====================================================
	function increase_bank_amount($user_id, $amount) {
		$db = con();
		$sql = $db->execute("update bank SET amount = amount + ".(int)$amount." where user_id='".(int)$user_id."'");
	return true;
	}
//====================================================
	function get_parent_id ($parent_name) {
		$db = con();
		$sql = $db->query("SELECT ID FROM u_users WHERE userName = '".$db->safe_string($parent_name)."'");
		$res = $db->fetchNextArray($sql);
	return $res['ID'];
	}
	
//====================================================
	function get_user_name ($userID) {
		$db = con();
        $query="select userName from u_users where ID='".(int)$userID."'";
        $result=$db->query($query);  
        $row=$db->fetchNextArray($result);
	return $row['userName'];
	}
//====================================================
	function get_member_days ($userID) {
		$db = con();
		$today = g_days_of_year(date("m"),date("d"),date("Y"));
		$query="select date from u_users where ID='".(int)$userID."'";
        $result=$db->query($query) ;  
        $row=$db->fetchNextArray($result);
		$member_date = explode("-",$row['date']);
		$first_day = g_days_of_year($member_date[1], $member_date[2], $member_date[0]);
		if($member_date[0] == date("Y")){
			$days = $today - $first_day;
		}elseif((date("Y") - $member_date[0]) == 1){
			$days = ($today + (365 - $first_day));
		}
		return $days;
	}
//====================================================
	function get_member_name ($userID) {
		$db = con();
        $query="select name_lastname from u_users where ID='".(int)$userID."'";
        $result=$db->query($query);  
        $row=$db->fetchNextArray($result);
	return $row['name_lastname'];
	}
//====================================================
	function get_user_level ($userID) {
		$db = con();
        $query="select status from u_users where ID='".(int)$userID."'";
        $result=$db->query($query);  
        $row=$db->fetchNextArray($result);
	return (int)$row['status'];
	}
//=====================================================
function get_from_num($userid){
	$db = con();
$sql=$db->query("select * from sending_numbers where user_id = '".$userid."' limit 1");
$row=$db->fetchNextArray($sql);
$num=$db->numRows($sql);
	if($num){
	  return $row['number'];
	}else{
	  return '9830004526';
	}
}
//====================================================
function nerkhe_tamas($groupid,$utf,$countryPrice='0'){
	$db = con();
	$sql=$db->query("SELECT * from nerkhe_sms where id=1");
	$res=$db->fetchNextArray($sql);
	if($countryPrice==1){
		$nerkhe_tamas=Get_nerkhe_tamas('countryPrice');
	}else{
		if($utf==1){
				switch($groupid) {
					case 1:
						$nerkhe_tamas = $res['farsi_1'];
					break;
					case 2:
						$nerkhe_tamas = $res['farsi_2'];
					break;
					case 3:
						$nerkhe_tamas = $res['farsi_3'];
					break;
					case 4:
						$nerkhe_tamas = $res['farsi_4'];
					break;
					case 5:
						$nerkhe_tamas = $res['farsi_5'];
					break;
					case 6:
						$nerkhe_tamas = $res['farsi_6'];
					break;
					case 7:
						$nerkhe_tamas = $res['farsi_7'];
					break;
					case 8:
						$nerkhe_tamas = $res['farsi_8'];
					break;
				}
		}elseif($utf==2){
				switch($groupid) {
					case 1:
						$nerkhe_tamas = $res['english_1'];
					break;
					case 2:
						$nerkhe_tamas = $res['english_2'];
					break;
					case 3:
						$nerkhe_tamas = $res['english_3'];
					break;
					case 4:
						$nerkhe_tamas = $res['english_4'];
					break;
					case 5:
						$nerkhe_tamas = $res['english_5'];
					break;
					case 6:
						$nerkhe_tamas = $res['english_6'];
					break;
					case 7:
						$nerkhe_tamas = $res['english_7'];
					break;
					case 8:
						$nerkhe_tamas = $res['english_8'];
					break;
				}		
		}
	}
	if($nerkhe_tamas){
		return $nerkhe_tamas;
	}else{
		return 240;
	}
}
function Get_nerkhe_tamas($X){
	$db = con();
	$sql=$db->query("SELECT * from nerkhe_sms where id=1");
	$res=$db->fetchNextArray($sql);
	return $res[$X];
}
//====================================================
	function check_date() {
		$db = con();
		$wsObj = new WebService();
		$tm=time();
		$sql = $db->query("SELECT * FROM sms_records WHERE smsStatus=0 AND date <= now() AND ( ((smsKey=0) OR (".$tm."-smsKey>180000 AND smsKey<>0))) LIMIT 100");
		while($res = $db->fetchNextArray($sql)){
			//echo time()-(time - $res['smsKey']);
				$db->execute("UPDATE sms_records SET smsKey= '".$tm."' WHERE smsID = ".(int)$res['smsID']);
				$newnumbers = trim ($res['to_num']);
				$message_counting = $res['text_message'];
				$message = array ($res['text_message']);
				$userid = $res['user_id'];
				$explode= explode(',', $newnumbers);
				foreach ($explode as $key => $value){
					$explode[$key] = trim($value);
					if(trim($value) == ''){
						unset($explode[$key]);
					}
				}
				//for sending to the count function 
				$explode_count = count ($explode);
				//for sendig to the send function
				$explode_final = $explode;
				//echo '$allamount = ' . $allamount . '$sms_amount = ' . $sms_amount . ' $explode_count = ' . $explode_count;
					if($db->query("UPDATE sms_records SET smsStatus = 1 , credit=0 WHERE smsID = ".(int)$res['smsID'])){
						$response = $wsObj->enqueue($message, $explode_final, $res['from_num']);
						$responseNum = count($response);
						$i = 1;
						$resposeCode = '';
						$numOfResponces = count($response);
						$goroohe_alan=user_group($userid);
						$detect_encoding =  mb_detect_encoding($res['text_message']);
				        foreach($response as $result){
				            // compare the response with the ERROR_MAX_VALUE
				            if($result <= 1000) {
				            	//$resposeCode .= $result;
				            	$explode_count--;
								if($detect_encoding == 'UTF-8'){
										$nerkhe_tamas=nerkhe_tamas($goroohe_alan,1);
										$get_return_credit=get_credit_amount_majazi_smsID($res['smsID']);
										$return_credit=$nerkhe_tamas+$get_return_credit;
								}else{		
										$nerkhe_tamas=nerkhe_tamas($goroohe_alan,2);
										$get_return_credit=get_credit_amount_majazi_smsID($res['smsID']);
										$return_credit=$nerkhe_tamas+$get_return_credit;
								}	
					            	$db->execute("UPDATE sms_records SET smsStatus = 3 ,credit='".$return_credit."' WHERE smsID = ".(int)$res['smsID']);
				            } else{
									$db->execute("UPDATE sms_records SET smsStatus = 1 , result='".$result."' WHERE smsID = ".(int)$res['smsID']);
				            }
				            $resposeCode .= $result;
				            if($responseNum != $i){
				            	$resposeCode .= ',';
				            }
				            $i++;
				        }
				        
				        if($explode_count > 0){
					        $db->execute("UPDATE sms_records SET smsStatus = 1, tctCodes = '$resposeCode', smsResponce = '$numOfResponces' WHERE smsID = ".(int)$res['smsID']);
							//update the creadit of person compair by UTF-8
				        }else{
				        	$db->execute("UPDATE sms_records SET tctCodes = '$resposeCode', WHERE smsID = ".(int)$res['smsID']);
				        }
					}else{
						$db->execute("UPDATE sms_records  SET smsStatus = 7,credit='".$res['credit']."' WHERE smsID = ".(int)$res['smsID']);
					}		
		}
		
    	$messages = $wsObj->getAllMessages(1000);
    	foreach($messages as $message){
    		$messageBody = $message['body'];
    		$recipientNumber = $message['recipientNumber'];
			$recipientNumber=getRecipientNumber($recipientNumber);
    		$senderNumber = $message['senderNumber'];
    		$userNum = 0;
			//print_r($senderNumber);
			//print_r( $messageBody).'<br />';
    		$explode = explode(' ', $messageBody);
    		$userid = (int)$explode[0] - 1000;
			echo $userid;
    		$sql = $db->query("SELECT * FROM u_users WHERE ID = $userid");
    		if($db->numRows($sql)){
    			$userNum = $userid;
    			$messageBody = '';
    			$i = 1;
    			foreach($explode as $subtext){
    				if($i != 1){
    					$messageBody .= $subtext . ' ';
    				}    				
    				$i++;
    			}
    		}else{
    			$sql2 = $db->query("SELECT user_id FROM sending_numbers WHERE number = $recipientNumber");
    			if($db->numRows($sql2)){
    				$res2 = $db->fetchNextArray($sql2);
    				$userNum = $res2['user_id'];
    			}
    		}
    		$db->execute("INSERT INTO sms_records SET user_id = $userNum,
    													from_num = $senderNumber,
    													to_num = $recipientNumber,
    													text_message = '$messageBody',
    													amount = 0,
    													date = now(),
    													smsStatus = 1,
    													smsType = 2");
			echo 'userNum = ' . $userNum . 'messageBody = ' . $messageBody .'-recipientNumber='.$recipientNumber;
			$sqlxx = $db->query ("select * from secretary where userID = '".(int)$userNum."' and receivedSms like '%".trim($messageBody)."%' and secretaryType=1");
			$sqlxx2 = $db->query ("select * from secretary where userID = '".(int)$userNum."' and (receivedSms = '؟' OR receivedSms = '?') and secretaryType=1");
			$sqlxx3 = $db->query ("select * from sms_pool where userID = '".(int)$userNum."' and reciveNum= $recipientNumber and poolType=1");
			//echo $query;
				if( $numxx = $db->numRows($sqlxx)) {
					//echo '$userNum2 = ' . $userNum . '$messageBody2 = ' . $messageBody. '$numxx = ' .$numxx;
					$row=$db->fetchNextArray($sqlxx);
					$db->execute("INSERT INTO sms_records SET user_id = '".(int)$userNum."', 
																	from_num = '".get_from_num($userNum)."', 
																	to_num = '".$senderNumber."', 
																	text_message = '".$row['answer']."', 
																	amount = '".(int)$row['answerNum']."',
																	sms_type_send=0,
																	date = now()");
			    }
				if( $numxx2 = $db -> numRows ( $sqlxx2 ) ) {
					//echo '$userNum2 = ' . $userNum . '$messageBody2 = ' . $messageBody. '$numxx = ' .$numxx;
					$row2=$db->fetchNextArray($sqlxx2);
					$db->execute("INSERT INTO sms_records SET user_id = '".(int)$userNum."', 
																	from_num = '".get_from_num($userNum)."', 
																	to_num = '".$senderNumber."', 
																	text_message = '".$row2['answer']."', 
																	amount = '".(int)$row2['answerNum']."', 
																	date = now()");
			    }
			    
				if($numxx3 = $db->numRows($sqlxx3)){
					$row3=$db->fetchNextArray($sqlxx3);
					if($row3['timeLimit']==2){
						//$singleSms=get_repeat_vote_sms($senderNumber,$row3['pID']);
					}
/*					if($row3['timeLimit']==1){
					//	محدوده زمانی 
						$startDate=$row3['startDate'];
						$finishDate=$row3['finishDate'];
					}*/
					
					if($row3['responseSms']==1){
					//	ارسال پیامك تایید برای شركت كننده
						$responseText=$row3['responseText'];
						$db->execute("INSERT INTO sms_records SET user_id = '".(int)$userNum."', 
																	from_num = '".$recipientNumber."', 
																	to_num = '".$senderNumber."', 
																	text_message = '".$responseText."', 
																	amount = '".(int)$row3['responseNum ']."', 
																	sms_type_send=0,
																	date = now()");
						$db->execute("UPDATE credit SET amount =  amount - ".(int)$row3['responseNumAmount']."  WHERE user_id = '".(int)$userNum."'");
					}
					if($row3['repeatSms']==1){
						//	ارسال پیامك در صورت تكراری بودن شماره
						$singleSms=get_repeat_vote_sms($senderNumber,$row3['pID']);
						if($singleSms==1){
						$responseText=$row3['repeatText'];
						$db->execute("INSERT INTO sms_records SET user_id = '".(int)$userNum."', 
																	from_num = '".$recipientNumber."', 
																	to_num = '".$senderNumber."', 
																	text_message = '".$responseText."', 
																	amount = '".(int)$row3['repeatNum']."', 
																	sms_type_send=0,
																	date = now()");
						$db->execute("UPDATE credit SET amount =  amount - ".(int)$row3['responseNumAmount']."  WHERE user_id = '".(int)$userNum."'");
						}
					}
					
					if($row3['falseSms']==1){
						//	ارسال پیامک درصورت اشتباه بودن جواب
						$return_voteID=get_return_vote($row3['pID'],trim($messageBody));
						if(!$return_voteID){
						$falseText=$row3['falseText'];
						$db->execute("INSERT INTO sms_records SET user_id = '".(int)$userNum."', 
																	from_num = '".$recipientNumber."', 
																	to_num = '".$senderNumber."', 
																	text_message = '".$falseText."', 
																	amount = '".(int)$row3['falseNum']."', 
																	sms_type_send=0,
																	date = now()");
						$db->execute("UPDATE credit SET amount =  amount - ".(int)$row3['falseNumAmount']."  WHERE user_id = '".(int)$userNum."'");
						}
					}					
										
										
					$return_voteID=get_return_vote($row3['pID'],trim($messageBody));
					if($return_voteID and $singleSms==2){
						$status=1;
					}else{
						$status=2;
					}
					$db->execute("INSERT INTO sms_pool_user SET number = '".$senderNumber."', 
																	answer = '".$messageBody."', 
																	pID = '".$row3['pID']."', 
																	vID = '".$return_voteID."', 
																	status 	 = '".(int)$status."',
																	date = now()");
			    }
    	}
		echo get_repeat_vote_sms(9830004526,3);
	}
//===============================================
function get_return_vote($pID,$messageBody){
	$db = con();
	$latin_messageBody=Convertnumber2latin2($messageBody);
	$sql=$db->query("select * from votes_pool where pID='".$pID."' and keyword ='".$latin_messageBody."'" );
	$res=$db->fetchNextArray($sql);
	//echo '$messageBody'.$messageBody.'vID'.$res['vID'];
	return $res['vID'];
}

//================================================
function get_repeat_vote_sms($senderNumber,$pID){
	$db = con();
	$sql=$db->query("select * from sms_pool_user where number='".$senderNumber."' AND pID='".$pID."'" );
	$num=$db->numRows($sql);
	if($num > 0){
		return 1;
	}else{
		return 2;	
	}
}
//=================================================
function getRecipientNumber($recipientNumber){
	$num=substr($recipientNumber,0,2);
	if($num==98){
		$returnrecipientNumber=$recipientNumber;
	}else{
		$returnrecipientNumber='98'.$recipientNumber;
	}
	return $returnrecipientNumber;
}
//=================================================
function GetNewsletterState($user_id, $newsletterID){
		$db = con();
		$sql = $db->query("SELECT * FROM newslettertousers WHERE user_id = '".(int)$user_id."' AND newsletter_id = '".(int)$newsletterID."'");
		if($res = $db->fetchNextArray($sql)){
			return true;
		}else{
			return false;
		}
}
//=======================================================
	function getUnreadNewsletter($user_id){
		$db = con();
		$sql = $db->query("SELECT id FROM newsletter");
		$num = 0;
		while($res = $db->fetchNextArray($sql)){
			if(!GetNewsletterState($user_id, $res['id'])){
				$num++;
			}
		}
	return $num;
	}
//======================================================
	function get_message_counter ($userID) {
		$db = con();
		$sql = $db->query("SELECT * FROM messages_user WHERE r_m_user = '".(int)$userID."' and dell_r = '0'");
		$num = $db->numRows($sql);
	return $num;
	}
//======================================================
function generatePassword($length = 8){

  // start with a blank password
  $password = "";

  // define possible characters
  $possible = "0123456789bcdfghjkmnpqrstvwxyz"; 
    
  // set up a counter
  $i = 0; 
    
  // add random characters to $password until $length is reached
  while ($i < $length) { 

    // pick a random character from the possible ones
    $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
        
    // we don't want this character if it's already in the password
    if (!strstr($password, $char)) { 
      $password .= $char;
      $i++;
    }

  }

  // done!
  return $password;

}


//==============================================


	function getGalleryName($catID){
		$db = con();
		$sql = $db->query("SELECT cat_name FROM category WHERE cid = '".(int)$catID."'");
		$res = $db->fetchNextArray($sql);
	return $res['cat_name'];
	}


//==============================================


	function getFlagID($countryID){
		$db = con();
		$sql = $db->query("SELECT flag_id FROM country WHERE country_id = '".(int)$countryID."'");
		$res = $db->fetchNextArray($sql);
		return $res['flag_id'];
	}




//==============================================
//get number of posible sending message (farsi)

function getamountsmsfarsi ($user_id){
	$db = con();
	$res = $db->fetchNextArray($db->query("SELECT * FROM nerkhe_sms where id = 1"));
	$goroohe_alan = $db->fetchNextArray($db->query("SELECT * FROM goroohe_karbaran where user_id = $user_id"));
	if ($goroohe_alan['groupid'] == 1 ){
		$nerkhe_tamas = $res['farsi_1'];}
	 elseif ($goroohe_alan['groupid'] == 2 ){
		$nerkhe_tamas = $res['farsi_2'];}
	 elseif ($goroohe_alan['groupid'] == 3 ){
		$nerkhe_tamas = $res['farsi_3'];}
	 elseif ($goroohe_alan['groupid'] == 4 ){
		$nerkhe_tamas = $res['farsi_4'];}
	 elseif ($goroohe_alan['groupid'] == 5 ){
		$nerkhe_tamas = $res['farsi_5'];}
	 elseif ($goroohe_alan['groupid'] == 6 ){
		$nerkhe_tamas = $res['farsi_6'];}
	 elseif ($goroohe_alan['groupid'] == 7 ){
		$nerkhe_tamas = $res['farsi_1'];}
	 elseif ($goroohe_alan['groupid'] == 8 ){
		$nerkhe_tamas = $res['farsi_8'];}		
		
		
$hala = (int)get_credit_amount($user_id);
$result = (int)($hala/$nerkhe_tamas);
return $result;
}




//================================================
//get number of posible sending message (english)-
function getamountsmsenglish ($user_id){
	$db = con();
$res = $db->fetchNextArray($db->query("SELECT * FROM nerkhe_sms where id = 1"));
$goroohe_alan = $db->fetchNextArray($db->query("SELECT * FROM goroohe_karbaran where user_id = $user_id"));
	if ($goroohe_alan['groupid'] == 1 ){
		$nerkhe_tamas = $res['english_1'];}
	 elseif ($goroohe_alan['groupid'] == 2 ){
		$nerkhe_tamas = $res['english_2'];}
	 elseif ($goroohe_alan['groupid'] == 3 ){
		$nerkhe_tamas = $res['english_3'];}
	 elseif ($goroohe_alan['groupid'] == 4 ){
		$nerkhe_tamas = $res['english_4'];}
	 elseif ($goroohe_alan['groupid'] == 5 ){
		$nerkhe_tamas = $res['english_5'];}
	 elseif ($goroohe_alan['groupid'] == 6 ){
		$nerkhe_tamas = $res['english_6'];}
	 elseif ($goroohe_alan['groupid'] == 7 ){
		$nerkhe_tamas = $res['english_1'];}
	 elseif ($goroohe_alan['groupid'] == 8 ){
		$nerkhe_tamas = $res['english_8'];}		
		
$hala = (int)get_credit_amount($user_id);
$result = (int)($hala/$nerkhe_tamas);
return $result;
}



//==============================================
//get number of posible sending message (farsi)

function getamountofsmsfarsi($user_id, $amount){
	$db = con();
$res = $db->fetchNextArray($db->query("SELECT * FROM nerkhe_sms where id = 1"));
$goroohe_alan = $db->fetchNextArray($db->query("SELECT * FROM goroohe_karbaran where user_id = $user_id"));
if ($goroohe_alan['groupid'] == 1 ){
 $nerkhe_tamas = $res['farsi_1'];}
 	elseif ($goroohe_alan['groupid'] == 2 ){
 $nerkhe_tamas = $res['farsi_2'];}
 	elseif ($goroohe_alan['groupid'] == 3 ){
 $nerkhe_tamas = $res['farsi_3'];}
 	elseif ($goroohe_alan['groupid'] == 4 ){
 $nerkhe_tamas = $res['farsi_4'];}
 	elseif ($goroohe_alan['groupid'] == 5 ){
 $nerkhe_tamas = $res['farsi_5'];}
 	elseif ($goroohe_alan['groupid'] == 6 ){
 $nerkhe_tamas = $res['farsi_6'];}
 	elseif ($goroohe_alan['groupid'] == 7 ){
 $nerkhe_tamas = $res['farsi_1'];}
  	elseif ($goroohe_alan['groupid'] == 8 ){
 $nerkhe_tamas = $res['farsi_8'];}
 
$hala = (int)get_credit_amount($user_id);
$mablaghe_tamas = (int)$nerkhe_tamas*$amount;
$result = $hala-$mablaghe_tamas;
return $result;
}




//================================================
//get number of posible sending message (english)
function getamountofsmsenglish ($user_id, $amount){
	$db = con();
$res = $db->fetchNextArray($db->query("SELECT * FROM nerkhe_sms where id = 1"));
$goroohe_alan = $db->fetchNextArray($db->query("SELECT * FROM goroohe_karbaran where user_id = $user_id"));

if ($goroohe_alan['groupid'] == 1 ){
 $nerkhe_tamas = $res['english_1'];}
 elseif ($goroohe_alan['groupid'] == 2 ){
 $nerkhe_tamas = $res['english_2'];}
 elseif ($goroohe_alan['groupid'] == 3 ){
 $nerkhe_tamas = $res['english_3'];}
 elseif ($goroohe_alan['groupid'] == 4 ){
 $nerkhe_tamas = $res['english_4'];}
 elseif ($goroohe_alan['groupid'] == 5 ){
 $nerkhe_tamas = $res['english_5'];}
 elseif ($goroohe_alan['groupid'] == 6 ){
 $nerkhe_tamas = $res['english_6'];}
 elseif ($goroohe_alan['groupid'] == 7 ){
 $nerkhe_tamas = $res['english_1'];}
 elseif ($goroohe_alan['groupid'] == 8 ){
 $nerkhe_tamas = $res['english_8'];}
 
$hala = (int)get_credit_amount($user_id);
$mablaghe_tamas = (int)$nerkhe_tamas*$amount;
$result = $hala-$mablaghe_tamas;
return $result;
}
//==============================================
//get number of posible sending message (farsi)

function getamountofsmsgroupfarsi ($user_id, $amount, $explode_count){
	$db = con();
	$res = $db->fetchNextArray($db->query("SELECT * FROM nerkhe_sms where id = 1"));
	$goroohe_alan = $db->fetchNextArray($db->query("SELECT * FROM goroohe_karbaran where user_id = $user_id"));
	
	if ($goroohe_alan['groupid'] == 1 ){
		$nerkhe_tamas = $res['farsi_1'];}
	elseif ($goroohe_alan['groupid'] == 2 ){
		$nerkhe_tamas = $res['farsi_2'];}
	elseif ($goroohe_alan['groupid'] == 3 ){
		$nerkhe_tamas = $res['farsi_3'];}
	elseif ($goroohe_alan['groupid'] == 4 ){
		$nerkhe_tamas = $res['farsi_4'];}
	elseif ($goroohe_alan['groupid'] == 5 ){
		$nerkhe_tamas = $res['farsi_5'];}
	elseif ($goroohe_alan['groupid'] == 6 ){
		$nerkhe_tamas = $res['farsi_6'];}
	elseif ($goroohe_alan['groupid'] == 7 ){
		$nerkhe_tamas = $res['farsi_1'];}
	elseif ($goroohe_alan['groupid'] == 8 ){
		$nerkhe_tamas = $res['farsi_8'];}
	 
	$hala = (int)get_credit_amount($user_id);
	$mablaghe_tamas = (int)$nerkhe_tamas*$amount*$explode_count;
	$result = $hala-$mablaghe_tamas;
	return $result;
}


//get number of posible sending message (farsi)

function getamountofsmsgroup ($user_id, $amount, $nerkhe_tamas){
	$db = con();
	$credit = (int)get_credit_amount($user_id);
	$mablaghe_tamas = (int)$nerkhe_tamas*$amount;
	$result = $credit-$mablaghe_tamas;
	return $result;
}



//================================================
//get number of posible sending message (english)
function getamountofsmsgroupenglish ($user_id, $amount, $explode_count){
	$db = con();
$res = $db->fetchNextArray($db->query("SELECT * FROM nerkhe_sms where id = 1"));
$goroohe_alan = $db->fetchNextArray($db->query("SELECT * FROM goroohe_karbaran where user_id = $user_id"));

if ($goroohe_alan['groupid'] == 1 ){
 $nerkhe_tamas = $res['english_1'];}
 elseif ($goroohe_alan['groupid'] == 2 ){
 $nerkhe_tamas = $res['english_2'];}
 elseif ($goroohe_alan['groupid'] == 3 ){
 $nerkhe_tamas = $res['english_3'];}
 elseif ($goroohe_alan['groupid'] == 4 ){
 $nerkhe_tamas = $res['english_4'];}
 elseif ($goroohe_alan['groupid'] == 5 ){
 $nerkhe_tamas = $res['english_5'];}
 elseif ($goroohe_alan['groupid'] == 6 ){
 $nerkhe_tamas = $res['english_6'];}
 elseif ($goroohe_alan['groupid'] == 7 ){
 $nerkhe_tamas = $res['english_1'];}
 elseif ($goroohe_alan['groupid'] == 8 ){
 $nerkhe_tamas = $res['english_8'];}
 
$hala = (int)get_credit_amount($user_id);
$mablaghe_tamas = (int)$nerkhe_tamas*$amount*$explode_count;
$result = $hala-$mablaghe_tamas;
return $result;
}


//==============================================

	function getNumbersXLS($userID){
		$db =con();
		$xl = new xls();
		
		$sql = $db->query("SELECT to_num FROM sms_records WHERE user_id = $userID AND smsType = 1");
		$xl->add_cell("1:1","Mobile Number");
		$i = 2;
		while($res = $db->fetchNextArray($sql)){
			$xl->add_cell("$i:1",$res ['to_num']);
			$i++;
		}
		$xl->execute("mobileNumbers.xls");
	}
//==============================================

	
	function sql2XLS($fileName, $tableName, $fields, $names, $whereClaus = '', $orderBy = '', $limit = ''){
		$db =con();
		$xl = new xls();
		$selects = "";
		$selectNum = count($fields);
		$i = 1;
		foreach($fields as $field){
			$selects .= "$field AS ".$names[$i];
			if($i < $selectNum){
				$selects .= ", ";
			}
			$i++;
		}
		$sql = $db->query("SELECT $selects FROM $tableName $whereClaus $limit");
		$k = 1;
		foreach($fields as $field){
			$xl->add_cell("1:$k", $names[$k]);
			$j = 2;
			while($res = $db->fetchNextArray($sql)){
				$xl->add_cell("$k:$j",$res [$names[$k]]);
				$j++;
			}
			$k++;
		}
		$xl->execute("$fileName.xls");
	}
//==================================================

	function getDiff ($a, $b) {
		if($a >= $b) {
			if(($a - $b) < 10) {
				return true;
			}else{
				return false;
			}
		}elseif($a < $b) {
			if(($b - $a) < 10) {
				return true;
			}else{
				return false;
			}
		}
	}
//-----------------------------------------------------
function user_group($userID){
	$db =con();
	$res_gorooh = $db->fetchNextArray($db->query("SELECT * FROM goroohe_karbaran WHERE user_id = '".$userID."'"));
	$goroohe_alan = $res_gorooh['groupid'];
	return $goroohe_alan;
}
//-----------------------------------------------------
function user_location($userID){
	$db =con();
	$res_gorooh = $db->fetchNextArray($db->query("SELECT * FROM goroohe_karbaran WHERE user_id = '".$userID."'"));
	$location = $res_gorooh['location'];
	if($location==1){
		$return_location='اعتبار شما به اتمام رسیده است برای استفاده از خدمات سایت ، پلن مورد نظر خود را خریداری نمایید';
	}elseif($location==2){
		$return_location='مدت عضویت شما به اتمام رسیده است برای استفاده از خدمات سایت ، پلن مورد نظر خود را خریداری نمایید';
	}elseif($location==3){
		$return_location='اعتبار شما به اتمام رسیده است  برای استفاده از خدمات سایت ، پلن مورد نظر خود را خریداری نمایید';
	}
	return $return_location;
}
//=====================================================
function get_user_expire_date($userID){
$db = con();
$date_encoding = $db->fetchNextArray ($db->query("SELECT * FROM goroohe_karbaran WHERE user_id = $userID"));
$end_date = tep_hejri2($date_encoding['expire_date']);
return $end_date;

}
//=====================================================
function get_user_permition_date($userID){
$db = con();
$date_encoding = $db->fetchNextArray ($db->query("SELECT * FROM goroohe_karbaran WHERE user_id = $userID "));
$end_date = $date_encoding['expire_date'];
$now = date("Y-m-d H:i:s");

		if($now >= $end_date){
			return 1;
		}else { return 0;}
}
//-----------------------------------------------------
function update_user_group_expier_date($userID){
	$db =con();
	$db->execute("update goroohe_karbaran set groupid=7 WHERE user_id =$userID");
}
//-----------------------------------------------------
function get_user_permition_sms($userID){
	$db = con();
	$num = $db->numRows ($db->query("SELECT * FROM credit WHERE user_id = $userID AND amount<120"));
	if ($num){
		return 1;
	}else { return 0;}
}
//-----------------------------------------------------
function lastIDsettel(){
	$db =con();
	$res = $db->fetchNextArray($db->query("SELECT * FROM epay_mellat order by OrderId desc limit 1"));
	$OrderId = $res['OrderId'] + 1;
	return $OrderId;
}
//-----------------------------------------------------
function count_mobile_trades($km_group){
	$db =con();
	$sql = $db->query("SELECT * FROM trades_mass where km_group0 ='".$km_group."' AND km_type = 1");
	$num = $db->numRows($sql);
	return $num;
}
//-----------------------------------------------------
function count_mobile_trades1($km_group){
	$db =con();
	$sql = $db->query("SELECT * FROM trades_mass where km_group ='".$km_group."' AND km_type = 1");
	$num = $db->numRows($sql);
	return $num;
}
//-----------------------------------------------------
function return_city($id){
	$db =con();
	$sql = $db->query("SELECT * FROM shahr where id = '".$id."' ");
	$res = $db->fetchNextArray($sql);
	return $res['name'];
}
//-----------------------------------------------------
function return_state($id){
	$db =con();
	$sql = $db->query("SELECT * FROM ostan where id = '".$id."' ");
	$res = $db->fetchNextArray($sql);
	return $res['name'];
}
//-----------------------------------------------------
function get_sms_type ($status) {
		switch($status) {
			case 0:
				$output ='<img src="images/icon/1.png" alt="ارسال تکی" title="ارسال تکی"> ';
			break;
			case 1:
				$output = '<img src="images/icon/2.png" alt="ارسال منطقه ای" title="ارسال منطقه ای">';
			break;
			case 2:
				$output = '<img src="images/icon/3.png" alt="ارسال به اصناف" title="ارسال به اصناف">';
			break;
			case 3:
				$output = '<img src="images/icon/4.png" alt="ارسال شهر و استان " title="ارسال شهر و استان">';
			break;
			case 4:
				$output = '<img src="images/icon/5.png" alt="ارسال زمانبندی" title="ارسال زمانبندی">';
			break;
			case 5:
				$output = '<img src="images/icon/" alt="ارسال ';
			break;
			case 6:
				$output = '<img src="images/icon/" alt="ارسال پیوسته" title="ارسال پیوسته">';
			break;
			case 7:
				$output = '<img src="images/icon/6.png" alt="ارسال تصادفی" title="ارسال تصادفی">';
			break;
			case 8:
				$output = '<img src="images/icon/7.png" alt="ارسال گروهی" title="ارسال گروهی">';
			break;	
			case 10:
				$output = '<img src="images/icon/8.png" alt="sms srvice " title="sms srvice">';
			break;		
			case 11:
				$output = '<img src="../images/icon/4.png" alt="ارسال کد پستی " title="ارسال کد پستی">';
			break;	
			case 12:
				$output = '<img src="../images/icon/4.png" alt="ارسال پیش شماره " title="ارسال پیش شماره">';
			break;				
							
	}
return $output;
}
//-----------------------------------------------------
function return_all_send($id,$type){
	$db =con();

	if($type){
		$where_claus .= " WHERE smsType = ".(int)$type;
	}else{
		//$where_claus .= "  ";
	}
	if($id < 1){
		
	}else{
		$where_claus .= " AND user_id = ".(int)$id;
	}	
	
	$all_amount=0;
	$sql =$db->query("SELECT * FROM sms_records $where_claus ");
	while($res = $db->fetchNextArray($sql)){
		$detect_encoding =  mb_detect_encoding($res['text_message']);
		$replace_text_message=str_replace("\r","",$res['text_message']);
		$str_len = mb_strlen ($replace_text_message,'UTF-8');
		if ($detect_encoding == 'UTF-8'){
			$maxLength=70;
			$udhLength=3;
			if($str_len<=70){
				$sms_amount=1;
			}else{
				$sms_amount = ((int)($str_len - 1) / (int)($maxLength - $udhLength)) + 1;
			}
		} else {
			$maxLength=160;
			$udhLength=6;
			if($str_len<=160){
				$sms_amount=1;
			}else{
				$sms_amount = ((int)($str_len - 1) / (int)($maxLength - $udhLength)) + 1;
			}
		}	
	$all_amount = ((int)$sms_amount * (int)$res['amount'])  + (int)$all_amount ;
	}
	return $all_amount;
}
//===========================================
function count_pool($pID,$status){
	$db=con();
	if($status==0){
		$p_status='';
	}elseif($status==1){
		$p_status='AND status=1';
	}elseif($status==2){
		$p_status='AND status =2';
	}
	$sql=$db->query("select * from sms_pool_user where pID='".$pID."' $p_status");
	$num=$db->numRows($sql);
	return $num;
}
//===========================================
function count_pool_vote($pID,$vID){
	$db=con();
	$sql=$db->query("select * from sms_pool_user where pID='".$pID."' AND vID='".$vID."' AND status=1");
	$num=$db->numRows($sql);
	return $num;
}
//---------------------------------------
function get_pool_vote_name($vID){
	$db=con();
	$sql=$db->query("select * from votes_pool where vID='".$vID."' ");
	$res=$db->fetchNextArray($sql);
	return $res['vote'];
}
//--------------------------------------
function get_config_price($fildName){
	$db=con();
	$sql=$db->query("select * from nerkhe_sms where id=1 ");
	$res=$db->fetchNextArray($sql);
	return $res[$fildName];	
}

//---------------------------------------------------------------------------------------
function getExpireDate ($aFromDate,$aAddDays){
	// aFromDate on the format YYmd, like 20040212
	$from_year=substr($aFromDate,0,4);
	$from_month=substr($aFromDate,4,2);
	$from_day=substr($aFromDate,6,2);
	$expire_date_conv = formatDate(date ("Ymd", mktime (date("H"),date("i"),date("s"),$from_month,$from_day+$aAddDays,$from_year)));  
	return $expire_date_conv;
}
//----------------------------------------------------------------------------------------
function formatDate($aDate){
	// aDate should have Ymd format
	 $date_format="y-m-d";
	$year=substr($aDate,0,4);
	$month=substr($aDate,4,2);
	$day=substr($aDate,6,2);
	// Date_format grabbed from settings...
	$date_added_1 = $date_format;
	$date_added_1 = ereg_replace("d", "$day", $date_added_1);
	$date_added_1 = ereg_replace("m", "$month", $date_added_1);
	$date_added_1 = ereg_replace("y", "$year", $date_added_1);
	$sitedate1 = $date_added_1;
	return $sitedate1;
}
//-----------------------------------------------------------
function count_pattern($p_g_id){
	$db=con();
	$sql=$db->query("select * from insertPattern where p_g_id='".$p_g_id."'");
	$num=$db->numRows($sql);
	return $num;
}
//------------------------------------------------------------
function patternGroupName($p_g_id){
	$db=con();
	$sql=$db->query("select * from patternGroup where p_g_id='".$p_g_id."'");
	$res=$db->fetchNextArray($sql);
	return $res['title'];
}
//-------------------------------------------------------------
function get_cost_settle($settle_id){
	$db=con();
	$sql=$db->query("select * from settle where settle_id='".$settle_id."'");
	$res=$db->fetchNextArray($sql);
	return $res['amount'];
}