Location: PHPKode > projects > KSMS bulk sms manager > ksms-e1.2.35/functions.php
<?php
// -------------------------------------------------------------------------//
// KSMS ^ Short Message System Manager										//
// -------------------------------------------------------------------------//
// Based on "DBSMS" (C) 2002 Paolo Remonato									//
// Copyright (C) 2002-2006 Paolo Remonato									//
// KSMS-PROJECT HOME  :  http://ksms.sourceforge.net/						//
// -------------------------------------------------------------------------//
//   Please,do not delete these lines	^^^									//
// -------------------------------------------------------------------------//
/*
  This program is free software; you can redistribute it and/or modify it under the terms
  of the GNU General Public License as published by the Free Software Foundation.
  The software is provided "as is" without any express or implied warranty of any kind,
  Including warranties of noninfringement, merchantability, or fitness for a particular purpose.  
*/
###		@version 	: 2006-02-21,v1.2.35	kingmo
###		@last sing_upd 	: 
###		@filename 	: 

define('IN_KSMS', true);

function check_smsc($db)
{
	//global $okk;
		$idORG = $_SESSION["id_company"];
		$gwconnects = $db->Execute("SELECT gwprovider.EMIuser, gwprovider.EMIpass, gwprovider.bareboxIP, gwprovider.KanlSmsPort FROM gwprovider LEFT JOIN organization ON gwprovider.id=organization.id_gwprovider WHERE organization.id='$idORG'");
//		$gatefile = $gwfile->fields["original_gwfile_name"];
		$EMI_User = $gwconnects->fields["EMIuser"];
		$EMI_Pass = $gwconnects->fields["EMIpass"];
		$UCP_BxIP = $gwconnects->fields["bareboxIP"];
		$UCP_KPrt = $gwconnects->fields["KanlSmsPort"];
		$cfgg = $db->Execute("SELECT id_config, project_name, prgmURL FROM config");
		$www_source = "http://".$_SERVER['SERVER_ADDR'];
		$cfgid = $cfgg->fields["id_config"];
		$rel_URL = $cfgg->fields["prgmURL"];
		$KsmsURL = $www_source."/".$rel_URL;
		$KwwwURL=$KsmsURL;
	// check the connection ...
		$okk = "";
		$connection = fsockopen($UCP_BxIP, $UCP_KPrt, $errno, $errstr, 60);

		if(!$connection) 
    		{
				$okk = 'N';
			if ($errstr=="Connection refused")
					{
					$errstr2="BBOX_ERROR : Please contact the system administrator!"; 
					}
				$errsmess = "<br><font style='background: #ffff99;'>(err 775DK |".$errno.")</font> - Internal Gateway Connection!!!<br>".$errstr2."<br><br><br>";
				echo ($errsmess);
			} else {
			//************
		$okk = 'Y';
 	fclose ($connection);
		 }

return $okk;
}

// DISPLAY ALL SINGLE NUMBER SELECTED!
function display_single_sel($db, $sms_numbers)
{
	echo "<tr><td bgcolor='#E8FDFF'><b>Sending messages to the follow numbers:</b></td></tr></table><br>";
            echo "<table width=\"450\" align=\"center\">";
			echo "<tr class='row_head'><td><b>OraInvio</b></td><td><b>Date</b></td> <td><b>Mobile Nrs.</b></td></tr>";
			for($i = 0; $i < count($sms_numbers); $i++)
			{
			echo "<tr>";
			$Ktimenow=date("H:i:s");
			$Kdatenow=date("d-m-Y");
			$allnrs=$sms_numbers[$i];
				echo "<td>".$Ktimenow."</td>";
				echo "<td>".$Kdatenow."</td>";
				echo "<td>".$Kdatenow."</td>";
				echo "<td>".$allnrs."</td>";
			echo "</tr>";
					};
}

function setsmsmailed($db,$idORG,$Kmprenr,$Kmphonr,$Kmidmex,$serv_cue,$refer)
// Send an email only to the abilited users
//setsmsmailed($db,$idORG,$Kiidmx)
{
	
	$query = "UPDATE sendgatenumbs SET"
		. " mailed ='Y', myserv_queue='$serv_cue'"
		. " WHERE id_organization='$idORG' AND ref='$refer' AND mailed ='N' AND mobile_prenumber='$Kmprenr' AND mobile_phone_number='$Kmphonr' AND sms_id='$Kmidmex'";
         if (!$db->Execute($query)) {
		 echo "<p class='tbl_error'>Database Error: (updSGT0075) + " . $db->ErrorMsg() . "</p>";
				break;
						}
    return;
}

function setsmsmailed_test($db,$idORG,$Kmprenr,$Kmphonr,$Kmidmex,$serv_cue,$refer)
{
# NOW I'M SEND AN EMAIL TO THE USERS THAT AREN'T AUTHORIZED TO SEND MESSAGES.

	$query = "UPDATE sendgatenumbs SET"
		. " sended='T', mailed ='Y', groupselect ='TestOnlyMail', myserv_queue='MKKT'"
		. " WHERE ref='$refer' AND mailed ='N' AND mobile_prenumber='$Kmprenr' AND mobile_phone_number='$Kmphonr' AND id_organization='$idORG' AND sms_id='$Kmidmex'";
         if (!$db->Execute($query)) {
            	echo "<p class='tbl_error'>Database Error: " . $db->ErrorMsg() . "</p>";
				break;
						}
    return;
}


function sendmailtoServer($db,$refer,$smsid,$mailsendtest,$mailsel)
 {
 	//	function for user with privileges over "4" ($priv > 4). SPEDISCO I MESSAGGI SOLO VIA E.MAIL!
	// set global variable
	$date_format		= "Y-m-d";
	$time_format		= "G:i:s";
	$datetime_format 	= $date_format." ".$time_format;
	$date_now			= date($date_format, time());
	$time_now			= date($time_format, time());
	$datetime_now		= date($datetime_format, time());
	$idORG = $_SESSION["id_company"];
	//$mailKsms = $db->Execute("SELECT * FROM ksms WHERE id='$smsid' AND id_organization='$idORG'");
	//$messaggetext = $mailKsms->fields["sms_text"];	
	$sendgatemail = $db->Execute("SELECT * FROM sendgate_data WHERE tpl_sended='N' AND id_sms='$smsid' AND id_organization='$idORG' AND ref='$refer'");
	$Msms_idmxxg = $sendgatemail->fields["id_sms"]; // ID of every sms message
	$Msms_Txmxxg = $sendgatemail->fields["sms_text"]; // the text
	$Msms_TUhead = $sendgatemail->fields["txt_head_sender"]; // Head instead of number diplayed on the mobile
	$Msms_intIDx = $sendgatemail->fields["internal_id_mex"]; // ID for internal use
	$messaggetext = $Msms_intIDx." [  ".$Msms_Txmxxg."   ]";
	// if ($mailsel == "SMSsended") { $myserqu = "MIKV"; }
	// if ($mailsel == "kerror") { $myserqu = "MMER"; }
	// if ($mailsel == "onlymailtest") { $myserqu = "MKKT"; }
	
	# SELECT ONLY NUMBERS THAT AREN'T SENDED
	$mailnrs = $db->Execute("SELECT * FROM sendgatenumbs WHERE mailed='N' AND sended='N' AND sms_id='$Msms_idmxxg' AND id_organization='$idORG' AND ref='$refer'");
	$admconfg = $db->Execute("SELECT email_admin, email_copy FROM config");
	$Kadmmail01 = $admconfg->fields["email_admin"];
	$Kadmmail02 = $admconfg->fields["email_copy"];
	$OrgTbl = $db->Execute("SELECT id, email, company, txt_head_sender FROM organization WHERE id='$idORG'");
	$organ_id = $OrgTbl->fields["id"];
	$organ_mail = $OrgTbl->fields["email"];
	$organ_name = $OrgTbl->fields["company"];
	$organ_head = $OrgTbl->fields["txt_head_sender"];
	$serv_cue = "MoCY";
		// MAIL SENDMAIL MAIL------------------------------------------------------
		if($mailsendtest=="Y") { $headMailMex="====== TEST::: This is only a test! The message wasn't sended to users === \n\n"; }
		if($mailsendtest=="ERR01") { 
	$headMailMex="================= ERROR725::: These messages aren't send!!! === \n\n"; 
	$serv_cue = "MMER";
			}
		$bcc = $Kadmmail01;
		$web_title = "KSMS - bulk SMS";
		$email_footer = "Visit us at viabazar.com";
		$from_name = "hide@address.com";
			// configure here an email address used for test
			if($Kadmmail02=="") { $Kadmmail02="hide@address.com"; }
			if($organ_mail=="") { $organ_mail=$Kadmmail02; }
		$headers = "From: ".$from_name."\r\n";
			if(!empty($cc))  { $headers.= "Cc: $cc\r\n"; }
			if(!empty($bcc)) { $headers.= "Bcc: $bcc\r\n"; }
		$headers .= "Return-Path: ".$from_name."\n";
		$headers .= "MIME-Version: 1.0\n";
		$headers .= "Content-type: text/plain; charset=iso-8859-1\n";
		$headers .= "Reply-To: ".$from_name."\n";
		$headers .= "X-Priority: 1\n";
		$headers .= "X-MSMail-Priority: High\n";
		$headers .= "X-Mailer: KSMSmailer\n";
		$headers .= "X-MimeOLE: from KSMS a Short GSM Messages Manager by viabazar.com\n";
		$headers .= "X-AntiAbuse: Script smsServername at www.viabazar.com\n";
		$headers .= "X-AntiAbuse: User ".$organ_id."_".$organ_name." ".$organ_head."\n";
		$to = $organ_mail;
		$subject = "Messages sended by $organ_name";
		$body = "Forward WebSMS ($web_title)\n";
		$body .= "Report date: $date_now\n\n";
		//$body .= "Sender: $sms_sender\n";
		//$body .= "Code: $target_code\n\n";
		//$body .= "Message:\n".$Kmessage[$i]."\n\n\n";
		$body .= "THIS IS A RESERVED eMAIL!!!\n\n";
		$body .= $headMailMex;
		$body .= "THIS IS A RESERVED MESSAGE:\n\n";
		$body .= "( \n";
		$body .= " ".$messaggetext."\n";
		$body .= " )\n\n";
		$body .= "GSM NUMBERS:\n\n";
/* ---> MESSAGGIO ::: numeri tel */
	$i = 1;
	while (!$mailnrs->EOF)
			{
				$Kmprenr = $mailnrs->fields["mobile_prenumber"];
				$Kmphonr = $mailnrs->fields["mobile_phone_number"];
				$Kmphtmr = $mailnrs->fields["toserver_times"];
				//$Kiidmx = $mailnrs->fields["internal_id_mex"];
				$Kmidmex = $mailnrs->fields["sms_id"];
				//$Kiidmx2 = substr($Kiidmx, 10, 15);
				$Kiidmx2 = $Kmidmex.$Kmphtmr;
					// $mprenr = $Kmprenr[$i];
					// $mphonr = $Kmphonr[$i];
				$Kmessage = $Kmprenr."/".$Kmphonr." | ".$Kiidmx2."";
				$body .= $i." | ".$Kmessage."\n";
				# ref='$refer'
		if($mailsendtest == "Y") {
		 setsmsmailed_test($db,$idORG,$Kmprenr,$Kmphonr,$Kmidmex,$serv_cue,$refer); 
		 	}
			else {
			setsmsmailed($db,$idORG,$Kmprenr,$Kmphonr,$Kmidmex,$serv_cue,$refer);
			  }
	 			$i++;
     			$mailnrs->MoveNext();
			}
				$body .= "\n\n".$email_footer."\n\n";
				mail($to,$subject,$body,$headers);

//$send2serv = $db->Execute("SELECT * FROM sendtogate WHERE inviato='YES' AND id_organization='$idORG'");




    return;
}// end function sendmailtoServer


function paint_table_manual_select($db, $smsid) {
   	$company = $_SESSION["company"];
   	$idORG = $_SESSION["id_company"];
	$smphones = $db->Execute("SELECT mobile_pref,mobile_phone,id_user FROM userz WHERE country_code='39' AND id_organization='$idORG' ORDER BY mobile_pref");
if (!$orgsel3E = $db->Execute("SELECT * FROM credits_manager WHERE id_orgz='$idORG'")) {
      	 	echo "<p class='tbl_error'>Database Error: " . $db->ErrorMsg() . "</p>";
	      		break;
   				}
		$conxx = $orgsel3E->fields["connext_type"];
		$kstot = $orgsel3E->fields["smscredits_totalsum"];
		$ksrem = $orgsel3E->fields["smscredits_remain"];
		$kntot = $orgsel3E->fields["nrsms_totalsum"];
		$knrem = $orgsel3E->fields["nrsms_remain"];
		$cr_ac = $orgsel3E->fields["credit_activated"];
	if ($cr_ac == "Y") {
		if ($conxx == "fee") { $cust_credsrem = $ksrem; }
		 else if ($conxx == "oto") { $cust_credsrem = $knrem; }
		 else $cust_credsrem = 0;
		$totcountnrs_it = number_format($totcountnrs, 0, ',', '.'); // european format numbers!!!
		$cust_credsrem_it = number_format($cust_credsrem, 0, ',', '.'); // european ft without dec. (0 decim.)
	}
?>

<br>
   <table class="small" border="0" cellspacing="0" cellpadding="1" width="800" bgcolor="#0450AC">
<tr>
    <td>
	<table class="small" width="799" border="0" cellspacing="0" cellpadding="1">
		<form name="formsend2" method="post" action="ne_SMS.php">
      		<tr class="row_head"><td><div align="center"><b><font size="4" color="#ffcc99">YOU HAVE MAXIMUM <?PHP echo $cust_credsrem_it; ?> NUMBERS TO SELECT!</font></b></div></td></tr>
	   		<tr>
				<td>
				<table align="center" width="100%" cellspacing="3" cellpadding="3" border="0">
<tr>
    <td><font face="Verdana,Geneva,Arial,Helvetica,sans-serif" size="2" color="#dffaff">
	<b>Multiple selection</b><br>
Per selezionare piĆ¹ numeri:<br>
1.) Click and select at the bottom &quot;<i>Numbers Multiple Select</i>&quot;<br>
2.) Click, with the left mouse button, on the first number that you want. Hit <b>CTRL</b> on your keyboard and select others.<br>
3.) For select a group, left-click on the first and (with pushed <b>SHIFT</b> of your keyboard) select the last number!</font></td>
    <td>
			<label><font face="Verdana,Geneva,Arial,Helvetica,sans-serif" size="1" color="#0450AC">SMS da spedire a:</font><br>
				<select name="sms_numbers[]" size="10" multiple="yes"><?php
      				$i = 1;
      				while (!$smphones->EOF) {
			$smnumbers = ($smphones->fields["mobile_pref"]."-".$smphones->fields["mobile_phone"]);
			//$smphones = $db->Execute("SELECT mobile_pref,mobile_phone,id_user FROM userz WHERE country_code='39' AND id_organization='$idORG' ORDER BY mobile_pref");
			$ksmsiduser = $smphones->fields["id_user"];
			// old :    <option value="< ?php echo $smnumbers; ? >"> < ?php echo $smnumbers; ? >
         			?>					
			<option value="<?php echo $ksmsiduser; ?>"> <?php echo $smnumbers; ?>
		<?php
         	$i++;
         	$smphones->MoveNext();
      		}
	$Optable="disabled";
		?>
					</select>
				</label>
	</td>
</tr>
</table>			
				</td>
			</tr>
		</table>
			
	</td>
</tr>
</table>
  
         </tr>
   </table>
      <table class="small" border="0" cellpadding="1" cellspacing="0" width="801">
      <tr class="row_foot">
         <td><div align="center"> 
		 <a href="ne_SMS.php?action=Abort">
			   	  	<img src="images/pub/bt_cancel.gif" border="0" alt="Annulla">
						</a>&nbsp;&nbsp;
						<img src="images/pub/bt_enter.gif" border="0" alt="Invio Finale di SMS"
                  onClick="document.formsend2.submit();">
			</div></td>
      </tr>
	  <input type="hidden" name="smsgroupsel" value="ksms_SingleSelector">
	  <input type="hidden" name="smopt" value="manual">
	  <input type="hidden" name="smsid" value="<?php echo $smsid ?>">
	  <input type="hidden" name="action" value="finalsend">
	 	</form>
   </table>

 <?php
} // end function

function paint_table_autom_select($db, $smsid, $smopt) {

	echo ".............Sending messages with automatic selection... ..........please wait!!";

} // end function

// UPDATE CREDITS MANAGER EVERY TIME A MESSAGE IS SENT TO THE KANNEL
function creditsupdt($db,$conxx,$custcred_value,$KuidOrg,$totcountnrs) {
	//  credits_manager
	if ($conxx == "fee") {
		$my_credsrem = "smscredits_spend";
		// 
		if (!$credsman_fee = $db->Execute("SELECT * FROM credits_manager WHERE id_orgz='$KuidOrg' AND connext_type='fee'")) {
      	 		echo "<p class='tbl_error'>Database Error: " . $db->ErrorMsg() . "</p>";
	      		break;
   				}
		$creds_spend = $credsman_fee->fields["smscredits_spend"];
		$creds_smrem = $credsman_fee->fields["smscredits_remain"];
		$newcredsspend = $creds_spend + ($custcred_value * $totcountnrs);
		$newcredsremain = $creds_smrem - ($custcred_value * $totcountnrs);
	### TESTING...
//	echo "<hr><p class='testing'>TEST DELIVERED VARIABLES... 
//			old is the first value, new is the value after the operations!</p>";
//	echo "<p class='testing'>[TOTAL OF SENDED MESSAGES] ".$totcountnrs."</p>";
//	echo "<p class='testing'>[old CREDITS CONSUMED] ".$creds_spend."</p>";
//	echo "<p class='testing'>[old CREDITS UNUSUED] ".$creds_smrem."</p>";
//	echo "<p class='testing'>[new CREDITS CONSUMED] ".$newcredsspend."</p>";
//	echo "<p class='testing'>[new CREDITS REMAIN] ".$newcredsremain."</p>";
//	echo "<p class='testing'>[ID_ORG] ".$KuidOrg."</p>";
//	echo "<p class='testing'>- [CONNECTION_TYPE] ".$conxx."</p>";
//	echo "<p class='testing'>[CREDS_VALUE] ".$custcred_value."</p>";
//	echo "<p class='testing'>[+ROUND-CREDS_REM] ".ceil($newcredsremain)."</p>";
//	echo "<p class='testing'>[-ROUND-CREDS_REM] ".floor($newcredsremain)."</p>";
//	echo "<p class='testing'>[TOT_MESSAGES] ".$totcountnrs."</p>";
	### end TESTING ...
## DOCS:
// Variables:
// $custcred_value : is the value debited for each message sended!
// $creds_spend : is the summ of every custcred_value consumed
// $creds_smrem : is the arithmetic summ of all credits (buy and sold)
//   connext_type	credits_sale_value	smscredits_totalsum	smscredits_spend	smscredits_remain
//   ---------------------------------------------------------------------------------------------
//   fee				  1.7884            	1000.0000			0.0000				1000.0000
### Update the table of sms credits
		$querysendd = "UPDATE credits_manager SET"
			. " smscredits_spend='$newcredsspend', smscredits_remain='$newcredsremain', "
			. " last_update=NOW()"
			. " WHERE id_orgz='$KuidOrg' AND connext_type='fee'";
         if (!$db->Execute($querysendd)) {
    			echo "<p class='tbl_error'>Database Error: " . $db->ErrorMsg() . "</p>";
           		 break;
         			}
	} elseif ($conxx == "oto") {
		 $my_credsrem = "nrsms_spend";
		 // per ogni sms inviato si toglie 1 crediti ... (tbl-->credits_manager || credits_sale_value = 1)
		 if (!$credsman_oto = $db->Execute("SELECT * FROM credits_manager WHERE id_orgz='$idORG' AND connext_type='oto'")) {
      	 		echo "<p class='tbl_error'>Database Error: " . $db->ErrorMsg() . "</p>";
	      		break;
   				}
		$credso_spend = $credsman_oto->fields["smscredits_spend"];
		$credso_smrem = $credsman_oto->fields["smscredits_remain"];
		$newcredsospend = $credso_spend + ($custcred_value * $totcountnrs);
		$newcredsoremain = $credso_smrem - ($custcred_value * $totcountnrs);
	### TESTING...
//	echo "<hr><p class='testing'>TEST DELIVERED VARIABLES... 
//			old is the first value, new is the value after the operations!</p>";
//	echo "<p class='testing'>[TOTAL OF SENDED MESSAGES] ".$totcountnrs."</p>";
//	echo "<p class='testing'>[old CREDITS CONSUMED] ".$credso_spend."</p>";
//	echo "<p class='testing'>[old CREDITS UNUSUED] ".$credos_smrem."</p>";
//	echo "<p class='testing'>[new CREDITS CONSUMED] ".$newcredsospend."</p>";
//	echo "<p class='testing'>[new CREDITS REMAIN] ".$newcredsoremain."</p>";
//	echo "<p class='testing'>[ID_ORG] ".$KuidOrg."</p>";
//	echo "<p class='testing'>- [CONNECTION_TYPE] ".$conxx."</p>";
//	echo "<p class='testing'>[CREDS_VALUE] ".$custcred_value."</p>";
//	echo "<p class='testing'>[+ROUND-CREDS_REM] ".ceil($newcredsoremain)."</p>";
//	echo "<p class='testing'>[-ROUND-CREDS_REM] ".floor($newcredsoremain)."</p>";
//	echo "<p class='testing'>[TOT_MESSAGES] ".$totcountnrs."</p>";
	### end TESTING ...
## DOCS:
// Variables:
// $custcred_value : is the value debited for each message sended!
// $creds_spend : is the summ of every custcred_value consumed
// $creds_smrem : is the arithmetic summ of all credits (buy and sold)
//   connext_type	credits_sale_value	smscredits_totalsum	smscredits_spend	smscredits_remain
//   ---------------------------------------------------------------------------------------------
//   fee				  1.7884            	1000.0000			0.0000				1000.0000
### Update the table of sms credits
		$querysendd = "UPDATE credits_manager SET"
			. " nrsms_spend='$newcredsospend', nrsms_remain='$newcredsoremain', "
			. " last_update=NOW()"
			. " WHERE id_orgz='$KuidOrg' AND connext_type='oto'";
         if (!$db->Execute($querysendd)) {
    			echo "<p class='tbl_error'>Database Error: " . $db->ErrorMsg() . "</p>";
           		 break;
         			}
		 }
		 else {
		 	$cust_credsrem = "";
		 	echo "<p class='tbl_error'>CONNECTION TYPE ERROR : CT54250029</p>";
		 	exit();
				}
return;
}






// ########## OTHER FUNCTION TO DETECT BROWSER (like browser_detection),SYSTEM OPERATOR AND SO ON ...
// ##########  SEE AT "detector_fll.php"



?>
Return current item: KSMS bulk sms manager