mattermost/mattermost.inc.php

89 lines
2.6 KiB
PHP
Raw Permalink Normal View History

2023-10-23 18:38:32 +03:00
<?php
function mattermost_send($server, $token, $channel_id, $msg, $fields = [])
{
$url = "$server/api/v4/posts";
$headers = [
'Content-Type: application/json',
'Authorization: Bearer ' . $token
];
$fields['channel_id'] = $channel_id;
$fields['message'] = $msg;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if($status != 201)
throw new Exception("Post failed with status: " . $status .", result: " . var_export($result, true));
return json_decode($result, true);
}
function mattermost_send_file($server, $token, $channel_id, $title, $filepath, $mime = 'application/octet-stream', $post_fields = [])
{
$url = "$server/api/v4/files";
$headers = [
'Content-Type: multipart/form-data',
'Authorization: Bearer ' . $token
];
$cfile = new \CURLFile(realpath($filepath), $mime, basename($filepath));
$upload_fields = [
'channel_id' => $channel_id,
'files' => $cfile
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $upload_fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
$result = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if($status != 201)
throw new Exception("File failed with status: " . $status .", result: " . var_export($result, true));
$result = json_decode($result, true);
$file_id = $result['file_infos'][0]['id'];
$post_fields['file_ids'] = array($file_id);
return mattermost_send($server, $token, $channel_id, $title, $post_fields);
}
function mattermost_send_thread_with_replies($server, $token, $channel_id, $msg, array $replies, $fields = [])
{
$mm_orig_resp = mattermost_send($server, $token, $channel_id, $msg, $fields);
$root_key = 'id';
if(!isset($mm_orig_resp[$root_key]))
{
echo "Failed to post to Mattermost: response contains no '$root_key' value to post thread replies:\n".json_encode($mm_orig_resp, JSON_PRETTY_PRINT)."\n";
return null;
}
$root_id = $mm_orig_resp[$root_key];
$fields['root_id'] = $root_id;
foreach($replies as $reply)
mattermost_send($server, $token, $channel_id, $reply, $fields);
return $root_id;
}