Update Master.au3

Update Master.au3

; #INDEX# =======================================================================================================================
; Title .........: Master
; AutoIt Version : 3.3.14.5
; Description ...: coletânea de funções
; Source.........: https://github.com/chechelaky/AutoIt/blob/master/Master/Master.au3
; Author.........: Luismar Chechelaky (Luigi)
; Obs............: 10/10/2018, 11 horas, intervalo, fim 09:17
; ===============================================================================================================================

#include-once
#include <Array.au3>
#include <String.au3>
#include <FileConstants.au3>
#include <Crypt.au3>

;~ https://github.com/chechelaky/AutoIt/blob/master/_TimeUnix/_TimeUnix.au3
#include <_TimeUnix.au3>

OnAutoItExitRegister("Master_OnExit")

Global $oError = ObjEvent("AutoIt.Error", "_ErrFunc")

Global Const $COMUM = RegRead("HKEY_CURRENT_USER\Software\AutoIt v3\AutoIt", "Include")

Global Const $PSFTP = $COMUM & "\psftp.exe"
Global Const $PLINK = $COMUM & "\plink.exe"
Global Const $PSCP = $COMUM & "\pscp.exe"

_Crypt_Startup()

Func Master_OnExit()
	_Crypt_Shutdown()
EndFunc   ;==>Master_OnExit

Func _ErrFunc($oErr)
	ConsoleWrite("COM Error, ScriptLine(" & $oErr.scriptline & ") : Number 0x" & Hex($oErr.number, 8) & " - " & $oErr.windescription & @CRLF)
EndFunc   ;==>_ErrFunc

; #FUNCTION# ====================================================================================================================
; Name ..........: _ArrayAdd2D
; Description ...:
; Syntax ........:
; Parameters ....:
; Return values .:
;
; Author ........: Luigi (Luismar Chechelaky)
; Example .......:
; ===============================================================================================================================
Func _ArrayAdd2D(ByRef $array, $m1 = Default, $m2 = Default, $m3 = Default, $m4 = Default, $m5 = Default, $m6 = Default, $m7 = Default, $m8 = Default, $m9 = Default, $m10 = Default, $m11 = Default, $m12 = Default, $m13 = Default, $m14 = Default, $m15 = Default, $m16 = Default, $m17 = Default, $m18 = Default, $m19 = Default, $m20 = Default, $m21 = Default, $m22 = Default, $m23 = Default, $m24 = Default, $m25 = Default)
	$array[0][0] = UBound($array, 1)
	ReDim $array[$array[0][0] + 1][UBound($array, 2)]
	Local $iCol = @NumParams - 1 < UBound($array, 2) ? @NumParams - 1 : UBound($array, 2)
	For $ii = 1 To $iCol
		$array[$array[0][0]][$ii - 1] = Execute("$m" & $ii)
	Next
	Return $array[0][0]
EndFunc   ;==>_ArrayAdd2D

; #FUNCTION# ====================================================================================================================
; Name ..........: _ArrayDump
; Description ...:
; Syntax ........:
; Parameters ....:
; Return values .:
;
; Author ........:  Luigi (Luismar Chechelaky)
; Example .......:
; ===============================================================================================================================
Func _ArrayDump($array, $name = "")
;~ Author: Luigi (Luismar Chechelaky)
	Local $iCol = UBound($array, 2)
	Local $aCol[$iCol]
	Local $iLen, $iLenB
	Local $line_head = "+"
	For $ii = 0 To UBound($array, 1) - 1
		For $jj = 0 To UBound($array, 2) - 1
			$iLen = StringLen($array[$ii][$jj])
			If $iLen > $aCol[$jj] Then $aCol[$jj] = $iLen
			$iLenB = StringLen(String($jj))
			If $iLenB > $aCol[$jj] Then $aCol[$jj] = $iLenB
		Next
	Next

	Local $line = "+"
	For $ii = 0 To $iCol - 1
		$line &= _StringRepeat("-", $aCol[$ii]) & "+"
		$line_head &= _StringRepeat("-", $aCol[$ii] - StringLen(String($ii))) & $ii & "+"
	Next
	If $name Then ConsoleWrite("arr[ " & $name & " ] " & UBound($array, 1) & "x" & UBound($array, 2) & @LF)
	ConsoleWrite($line_head & @LF)
	For $ii = 0 To UBound($array, 1) - 1
		ConsoleWrite($ii = 1 ? $line & @LF & "|" : "|")
		For $jj = 0 To UBound($array, 2) - 1
			$iLen = StringLen($array[$ii][$jj])
			ConsoleWrite(Conv($array[$ii][$jj]) & _StringRepeat(" ", $aCol[$jj] - $iLen) & "|")
		Next
		ConsoleWrite(@LF)
	Next
	ConsoleWrite($line & @LF)
EndFunc   ;==>_ArrayDump

; #FUNCTION# ====================================================================================================================
; Name ..........: Conv
; Description ...:
; Syntax ........:
; Parameters ....:
; Return values .:
;
; Author ........:  Luigi (Luismar Chechelaky)
; Example .......:
; ===============================================================================================================================
Func Conv($var)
	Local $Pattern[][2] = [["[áãâ]", "a"], ["[éê]", "e"], ["[íî]", "i"], ["[óõô]", "o"], ["[úû]", "u"], ["[ÁÃÂ]", "A"], ["[ÉÊ]", "E"], ["[ÍÎ]", "I"], ["[ÓÕÔ]", "O"], ["[ÚÛ]", "U"], ["[Ç]", "C"], ["[ç]", "c"]]
	For $ii = 0 To UBound($Pattern, 1) - 1
		$var = StringRegExpReplace($var, $Pattern[$ii][0], $Pattern[$ii][1])
	Next
	Return $var
EndFunc   ;==>Conv

; #FUNCTION# ====================================================================================================================
; Name ..........: StringtoArray
; Description ...:
; Syntax ........:
; Parameters ....:
; Return values .:
;
; Author ........:  Luigi (Luismar Chechelaky)
; Example .......:
; ===============================================================================================================================
Func StringtoArray($in = "")
	If Not $in Then Return $in
	Local $ret[1] = [0]
	$in = StringReplace($in, @CRLF, @LF)
	$in = StringReplace($in, @CR, @LF)
	StringRemoveDouble($in, @LF)
	$in = StringSplit($in, @LF)
	For $ii = 1 To $in[0]
		$in[$ii] = __StringTrim($in[$ii])
		If $in[$ii] Then _ArrayAdd($ret, $in[$ii])
	Next
	$ret[0] = UBound($ret, 1) - 1
	Return $ret
EndFunc   ;==>StringtoArray

; #FUNCTION# ====================================================================================================================
; Name ..........: StringRemoveDouble
; Description ...:
; Syntax ........:
; Parameters ....:
; Return values .:
;
; Author ........:  Luigi (Luismar Chechelaky)
; Example .......:
; ===============================================================================================================================
Func StringRemoveDouble(ByRef $input, $double)
	Local $find = $double & $double
	While StringInStr($input, $find)
		$input = StringReplace($input, $find, $double)
	WEnd
EndFunc   ;==>StringRemoveDouble

; #FUNCTION# ====================================================================================================================
; Name ..........: __StringTrim
; Description ...:
; Syntax ........:
; Parameters ....:
; Return values .:
;
; Author ........:  Luigi (Luismar Chechelaky)
; Example .......:
; ===============================================================================================================================
Func __StringTrim($input)
	While StringLeft($input, 1) = " "
		$input = StringTrimLeft($input, 1)
	WEnd
	While StringRight($input, 1) = " "
		$input = StringTrimRight($input, 1)
	WEnd
	Return $input
EndFunc   ;==>__StringTrim

; #FUNCTION# ====================================================================================================================
; Name ..........: __DataConv
; Description ...:
; Syntax ........:
; Parameters ....:
; Return values .:
;
; Author ........:  Luigi (Luismar Chechelaky)
; Example .......:
; ===============================================================================================================================
Func __DataConv($input, $iMode = 0)
	Switch $iMode
		Case 0
			; from 2015/06/10 20:21:22
			; to   2017-06-01 13:38:13
			Return StringReplace($input, "-", "/")
		Case Else
			Return $input
	EndSwitch
EndFunc   ;==>__DataConv

; #FUNCTION# ====================================================================================================================
; Name ..........: PassWord
; Description ...:
; Syntax ........:
; Parameters ....:
; Return values .:
;
; Author ........:  Luigi (Luismar Chechelaky)
; Example .......:
; ===============================================================================================================================
Func PassWord($len = 8)
	If $len < 8 Then $len = 8
	Local $num[] = [0, 2, 3, 4, 5, 6, 7, 8, 9]
	$num[0] = UBound($num, 1) - 1
	Local $let[] = [0, "A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "X", "Y", "W", "Z"]
	$let[0] = UBound($let, 1) - 1

	Local $try, $ret = $let[Random(1, $let[0], 1)]
	Local $last = $ret
	$len -= 1

	While $len
		$try = Random(0, 1, 1) ? $num[Random(1, $num[0], 1)] : $let[Random(1, $let[0], 1)]
		If $try <> $last Then
			$ret &= $try
			$last = $try
			$len -= 1
		EndIf
	WEnd
	Return $ret
EndFunc   ;==>PassWord

; #FUNCTION# ====================================================================================================================
; Name ..........: oo()
; Description ...:
; Syntax ........:
; Parameters ....:
; Return values .:
;
; Author ........:  Luigi (Luismar Chechelaky)
; Example .......:
; ===============================================================================================================================
Func oo()
	Return ObjCreate("Scripting.Dictionary")
EndFunc   ;==>oo

; #FUNCTION# ====================================================================================================================
; Name ..........: _ArrayDumpLine
; Description ...:
; Syntax ........:
; Parameters ....:
; Return values .:
;
; Author ........:  Luigi (Luismar Chechelaky)
; Example .......:
; ===============================================================================================================================
Func _ArrayDumpLine($label, $val, $line)
;~ Author: Luigi (Luismar Chechelaky)
;~ Requirements
;~ #include <Array.au3>
;~ #include <String.au3>

;~ Exemplo
;~ Global $label[2] = ["nome", "valor"]
;~ Global $val[2][2] = [[100000, 2], [3, 4]]
;~ _ArrayDumpLine($label, $val, 0)
;~ _ArrayDumpLine($label, $val, 1)

;~ Resultado
;~ +------+-----+
;~ |nome  |valor|
;~ +------+-----+
;~ |100000|    2|
;~ +------+-----+
	If Not (UBound($label, 1) = UBound($val, 2)) Then Return
	Local $iCol = UBound($label, 1) - 1
	Local $col[3][$iCol + 1], $len
	For $ii = 0 To $iCol
		$col[0][$ii] = StringLen($label[$ii])
		$col[1][$ii] = $label[$ii]
	Next
	For $ii = 0 To $iCol
		$len = StringLen($val[$line][$ii])
		If $len > $col[0][$ii] Then $col[0][$ii] = $len
		$col[2][$ii] = $val[$line][$ii]
	Next
	Local $line_sep[1]
	For $ii = 0 To $iCol
		_ArrayAdd($line_sep, _StringRepeat("-", $col[0][$ii]))
	Next
	_ArrayAdd($line_sep, "")
	$line_sep = _ArrayToString($line_sep, "+")
	ConsoleWrite($line_sep & @LF)
	Local $word[1]
	For $ii = 0 To $iCol
		_ArrayAdd($word, $col[1][$ii] & _StringRepeat(" ", $col[0][$ii] - StringLen($col[1][$ii])))
	Next
	_ArrayAdd($word, "")
	$word = _ArrayToString($word, "|")
	ConsoleWrite($word & @LF)
	ConsoleWrite($line_sep & @LF)
	Local $word[1]
	For $ii = 0 To $iCol
		_ArrayAdd($word, _StringRepeat(" ", $col[0][$ii] - StringLen($col[2][$ii])) & $col[2][$ii])
	Next
	_ArrayAdd($word, "")
	$word = _ArrayToString($word, "|")
	ConsoleWrite($word & @LF)
	ConsoleWrite($line_sep & @LF)
EndFunc   ;==>_ArrayDumpLine

; #FUNCTION# ====================================================================================================================
; Name ..........: FileSave
; Description ...:
; Syntax ........:
; Parameters ....:
; Return values .:
;
; Author ........:  Luigi (Luismar Chechelaky)
; Example .......:
; ===============================================================================================================================
Func FileSave($file_path, $var)
;~ 	ConsoleWrite("FileSave( $path=" & $file_path & " )" & @LF)
	Local $hFile = FileOpen($file_path, $FO_OVERWRITE + $FO_CREATEPATH + $FO_FULLFILE_DETECT)
	If IsArray($var) Then
		FileWrite($hFile, _ArrayToString($var, @LF, 1))
	Else
		FileWrite($hFile, $var)
	EndIf
	FileClose($hFile)
EndFunc   ;==>FileSave

; #FUNCTION# ====================================================================================================================
; Name ..........: FileLoad
; Description ...:
; Syntax ........:
; Parameters ....:
; Return values .:
;
; Author ........:  Luigi (Luismar Chechelaky)
; Example .......:
; ===============================================================================================================================
Func FileLoad($file)
	; @TODO ter certeza da codifição do arquivo
	Local $hFile = FileOpen($file, $FO_UTF8_NOBOM)
	Local $READ = FileRead($hFile)
	FileClose($hFile)
	Return $READ
EndFunc   ;==>FileLoad

#Region  _ArrayAdd_InArray
; #FUNCTION# ====================================================================================================================
; Name ..........: _ArrayAdd_InArray
; Description ...:
; Syntax ........:
; Parameters ....:
; Return values .:
;
; Author ........:  Luigi (Luismar Chechelaky)
; Example .......:
; ===============================================================================================================================
Func _ArrayAdd_InArray(ByRef $aParent, $aChild)
	Local $parent[3] = [UBound($aParent, $UBOUND_DIMENSIONS), UBound($aParent, $UBOUND_ROWS), UBound($aParent, $UBOUND_COLUMNS)]
	Local $child[3] = [UBound($aChild, $UBOUND_DIMENSIONS), UBound($aChild, $UBOUND_ROWS), UBound($aChild, $UBOUND_COLUMNS)]
	If $parent[0] = 1 And $child[0] = 1 Then
		__ArrayAdd_1x1($parent, $aParent, $child, $aChild)
	ElseIf $parent[0] = 1 And $child[0] = 2 Then
		__ArrayAdd_1x2($parent, $aParent, $child, $aChild)
	ElseIf $parent[0] = 2 And $child[0] = 2 Then
		__ArrayAdd_2x2($parent, $aParent, $child, $aChild)
	ElseIf $parent[0] = 2 And $child[0] = 1 Then
		__ArrayAdd_2x1($parent, $aParent, $child, $aChild)
	Else
		ConsoleWrite("__ArrayAdd: @error" & @LF)
	EndIf
EndFunc   ;==>_ArrayAdd_InArray

; #FUNCTION# ====================================================================================================================
; Name ..........: __ArrayAdd_1x1
; Description ...:
; Syntax ........:
; Parameters ....:
; Return values .:
;
; Author ........:  Luigi (Luismar Chechelaky)
; Example .......:
; ===============================================================================================================================
Func __ArrayAdd_1x1($parent, ByRef $aParent, $child, $aChild)
	For $ii = 0 To $child[$UBOUND_ROWS] - 1
		_ArrayAdd($aParent, $aChild[$ii])
	Next
	Return UBound($aParent, 1) - 1
EndFunc   ;==>__ArrayAdd_1x1

; #FUNCTION# ====================================================================================================================
; Name ..........: __ArrayAdd_1x2
; Description ...:
; Syntax ........:
; Parameters ....:
; Return values .:
;
; Author ........:  Luigi (Luismar Chechelaky)
; Example .......:
; ===============================================================================================================================
Func __ArrayAdd_1x2($parent, ByRef $aParent, $child, $aChild)
	Local $max_col = $parent[$UBOUND_COLUMNS]
;~ 	ConsoleWrite("__ArrayAdd_1x2 $max_col[" & $max_col & "]" & @LF)
	For $ii = 0 To $child[$UBOUND_ROWS] - 1
		_ArrayAdd($aParent, $aChild[$ii][0])
	Next
	Return UBound($aParent, 1) - 1
EndFunc   ;==>__ArrayAdd_1x2

; #FUNCTION# ====================================================================================================================
; Name ..........: __ArrayAdd_2x2
; Description ...:
; Syntax ........:
; Parameters ....:
; Return values .:
;
; Author ........:  Luigi (Luismar Chechelaky)
; Example .......:
; ===============================================================================================================================
Func __ArrayAdd_2x2($parent, ByRef $aParent, $child, $aChild)
;~ 	ConsoleWrite("__ArrayAdd_2x2" & @LF)
	Local $max_col = $parent[$UBOUND_COLUMNS] > $child[$UBOUND_COLUMNS] ? $child[$UBOUND_COLUMNS] : $parent[$UBOUND_COLUMNS]
	ReDim $aParent[$parent[$UBOUND_ROWS] + $child[$UBOUND_ROWS]][$parent[$UBOUND_COLUMNS]]
	$parent[$UBOUND_ROWS] += $child[$UBOUND_ROWS] - 2
	For $ii = $parent[$UBOUND_ROWS] To $parent[$UBOUND_ROWS] + $child[$UBOUND_ROWS] - 1
		For $jj = 0 To $max_col - 1
			$aParent[$ii][$jj] = $aChild[$ii - $parent[$UBOUND_ROWS]][$jj]
		Next
	Next
	Return $parent[$UBOUND_ROWS]
EndFunc   ;==>__ArrayAdd_2x2

; #FUNCTION# ====================================================================================================================
; Name ..........: __ArrayAdd_2x1
; Description ...:
; Syntax ........:
; Parameters ....:
; Return values .:
;
; Author ........:  Luigi (Luismar Chechelaky)
; Example .......:
; ===============================================================================================================================
Func __ArrayAdd_2x1($parent, ByRef $aParent, $child, $aChild)
;~ 	ConsoleWrite("__ArrayAdd_2x1" & @LF)
	Local $max_col = $parent[$UBOUND_COLUMNS] < $child[$UBOUND_ROWS] ? $parent[$UBOUND_COLUMNS] : $child[$UBOUND_ROWS]
	ReDim $aParent[$parent[$UBOUND_ROWS] + 1][$parent[$UBOUND_COLUMNS]]
	$parent[$UBOUND_ROWS] += 1
	For $ii = 0 To $max_col - 1
		$aParent[$parent[$UBOUND_ROWS] - 1][$ii] = $aChild[$ii]
	Next
	Return $parent[$UBOUND_ROWS]
EndFunc   ;==>__ArrayAdd_2x1
#EndRegion _ArrayAdd_InArray

; #FUNCTION# ====================================================================================================================
; Name ..........: __ArrayExtract
; Description ...:
; Syntax ........:
; Parameters ....:
; Return values .:
;
; Author ........:  Luigi (Luismar Chechelaky)
; Example .......:
; ===============================================================================================================================
Func __ArrayExtract($arr, $x1, $y1 = -1, $y2 = -1)
	Local $ret[1]
	If $y1 = -1 Then $y1 = 0
	Switch UBound($arr, 0)
		Case 1
			If $y2 = -1 Then $y2 = UBound($arr, 1) - 1
			For $ii = $y1 To $y2
				ConsoleWrite($arr[$ii] & @LF)
				_ArrayAdd($ret, $arr[$ii])
			Next
		Case 2
			If $y2 = -1 Then $y2 = UBound($arr, 2) - 1
			For $ii = $y1 To $y2
				_ArrayAdd($ret, $arr[$x1][$ii])
			Next

	EndSwitch
	If UBound($ret, 1) > 1 Then _ArrayDelete($ret, 0)
	Return $ret
EndFunc   ;==>__ArrayExtract

; #FUNCTION# ====================================================================================================================
; Name ..........: _ArrayFrame
; Description ...:
; Syntax ........:
; Parameters ....:
; Return values .:
;
; Author ........:  Luigi (Luismar Chechelaky)
; Example .......:
; ===============================================================================================================================
Func _ArrayFrame($arr)
	Local $ret[4]
	If IsArray($arr) Then
		$ret[0] = 1
		$ret[1] = UBound($arr, $UBOUND_DIMENSIONS)
		$ret[2] = UBound($arr, $UBOUND_ROWS)
		$ret[3] = UBound($arr, $UBOUND_COLUMNS)
	EndIf
	Return $ret
EndFunc   ;==>_ArrayFrame

; #FUNCTION# ====================================================================================================================
; Name ..........: _ArrayTypes
; Description ...:
; Syntax ........:
; Parameters ....:
; Return values .:
;
; Author ........:  Luigi (Luismar Chechelaky)
; Example .......:
; ===============================================================================================================================
Func _ArrayTypes($sql)
;~ 	### Exclusive for SQLite ###
;~ 	INPUT
;~ 	$sql = 'CREATE TABLE "auth" ( `id` INTEGER PRIMARY KEY AUTOINCREMENT, `randum` TEXT, `user_id` INTEGER, `time` INTEGER )'

;~ 	OUTPUT
;~ 	+-------+-------+
;~ 	|      4|       |
;~ 	|id     |INTEGER|
;~ 	|randum |TEXT   |
;~ 	|user_id|INTEGER|
;~ 	|time   |INTEGER|
;~ 	+-------+-------+

	$sql = StringRegExpReplace($sql, "[\t]", " ")
	$sql = StringRegExpReplace($sql, "[\r\n\`\'\""]", "")
	While StringInStr($sql, "  ")
		$sql = StringReplace($sql, "  ", " ")
	WEnd
	ConsoleWrite("@line[" & @ScriptLineNumber & "] sql[ " & $sql & " ]" & @LF)

	Local $aFields[1][2], $temp1

	Local $arr = StringRegExp($sql, "(?m)\((.*?)\)", $STR_REGEXPARRAYGLOBALMATCH)

	If IsArray($arr) Then
		$arr = StringSplit($arr[0], ",", 2)
		For $ii = 0 To UBound($arr, 1) - 1
			$arr[$ii] = __StringTrim($arr[$ii])
			$temp1 = StringSplit($arr[$ii], " ", $STR_CHRSPLIT)
			_ArrayAdd2D($aFields, $temp1[1], $temp1[2])
		Next
	Else

	EndIf
	Return $aFields
EndFunc   ;==>_ArrayTypes

; #FUNCTION# ====================================================================================================================
; Name ..........: File_MD5
; Description ...:
; Syntax ........:
; Parameters ....:
; Return values .:
;
; Author ........:  Luigi (Luismar Chechelaky)
; Example .......:
; ===============================================================================================================================
Func File_MD5($file = 0)
	If Not $file Then Return SetError(1, 0, 0)
	If Not FileExists($file) Then Return SetError(2, 0, 0)
	If Not FileGetSize($file) Then Return SetError(3, 0, 0)
	Local $hash = _Crypt_HashFile($file, $CALG_MD5)
	If @error Then Return SetError(4, 0, 0)
	Return StringLower(StringTrimLeft($hash, 2))
EndFunc   ;==>File_MD5

; #FUNCTION# ====================================================================================================================
; Name ..........: LS
; Description ...:
; Syntax ........:
; Parameters ....:
; Return values .:
;
; Author ........:  Luigi (Luismar Chechelaky)
; Example .......:
; ===============================================================================================================================
Func LS($host, $user, $pass, $path = "/")
	Local $linux = "/usr/linux/bin/ls --full-time -lnb " & $path & " ; md5sum " & $path & "/*"
	Local $linux = "ls --full-time -lnb " & $path & " ; md5sum " & $path & "/*"
	Local $cmd = @ComSpec & " /c " & $PLINK & " -batch -ssh " & $user & "@" & $host & " -pw " & $pass & " """ & $linux & """"

	Local $iPid = Run($cmd, @ScriptDir, @SW_HIDE, $STDIN_CHILD + $STDERR_MERGED)
	ProcessWaitClose($iPid)
	Local $sOutput = StdoutRead($iPid, False, False)
;~ 	ConsoleWrite( $sOutput & @LF)

	Return __LS($sOutput, $path)
EndFunc   ;==>LS

; #FUNCTION# ====================================================================================================================
; Name ..........: __LS
; Description ...:
; Syntax ........:
; Parameters ....:
; Return values .:
;
; Author ........:  Luigi (Luismar Chechelaky)
; Example .......:
; ===============================================================================================================================
Func __LS($txt = "", $path = "")
	Local $ret[1][25] = [[0]]
	Local $regex = "(?s)([-d])([-r])([-w])([-x])([-r])([-w])([-x])([-r])([-w])([-x])(?:\.)?\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})\.(\d{9})\s+(-\d{4})\s+(.*?)[\n\r]"
	Local $arr = StringRegExp($txt, $regex, $STR_REGEXPARRAYGLOBALMATCH)

	Local $size = UBound($arr, 1) - 1
	If Not $size Then Return $ret
	Local $line
	If $size Then
		For $ii = 0 To $size Step 23
			_ArrayAdd2D($ret, $arr[$ii], $arr[$ii + 1], $arr[$ii + 2], $arr[$ii + 3], $arr[$ii + 4], $arr[$ii + 5], $arr[$ii + 6], $arr[$ii + 7], $arr[$ii + 8], $arr[$ii + 9], $arr[$ii + 10], $arr[$ii + 11], $arr[$ii + 12], $arr[$ii + 13], $arr[$ii + 14], $arr[$ii + 15], $arr[$ii + 16], $arr[$ii + 17], $arr[$ii + 18], $arr[$ii + 19], $arr[$ii + 20], $arr[$ii + 21], $arr[$ii + 22], _TimeUnix($arr[$ii + 14] & "/" & $arr[$ii + 15] & "/" & $arr[$ii + 16] & " " & $arr[$ii + 17] & ":" & $arr[$ii + 18] & ":" & $arr[$ii + 19]))
		Next
		$ret[0][0] = UBound($ret, 1) - 1

		$regex = "(?s)([a-f0-9]{32})\s+"
		$arr = StringRegExp($txt, $regex, $STR_REGEXPARRAYGLOBALMATCH)

		For $ii = 1 To $ret[0][0]
			$ret[$ii][24] = $arr[$ii - 1]
		Next
	EndIf
	Return $ret
EndFunc   ;==>__LS

; #FUNCTION# ====================================================================================================================
; Name ..........: File_Download
; Description ...:
; Syntax ........:
; Parameters ....:
; Return values .:
;
; Author ........:  Luigi (Luismar Chechelaky)
; Example .......:
; ===============================================================================================================================
Func File_Download($_host, $_user, $_pass, $_path, $_file, $_folder, $md5 = 0)

	$_folder = StringReplace($_folder, "/", "\")
	StringRemoveDouble($_folder, "\")
	If Not FileExists($_folder) Then DirCreate($_folder)

	ConsoleWrite("File_Download( $_host=" & $_host & ", $_user=" & $_user & ", $_pass=" & $_pass & ", $_path=" & $_path & ", $_file=" & $_file & ", $_folder=" & $_folder & ", $md5=" & $md5 & " )" & @LF)

	Local $remote = $_path & "/" & $_file

	Local $cmd = @ComSpec & " /c " & $PSCP & " -batch -v -pw " & $_pass & " " & $_user & "@" & $_host & ":" & $remote & " """ & $_folder & """"

	Local $pid = Run($cmd, @ScriptDir, @SW_HIDE, $STDERR_MERGED)
	ProcessWaitClose($pid)

	Local $out = StdoutRead($pid)

	If $md5 Then
		If $md5 = File_MD5($_folder & "\" & $_file) Then
			ConsoleWrite("MD5: @OK" & @LF)
		Else
			ConsoleWrite("MD5: @ERR" & @LF)
		EndIf
	EndIf

	ConsoleWrite(">>" & $out & "<<" & @LF)
EndFunc   ;==>File_Download

; #FUNCTION# ====================================================================================================================
; Name ..........: IniGet
; Description ...:
; Syntax ........:
; Parameters ....:
; Return values .:
;
; Author ........:  Luigi (Luismar Chechelaky)
; Example .......:
; ===============================================================================================================================
Func IniGet($arr, $key, $default_value = "")
	Local $iSearch = _ArraySearch($arr, $key, 1, Default)
	If @error Then Return $default_value
	If Not IsDeclared("MACROS") Then Local $MACROS[1][2]
	For $ii = 1 To $MACROS[0][0]
		If StringInStr($arr[$iSearch][1], "%" & $MACROS[$ii][0] & "%") Then
			$arr[$iSearch][1] = StringReplace($arr[$iSearch][1], "%" & $MACROS[$ii][0] & "%", $MACROS[$ii][1])
			ExitLoop
		EndIf
	Next

	Return $arr[$iSearch][1]
EndFunc   ;==>IniGet

; #FUNCTION# ====================================================================================================================
; Name ..........: IniSet
; Description ...:
; Syntax ........:
; Parameters ....:
; Return values .:
;
; Author ........:  Luigi (Luismar Chechelaky)
; Example .......:
; ===============================================================================================================================
Func IniSet(ByRef $arr, $key, $new_value)
	Local $iSearch = _ArraySearch($arr, $key, 1, Default)
	If @error Then Return SetError(1, 0, False)
	$arr[$iSearch][1] = $new_value
	Return True
EndFunc   ;==>IniSet


Updated to 2.0 version (can't test since i'm using mac now and there's no 2.0 instalers either. Also converted some tabs to spaces etc.

;;  Copyright 2008 Nokia Siemens Networks Oyj
;;
;;  Licensed under the Apache License, Version 2.0 (the "License");
;;  you may not use this file except in compliance with the License.
;;  You may obtain a copy of the License at
;;
;;      http://www.apache.org/licenses/LICENSE-2.0
;;
;;  Unless required by applicable law or agreed to in writing, software
;;  distributed under the License is distributed on an "AS IS" BASIS,
;;  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;  See the License for the specific language governing permissions and
;;  limitations under the License.

;; Robot Framework One Click Installer for Windows
;;
;; This installer installs Robot Framework and its preconditions Python and
;; Jython (optional). If installer is executed without arguments, it opens a
;; dialog explaining the options and asking the user to enter the installation
;; directory. If a command line options is given, it must be a path to an
;; existing directory and it is used as installation directory.
;;
;; For more information about this script see $USAGE below. To learn more
;; about silent Python installation, see url [1]. Silent Jython installation
;; options can be seen with command [2].
;;
;; [1] http://www.python.org/download/releases/2.5/msi/#automated
;; [2] java -jar jython_installer-2.2.x.jar --help

;;
;; Config
;;

; Expected patterns for installer names and target directory names.
$PYTHON_DIR_NAME = "Python25"
$JYTHON_DIR_NAME = "Jython22"
$PYTHON_PATTERN = "python-2.5*.msi"
$ROBOT_PATTERN = "robotframework-2.*.exe"
$JYTHON_PATTERN = "jython_installer-2.2*.jar"

; Usage to show to the user. If major versions of installed software are changed update them also here!!
; Patterns and directory names above are used in the usage so that they don't need to be updated.
$USAGE = "One Click Installer installs Robot Framework and its preconditions Python and Jython (optional). " & _
         "It also sets Robot Framework start-up scripts (pybot, jybot, rebot) as well as Python and Jython executables " & _
         "into %PATH% environment variable so that they can be executed from the command line. (Note that " & _
         "you need to restart the command prompt for these changes to take effect.)" & @CRLF & @CRLF & _
         "You should use this installer ONLY if you don't previously have Python or Jython installed. " & _
         "In that case, and also if you want to have a custom installation, you need to install needed " & _
         "components separately." & @CRLF & @CRLF & _
         "One Click Installer requires that you have all the required component installers in the same directory " & _
         "with it and that they have expected names. If Robot Framework or Python installer is missing, " & _
         "installation fails. If Jython installer doesn't exist, Jython is simply not installed. Note that " & _
         "in order to install Jython, Java 1.4 or newer must be already installed. Supported " & _
         "versions are Robot Framework 2.x, Python 2.5.x and Jython 2.2.x where '.x' means that any minor version " & _
         "(e.g. 2.5 or 2.5.2) is OK. These installers can be downloaded from respective project websites if " & _
         "they are missing. Expected patterns for installer names are '" & $ROBOT_PATTERN & "', '" & _
         $PYTHON_PATTERN & "' and '" & $JYTHON_PATTERN & "'." & @CRLF & @CRLF & _
         "The only thing you need to specify is the base directory where to install Python and Jython. " & _
         "They are installed into directories '" & $PYTHON_DIR_NAME & "' and '" & $JYTHON_DIR_NAME & "', " & _
         "respectively, inside the given base directory. Robot Framework itself is installed under Python " & _
         "installation directory and its startup scripts can be found from '[PYTHON]\Scripts' and code from " & _
         "'[PYTHON]\Lib\site-packages'." & @CRLF & @CRLF & _
         "Note that the specified base directory MUST exist and Python and Jython directories inside it must not. " & _
         "It is also not recommended to use a path containing spaces. Good candidates include directories like " & _
         "'C:\' and 'C:\APPS'."

;;
;; Main
;;

$base_dir = GetBaseDirectory()
$python_installer = GetRequiredInstaller($PYTHON_PATTERN, "Python")
$robot_installer = GetRequiredInstaller($ROBOT_PATTERN, "Robot")
$jython_installer = GetOptionalInstaller($JYTHON_PATTERN)
$python_dir = GetPythonDir($base_dir & $PYTHON_DIR_NAME)
$jython_dir = GetJythonDir($base_dir & $PYTHON_DIR_NAME, $jython_installer)
InstallPython($python_installer, $python_dir)
InstallJython($jython_installer, $jython_dir)
SetPath($python_dir, $jython_dir)  ; This must be done before InstallRobot to always have msvcrt71.dll in PATH
InstallRobot($robot_installer)
Exit

;;
;; Functions
;;

Func GetBaseDirectory()
    If $CmdLine[0] == 0 Then
        $base = InputBox("Robot Framework One Click Installer", $USAGE, "C:\", "", 500, 470)
    ElseIf $CmdLine[0] == 1 Then
        $base = $CmdLine[1]
    Else
        Cancel("Usage: " & @ScriptName & " [basedir]")
    EndIf
    If $base == "" Then
        Cancel("Installation cancelled by user.")
    ElseIf FileExists($base) == 0 Then
        Cancel("Given directory doesn't exist.")
    ElseIf StringRight($base, 1) <> "\" Then
        $base = $base & "\"
    EndIf
    Return $base
EndFunc

Func Cancel($msg)
    MsgBox(0, "Installation Cancelled", $msg)
    Exit
EndFunc

Func GetRequiredInstaller($pattern, $name)
    $installer = GetOptionalInstaller($pattern)
    If $installer == "" Then
        Cancel("Could not find " & $name & " installer with pattern '" & $pattern & "'")
    Endif
    return $installer
EndFunc

Func GetOptionalInstaller($pattern)
    $found = FileFindFirstFile($pattern)
    If $found == -1 Then
        $installer = ""
    Else
        $installer = FileFindNextFile($found)
    EndIf
    FileClose($found)
    return $installer
EndFunc

Func GetPythonDir($dir)
    VerifyInstallationDir($dir, "Python")
    return $dir
EndFunc

Func GetJythonDir($dir, $installer)
    If $installer == "" Then
        return ""
    EndIf
    VerifyInstallationDir($dir, "Jython")
    return $dir
EndFunc

Func VerifyInstallationDir($dir, $name)
    If FileExists($dir) == 1 Then
        Cancel($name & " installation directory '" & $dir & "' already exists.")
    EndIf
EndFunc

Func InstallPython($installer, $dir)
    $cmd = "msiexec /i " & $installer & " TARGETDIR=" & $dir & " /qb!"
    RunWait($cmd)
EndFunc

Func InstallJython($installer, $dir)
    If $installer == "" Then
        return
    EndIf
    $cmd = "java -jar " & $installer & " -s -d " & $dir
    RunWait($cmd)
EndFunc

Func InstallRobot($installer)
    Run($installer)
    WaitSetupWindowAndClickEnter("This Wizard will install")
    WaitSetupWindowAndClickEnter("Select python installation")
    WaitSetupWindowAndClickEnter("Ready to install")
    WaitSetupWindowAndClickEnter("Postinstall script finished")
EndFunc

Func WaitSetupWindowAndClickEnter($exp_text)
    WinWaitActive("Setup", $exp_text)
    Send("{ENTER}")
EndFunc

Func SetPath($python, $jython)
    $update = $python & ";" & $python & "\Scripts;" & $jython
    $orig = RegRead("HKCU\Environment", "PATH")

    If $orig == "" Then
        $new = $update
    ElseIf StringRight($orig, 1) == ";" Then
        $new = $orig & $update
    Else
        $new = $orig & ";" & $update
    EndIf

    RegWrite("HKCU\Environment", "PATH", "REG_EXPAND_SZ", $new)
    EnvUpdate()
EndFunc

;;  Copyright 2008 Nokia Siemens Networks Oyj
;;
;;  Licensed under the Apache License, Version 2.0 (the "License");
;;  you may not use this file except in compliance with the License.
;;  You may obtain a copy of the License at
;;
;;      http://www.apache.org/licenses/LICENSE-2.0
;;
;;  Unless required by applicable law or agreed to in writing, software
;;  distributed under the License is distributed on an "AS IS" BASIS,
;;  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;  See the License for the specific language governing permissions and
;;  limitations under the License.

;; Robot Framework One Click Installer for Windows
;;
;; This installer installs Robot Framework and its preconditions Python and
;; Jython (optional). If installer is executed without arguments, it opens a
;; dialog explaining the options and asking the user to enter the installation
;; directory. If a command line options is given, it must be a path to an
;; existing directory and it is used as installation directory.
;;
;; For more information about this script see $USAGE below. To learn more
;; about silent Python installation, see url [1]. Silent Jython installation
;; options can be seen with command [2].
;;
;; [1] http://www.python.org/download/releases/2.5/msi/#automated
;; [2] java -jar jython_installer-2.2.x.jar --help

;;
;; Config
;;

; Expected patterns for installer names and target directory names.
$PYTHON_DIR_NAME = "Python25"
$JYTHON_DIR_NAME = "Jython22"
$PYTHON_PATTERN = "python-2.5*.msi"
$ROBOT_PATTERN = "robot-1.8*.exe"
$JYTHON_PATTERN = "jython_installer-2.2*.jar"

; Usage to show to the user. If major versions of installed software are changed update them also here!!
; Patterns and directory names above are used in the usage so that they don't need to be updated.
$USAGE = "One Click Installer installs Robot Framework and its preconditions Python and Jython (optional). " & _
         "It also sets Robot start-up scripts (pybot, jybot, rebot) as well as Python and Jython executables " & _
         "into %PATH% environment variable so that they can be executed from the command line. (Note that " & _
         "you need to restart the command prompt for these changes to take effect.)" & @CRLF & @CRLF & _
		 "You should use this installer ONLY if you don't previously have Python or Jython installed. " & _
	     "In that case, and also if you want to have a custom installation, you need to install needed " & _
		 "components separately." & @CRLF & @CRLF & _
         "One Click Installer requires that you have all the required component installers in the same directory " & _
         "with it and that they have expected names. If Robot or Python installer is missing, " & _
         "installation fails. If Jython installer doesn't exist, Jython is simply not installed. Note that " & _
         "in order to install Jython, Java 1.4 or newer must be already installed. Supported " & _
         "versions are Robot 1.8.x, Python 2.5.x and Jython 2.2.x where '.x' means that any minor version " & _
         "(e.g. 1.8 or 1.8.3) is ok. These installers can be downloaded from respective project websites if " & _
         "they are missing. Expected patterns for installer names are '" & $ROBOT_PATTERN & "', '" & _
         $PYTHON_PATTERN & "' and '" & $JYTHON_PATTERN & "'." & @CRLF & @CRLF & _
         "The only thing you need to specify is the base directory where to install Python and Jython. " & _
         "They are installed into directories '" & $PYTHON_DIR_NAME & "' and '" & $JYTHON_DIR_NAME & "', " & _
         "respectively, inside the given base directory. Robot Framework itself is installed under Python " & _
         "installation directory and its startup scripts can be found from '[PYTHON]\Scripts' and code from " & _
         "'[PYTHON]\Lib\site-packages'." & @CRLF & @CRLF & _
         "Note that the specified base directory MUST exist and Python and Jython directories inside it must not. " & _
         "It is also not recommended to use a path containing spaces. Good candidates include directories like " & _
         "'C:\' and 'C:\APPS'."

;;
;; Main
;;

$base_dir = GetBaseDirectory()
$python_installer = GetRequiredInstaller($PYTHON_PATTERN, "Python")
$robot_installer = GetRequiredInstaller($ROBOT_PATTERN, "Robot")
$jython_installer = GetOptionalInstaller($JYTHON_PATTERN)
$python_dir = GetPythonDir($base_dir & "Python25")
$jython_dir = GetJythonDir($base_dir & "Jython22", $jython_installer)
InstallPython($python_installer, $python_dir)
InstallJython($jython_installer, $jython_dir)
SetPath($python_dir, $jython_dir)  ; This should be done before InstallRobot to get msvcrt71.dll into PATH
InstallRobot($robot_installer)
Exit

;;
;; Functions
;;

Func GetBaseDirectory()
	If $CmdLine[0] == 0 Then
		$base = InputBox("Robot Framework One Click Installer", $USAGE, "C:\", "", 500, 470)
	ElseIf $CmdLine[0] == 1 Then
		$base = $CmdLine[1]
	Else
		Cancel("Usage: " & @ScriptName & " [basedir]")
	EndIf
    If $base == "" Then
        Cancel("Installation cancelled by user.")
    ElseIf FileExists($base) == 0 Then
        Cancel("Given directory doesn't exist.")
    ElseIf StringRight($base, 1) <> "\" Then
        $base = $base & "\"
    EndIf
    Return $base
EndFunc

Func Cancel($msg)
    MsgBox(0, "Installation Cancelled", $msg)
    Exit
EndFunc

Func GetRequiredInstaller($pattern, $name)
    $installer = GetOptionalInstaller($pattern)
    If $installer == "" Then
        Cancel("Could not find " & $name & " installer with pattern '" & $pattern & "'")
    Endif
    return $installer
EndFunc

Func GetOptionalInstaller($pattern)
    $found = FileFindFirstFile($pattern)
    If $found == -1 Then
        $installer = ""
    Else
        $installer = FileFindNextFile($found)
    EndIf
    FileClose($found)
    return $installer
EndFunc

Func GetPythonDir($dir)
    VerifyInstallationDir($dir, "Python")
    return $dir
EndFunc

Func GetJythonDir($dir, $installer)
    If $installer == "" Then
        return ""
    EndIf
    VerifyInstallationDir($dir, "Jython")
    return $dir
EndFunc

Func VerifyInstallationDir($dir, $name)
    If FileExists($dir) == 1 Then
        Cancel($name & " installation directory '" & $dir & "' already exists.")
    EndIf
EndFunc

Func InstallPython($installer, $dir)
    $cmd = "msiexec /i " & $installer & " TARGETDIR=" & $dir & " /qb!"
    RunWait($cmd)
EndFunc

Func InstallJython($installer, $dir)
    If $installer == "" Then
        return
    EndIf
    $cmd = "java -jar " & $installer & " -s -d " & $dir
    RunWait($cmd)
EndFunc

Func InstallRobot($installer)
    Run($installer)
    WaitSetupWindowAndClickEnter("This Wizard will install")
    WaitSetupWindowAndClickEnter("Select python installation")
    WaitSetupWindowAndClickEnter("Ready to install")
    WaitSetupWindowAndClickEnter("Postinstall script finished")
EndFunc

Func WaitSetupWindowAndClickEnter($exp_text)
    WinWaitActive("Setup", $exp_text)
    Send("{ENTER}")
EndFunc

Func SetPath($python, $jython)
    $update = $python & ";" & $python & "\Scripts;" & $jython
    $orig = RegRead("HKCU\Environment", "PATH")

    If $orig == "" Then
        $new = $update
    ElseIf StringRight($orig, 1) == ";" Then
        $new = $orig & $update
    Else
        $new = $orig & ";" & $update
    EndIf

    RegWrite("HKCU\Environment", "PATH", "REG_EXPAND_SZ", $new)
    EnvUpdate()
EndFunc


Time Functions

Time Functions

#region ====INIT ===============================================================
	Func _ConfigInitial()
;~ 		ConsoleWrite('++ConfigDBInitial() = ' & @CRLF)
		_SQLite_down()
;~ 		_DBvarInit()
		; -------check if SQLIte SubteBA db exist
		SQLite_init()
		$SQLq = "SELECT name FROM sqlite_temp_master WHERE type='table';"
		_SQLITErun($SQLq, $dbfile, $quietSQLQuery)
	;~ 	;-------- Init Log
	;~ 	_initLog()
		;------------------------------------------------------------------------------
	EndFunc   ;==>_ConfigDBInitial
#endregion
#region  ==== SQL functions =======================================================================
	Func SQLInsertMessage($TweetID,$TweeMsg,$TweeDate)
;~ 		ConsoleWrite('++InsertMessageSQL() = '& @crlf)
		$query='INSERT INTO messages VALUES (' & $TweetID & ',"' & $TweeMsg & '" ,' & $TweeDate & ') ;'
		if _SQLITErun($query,$dbfullPath,$quietSQLQuery) Then
			return true
		Else
			MsgBox(48+4096,"Error inserting mesages ErrNo 1010" & @CRLF & $query,0,0)
			Return false
		EndIf
	EndFunc
	Func SQLGetUsers()
;~ 		ConsoleWrite('++SQLGetUsers() = '& @crlf)
		$query='SELECT * FROM Users ;'
		_SQLITEqry($query,$dbfullPath)
	EndFunc
	Func SQLGetActiveUsers()
;~ 		ConsoleWrite('++SQLGetActiveUsers() = '& @crlf)
		$query='SELECT * FROM Users WHERE Active=1 ;'
		_SQLITEqry($query,$dbfullPath)
	EndFunc
	Func SQLGetDevUsers()
;~ 		ConsoleWrite('++SQLGetDevUsers() = '& @crlf)
		$query='SELECT * FROM Users WHERE Active=1 AND Dev=1 ;'
		_SQLITEqry($query,$dbfullPath)
	EndFunc
	Func SQLExist_Message($TweetID)
;~ 		ConsoleWrite('++Exist_Message() = '&$TweetID& @crlf)
		$query='SELECT id FROM messages WHERE id="'&$TweetID &'";'
		_SQLITEqry($query,$dbfullPath)
		If  IsArray($qryResult) Then
			if UBound($qryResult)>1 then
				return $qryResult[1][0]
			EndIf
			return 0
		endif
		Return 0
	EndFunc
#endregion
#region  ==== send messages =======================================================================
;~  	Func sendmessages($message)  ;~ from file of recipients
;~ 		Local $fileh = FileOpen("secret\recipients.txt", 0)
;~ 		If $fileh = -1 Then
;~ 			Exit 26
;~ 		EndIf
;~ 		While 1
;~ 			Local $chatidLine = FileReadLine($fileh)
;~ 			If @error = -1 Then ExitLoop
;~ 			$chatidArr = StringSplit($chatidLine, ',')
;~ 			$chatid = $chatidArr[1]
;~ 			if $chatID<>"" then
;~ 				ConsoleWrite('- $chatid = ' & $chatid & "  ->  " & $chatidArr[2] & @CRLF)
;~ 				$respuesta = SendTelegramexec($chatid,$message)
;~ 			$respuesta  0 is ok
;~ 			endif
;~ 		WEnd
;~ 		FileClose($fileh)
;~ 	EndFunc   ;==>_sendmessages
	Func TelegramInitialMessage($UserID)
;~ 	ConsoleWrite('++TelegramInitialMessage() = '& @crlf)
		$message ="SubteBA BOT , lee los informes de Subte BA en Twitter, y los manda por este canal. "
		$message&='Este canal no es official del subte de Buenos Aires Ni de Metrovias.'  & $nuevaLinea
		$message&= $nuevaLinea
		$message&='Commandos:'  & $nuevaLinea
		$message&='/INFO -> Muestra este mensage'  & $nuevaLinea
		$message&='/START -> Activa la recepcion de alertas. '  & $nuevaLinea
		$message&='/STOP  -> Desactiva la recepcion de alertas. '  & $nuevaLinea
		$message&= $nuevaLinea
		$message&='Futuros Commandos:'  & $nuevaLinea
		$message&='/Solo A  -> Solo recepcion de alertas de la Linea A, B (C, D, E, H, P.'  & $nuevaLinea
		$message&='/P propuesta -> Enviar propuestas'  & $nuevaLinea

		$respuesta = SendTelegramexec($UserID,$message)
		return $respuesta
;~ 		ConsoleWrite('@@(' & @ScriptLineNumber & ') : $respuestaInitialMessage = ' & $respuesta & @crlf )
	EndFunc
	Func TelegramSTOPMessage($UserID)
		$message ="Los mensajes de alertas han sido deshabilitados" & $nuevaLinea
		$message&='/START -> Para habilitar la recepcion de alertas'  & $nuevaLinea
		$message&='INFO -> para mas informacion.'  & $nuevaLinea

		$respuesta = SendTelegramexec($UserID,$message)
		return $respuesta
;~ 		ConsoleWrite('@@(' & @ScriptLineNumber & ') : TelegramSTOPMessage = ' & $respuesta & @crlf )
	EndFunc
	Func TelegramSTARTMessage($UserID)
		$message ="Los mensajes de alertas han sido habilitados" & $nuevaLinea
		$message&='/STOP-> Para deshabilitar la recepcion de alertas'  & $nuevaLinea
		$message&='INFO -> para mas informacion.'  & $nuevaLinea

		$respuesta = SendTelegramexec($UserID,$message)
		return $respuesta
;~ 		ConsoleWrite('@@(' & @ScriptLineNumber & ') : TelegramSTARTMessage = ' & $respuesta & @crlf )
	EndFunc
	Func TelegramErrorMessage($UserID)
		$message ="No se ha registrado el cambio requerido." & $nuevaLinea
		$message&='Reintente enviar el comando nuevamente.'  & $nuevaLinea
		$message&='INFO -> para mas informacion.'  & $nuevaLinea

		$respuesta = SendTelegramexec($UserID,$message)
		return $respuesta
;~ 		ConsoleWrite('@@(' & @ScriptLineNumber & ') : TelegramErrorMessage = ' & $respuesta & @crlf )
	EndFunc
	Func TelegramBaseMessage($UserID)
		$message ="No logro entender el mensaje." & $nuevaLinea
		$message&='Reintente enviar el comando nuevamente.'  & $nuevaLinea
		$message&='INFO -> para mas informacion.'  & $nuevaLinea
		$respuesta = SendTelegramexec($UserID,$message)
		return $respuesta
;~ 		ConsoleWrite('@@(' & @ScriptLineNumber & ') : TelegramErrorMessage = ' & $respuesta & @crlf )
	EndFunc
	Func ReformatMessage($message)
;~ 	ConsoleWrite('++ReformatMessage() = '& @crlf)
		$msgArr=StringSplit($message,"Actualizado",1)
		$diaHoraArr=stringsplit(StringStripWS($msgArr[2],1+2)," ")
		$hora=$diaHoraArr[2]
		$dia=$diaHoraArr[1]
		$msg=""&$hora&""&"     " & $dia & $nuevaLinea & StringStripWS($msgArr[1],1+2)
		return $msg
	EndFunc
	Func sendmessages($message)
		$message=ReformatMessage($message)
		SQLGetActiveUsers()
		If  IsArray($qryResult) Then
			for $i=1 to UBound($qryResult)-1
				$isDev = $qryResult[$i][4]
				$chatid = $qryResult[$i][0]
				$ChatUser = $qryResult[$i][1] & " " & $qryResult[$i][2]
				if $chatID<>"" then
					select
						Case $SendToAll = 1
							ConsoleWrite('- $chatid = ' & $chatid & "  ->  " & $ChatUser & @CRLF)
							$respuesta = SendTelegramexec($chatid,$message)
						Case $isDev = 1 AND $SendToAll = 0
							ConsoleWrite('- $chatid = ' & $chatid & "  ->  " & $ChatUser & @CRLF)
							$respuesta = SendTelegramexec($chatid,$message)
					endSelect
					;~ $respuesta  0 is ok
				endif
			next
			return true
		endif
		Return false
	EndFunc   ;==>_sendmessages
	Func SendTelegramexec($chatid,$msgtext="testeo harcoded")
		$urlMSG="https://api.telegram.org/" & $token & "/sendMessage?chat_id=" & $chatid & _
		"&text=" & $msgtext & "&parse_mode=HTML"
		$sGet = HttpGet($urlMSG)

		if $sget<>"0"  then
			ConsoleWrite('Tlgm sent = ' & $msgtext & @crlf )
			return 0
		Else
			$s_text="Error sending message to Telegram = " & $sGet
			ConsoleWrite('!! ' & $s_text & @crlf )
			return 1
		endif
	EndFunc

#endregion
#region  ==== Tweeter scrapping ===================================================================
	func _ScrapTweetMessages($Username)
		Local $sData = InetRead("https://twitter.com/"&$Username)
		Local $nBytesRead = @extended
		ConsoleWrite('@@ BytesRead = ' & $nBytesRead &"   ")
		$htmltxt = BinaryToString($sData)
		If $nBytesRead < 100000 or StringInStr($htmltxt,"subteba")<1 Then
			ConsoleWrite('  Connection issue contacting  ' & "https://twitter.com/"&$Username& @crlf)
			$htmltxt=""
			Return $htmltxt
		endif
		return $htmltxt
	EndFunc
	Func _gettweetArr($htmltxt)
		$MSGArr = StringRegExp($htmltxt, '(?s)(?i)
(.*?)
', 3)
		if IsArray($MSGArr) then
			dim  $TweetMSGArr[UBound($MSGArr)]
			For $i = 0 To UBound($MSGArr) -1
				$TweetMessage = StringRegExp($MSGArr[$i], '(?s)(?i)
(.*?)
', 1)
				$mensaje = clearstring($TweetMessage[1])
				$TweetMSGArr[$i]=$mensaje
			Next
			$TweetDate = StringRegExp($htmltxt, '(?s)(?i)data-time="(.*?)"', 3)
			$TweetIDArr = StringRegExp($htmltxt, '(?s)(?i)data-tweet-id="(.*?)"', 3)
			$TweetArrAux = _mergeArray($TweetIDArr, $TweetMSGArr)
			$TweetArr = _mergeArray($TweetArrAux, $TweetDate)
	;~ 		_ArrayDisplay($TweetArr)
			return $TweetArr
		Else
			ConsoleWrite('!!!(' &  @ScriptLineNumber & ') : Error on  $MSGArr = ' & $MSGArr & @crlf )
			return 0
		endif
	EndFunc
#endregion
#region  ==== Bot Messages handeling ===================================================================
	Func Get_BotOffSet()
;~ 		ConsoleWrite('++Get_BotOffSet() = '& @crlf)
		if NOT FileExists($OffsetFile) then
			$fileh = FileOpen($OffsetFile,1+8)
			If $fileh = -1 Then
				ConsoleWrite('   "Unable to open file 1.' & $OffsetFile )
				return 0
			endif
			FileClose($fileh)
		EndIf
		$fileh = FileOpen($OffsetFile,0)
		If $fileh = -1 Then
			ConsoleWrite('   "Unable to open file 2.' & $OffsetFile )
			return 0
		endif
		Local $offset = FileReadLine($fileh)
		if @error = -1 Then
			FileClose($fileh)
			return 0
		endif
		ConsoleWrite("Get OffSet:"& $offset)
		FileClose($fileh)
		return $offset
	EndFunc
	Func Set_BotOffSet($offset)
;~ 		ConsoleWrite('++Set_BotOffSet() = '&$offset& @crlf)
		if NOT FileExists($OffsetFile) then
			$fileh = FileOpen($OffsetFile,1+8)
			If $fileh = -1 Then
				ConsoleWrite('   "Unable to open file 3.' & $OffsetFile )
				return 0
			endif
			FileClose($fileh)
		EndIf
		$fileh = FileOpen($OffsetFile,2)
		If $fileh = -1 Then
			ConsoleWrite('   "Unable to open file 4.' & $OffsetFile )
			return 0
		endif
		FileWriteLine($fileh,$offset)
		if @error = -1 Then
			FileClose($fileh)
			return 0
		endif
		ConsoleWrite("    Set OffSet:"& $offset &@crlf)
		FileClose($fileh)
		return 1
	EndFunc
	func UpdateUsers()
		ConsoleWrite('  '&@HOUR & ':' & @MIN&'  Update users.  ' )
		local $s=GetBotUpdates()
		if $s then
			$s=ParseForUserUpdate($s)
			if $s then
				$oJSON = _OO_JSON_Init()
				$jsonObj = $oJSON.parse($s)
				if $jsonObj.ok  then
					if $jsonObj.jsonPath( "$.result").stringify() = "[[]]" then
						ConsoleWrite(' No Bot data ' & @crlf)
					Else
						ConsoleWrite('  Updating... ' & @crlf)
						$UpdateIDArr = StripIntJS($jsonObj.jsonPath( "$.result..update_id").stringify()  )
						$UserIDArr =   StripIntJS($jsonObj.jsonPath( "$.result..message.from.id").stringify())
						$FnameArr =    StripStrJS($jsonObj.jsonPath( "$.result..message.from.first_name").stringify())
						$LnameArr =    StripStrJS($jsonObj.jsonPath( "$.result..message.from.last_name").stringify())
						$epochArr =    StripIntJS($jsonObj.jsonPath( "$.result..message.date").stringify())
						$menssageArr = StripStrJS($jsonObj.jsonPath( "$.result..message.text").stringify())
						if  $UserIDArr[0] = $UpdateIDArr[0] AND $UserIDArr[0] = $FnameArr[0] AND $UserIDArr[0] = $LnameArr[0]  AND $UserIDArr[0] = $epochArr[0]  AND $UserIDArr[0] = $menssageArr[0] then
							$retBad=0
							for $i=1 to $UserIDArr[0]
								$ret=SQLregister($UserIDArr[$i],$FnameArr[$i],$LnameArr[$i],$epochArr[$i],$menssageArr[$i])
								$ret1=ParseBotMessage()
								ConsoleWrite('@@(' & @ScriptLineNumber & ') : $ret1 = ' & $ret1 & @crlf )
								if (Not $ret) or (Not $ret1)  then	$retBad+=1
								$UpdateID=$UpdateIDArr[$i]
							next
							if $retBad=0 then Set_BotOffSet($UpdateID+1)
						Else
							_printFromArray($UserIDArr)
							_printFromArray($FnameArr)
							_printFromArray($LnameArr)
							_printFromArray($epochArr)
							_printFromArray($menssageArr)
							ConsoleWrite('  Error in JS array . exiting..... ' & @crlf)
							exit 29
						endif
					endif
				endif
			endif
		endif
	EndFunc
	Func GetBotUpdates()
		$offset=Get_BotOffSet()
		$urlMSG="https://api.telegram.org/" & $token & "/getUpdates?offset="&$offset
		$sGet = HttpGetJson1($urlMSG)
		ConsoleWrite('@@ $sGet = ' & $sGet & @crlf )
		if $sGet<>"" then
			return $sGet
		Else
			$s_text="Error getUpdates from Telegram = "
			ConsoleWrite('!! ' & $s_text & @crlf & "! " & $sGet)
			return false
		endif
	EndFunc
	Func StripStrJS($st)
		$st=StringReplace($st,'","',":::")
		$st=clearstring($st)
		$st=StringReplace($st,"[","")
		$st=StringReplace($st,"]","")
		$st=StringReplace($st,'"',"")
		$stArr=StringSplit($st,":::",1)
		return $stArr
	EndFunc
	Func StripIntJS($st)
		$st=StringReplace($st,',',":::")
		$st=clearstring($st)
		$st=StringReplace($st,"[","")
		$st=StringReplace($st,"]","")
		$st=StringReplace($st,'"',"")
		$stArr=StringSplit($st,":::",1)
		return $stArr
	EndFunc
	Func ParseForUserUpdate($s)
		if StringInStr($s,'"location":') Then
			$s='{"ok":true,"result":[]}'
			return $s
		endif
;~ 		eliminate contact info
		$s=StringRegExpReplace($s,'(?s)(?i)"contact":(.*?)}'  ,  '"text": ""' )
;~ 		replace username last-name
		$s=StringReplace($s,'"username":','"last_name":')
		return $s
	EndFunc
	Func SQLregister($UserID,$Fname,$Lname,$epoch,$mensage)
;~ 	ConsoleWrite('++SQLregister() = '& @crlf)

		$existUser=0
		If SQLExistUser($UserID)=$userID then $existUser=1
		if $existUser=0 then
			$setactive=1
			$ret=SQLInsertUser($UserID,$Fname,$Lname,$epoch,$setactive)
			if $ret then
				$ret=TelegramSTOPMessage($UserID)
				if $ret=0 then return true
			else
				$ret=TelegramErrorMessage($UserID)
				if $ret=0 then return true
			endif
			return false
		endif

		$setactive=-1
		if AIMessage($mensage,"/START") then $setactive=1
		if AIMessage($mensage,"/STOP") then $setactive=0
		if $existUser=1 AND $setactive<>-1 then
			$ret=SQLUpdateUserActive($UserID,$Fname,$Lname,$setactive)
			if $ret and $setactive=0 then
				$ret=TelegramSTOPMessage($UserID)
				if $ret=0 then return true
			endif
			if $ret and $setactive=1 then
				$ret=TelegramSTARTMessage($UserID)
				if $ret=0 then return true
			endif
			if NOT $ret then TelegramErrorMessage($UserID)
			return false
		endif

		return true
	EndFunc
	Func SQLInsertUser($UserID,$Fname,$Lname,$epoch,$active=1)
		ConsoleWrite('  Nuevo usuario = '& $Fname & "  "  & $Lname  & @crlf)
		$query='INSERT INTO Users VALUES (' & $UserID & ',"' & $Fname & '","' & $Lname & '",' & $active &',0,' & $epoch & ') ;'
		if _SQLITErun($query,$dbfullPath,$quietSQLQuery) Then
			return true
		Else
			MsgBox(48+4096,"Error inserting User ErrNo 1011" & @CRLF & $query,0,0)
			Return false
		EndIf
	EndFunc
	Func SQLUpdateUserActive($UserID,$Fname,$Lname,$active=1)
		ConsoleWrite('    Usuario Activo 1/Start 0/Stop= '&$active& "  " & $Fname & "  "  & $Lname  & @crlf)
		$query='UPDATE  Users SET Active=' & $active &' WHERE UserID='& $UserID & ' ;'
		if _SQLITErun($query,$dbfullPath,$quietSQLQuery) Then
			return true
		Else
			ConsoleWrite("       Error updating active user User ErrNo 1012" & @CRLF & $query& @crlf)
			Return false
		EndIf
	EndFunc
	Func SQLExistUser($UserID)
;~ 	ConsoleWrite('++SQLExistUser() = '& @crlf)
		$query='SELECT UserID FROM Users WHERE UserID="'&$UserID &'";'
		_SQLITEqry($query,$dbfullPath)
		If  IsArray($qryResult) Then
			if UBound($qryResult)>1 then
				return $qryResult[1][0]
			EndIf
			return 0
		endif
		Return 0
	EndFunc
#endregion
#region   ===========================================================================
	func closeall()
		_SQLite_Close()
		_SQLite_Shutdown()
		exit 30
	EndFunc
#endregion
#region =====================================   Helpers functions  ===============================
	Func _mergeArray($array1, $array2)
		$array1 = _ArrayAdd_Column($array1)
		$size = UBound($array1)
		$newCol = UBound($array1, 2) - 1
		For $i = 0 To $size - 1
			$array1[$i][$newCol] = $array2[$i]
		Next
	;~   _ArrayDisplay($array1)
		Return $array1
	EndFunc   ;==>_mergeArray
	Func _ArrayAdd_Column($Array)
		Local $aTemp[UBound($Array)][UBound($Array, 0) + 1]
		For $i = 0 To UBound($Array) - 1

			For $j = 0 To UBound($Array, 0) - 1
				If UBound($Array, 0) = 1 Then $aTemp[$i][0] = $Array[$i]
				If UBound($Array, 0) > 1 Then $aTemp[$i][$j] = $Array[$i][$j]
			Next
		Next
		Return $aTemp
	EndFunc   ;==>_ArrayAdd_Column
	Func _ClearSciteConsole()
		ConsoleWrite('!!!!!!!!!!!_ClearSciteConsole Func General 92!!!!!!!!!!!!  ' & @CRLF)
		ControlSend("[CLASS:SciTEWindow]", "", "Scintilla2", "+{F5}")
	EndFunc   ;==>_ClearSciteConsole
	Func _GetDOSOutput($sCommand)
	 ConsoleWrite('++_GetDOSOutput $sCommand = ' & $sCommand & @crlf )
		Local $iPID, $sOutput = ""
		$iPID = Run('"' & @ComSpec & '" /c ' & $sCommand, "", @SW_HIDE, 2 + 4)
		While 1
			$sOutput &= StdoutRead($iPID, False, False)
			$err=@error
			If $err Then
				ConsoleWrite('!!  _GetDOSOutput $err = ' & $err & @crlf )
				ExitLoop
			EndIf
	;~ 	Sleep(10)
		WEnd
		ConsoleWrite('>> 	Output = ' & $sOutput & @crlf )
		Return $sOutput
	EndFunc   ;==>_GetDOSOutput
	Func _timeBetween($cTime, $sTime, $eTime)
		 If Not _DateIsValid('2000/01/01 ' & $cTime) Then Return -1
		 If Not _DateIsValid('2000/01/01 ' & $sTime) Then Return -2
		 If Not _DateIsValid('2000/01/01 ' & $eTime) Then Return -3
		 ;~  ConsoleWrite(_DateDiff('s', '2000/01/01 ' & $cTime & ':00', '2000/01/01 ' & $sTime & ':00') & @CRLF)
		 ;~  ConsoleWrite(_DateDiff('s', '2000/01/01 ' & $cTime & ':00', '2000/01/01 ' & $eTime & ':00') & @CRLF)
		 If _DateDiff('s', '2000/01/01 ' & $cTime & ':00', '2000/01/01 ' & $sTime & ':00') < 0 And _
			 _DateDiff('s', '2000/01/01 ' & $cTime & ':00', '2000/01/01 ' & $eTime & ':00') > 0 Then
			  Return 1
		 Else
			  Return 0
		 EndIf
	EndFunc  ; ==>_timeBetween
#endregion
#region time
	Func  Sec2Time($nr_sec)
		$sec2time_hour = Int($nr_sec / 3600)
		$sec2time_min = Int(($nr_sec - $sec2time_hour * 3600) / 60)
		$sec2time_sec = $nr_sec - $sec2time_hour * 3600 - $sec2time_min * 60
		Return StringFormat('%02d:%02d:%02d', $sec2time_hour, $sec2time_min, $sec2time_sec)
	EndFunc   ;==>Sec2Time
	Func _GetUnixTime($sDate = 0);Date Format: 2013/01/01 00:00:00 ~ Year/Mo/Da Hr:Mi:Se
		Local $aSysTimeInfo = _Date_Time_GetTimeZoneInformation()
		Local $utcTime = ""
		If Not $sDate Then $sDate = _NowCalc()
		If Int(StringLeft($sDate, 4)) < 1970 Then Return ""
		If $aSysTimeInfo[0] = 2 Then
			$utcTime = _DateAdd('n', $aSysTimeInfo[1] + $aSysTimeInfo[7], $sDate)
		Else
			$utcTime = _DateAdd('n', $aSysTimeInfo[1], $sDate)
		EndIf
		Return _DateDiff('s', "1970/01/01 00:00:00", $utcTime)
	EndFunc   ;==>_GetUnixTime
#endregion