Ejemplo n.º 1
0
 public function Execute(WhatsApp\Message $Message, array $Params = array())
 {
     try {
         if ($Message->Time >= $this->WhatsBot->GetStartTime()) {
             if ($this->IsEnabled() === self::ENABLED) {
                 if (is_readable($this->XPath)) {
                     $LangSection = "{$this->Key}_{$this->AliasOf}";
                     $this->WhatsApp->SetLangSection($LangSection);
                     $this->Lua->LinkObject(new Lang($LangSection), true, true, true);
                     $this->Lua->AssignVariables($Params);
                     $this->Lua->LinkObject($Message, true, false, false);
                     $Return = $this->Lua->Include($this->XPath);
                     if ($Return === false) {
                         return INTERNAL_ERROR;
                     }
                     if ($Return === null) {
                         return self::EXECUTED;
                     }
                     return $Return;
                 }
                 Std::Out("[Warning] [Modules] (Lua) Can't execute {$this->Key}::{$this->Name} ({$this->AliasOf}). {$this->PathExtension} file is not readable");
                 return self::NOT_READABLE;
             }
             return self::NOT_ENABLED;
         }
         return self::EXECUTED;
     } catch (Exception $Exception) {
         Std::Out("[Warning] [Modules] (Lua) Can't execute {$this->Key}::{$this->Name} ({$this->AliasOf}). " . get_class($Exception) . 'thrown (' . $Exception->GetMessage() . ')');
         return INTERNAL_ERROR;
     }
 }
Ejemplo n.º 2
0
 public function Execute(WhatsApp\Message $Message, array $Params = array())
 {
     if ($Message->Time >= $this->WhatsBot->GetStartTime()) {
         if ($this->IsEnabled() === self::ENABLED) {
             if (is_readable($this->XPath)) {
                 $LangSection = "{$this->Key}_{$this->AliasOf}";
                 $this->WhatsApp->SetLangSection($LangSection);
                 $Lang = new Lang($LangSection);
                 $ModuleManager = $this->ModuleManager;
                 $WhatsBot = $this->WhatsBot;
                 $WhatsApp = $this->WhatsApp;
                 extract($Params);
                 $Return = (include $this->XPath);
                 if ($Return !== 1) {
                     return $Return;
                 }
                 return self::EXECUTED;
             }
             Std::Out("[Warning] [Modules] Can't execute {$this->Key}::{$this->Name} ({$this->AliasOf}). {$this->PathExtension} file is not readable");
             return self::NOT_READABLE;
         }
         return self::NOT_ENABLED;
     }
     return self::EXECUTED;
 }
Ejemplo n.º 3
0
 public function LoadModules()
 {
     Std::Out();
     Std::Out('[Info] [Modules] Loading');
     Std::Out('[Info] [Modules] Available languages: ' . implode(', ', $this->GetAvailableLanguages(false)));
     $Modules = Config::Get('Modules');
     if (is_array($Modules)) {
         $Loaded = array();
         $Keys = array_keys($Modules);
         foreach ($Keys as $Key) {
             foreach ($Modules[$Key] as $Module) {
                 if (is_string($Module)) {
                     $Module = array($Module, $Module);
                 }
                 if (is_array($Module) && !empty($Module[0]) && !empty($Module[1])) {
                     $Name = strtolower($Module[0]);
                     $Loaded[$Key][$Name] = $this->LoadModule($Key, $Name, $Module[1]);
                 } else {
                     Std::Out('[Warning] [Modules] Config must be Key::Name or Key::[Name, AliasOf]');
                     Std::Out("{$Key}::", false);
                     Std::Out(var_export($Module, true));
                 }
             }
         }
         Std::Out('[Info] [Modules] Ready!');
         // ($N loaded modules)
         return $Loaded;
     }
     Std::Out('[Warning] [Modules] Config file is not an array');
     return false;
 }
Ejemplo n.º 4
0
 public function ModuleExists($Key, $Name, $ShowWarn = true)
 {
     $Name = strtolower($Name);
     if (!empty($this->Modules[$Key][$Name])) {
         return Module::LOADED;
     }
     if ($ShowWarn) {
         Std::Out("[Warning] [Modules] Module {$Key}::{$Name} doesn't exists");
     }
     return Module::NOT_LOADED;
 }
Ejemplo n.º 5
0
 public function RegisterCallback($Name, $Callback)
 {
     if (is_callable($Callback)) {
         if (is_object(parent::RegisterCallback($Name, $Callback))) {
             return true;
         } else {
             Std::Out("[Warning] [Lua] Can't register {$Name} callback");
         }
     } else {
         Std::Out("[Warning] [Lua] Can't register {$Name} callback. It is not callable");
     }
     return false;
 }
Ejemplo n.º 6
0
 public function Get($Key)
 {
     if (!empty($this->Data[$Key])) {
         $Args = func_get_args();
         if (count($Args) > 1) {
             $Args[0] = $this->Data[$Key];
             return call_user_func_array('sprintf', $Args);
         }
         return $this->Data[$Key];
     }
     Std::Out("[Warning] [Lang] Key {$this->Section}::{$Key} doesn't exists");
     return false;
 }
Ejemplo n.º 7
0
 public static function Get($Filename, $ShowWarning = true, $Throw = false)
 {
     self::Init();
     if (isset(self::$Config[$Filename])) {
         return self::$Config[$Filename];
     }
     if ($ShowWarning) {
         Std::Out('[Warning] [Config] No such file ' . self::$FileManager->GetDirectory() . "/{$Filename}.json");
     }
     if ($Throw) {
         throw new Exception('No such file ' . self::$FileManager->GetDirectory() . "/{$Filename}.json");
     }
     return false;
 }
Ejemplo n.º 8
0
 public static function Get($Filename, $Throw = false, $FixArray = false)
 {
     if (isset(self::$Config[$Filename])) {
         if ($FixArray) {
             return LuaFixArrayRecursive(self::$Config[$Filename]);
         } else {
             return self::$Config[$Filename];
         }
     }
     Std::Out("[Warning] [Config] config/{$Filename}.json does not exists or is not decodeable. Try to Config::Load()");
     if ($Throw) {
         throw new Exception("No such file config/{$Filename}.json");
     }
     return false;
 }
Ejemplo n.º 9
0
 public function GetModule($Key, $Name, $ShowWarn = true)
 {
     $Name = strtolower($Name);
     if ($this->ModuleExists($Key, $Name, $ShowWarn) === Module::LOADED) {
         if ($this->Modules[$Key][$Name]->IsLoaded()) {
             return $this->Modules[$Key][$Name];
         } else {
             return Module::LOAD_ERROR;
         }
     }
     if ($ShowWarn) {
         Std::Out("[Warning] [Modules] Trying to get not loaded module. {$Key}::{$Name}");
     }
     return Module::NOT_LOADED;
 }
Ejemplo n.º 10
0
 public function Get($Key)
 {
     if (isset($this->Data[$Key])) {
         $Args = func_get_args();
         if (func_num_args() > 1) {
             $Args[0] = $this->Data[$Key];
             return call_user_func_array('sprintf', $Args);
             // sprintf($Key, ...$Args)
         }
         return $this->Data[$Key];
     } else {
         Std::Out("[Warning] [Lang] Key {$this->Section}::{$Key} doesn't exist");
     }
     return false;
 }
Ejemplo n.º 11
0
 public static function Encode($Filename, $Data, $Options = JSON_PRETTY_PRINT)
 {
     $Data = json_encode($Data, $Options);
     if ($Data !== false) {
         $ToWrite = strlen($Data);
         $Writed = file_put_contents($Filename, $Data);
         if ($Writed === $ToWrite) {
             return true;
         } else {
             Std::Out("[Warning] [Json] {$Filename} : {$Writed} bytes writed of {$ToWrite}");
         }
     } else {
         Std::Out("[Warning] [Json] Can't encode {$Filename}");
     }
     return false;
 }
Ejemplo n.º 12
0
function LoadLib($Lib)
{
    $Path = "class/Lib/_{$Lib}.php";
    if (basename(dirname(realpath($Path))) === 'Lib') {
        if (is_readable($Path)) {
            // Lint
            require_once $Path;
            return true;
        } else {
            Std::Out("[Warning] [Libs] Can't load {$Lib}. It is not readable");
        }
    } else {
        Std::Out("[Warning] [Libs] Can't load {$Lib}. It is not in Lib/ folder");
    }
    return false;
}
Ejemplo n.º 13
0
 public final function Run()
 {
     sleep(5);
     $this->LoadTaskManager();
     $this->Execute();
     Std::Out();
     Std::Out("[Info] [Threads] {$this->Name} stopped ({$this->Stop})");
     if (strtolower(substr(PHP_OS, 0, 3)) === 'win') {
         // When a thread gets stopped, windows says "PHP-CLI has stopped working *trollface*"
         while (true) {
             // So ...
             sleep(1);
         }
     }
     // We will wait ... ... ...
 }
Ejemplo n.º 14
0
 protected function Execute()
 {
     try {
         $Lua = new LuaWithPHP();
         $Lua->AssignUserConstants();
         $Lua->LinkObject($this, false, false, false);
         $Lua->AssignVariables(array('Name' => $this->Name, 'Path' => $this->Path, 'JPath' => $this->JPath, 'XPath' => $this->XPath, 'PathExtension' => $this->PathExtension, 'Data' => $this->Data, 'Loaded' => $this->Loaded));
         $Lua->LinkObjects(array($this->ThreadManager, $this->ModuleManager, $this->EventManager, $this->WhatsApp, $this->WhatsBot));
         $Lua->LinkObject(new Lang("Thread_{$this->Name}"), true, true, true);
         while (!$this->Stop && is_readable($this->XPath)) {
             if ($Lua->Include($this->XPath) === false) {
                 $this->Stop('Lua fatal error');
             }
         }
     } catch (Exception $Exception) {
         Std::Out("[Warning] [Threads] (Lua) Can't execute {$this->Name}. " . get_class($Exception) . 'thrown (' . $Exception->GetMessage() . ')');
     }
 }
Ejemplo n.º 15
0
 public static function Encode($Filename, $Data, $Options = JSON_PRETTY_PRINT)
 {
     $EncodedData = json_encode($Data, $Options);
     if ($EncodedData !== false) {
         $ToWrite = strlen($EncodedData);
         $Written = file_put_contents($Filename, $EncodedData);
         if ($Written === $ToWrite) {
             return true;
         } else {
             Std::Out("[Warning] [Json] {$Filename} : {$Written} bytes written of {$ToWrite}");
         }
     } else {
         $LogFileName = 'json_warning_' . time();
         Data::Set($LogFileName, sprintf("Can't encode %s: %s", $Filename, var_export($Data, true)));
         Std::Out("[Warning] [Json] Can't encode {$Filename} (see data/{$LogFileName})");
     }
     return false;
 }
Ejemplo n.º 16
0
function LoadLib($Lib, $Test = true, $ShowWarning = true)
{
    if ($Test) {
        $Path = __DIR__ . "/{$Lib}.php";
        if (is_file($Path)) {
            if (is_readable($Path)) {
                // Lint
                return (bool) (require_once $Path);
            } elseif ($ShowWarning) {
                Std::Out("[Warning] [Libs] Can't load {$Lib}. File isn't readable");
            }
        } elseif (strpos(str_replace('\\', '/', $Lib), '/') === false && LoadLib($Lib . '/' . $Lib, $Test, false)) {
            return true;
        } elseif ($ShowWarning) {
            Std::Out("[Warning] [Libs] Can't load {$Lib}. File doesn't exist");
        }
        return false;
    } else {
        return (bool) (require_once __DIR__ . "/{$Lib}.php");
    }
}
Ejemplo n.º 17
0
 public static function Delete($Index)
 {
     $Admins = Config::Get('Admins');
     if ($Admins !== false) {
         $Index = intval($Index);
         if (isset($Admins[$Index])) {
             $Admin = $Admins[$Index];
             unset($Admins[$Index]);
             $Saved = Config::Set('Admins', array_values($Admins));
             if ($Saved) {
                 Std::Out("[Info] [Admin] {$Admin[0]}" . (empty($Admin[1]) ? null : ":{$Admin[1]}") . ' deleted');
                 return array($Index, $Admin[0], $Admin[1]);
             } else {
                 Std::Out("[Warning] [Admin] Error while trying to delete {$Admin[0]}" . (empty($Admin[1]) ? null : ":{$Admin[1]}"));
                 return false;
             }
         }
         return 1;
     }
     return false;
 }
Ejemplo n.º 18
0
 public function SetJson($Filename, $Data, array $Directories = array(), $ShowWarning = true)
 {
     $Path = $this->GetPath($Filename, $Directories);
     $JsonData = json_encode($Data, $this->JsonOptions);
     if ($JsonData !== false) {
         return $this->Set($Filename, $JsonData, false, $Directories, $ShowWarning);
     } else {
         $LogFilename = time() . '_warning_json';
         $this->Set($LogFilename, sprintf("Can't encode %s: %s", $Filename, var_export($Data, true)), false, array('..', 'data', 'log'), $ShowWarning);
         if ($ShowWarning) {
             Std::Out("[Warning] [FileManager :: {$this->Directory}] Can't encode {$Path} (see data/log/{$LogFilename})");
         }
     }
     return false;
 }
 public function DisableListener($Key)
 {
     if (isset($this->Listeners[$Key])) {
         $this->Listeners[$Key][2] = false;
         Std::Out("[Info] [Events] {$this->Listeners[$Key][0]} : {$Key} disabled");
         return true;
     }
     Std::Out("[Warning] [Events] Trying to disable non-existig listener ({$Key})");
     return false;
 }
Ejemplo n.º 20
0
 public final function Load()
 {
     if (!is_string($this->Extension) || extension_loaded($this->Extension)) {
         if ($this->ModuleManager->KeyExists($this->Key)) {
             $this->Path = "class/Modules/{$this->Key}_{$this->AliasOf}";
             $this->JPath = $this->Path . '.json';
             $this->XPath = $this->Path . '.' . $this->PathExtension;
             if (basename(dirname(realpath($this->JPath))) === 'Modules') {
                 $Json = Json::Decode($this->JPath);
                 if (is_array($Json)) {
                     if (is_readable($this->XPath)) {
                         // Lint
                         $this->Data = $Json;
                         if (isset($this->Data['Libs']) && is_array($this->Data['Libs'])) {
                             foreach ($this->Data['Libs'] as $Lib) {
                                 if (!LoadLib($Lib)) {
                                     Std::Out("[Warning] [Modules] Can't load {$this->Key}::{$this->Name} ({$this->AliasOf}). {$Lib} lib doesn't exists");
                                     $this->Loaded = self::NOT_LOADED;
                                     return $this->Loaded;
                                 }
                             }
                         }
                         $this->Loaded = $this->_Load();
                         return $this->Loaded;
                     } else {
                         Std::Out("[Warning] [Modules] Can't load {$this->Key}::{$this->Name} ({$this->AliasOf}). {$this->PathExtension} file is not readable");
                     }
                 } else {
                     Std::Out("[Warning] [Modules] Can't load {$this->Key}::{$this->Name} ({$this->AliasOf}). Json file is not decodeable");
                 }
             } else {
                 Std::Out("[Warning] [Modules] Can't load {$this->Key}::{$this->Name} ({$this->AliasOf}). It is not in Modules folder");
             }
         } else {
             Std::Out("[Warning] [Modules] Can't load {$this->Key}::{$this->Name} ({$this->AliasOf}). That key doesn't exists");
         }
     } else {
         Std::Out("[Warning] [Modules] Can't load {$this->Key}::{$this->Name} ({$this->AliasOf}). {$this->Extension} extension is not loaded");
     }
     $this->Loaded = self::NOT_LOADED;
     return $this->Loaded;
 }
Ejemplo n.º 21
0
 public function ExecuteTasks()
 {
     foreach ($this->Threads as $Name => $Thread) {
         $Tasks = $Thread->GetTasks();
         foreach ($Tasks as $Task) {
             if (empty($Task[0])) {
                 $Task[0] = null;
             }
             // We don't need to require anything. If $this->Threads contains anything, WhatsBotThread is loaded and ThreadTaskManager will require it all
             if ($Task[0] === WHATSBOT) {
                 $Object = $this->WhatsBot;
             } elseif ($Task[0] === WHATSAPP) {
                 $Object = new WhatsApp($this->WhatsProt, "Thread_{$Name}");
             } elseif ($Task[0] === EVENTMANAGER) {
                 $Object = $this->EventManager;
             } elseif ($Task[0] === MODULEMANAGER) {
                 $Object = $this->ModuleManager;
             } elseif ($Task[0] === THREADMANAGER) {
                 $Object = $this;
             } else {
                 $Object = $Task[0];
             }
             if (is_object($Object) && !empty($Task[1]) && is_string($Task[1]) && !empty($Task[2]) && is_array($Task[2])) {
                 if (method_exists($Object, $Task[1]) && is_callable(array($Object, $Task[1]))) {
                     $Thread->SetReturn($Task[0], $Task[1], call_user_func_array(array($Object, $Task[1]), $Task[2]));
                     continue;
                 }
             }
             Std::Out();
             Std::Out("[Warning] [Threads] Can't execute task " . var_export($Object, true) . "->{$Task[1]} (From {$Name})");
         }
     }
 }
Ejemplo n.º 22
0
 protected function Warning($String, $NewLines = 1)
 {
     Std::Out();
     return Std::Out('[Warning] [API ' . get_class($this) . '] ' . $String, $NewLines);
 }
Ejemplo n.º 23
0
 private function SendResponse(Message $Message, $Code)
 {
     if ($Code === Module::EXECUTED || $Code === floatval(Module::EXECUTED)) {
         return $Code;
     }
     if (is_float($Code)) {
         $Code = intval($Code);
     }
     if ($Code === SEND_USAGE) {
         $this->WhatsApp->SendMessage($Message->From, 'usage');
     } else {
         $this->WhatsApp->SetLangSection('WhatsBot');
         if ($Code === Module::NOT_LOADED) {
             $this->WhatsApp->SendMessage($Message->From, 'message:module::not_loaded');
         } elseif ($Code === NOT_ADMIN) {
             $this->WhatsApp->SendMessage($Message->From, 'message:not_admin');
         } elseif ($Code === Module::NOT_ENABLED) {
             $this->WhatsApp->SendMessage($Message->From, 'message:module::not_enabled');
         } elseif ($Code === INTERNAL_ERROR || $Code === Module::NOT_READABLE) {
             $this->WhatsApp->SendMessage($Message->From, 'message:internal_error');
         } elseif ($Code === Module::LOAD_ERROR) {
             $this->WhatsApp->SendMessage($Message->From, 'message:module::load_error');
         } elseif (is_array($Code) && !empty($Code[1])) {
             // Some other
             $this->WhatsApp->SendLangError($Message->From, $Code[1]);
         } else {
             $Key = array_search($Code, get_defined_constants(true)['user'], true);
             if ($Key !== false) {
                 $Key = "const {$Key} = ";
             }
             Std::Out("[Warning] [Parser] Wrong response code ({$Key}" . var_export($Code, true) . "). Message from {$Message->From} ({$Message->ID})");
             $this->WhatsApp->SendMessage($Message->From, 'message:internal_error:wrong_response_code', $Code);
         }
     }
     return $Code;
 }
Ejemplo n.º 24
0
<?php

require_once 'class/WhatsBot.php';
# Config
$Debug = false;
Std::Out('Starting WhatsBot...');
$W = new WhatsBot($Debug);
$W->Start();
$W->Listen();
Ejemplo n.º 25
0
 public function Listen($PingDelay = 60, $ReconnectDelay = 300)
 {
     # Check Exit
     if ($this->Exit !== false) {
         Std::Out();
         Std::Out("[Info] [WhatsBot] Exiting ({$this->Exit})...");
         return $this->Exit;
     }
     $this->StartTime = time();
     $ReconnectTimer = $this->StartTime;
     $PingTimer = $this->StartTime;
     Std::Out();
     Std::Out("[Info] [WhatsBot] Start time is {$this->StartTime}");
     Std::Out();
     Std::Out('[Info] [WhatsBot] Listening...');
     # Start threads
     $this->ThreadManager->StartThreads();
     while (true) {
         try {
             # Check Exit
             if ($this->Exit !== false) {
                 $this->ThreadManager->StopThreads();
                 Std::Out();
                 Std::Out("[Info] [WhatsBot] Exiting ({$this->Exit})...");
                 return $this->Exit;
             }
             # Reconnect if disconnected
             if (!$this->WhatsApp->IsConnected()) {
                 $this->Connect(false);
             }
             # Execute thread's tasks
             $this->ThreadManager->ExecuteTasks();
             # Listen
             $this->WhatsApp->PollMessage();
             # Ping & Reconnect
             if (time() >= $PingTimer + $PingDelay) {
                 $this->WhatsApp->SendPing();
                 $PingTimer = time();
             }
             if (time() >= $ReconnectTimer + $ReconnectDelay) {
                 $this->Connect(false);
                 $ReconnectTimer = time();
             }
         } catch (ConnectionException $Exception) {
             Std::Out();
             Std::Out('[Warning] [WhatsBot] Connection error (' . $Exception->GetMessage() . ')');
             $this->Connect(1);
         } catch (Exception $Exception) {
             Std::Out();
             Std::Out('[Warning] [WhatsBot] ' . get_class($Exception) . ' thrown while listening (' . $Exception->GetMessage() . ')');
             $this->Connect(1);
         }
     }
 }