/**
 * Hook a ejecutar antes del paso 5 de la instalación
 * Extrae cuales son las fuentes de datos principales que podría utilizarse
 *
 * @param array &$data  Los datos a utilizar por las plantillas de tipo stepn
 */
function idpinstaller_hook_step5(&$data)
{
    $data['datasources'] = getDataSources();
    $require_mods = array("saml", "idpinstaller", "modinfo", "ldap", "sqlauth", "core", "portal", "sir2skin");
    //Modulos obligatorios
    $ssphpobj = $data['ssphpobj'];
    $modules = SimpleSAML_Module::getModules();
    sort($modules);
    $perms_ko = array();
    $modules_ko = array();
    foreach ($modules as $m) {
        $f = realpath(__DIR__ . '/../../' . $m);
        if (!file_exists($f . '/default-disable') && !file_exists($f . '/default-enable') && in_array($m, $require_mods)) {
            $modules_ko[] = $f;
        } elseif (file_exists($f . '/default-disable') && !is_writable($f . '/default-disable') || file_exists($f . '/default-enable') && !is_writable($f . '/default-enable')) {
            $perms_ko[] = $f;
        } else {
            if (in_array($m, $require_mods)) {
                //PARA LOS QUE SI QUEREMOS ACTIVAR
                if (file_exists($f . '/default-disable')) {
                    @unlink($f . '/default-disable');
                    @touch($f . '/default-enable');
                    if (!file_exists($f . '/default-enable')) {
                        $data['errors'][] = $ssphpobj->t('{idpinstaller:idpinstaller:step4_error}');
                    }
                }
            } else {
                //PARA LOS QUE QUEREMOS DESACTIVAR
                if (file_exists($f . '/default-enable')) {
                    @unlink($f . '/default-enable');
                    @touch($f . '/default-disable');
                    if (!file_exists($f . '/default-disable')) {
                        $data['errors'][] = $ssphpobj->t('{idpinstaller:idpinstaller:step4_error}');
                    }
                }
            }
        }
    }
    if (count($modules_ko) > 0) {
        $data['errors'][] = $ssphpobj->t('{idpinstaller:idpinstaller:step4_error}');
    } elseif (count($perms_ko) > 0) {
        if (function_exists('posix_getgrnam')) {
            $aux = "<br/>" . $ssphpobj->t('{idpinstaller:idpinstaller:step4_perms_ko}');
            $filename = $perms_ko[0];
            $file_owner = posix_getpwuid(fileowner($filename));
            $group = posix_getgrgid(posix_getgid());
            $recursive = is_dir($filename) ? "-R" : "";
            $aux .= "<pre>&gt; chown {$recursive} " . $file_owner['name'] . ":" . $group['name'] . " {$filename}\n&gt; chmod {$recursive} g+w " . $filename . "</pre>";
        }
        $data['errors'][] = $aux;
        $data['errors'][] = $ssphpobj->t("{idpinstaller:idpinstaller:step1_remember_change_perms}");
    }
    if (count($data['errors']) == 0) {
        $data['info'][] = $ssphpobj->t('{idpinstaller:idpinstaller:step4_all_ok}');
    }
    /*else {
          $data['errors'][] = $ssphpobj->t('{idpinstaller:idpinstaller:step4_error}');
      }*/
    return true;
}
/**
 * Hook a ejecutar antes del paso 6 de la instalación
 * Comprueba los datos de conexión de la fuente de datos principal
 *
 * @param array &$data  Los datos a utilizar por las plantillas de tipo stepn
 */
function idpinstaller_hook_step6(&$data)
{
    $data['datasources'] = getDataSources();
    if (isset($_REQUEST['data_source_type'])) {
        $ds_type = $_REQUEST['data_source_type'];
        if (strcmp($ds_type, "ldap") == 0 && ($data['datasources'] == "all" || $data['datasources'] == "ldap")) {
            if (array_key_exists('ldap_hostname', $_REQUEST) && !empty($_REQUEST['ldap_hostname']) && array_key_exists('ldap_port', $_REQUEST) && !empty($_REQUEST['ldap_port']) && array_key_exists('ldap_enable_tls', $_REQUEST) && array_key_exists('ldap_referral', $_REQUEST)) {
                $res = ldap_connect($_REQUEST['ldap_hostname'], $_REQUEST['ldap_port']);
                ldap_set_option($res, LDAP_OPT_PROTOCOL_VERSION, 3);
                if (!empty($_REQUEST['ldap_anonymous_bind']) && $_REQUEST['ldap_anonymous_bind'] != '0') {
                    $res = @ldap_bind($res);
                    //anonymous bind
                } else {
                    $res = @ldap_bind($res, $_REQUEST['ldap_binddn'], $_REQUEST['ldap_bindpassword']);
                    //non-anonymous bind
                }
                if (!$res) {
                    $data['errors'][] = $data['ssphpobj']->t('{idpinstaller:idpinstaller:step5_datasource_error}');
                    $data['datasource_selected'] = 'ldap';
                } else {
                    $filename = __DIR__ . '/../../../config/authsources.php';
                    include $filename;
                    $config['ldap_datasource'] = array('ldap:LDAP', 'hostname' => $_REQUEST['ldap_hostname'] . ":" . $_REQUEST['ldap_port'], 'enable_tls' => $_REQUEST['ldap_enable_tls'] == 0 ? TRUE : FALSE, 'referrals' => $_REQUEST['ldap_referral'] == 0 ? TRUE : FALSE, 'timeout' => 30, 'debug' => FALSE, 'attributes' => NULL, 'dnpattern' => "'uid=%username%," . $_REQUEST['ldap_binddn'] . "'", 'ldap.password' => $_REQUEST['ldap_bindpassword'], 'search.enable' => FALSE, 'search.base' => '', 'search.attributes' => array(), 'search.username' => NULL, 'search.password' => NULL, 'priv.read' => FALSE, 'priv.username' => NULL, 'priv.password' => NULL, 'authority' => "urn:mace:" . $_SERVER['HTTP_HOST']);
                    if (array_key_exists('sql_datasource', $config)) {
                        unset($config['sql_datasource']);
                    }
                    $res2 = @file_put_contents($filename, '<?php  $config = ' . var_export($config, 1) . "; ?>");
                    if (!$res2) {
                        $data['errors'][] = $data['ssphpobj']->t('{idpinstaller:idpinstaller:step2_contact_save_error}');
                        $data['errors'][] = $data['ssphpobj']->t('{idpinstaller:idpinstaller:step2_contact_save_error2}') . " <i>" . realpath($filename) . "</i>";
                        $data['datasource_selected'] = 'ldap';
                    }
                }
                return true;
            }
        } else {
            if (strcmp($ds_type, "pdo") == 0 && ($data['datasources'] == "all" || $data['datasources'] == "pdo")) {
                if (array_key_exists('pdo_dsn', $_REQUEST) && !empty($_REQUEST['pdo_dsn'])) {
                    $dsn = $_REQUEST['pdo_dsn'];
                    $username = isset($_REQUEST['pdo_username']) ? $_REQUEST['pdo_username'] : "";
                    $password = isset($_REQUEST['pdo_password']) ? $_REQUEST['pdo_password'] : "";
                    try {
                        $res = new PDO($dsn, $username, $password);
                    } catch (PDOException $e) {
                        $res = false;
                    }
                    if ($res === false) {
                        $data['errors'][] = $data['ssphpobj']->t('{idpinstaller:idpinstaller:step5_datasource_error}');
                        $data['datasource_selected'] = 'pdo';
                    } else {
                        $filename = __DIR__ . '/../../../config/authsources.php';
                        include $filename;
                        $config['sql_datasource'] = array('sqlauth:SQL', 'dsn' => $dsn, 'username' => $username, 'password' => $password, 'query' => '');
                        if (array_key_exists('ldap_datasource', $config)) {
                            unset($config['ldap_datasource']);
                        }
                        $res2 = @file_put_contents($filename, '<?php  $config = ' . var_export($config, 1) . "; ?>");
                        if (!$res2) {
                            $data['errors'][] = $data['ssphpobj']->t('{idpinstaller:idpinstaller:step2_contact_save_error}');
                            $data['errors'][] = $data['ssphpobj']->t('{idpinstaller:idpinstaller:step2_contact_save_error2}') . " <i>" . realpath($filename) . "</i>";
                            $data['datasource_selected'] = 'pdo';
                        }
                    }
                    return true;
                }
            }
        }
    }
    $data['errors'][] = $data['ssphpobj']->t('{idpinstaller:idpinstaller:step5_datasource_request_error}');
    return true;
}