diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..782a260 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +composer.phar +composer.lock +config.php +vendor +log +Download +Upload \ No newline at end of file diff --git a/Commands/ChatidCommand.php b/Commands/ChatidCommand.php new file mode 100644 index 0000000..73eafb7 --- /dev/null +++ b/Commands/ChatidCommand.php @@ -0,0 +1,66 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Commands\UserCommands; + +use Longman\TelegramBot\Commands\UserCommand; + +use Longman\TelegramBot\Entities\ServerResponse; +use Longman\TelegramBot\Request; + + +/** + * User "/echo" command + * + * Simply echo the input back to the user. + */ +class ChatidCommand extends UserCommand +{ + /** + * @var string + */ + protected $name = 'chatid'; + + /** + * @var string + */ + protected $description = 'Show chat ID'; + + /** + * @var string + */ + protected $usage = '/chatid'; + + /** + * @var string + */ + protected $version = '1.1.0'; + + /** + * Command execute method + * + * @return \Longman\TelegramBot\Entities\ServerResponse + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function execute(): ServerResponse + { + $message = $this->getMessage(); + $chat_id = $message->getChat()->getId(); + $text = trim($message->getText(true)); + + + $data = [ + 'chat_id' => $chat_id, + 'text' => $chat_id, + ]; + + return Request::sendMessage($data); + } +} diff --git a/Commands/DeluploadCommand.php b/Commands/DeluploadCommand.php new file mode 100644 index 0000000..31d136a --- /dev/null +++ b/Commands/DeluploadCommand.php @@ -0,0 +1,131 @@ +'; + + /** + * @var string + */ + protected $version = '1.2.0'; + + /** + * Main command execution + * + * @return ServerResponse + * @throws TelegramException + */ + public function execute(): ServerResponse + { + $config = require __DIR__ . '/../config.php'; + $auth = $config['authids']; + + $message = $this->getMessage(); + // $from = $message->getFrom(); + // $user_id = $from->getId(); + $chat_id = $message->getChat()->getId(); + if(!in_array($chat_id, $auth)) + { + $data_tlg = [ + 'chat_id' => $chat_id, + 'text' => "Non autorizzato", + ]; + + return Request::sendMessage($data_tlg); + die("Unauthorised"); + } + $text = trim($message->getText(true)); + if ($text === 'help') { + $replytext = 'Command usage: ' . $this->getUsage(); + } + else + { + if($text != NULL) + { + $replytext = $this->delete($text); + + } + else + { + $replytext = "Devi inserire un link da eliminare /delupload . Scrivi /delupload help per ulteriori info"; + } + } + $data_tlg = [ + 'chat_id' => $chat_id, + 'text' => $replytext, + ]; + + return Request::sendMessage($data_tlg); + + } + + + private function delete($url) + { + $config = require __DIR__ . '/../config.php'; + + $rundb = $config['rundb']; + + $mysqli = new \mysqli($rundb['host'], $rundb['user'], $rundb['password'], $rundb['database']); + $query = $mysqli->prepare("SELECT * FROM `cdn` WHERE link = ?"); + + $query->bind_param('s',$url); + $query->execute(); + $result = mysqli_stmt_get_result($query); + + $rowcount=mysqli_num_rows($result); + if($rowcount == 0) + { + return "Hai già eliminato questo file. "; + } + $row = $result->fetch_array(MYSQLI_ASSOC); + + $path = $row['path']; + $uidf = $row['uidf']; + unlink($path); + $query = $mysqli->prepare("DELETE FROM `cdn` WHERE uidf = ?"); + $query->bind_param('s',$uidf); + + if($query->execute()) + { + $query->close(); + return "File eliminato correttamente."; + } + else + { + $query->close(); + return "Oh no! Qualcosa è andato storto! :("; + } + + } +} \ No newline at end of file diff --git a/Commands/GenericmessageCommand.php b/Commands/GenericmessageCommand.php new file mode 100644 index 0000000..cf914d7 --- /dev/null +++ b/Commands/GenericmessageCommand.php @@ -0,0 +1,85 @@ +getMessage(); + + // If a conversation is busy, execute the conversation command after handling the message. + $conversation = new Conversation( + $message->getFrom()->getId(), + $message->getChat()->getId() + ); + + // Fetch conversation command if it exists and execute it. + if ($conversation->exists() && $command = $conversation->getCommand()) { + return $this->telegram->executeCommand($command); + } + + return Request::emptyResponse(); + } +} \ No newline at end of file diff --git a/Commands/ShortenCommand.php b/Commands/ShortenCommand.php new file mode 100644 index 0000000..35a4a98 --- /dev/null +++ b/Commands/ShortenCommand.php @@ -0,0 +1,144 @@ +'; + + /** + * @var string + */ + protected $version = '1.2.0'; + + /** + * Main command execution + * + * @return ServerResponse + * @throws TelegramException + */ + public function execute(): ServerResponse + { + $config = require __DIR__ . '/../config.php'; + $auth = $config['authids']; + + $message = $this->getMessage(); + $from = $message->getFrom(); + $user_id = $from->getId(); + $chat_id = $message->getChat()->getId(); + if(!in_array($chat_id, $auth)) + { + $data_tlg = [ + 'chat_id' => $chat_id, + 'text' => "Non autorizzato", + ]; + + return Request::sendMessage($data_tlg); + die("Unauthorised"); + } + $text = trim($message->getText(true)); + if ($text === 'help') { + $replytext = 'Command usage: ' . $this->getUsage(); + } + else + { + $reply = $message->getReplyToMessage(); + if($reply != NULL) + { + $replytext1 = $reply->getText(); + $result = json_decode($this->shorten($replytext1, $text, $user_id), true); + $replytext = $result['message']."\n\nShortened link: ".$result['shorturl']."\n\nQR Code: ".$result['shorturl'].".qr\n\nStats: ".$result['shorturl']."+"; + + } + else + { + $replytext = "Devi inserire un link da accorciare come risposta al comando /shorten. Scrivi /shorten help per ulteriori info"; + } + } + $data_tlg = [ + 'chat_id' => $chat_id, + 'text' => $replytext, + ]; + + return Request::sendMessage($data_tlg); + + } + + + private function shorten($url, $keyword, $userid) + { + $config = require __DIR__ . '/../config.php'; + $yls = $config['yourls']; + + $timestamp = time(); + $signature = md5( $timestamp . $yls['token'] ); + + $format = 'json'; // output format: 'json', 'xml' or 'simple' + + $api_url = $yls['apiurl']; + + // Init the CURL session + $ch = curl_init(); + curl_setopt( $ch, CURLOPT_URL, $api_url ); + curl_setopt( $ch, CURLOPT_HEADER, 0 ); // No header in the result + curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); // Return, do not echo result + curl_setopt( $ch, CURLOPT_POST, 1 ); // This is a POST request + curl_setopt( $ch, CURLOPT_POSTFIELDS, array( // Data to POST + 'url' => $url, + 'keyword' => $keyword, + 'title' => "", + 'format' => $format, + 'action' => 'shorturl', + 'timestamp' => $timestamp, + 'signature' => $signature + ) ); + + // Fetch and return content + $data = curl_exec($ch); + curl_close($ch); + + $jsr = json_decode($data, true); + if($jsr['statusCode'] == "200") + { + $surl = $jsr['shorturl']; + $timest = time(); + $owner = "TELEGRAMBOT_".$userid; + $from = $_SERVER['SERVER_NAME']; + $rundb = $config['rundb']; + $mysqli = new \mysqli($rundb['host'], $rundb['user'], $rundb['password'], $rundb['database']); + $query = $mysqli->prepare("INSERT INTO `shortener`(`shorturl`, `owner`, `creato`, `from_serv`) VALUES (?,?,?,?)"); + $query->bind_param('ssis',$surl,$owner,$timest,$from); + $query->execute(); + } + + return $data; + } +} \ No newline at end of file diff --git a/Commands/UploadCommand.php b/Commands/UploadCommand.php new file mode 100644 index 0000000..b51a3c5 --- /dev/null +++ b/Commands/UploadCommand.php @@ -0,0 +1,191 @@ +getMessage(); + $chat = $message->getChat(); + $chat_id = $chat->getId(); + $user_id = $message->getFrom()->getId(); + if(!in_array($chat_id, $auth)) + { + $data_tlg = [ + 'chat_id' => $chat_id, + 'text' => "Non autorizzato", + ]; + + return Request::sendMessage($data_tlg); + die("Unauthorised"); + } + // Make sure the Download path has been defined and exists + $download_path = $this->telegram->getDownloadPath(); + if (!is_dir($download_path)) { + return $this->replyToChat('Sembra esserci un problema di configurazione. Scrivi a quei pelandroni dell\'Area IT!'); + } + + // Initialise the data array for the response + $data['chat_id'] = $chat_id; + + if ($chat->isGroupChat() || $chat->isSuperGroup()) { + // Reply to message id is applied by default + $data['reply_to_message_id'] = $message->getMessageId(); + // Force reply is applied by default to work with privacy on + $data['reply_markup'] = Keyboard::forceReply(['selective' => true]); + } + + // Start conversation + $conversation = new Conversation($user_id, $chat_id, $this->getName()); + $message_type = $message->getType(); + + if (in_array($message_type, ['audio', 'document', 'photo', 'video', 'voice'], true)) { + $doc = $message->{'get' . ucfirst($message_type)}(); + + // For photos, get the best quality! + ($message_type === 'photo') && $doc = end($doc); + + $file_id = $doc->getFileId(); + $file = Request::getFile(['file_id' => $file_id]); + if ($file->isOk() && Request::downloadFile($file->getResult())) { + $result = $this->cdnupload($download_path . '/' . $file->getResult()->getFilePath(), $download_path, "TELEGRAMBOT_".$user_id); + $data['text'] = $result; + } else { + $data['text'] = 'Impossibile scaricare la risorsa.'; + } + + $conversation->notes['file_id'] = $file_id; + $conversation->update(); + $conversation->stop(); + } else { + $data['text'] = 'Invia il file qui. ATTENZIONE: il file che caricherai sarà pubblicamente accessibile!'; + } + + return Request::sendMessage($data); + } + + public function cdnupload($tempfile, $path, $user) + { + $config = require __DIR__ . '/../config.php'; + $cdnconf = $config['cdn']; + + $base = $cdnconf['path']; + $cdnurl = $cdnconf['urlbase']; + + $temp = explode(".", $tempfile); + $newfilename = strtoupper(uniqid()) . '.' . end($temp); + if(rename($tempfile, $path."/".$newfilename)) + { + // if($clamav->scan("/ssda1/www/portal.runpolito.it/lib/tmp/".$newfilename)) + // { + $mime = mime_content_type($path."/".$newfilename); + $extp = explode("/", $mime); + + $ext = $extp[0]; + + switch ($ext) + { + case "image" : + $sfolder = "/img/"; + break; + case "video" : + $sfolder = "/video/"; + break; + case "application" : + $sfolder = "/docs/"; + break; + case "text" : + $sfolder = "/docs/"; + break; + default : + $sfolder = "/misc/"; + break; + } + $folder = $base.$sfolder; + + rename($path."/".$newfilename, $folder.$newfilename); + $path1 = $folder.$newfilename; + $url = $cdnurl.$sfolder.$newfilename; + //INSERT INTO `cdn`(`nome`, `descr`, `owner`, `ndl`, `link`, `path`, `mime`, `exp`, `creato`) VALUES () + //mettere credenziali MySQL su config.php! + $rundb = $config['rundb']; + + $mysqli = new \mysqli($rundb['host'], $rundb['user'], $rundb['password'], $rundb['database']); + $query = $mysqli->prepare("INSERT INTO `cdn`(`uidf`,`nome`, `descr`, `owner`, `link`, `path`, `mime`, `creato`) VALUES (?,?,?,?,?,?,?,?)"); + $query->bind_param('sssssssi',$newfilename,$newfilename,$newfilename,$user,$url,$path1,$mime,time()); + $query->execute(); + //unlink("./tmp/".$newfilename); + unlink($path."/".$newfilename); + + return "File caricato correttamente.\n\nURL pubblico risorsa: ".$cdnurl.$sfolder.$newfilename; + // http_response_code(200); + // } + // else + // { + // unlink("./tmp/".$newfilename); + // rpl::log($uid, "[WARN]", "cdn/upload", "upload file infetto bloccato: ".$clamav->getMessage()); + // header("HTTP/1.1 415 "."File infetto: " . $clamav->getMessage()); + // } + } + else + { + return "Oh crap, something went south!"; + //rpl::log($uid, "[ERROR]", "cdn/upload", "upload file non riuscito: ".$_FILES['upfile']['name']); + // http_response_code(415); + } + } + +} \ No newline at end of file diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..1df8fe8 --- /dev/null +++ b/composer.json @@ -0,0 +1,5 @@ +{ + "require": { + "longman/telegram-bot": "^0.71.0" + } +} diff --git a/hook.php b/hook.php new file mode 100644 index 0000000..b58d863 --- /dev/null +++ b/hook.php @@ -0,0 +1,45 @@ +addCommandsPaths($commands_paths); + $telegram->enableAdmins($config['admins']); +$telegram->enableMySql($config['mysql']); + $telegram->setDownloadPath($config['paths']['download']); + $telegram->setUploadPath($config['paths']['upload']); + + Longman\TelegramBot\TelegramLog::initialize( + new Monolog\Logger('telegram_bot', [ + (new Monolog\Handler\StreamHandler($config['logging']['debug'], Monolog\Logger::DEBUG))->setFormatter(new Monolog\Formatter\LineFormatter(null, null, true)), + (new Monolog\Handler\StreamHandler($config['logging']['error'], Monolog\Logger::ERROR))->setFormatter(new Monolog\Formatter\LineFormatter(null, null, true)), + ]), + new Monolog\Logger('telegram_bot_updates', [ + (new Monolog\Handler\StreamHandler($config['logging']['update'], Monolog\Logger::INFO))->setFormatter(new Monolog\Formatter\LineFormatter('%message%' . PHP_EOL)), + ]) + ); + // Handle telegram webhook request + $telegram->handle(); +} catch (Longman\TelegramBot\Exception\TelegramException $e) { + // Silence is golden! + // log telegram errors + // echo $e->getMessage(); +} \ No newline at end of file diff --git a/set.php b/set.php new file mode 100644 index 0000000..5b77735 --- /dev/null +++ b/set.php @@ -0,0 +1,32 @@ +setWebhook($hook_url); + if ($result->isOk()) { + echo $result->getDescription(); + } +} catch (Longman\TelegramBot\Exception\TelegramException $e) { + // log telegram errors + // echo $e->getMessage(); +} \ No newline at end of file diff --git a/unset.php b/unset.php new file mode 100644 index 0000000..bf18c56 --- /dev/null +++ b/unset.php @@ -0,0 +1,41 @@ +deleteWebhook(); + + echo $result->getDescription(); +} catch (Longman\TelegramBot\Exception\TelegramException $e) { + echo $e->getMessage(); +} \ No newline at end of file