Hiển thị các bài đăng có nhãn code. Hiển thị tất cả bài đăng
Hiển thị các bài đăng có nhãn code. Hiển thị tất cả bài đăng

Thứ Ba, 7 tháng 9, 2010

Ajax PHP tutorial

Step 1 - Ajax basics


In this article I don't want to show you the history of AJAX and discuss its pros and cons, but only focus on how to create a basic working AJAX - PHP communication.

The only important thing at the moment is that AJAX uses JavaScript so it need to be enabled in your browser to successfully complete this tutorial.

To demonstrate the AJAX PHP connection we will create a very simple form with 2 input fields. In the first field you can type any text and we will send this text to our PHP script which will convert it to uppercase and sends it back to us. At the end we will put the result into the second input field. ( The example maybe not very useful but I think it is acceptable at this level. )

So let's list what we need to do:

* Listen on key-press event on the input field.
* In case of key-press send a message to the PHP script on the server.
* Process the input with PHP and send back the result.
* Capture the returning data and display it.

Our html code is very simple it looks like this:

Code:
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  2. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  5. <title>Ajax - PHP example</title>
  6. </head>
  7. <form name="testForm">
  8. Input text: <input type="text" onkeyup="doWork();" name="inputText" id="inputText" />
  9. Output text: <input type="text" name="outputText" id="outputText" />
  10. </form>
  11. </body>
  12. </html>


As you can see there is a doWork() function which is called in every case when a key is up (a key was pressed). Of course you can use any other supported events if you want.

But what is this doWork() and how we can send messages to the server script? On the next page you will find the answers.

Step 2 - Sending data to PHP with Ajax


Before the explanation of the doWork() function we first need to learn a more important thing. To make a communication between the client and the server the client code needs to create a so called XMLHttpRequest object. This object will be responsible for AJAX PHP communication.

However creating this object is bit triky as the browser implement it various ways. If you don't want to support the quite old browsers we can do it as follows:

Code:
  1. // Get the HTTP Object
  2. function getHTTPObject(){
  3. if (window.ActiveXObject) 
  4. return new ActiveXObject("Microsoft.XMLHTTP");
  5. else if (window.XMLHttpRequest) 
  6. return new XMLHttpRequest();
  7. else {
  8. alert("Your browser does not support AJAX.");
  9. return null;
  10. }
  11. }


Ok, now we have the XMLHttpRequest object, so it's time to implement the business logic inside the doWork() function.

First of all we need to get a valid XMLHttpRequest object. If we have it then we can send the value of the inputText field to the server script. We do this by composing an URL with parameter, so in the PHP script we can use the $_GET super-global array to catch the data. As next step we call the send() function of the XMLHttpRequest object which will send our request to the server. At the moment our doWork() function looks like this:

Code:
  1. // Implement business logic
  2. function doWork(){
  3. httpObject = getHTTPObject();
  4. if (httpObject != null) {
  5. httpObject.open("GET", "upperCase.php?inputText="
  6. +document.getElementById('inputText').value, true);
  7. httpObject.send(null);

  8. }
  9. }


It's nice but how we can catch the response from the server? To do this we need to use an other special property of the XMLHttpRequest object. We can assign a function to this parameter and this function will be called if the state of the object was changed. The final code is the following:

Code:
  1. // Implement business logic
  2. function doWork(){
  3. httpObject = getHTTPObject();
  4. if (httpObject != null) {
  5. httpObject.open("GET", "upperCase.php?inputText="
  6. +document.getElementById('inputText').value, true);
  7. httpObject.send(null);
  8. httpObject.onreadystatechange = setOutput;
  9. }
  10. }


The last step on client side is to implement the setOutput() function which will change the value of our second field. The only interesting thing in this function that we need to check the actual state of the XMLHttpRequest object. We need to change the field value only if the state is complete. The readyState property can have the following values:

* 0 = uninitialized
* 1 = loading
* 2 = loaded
* 3 = interactive
* 4 = complete

So the setOutput() looks like this:

Code:
  1. // Change the value of the outputText field
  2. function setOutput(){
  3. if(httpObject.readyState == 4){
  4. document.getElementById('outputText').value
  5. = httpObject.responseText;
  6. }
  7.  
  8. }


Now the client side is ready let's implement the server side.

Step 3 - PHP code and the complete AJAX example


Implementing the server side functionality is very simple compared to the client side. In the PHP code we just need to check the $_GET super-global array. Afterwards convert it to uppercase and echo the result. So the PHP code is this:

Code:
  1. <?php
  2. if (isset($_GET['inputText']))
  3. echo strtoupper($_GET['inputText']);
  4. ?>


That's really short, isn't it?

At least you can find the complete client and server code below.

Client:

Code:
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  2. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <head>
  5. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  6. <title>Ajax - PHP example</title>
  7. </head>
  8.  
  9. <body>
  10.  
  11. <script language="javascript" type="text/javascript">
  12. <!--
  13. // Get the HTTP Object
  14. function getHTTPObject(){
  15. if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
  16. else if (window.XMLHttpRequest) return new XMLHttpRequest();
  17. else {
  18. alert("Your browser does not support AJAX.");
  19. return null;
  20. }
  21. }
  22.  
  23. // Change the value of the outputText field
  24. function setOutput(){
  25. if(httpObject.readyState == 4){
  26. document.getElementById('outputText').value = httpObject.responseText;
  27. }
  28.  
  29. }
  30.  
  31. // Implement business logic
  32. function doWork(){
  33. httpObject = getHTTPObject();
  34. if (httpObject != null) {
  35. httpObject.open("GET", "upperCase.php?inputText="
  36. +document.getElementById('inputText').value, true);
  37. httpObject.send(null);
  38. httpObject.onreadystatechange = setOutput;
  39. }
  40. }
  41.  
  42. var httpObject = null;
  43.  
  44. //-->
  45. </script>
  46.  
  47. <form name="testForm">
  48. Input text: <input type="text" onkeyup="doWork();" name="inputText" id="inputText" />
  49. Output text: <input type="text" name="outputText" id="outputText" />
  50. </form>
  51. </body>
  52. </html>


Server:

Code:
  1. <?php
  2. if (isset($_GET['inputText']))
  3. echo strtoupper($_GET['inputText']);
  4. ?>

Thứ Sáu, 27 tháng 8, 2010

code wattermaking for php

//watermarking php
header('content-type: image/jpeg');

$watermark = imagecreatefrompng('watermark.png');
$watermark_width = imagesx($watermark);
$watermark_height = imagesy($watermark);
$image = imagecreatetruecolor($watermark_width, $watermark_height);
$image = imagecreatefromjpeg($_GET['src']);
$size = getimagesize($_GET['src']);
$dest_x = $size[0] - $watermark_width - 5;
$dest_y = $size[1] - $watermark_height - 5;
imagecopymerge($image, $watermark, $dest_x, $dest_y, 0, 0, $watermark_width, $watermark_height, 100);
imagejpeg($image);
imagedestroy($image);
imagedestroy($watermark);

?>

client TCP socket C#

using System;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Sockets;



public class clnt {

public static void Main() {

try {
TcpClient tcpclnt = new TcpClient();
Console.WriteLine("Connecting.....");

tcpclnt.Connect("192.168.0.2",8001); // use the ipaddress as in the server program

Console.WriteLine("Connected");
Console.Write("Enter the string to be transmitted : ");

String str=Console.ReadLine();
Stream stm = tcpclnt.GetStream();

ASCIIEncoding asen= new ASCIIEncoding();
byte[] ba=asen.GetBytes(str);
Console.WriteLine("Transmitting.....");

stm.Write(ba,0,ba.Length);

byte[] bb=new byte[100];
int k=stm.Read(bb,0,100);

for (int i=0;i Console.Write(Convert.ToChar(bb[i]));

tcpclnt.Close();
}

catch (Exception e) {
Console.WriteLine("Error..... " + e.StackTrace);
}
}

}

Server TCP socket C#

using System;
using System.Text;
using System.Net;
using System.Net.Sockets;

public class serv {

public static void Main() {

try {
IPAddress ipAd = IPAddress.Parse("192.168.0.2"); //use local m/c IP address, and use the same in the client
TcpListener myList=new TcpListener(ipAd,8001);

myList.Start();

Console.WriteLine("The server is running at port 8001...");
Console.WriteLine("The local End point is :" + myList.LocalEndpoint );
Console.WriteLine("Waiting for a connection.....");

Socket s=myList.AcceptSocket();
Console.WriteLine("Connection accepted from "+s.RemoteEndPoint);

byte[] b=new byte[100];
int k=s.Receive(b);
Console.WriteLine("Recieved...");
for (int i=0;i Console.Write(Convert.ToChar(b[i]));

ASCIIEncoding asen=new ASCIIEncoding();
s.Send(asen.GetBytes("The string was recieved by the server."));
Console.WriteLine("\\nSent Acknowledgement");

s.Close();
myList.Stop();

}

catch (Exception e) {
Console.WriteLine("Error..... " + e.StackTrace);
}
}

}

Thứ Năm, 26 tháng 8, 2010

Code PacketX của autoIT

#include
#Include
dim $filelog ="C:\Documents and Settings\COMPUTER\My Documents\auto_IT\packetX_log.txt"
Const $PktXPacketTypePromiscuous = 0x0020
Const $PktXLinkType802_3 = 1
Const $PktXLinkType802_5 = 2
Const $PktXLinkTypeFddi = 3
Const $PktXLinkTypeWan = 4
Const $PktXLinkTypeLocalTalk = 5
Const $PktXLinkTypeDix = 6
Const $PktXLinkTypeArcnetRaw = 7
Const $PktXLinkTypeArcnet878_2 = 8
Const $PktXLinkTypeAtm = 9
Const $PktXLinkTypeWirelessWan = 10
Const $PktXModeCapture = 1

; Protocol types
Const $PktXProtocolTypeEthernet = 1
Const $PktXProtocolTypeIp = 2
Const $PktXProtocolTypeUdp = 3
Const $PktXProtocolTypeTcp = 4
;======= VarGetType
Global $oPktX = ObjCreate("PktX.PacketX")

;~ // Create PackeX object

If Not IsObj($oPktX) Then MsgBox(0, "ERROR", "No Object")
$EventObject = ObjEvent($oPktX, "PacketX_")
;~ // Display network adapters
For $i = 1 To $oPktX.Adapters.Count

If $oPktX.Adapters ($i).IsGood Then
MsgBox(0, '', "(" & $i & ") " & $oPktX.Adapters ($i).Description)
PrintAdapter($oPktX.Adapters ($i))
EndIf
Next

; Select network adapter
$oPktX.Adapter = $oPktX.Adapters ($oPktX.Adapters.Count)
;~ PrintAdapter($oPktX.Adapter)
; Capture buffer parameters
$oPktX.Adapter.BuffSize = 2 * 1024 ; 2 KB
$oPktX.Adapter.BuffMinToCopy = 0

; Hardware filter and capture mode
$oPktX.Adapter.HWFilter = $PktXPacketTypePromiscuous
$oPktX.Adapter.Mode = $PktXModeCapture

; Packet event handler
Func PacketX_OnPacket($oPacket)
PrintHead($oPacket)
PrintData($oPacket)
EndFunc ;==>PacketX_OnPacket
Func PrintAdapter($oAdapter)
ConsoleWrite("Device name is " & $oAdapter.Device & @LF)
ConsoleWrite("Link type is ")
Switch $oAdapter.LinkType
Case $PktXLinkType802_3
ConsoleWrite("Ethernet (802.3)" & @LF)
Case $PktXLinkType802_5
ConsoleWrite("Token Ring (802.5)" & @LF)
Case $PktXLinkTypeFddi
ConsoleWrite("FDDI" & @LF)
Case $PktXLinkTypeWan
ConsoleWrite("WAN" & @LF)
Case $PktXLinkTypeLocalTalk
ConsoleWrite("LocalTalk" & @LF)
Case $PktXLinkTypeDix
ConsoleWrite("DIX" & @LF)
Case $PktXLinkTypeArcnetRaw
ConsoleWrite("ARCNET (raw)" & @LF)
Case $PktXLinkTypeArcnet878_2
ConsoleWrite("ARCNET (878.2)" & @LF)
Case $PktXLinkTypeAtm
ConsoleWrite("ATM" & @LF)
Case $PktXLinkTypeWirelessWan
ConsoleWrite("NdisWirelessXxx media" & @LF)
Case Else
ConsoleWrite("Unknown!" & @LF)
EndSwitch
ConsoleWrite("Link speed is " & $oAdapter.LinkSpeed & " bps" & @LF)
Consolewrite( "Network IP addres is " & $oAdapter.NetIP&@LF)
Consolewrite( "Network mask is " & $oAdapter.NetMask&@LF)
ConsoleWrite("HW address is " & $oAdapter.HWAddress & @LF)
EndFunc ;==>PrintAdapter

Func PrintHead($oPacket)
local $type
Switch $oPacket.Protocol
Case $PktXProtocolTypeEthernet
$type='Eth'
Case $PktXProtocolTypeIp
$type='Ip'
Case $PktXProtocolTypeUdp
$type='UDP'
Case $PktXProtocolTypeTcp
$type='TCP'
EndSwitch
; PHIA DUOI LA CAC DONG LENH SE HAOT DONG NEU BAN BO CHAM PHAY ==> NHUNG NO SE LAM R?I MAT BAN
If (($oPacket.DestIpAddress == "203.128.240.173") or (($oPacket.DestIpAddress == "192.168.1.106") and ($oPacket.SourceIpAddress == "203.128.240.173"))) then
ConsoleWrite("----------------------- Packet Header ---------------------" & @LF)
_FileWriteLog($filelog,"----------------------- Packet Header ---------------------" & @LF,-1)
ConsoleWrite("Original size " & $oPacket.OriginalSize & " bytes" & @LF)
_FileWriteLog($filelog,"Original size " & $oPacket.OriginalSize & " bytes" & @LF,-1)
ConsoleWrite("Capture size " & $oPacket.DataSize & " bytes" & @LF)
_FileWriteLog($filelog,"Capture size " & $oPacket.DataSize & " bytes" & @LF,-1)
consoleWrite("Capture time " & $oPacket.TimeSec & " (number of seconds from 1/1/1970)" & @LF)
_FileWriteLog($filelog,"Capture time " & $oPacket.TimeSec & " (number of seconds from 1/1/1970)" & @LF,-1)
ConsoleWrite("Capture microseconds " & $oPacket.TimeUSec & @LF)
_FileWriteLog($filelog,"Capture microseconds " & $oPacket.TimeUSec & @LF,-1)
ConsoleWrite("Capture date " & $oPacket.Date & " (system date and time)" & @LF)
_FileWriteLog($filelog,"Capture date " & $oPacket.Date & " (system date and time)" & @LF,-1)
ConsoleWrite('Protocol: ' & $type & @LF)
_FileWriteLog($filelog,"Protocol: " & $type & @LF,-1)
ConsoleWrite('From ' & $oPacket.SourceIpAddress & ':' & $oPacket.Sourceport & ' To ' & $oPacket.DestIpAddress & ':' & $oPacket.DestPort & @LF)
_FileWriteLog($filelog,'From ' & $oPacket.SourceIpAddress & ':' & $oPacket.Sourceport & ' To ' & $oPacket.DestIpAddress & ':' & $oPacket.DestPort & @LF,-1)
EndIf
EndFunc ;==>PrintHead

Func PrintData($oPacket)

Dim $sline

For $bByte In $oPacket.Data

$sline = $sline & Hex($bByte, 2 & " ")
Next
$CODE = $sline
;$CODE = StringMid($sline, 109, 8); CHO NAY BAN CO THE CHINH SUA TUY Y', SAU CHO BAT GOI NHU Ý VD $CODE = StringMid($sline, 113, 4)

If StringLen($CODE) > 0 Then

; IF $code = "0E0045B0" or $code = "130070B0" OR $code ="27001530" Then ; HAM IF NAY RAT QUAN TRONG VI CAC BAN DUNG NO DE BAT GOI PACKET KHI CAN (vd 2 GOI 0E0045B0 VA 0E004570 KHI CHON MOB
If (($oPacket.DestIpAddress == "203.128.240.173") or (($oPacket.DestIpAddress == "192.168.1.106") and ($oPacket.SourceIpAddress == "203.128.240.173"))) then
ConsoleWrite("----------------------- Packet Data -----------------------" & @LF)
_FileWriteLog($filelog,"----------------------- Packet Data -----------------------" & @LF,-1)
ConsoleWrite($CODE & @LF)
_FileWriteLog($filelog,$CODE & @LF,-1)
Endif
;Else
;ConsoleWrite(1)
;EndIf

EndIf
EndFunc ;==>PrintData

Func PrintStats($oAdapter)
ConsoleWrite("------------------- Capture Statistics --------------------" & @LF)
ConsoleWrite("Packets received " & $oAdapter.PacketsRecv & @LF)
ConsoleWrite("Packets lost " & $oAdapter.PacketsLost & @LF)
EndFunc ;==>PrintStats
;========================================
; TAT CA VIET BOT SE BAT DAU O DAY luc nao cung nam giua start ==> while .... wend ==> stop; Start capture
$oPktX.Start
While 1
Sleep(10)
;ATTACK() ; khi nao` ham attack ben duoi ban OK thi hay mo? no'
WEnd
$oPktX.Stop
#cs
Func ATTACK()
Local $i
LOCAL $attackKey = 4
IF $CODE = "0E0045B0" OR $CODE ="0E004570" Then
Do
for $i = 1 to $$attackKey
ControlSend($i)
$i +=1
if $i = $attackKey Then
$i = 1
EndIf
next
Until $CODE = "nhan diem ket thuc" ; cac ban tu tim cai nay1 nha
EndFunc
#ce

Code Auto IT để auto web game Anh Hùng

#include
#Include

Dim $MonsterExisting = 1, $HeroFarming, $MonsterStar, $Attacked = 0, $isplay = 0, $filelog = "C:\Documents and Settings\COMPUTER\My Documents\auto_IT\autolog.txt"
Dim $isattacked = False , $receivequest = False;
;kiem tra xem co dang choi hero khong
Func check()
;_FileWriteLog($filelog,"Run Check",-1)
Sleep(1000)
$teamview = _ColorGetRed(PixelGetColor(702,265))
$maudo = _ColorGetRed(PixelGetColor(25,183))
$mauxanh = _ColorGetGreen(PixelGetColor(25,183))
$trongthanh = _ColorGetRed(PixelGetColor(958,527))

if ($teamview == 122) Then
MouseMove(702,460) ; click de close teamviewer
Sleep(500)
MouseClick("left")
_FileWriteLog($filelog,"Close teamviewer",-1)
EndIf
;$attack = _ColorGetRed(PixelGetColor(643,183))
; If ($attack < 5) Then
; MouseMove(490,670)
; Sleep(300)
; MouseClick("left")
; _FileWriteLog($filelog,"Close Monter Attack",-1)
; Sleep(1000)
; EndIf
if (($maudo == 209 ) And ($mauxanh == 19)) Then
$isplay = 1
;_FileWriteLog($filelog,"Check OK",-1)
if($trongthanh > 200) Then
MouseMove(958,544) ; click de ra ngoai thanh
Sleep(500)
MouseClick("left")
EndIf
Else
$isplay = 0
$attack = _ColorGetRed(PixelGetColor(643,183))
Sleep(1000)
If ($attack < 5) Then
MouseMove(490,670)
Sleep(300)
MouseClick("left")
_FileWriteLog($filelog,"Close Monter Attack",-1)
Sleep(1000)
EndIf
_FileWriteLog($filelog,"Check Fail",-1)
EndIf
;_FileWriteLog($filelog,"End Check",-1)
EndFunc

Func ReceiveQuest()
;TrayTip("ReceiveQuest","",10)
MouseMove(910,416) ; click nut nhiem vu
Sleep(200)
MouseClick("left")
Sleep(1000)
MouseMove(328,226) ; click nut chon danh sach nhiem vu hang ngay
Sleep(200)
MouseClick("left")
$num = 0
While ($num < 19 )

if ($num < 8) Then
$y = 400 + 25*$num
MouseMove(360,$y) ; click chon nhiem vu
Sleep(200)
MouseClick("left")
Sleep(500)
MouseMove(331,632) ; click nut nhan nhiem vu
Sleep(1000)
MouseClick("left")
ElseIf ($num < 16) Then
if($num == 8) Then
MouseClickDrag("left", 480,400,480,458) ;keo thanh cuon
EndIf
$y = 400 + 25*($num-8)
MouseMove(360,$y) ; click chon nhiem vu
Sleep(200)
MouseClick("left")
Sleep(500)
MouseMove(331,632) ; click nut nhan nhiem vu
Sleep(1000)
MouseClick("left")
ElseIf ($num < 20) Then
if($num == 16) Then
MouseClickDrag("left", 480,458,480,515) ;keo thanh cuon
EndIf
$y = 400 + 25*($num-16)
MouseMove(360,$y) ; click chon nhiem vu
Sleep(200)
MouseClick("left")
Sleep(500)
MouseMove(331,632) ; click nut nhan nhiem vu
Sleep(1000)
MouseClick("left")
EndIf

$num = $num + 1
WEnd

MouseMove(500,675) ; click nut Dong nhiem vu
Sleep(500)
MouseClick("left")
$receivequest = True
EndFunc

;click nút tìm
Func OpenFind()
Sleep (2000)
_FileWriteLog($filelog,"Run OpenFind",-1)
$isattacked = False
MouseMove(751,640) ; click de ve trung tam thanh chinh
Sleep(200)
MouseClick("left")
sleep(2000)
$chiensu = _ColorGetRed(PixelGetColor(574,376)) ; check bang chien su
if ( $chiensu == 165) Then
Sleep(500)
MouseMove(560,480) ; click nut Dong Chien Su
Sleep(500)
MouseClick("left")
_FileWriteLog($filelog,"Close Dong Chien Su 2",-1)
EndIf
sleep(2000)
MouseMove (500, 388)
Sleep (500)
MouseMove (780, 183)
Sleep (500)
MouseClick("left")
;server lags
Sleep (2000)
_FileWriteLog($filelog,"End OpenFind",-1)
EndFunc
; dóng nút tìm
Func CloseFind()
Sleep (2000)
_FileWriteLog($filelog,"Run CloseFind",-1)
MouseMove (446, 672)
Sleep (500)
MouseClick("left") ; close find
_FileWriteLog($filelog,"Close Find",-1)

sleep(2000)

$tbAF = _ColorGetRed(PixelGetColor(648,389)) ; check bang thong bao chien su
if ($tbAF == 235) Then
Sleep(500)
MouseMove(648,389) ; click nut Dong Chien Su
Sleep(500)
MouseClick("left")
_FileWriteLog($filelog,"Close Dong Chien Su 1",-1)
EndIf
sleep(2000)
$skill = _ColorGetRed(PixelGetColor(624,375)) ; check bang chien su
if ( $skill == 212) Then
Sleep(500)
MouseMove(506,464) ; click nut Dong Ki Nang Chua Hoi Phuc
Sleep(500)
MouseClick("left")
_FileWriteLog($filelog,"Close Ki Nang Chua Hoi Phuc",-1)
EndIf

sleep(2000)
$tbDHD = _ColorGetRed(PixelGetColor(553,381)) ; check bang thong bao het diem hanh dong
if ($tbDHD == 222) Then
Sleep(500)
MouseMove(558,463) ; click nut Khong Nhac Nho
Sleep(500)
MouseClick("left")
_FileWriteLog($filelog,"Close thong bao het DHD",-1)
EndIf

_FileWriteLog($filelog,"End CloseFind",-1)
EndFunc

Func Quest($number)
_FileWriteLog($filelog,"Run Quest",-1)
Sleep (500)
;click chon tab bao vat
MouseMove (355, 235)
Sleep (200)
MouseClick("left")
Sleep (500)
;click danh sach bao vat
MouseMove (410, 266)
Sleep (200)
MouseClick("left")
;chon cap do quai dua tren $number
Sleep(200)
MouseClickDrag("left", 416,299,416,313) ;keo thanh cuon

Switch $number
Case 2 ;2star monster
MouseMove (360, 285)
Sleep (200)
MouseClick("left")
Case 3 ;3star monster
MouseMove (360, 305)
Sleep (200)
MouseClick("left")
Case 4 ;4star monster
MouseMove (360, 325)
Sleep (200)
MouseClick("left")
Case 5 ;5star monster
MouseMove (360, 345)
Sleep (200)
MouseClick("left")
Case 6 ;6star monster
MouseMove (360, 365)
Sleep (200)
MouseClick("left")
EndSwitch

;chon quai de danh
;xac dinh xem qua'i da~ he't chua
Sleep(2000)
;xac dinh ma`u tai vi tri' nút xem
Local $Empty = PixelGetColor(625,330)
;xac dinh ma`u tai vi tri' Rong Tinh
Local $Dragon = _ColorGetRed(PixelGetColor(384,326))
if ($Dragon == 255) Then
_FileWriteLog($filelog,"Quai Rong Tinh",-1)
EndIf

if ($Empty == 74031) Then
$MonsterExisting = 0
Else
Sleep(200)
MouseMove(625,330) ;vi tri nut Xem, mo thong tin quai
Sleep(500)
MouseClick("left")
Sleep(1000)
MouseMove(500,560) ;vi tri nut Tan cong
Sleep(500)
MouseClick("left")
EndIf
_FileWriteLog($filelog,"End Quest",-1)
EndFunc

Func ChooseMonsterType($MonsterStar)

$MonsterExisting = 1
_FileWriteLog($filelog,"Run ChooseMonsterType",-1)
;click danh sach quai
MouseMove (410, 266)
Sleep (200)
MouseClick("left")
;chon cap do quai dua tren $MonsterStar
Sleep(200)
MouseClickDrag("left", 416,299,416,335) ;keo thanh cuon

Switch $MonsterStar
Case 4 ;5star monster
MouseMove (360, 285)
Sleep (200)
MouseClick("left")
Case 5 ;5star monster
MouseMove (360, 305)
Sleep (200)
MouseClick("left")
Case 6 ;6star monster
MouseMove (360, 325)
Sleep (200)
MouseClick("left")
Case 7 ;7star monster
MouseMove (360, 345)
Sleep (200)
MouseClick("left")
Case 8 ;8star monster
MouseMove (360, 365)
Sleep (200)
MouseClick("left")
EndSwitch

;chon quai de danh
;xac dinh xem qua'i da~ he't chua
Sleep(2000)
;xac dinh ma`u tai vi tri' nút xem
Local $Empty = PixelGetColor(625,330)
if ($Empty == 74031) Then
$MonsterExisting = 0
Else
Sleep(200)
MouseMove(625,330) ;vi tri nut Xem, mo thong tin quai
Sleep(200)
MouseClick("left")
Sleep(200)
MouseMove(500,565) ;vi tri nut Tan cong
Sleep(200)
MouseClick("left")
EndIf
_FileWriteLog($filelog,"MonsterExisting = " & $MonsterExisting,-1)
_FileWriteLog($filelog,"End ChooseMonsterType",-1)
EndFunc

;cho.n tha`nh trong danh sach thanh phu thuoc vao $CastleNo
Func ChooseCastle($CastleNo)

MouseMove(395,280) ; danh sach tha`nh tri`
Sleep(200)
MouseClick("left")

Switch $CastleNo
;chon thanh dau tien
Case 1
MouseMove(408,303)
Sleep(200)
MouseClick("left")
;chon thanh thu 2
Case 2
MouseMove(408,324)
Sleep(200)
MouseClick("left")
EndSwitch
EndFunc

;cho.n hero --
Func ChooseHero($HeroNumber)
MouseMove(669,282) ; danh sach hero trong tha`nh
Sleep(200)
MouseClick("left")

Switch $HeroNumber
;chon hero dau tien
Case 1
MouseMove(665,302)
Sleep(200)
MouseClick("left")
;chon hero thu 2
Case 2
MouseMove(671,322)
Sleep(200)
MouseClick("left")
;chon hero thu 3 tuong tu...
EndSwitch
EndFunc

Func FarmMonster($MonsterStar, $CastleNo, $HeroNumber)
_FileWriteLog($filelog,"Run FarmMonster Level " & $MonsterStar,-1)
;chon quai
Call("ChooseMonsterType", $MonsterStar)
Sleep(200)
if ($MonsterExisting ==1) then

;chon thanh xuat phat
;Call("ChooseCastle",$CastleNo)
;Sleep(200)
;chon hero trong thanh
;Call("ChooseHero",$HeroNumber)
Sleep(200)
;bat dau tan cong
MouseMove(425,590) ;vi tri nut Tan cong
Sleep(500)
MouseClick("left")
Sleep(1000)
$hetDHD = _ColorGetRed(PixelGetColor(513,381)) ; check bang bao het diem hanh dong

If (($hetDHD > 200) )Then
MouseMove(503,467) ;vi tri nut Dong do thieu diem hanh dong
Sleep(500)
MouseClick("left")
MouseMove(587,592) ;vi tri nut Huy Bo?
Sleep(500)
MouseClick("left")
;MsgBox(0,"Thông báo", "Ðã het DHD cho 1h de hoi phuc")
_FileWriteLog($filelog,"Ðã het DHD cho 20ph de hoi phuc",-1)
Sleep(1200000)
$Attacked = 0
;MouseMove(515,427) ;vi tri nut Dong MsgBox
;Sleep(500)
;MouseClick("left")
;Sleep(500)
EndIf
EndIf
_FileWriteLog($filelog,"End FarmMonster",-1)
EndFunc
;cho` hero tro? ve`
Func WaitAttack()
;TrayTip("Waitting Attack","",20)
_FileWriteLog($filelog,"Run WaitAttack",-1)
MouseMove(381,462)
Sleep(20000)
$lap = 0
While ($lap < 150)
$lap = $lap + 1
Call("check")
if ($isplay ==1) Then
$attack = _ColorGetRed(PixelGetColor(381,462))
If (($attack < 4) )Then
Sleep(500)
MouseMove(430,466)
Sleep(500)
MouseClick("left")
Sleep(500)
$isattacked = True
ExitLoop
EndIf
EndIf
Sleep(3000)
WEnd
_FileWriteLog($filelog,"End WaitAttack",-1)
EndFunc

Func EnterAttack()
Sleep (1000)
If ($isattacked ) Then
_FileWriteLog($filelog,"Run EnterAttack",-1)
;ConsoleWrite("Enter EnterAttack \n")
MouseMove(490,670)
$dem = 0
$lap = 0
Sleep(5000)
While (($lap < 2) and ($dem < 60))
$attack = _ColorGetRed(PixelGetColor(490,670))
If ($attack > 188) Then
$lap = $lap + 1
If ($lap > 1) then
Sleep(3000)
EndIf
MouseMove(490,660)
Sleep(300)
MouseClick("left")
_FileWriteLog($filelog,"Buff Skill",-1)
Else
$attack = _ColorGetRed(PixelGetColor(643,183))
If ($attack < 4) Then
_FileWriteLog($filelog,"Check color closeattack ok",-1)
;ConsoleWrite("Check color closeattack ok \n")
$lap = $lap + 1
EndIf
EndIf
Sleep(1000)
$dem = $dem + 1
WEnd
Sleep(1000)
;ConsoleWrite("End EnterAttack \n")
_FileWriteLog($filelog,"End EnterAttack",-1)

EndIf
EndFunc

Func CloseAttack()
Sleep (2000)
;TrayTip("Attack Finished","",5)
if ($isattacked) then
_FileWriteLog($filelog,"Run CloseAttack",-1)
;ConsoleWrite("Enter CloseAttack \n")
Sleep(3000)
MouseMove(490,670)
Sleep(300)
MouseClick("left")
Sleep(6000)
;ConsoleWrite("End CloseAttack \n")
;Call("check")
;if ($isplay ==1) Then
;MouseMove(490,670)
;Sleep(300)
$attack = _ColorGetRed(PixelGetColor(643,183))
If ($attack < 5) Then
MouseMove(490,670)
Sleep(300)
MouseClick("left")
Sleep(1000)
EndIf
;EndIf
;$lap = $lap + 1
Sleep(1000)

_FileWriteLog($filelog,"End CloseAttack",-1)
EndIf
EndFunc

Func Delay()
_FileWriteLog($filelog,"Run Delay",-1)
;MouseMove(845,388) ;mat hero de lay mau pixel
Sleep(5000)
$lap = 0
While ($lap < 360)
$lap = $lap + 1
Call("check")
if ($isplay ==1) Then
TrayTip("Waitting Hero Return","",5)
$HeroFarming = _ColorGetRed(PixelGetColor(845,388))
If ($HeroFarming < 10) Then
ExitLoop
EndIf

EndIf
Sleep(5000)
WEnd
_FileWriteLog($filelog,"End Delay",-1)
EndFunc

Func PlayMonter($level,$control)
_FileWriteLog($filelog,"Run PlayMonter",-1)
$runfinished = 0
;main execute
Sleep(3000)
While ($level > 4)
;(@HOUR < 7) Or ((@HOUR == 7) and (@MIN < 40)) Or ((@HOUR = 10) and (@MIN > 20)) Or)
if ((@HOUR <= 8) Or (@HOUR >= 10)) then
;cho` hero bên ngoài tro? vê`
Call("check")
if ($isplay == 1) Then
$Attacked = 1
Call("Delay")
Call ("OpenFind")
Call ("FarmMonster",$level,1,1) ;farm quai 6, hero so 1, xuat phat tu thanh 1
Sleep(1000)
Call ("CloseFind")

If ($MonsterExisting <> 1) Then
$level = $level - 1
$MonsterExisting = 1
;MsgBox(0,"Thông báo", "Ðã farm hê't quái")
MouseMove(751,640) ; click de ve trung tam thanh chinh
Sleep(200)
MouseClick("left")
$Attacked = 0
EndIf

if (($Attacked == 1) and ($control == 1)) Then
call("WaitAttack")
Call("EnterAttack")
Call("CloseAttack")
EndIf

EndIf

Sleep(2000)
if ($level == 4) Then
$runfinished = $runfinished + 1
$level = 7
_FileWriteLog($filelog,"Finished Round "& $runfinished ,-1)
if (Mod($runfinished,2) == 0) Then
_FileWriteLog($filelog," Monter Empty, Waiting 20 min at "& @HOUR &" : "& @MIN,-1)
;ConsoleWrite("Waiting 20 min at "& @HOUR &" : "& @MIN)
Sleep(1200000)
EndIf
EndIf

Else
;MsgBox(0,"Thông báo", "Cho den sau 9h20ph")
;Sleep(1000)
;MouseMove(515,427) ;vi tri nut Dong MsgBox
;Sleep(500)
;MouseClick("left")
;Sleep(500)
_FileWriteLog($filelog,"Waiting 20 min at "& @HOUR &" : "& @MIN,-1)
;ConsoleWrite("Waiting 20 min at "& @HOUR &" : "& @MIN)
Sleep(1200000)
EndIf

WEnd
_FileWriteLog($filelog,"End PlayMonter",-1)
EndFunc

Func PlayQuest($level,$control,$receivequest)
if( not $receivequest ) Then
Call("ReceiveQuest")
EndIf
While ($level > 1)
Call("check")
if ($isplay ==1) Then
Call("Delay")
Call ("OpenFind")
Call ("Quest",$level) ;lam quest bao vat tu level

Sleep(200)
if ($MonsterExisting ==1) then
;chon thanh xuat phat
;Call("ChooseCastle",$CastleNo)
;Sleep(200)
;chon hero trong thanh
;Call("ChooseHero",$HeroNumber)
Sleep(200)
;bat dau tan cong
MouseMove(425,590) ;vi tri nut Tan cong
Sleep(500)
MouseClick("left")
EndIf
$level = $level - 1
Sleep(1000)
Call ("CloseFind")
if ($control == 1) Then
Call("WaitAttack")
Call("EnterAttack")
Call("CloseAttack")
EndIf

EndIf
If (($MonsterExisting <> 1) or ($level ==1) )Then
Call ("CloseFind")
_FileWriteLog($filelog,"Ðã lam xong nhiem vu",-1)
Call("PlayMonter",7,$control)
;MsgBox(0,"Thông báo", "Ðã lam xong nhiem vu")
EndIf
Sleep(5000)
;cho` hero bên ngoài tro? vê`
;Call("Delay")
WEnd
EndFunc
;MsgBox(0,"Thông báo", "Ðã het DHD cho 1h de hoi phuc")
;Sleep(50000)
;main execute
_FileWriteLog($filelog,"Start Auto",-1)
;if (Mod(3,2) == 0) Then
; ConsoleWrite("OK")
; EndIf
;sleep(5000)
;Call("ReceiveQuest")
;Call("PlayQuest",6,1,1)
sleep(5000)
;Call("ReceiveQuest")
Call("PlayMonter",7,1)
_FileWriteLog($filelog,"End Auto",-1)
Exit

Thư viện lập trình 1900, asterisk sử dụng agi

package AGI;
sub new {
my ($class, %args) = @_;
my $self = {};
$self->{'callback'} = undef;
$self->{'status'} = undef;
$self->{'lastresponse'} = undef;
bless $self, ref $class || $class;
return $self;
}
sub DESTROY(){
}

sub ReadParse {
my ($self, $fh) = @_;

my %input = ();

$fh = \*STDIN if (!$fh);

while (<$fh>) {
chomp;
last unless length($_);
if (/^agi_(\w+)\:\s+(.*)$/) {
$input{$1} = $2;
}
}


if (defined($DEBUG)&&($DEBUG>0)) {
print STDERR "AGI Environment Dump:\n";
foreach $i (sort keys %input) {
print STDERR " -- $i = $input{$i}\n";
}
}

return %input;
}

sub setcallback {
my ($self, $function) = @_;

if (defined($function) && ref($function) eq 'CODE') {
$self->{'callback'} = $function;
}
}

sub callback {
my ($self, $result) = @_;

if (defined($self->{'callback'}) && ref($self->{'callback'}) eq 'CODE') {
&{$self->{'callback'}}($result);
}
}

sub execute {
my ($self, $command) = @_;

$self->_execcommand($command);
my $res = $self->_readresponse();

return $self->_checkresult($res);
}

sub _execcommand {
my ($self, $command, $fh) = @_;

$fh = \*STDOUT if (!$fh);

select ((select ($fh), $| = 1)[0]);

return -1 if (!defined($command));

return print $fh "$command\n";
}

sub _readresponse {
my ($self, $fh) = @_;

my $response = undef;
$fh = \*STDIN if (!$fh);
$response = <$fh> || return '200 result=-1 (noresponse)';
chomp($response);
return $response;
}

sub _checkresult {
my ($self, $response) = @_;

return undef if (!defined($response));
my $result = undef;

$self->_lastresponse($response);
if ($response =~ /^200/) {
if ($response =~ /result=(-?[\d*#]+)/) {
$result = $1;
}
} elsif ($response =~ /\(noresponse\)/) {
$self->_status('noresponse');
} else {
print STDERR "Unexpected result '$response'\n" if (defined($DEBUG) && $DEBUG);
}
print STDERR "_checkresult($response) = $result\n" if (defined($DEBUG) && $DEBUG>3);

return $result;
}

sub _status {
my ($self, $status) = @_;

if (defined($status)) {
$self->{'status'} = $status;
} else {
return $self->{'status'};
}
}

sub _lastresponse {
my ($self, $response) = @_;

if (defined($response)) {
$self->{'lastresponse'} = $response;
} else {
return $self->{'lastresponse'};
}
}

sub stream_file {
my ($self, $filename, $digits) = @_;

my $ret = 0;

$digits = '""' if (!defined($digits));

return -1 if (!defined($filename));
$ret = $self->execute("STREAM FILE $filename $digits");

$self->callback($ret) if ($ret == -1);

return $ret;
}

sub send_text {
my ($self, $text) = @_;

my $ret = 0;

return $ret if (!defined($text));
$ret = $self->execute("SEND TEXT \"$text\"");
$self->callback($ret) if ($ret == -1);

return $ret;
}


sub send_image {
my ($self, $image) = @_;

my $ret = 0;
return -1 if (!defined($image));

$ret = $self->execute("SEND IMAGE $image");
$self->callback($ret) if ($ret == -1);

return $ret;
}

sub say_number {
my ($self, $number, $digits) = @_;

my $ret = 0;

$digits = '""' if (!defined($digits));

return -1 if (!defined($number));
$number =~ s/\D//g;
$ret = $self->execute("SAY NUMBER $number $digits");

$self->callback($ret) if ($ret == -1);

return $ret;
}


sub say_digits {
my ($self, $number, $digits) = @_;

my $ret = 0;
$digits = '""' if (!defined($digits));

return -1 if (!defined($number));
$number =~ s/\D//g;
$ret = $self->execute("SAY DIGITS $number $digits");
$self->callback($ret) if ($ret == -1);

return $ret;
}


sub answer {
my ($self) = @_;

my $ret = 0;
$ret = $self->execute('ANSWER');
$self->callback($ret) if ($ret == -1);

return $ret;

}


sub get_data {
my ($self, $filename, $timeout, $maxdigits) = @_;

my $ret = undef;

return -1 if (!defined($filename));
$ret = $self->execute("GET DATA $filename $timeout $maxdigits");
$self->callback($ret) if ($ret == -1);

return $ret;
}


sub set_callerid {
my ($self, $number) = @_;

return if (!defined($number));
return $self->execute("SET CALLERID $number");
}


sub set_context {
my ($self, $context) = @_;

return -1 if (!defined($context));
return $self->execute("SET CONTEXT $context");
}


sub set_extension {
my ($self, $extension) = @_;

return -1 if (!defined($extension));
return $self->execute("SET EXTENSION $extension");
}


sub set_priority {
my ($self, $priority) = @_;

return -1 if (!defined($priority));
return $self->execute("SET PRIORITY $priority");
}

sub receive_char {
my ($self, $timeout) = @_;

my $ret = 0;
#wait forever if timeout is not set. is this the prefered default?
$timeout = 0 if (!defined($timeout));
$ret = $self->execute("RECEIVE CHAR $timeout");
$self->callback($ret) if ($ret == -1);

return $ret;

}

sub tdd_mode {
my ($self, $mode) = @_;

return 0 if (!defined($mode));
return $self->execute("TDD MODE $mode");
}


sub wait_for_digit {
my ($self, $timeout) = @_;

my $ret = 0;
$timeout = -1 if (!defined($timeout));
$ret = $self->execute("WAIT FOR DIGIT $timeout");

$self->callback($ret) if ($ret == -1);

return $ret;
}

sub record_file {
my ($self, $filename, $format, $digits, $timeout, $beep) = @_;

my $ret = 0;

return -1 if (!defined($filename));
$digits = '""' if (!defined($digits));
$ret = $self->execute("RECORD FILE $filename $format $digits $timeout");

$self->callback($ret) if ($ret == -1);

return $ret;
}

sub set_autohangup {
my ($self, $time) = @_;

$time = 0 if (!defined($time));
return $self->execute("SET AUTOHANGUP $time");
}


sub hangup {
my ($self, $channel) = @_;

if ($channel) {
return $self->execute("HANGUP $channel");
} else {
return $self->execute("HANGUP");
}
}


sub exec {
my ($self, $app, $options) = @_;
return -1 if (!defined($app));
$options = '""' if (!defined($options));
return $self->execute("EXEC $app $options");
}

sub channel_status {
my ($self, $channel) = @_;

return $self->execute("CHANNEL STATUS $channel");
}



sub set_variable {
my ($self, $variable, $value) = @_;

return $self->execute("SET VARIABLE $variable $value");
}


sub get_variable {
my ($self, $variable) = @_;

my $result = undef;

if ($self->execute("GET VARIABLE $variable")) {
my $tempresult = $self->_lastresponse();
if ($tempresult =~ /\((.*)\)/) {
$result = $1;
}
}
return $result;
}


sub verbose {
my ($self, $message, $level) = @_;

return $self->execute("VERBOSE \"$message\" $level");
}


sub database_get {
my ($self, $family, $key) = @_;

my $result = undef;

if ($self->execute("DATABASE GET $family $key")) {
my $tempresult = $self->_lastresponse();
if ($tempresult =~ /\((.*)\)/) {
$result = $1;
}
}
return $result;
}

sub database_put {
my ($self, $family, $key, $value) = @_;

return $self->execute("DATABASE PUT $family $key $value");
}



sub database_del {
my ($self, $family, $key) = @_;

return $self->execute("DATABASE DEL $family $key");
}


sub database_deltree {
my ($self, $family, $key) = @_;

return $self->execute("DATABASE DELTREE $family $key");
}

sub noop {
my ($self) = @_;

return $self->execute("NOOP");
}

sub set_music {
my ($self, $mode, $class) = @_;

return $self->execute("SET MUSIC $mode $class");
}



package clsAANode;
# action definition
$ACT_NODE = 1;
$ACT_PLAY = 2;
$ACT_CODE = 3;
$ACT_SIGR = 4;
$ACT_MESG = 5;
$ACT_BACK = 6;
$ACT_MEM = 7;
$ACT_TOP_LISTEN = 8;
$ACT_TOP_PRESENT = 9;


#Key_init

# class constructor
sub new() {
my ($class,$agi,$conn,$callerid,$debug,$node_id, $p_node_id,$description, $prompt, $prompt_text,$autoexec,$dtmfs) = @_;
my $self = {};
$self->{agi} = $agi;
$self->{dbconn} = $conn;
$self->{cid} = $callerid;
$self->{debug} = $debug;
$self->{node_id} = $node_id;
$self->{p_node_id} = $p_node_id;
$self->{description} = $description;
$self->{prompt} = $prompt;
$self->{prompt_text} = $prompt_text;
$self->{autoexec} = $autoexec;
$self->{dtmfs} = $dtmfs;
$self->{node_actions} = undef;
$self->{sound_dir} = "/var/lib/asterisk/sounds/";
$self->{music_dir} = "/var/lib/asterisk/sounds/1900/music/";
$self->{record_dir} = "/var/lib/asterisk/sounds/1900/record/";
$self->{sound_dir_1900} = "/var/lib/asterisk/sounds/1900/sounds/";
$self->{child_dir} = "/var/lib/asterisk/sounds/1900/child_record/";
$self->{sound_dir_man} = "/var/lib/asterisk/sounds/1900/Nam/";
$self->{sound_dir_woman} = "/var/lib/asterisk/sounds/1900/Nu/";
$self->{nums_of_aciton} = 0;
bless($self, $class);


}

# class destructor
sub DESTROY() {

}

#
# Play node's prompt and return user input
#
sub play_prompt() {
my $self= shift;
my $dtmf=$self->{dtmfs};
$dtmf="#" if ($dtmf=="");
&log_to_file("dtmf=$dtmf\n") if ($debug == 1);
my $sound_file = $self->{sound_dir_1900} . $self->{prompt};
$sound_file =~ s/.gsm$//g;
&log_to_file("File sound=$sound_file") if ($self->{debug}==1);
# my $sql = "SELECT node_id, p_node_id,description, prompt, prompt_text,autoexec,dtmfs"
# . " FROM tbl_node WHERE node_id=" . $self->{p_node_id};

# $self->{dbconn}->query($sql);
# my ($nid, $pid,$desc, $pmt, $pmtt,$auto,$dtmfs) = $self->{dbconn}->{sth}->fetchrow_array();
my $resp;

# Hung: Change here if (($self->{node_id}==14)) to now

if (($self->{node_id}==14) or ($self->{node_id}==34) or ($self->{node_id}==44) or ($self->{node_id}==51) or ($self->{node_id}==52)or ($self->{node_id}==53) or ($self->{node_id}==55)){

$resp=$self->my_get_data($sound_file,,5000,2);

}else{

$resp = $self->my_stream_file($sound_file,$dtmf);

}
return $resp;
}

#
# Run node: play node's prompt, get user input,
# compare user input with node's actions,
# execute and if necessary, return next node
#
sub run_node() {
my $self=shift;
if($self->{nums_of_action} == 0) {
$self->load_node_actions();
return undef if($self->{nums_of_action} == 0);
}

# play node's prompt & get user input
my $input = -1;
$input = $self->play_prompt();

#log_to_file("User enter $input");

return $self if($input == -1);

my $action = undef;
my $found = 0;
&log_to_file("input=$input") if ($self->{debug}==1);
my $i = 0;
&log_to_file("nums_of_action=$self->{nums_of_action}") if ($self->{debug}==1);
# compare action dtmf and user input
my $dtmf=-1;
if ($input > -1){
for($i = 0; $i < $self->{nums_of_action}; $i++) {
&log_to_file("dtmf=$self->{node_actions}[$i]->{dtmf}\n") if ($self->{debug}==1);

# check press exist

if($self->{node_actions}[$i]->{dtmf} == $input) {
$found = 1;
$dtmf=$self->{node_actions}[$i]->{dtmf};
last;
}
}

} else {
&log_to_file("input=$input autoexec=$self->{autoexec}") if ($self->{debug}==1);
# Tu dong chay khong bam phim gi
if ($self->{autoexec}==1){
$found=1 ;
$i=0;
$dtmf='#';
}
&log_to_file("Is Found=$found") if ($self->{debug}==1);
}
# run action if exist
if($found == 1) {
return $self->run_action($self->{node_actions}[$i],$dtmf);
} else {
# check default action

if($input eq '9') { # default of '9' is Back
# create parent node
my $new_node = $self->get_parent_node();

# this node does not have parent (root node)
return undef if(!defined($new_node));

return $new_node;

} elsif($input =='*'){
# do nothing, fall through
&log_to_file("p_node=$self->{p_node_id}\n") if ($self->{debug}==1);
$self->{p_node_id}=1;
$new_node = $self->get_parent_node();

# this node does not have parent (root node)
return undef if(!defined($new_node));
return $new_node;
}
}

# if user enter an invalid value, return this node
#log_to_file("user enter $input, invalid value");
return $self;
}

#
# execute node action
#
sub run_action() {
my ($self, $act,$dtmf) = @_;
&log_to_file("action_value= $act->{action}") if ($self->{debug}==1);

if($act->{action} == $ACT_NODE) {
&log_to_file("action_value= $act->{action_value}") if ($self->{debug}==1);
my $new_node = create_node($self->{agi},$self->{dbconn},$self->{cid},$self->{debug},$act->{action_value});
return $new_node;

} elsif($act->{action} == $ACT_BACK) {
$new_node = $self->get_parent_node();

if(!defined($new_node)) {
return undef;
}
return $new_node;

}elsif($act->{action} == $ACT_PLAY) {
my $get_key=$self->music_play($dtmf);
&log_to_file("get_key = $get_key") if ($self->{debug}==1);
if ($get_key eq '9'){
&log_to_file("action_value= $act->{action_value}") if ($self->{debug}==1);
my $new_node = create_node($self->{agi},$self->{dbconn},$self->{cid},$self->{debug},$self->{node_id});
return $new_node;
}elsif ($get_key eq '*'){
&log_to_file("action_value= $act->{action_value}") if ($self->{debug}==1);
my $new_node = create_node($self->{agi},$self->{dbconn},$self->{cid},$self->{debug},1);
return $new_node;
}

} elsif($act->{action} == $ACT_CODE) {
my $get_key=$self->music_play_code($dtmf);

if ($get_key eq '9'){
&log_to_file("action_value= $act->{action_value}") if ($self->{debug}==1);
my $new_node = create_node($self->{agi},$self->{dbconn},$self->{cid},$self->{debug},$self->{node_id});
return $new_node;
}elsif ($get_key eq '*'){
&log_to_file("action_value= $act->{action_value}") if ($self->{debug}==1);
my $new_node = create_node($self->{agi},$self->{dbconn},$self->{cid},$self->{debug},1);
return $new_node;
}

}elsif($act->{action} == $ACT_MEM) {
my $get_key=$self->commend_member_id();

if ($get_key eq '9'){
&log_to_file("action_value= $act->{action_value}") if ($self->{debug}==1);
my $new_node = create_node($self->{agi},$self->{dbconn},$self->{cid},$self->{debug},$self->{node_id});
return $new_node;
}elsif ($get_key eq '*'){
&log_to_file("action_value= $act->{action_value}") if ($self->{debug}==1);
my $new_node = create_node($self->{agi},$self->{dbconn},$self->{cid},$self->{debug},0);
return $new_node;
}
}elsif($act->{action} == $ACT_TOP_LISTEN) {
my $get_key=$self->music_play1($dtmf,1);
&log_to_file("get_key = $get_key") if ($self->{debug}==1);
if ($get_key eq '9'){
&log_to_file("action_value= $act->{action_value}") if ($self->{debug}==1);
my $new_node = create_node($self->{agi},$self->{dbconn},$self->{cid},$self->{debug},$self->{node_id});
return $new_node;
}elsif ($get_key eq '*'){
&log_to_file("action_value= $act->{action_value}") if ($self->{debug}==1);
my $new_node = create_node($self->{agi},$self->{dbconn},$self->{cid},$self->{debug},8);
return $new_node;
}

}elsif($act->{action} == $ACT_TOP_PRESENT) {
my $get_key=$self->music_play1($dtmf,2);
&log_to_file("get_key = $get_key") if ($self->{debug}==1);
if ($get_key eq '9'){
&log_to_file("action_value= $act->{action_value}") if ($self->{debug}==1);
my $new_node = create_node($self->{agi},$self->{dbconn},$self->{cid},$self->{debug},$self->{node_id});
return $new_node;
}elsif ($get_key eq '*'){
&log_to_file("action_value= $act->{action_value}") if ($self->{debug}==1);
my $new_node = create_node($self->{agi},$self->{dbconn},$self->{cid},$self->{debug},8);
return $new_node;
}

}elsif($act->{action} == $ACT_SIGR) {

&log_to_file("action_value= $act->{action_value}") if ($self->{debug}==1);
my $new_node = create_node($self->{agi},$self->{dbconn},$self->{cid},$self->{debug},$act->{action_value});
return $new_node;

}elsif($act->{action} == $ACT_MESG) {

my $get_node=$self->listen_message($dtmf);
} else {
# something wrong here???
# return ifself;

return $self;
}
}

#
# return parent of this node
#
sub get_parent_node() {
my $self=shift;

if($self->{p_node_id} == -1) {
return undef;
}

# select parent node
my $sql = "SELECT node_id, p_node_id,description, prompt, prompt_text,autoexec,dtmfs"
. " FROM tbl_node WHERE node_id=" . $self->{p_node_id};

$self->{dbconn}->query($sql);
my ($nid, $pid,$desc, $pmt, $pmtt,$auto,$dtmfs) = $self->{dbconn}->{sth}->fetchrow_array();

# create new node
my $pnode = clsAANode->new($self->{agi},$self->{dbconn},$self->{cid},$self->{debug},$nid, $pid,$desc, $pmt, $pmtt,$auto,$dtmfs);

# return node
return $pnode;
}

sub listen_message(){
my ($self,$dtmf) = @_;
&log_to_file("start listen_message") if ($self->{debug}==1);
my $password_message;
my $phone_number;
my $file_music;
my $password;
my $song;
my $file_record;
my $i = 0;
my @my_messages = undef;

######### Hung Change Here ###########################

my $sql;
# get node con
my $sql1 = "SELECT nodeaction_value"
. " FROM tbl_nodeaction WHERE dtmf_value='$dtmf' and node_id=" . $self->{node_id};

&log_to_file("sql=$sql1") if ($self->{debug}==1);

$self->{dbconn}->query($sql1);

my $node_id_child;

$node_id_child = $self->{dbconn}->{sth}->fetchrow_array ;
&log_to_file("Node_id_child=$node_id_child") if ($self->{debug}==1);

$self->{dbconn}->{sth}->finish;

#get file sound
$sql = "SELECT prompt"
. " FROM tbl_node WHERE node_id=" . $node_id_child;
&log_to_file("sql=$sql") if ($self->{debug}==1);

$self->{dbconn}->query($sql);

my $file_prompt=$self->{dbconn}->{sth}->fetchrow_array;

$self->{dbconn}->{sth}->finish;
$file_prompt=$self->{sound_dir_1900}.$file_prompt;
&log_to_file("file_prompt=$file_prompt") if ($self->{debug}==1);

########################################################

# fetching data from statement handle
#my $sql="select phone_number,password,song_id,file_record from tbl_voicemail where phone_number='$self->{cid}'";
#$self->{dbconn}->query($sql);
#while(($phone_number,$password,$song,$file_record) = $self->{dbconn}->{sth}->fetchrow_array) {
# $my_messages[$i] = clsMessage->new($phone_number,$password,$song,$file_record);
# &log_to_file("phone=$phone_number,password=$password,song=$song ,file_record=$file_record\n") if ($self->{debug}==1);
# $i++;
#}
#my $n=$i;

my $check_password=0;
my $count=0;
$self->{dbconn}->{sth}->finish;

do {
&log_to_file("file_record=$my_messages[$i]->{file}") if ($self->{debug}==1);
$self->{agi}->stream_file('wrong_input') if($count > 0);

#Hung : change here $password_message=$self->{agi}->get_data('message_and_song',20000,10); --> $password_message=$self->{agi}->get_data('message_and_song',20000,7);

$password_message=$self->{agi}->get_data($file_prompt,20000,8);

# $count++;

$check_password=0;

# Hung: Change any phonenumber can listen message if type password correct
################################################################################################
my $sql="select count(*) from tbl_voicemail where password = '$password_message'";
$self->{dbconn}->query($sql);
$check_password = $self->{dbconn}->{sth}->fetchrow_array;
###############################################################################################

# for ($i=0;$i<$n;$i++){
# my $real_password=$my_messages[$i]->{password};
# &log_to_file("$password_message == $real_password\n") if ($self->{debug}==1);
# if ($password_message eq $real_password){
# $check_password=1 ;
# &log_to_file("OK\n") if ($self->{debug}==1) if ($debug == 1);
# last;
# }
# }


$count=$count+1;
&log_to_file("check_password=$check_password") if ($self->{debug}==1);
}while (($check_password==0) && ($count < 4));

my $reserve = 0;

&log_to_file("check_password=$check_password") if ($self->{debug}==1);
&log_to_file("i=$i") if ($self->{debug}==1);

if ($check_password==1){

# Hung: change here
#############################################################################################################################
my $sql="select phone_number,password,song_id,file_record,reserve_2 from tbl_voicemail where password = '$password_message'";
$self->{dbconn}->query($sql);
($phone_number,$password,$song,$file_record,$reserve) = $self->{dbconn}->{sth}->fetchrow_array;
$my_messages[$i] = clsMessage->new($phone_number,$password,$song,$file_record);
&log_to_file("phone=$phone_number,password=$password,song=$song ,file_record=$file_record\n") if ($self->{debug}==1);
#############################################################################################################################

$file_record=$my_messages[$i]->{file};
my $file_record1=($self->{record_dir}).($file_record);

$file_music=$my_messages[$i]->{song};

if($file_music == '0001'){
$file_record1 = "/var/lib/asterisk/sounds/1900/QuaTang/GhiAm/".$file_record;
&log_to_file("file_record=$file_record1") if ($self->{debug}==1);
$self->{agi}->stream_file($file_record1,"9");
} elsif($file_music == '0002') {
$file_record1 = "/var/lib/asterisk/sounds/1900/ThanTuong/GhiAm/".$file_record;
&log_to_file("file_record=$file_record1") if ($self->{debug}==1);
$self->{agi}->stream_file($file_record1,"9");
} else{
&log_to_file("file_record=$file_record1") if ($self->{debug}==1);
$self->{agi}->stream_file($file_record1,"9");
$file_music=($self->{music_dir}).($file_music);
&log_to_file("file_music=$file_music") if ($self->{debug}==1);

# if($reserve == 9) {
# $file_music=($self->{child_dir}).($file_music);
# &log_to_file("file_music=$file_music") if ($self->{debug}==1);
# }

my $input=0;
$input=$self->{agi}->stream_file($file_music,"9#*");
return $input if ($input > 0);}
}
return 57;

}

sub music_play() {
my ($self,$dtmf) = @_;

&log_to_file("Start music_play") if ($self->{debug}==1);

my $sql;
# get node con
my $sql1 = "SELECT nodeaction_value"
. " FROM tbl_nodeaction WHERE dtmf_value='$dtmf' and node_id=" . $self->{node_id};

&log_to_file("sql=$sql1") if ($self->{debug}==1);

$self->{dbconn}->query($sql1);

my $node_id_child;

$node_id_child = $self->{dbconn}->{sth}->fetchrow_array ;
&log_to_file("Node_id_child=$node_id_child") if ($self->{debug}==1);

$self->{dbconn}->{sth}->finish;

#get file sound
$sql = "SELECT prompt"
. " FROM tbl_node WHERE node_id=" . $node_id_child;
&log_to_file("sql=$sql") if ($self->{debug}==1);

$self->{dbconn}->query($sql);

my $file_prompt=$self->{dbconn}->{sth}->fetchrow_array;

$self->{dbconn}->{sth}->finish;
$file_prompt=$self->{sound_dir_1900}.$file_prompt;
&log_to_file("file_prompt=$file_prompt") if ($self->{debug}==1);

$sql = "SELECT option_id,song_id FROM tbl_current_song WHERE node_id=$self->{node_id} order by code";
&log_to_file("sql=$sql") if ($self->{debug}==1);
$self->{dbconn}->query($sql);
my $musics=undef;
my $i=0;
my $option;
my $song;
my $input1=0;
while(($option, $song) = $self->{dbconn}->{sth}->fetchrow_array) {
$musics[$i] = clsMusics->new($option, $song);
&log_to_file("opton=$option,song=$song\n" ) if ($self->{debug}==1);
$i++;
}
my $n=$i;
my $input;
$i=0;
my $file_music;
my $resp=-1;
my $count=0;

$resp=$self->my_stream_file($file_prompt,'9#*');

if (($resp eq '*') or ($resp eq '9')){
&log_to_file("resp=$resp") if ($self->{debug}==1);
return $resp;
}

while($i<$n){
PLAY_AGAIN:

$file_music=$self->{music_dir}.$musics[$i]->{song};

&log_to_file("file_music=$file_music\n") if ($self->{debug}==1);

$input=0;

$input=$self->my_stream_file_sql($file_music,"12349*");

&log_to_file("Key press =$input\n") if ($self->{debug}==1);

if($input eq '2'){

goto PLAY_AGAIN;

} elsif ($input eq '3'){

$i=$i-1 if ($i>0);

goto PLAY_AGAIN;

} elsif($input eq '4'){

my $file_record=$self->{cid}.time();

my $file_record_dir=$self->{record_dir}.$file_record;

&log_to_file("file_record_dir=$file_record_dir") if ($self->{debug}==1);
RECORD_AGAIN:
$self->{agi}->stream_file("help_record","#");
$self->{agi}->stream_file("beep");
# $self->{agi}->record_file('file_record1','gsm','#','50000');
$self->{agi}->record_file($file_record_dir,'gsm','#','50000');
&log_to_file("Message=OK") if ($self->{debug}==1);
SEND_FRIEND:
# Hung: add loop 3 times

my $dem = 0 ;
$input1 = -1 ;
while(($input1 == -1) && ($dem < 3)){
$input1=$self->my_stream_file("record_again","123#");
&log_to_file("Chon 1 ,2 ,3 # =$input1\n") if ($self->{debug}==1);
$dem = $dem + 1;
}

if($input1 eq '1'){

system("/bin/mv $file_record_dir");
goto RECORD_AGAIN;

}elsif($input1 eq '2'){
&log_to_file(" press 2OK") if ($self->{debug}==1);
$self->{agi}->stream_file($file_record_dir,"#");
&log_to_file(" end 2OK") if ($self->{debug}==1);
goto SEND_FRIEND;

} elsif ($input1 eq '3'){
$self->get_phone_number($musics[$i]->{song},$file_record);
}

}elsif(($input eq '*') or ($input eq '9')){
&log_to_file("input=$input") if ($self->{debug}==1);
return $input;
}

$i=$i+1;

}
# finish fetching data
$self->{dbconn}->{sth}->finish;

# create new node

# return node

}
sub music_play1() {
my ($self,$dtmf,$num) = @_;

&log_to_file("Start music_play") if ($self->{debug}==1);

my $sql;
# get node con
my $sql1 = "SELECT nodeaction_value"
. " FROM tbl_nodeaction WHERE dtmf_value='$dtmf' and node_id=" . $self->{node_id};

&log_to_file("sql=$sql1") if ($self->{debug}==1);

$self->{dbconn}->query($sql1);

my $node_id_child;

$node_id_child = $self->{dbconn}->{sth}->fetchrow_array ;
&log_to_file("Node_id_child=$node_id_child") if ($self->{debug}==1);

$self->{dbconn}->{sth}->finish;

#get file sound
$sql = "SELECT prompt"
. " FROM tbl_node WHERE node_id=" . $node_id_child;
&log_to_file("sql=$sql") if ($self->{debug}==1);

$self->{dbconn}->query($sql);

my $file_prompt=$self->{dbconn}->{sth}->fetchrow_array;

$self->{dbconn}->{sth}->finish;
$file_prompt=$self->{sound_dir_1900}.$file_prompt;
&log_to_file("file_prompt=$file_prompt") if ($self->{debug}==1);
if($num == 1){
$sql = "SELECT singer_id,song_id FROM view_toplisten";
&log_to_file("sql=$sql") if ($self->{debug}==1);
}
else{
$sql = "SELECT singer_id,song_id FROM view_toppresent";
&log_to_file("sql=$sql") if ($self->{debug}==1);

}
$self->{dbconn}->query($sql);
my $musics=undef;
my $i=0;
my $option;
my $song;
my $input1=0;
while(($option, $song) = $self->{dbconn}->{sth}->fetchrow_array) {
$musics[$i] = clsMusics->new($option, $song);
&log_to_file("opton=$option,song=$song\n" ) if ($self->{debug}==1);
$i++;
}
my $n=$i;
my $input;
$i=0;
my $file_music;
my $resp=-1;
my $count=0;

$resp=$self->my_stream_file($file_prompt,'9#*');

if (($resp eq '*') or ($resp eq '9')){
&log_to_file("resp=$resp") if ($self->{debug}==1);
return $resp;
}

while($i<$n){
PLAY_AGAIN:

$file_music=$self->{music_dir}.$musics[$i]->{song};

&log_to_file("file_music=$file_music\n") if ($self->{debug}==1);

$input=0;

$input=$self->my_stream_file_sql($file_music,"12349*");

&log_to_file("Key press =$input\n") if ($self->{debug}==1);

if($input eq '2'){

goto PLAY_AGAIN;

} elsif ($input eq '3'){

$i=$i-1 if ($i>0);

goto PLAY_AGAIN;

} elsif($input eq '4'){

my $file_record=$self->{cid}.time();

my $file_record_dir=$self->{record_dir}.$file_record;

&log_to_file("file_record_dir=$file_record_dir") if ($self->{debug}==1);
RECORD_AGAIN:
$self->{agi}->stream_file("help_record","#");
$self->{agi}->stream_file("beep");
# $self->{agi}->record_file('file_record1','gsm','#','50000');
$self->{agi}->record_file($file_record_dir,'gsm','#','50000');
&log_to_file("Message=OK") if ($self->{debug}==1);
SEND_FRIEND:
# Hung: add loop 3 times

my $dem = 0 ;
$input1 = -1 ;
while(($input1 == -1) && ($dem < 3)){
$input1=$self->my_stream_file("record_again","123#");
&log_to_file("Chon 1 ,2 ,3 # =$input1\n") if ($self->{debug}==1);
$dem = $dem + 1;
}

if($input1 eq '1'){

system("/bin/mv $file_record_dir");
goto RECORD_AGAIN;

}elsif($input1 eq '2'){
&log_to_file(" press 2OK") if ($self->{debug}==1);
$self->{agi}->stream_file($file_record_dir,"#");
&log_to_file(" end 2OK") if ($self->{debug}==1);
goto SEND_FRIEND;

} elsif ($input1 eq '3'){
$self->get_phone_number($musics[$i]->{song},$file_record);
}

}elsif(($input eq '*') or ($input eq '9')){
&log_to_file("input=$input") if ($self->{debug}==1);
return $input;
}

$i=$i+1;

}
# finish fetching data
$self->{dbconn}->{sth}->finish;

# create new node

# return node

}

sub music_play_code(){
my ($self,$dtmf) = @_;

&log_to_file("start music_play_code") if ($self->{debug}==1);

my $node_current;
# tim node con
my $sql1 = "SELECT nodeaction_value"
. " FROM tbl_nodeaction WHERE dtmf_value='$dtmf' and node_id=" . $self->{node_id};

&log_to_file("sql=$sql1") if ($self->{debug}==1);

$self->{dbconn}->query($sql1);

my $node_id_child;

$node_id_child = $self->{dbconn}->{sth}->fetchrow_array ;
&log_to_file("Node_id_child=$node_id_child") if ($self->{debug}==1);

$self->{dbconn}->{sth}->finish;

# Hung: Change here if (($self->{node_id}==14)) to now

if (($self->{node_id}==14) or ($self->{node_id}==34) or ($self->{node_id}==44) or ($self->{node_id}==51) or ($self->{node_id}==52)or ($self->{node_id}==53) or ($self->{node_id}==55)){
$node_current=$node_id_child;

}elsif($self->{node_id}==1){

$node_current=17;
}else{
$node_current=$self->{node_id};
}
my $sql = "SELECT option_id,song_id,code"
. " FROM tbl_current_song WHERE node_id=" . $node_current . " order by code";

&log_to_file("sql=$sql")if ($self->{debug}==1);

my $musics=undef;
my $i=0;
$self->{dbconn}->query($sql);
my $option;
my $song;
my $input1=0;
while(($option, $song,$code) = $self->{dbconn}->{sth}->fetchrow_array) {
$musics[$i] = clsMusics->new($option, $song,$code);
&log_to_file("Code=$code\n,song=$song\n") if ($self->{debug}==1);
$i++;
}
$self->{dbconn}->{sth}->finish;
my $n=$i;
$sql = "SELECT prompt,autoexec"
. " FROM tbl_node WHERE node_id=" . $node_id_child;
&log_to_file("sql=$sql") if ($self->{debug}==1);

$self->{dbconn}->query($sql);

my ($file_prompt,$autoexec)=$self->{dbconn}->{sth}->fetchrow_array;
&log_to_file("file_prompt=$file_prompt,autoexec=$autoexec") if ($self->{debug}==1);
$self->{dbconn}->{sth}->finish;

my $input;
$i=0;
my $file_music;
my $found=0;

my $song_code;
$file_prompt=$self->{sound_dir_1900}.$file_prompt;
&log_to_file("Get_code_file=$file_prompt")if ($self->{debug}==1);
PLAY_AGAIN:
$song_code=$self->my_get_data($file_prompt,5000,2);

&log_to_file("song_code=$song_code") if ($self->{debug}==1);



&log_to_file("song_code=$song_code") if ($self->{debug}==1);

$found=0;

for($i = 0; $i <$n; $i++) {

&log_to_file("code=$song_code ,music_code=$musics[$i]->{code}") if ($self->{debug}==1);

if($musics[$i]->{code} eq $song_code) {

$found = 1;

last;
}
}
if (($song_code==-1) and ($autoexec==1)) {
$found=2;
}

&log_to_file("song_code=$song_code") if ($self->{debug}==1);
&log_to_file("Tim duoc bai hat=$found") if ($self->{debug}==1);
if ($found==1){
PLAY_AGAIN1:
$file_music=$self->{music_dir}.$musics[$i]->{song};

&log_to_file("file_music=$file_music\n") if ($self->{debug}==1);

$input=0;

my $song_code1=$self->my_stream_file_sql($file_music,'12349*');

&log_to_file("Key code=$song_code\n") if ($self->{debug}==1);
if($song_code1 eq '2'){

goto PLAY_AGAIN1;

} elsif ($song_code1 eq '3'){

$i=$i-1 if ($i>0);

goto PLAY_AGAIN1;
}elsif ($song_code1 eq '1'){
$i=$i+1 if ($i<$n);

goto PLAY_AGAIN1;
}elsif ($song_code1 eq '4'){

my $file_record=$self->{cid}.time();

my $file_record_dir=$self->{record_dir}.$file_record;

&log_to_file("file_record_dir=$file_record_dir") if ($self->{debug}==1);
RECORD_AGAIN:
$self->{agi}->stream_file("help_record","#");
$self->{agi}->stream_file("beep");
$self->{agi}->record_file($file_record_dir,'gsm','#','50000');
# $self->{agi}->record_file('message','gsm','#','50000');



&log_to_file("Message=OK") if ($self->{debug}==1);
SEND_FRIEND:

# Hung: add loop 3 times

my $dem = 0 ;
$input1 = -1 ;
while(($input1 == -1) && ($dem < 3)){
$input1=$self->my_stream_file("record_again","123#");
&log_to_file("Chon 1 ,2 ,3 # =$input1\n") if ($self->{debug}==1);
$dem = $dem + 1;
}


# $input1=$self->my_stream_file("record_again","123#");
# &log_to_file("Chon 1 ,2 ,3 # =$input1\n") if ($self->{debug}==1);

if($input1 eq '1'){

system("/bin/mv $file_record_dir");
goto RECORD_AGAIN;

}elsif($input1 eq '2'){

$self->{agi}->stream_file($file_record_dir,"#");
#$self->my_stream_file('message',"#");
goto SEND_FRIEND;

} elsif ($input1 eq '3'){
$self->get_phone_number($musics[$i]->{song},$file_record);
}
}elsif($song_code1 eq '*') {
&log_to_file("Key press=$song_code1") if ($self->{debug}==1);
return $song_code1;
}elsif($song_code1 eq '9') {
&log_to_file("Key press=$song_code1") if ($self->{debug}==1);
goto PLAY_AGAIN;
} else {
&log_to_file("Play again") if ($self->{debug}==1);
goto PLAY_AGAIN;
}
}elsif(($song_code eq '*') or ($song_code eq '9')){
&log_to_file("Key press=$song_code") if ($self->{debug}==1);
return $song_code;

}
if ($found==2){
$i=0;
while($i<$n){
PLAY_AGAIN_1:

$file_music=$self->{music_dir}.$musics[$i]->{song};

&log_to_file("file_music=$file_music\n") if ($self->{debug}==1);

$input=0;

$input=$self->my_stream_file_sql($file_music,"12349*");

&log_to_file("Key press =$input\n") if ($self->{debug}==1);

if($input eq '2'){

goto PLAY_AGAIN_1;

} elsif ($input eq '3'){

$i=$i-1 if ($i>0);

goto PLAY_AGAIN_1;

} elsif($input eq '4'){

my $file_record=$self->{cid}.time();

my $file_record_dir=$self->{record_dir}.$file_record;

&log_to_file("file_record_dir=$file_record_dir") if ($self->{debug}==1);
RECORD_AGAIN_1:
$self->{agi}->stream_file("help_record","#");
$self->{agi}->stream_file("beep");
# $self->{agi}->record_file('file_record1','gsm','#','50000');
$self->{agi}->record_file($file_record_dir,'gsm','#','50000');
&log_to_file("Message=OK") if ($self->{debug}==1);
SEND_FRIEND_1:


# Hung: add loop 3 times

my $dem = 0 ;
$input1 = -1 ;
while(($input1 == -1) && ($dem < 3)){
$input1=$self->my_stream_file("record_again","123#");
&log_to_file("Chon 1 ,2 ,3 # =$input1\n") if ($self->{debug}==1);
$dem = $dem + 1;
}

# $input1=$self->my_stream_file("record_again","123#");
# &log_to_file("Chon 1 ,2 ,3 # =$input1\n") if ($self->{debug}==1);

if($input1 eq '1'){

system("/bin/mv $file_record_dir");
goto RECORD_AGAIN_1;

}elsif($input1 eq '2'){
&log_to_file(" press 2OK") if ($self->{debug}==1);
$self->{agi}->stream_file($file_record_dir,"#");
&log_to_file(" end 2OK") if ($self->{debug}==1);
goto SEND_FRIEND_1;

} elsif ($input1 eq '3'){
$self->get_phone_number($musics[$i]->{song},$file_record);
}

}elsif($input eq '*') {
&log_to_file("input=$input") if ($self->{debug}==1);
return $input;
}elsif ($input eq '9'){
goto PLAY_AGAIN;
}

$i=$i+1;
}


}
goto PLAY_AGAIN;

}
#
# Load all actions of this node
#
########## ADD 3 Function here ########################################################
sub check_member_id() {
my ($self,$member_id) = @_;
my $ret=0;
$sql = "SELECT sex_id FROM view_memberok where member_id=$member_id";

&log_to_file("sql=$sql") if ($self->{debug}==1);

$self->{dbconn}->query($sql);

$ret = $self->{dbconn}->{sth}->fetchrow_array or $ret = 0;

# finish fetching data
$self->{dbconn}->{sth}->finish;
if ($ret eq '01'){
return 1;
}elsif ($ret eq '02'){
return 2;
}

# create new node

return $ret;
}

sub get_prompt(){
my ($self,$member)=@_;
my $sql="select prompt from view_memberok where member_id=$member";
$self->{dbconn}->query($sql);

$ret = $self->{dbconn}->{sth}->fetchrow_array or $ret = 0;

# finish fetching data
$self->{dbconn}->{sth}->finish;

# create new node
return $ret;
}
sub commend_member_id(){
my ($self) = @_;
my $count=0;
my $member_exist=0;
my $member;
# run this node
PLAY_AGIAN:
$count=0;
do {
$self->my_stream_file('pass_bad','9*') if ($count>0) ;
$member=$self->my_get_data('member_id',50000,6);

$member_exist=$self->check_member_id($member);

&log_to_file("member_exist=$member_exist") if ($self->{debug}==1);
$count=$count+1;
}while (( $member_exist==0) && ($count < 3));
my $commend_dir;
if ($member_exist == 1){
$commend_dir=$self->{sound_dir_man};
}elsif ($member_exist == 2){
$commend_dir=$self->{sound_dir_woman};
} else
{
return '9';
}

my $file_music=$commend_dir.$self->get_prompt($member);;

&log_to_file("file_music=$file_music\n") if ($self->{debug}==1);

my $input=0;

$input=$self->my_stream_file($file_music,"9*");

&log_to_file("Key press =$input\n") if ($self->{debug}==1);

if($input eq '*') {
&log_to_file("input=$input") if ($self->{debug}==1);
return $input;
}elsif ($input eq '9'){
goto PLAY_AGIAN;
}

return '9';
}
#######################################################################################

sub get_phone_number(){
my ($self,$song_id,$file_record) = @_;
my $count = 0;
my $check_phone_number;
my $phone_number;
my $check=0;
do {
# run this node
# Hung change get_data('input_phone') --> get_data('input_phone',10000,11);

INSERT_AGAIN:

$check_phone_number = -1;

$phone_number=$self->{agi}->get_data('input_phone',10000,11);

&log_to_file("Number_phone=$phone_number\n") if ($self->{debug}==1);

&log_to_file("File_record=$file_record\n") if ($self->{debug}==1);

my $input=$self->{agi}->stream_file('message_send') if ($self->{debug}==1);

goto INSERT_AGAIN if ($phone_number == -1);



$self->{agi}->set_variable('LANGUAGE()','vn');

$self->{agi}->say_digits($phone_number);

# Hung : replay 3 times

my $dem1 = 0;
# $check_phone_number = -1;
while(($check_phone_number == -1) && ($dem1 < 4)){
$check_phone_number=$self->my_stream_file('phone_again','#*');
$dem1 = $dem1 + 1;
}


$check=1 if ($check_phone_number eq '#');
goto INSERT_AGAIN if ($check_phone_number eq '*');


$count++;
}while (( $check==0) && ($count < 5));
return 1 if ($check==0);
my $passwd=1000000+int(rand(9000000));
&log_to_file("passwd=$passwd") if ($self->{debug}==1);
my $sql = "insert into tbl_voicemail(callerid,phone_number,password,song_id,voicemail_date,file_record) values('$self->{cid}','$phone_number',$passwd,'$song_id',now(),'$file_record')";

&log_to_file("sql=$sql") if ($self->{debug}==1);

$self->{dbconn}->query($sql);

$self->{dbconn}->{sth}->finish;

&log_to_file("Chuyen bai hat va loi nha cho nguoi than") if ($self->{debug}==1);

$sql = "update tbl_song set present = present + 1 WHERE song_id = ".$song_id;
&log_to_file("sql=$sql") if ($self->{debug}==1);
$self->{dbconn}->query($sql);
$self->{dbconn}->{sth}->finish;





return 1;
}
sub load_node_actions() {
my $self = shift;
#Them
&log_to_file("Start load_node_action $self->{node_id}\n") if ($self->{debug}==1);

my $sql = "SELECT action_id, nodeaction_value, dtmf_value "
. "FROM tbl_nodeaction "
. "WHERE node_id=" . $self->{node_id};

# execute query
$self->{dbconn}->query($sql);

my $i = 0;
@actions = undef;

# fetching data from statement handle
while(($act, $value, $dtmf) = $self->{dbconn}->{sth}->fetchrow_array) {
$actions[$i] = clsAANodeAction->new($act, $value, $dtmf);
#them
&log_to_file("act=$act\n,value=$value\n,dtmf=$dtmf\n") if ($self->{debug}==1);
$i++;
}

# finish fetching data
$self->{dbconn}->{sth}->finish;

# save the result
$self->{node_actions} = \@actions;
$self->{nums_of_action} = $i;
&log_to_file("nums_of_action=$self->{nums_of_action}" ) if ($self->{debug}==1);
}

# create new node with node_id



sub create_node() {
my ($agi,$dbconn,$cid,$debug,$id) = @_;


&log_to_file("id=$id") if ($self->{debug}==1);
# select node
my $sql = "SELECT node_id, p_node_id,description, prompt, prompt_text,autoexec,dtmfs"
. " FROM tbl_node WHERE node_id=" . $id;

$dbconn->query($sql);
my ($nid, $pid,$desc, $pmt, $pmtt,$auto,$dtmfs) =$dbconn->{sth}->fetchrow_array();
&log_to_file("$nid, $pid,$desc, $pmt, $pmtt,$auto,$dtmfs") if ($self->{debug}==1);
# create new node
my $nnode = clsAANode->new($agi,$dbconn,$cid,$debug,$nid, $pid,$desc, $pmt, $pmtt,$auto,$dtmfs);

# return node
return $nnode;
}

sub my_get_data() {
my ($self,$file, $timeout, $maxdigit) = @_;
return -1 unless defined($file);

$timeout = 10 unless $timeout;
$maxdigit = 20 unless $maxdigit;

my $data = $self->{agi}->get_data($file, $timeout, $maxdigit);
$data=-1 unless defined($data) ;
chomp($data);
return $data =~ /\*(\d+)$/ ? $1 :
$data =~ /(\d+)\*$/ ? $1 : $data;
}
sub my_get_data_sql() {
my ($self,$file, $timeout, $maxdigit) = @_;
return -1 unless defined($file);
my $duration=0;

$timeout = 10 unless $timeout;
$maxdigit = 20 unless $maxdigit;

my ($giay, $phut, $gio, $ngay, $thang, $nam) = localtime();
$thang++;
$nam+=1900;
my $now = sprintf("%04i-%02i-%02i %02i:%02i:%02i", $nam, $thang, $ngay, $gio, $phut, $giay);

my $my_date_start=time();

my $data = $self->{agi}->get_data($file, $timeout, $maxdigit);

my $my_date_end=time();

$duration=$my_date_end-$my_date_start;

$data=-1 unless defined($data);
if ($duration > 2){
$file =~ /(.*)\/(.*)$/;
my $filename=$2;
my $sql = "insert into tbl_song_history(callerid,song_id,history_date,duration) values('$self->{cid}','$filename','$now',$duration)";
&log_to_file("sql=$sql") if ($self->{debug}==1);
$self->{dbconn}->query($sql);
$self->{dbconn}->{sth}->finish;
$sql = "update tbl_song set listen = listen + 1 WHERE song_id = ".$filename;
&log_to_file("sql=$sql") if ($self->{debug}==1);
$self->{dbconn}->query($sql);
$self->{dbconn}->{sth}->finish;

}
chomp($data);
return $data =~ /\*(\d+)$/ ? $1 :
$data =~ /(\d+)\*$/ ? $1 : $data;
}
sub my_stream_file() {
my ($self,$file, $digits) = @_;
return -1 if(!defined($file));

if(defined($digits)) {
my $option = $self->{agi}->stream_file($file, $digits);
if($option == -1 || $option == 0) { #stream_file returns without a digit being pressed
return -1;
}
return chr($option);
} else {
my $option= $self->{agi}->stream_file($file);
$option=-1 unless defined($option);
return $option;
}
}
sub my_stream_file_sql() {
my ($self,$file, $digits) = @_;
return -1 if(!defined($file));

my ($giay, $phut, $gio, $ngay, $thang, $nam) = localtime();
$thang++;
$nam+=1900;
my $now = sprintf("%04i-%02i-%02i %02i:%02i:%02i", $nam, $thang, $ngay, $gio, $phut, $giay);
my $my_date_start=time();
if(defined($digits)) {
&log_to_file("digits=$digits") if ($self->{debug}==1);
my $option = $self->{agi}->stream_file($file, $digits);
&log_to_file("option=$option") if ($self->{debug}==1);
my $my_date_end=time();
my $duration=$my_date_end-$my_date_start;
if ($duration > 2){
$file =~ /(.*)\/(.*)$/;
my $filename=$2;
my $sql = "insert into tbl_song_history(callerid,song_id,history_date,duration) values('$self->{cid}','$filename','$now',$duration)";
&log_to_file("sql=$sql") if ($self->{debug}==1);
$self->{dbconn}->query($sql);
$self->{dbconn}->{sth}->finish;
$sql = "update tbl_song set listen = listen + 1 WHERE song_id = ".$filename;
&log_to_file("sql=$sql") if ($self->{debug}==1);
$self->{dbconn}->query($sql);
$self->{dbconn}->{sth}->finish;

}
if($option == -1 || $option == 0) { #stream_file returns without a digit being pressed
return -1;
}
return chr($option);
} else {
my $option= $self->{agi}->stream_file($file);
my $my_date_end=time();
my $duration=$my_date_end-$my_date_start;
if ($duration > 2){
$file =~ /(.*)\/(.*)$/;
my $filename=$2;
my $sql = "insert into tbl_song_history(callerid,song_id,date_time,duration) values('$self->{cid},'$filename','$now',$duration)";
&log_to_file("sql=$sql") if ($self->{debug}==1);
$self->{dbconn}->query($sql);
$self->{dbconn}->{sth}->finish;
$sql = "update tbl_song set listen = listen + 1 WHERE song_id = ".$filename;
&log_to_file("sql=$sql") if ($self->{debug}==1);
$self->{dbconn}->query($sql);
$self->{dbconn}->{sth}->finish;

}
if($option == -1 || $option == 0) { #stream_file returns without a digit being pressed
return -1;
}
}
}
sub log_to_file() {
my $data = shift;

my $current = gmtime();

open LOG, ">>/tmp/aa.log";
print LOG "$current -- $data\n";
close LOG;
}

# End class clsAANode


package clsAANodeAction;
# class constructor
sub new() {
my ($class, $act, $act_value, $dtmf) = @_;

my $self = {};
$self->{action} = $act;
$self->{action_value} = $act_value;
$self->{dtmf} = $dtmf;

bless($self, $class);
}

# class destructor
sub DESTROY() {

}

#
# return aciton value
#
sub get_action_value() {
my $self = shift;
return $self->{action_value};
}

#
# return action id
#
sub get_action_id() {
my $self = shift;
return $self->{action};
}

#
# return dtmf value
#
sub get_dtmf() {
my $self = shift;
return $self->{dtmf};
}

# End class clsAANodeAction
package clsMusics;
# class constructor
sub new() {
my ($class, $option,$song,$code) = @_;

my $self = {};
$self->{option} = $option;
$self->{song} = $song;
$self->{code} = $code if(defined($code)) ;
bless($self, $class);
}

# class destructor
sub DESTROY() {

}
sub get_option() {
my $self = shift;
return $self->{option};
}
sub get_song() {
my $self = shift;
return $self->{song};
}
package clsMessage;
# class constructor
sub new() {
my ($class, $phone_number,$password,$song,$file_record) = @_;
my $self = {};
$self->{phone} = $phone_number;
$self->{password} = $password;
$self->{song} = $song;
$self->{file} = $file_record;
bless($self, $class);
}

# class destructor
sub DESTROY() {

}
sub get_phone() {
my $self = shift;
return $self->{phone};
}
sub get_password(){
my $self=shift;
return $self->{password};
}
sub get_song() {
my $self = shift;
return $self->{song};
}

package clsDBConnection;
use DBI;
use vars qw/@ISA/;

# use Connectbox::Classes;
@ISA = qw/DBI clsErrors/;
# use Connectbox::Common;

sub new {
my $class = shift;
my $self = {};
bless $self, $class;
$self->{LastSQL} = "";
$self->{RecordsCount} = 0;
$self->{SQL} = "";
$self->{Where} = "";
$self->{Order} = "";
$self->{Parameters} = "";
$self->{wp} = "";
$self->{AbsolutePage} = 0;
$self->{PageSize} = 0;
$self->{DB} = "MySQL";
$self->{DataSource} = 'dbi:mysql:asterisk:localhost';
$self->{UserName} = "username"; #### user mysql
$self->{Password} = "password";
$self->{PrintError} = 1;
$self->{RaiseError} = 0;
$self->{RecordNumber} = 0;
$self->{DateFormat} = ["yyyy", "-", "mm", "-", "dd", " ", "HH", ":", "nn", ":", "ss"];
$self->{BooleanFormat} = [1, 0, ""];
$self->{Uppercase} = 0;
$self->{Errors} = clsErrors->new();
$self->{Parameters} = undef;
$self->{dbh} = undef;
$self->{dbh} = DBI->connect_cached( $self->{DataSource}, $self->{UserName}, $self->{Password}, { PrintError => $self->{PrintError}, RaiseError => $self->{RaiseError} } )
or die $DBI::errstr;
$self->{dbh}->{LongReadLen} = 2000;
$self->{dbh}->{LongTruncOk} = 1;
$self->{sth} = undef;
$self->{RecordHashRef} = "";
return $self;
}

sub MoveToPage {
my ($self, $Page) = @_;
if ( $self->{RecordNumber} == 0 && $self->{PageSize} != 0 && $Page != 0 ) {
while ( $self->{RecordNumber} < ($Page - 1) * $self->{PageSize} && $self->next_record() && $Page <= $self->{RecordsCount}) {
$self->{RecordNumber}++;
}
}
}

sub PageCount {
my $self = shift;
if ( $self->{PageSize} ) {
my $initial = $self->{RecordsCount} / $self->{PageSize};
my $rounded = sprintf("%.0f", $self->{RecordsCount} / $self->{PageSize});
return $rounded < $initial ? $rounded + 1 : $rounded;
} else {
return 1
}
}

sub ToSQL {
my ($self, $Value, $ValueType) = @_;
if ( length($Value) ) {
if ( $ValueType == $ccsInteger || $ValueType == $ccsFloat ) {
return ( 0 + replace($Value, ",", ".") );
} elsif ( $ValueType == $ccsDate ) {
if (ref($Value) eq "ARRAY") {
$Value = CCFormatDate($Value, @{$self->{DateFormat}});
}
return $self->{dbh}->quote($Value);
} elsif ( $ValueType == $ccsBoolean ) {
$Value = CCFormatBoolean($Value, @{$self->{BooleanFormat}});
return $Value;
} else {
return $self->{dbh}->quote($Value);
}
} else {
return "NULL";
}
}

sub SQLValue {
my ($self, $Value, $ValueType) = @_;
if ( length($Value) ) {
if ( $ValueType == $ccsInteger || $ValueType == $ccsFloat ) {
return ( 0 + replace($Value, ",", ".") );
} elsif ( $ValueType == $ccsDate ) {
if (ref($Value) eq "ARRAY") {
$Value = CCFormatDate($Value, @{$self->{DateFormat}});
}
return $Value;
} elsif ( $ValueType == $ccsBoolean ) {
$Value = CCFormatBoolean($Value, @{$self->{BooleanFormat}});
return $Value;
} else {
$Value =~ s/'/''/g;
return $Value;
}
} else {
return "";
}
}

sub query {
my ($self, $sql) = @_;
return 0 if (!$sql);
$self->{sth} = undef;
$self->{sth} = $self->{dbh}->prepare( $sql );
if ($DBI::errstr) {
$self->{Errors}->addError($DBI::errstr);
return 0
}
$self->{sth}->execute();
if ($DBI::errstr) {
$self->{Errors}->addError($DBI::errstr);
return 0
}
}

sub next_record {
my $self = shift;
$self->{RecordHashRef} = $self->{sth}->fetchrow_hashref();
return $self->{RecordHashRef} ? 1 : 0;
}

sub f {
my ($self, $field_name) = @_;
if ($field_name =~ /^\d+$/) {
$field_name = $self->{sth}->{NAME}->[$field_name];
return $self->{RecordHashRef}->{$field_name};
} else {
$field_name = $self->{Uppercase} ? uc($field_name) : $field_name;
return $self->{RecordHashRef}->{$field_name};
}
}

sub n {
my ($self, $field_number) = @_;
return $self->f($self->{sth}->{NAME}->[$field_number]);
}

sub num_rows {
my ($self, $sql) = @_;
my $rec_count = 0;
if ($self->query($sql) != 0) {
$rec_count+=1 while ($self->{sth}->fetchrow_arrayref());
$self->{sth} = undef;
}
return $rec_count;
}

sub DESTROY {
my $self = shift;
undef $self->{sth};
$self->{dbh}->disconnect();
undef $self->{dbh};
}

# End class clsDBConnection

#clsErrors Class @0-347B837F

package clsErrors;

sub new {
my $self = {};
$self->{ErrorDelimiter} = "
";
$self->{ErrorsCount} = 0;
$self->{Errors} = [];
return bless $self;
}

sub addError {
my ($self, $Description) = @_;
if ($Description) {
$self->{Errors}->[$self->{ErrorsCount}] = $Description;
$self->{ErrorsCount}++;
}
}

sub AddErrors {
my ($self, $Errors) = @_;
for ( my $i = 0; $i < ( $#{$self->{Errors}} + 1 ); $i++) {
$self->addError($self->{Errors}->[$i])
}
}

sub Clear {
my $self = shift;
$self->{ErrorsCount} = 0;
@{$self->{Errors}} = ();
}

sub Count {
my $self = shift;
return $self->{ErrorsCount};
}

sub ToString {
my $self = shift;
if ( ( $#{$self->{Errors}} + 1 ) > 0) {
return join( $self->{ErrorDelimiter}, @{$self->{Errors}} ) . $self->{ErrorDelimiter};
} else {
return "";
}
}