<?php

/**
*
*/
function pp_kw2011_portal_init() {
	// add jquery ui
		jquery_ui_add('ui.core');

	// get path
		$module_path = drupal_get_path('module', 'jquery_ui');

	// add theme css
		drupal_add_css($module_path.'/jquery.ui/themes/ui-darkness/ui.theme.css');

	// get path
		$module_path = drupal_get_path('module', 'pp_kw2011_portal');

	// add css
		drupal_add_css($module_path.'/ui.selectmenu.css');
		drupal_add_css($module_path.'/pp_kw2011_portal.css');

	// add js
		drupal_add_js($module_path.'/ui.selectmenu.js');
		drupal_add_js($module_path.'/jquery.cookie.js');
		drupal_add_js($module_path.'/pp_kw2011_portal.js');

	// open the portal
		drupal_add_js("$(document).ready(function() { showPortal('/".$module_path."', false); });", 'inline');
}


/**
* Menu for this module
* @return array An array with this module's settings.
*/
function pp_kw2011_portal_menu() {
	// items
		$items = array();

	// api
		$items['api/kw2011_portal'] = array(
			'title' => 'API',
			'description' => 'KW2011 Portal API',
			'page callback' => 'pp_kw2011_portal_api',
			'page arguments' => array('mode'),
			'access arguments' => array('access content'),
			'type' => MENU_CALLBACK,
		);

	// return
		return $items;
}


/**
*
*/
function pp_kw2011_portal_api($param, $arg) {
	// api
		if ($param == "mode" && $arg == "closeSession") {
			$_SESSION["pp_kw2011_portal_shown"] = true;
			echo json_encode("true");
		} else if ($param == "mode" && $arg == "getNews") {
			echo pp_kw2011_portal_getNews();
		} else {
			echo json_encode(array("error" => "mode not set"));
		}
}


/**
*
*/
function pp_kw2011_portal_getNews() {
	// data
		$data = array();

	// area
		$areas = array("hp", "da", "f", "gi", "htk", "ks", "mkk", "mr", "of", "ofl", "fb", "wi", "kb");

	// doubles
		$doubles = array();

	// load all
		$sql = "SELECT * FROM {pp_kw2011_portal} ORDER BY `date` DESC LIMIT 0, 15";
		$results = db_query($sql);
		while ($info = db_fetch_array($results)) {
			if (!isset($data["all"]))
				$data["all"] = array();
			$info["title"] = pp_kw2011_portal_setTitle($info["title"]);
			$info["date"] = pp_kw2011_portal_setDate($info["date"]);
			#$pos = array_push($data["all"], $info);
			$data["all"][$info["id"]] = $info;

			$words = pp_kw2011_portal_getFirstWords($info["title"]);
			if (!isset($doubles["all"]))
				$doubles["all"] = array();
			if (!isset($doubles["all"][$words]))
				$doubles["all"][$words] = array();
			$doubles["all"][$words][$info["type"]] = $info["id"]; //$pos - 1;
		}

	// load areas
		foreach ($areas as $area) {
			$sql = "SELECT * FROM {pp_kw2011_portal} WHERE `area` = '".$area."' ORDER BY `date` DESC LIMIT 0, 12";
			$results = db_query($sql);
			while ($info = db_fetch_array($results)) {
				if (!isset($data[$area]))
					$data[$area] = array();
				$info["title"] = pp_kw2011_portal_setTitle($info["title"]);
				$info["date"] = pp_kw2011_portal_setDate($info["date"]);
				#$pos = array_push($data[$area], $info);
				$data[$area][$info["id"]] = $info;

				$words = pp_kw2011_portal_getFirstWords($info["title"]);
				if (!isset($doubles[$area]))
					$doubles[$area] = array();
				if (!isset($doubles[$area][$words]))
					$doubles[$area][$words] = array();
				$doubles[$area][$words][$info["type"]] = $info["id"]; //$pos - 1;
			}
		}

	// debug
		#echo "<pre>";
		#print_r($doubles);

	// filter doubles
		foreach($doubles as $area => $rows) {
			#if ($area == "f") print_r($data[$area]);
			foreach($rows as $double) {
				#if ($area == "f") print_r($double);
				if (sizeof($double) == 2) {
					if ($double["facebook"] && $double["website"]) {
						unset($data[$area][$double["facebook"]]);
					} else if ($double["facebook"] && $double["twitter"]) {
						unset($data[$area][$double["facebook"]]);
					} else if ($double["twitter"] && $double["website"]) {
						unset($data[$area][$double["twitter"]]);
					}
				} else if (sizeof($double) == 3) {
					unset($data[$area][$double["facebook"]]);
					unset($data[$area][$double["twitter"]]);
				}
			}
			#if ($area == "f") print_r($data[$area]);
		}

	// debug end
		#echo "</pre>";

	// size data
		foreach($data as $area => $rows) {
			$size = 4;
			if ($area == "all")
				$size = 5;
			$data[$area] = array_slice($rows, 0, $size);
		}

	// return
		return json_encode($data);
}

/**
*
*/
function pp_kw2011_portal_getFirstWords($title) {
	#echo "<pre>";
	#echo $title."\n";
	$title = str_replace(".", " ", $title);
	$title = str_replace(":", " ", $title);
	$title = str_replace(",", " ", $title);
	$title = str_replace(";", " ", $title);
	$title = str_replace("\"", " ", $title);
	$title = str_replace("@", " ", $title);
	$title = preg_replace("/\s\s+/", " ",$title);
	$title = str_replace(".", " ", $title);
	#echo $title."\n";
	$title = explode(" ", $title);
	#print_r($title);
	#echo "<pre>";
	$title = $title[0].$title[1].$title[2].$title[3].$title[4].$title[5];
	return $title;
}

/**
*
*/
function pp_kw2011_portal_setTitle($title) {
	if (strlen($title) > 200) {
		$title = explode("\n", $title);
		$title = $title[0];
	}
	return $title;
}

/**
*
*/
function pp_kw2011_portal_setDate($date) {
	$date = date("d.m.Y", strtotime($date));
	return $date;
}

/**
* Display help and module information.
* @param path
*   Which path of the site we're displaying help.
* @param arg
*   Array that holds the current path as would be returned from arg() function.
* @return
*   help text for the path.
*/
function pp_kw2011_portal_help($path, $arg) {
  $output = '';
  switch ($path) {
    case "admin/help#pp_kw2011_portal":
      $output = '<p>'. t("Zeigt den Block für die Kommunalwahlen 2011 in Hessen").'</p>';
      break;
  }
  return $output;
} // function pp_kw2011_portal_help


/**
* Valid permissions for this module
* @return array An array of valid permissions for the pp_hessen module
*/
#function pp_kw2011_portal_perm() {
#  return array('administer pp_kw2011_portal');
#} // function pp_kw2011_portal_perm()


/**
* Generate HTML for the pp_hessen block
* @param op the operation from the URL
* @param delta offset
* @returns block HTML
*/
function pp_kw2011_portal_block($op='list', $delta=0) {
	// listing of blocks, such as on the admin/block page
		if ($op == "list") {
			// return
				$block[0]["info"] = t('Kommunalwahl 2011 Button');
				return $block;
		} else if ($op == 'view') {
			// get path
				$module_path = drupal_get_path('module', 'pp_kw2011_portal');

			// content
				$block_content = '<div style="padding-left: 18px;">';
				$block_content .= '<p><a id="pp_kw2011_portal-blockButton" href="javascript:void(0);" onclick="showPortal(\'/'.$module_path.'\', true);"><img width="160" height="220" src="/'.$module_path.'/pp_kw2011_portal-buttonBlock.png" alt="Kommunalwahl-Portal 2011" /></a></p>';
				$block_content .= '</div>';

			// our block content
				$block['subject'] = 'Kommunalwahl 2011';
				$block['content'] = $block_content;
				return $block;
		}
}


/**
* read facebook
*/
		function pp_kw2011_portal_readFacebook($id, $area) {
			$facebook = new Facebook(array(
				'appId'  => '125080340892097',
				'secret' => '4b77f40ca3e83cbec328ef8f89e0467e',
				'cookie' => true, // enable optional cookie support
			));

			try {
				$result = $facebook->api(array(
					'query' => 'SELECT permalink, created_time, message, attachment FROM stream WHERE source_id = '.$id.' AND actor_id = '.$id.' AND attribution != "Twitter"',
					'method' => 'fql.query'));
			} catch (FacebookApiException $e) {
				#print_r($e);
			}
			#print_r($result);

			$ret = array();
			foreach($result as $row) {
				$data = array();
				$data["type"] = "facebook";
				$data["area"] = $area;
				if (!empty($row["message"]))
					$data["title"] = $row["message"];
				else
					$data["title"] = $row["attachment"]["name"];
				$data["link"] = $row["permalink"];
				$data["date"] = $row["created_time"];
				array_push($ret, $data);
			}
			unset($facebook);
			return $ret;
		}

/**
* read rss
*/
		function pp_kw2011_portal_readRss($url, $type, $area) {
			$days_de = array("Mo,",  "Di,",  "Mi,",  "Do,",  "Fr,",  "Sa,",  "So,");
			$days_en = array("Mon,", "Tue,", "Wed,", "Thu,", "Fri,", "Sat,", "Sun,");

			$months_de = array("Jan", "Feb", "Mär", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez");
			$months_en = array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");

			$doc = new DOMDocument();
			$doc->load($url);
			$arrFeeds = array();
			foreach ($doc->getElementsByTagName('item') as $node) {
				$itemRSS = array (
					'type' => $type,
					'area' => $area,
					'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
					'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
					'date' => strtotime(str_replace($months_de, $months_en, str_replace($days_de, $days_en, $node->getElementsByTagName('pubDate')->item(0)->nodeValue)))
				);

				if ($type == "twitter") {
					$title = explode(":", $itemRSS["title"]);
					array_shift($title);
					$itemRSS["title"] = trim(implode(":", $title));
				}
				array_push($arrFeeds, $itemRSS);
			}
			unset($doc);
			return $arrFeeds;
		}


/**
*
*/
function pp_kw2011_portal_cron() {
	// get path
		$module_path = drupal_get_path('module', 'pp_kw2011_portal');

	// includes
		require $module_path.'/includes/facebook.php';

		// feeds
			$feeds = array(
						"hp"	=>	array(
										"website"	=>	"http://www.piraten-bergstrasse.de/rss.xml",
										"twitter"	=>	"http://twitter.com/statuses/user_timeline/74127944.rss",
										"facebook"	=>	"",
									),
						"da"	=>	array(
										"website"	=>	"",
										"twitter"	=>	"http://twitter.com/statuses/user_timeline/94058063.rss",
										"facebook"	=>	"178670105500687",
									),
						"f"		=>	array(
										"website"	=>	"http://www.piratenpartei-frankfurt.de/rss.xml",
										"twitter"	=>	"http://twitter.com/statuses/user_timeline/86837137.rss",
										"facebook"	=>	"121055301279305",
									),
						"gi"	=>	array(
										"website"	=>	"http://www.piratenpartei-giessen.de/rss.xml",
										"twitter"	=>	"http://twitter.com/statuses/user_timeline/45783877.rss",
										"facebook"	=>	"105453226187689",
									),
						"htk"	=>	array(
										"website"	=>	"http://www.piratenpartei-hochtaunus.de/rss.xml",
										"twitter"	=>	"http://twitter.com/statuses/user_timeline/113692272.rss",
										"facebook"	=>	"171335258766",
									),
						"ks"	=>	array(
										"website"	=>	"http://www.piratenpartei-kassel.de/rss.xml",
										"twitter"	=>	"http://twitter.com/statuses/user_timeline/56069781.rss",
										"facebook"	=>	"100001738696565",
									),
						"mkk"	=>	array(
										"website"	=>	"http://www.kinzigpiraten.de/rss.xml",
										"twitter"	=>	"http://twitter.com/statuses/user_timeline/55660231.rss",
										"facebook"	=>	"",
									),
						"mr"	=>	array(
										"website"	=>	"http://www.piratenpartei-marburg.de/rss.xml",
										"twitter"	=>	"http://twitter.com/statuses/user_timeline/50764745.rss",
										"facebook"	=>	"120479954667530",
									),
						"of"	=>	array(
										"website"	=>	"http://www.piratenpartei-offenbach.de/rss.xml",
										"twitter"	=>	"http://twitter.com/statuses/user_timeline/125916800.rss",
										"facebook"	=>	"139457009429820",
									),
						"ofl"	=>	array(
										"website"	=>	"http://www.kreispiraten-of.de/rss.xml",
										"twitter"	=>	"http://twitter.com/statuses/user_timeline/63279484.rss",
										"facebook"	=>	"",
									),
						"fb"	=>	array(
										"website"	=>	"http://www.piratenpartei-wetterau.de/rss.xml",
										"twitter"	=>	"http://twitter.com/statuses/user_timeline/64974941.rss",
										"facebook"	=>	"159298207455207",
									),
						"wi"	=>	array(
										"website"	=>	"http://www.piratenpartei-wiesbaden.de/rss.aspx",
										"twitter"	=>	"http://twitter.com/statuses/user_timeline/134227607.rss",
										"facebook"	=>	"100001492291918",
									),
						"kb"	=>	array(
										"website"	=>	"http://piraten-waldeck-frankenberg.de/rss.xml",
										"twitter"	=>	"http://twitter.com/statuses/user_timeline/56827335.rss",
										"facebook"	=>	"182205524665",
									),
			);

		// run
			$data = array();
			foreach($feeds as $area => $feed) {
				if (!empty($feed["website"]))
					$data = array_merge($data, pp_kw2011_portal_readRss($feed["website"], "website", $area));
				if (!empty($feed["twitter"]))
					$data = array_merge($data, pp_kw2011_portal_readRss($feed["twitter"], "twitter", $area));
				if (!empty($feed["facebook"]))
					$data = array_merge($data, pp_kw2011_portal_readFacebook($feed["facebook"], $area));
			}
			#print_r($data);

		// load
			$links = array();
			$sql = "SELECT link FROM {pp_kw2011_portal}";
			$results = db_query($sql);
			while ($info = db_fetch_array($results)) {
				$links[$info["link"]] = true;
			}
			unset($results);

		// save
			foreach($data as $row) {
				if (!isset($links[$row["link"]])) {
					$row["date"] = date('Y-m-d H:i:s', $row["date"]);
					drupal_write_record("pp_kw2011_portal", $row);
				}
			}
}

?>
