<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>[13001] sites/trunk/api.wordpress.org/public_html/dotorg/matrix: [matrix] add trac bot endpoint for maubot</title>
</head>
<body>

<style type="text/css"><!--
#msg dl.meta { border: 1px #006 solid; background: #369; padding: 6px; color: #fff; }
#msg dl.meta dt { float: left; width: 6em; font-weight: bold; }
#msg dt:after { content:':';}
#msg dl, #msg dt, #msg ul, #msg li, #header, #footer, #logmsg { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt;  }
#msg dl a { font-weight: bold}
#msg dl a:link    { color:#fc3; }
#msg dl a:active  { color:#ff0; }
#msg dl a:visited { color:#cc6; }
h3 { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt; font-weight: bold; }
#msg pre { white-space: pre-line; overflow: auto; background: #ffc; border: 1px #fa0 solid; padding: 6px; }
#logmsg { background: #ffc; border: 1px #fa0 solid; padding: 1em 1em 0 1em; }
#logmsg p, #logmsg pre, #logmsg blockquote { margin: 0 0 1em 0; }
#logmsg p, #logmsg li, #logmsg dt, #logmsg dd { line-height: 14pt; }
#logmsg h1, #logmsg h2, #logmsg h3, #logmsg h4, #logmsg h5, #logmsg h6 { margin: .5em 0; }
#logmsg h1:first-child, #logmsg h2:first-child, #logmsg h3:first-child, #logmsg h4:first-child, #logmsg h5:first-child, #logmsg h6:first-child { margin-top: 0; }
#logmsg ul, #logmsg ol { padding: 0; list-style-position: inside; margin: 0 0 0 1em; }
#logmsg ul { text-indent: -1em; padding-left: 1em; }#logmsg ol { text-indent: -1.5em; padding-left: 1.5em; }
#logmsg > ul, #logmsg > ol { margin: 0 0 1em 0; }
#logmsg pre { background: #eee; padding: 1em; }
#logmsg blockquote { border: 1px solid #fa0; border-left-width: 10px; padding: 1em 1em 0 1em; background: white;}
#logmsg dl { margin: 0; }
#logmsg dt { font-weight: bold; }
#logmsg dd { margin: 0; padding: 0 0 0.5em 0; }
#logmsg dd:before { content:'\00bb';}
#logmsg table { border-spacing: 0px; border-collapse: collapse; border-top: 4px solid #fa0; border-bottom: 1px solid #fa0; background: #fff; }
#logmsg table th { text-align: left; font-weight: normal; padding: 0.2em 0.5em; border-top: 1px dotted #fa0; }
#logmsg table td { text-align: right; border-top: 1px dotted #fa0; padding: 0.2em 0.5em; }
#logmsg table thead th { text-align: center; border-bottom: 1px solid #fa0; }
#logmsg table th.Corner { text-align: left; }
#logmsg hr { border: none 0; border-top: 2px dashed #fa0; height: 1px; }
#header, #footer { color: #fff; background: #636; border: 1px #300 solid; padding: 6px; }
#patch { width: 100%; }
#patch h4 {font-family: verdana,arial,helvetica,sans-serif;font-size:10pt;padding:8px;background:#369;color:#fff;margin:0;}
#patch .propset h4, #patch .binary h4 {margin:0;}
#patch pre {padding:0;line-height:1.2em;margin:0;}
#patch .diff {width:100%;background:#eee;padding: 0 0 10px 0;overflow:auto;}
#patch .propset .diff, #patch .binary .diff  {padding:10px 0;}
#patch span {display:block;padding:0 10px;}
#patch .modfile, #patch .addfile, #patch .delfile, #patch .propset, #patch .binary, #patch .copfile {border:1px solid #ccc;margin:10px 0;}
#patch ins {background:#dfd;text-decoration:none;display:block;padding:0 10px;}
#patch del {background:#fdd;text-decoration:none;display:block;padding:0 10px;}
#patch .lines, .info {color:#888;background:#fff;}
--></style>
<div id="msg">
<dl class="meta" style="font-size: 105%">
<dt style="float: left; width: 6em; font-weight: bold">Revision</dt> <dd><a style="font-weight: bold" href="http://meta.trac.wordpress.org/changeset/13001">13001</a><script type="application/ld+json">{"@context":"http://schema.org","@type":"EmailMessage","description":"Review this Commit","action":{"@type":"ViewAction","url":"http://meta.trac.wordpress.org/changeset/13001","name":"Review Commit"}}</script></dd>
<dt style="float: left; width: 6em; font-weight: bold">Author</dt> <dd>ashfame</dd>
<dt style="float: left; width: 6em; font-weight: bold">Date</dt> <dd>2023-12-04 16:03:45 +0000 (Mon, 04 Dec 2023)</dd>
</dl>

<pre style='padding-left: 1em; margin: 2em 0; border-left: 2px solid #ccc; line-height: 1.25; font-size: 105%; font-family: sans-serif'>[matrix] add trac bot endpoint for maubot</pre>

<h3>Added Paths</h3>
<ul>
<li>sites/trunk/api.wordpress.org/public_html/dotorg/matrix/</li>
<li><a href="#sitestrunkapiwordpressorgpublic_htmldotorgmatrixtracbotphp">sites/trunk/api.wordpress.org/public_html/dotorg/matrix/trac-bot.php</a></li>
</ul>

</div>
<div id="patch">
<h3>Diff</h3>
<a id="sitestrunkapiwordpressorgpublic_htmldotorgmatrixtracbotphp"></a>
<div class="addfile"><h4 style="background-color: #eee; color: inherit; margin: 1em 0; padding: 1.3em; font-size: 115%">Added: sites/trunk/api.wordpress.org/public_html/dotorg/matrix/trac-bot.php</h4>
<pre class="diff"><span>
<span class="info" style="display: block; padding: 0 10px; color: #888">--- sites/trunk/api.wordpress.org/public_html/dotorg/matrix/trac-bot.php                              (rev 0)
+++ sites/trunk/api.wordpress.org/public_html/dotorg/matrix/trac-bot.php        2023-12-04 16:03:45 UTC (rev 13001)
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -0,0 +1,238 @@
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+<?php
+
+namespace {
+       require dirname( dirname( __DIR__ ) ) . '/wp-init.php';
+
+       require dirname( dirname( __DIR__ ) ) . '/includes/class-trac.php';
+
+       require dirname( dirname( __DIR__ ) ) . '/includes/matrix/config.php';
+
+       // Load Dotorg\Slack autoloader since Trac's Ticket and Commit class are defined under \Dotorg\Slack\ namespace.
+       require dirname( dirname( __DIR__ ) ) . '/includes/slack/autoload.php';
+}
+
+namespace Dotorg\Matrix\Trac {
+
+       define( 'DISABLE_TRAC_TICKETS_UPDATION', true ); // For testing, this prevents test stuff to be posted on Trac tickets.
+       define( 'REPOST_MATRIX_LINK_TIME', 300 ); // 5 mins
+       define( 'REPOST_TRAC_COMMENT_TIME', 7200 ); // 2 hrs
+
+       // Simulate a webhook request.
+       // $_GET['secret'] = URL_SECRET__TRAC_BOT;
+       // $_POST['text'] = 'Hello #40007 and #1232-bbpress'; // Or 'Hello #1232-bbpress'
+       // $_POST['user_id'] = '@admin:matrix.test';
+       // $_POST['room_id'] = '!XXXXXXXX:matrix.test';
+       // $_POST['room_alias'] = '#sandbox:matrix.test';
+       // $_POST['event_id'] = '$HHHHHHHHHHHHH';
+
+       // Verify it came from Maubot tracbot plugin.
+       if ( ! isset( $_GET['secret'] ) || $_GET['secret'] !== URL_SECRET__TRAC_BOT ) {
+               http_response_code( 403 );
+               return;
+       }
+
+       $room_alias_local_part = ltrim( explode( ':', $_POST['room_alias'] )[0], '#' );
+
+       // Prevent frequent posting to both Matrix & Trac using Redundancy Manager.
+       $redundancy_manager = new Redundancy_Manager(
+               $room_alias_local_part,
+               REPOST_MATRIX_LINK_TIME,
+               REPOST_TRAC_COMMENT_TIME,
+       );
+       $redundancy_manager->avoid_redundancy();
+
+       // Note: echos are prevented and won't be received, so no need to handle them.
+
+       // Data adjustment since trac bot is written for Slack.
+       $post_data                 = $_POST;
+       $post_data['channel_name'] = $room_alias_local_part;
+
+       // Following code is copied from api/public_html/dotorg/slack/trac-bot.php and then modified.
+       $parser = new \Dotorg\Slack\Trac\Bot( $post_data );
+       $parsed = $parser->parse();
+
+       $ticket_class = '\Dotorg\Slack\Trac\Ticket';
+       $commit_class = '\Dotorg\Slack\Trac\Commit';
+
+       // Matrix messages that would be posted as a response to this webhook request being handled.
+       $matrix_messages = array();
+
+       // Loop through all results, grouped by Trac and then by type (commit versus ticket).
+       foreach ( $parsed as $trac => $results ) {
+               $trac_obj = \Dotorg\Slack\Trac\Trac::get( $trac );
+
+               $parsed_objects = array(
+                       'ticket' => array(),
+                       'commit' => array(),
+               );
+
+               //
+               // What needs to be posted on Matrix?
+               //
+
+               foreach ( $results as $type => $values ) {
+                       // Loop through all tickets and commits for this Trac.
+                       foreach ( $values as $value ) {
+                               $id = is_array( $value ) ? $value['id'] : $value;
+
+                               $class = 'commit' === $type ? $commit_class : $ticket_class;
+                               // Get the Ticket or Commit object for this Trac + ID.
+                               $obj = call_user_func( array( $class, 'get' ), $trac_obj, $id );
+
+                               // Keep a reference to this object for later.
+                               $parsed_objects[ $type ][ $id ] = $obj;
+
+                               // skip if we have recently posted to Matrix.
+                               if ( $redundancy_manager->is_redundant( 'matrix', $trac, $type, $id ) ) {
+                                       continue;
+                               }
+
+                               $matrix_message = '';
+                               $attachment     = $obj->get_attachment();
+                               if ( $attachment ) {
+                                       $matrix_message = '[' . $attachment['title'] . '](' . $attachment['title_link'] . ')';
+                               } else {
+                                       $url = $obj->get_url();
+                                       if ( $url ) {
+                                               $matrix_message = $url;
+                                       }
+                               }
+
+                               if ( $matrix_message ) {
+                                       $matrix_messages[] = $matrix_message;
+                                       $redundancy_manager->set( 'matrix', $trac, $type, $id );
+                               }
+                       }
+               }
+
+               // It's possible that all of our tickets/commits were redundant and thus skipped.
+               if ( count( $matrix_messages ) === 0 ) {
+                       continue;
+               }
+
+               //
+               // What needs to be posted on Trac?
+               //
+
+               // If there's no tickets referenced (ie. just commits) then there's no need to flag the reference on Trac.
+               if ( empty( $results['ticket'] ) ) {
+                       continue;
+               }
+
+               if ( ! DISABLE_TRAC_TICKETS_UPDATION ) {
+                       if ( defined( TRACBOT_WPORG_PASSWORD ) && ! empty( TRACBOT_WPORG_PASSWORD ) ) {
+                               $trac_xmlrpc = new \Trac( 'matrixbot', TRACBOT_WPORG_PASSWORD, "https://$trac.trac.wordpress.org/login/xmlrpc" );
+                       }
+               }
+
+               $comment_template = 'This ticket was mentioned in [Matrix](https://matrix.wordpress.net/) in %1$s by %2$s. [View the logs](https://matrix.to/#/%3$s/%4$s?via=trac).';
+               $trac_comment     = sprintf( $comment_template, $post_data['room_alias'], $post_data['user_id'], $post_data['room_id'], $post_data['event_id'] );
+
+               foreach ( $results['ticket'] as $ticket ) {
+                       $ticket_id = is_array( $ticket ) ? $ticket['id'] : $ticket;
+
+                       // If the ticket is closed and hasn't been modified in over 2 years, don't post a reference to it.
+                       if ( ! empty( $parsed_objects['ticket'][ $ticket_id ] ) ) {
+                               $ticket_object = $parsed_objects['ticket'][ $ticket_id ];
+                               $ticket_object->fetch();
+
+                               $is_closed         = ( 'closed' === $ticket_object->status );
+                               $last_modified     = strtotime( $ticket_object->modified );
+                               $has_recent_change = ( ! $last_modified || $last_modified > ( time() - 2 * YEAR_IN_SECONDS ) );
+
+                               if ( $is_closed && ! $has_recent_change ) {
+                                       continue;
+                               }
+                       }
+
+                       if ( $redundancy_manager->is_redundant( 'trac', $trac, 'ticket', $ticket_id ) ) {
+                               continue;
+                       }
+
+                       $redundancy_manager->set( 'trac', $trac, 'ticket', $ticket_id );
+
+                       if ( ! DISABLE_TRAC_TICKETS_UPDATION ) {
+                               isset( $trac_xmlrpc ) && $trac_xmlrpc->ticket_update( $ticket_id, $trac_comment );
+                       }
+               }
+       }
+
+       // Bail if it's too early to post matrix links again, as it would be too early to post a link on trac ticket as well.
+       if ( count( $matrix_messages ) === 0 ) {
+               http_response_code( 204 );
+               exit;
+       }
+
+       // Return JSON, so that matrix messages can get posted.
+       header( 'Content-Type: application/json' );
+       $response = array(
+               'messages'       => $matrix_messages,
+               'post_in_thread' => false,
+       );
+       echo json_encode( $response );
+       die();
+
+       /**
+        * Redundancy_Manager class
+        */
+       class Redundancy_Manager {
+
+               private $cache_group = 'matrixtrac';
+               private array $redundant_time;
+               private bool $avoid_redundancy = false;
+               private string $room;
+
+               public function __construct( $room, $matrix_redundant_time, $trac_redundant_time ) {
+                       $this->room           = $room;
+                       $this->redundant_time = array(
+                               'matrix' => $matrix_redundant_time,
+                               'trac'   => $trac_redundant_time,
+                       );
+               }
+
+               public function avoid_redundancy() {
+                       $this->avoid_redundancy = true;
+                       wp_cache_init();
+               }
+
+               public function is_redundant( $realm, $trac, $type, $id ): bool {
+                       if ( ! $this->avoid_redundancy ) {
+                               return false;
+                       }
+
+                       $since = wp_cache_get(
+                               $this->key( $realm, $trac, $type, $id ),
+                               $this->cache_group
+                       );
+
+                       if ( empty( $since ) ) {
+                               return false;
+                       }
+
+                       $now                    = time();
+                       $redundancy_expiring_at = $since + $this->redundant_time[ $realm ];
+
+                       if ( $redundancy_expiring_at < $now ) {
+                               return false;
+                       }
+
+                       return true;
+               }
+
+               public function set( $realm, $trac, $type, $id ) {
+                       if ( ! $this->avoid_redundancy ) {
+                               return;
+                       }
+                       wp_cache_set(
+                               $this->key( $realm, $trac, $type, $id ),
+                               time(),
+                               $this->cache_group,
+                               $this->redundant_time[ $realm ]
+                       );
+               }
+
+               private function key( $realm, $trac, $type, $id ) {
+                       return sprintf( 'room:%s:%s:%s:%s:%d', $this->room, $realm, $trac, $type, $id );
+               }
+       }
+}
</ins><span class="cx" style="display: block; padding: 0 10px">Property changes on: sites/trunk/api.wordpress.org/public_html/dotorg/matrix/trac-bot.php
</span><span class="cx" style="display: block; padding: 0 10px">___________________________________________________________________
</span></span></pre></div>
<a id="svneolstyle"></a>
<div class="addfile"><h4 style="background-color: #eee; color: inherit; margin: 1em 0; padding: 1.3em; font-size: 115%">Added: svn:eol-style</h4></div>
<ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+native
</ins><span class="cx" style="display: block; padding: 0 10px">\ No newline at end of property
</span></div>

</body>
</html>