Files
matrix-register-bot/MatrixConnection.php

112 lines
2.6 KiB
PHP

<?php
class MatrixConnection
{
private $hs;
private $at;
function __construct($homeserver) {
$this->hs = $homeserver;
}
function __construct($homeserver, $access_token) {
$this->hs = $homeserver;
$this->at = $access_token;
}
function send($room_id, $message) {
if (!$this->at) {
error_log("No access token defined");
return false;
}
$send_message = NULL;
if (!$message) {
error_log("no message to send");
} elseif(is_array($message)) {
$send_message = $message;
} elseif ($message instanceof MatrixMessage) {
$sendmessage = $message->get_object();
} else {
error_log("message is of not valid type\n");
return false;
}
$url="https://".$this->hs."/_matrix/client/r0/rooms/"
. urlencode($room_id) ."/send/m.room.message?access_token=".$this->at;
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($handle, CURLOPT_TIMEOUT, 60);
curl_setopt($handle, CURLOPT_POSTFIELDS, json_encode($message));
curl_setopt($handle, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
return exec_curl_request($handle);
}
function send_msg($room_id, $message) {
return $this->send($room_id, array(
"msgtype" => "m.notice",
"body" => $message
)
);
}
function register($username, $password, $shared_secret) {
if (!$username) {
error_log("no username provided")
}
if (!$password) {
error_log("no message to send");
}
$mac = hash_hmac('sha1', $username, $registration_shared_secret);
$data = array(
"username" => $user,
"password" => $password,
"mac" => $mac,
}
$url="https://".$this->hs."/_matrix/client/v2_alpha/register";
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($handle, CURLOPT_TIMEOUT, 60);
curl_setopt($handle, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
curl_setopt($handle, CURLOPT_POSTFIELDS, json_encode($data));
return exec_curl_request($handle);
}
}
class MatrixMessage
{
private $message;
function __construct() {
$this->message = array(
"msgtype" => "m.notice",
);
}
function set_type($msgtype) {
$this->$message["msgtype"] = $msgtype;
}
function set_format($format) {
$this->message["format"] = $format;
}
function set_body($body) {
$this->message["body"] = $body;
}
function set_formatted_body($fbody, $format="org.matrix.custom.html") {
$this->message["formatted_body"] = $fbody;
$this->message["format"] = $format;
}
function get_object() {
return $this->message;
}
}
?>