<?php
if (empty($module)) {
	$module_handler =& xoops_gethandler('module');
	$module = $module_handler->getByDirname($mydirname);
}

eval( ' function xoops_module_uninstall_'.$mydirname.'( $module ) { return links_onuninstall_base( $module , "'.$mydirname.'" ) ; } ' ) ;


if( ! function_exists( 'links_onuninstall_base' ) ) {

	function links_onuninstall_base( $module , $mydirname )
	{
		// transations on module uninstall

		global $ret; // TODO :-D

		if( ! is_array( $ret ) ) 
			$ret = array() ;

		$db = icms_db_Factory::instance() ;
		$mid = $module->getVar('mid') ;

		// TABLES (loading mysql.sql)
		$sql_file_path = dirname(__FILE__) .'/sql/mysql.sql' ;
		$prefix_mod = $db->prefix() . '_' . $mydirname ;
		if( file_exists( $sql_file_path ) ) {
			$ret[] = "SQL file found at <strong>".htmlspecialchars($sql_file_path)."</strong>.<br  /> Deleting tables...<br />";
			$sql_lines = file( $sql_file_path ) ;
			foreach( $sql_lines as $sql_line ) {
				if( preg_match( '/^CREATE TABLE \`?([a-zA-Z0-9_-]+)\`? /i' , $sql_line , $regs ) ) {
					$sql = 'DROP TABLE '. $prefix_mod.'_'.$regs[1];
					if (!$db->query($sql)) {
						$ret[] = '<span style="color:#ff0000;">ERROR: Could not drop table <strong>'.htmlspecialchars($prefix_mod.'_'.$regs[1]).'</strong>.</span><br />';
					} else {
						$ret[] = 'Table <strong>'.htmlspecialchars($prefix_mod.'_'.$regs[1]).'</strong> dropped.<br />';
					}
				}
			}
		}

		// DELETE capture images
		unlink_capture_images($mydirname);

		return true ;
	}

function links_message_append_onuninstall( &$controller , &$eventArgs )
{
	if( is_array( @$GLOBALS['ret'] ) ) {
		foreach( $GLOBALS['ret'] as $message ) {
			$controller->mLog->add( $message ) ;
		}
	}
}

	function unlink_capture_images($mydirname)
	{
		global $ret;

		$cache_dir = XOOPS_ROOT_PATH .'/uploads/' . $mydirname . '_capture_cache';

		if (is_dir($cache_dir)) {
			$count = 1;
			$dir = dir($cache_dir);
			$temp_ret = '';
			while(($fileName = $dir->read()) !== FALSE) {
				if ($fileName == '.' || $fileName == '..') continue;
				if ($count == 1) $temp_ret = '[DELETED FILES] ';
				$imagePath = $dir->path . '/' . $fileName;
				if (@unlink($imagePath)) {
					$temp_ret .= htmlspecialchars($fileName, ENT_QUOTES) . ' ';
				}
				$count++;
			}
			if ($count > 1) $temp_ret .= '<br />';
			$ret[] = $temp_ret;
			if (@rmdir($cache_dir)) {
				$ret[] = '[DELETED DIR] '. $cache_dir;
			}
		}
	}
}

