<?php

/**
 * MMNotify extension
 *
 * @file
 * @ingroup Extensions
 * @copyright 2019-2020 Someone <someone@somenet.org>
 * @license MIT
 */

class MMNotify{
    /**
    * Occurs after a new article has been created.
    * @see http://www.mediawiki.org/wiki/Manual:Hooks/ArticleInsertComplete
    */
    static function onPageContentInsertComplete(WikiPage $wikiPage, $user, $text, $summary, $isminor, $iswatch, $section, $flags, $revision){
        if (stripos($wikiPage->getTitle()->getText(), 'FSPlenum') === false) return;

        $text = ContentHandler::getContentText($wikiPage->getRevision()->getContent( Revision::RAW));
        preg_match_all('/^={1,4}[^=].*$/m', $text, $out);

        $post = '\n';
        foreach ($out[0] as $heading) {
            if((stripos($heading, 'outcome') !== false))continue;

            $heading = preg_replace('/\s*=+\s*$/', '', $heading);
            $heading = preg_replace('/^(=+)\s*/', '\1+ ', $heading);
            $heading = explode ('+ ', $heading, 2);

            $post .= str_replace("=", " ", $heading[0]).'+ '.$heading[1].'\n';
        }

        $post = wfMessage('mmmotify-onPageContentInsertComplete')->plain().'\n'.$wikiPage->getTitle()->getFullURL().'\n\n----'.self::unindent($post);

        self::send_curl_request('{"text": "'.str_replace('"', '\"', $post).'"}');
        return true;
    }


    // stolen from Indentation.class.php
    private static function lines($lines) {
        if(is_string($lines)) $lines = explode("\n",str_replace("\r\n","\n",$lines));
        return $lines;
    }

    // stolen from Indentation.class.php
    private static function unindent($lines) {
        $lines = self::lines($lines);
        if(!$lines) return '';

        $first = array_shift($lines);
        $min = PHP_INT_MAX;

        foreach($lines as $l) { # find smallest indentation
            $ind = strlen($l) - strlen(ltrim($l));
            if($ind < $min)$min = $ind;
         }
        foreach($lines as $idx=>$l) $lines[$idx] = substr($l,$min);
        return trim($first."\n".implode("\n",$lines));
    }

    private static function send_curl_request($postData) {
        global $MMIncomingWebhookUrl;

        $h = curl_init();
        curl_setopt($h, CURLOPT_URL, $MMIncomingWebhookUrl);
        curl_setopt($h, CURLOPT_POST, 1);
        curl_setopt($h, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($h, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: '.strlen($postData)));
        curl_setopt($h, CURLOPT_RETURNTRANSFER, true);
        $curl_output = curl_exec($h);
        curl_close($h);
    }
}