Click here to Skip to main content
12,349,884 members (23,635 online)
Click here to Skip to main content

Stats

42.6K views
1.9K downloads
41 bookmarked
Posted

Internet Explorer AdBlock

, 17 Jan 2008 GPL3
Internet Explorer AdBlock Add-on
IE AdBlockPS
IE AdBlockps.def
IE AdBlock
AdBlockBand.rgs
AdBlockBHO.rgs
bin
XListCtrlSSDU.lib
XListCtrlSSRU.lib
IE AdBlock.def
IE AdBlock.rgs
res
bmpToolbar.bmp
checkboxes.bmp
icoSettings.ico
XListCtrl
checkboxes.bmp
//*********************************************************************
// INCLUDES
//*********************************************************************

#include "stdafx.h"
#include "AdBlockBHO.h"
#include "Urlmon.h"			// UrlDownloadToFile function
#include "AdBlock.h"

//*********************************************************************
// MESSAGE MAP
//*********************************************************************

//*********************************************************************
// CONSTRUCTOR & DESTRUCTOR
//*********************************************************************

CAdBlockBHO::CAdBlockBHO()
{
}

//*********************************************************************
// PUBLIC FUNCTIONS
//*********************************************************************

HRESULT CAdBlockBHO::FinalConstruct()
{
	return S_OK;
}

//=====================================================================

void CAdBlockBHO::FinalRelease()
{
}

//=====================================================================

STDMETHODIMP CAdBlockBHO::SetSite(IUnknown * pUnkSite)
{
	// Check if we are subscribing or unsubscribing
    if (pUnkSite != NULL)
    {
		// Initialize
		if (Initialize(pUnkSite) != S_OK)
		{
			return E_FAIL;
		}
    }
    else
    {
		// DeInitialize
		DeInitialize();
    }

    // Return the base class implementation
    return IObjectWithSiteImpl<CAdBlockBHO>::SetSite(pUnkSite);
}

//=====================================================================

void STDMETHODCALLTYPE CAdBlockBHO::OnDocumentComplete(IDispatch *pDisp, VARIANT *pvarURL)
{
	// Declare variables
    HRESULT hr = S_OK;

    // Query for the IWebBrowser2 interface
    CComQIPtr<IWebBrowser2> spTempWebBrowser = pDisp;

    // Is this event associated with the top-level browser?
    if (spTempWebBrowser && m_spWebBrowser &&
        m_spWebBrowser.IsEqualObject(spTempWebBrowser))
    {
		// Is adblock enabled?
		if (m_pSettings->GetEnabled())
		{
			// Get the current document object from browser...
			CComPtr<IDispatch> spHTMLDocumentDispatch;
			hr = m_spWebBrowser->get_Document(&spHTMLDocumentDispatch);
			if (SUCCEEDED(hr))
			{
				// ...and query for an HTML document
				CComQIPtr<IHTMLDocument2> spHTMLDocument = spHTMLDocumentDispatch;
				if (spHTMLDocument != NULL)
				{
					// Yes, remove the advertisement
					RemoveAdvertisement(spHTMLDocument);

					// Increase timer
					m_iSpeedUpCacheTimer++;

					// Check if we should increase cache now
					if (m_iSpeedUpCacheTimer >= 10)
					{
						// Speed up cache
						SpeedUpCache();

						// Set timer to 0
						m_iSpeedUpCacheTimer = 0;
					}
				}
			}
		}
    }
}

//=====================================================================

void STDMETHODCALLTYPE CAdBlockBHO::OnBeforeNavigate2(IDispatch *pDisp, VARIANT *pvarURL,
										 short flags, VARIANT *pvarTarget, 
										 VARIANT *pvarPost, VARIANT *pvarHeaders,
										 VARIANT *pvarCancel)
{
	// Check if adblock is enabled
	if (m_pSettings->GetEnabled())
	{
		// Check if the site is listed on whitelist
		if (!m_pListData->GetWhiteList()->Matches(CString(pvarURL->bstrVal), _T("")))
		{
			// Check if the site is listed on blacklist
			if (m_pListData->GetBlackList()->Matches(CString(pvarURL->bstrVal), _T("")))
			{
				// This element or URL should be blocked, cancel the navigation for this element
				pvarCancel->boolVal = TRUE;
			}
		}
	}
}

//*********************************************************************
// PRIVATE FUNCTIONS
//*********************************************************************

HRESULT CAdBlockBHO::Initialize(IUnknown * pUnkSite)
{
	// Declare variables
	HRESULT hr = S_OK;

    // Cache the pointer to IWebBrowser2
    hr = pUnkSite->QueryInterface(IID_IWebBrowser2, (void **)&m_spWebBrowser);
    if (FAILED(hr))
    {
		return E_FAIL;
	}

    // Register to sink events from DWebBrowserEvents2
    hr = DispEventAdvise(m_spWebBrowser);
    if (SUCCEEDED(hr))
    {
        m_fAdvised = TRUE;
    }

	// Initialize singleton classes
	m_pSettings = CSettings::Instance();
	m_pPath = CPath::Instance();
	m_pListData = CListData::Instance();

	// Initialize speed up cache timer
	m_iSpeedUpCacheTimer = 0;

	// Is this first instance?
	if (CAppInfo::Instance()->GetInstanceCount() == 0)
	{
		// Create special folders
		m_pPath->Init();
		m_pPath->CreateAdBlockFolders();

	// Read settings
#ifdef _DEBUG
		// Strip "debug" folder too
		CString sSettingsPath = m_pPath->ExtractFilePath(m_pPath->GetPathAdBlockLocation());
		sSettingsPath.Delete(sSettingsPath.GetLength() - lstrlen(_T("debug\\")), lstrlen(_T("debug\\")));
		m_pSettings->LoadSettings(sSettingsPath + _T("settings.ini"));
#else
		// Don't strip debug folder
		m_pSettings->LoadSettings(m_pPath->ExtractFilePath(m_pPath->GetPathAdBlockLocation()) + _T("settings.ini"));
#endif

		// Should we load list?
		if (!m_pListData->ListDataLoaded())
		{
			// Set lists options
			m_pListData->GetBlackList()->SetKeepSorted(true);
			m_pListData->GetWhiteList()->SetKeepSorted(true);

#ifdef _DEBUG
			// Strip "debug" folder too
			CString sAdListPath = m_pPath->ExtractFilePath(m_pPath->GetPathAdBlockLocation());
			sAdListPath.Delete(sAdListPath.GetLength() - lstrlen(_T("debug\\")), lstrlen(_T("debug\\")));
			if (!m_pListData->LoadListData(sAdListPath + _T("adlist.xml")))
			{
				SetStatus(CLanguage::Instance()->GetString(IDS_ERROR_UNABLELOADDATA));
			}
#else
			// Don't strip debug folder
			if (!m_pListData->LoadListData(m_pPath->ExtractFilePath(m_pPath->GetPathAdBlockLocation()) + _T("adlist.xml")))
			{
				SetStatus(CLanguage::Instance()->GetString(IDS_ERROR_UNABLELOADDATA));
			}
#endif
		}

		// Sync newest lists
		SyncNewestLists();
	}

	// Increase instance
	CAppInfo::Instance()->IncreaseInstanceCount();
	
	// Succeeded
	return S_OK;
}

//=====================================================================

void CAdBlockBHO::DeInitialize()
{
    // Unregister event sink
    if (m_fAdvised)
    {
        DispEventUnadvise(m_spWebBrowser);
        m_fAdvised = FALSE;
    }

    // Release cached pointers and other resources here
    m_spWebBrowser.Release();

	// Decrease instance
	CAppInfo::Instance()->DecreaseInstanceCount();

	// Was this the last one?
	if (CAppInfo::Instance()->GetInstanceCount() <= 0)
	{
		// Store list data
		CListData::Instance()->StoreListData();

		// Clean up list data
		CListData::Instance()->CleanUp();
	}
}	

//=====================================================================

void CAdBlockBHO::SyncNewestLists()
{
	// Declare variables
	bool bSync = false;
	CTime tmFile, tmCurrent;
	CString sDestination = _T(""), sURL = _T("");
	BlackList oBlackList;

	// Loop all selected lists
	for (int i = 0; i < BLACKLIST_COUNT; i++)
	{
		// DutchBlock
		if (i == BLACKLIST_DUTCHBLOCK.ArrayIndex)
		{
			oBlackList = BLACKLIST_DUTCHBLOCK;
		}

		// FanBoy
		if (i == BLACKLIST_FANBOY.ArrayIndex)
		{
			oBlackList = BLACKLIST_FANBOY;
		}

		// Set up file locations
		sDestination.Format(_T("%s%s"), m_pPath->GetPathAdBlockTemp(), oBlackList.TempFile);
		sURL = oBlackList.URL;

		// Should we sync this blacklist?
		if (m_pSettings->GetBlackList(oBlackList.ArrayIndex))
		{
			// Check if file exists
			if (!PathFileExists(sDestination))
			{
				// Sync
				bSync = true;
			}
			else
			{
				// Check if we have valid items in our blacklist
				if (m_pListData->GetItemCount() == 0)
				{
					// Sync
					bSync = true;
				}
				else
				{
					// Get file date/time
					tmFile = m_pPath->GetFileDateTime(sDestination);

					// Get current date/time
					tmCurrent = CTime::GetCurrentTime();

					// Calculate difference	
					CTimeSpan tsDifference = tmCurrent - tmFile;

					// How many days have passed since last download?
					if (tsDifference.GetDays() > m_pSettings->GetBlackListSyncRestDays())
					{
						// Sync
						bSync = true;
					}
					else
					{
						// Don't sync
						bSync = false;
					}
				}
			}

			// Should we sync the file?
			if (bSync)
			{
				// Sync the lists
				m_pListData->Sync(oBlackList);
			}
		}
	}
}

//=====================================================================

void CAdBlockBHO::SpeedUpCache()
{
	// Get list data
	CListData * pListData = CListData::Instance();

	// Speed up cache by sorting
	pListData->GetBlackList()->SortCache();
	pListData->GetWhiteList()->SortCache();
}

//=====================================================================

void CAdBlockBHO::RemoveAdvertisement(IHTMLDocument2 * pDocument)
{
	// Declare variables
	CAdBlock oAdBlock;

	// Block advertisements
	oAdBlock.BlockAdvertisements(pDocument);
}

//=====================================================================

void CAdBlockBHO::SetStatus(CString sStatus)
{
	// Declare variables
	HRESULT hr = S_OK;
	bool bShowMessageBox = false;

	// Check if we have a valid webbrowser
	if (m_spWebBrowser)
	{
		hr = m_spWebBrowser->put_StatusText(_bstr_t(sStatus));
		if (FAILED(hr))
		{
			// Show message box instead
			bShowMessageBox = true;
		}
	}
	else
	{
		// Show message box instead
		bShowMessageBox = true;
	}

	// Should we show message box?
	if (bShowMessageBox)
	{
		// No, use messagebox instead
		MessageBox(NULL, sStatus, _T("AdBlock information"), MB_ICONINFORMATION);
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)

Share

About the Author

Geert van Horrik
Software Developer CatenaLogic
Netherlands Netherlands
I am Geert van Horrik, and I have studied Computer Science in the Netherlands.

I love to write software using .NET (especially the combination of WPF and C#). I am also the lead developer of Catel, an open-source application development framework for WPF, Silverlight, WP7 and WinRT with the focus on MVVM.

I have my own company since January 1st 2007, called CatenaLogic. This company develops commercial and non-commercial software.

To download (or buy) applications I have written, visit my website: http://www.catenalogic.com

You may also be interested in...

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160621.1 | Last Updated 17 Jan 2008
Article Copyright 2008 by Geert van Horrik
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid