<?php
/**
 * Server Test Class
 * @access public
 */
class imTest {
    const PHP_MIN_VERSION = '7.1.0';

    /**
     * Utility that combine a series of paths
     * @method pathCombine
     * @param  {array}  $paths The array with the elements of the path
     * @return {string} The path created combining the elements of the array
     */
    public static function testPathCombine($paths = array())
    {
        $s = array();
        foreach ($paths as $path) {
            if (strlen($path)) {
                $s[] = trim($path, "/\\ ");
            }
        }
        return implode("/", $s);
    }

    /*
     * Session check
     */
    public static function session_test()
    {
        if (!isset($_SESSION))
            return false;
        $_SESSION['imAdmin_test'] = "test_message";
        return ($_SESSION['imAdmin_test'] == "test_message");
    }

    /*
     * Writable files check
     */
    public static function writable_folder_test($dir)
    {
        if (!file_exists($dir) && $dir != "" && $dir != "./.")
            @mkdir($dir, 0777, true);

        $fp = @fopen(imTest::testPathCombine(array($dir, "imAdmin_test_file")), "w");
        if (!$fp)
            return false;
        if (@fwrite($fp, "test") === false)
            return false;
        @fclose($fp);
        if (!@file_exists(imTest::testPathCombine(array($dir, "imAdmin_test_file"))))
            return false;
        @unlink(imTest::testPathCombine(array($dir, "imAdmin_test_file")));
        return true;
    }

    /*
     * PHP Version check
     */
    public static function php_version_test()
    {
        if (!function_exists("version_compare") || version_compare(PHP_VERSION, self::PHP_MIN_VERSION) < 0)
            return false;
        return true;
    }

    /*
     * MySQL Connection check
     */
    public static function mysql_test($db)
    {
        if (!$db->testConnection())
            return false;
        $db->closeConnection();
        return true;
    }

}
// End of file



session_start();

/**
 * Server Test Class
 * @access public
 */
class imFtpTest {

    /**
     * Test the current WSX5 configuration
     *
     * @return Array An array containing the test results as array("name" => string, "success" => bool)
     */
    public static function testWsx5Configuration($imSettingsTest)
    {
        $testedFolders = array();
        $test = new imTest();
        $keyPhpVersionTest = "FTPphpVersionTest";
        $keySessionTest = "FTPSessionTest";
        $keyPublicFolderTest = "FTPFolderTest";
        $keyDatabaseTest = "FTPDatabaseTest";
        $results = array();

        // PHP version
        $results[] = array(
            "name" => $keyPhpVersionTest,
            "success" => imTest::php_version_test(),
            "extra" => array(
                "phpMinVersion" => imTest::PHP_MIN_VERSION,
                "phpVersion" => PHP_VERSION
            )
        );

        // Session
        $results[] = array(
            "name"    => $keySessionTest,
            "success" => imTest::session_test()
        );

        // Generic public folder
        if (isset($imSettingsTest['general']['public_folder'])) {
            $testedFolders[] = $imSettingsTest['general']['public_folder'];
            $results[] = array(
                "name"    => $keyPublicFolderTest,
                "success" => imTest::writable_folder_test($imSettingsTest['general']['public_folder']),
                "extra" => array(
                    "folder" => ($imSettingsTest['general']['public_folder'] != "" ? " (" . $imSettingsTest['general']['public_folder'] . ")": " (site root folder)")
                )
            );
        }        

        // Blog public folder
        if (isset($imSettingsTest['blog']) && $imSettingsTest['blog']['comments_source'] == 'wsx5' && $imSettingsTest['blog']['sendmode'] == 'file' && !in_array($imSettingsTest['blog']['folder'], $testedFolders)) {
            $testedFolders[] = $imSettingsTest['blog']['folder'];
            $results[] = array(
                "name"    => $keyPublicFolderTest,
                "success" => imTest::writable_folder_test($imSettingsTest['blog']['folder']),
                "extra" => array(
                    "folder" => ($imSettingsTest['blog']['folder'] != "" ? " (" . $imSettingsTest['blog']['folder'] . ")": " (site root folder)")
                )
            );
        }
  
        // Guestbooks public folder
        if (isset($imSettingsTest['guestbooks'])) {
            foreach($imSettingsTest['guestbooks'] as $gb) {
                if ($gb['sendmode'] == 'file') {
                    // Check this folder only if it's different from the blog's one
                    if (!in_array($gb['folder'], $testedFolders)) {
                        $testedFolders[] = $gb['folder'];
                        $results[] = array(
                            "name"    => $keyPublicFolderTest,
                            "success" => imTest::writable_folder_test($gb['folder']),
                            "extra" => array(
                                "folder" => ($gb['folder'] != "" ? " (" . $gb['folder'] . ")" :  " (site root folder)")
                            )
                        );
                    }
                }
            }
        }
        
        // Dynamic Objects public folder
        if (isset($imSettingsTest['dynamicobjects'])) {
            foreach($imSettingsTest['dynamicobjects'] as $objType => $objValue) {
                foreach($objValue as $objId => $obj) {
                    if (isset($obj['folder']) && !in_array($obj['folder'], $testedFolders)) {
                        $testedFolders[] = $obj['folder'];
                        $results[] = array(
                            "name"    => $keyPublicFolderTest,
                            "success" => imTest::writable_folder_test($obj['folder']),
                            "extra" => array(
                                "folder" => ($obj['folder'] != "" ? " (" . $obj['folder'] . ")" :  " (site root folder)")
                            )
                        );
                    }
                }
            }
        }
        
        // Databases
        if (isset($imSettingsTest['databases'])) {
            foreach($imSettingsTest['databases'] as $dbid => $db) {
                $database = new ImDbTest($db['host'], $db['user'], $db['password'], $db['database']);
                $results[] = array(
                    "name"    => $keyDatabaseTest,
                    "success" => imTest::mysql_test($database),
                    "extra" => array(
                        "databaseId" => $dbid,
                        "databaseDescription" => $db['description']
                    )
                );
            }
        }
        
        return $results;
    }
}

/**
 * @summary
 * A utility class which provides an easy access to the databases defined by the WSX5 user.
 * Is used only for the test during project export with ftp.
 * Detect if mySQLi or MySQL is supported.
 * 
 * @description Create a new ImDbTest Object
 *
 * @class
 * @constructor
 * 
 * @param {string} $host  The database host address
 * @param {string} $user  The database username
 * @param {string} $pwd   The database password
 * @param {string} $db    The database name
 */
class ImDbTest {

    private $conn;
    private $db;
    private $engine;
    private $type;
    public $error = false;


    function __construct($host, $user, $pwd, $db)
    {
        // Detect the correct driver
        if (function_exists("mysqli_connect")) {
            mysqli_report(MYSQLI_REPORT_OFF);
            
            $this->type = "mysqli";
            $this->engine = "INNODB";
            $this->db = @new mysqli($host, $user, $pwd);

            if ($this->db->connect_errno) {
                $this->error = true;
                return;
            }
            if (strlen($db)) {
                if (@$this->db->select_db($db) == false) {
                    $this->error = true;
                }
            }
        
        } else if (function_exists("mysql_connect")) {

            $this->type = "mysql";
            $this->engine = "MYISAM";

            $this->conn = @mysql_connect($host, $user, $pwd);
            if ($this->conn === false) {
                $this->error = true;
                return;
            }
            $this->db = @mysql_select_db($db, $this->conn);
            if ($this->db === false) {
                $this->error = true;
            }

        } else {
            $this->error = true;
        }
    }

    /**
     * Check if the class is connected or not to a db
     *
     * @return {boolean} True if the class is connected to a DB. False otherwise.
     */
    function testConnection()
    {
        return !$this->error;
    }

    /**
    * Close the connection
    * 
    * @return void
    */
    function closeConnection()
    {
        if($this->type == "mysqli")
            @mysqli_close($this->db);
        else
            @mysql_close($this->conn);
    }

}
// End of file

$imSettingsTest = array();
$imSettingsTest['databases'] = array();
$imSettingsTest['general']['public_folder'] = "";
$imSettingsTest['blog'] = array(	'description' => '',
	'keywords' => '',
	'root' => 'https://www.fougere-lune.ch/blog/',
	'home_posts_number' => 10,
	'card_style' => array(
		'layout' => "fixedheight",
		'cardsPerRow' => 1,
		'rowsPerPage' => 10,
		'paginationEnabled' => true,
		'contentWidthPerc' => 50,
		'card' => array(
			'type' => "leftcoverrightcontents",
			'margin' => 80,
			'height' => 200,
			'backgroundColor' => array(
				'a' => 255,
				'r' => 0,
				'g' => 0,
				'b' => 0
			),
			'border' => array(
				'colors' => array(
					'top' => array(
						'a' => 255,
						'r' => 102,
						'g' => 102,
						'b' => 102
					),
					'bottom' => array(
						'a' => 255,
						'r' => 102,
						'g' => 102,
						'b' => 102
					),
					'left' => array(
						'a' => 255,
						'r' => 102,
						'g' => 102,
						'b' => 102
					),
					'right' => array(
						'a' => 255,
						'r' => 102,
						'g' => 102,
						'b' => 102
					)
				),
				'radius' => array(
					'topLeft' => 0,
					'bottomLeft' => 0,
					'topRight' => 0,
					'bottomRight' => 0
				),
				'widths' => array(
					'top' => 0,
					'bottom' => 1,
					'left' => 0,
					'right' => 0
				)
			),
			'shadow' => array(
				'enabled' => false,
				'color' => array(
					'a' => 255,
					'r' => 128,
					'g' => 128,
					'b' => 128
				),
				'offset' => array(
					'x' => 3,
					'y' => 3
				),
				'spread' => 0,
				'blur' => 5
			),
			'image' => array(
				'percentSize' => 50,
				'margins' => array(
					'top' => 0,
					'bottom' => 0,
					'left' => 0,
					'right' => 0
				),
				'sizeAdapted' => true,
				'mouseovereffect' => 'none'
			),
			'txtBlock' => array(
				'height' => 200,
				'margins' => array(
					'top' => 10,
					'bottom' => 30,
					'left' => 20,
					'right' => 5
				),
				'align' => 'start',
				'name' => array(
					'show' => true,
					'style' => array(
						'backgroundColor' => array(
							'a' => 0,
							'r' => 255,
							'g' => 255,
							'b' => 255
						),
						'textColor' => array(
							'a' => 255,
							'r' => 199,
							'g' => 160,
							'b' => 85
						),
						'align' => 'start',
						'font' => array(
							'familyName' => 'Dancing Script',
							'size' => 22,
							'style' => "bold"
						)
					)
				),
				'description' => array(
					'show' => true,
					'style' => array(
						'backgroundColor' => array(
							'a' => 0,
							'r' => 255,
							'g' => 255,
							'b' => 255
						),
						'textColor' => array(
							'a' => 255,
							'r' => 217,
							'g' => 217,
							'b' => 217
						),
						'align' => 'start',
						'font' => array(
							'familyName' => 'Montserrat',
							'size' => 12,
							'style' => "regular"
						)
					)
				),
				'details' => array(
					'showCategory' => true,
					'style' => array(
						'backgroundColor' => array(
							'a' => 0,
							'r' => 255,
							'g' => 255,
							'b' => 255
						),
						'textColor' => array(
							'a' => 255,
							'r' => 217,
							'g' => 217,
							'b' => 217
						),
						'align' => 'start',
						'font' => array(
							'familyName' => 'Oswald',
							'size' => 10,
							'style' => "regular"
						)
					),
					'showAuthor' => false,
					'showDate' => false,
					'showReadTime' => true
				),
				'button' => array(
					'show' => true,
					'useImage' => false,
					'style' => array(
						'backgroundColor' => array(
							'a' => 255,
							'r' => 199,
							'g' => 160,
							'b' => 85
						),
						'textColor' => array(
							'a' => 255,
							'r' => 0,
							'g' => 0,
							'b' => 0
						),
						'align' => 'start',
						'font' => array(
							'familyName' => 'Montserrat',
							'size' => 10,
							'style' => "bold"
						)
					),
					'border' => array(
						'colors' => array(
							'top' => array(
								'a' => 0,
								'r' => 255,
								'g' => 255,
								'b' => 255
							),
							'bottom' => array(
								'a' => 0,
								'r' => 255,
								'g' => 255,
								'b' => 255
							),
							'left' => array(
								'a' => 0,
								'r' => 255,
								'g' => 255,
								'b' => 255
							),
							'right' => array(
								'a' => 0,
								'r' => 255,
								'g' => 255,
								'b' => 255
							)
						),
						'radius' => array(
							'topLeft' => 20,
							'bottomLeft' => 20,
							'topRight' => 20,
							'bottomRight' => 20
						),
						'widths' => array(
							'top' => 0,
							'bottom' => 0,
							'left' => 0,
							'right' => 0
						)
					),
					'margins' => array(
						'top' => 8,
						'bottom' => 8,
						'left' => 30,
						'right' => 30
					),
					'image' => null,
					'position' => 'end',
					'flipImage' => false
				)
			)
		),
		'highlight' => array(
			'mode' => "none",
			'count' => 1,
			'height' => 300
		)
	),
	'article_type' => 'titlecovercontents',
	'article_read_speed' => 180,
	'file_prefix' => 'x5_',
	'minCardWidth' => 400,
	'itemsContainerWidth' => [994, 768, 480, 0],
	'comments_source' => 'wsx5',
	'email' => '',
	'moderate' => false,
	'sendmode' => 'db',
	'dbid' => '',
	'dbtable' => '',
	'comment_type' => 'both',
	'comments_order' => 'asc',
	'comments_on_multiple_columns' => true,
	'abuse' => false,
	'captcha' => false,
	'categories' => Array('DJ Set', 'Live Music Show', 'Special Event'),
	'posts' => Array(),
	'posts_cat' => Array(),
	'posts_author' => Array(),
	'posts_month' => Array(),
	'posts_slug' => Array()
)
;
$imSettingsTest['guestbooks'] = array();
$imSettingsTest['dynamicobjects'] = array(	'template' => array(
),
	'pages' => array(

	));
$result = imFtpTest::testWsx5Configuration($imSettingsTest);
echo json_encode($result);
