<?php defined('SYSPATH') or die('No direct access allowed.');

/**
 * Delete old data from the TASK_LOG
 *
 * @package    Task
 * @category   Tasks
 * @author     Deon George
 * @copyright  (c) 2009-2013 Open Source Billing
 * @license    http://dev.osbill.net/license.html
 */
class Task_Task_Clean extends Minion_Task {
	// @todo This needs to be more dynamic, without hard coding task_ids or messages.
	protected function _execute(array $params) {
		$tl = ORM::factory('Task_Log');
		$delay = 86400*2;

		foreach ($tl->find_all() as $to) {
			// Delete Task already running messages.
			if (preg_match('/^Task\ [0-9]+\ is already running$/',$to->message) AND $to->date_orig < time()-$delay) {
				$to->delete();
				continue;
			}

			// Delete Empty Invoices Sent
			if (preg_match('/^Invoices Sent:\s+$/',$to->message) AND $to->date_orig < time()-$delay) {
				$to->delete();
				continue;
			}

			// Delete Overdue Notes Sent
			if (preg_match('/^OverDue Notice #[0-9] Reminders Sent:\s+$/',$to->message) AND $to->date_orig < time()-$delay) {
				$to->delete();
				continue;
			}

			// Over Notes Sent
			if (preg_match('/^(Overdue|Due) Reminders Sent:\s+$/',$to->message) AND $to->date_orig < time()-$delay) {
				$to->delete();
				continue;
			}

			// Services Invoiced
			if (preg_match('/^Services Invoiced:\s+$/',$to->message) AND $to->date_orig < time()-$delay) {
				$to->delete();
				continue;
			}

			// Alerts Sent
			if (preg_match('/^0 alerts sent \(\)$/',$to->message) AND $to->date_orig < time()-$delay) {
				$to->delete();
				continue;
			}

			if (in_array($to->task_id,array(4,13)) AND $to->date_orig < time()-$delay) {
				$to->delete();
				continue;
			}

			if (in_array($to->task_id,array(3)) AND $to->date_orig < time()-86400*60) {
				$to->delete();
				continue;
			}

			// Errors
			if ((preg_match('/ErrorException\s+/',$to->message)
				OR preg_match('/^The requested URL\s+/',$to->message)
				OR preg_match('/^Unable to find a route to match the URI:/',$to->message)
				OR preg_match('/View_Exception\s+/',$to->message)
				OR preg_match('/Kohana_Exception\s+/',$to->message))

				AND $to->date_orig < time()-$delay) {

				$to->delete();
				continue;
			}
		}
	}
}
?>
