<?php
  /**
   * phpaga
   *
   * requirements test
   *
   * This file tests if all necessary requirements for running phpaga are
   * fulfilled.
   *
   * @author Florian Lanthaler <florian@phpaga.net>
   * @version $Id: test.php 768 2006-12-08 00:34:44Z florian $
   *
   * Copyright (c) 2003, Florian Lanthaler <florian@phpaga.net>
   *
   * All rights reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions are
   * met:
   *
   *    * Redistributions of source code must retain the above copyright
   *      notice, this list of conditions and the following disclaimer.
   *
   *    * Redistributions in binary form must reproduce the above copyright
   *      notice, this list of conditions and the following disclaimer in
   *      the documentation and/or other materials provided with the
   *      distribution.
   *
   *    * Neither the name of Florian Lanthaler nor the names of his
   *      contributors may be used to endorse or promote products derived
   *      from this software without specific prior written permission.
   *
   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
   * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
   * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
   * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
   * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   */

session_name("phpaga_test");

if (!isset($_SESSION["phpaga_test"]))
{
    $_SESSION["phpaga_test"] = 1;
    session_register("phpaga_test");
}

$_SESSION["phpaga_test"]++;

$phpaga_test = $_SESSION["phpaga_test"];

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <title>phpaga: system requirements test</title>
    <style type="text/css">
    <!--

    a:link, a:visited, a:active
{
color:#222;
}

body
{
    font-family: Verdana, sans-serif, Arial, Helvetica;
    font-size: 10pt;
    color: #000;
    background-color: #fff;
    margin: 0px 20px 0px 0px;
}

table
{
border: none;
    margin-top: 0;
    margin-bottom: 10px;
}

table caption
{
    margin-bottom: 0;
    padding-bottom: 0;
    font-size: 10pt;
    color: #444;
    background-color: #ccc;
    letter-spacing: 2px;
    border-top: solid #888 1px;
    white-space: nowrap;
    text-align: left;
    font-weight: normal;
}

table td
{
    padding: 2px;
    vertical-align: top;
}

table td.label
{
    text-align: right;
    background-color: #efefef;
    border-bottom: solid #ddd 1px;
    vertical-align: top;
    white-space: nowrap;
}

table td.data
{
    background-color: #f8f8f8;
    border-bottom: solid #eee 1px;
}

table td.subheader
{
    font-size: 10pt;
    color: #888;
    background-color: #ddd;
    letter-spacing: 2px;
    border-top: solid #888 1px;
    border-bottom: solid #888 1px;
    white-space: nowrap;
}

table td.footer
{
    font-family: Helvetica, sans-serif;
    font-size: 10pt;
    color: #888;
    background-color:#ccc;
    text-align:center;
    border-top: solid #888 1px;
    border-bottom: solid #888 1px;
}

table td.footer a
{
color: #888;
}

.yes
{
color: black;
}

.no
{
color: red;
}

-->
</style>
</head>
<body>

<table cellspacing="0" align="center">
    <caption> phpaga: system requirements test </caption>
    <?php

    $definitions = array("PHPAGA_BASEPATH",
                         "PHPAGA_DB_SYSTEM",
                         "PHPAGA_DB_HOST",
                         "PHPAGA_DB_NAME",
                         "PHPAGA_DB_LOGIN",
                         "PHPAGA_DB_PASSWD"
        );

$jpgraph_definitions = array("USE_CACHE",
                             "CACHE_DIR",
                             "READ_CACHE",
                             "CACHE_FILE_MOD",
                             "TTF_DIR",
                             "LANGUAGE_CYRILLIC",
                             "CYRILLIC_FROM_WINDOWS",
                             "CSIMCACHE_DIR",
                             "CSIMCACHE_HTTP_DIR",
                             "DEFAULT_GFORMAT",
                             "USE_TRUECOLOR",
                             "USE_IMAGE_ERROR_HANDLER",
                             "USE_APPROX_COLORS"
    );

function fulfilled($text = "", $bool)
{
    if ($bool)
        return("<span class=\"yes\">$text</span>");
    else
        return("<span class=\"no\">$text</span>");
}

function yesno($bool)
{
    if ($bool)
        return(fulfilled("Yes", true));
    else
        return(fulfilled("No", false));
}

function separator($text = "")
{
    print("  <tr><td class=\"subheader\" colspan=\"2\">$text</td></tr>\n");
}

function tablerow($label = "", $value = "")
{
    print ("  <tr><td class=\"label\"> $label </td><td class=\"data\"> $value </td></tr>\n");
}

function contains_illegal_whitespace($filename)
{

    $content = implode("", file($filename));

    return (($content[0] != "<")
            || (($content[strlen($content)-2] != ">")
                && ($content[strlen($content)-1] != ">") ));
}

/* ----------------------------------------------------------------- */

error_reporting(E_ALL);

$illegal_whitespace_message = "The file %s contains illegal whitespace or ".
    "other characters outside the PHP tags &lt;?php and ?&gt;. Please remove ".
    "all illegal characters outside these tags.";

$htdocs_config_filename = "./config.php";
$etc_config_filename = "";
$etc_config = false;

$etc_config_local_filename = "";
$etc_config_local = false;

$mysql = extension_loaded("mysql");
$pgsql = extension_loaded("pgsql");
$gd = extension_loaded("gd");
$gettext = extension_loaded("gettext");

$basepath = "";

$htdocs_config = (is_file($htdocs_config_filename) && is_readable($htdocs_config_filename));

if ($htdocs_config)
{

    $htdocs_config_content = implode('', file("./config.php"));

    if (ereg("[^\*]*(require|include).*[\"\'](.*)[\"\']", $htdocs_config_content, $matches))
    {
        $etc_config_filename = $matches[2];
        $etc_config = (is_file($etc_config_filename) && is_readable($etc_config_filename));

        $etc_config_local_filename = dirname($etc_config_filename)."/config.local.php";
        $etc_config_local = (is_file($etc_config_local_filename) && is_readable($etc_config_local_filename));
    }
}

/* ----------------------------------------------------------------- */

separator("Configuration files");

if (!$htdocs_config)
{
    tablerow($htdocs_config_filename." readable", fulfilled("No -> You need to create the file config.php in your htdocs/ ".
                                                            "directory (see INSTALL).", false));
}
else
{
    tablerow($htdocs_config_filename." readable", yesno($htdocs_config));

    if (contains_illegal_whitespace($htdocs_config_filename))
        tablerow("$htdocs_config_filename format",
                 fulfilled(sprintf($illegal_whitespace_message,
                                   $htdocs_config_filename), false));

    if ($etc_config)
    {
        tablerow("etc/config.php location", $etc_config_filename);

        if (contains_illegal_whitespace($etc_config_filename))
            tablerow("etc/config.php format",
                     fulfilled(sprintf($illegal_whitespace_message,
                                       $etc_config_filename), false));

    }

    tablerow("etc/config.php readable", yesno($etc_config));


    if (!$etc_config_local)
        tablerow($etc_config_local_filename." readable", fulfilled("No -> You need to create the file config.local.php in your etc/ ".
                                                                   "directory (see INSTALL).", false));
    else
    {
        tablerow("etc/config.local.php location", $etc_config_local_filename);
        if (contains_illegal_whitespace($etc_config_local_filename))
            tablerow("etc/config.local.php format",
                     fulfilled(sprintf($illegal_whitespace_message,
                                       $etc_config_local_filename), false));
        include_once($etc_config_local_filename);

        tablerow("etc/config.local.php readable", yesno($etc_config_local));




/* ----------------------------------------------------------------- */

        separator("phpaga settings");

        foreach ($definitions as $def)
        {
            if (defined($def))
            {
                if ($def == "PHPAGA_DB_PASSWD")
                {
                    if (strlen(constant($def)))
                        tablerow($def, fulfilled("[set]", true));
                    else
                        tablerow($def, "[empty]");
                }
                elseif (($def == "PHPAGA_BASEPATH")
                        && (!strlen(constant($def))
                            || !is_dir(constant($def))))

                    tablerow($def, fulfilled("Invalid base path: ".constant($def), false));
                else

                    tablerow($def, fulfilled(constant($def), true));
            }
            else
                tablerow($def, fulfilled("[not set]", false));
        }

        $tmp_tpl_c_dir = PHPAGA_BASEPATH."templates_c";
        if (!is_dir($tmp_tpl_c_dir))
            tablerow("directory for compiled templates", fulfilled("$tmp_tpl_c_dir does not exist", false));
        elseif (!is_writable($tmp_tpl_c_dir))
            tablerow("directory for compiled templates", fulfilled("$tmp_tpl_c_dir is not writable", false));
        else
            tablerow("directory for compiled templates", fulfilled("$tmp_tpl_c_dir exists and is writable", true));

        if (!defined("PHPAGA_PICTUREPATH"))
            define("PHPAGA_PICTUREPATH", PHPAGA_BASEPATH."pictures/");

        if (!is_dir(PHPAGA_PICTUREPATH))
            tablerow("upload directory for pictures", fulfilled(PHPAGA_PICTUREPATH." does not exist", false));
        elseif (!is_writable(PHPAGA_PICTUREPATH))
            tablerow("upload directory for pictures", fulfilled(PHPAGA_PICTUREPATH." is not writable", false));
        else
            tablerow("upload directory for pictures", fulfilled(PHPAGA_PICTUREPATH." exists and is writable", true));

        if (!defined("PHPAGA_FILEPATH"))
            define("PHPAGA_FILEPATH", PHPAGA_BASEPATH."files/");

        if (!is_dir(PHPAGA_FILEPATH))
            tablerow("upload directory for files", fulfilled(PHPAGA_FILEPATH." does not exist", false));
        elseif (!is_writable(PHPAGA_FILEPATH))
            tablerow("upload directory for files", fulfilled(PHPAGA_FILEPATH." is not writable", false));
        else
            tablerow("upload directory for files", fulfilled(PHPAGA_FILEPATH." exists and is writable", true));

        if (!defined("PHPAGA_FILES_PREVIEW") || PHPAGA_FILES_PREVIEW) // enabled by default
            tablerow("file thumbnails", fulfilled("enabled", true));
        else
            tablerow("file thumbnails", fulfilled("disabled", false));

        if (!defined("PHPAGA_BIN_CONVERT")) {
            if (!file_exists('/usr/bin/convert'))
                tablerow("file thumbnails creation tool", fulfilled("Full path to the executable is not defined - using default value /usr/bin/convert - file does not exist", false));
            else
                tablerow("file thumbnails creation tool", fulfilled("Full path to the executable is not defined - using default value /usr/bin/convert - file exists", true));
        }
        elseif (!file_exists(PHPAGA_BIN_CONVERT))
            tablerow("file thumbnails creation tool", fulfilled(PHPAGA_BIN_CONVERT." does not exist - you will not be able to see thumbnails for uploaded files", false));
        else
            tablerow("file thumbnails creation tool", fulfilled(PHPAGA_BIN_CONVERT." exists", true));


/* ----------------------------------------------------------------- */

        $mem = preg_match('/^(\d+)([a-zA-Z]+)/', trim(ini_get("memory_limit")), $memlimit);

        separator("PHP");

        tablerow("PHP OS", PHP_OS);
        tablerow("PHP Version", PHP_VERSION);
        tablerow("PHP uname", php_uname());
        tablerow("PHP SAPI name", php_sapi_name());
        tablerow("Server", $_SERVER["SERVER_SOFTWARE"]);
        tablerow("MySQL enabled", yesno($mysql));
        tablerow("PostgreSQL enabled", yesno($pgsql));
        tablerow("GD enabled", yesno($gd));
        tablerow("gettext enabled", yesno($gettext));
        tablerow("include_path", ini_get("include_path"));
        tablerow("session test counter", $phpaga_test);
        tablerow("magic_quotes_gpc", get_magic_quotes_gpc() ? "On - phpaga does not need magic_quotes_gpc to be on and will strip slashes from \$_REQUEST, \$_POST and \$_GET" : "Off (good)");
        tablerow("register_globals", ini_get("register_globals") ? "On - phpaga does not need register_globals to be on, but other installed applications on your server might." : "Off (good)");

        if (isset($memlimit[1]) && ($memlimit[1] > 12))
            tablerow("memory_limit", ini_get("memory_limit"));
        else
        {
            $str = sprintf("%s - this might not be sufficient; if you encounter problems like blank pages, try to increase the value of memory_limit in php.ini", ini_get("memory_limit"));
            tablerow("memory_limit", fulfilled($str, false));
        }
/* ----------------------------------------------------------------- */

        separator("Languages and locales");

        $langfile = dirname($etc_config_filename)."/languages.php";

        if (!is_file($langfile)
            || !is_readable($langfile))
        {
            tablerow($langfile, fulfilled("Unable to find language file (this is fine for phpaga 0.2 and previous verisons)", false));
        }
        else
        {
            include_once($langfile);

            if (!isset($phpaga_languages) || (count($phpaga_languages) == 0))
                tablerow("Languages", fulfilled("NO AVAILABLE LANGUAGES", false));
            else
            {
                foreach($phpaga_languages aS $langid => $langarr)
                {

                    $langname = setlocale(LC_ALL, $langarr);

                    if (strstr(PHP_OS, 'WIN'))
                    {
                        putenv("LANG=".$langname);
                        putenv("LANGUAGE=".$langname);
                    }

                    $l = !($langname === false);

                    if ($l)
                        tablerow($langname, yesno($l));
                    else
                        tablerow($langid, fulfilled("NO - you need to install the proper locale if you want to offer this language to your users", false));
                }
            }
        }

/* ----------------------------------------------------------------- */

        $pear_modules = array("DB" => array("minversion" => "1.7.6",
                                            "errmsg" => null),

                              "Mail" => array("minversion" => "1.1.10",
                                              "errmsg" => null),

                              "Log" => array("minversion" => "1.9.7",
                                             "errmsg" => null),

                              "HTTP_Upload" => array("minversion" => "0.9.1",
                                                     "errmsg" => "This package is optional. File uploads will not be possible without it."),

                              "HTTP_Download" => array("minversion" => "1.1.1",
                                                       "errmsg" => "This package is optional and only required if HTTP_Upload is installed."),

                              "HTTP_Header" => array("minversion" => "1.2.0",
                                                     "errmsg" => "This package is optional and only required if HTTP_Upload is installed."),


                              "Image_GraphViz" => array("minversion" => "1.2.1",
                                                        "errmsg" => "This package is optional. Relationship graphs will not be possible without it.")

            );

        $peardb = false;
        require_once('PEAR/Registry.php');
        $reg = new PEAR_Registry();

        separator("PEAR");
        tablerow("PEAR", yesno($reg != null));

        if ($reg != null)
        {

            foreach($pear_modules as $pname => $param)
            {
                $pinfo = $reg->packageInfo($pname);
                if (empty($pinfo))
                {
                    $errmsg = "Missing";
                    if (strlen($param["errmsg"]))
                        $errmsg .= " - ".$param["errmsg"];

                    tablerow($pname, fulfilled($errmsg, false));
                }
                else
                {
                    if ($pname == "DB")
                        $peardb = true;

                    if (strlen($param["minversion"]))
                        $pname .= " &gt;= ".$param["minversion"];

                    if (is_array($pinfo["version"]) && isset($pinfo["version"]["release"]))
                        $pinfo["version"] = $pinfo["version"]["release"];

                    $versionok = (version_compare($param["minversion"], $pinfo["version"]) <= 0);

                    if ($versionok)
                        tablerow($pname, fulfilled("Yes - ".$pinfo["version"], $versionok));
                    else
                        tablerow($pname, fulfilled("No - ".$pinfo["version"]." is installed - upgrade required", $versionok));
                }
            }
        }

/* ----------------------------------------------------------------- */

        separator("Database connection");


        if (!$peardb)
            tablerow("Database abstraction", fulfilled("PEAR DB is not installed", false));
        else
        {

            require_once("DB.php");

            $db = DB::connect(PHPAGA_DB_SYSTEM . "://" .
                              PHPAGA_DB_LOGIN . ":" .
                              PHPAGA_DB_PASSWD . "@" .
                              PHPAGA_DB_HOST . "/" .
                              PHPAGA_DB_NAME);

            if (DB::isError($db))
                tablerow("Database connection", fulfilled("Error: ".$db->getDebugInfo(), false));
            else
            {
                tablerow("Database connection", fulfilled("OK", true));

                $result = $db->query ("select version();");
                if ((DB::isError($result)))
                {
                    tablerow("Server version", "unknown");
                }
                else
                {
                    $qrow = $result->fetchRow();
                    $result->free();

                    tablerow("Server version", $qrow[0]);
                }
            }
        }

/* ----------------------------------------------------------------- */

        separator("JpGraph");

        $jpgraph_wrapper = constant("PHPAGA_BASEPATH")."lib/jpgraph_wrapper.php";

        if (!defined("JPGRAPH_DIR"))
            define("JPGRAPH_DIR", constant("PHPAGA_BASEPATH")."ext/jpgraph/src/");

        $jpgraph_file = (is_file(JPGRAPH_DIR."jpgraph.php")
                         && is_readable(JPGRAPH_DIR."jpgraph.php"));

        if ($jpgraph_file)
            include_once($jpgraph_wrapper);

        tablerow("Path to wrapper", $jpgraph_wrapper);
        tablerow("JPGRAPH_DIR", JPGRAPH_DIR);
        tablerow(JPGRAPH_DIR."jpgraph.php readable", yesno($jpgraph_file));

        if ($jpgraph_file)
        {
            foreach ($jpgraph_definitions as $def)
            {
                if (!defined($def))
                    tablerow($def, fulfilled("[not set]", false));
                else
                {
                    if (!strlen(constant($def)) && !is_bool(constant($def)))
                        tablerow($def, "[empty]");
                    elseif (is_bool(constant($def)))
                        if (constant($def))
                            tablerow($def, "Yes");
                        else
                            tablerow($def, "No");
                    else
                    {


                        if ($def == "CACHE_DIR")
                        {

                            if (USE_CACHE == true)
                                tablerow($def, fulfilled(constant($def), true));

                            if ((USE_CACHE == true)
                                && (!is_dir(constant($def))
                                    || !is_writable(constant($def))))
                                tablerow($def." writable",
                                         fulfilled("No -> The directory ".
                                                   CACHE_DIR." does not exist or ".
                                                   "it is not writable.",
                                                   false));
                        }
                        elseif ($def == "TTF_DIR")
                        {
                            tablerow($def, fulfilled(constant($def), true));

                            if (!is_dir(constant($def))
                                && !is_readable(constant($def)))

                                tablerow($def." readable",
                                         "The directory ".TTF_DIR.
                                         "does not exist or ".
                                         "is not readable. phpaga will work, ".
                                         "but you won't be able to use ".
                                         "TrueType fonts in the graphs.");
                            else
                                tablerow($def." readable", yesno(true));

                        }
                        else
                            tablerow($def, fulfilled(constant($def), true));

                    }
                }
            }
        }
    }
}
?>
<tr><td class="footer" colspan="2"><a href="http://phpaga.net/">phpaga.net</a></td></tr>
    </table>

    </body>
    </html>
