<?php

class upgrade_2016 {
	
	var $usedFiles = array( 'mainfile.php' );
	
	function isApplied() {
		return ( /*$this->check_file_patch() &&*/ $this->check_auth_db() );
	}

	function apply() {	
		return $this->apply_auth_db();
	}

	function check_file_patch() {
		$path = XOOPS_ROOT_PATH . '/class/auth';
		$lines = file( "$path/auth_provisionning.php");
		foreach ( $lines as $line ) {
			if ( strpos( $line, "ldap_provisionning_upd" ) !== false ) {
				// Patch found: do not apply again
				return true;
			}
		}
		return false;
	}


	function check_auth_db() {
		$db = $GLOBALS['xoopsDB'];
		$value = getDbValue( $db, 'config', 'conf_id',
			"`conf_name` = 'ldap_field_mapping' AND `conf_catid` = " . XOOPS_CONF_AUTH
		);
		$value1 = getDbValue( $db, 'config', 'conf_id',
			"`conf_name` = 'ldap_provisionning_upd' AND `conf_catid` = " . XOOPS_CONF_AUTH
		);		
		return (bool)($value && $value1);
	}
	
	function query( $sql ) {
		$db = $GLOBALS['xoopsDB'];
		if ( ! ( $ret = $db->queryF( $sql ) ) ) {
			echo $db->error();
		}
	}		

	function apply_auth_db() {
		$db = $GLOBALS['xoopsDB'];
		
		// Insert config values
		$table = $db->prefix( 'config' );
		$data = array(
	   		'ldap_field_mapping'	=> "'_MD_AM_LDAP_FIELD_MAPPING_ATTR', 'email=mail|name=displayname', '_MD_AM_LDAP_FIELD_MAPPING_DESC', 'textarea', 'text', 18",
	   		'ldap_provisionning_upd'=> "'_MD_AM_LDAP_PROVIS_UPD', '1', '_MD_AM_LDAP_PROVIS_UPD_DESC', 'yesno', 'int', 19",
		);
		foreach ( $data as $name => $values ) {
			if ( !getDbValue( $db, 'config', 'conf_id', "`conf_modid`=0 AND `conf_catid`=7 AND `conf_name`='$name'" ) ) {
				$this->query(
					"INSERT INTO `$table` (conf_modid,conf_catid,conf_name,conf_title,conf_value,conf_desc,conf_formtype,conf_valuetype,conf_order) " .
					"VALUES ( 0,7,'$name',$values)"
				);
			}
		}
		return true;
	}
}

$upg = new upgrade_2016();
return $upg;

?>