<?php
/*
 * @package AJAX_Chat
 * @author Sebastian Tschan
 * @copyright (c) Sebastian Tschan
 * @license GNU Affero General Public License
 * @link https://blueimp.net/ajax/
 */

if(!empty($_GET['common'])) {
    $domain = (strpos($_SERVER['HTTP_HOST'], 'flashii.net') ? 'flashii' : 'edgii');
    $commonUrl = 'https://futami.' . $domain . '.net/common.json';
    $common = json_decode(file_get_contents($commonUrl));

    if($_GET['common'] === 'config') {
        function array_to_jsobj(array $array): string {
            $isList = array_is_list($array);
            $parts = [];

            foreach($array as $key => $value) {
                $entry = $isList ? '' : ($key . ': ');
                $type = gettype($value);
                if($type === 'NULL')
                    $entry .= 'null';
                elseif($type === 'array') {
                    $entry .= array_to_jsobj($value);
                } elseif($type === 'boolean')
                    $entry .= $value ? 'true' : 'false';
                elseif($type === 'integer')
                    $entry .= $value;
                elseif($type === 'double')
                    $entry .= $value;
                elseif($type === 'string')
                    $entry .= '\'' . addslashes($value) . '\'';

                $parts[] = $entry;
            }

            return ($isList ? 'new Array(' : '{')
                . implode(', ', $parts)
                . ($isList ? ')' : '}');
        }

        $config = [
            'loginChannelID' => null,
            'loginChannelName' => null,
            'timerRate' => 2000,
            'ajaxURL' => './?ajax=true',
            'baseURL' => './',
            'regExpMediaUrl' => '^((http)|(https)):\\/\\/',
            'startChatOnLoad' => true,
            'domIDs' => [
                'chatList' => 'chatList',
                'onlineList' => 'onlineList',
                'inputField' => 'inputField',
                'messageLengthCounter' => 'messageLengthCounter',
                'channelSelection' => 'channelSelection',
                'styleSelection' => 'styleSelection',
                'emoticonsContainer' => 'emoticonsContainer',
                'colorCodesContainer' => 'colorCodesContainer',
                'flashInterfaceContainer' => 'flashInterfaceContainer',
            ],
            'settings' => [
                'bbCode' => true,
                'bbCodeImages' => true,
                'bbCodeColors' => true,
                'hyperLinks' => true,
                'lineBreaks' => true,
                'emoticons' => true,
                'autoFocus' => true,
                'autoScroll' => true,
                'maxMessages' => 0,
                'wordWrap' => false,
                'maxWordLength' => true,
                'dateFormat' => '(%H:%i:%s)',
                'persistFontColor' => true,
                'fontColor' => null,
                'audio' => true,
                'audioVolume' => 1.0,
                'soundReceive' => 'ajaxchat_incoming',
                'soundSend' => 'ajaxchat_outgoing',
                'soundEnter' => 'ajaxchat_join',
                'soundLeave' => 'ajaxchat_leave',
                'soundChatBot' => 'ajaxchat_server',
                'soundError' => 'local_error',
                'soundKick' => 'dokuro_pipiru',
                'soundPrivate' => 'ajaxchat_incoming',
                'blink' => true,
                'blinkInterval' => 500,
                'blinkIntervalNumber' => 10,
            ],
            'nonPersistentSettings' => ['wordWrap'],
            'bbCodeTags' => ['b', 'i', 'u', 'quote', 'code', 'color', 'url', 'img'],
            'colorCodes' => [],
            'emoticonCodes' => [],
            'emoticonFiles' => [],
            'soundFiles' => [
                'local_error' => '/sounds/ajax_error.mp3',
                'local_shit' => '/sounds/ajax_shit.mp3',
            ],
            'sessionName' => 'ajax_chat',
            'cookieExpiration' => 365,
            'cookiePath' => '/',
            'cookieDomain' => null,
            'cookieSecure' => null,
            'chatBotName' => 'Koishi',
            'chatBotID' => 2147483647,
            'allowUserMessageDelete' => false,
            'inactiveTimeout' => 2,
            'privateChannelDiff' => 500000000,
            'privateMessageDiff' => 1000000000,
            'showChannelMessages' => true,
            'messageTextMaxLength' => 2000,
            'socketServerEnabled' => false,
            'socketServerHost' => 'localhost',
            'socketServerPort' => 1935,
            'socketServerChatID' => 0,
        ];


        foreach($common->colours as $colourInfo)
            $config['colorCodes'][] = str_replace(' ', '', $colourInfo->n);

        $config['title'] = $common->title;

        $soundsUrl = 'https:' . (isset($common->sounds2) ? $common->sounds2 : $common->sounds);
        $sounds = json_decode(file_get_contents($soundsUrl));
        foreach($sounds->library as $soundInfo)
            if(isset($soundInfo->sources->mp3))
                $config['soundFiles'][strtr($soundInfo->name, [':' => '_', '-' => '_'])] = $soundInfo->sources->mp3;

        $emotesUrl = 'https:' . $common->emotes;
        $emotes = json_decode(file_get_contents($emotesUrl));
        foreach($emotes as $emoteInfo)
            if($emoteInfo->Hierarchy < 1) {
                $config['emoticonCodes'][] = $emoteInfo->Text[0];
                $config['emoticonFiles'][] = $emoteInfo->Image;
            }

        header('Content-Type: application/javascript; charset=utf-8');
        echo 'var ajaxChatConfig = ' . array_to_jsobj($config) . ';';
    } elseif($_GET['common'] === 'colours') {
        header('Content-Type: text/css');
        foreach($common->colours as $colourInfo) {
            $colourName = str_replace(' ', '', $colourInfo->n);
            $colourHex = '#' . str_pad(dechex($colourInfo->c), 6, '0', STR_PAD_LEFT);
            echo 'a.' . $colourName . ' { background-color: ' . $colourHex . "; }\r\n";
            echo '#content .' . $colourName . ' { color: ' . $colourHex . "; }\r\n";
        }
    }
    exit;
}

// Include Class libraries:
require_once __DIR__ . '/../ajaxchat.php';

// Initialize the chat:
$ajaxChat = new CustomAJAXChat();
