<?php
	class ActivityLogComponent extends Component
	{

		public function GetUUIDs()
		{
			$uuids[] = 'activity_log(\.do){0,1}$';
			return $uuids;
		}

		public function Run( $page, $matches )
		{
			if (isset($_REQUEST['json']))
			{
				header('Content-Type: application/json; charset=utf-8');
				$ret = [];
				$res = get_db_rows( 'SELECT time, reftype, description FROM activity_log ORDER BY time DESC' );
				while( $row = get_db_tuple( $res ) )
				{
					$description = str_replace( ' by <strong></strong>', '', $row['description'] );
					$ips = array();
					if( preg_match( '/([0-9a-f]+:[0-9a-f]+:[0-9a-f:]+)/i', $description, $matches) || preg_match( '/([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})/', $description, $matches ) )
					{
						foreach( $matches AS $match )
						{
							if( in_array( $match, $ips ) || !is_valid_ip( $match ) )
								continue;
							array_push( $ips, $match);
							$description = str_replace( $match, '<a href="/lookup?ip=' . $match . '">' . $match . '</a>', $description );
						}
					}
					$ret[] = [gmdate( 'Y-m-d H:i:s T', $row['time'] ), _activity_log_name_from_type( $row['reftype'] ), $description];
				}
				die(json_encode(['data' => $ret]));
			}
			_page_header( SITE_NAME . ' :: Activity log' );

			$count_offset = time() - 86400;

			// Auto cleanup entries older then above offset (24 hours)
			$del = get_db_rows( 'DELETE FROM activity_log WHERE time < ' . $count_offset);

			$count_add = get_db_tuple( get_db_rows( 'SELECT COUNT(*) FROM blacklist WHERE timestamp >= ' . $count_offset ) );
			$count_del = get_db_tuple( get_db_rows( 'SELECT COUNT(*) FROM blacklist WHERE ts_del >= ' . $count_offset ) );
?>
<h2>Activity log</h2>
<p>This page lists recent changes made to the blacklist.</p>
<p>Activity during last 24 hours: <?= $count_add['count'] ?> adds / <?= $count_del['count'] ?> removes</p>
<table class="listing3 stripe compact" data-src="?json=1">
	<thead>
		<tr>
			<th>Timestamp</th>
			<th>Type</th>
			<th>Description</th>
		</tr>
	</thead>
	<tbody>
	</tbody>
</table>
<?php
			_page_footer();
		}
	};

	new ActivityLogComponent;
?>
