<?php
  /**************************************************************************\
  * phpGroupWare - news headlines                                            *
  * http://www.phpgroupware.org                                              *
  * Written by Mark Peters <mpeters@satx.rr.com>                             *
  * Based on pheadlines 0.1 19991104 by Dan Steinman <dan@dansteinman.com>   *
  * --------------------------------------------                             *
  *  This program is free software; you can redistribute it and/or modify it *
  *  under the terms of the GNU General Public License as published by the   *
  *  Free Software Foundation; either version 2 of the License, or (at your  *
  *  option) any later version.                                              *
  \**************************************************************************/

  /* $Id: functions.inc.php,v 1.1.1.3.6.1 2004/09/27 03:52:07 kazuyan Exp $ */

	class headlines
	{
		// socket timeout in seconds
		var $current_time;
		var $db;

		var $con       = 0;
		var $display   = '';
		var $base_url  = '';
		var $newsfile  = '';
		var $lastread  = 0;
		var $newstype  = '';
		var $cachetime = 0;
		var $listings  = 0;
		var $error_timeout = False;
		var $codecv;

		// wired news was messing up, I dunno
		// "wired" => array("Wired&nbsp;News","http://www.wired.com","/news_drop/netcenter/netcenter.rdf/","rdf"),	

		function headlines()
		{
			$GLOBALS['phpgw']->network = CreateObject('phpgwapi.network',False);
			$this->codecv = CreateObject('phpgwapi.codecv');
		}

		// try to get the links for the site
		function getLinks($site)
		{
			if (! $this->readtable($site))
			{
				return $links;
			}

			if ($this->isCached())
			{
				$links = $this->getLinksDB();
			}
			else
			{
				$links = $this->getLinksSite();

				if ($links)
				{
					$this->saveToDB($links);
				}
				else
				{
					$links = $this->getLinksDB();
					$this->error_timeout = True;
				}
			}
			return $links;
		}

		// do a quick read of the table
		function readtable($site)
		{
			$GLOBALS['phpgw']->db->query('SELECT con,display,base_url,newsfile,lastread,newstype,cachetime,listings '
				. ' FROM phpgw_headlines_sites WHERE con = ' . intval($site),__LINE__,__FILE__);
			if (! $GLOBALS['phpgw']->db->num_rows())
			{
				return False;
			}
			$GLOBALS['phpgw']->db->next_record();

			$this->con       = $GLOBALS['phpgw']->db->f('con');
			$this->display   = $GLOBALS['phpgw']->db->f('display');
			$this->base_url  = $GLOBALS['phpgw']->db->f('base_url');
			$this->newsfile  = $GLOBALS['phpgw']->db->f('newsfile');
			$this->lastread  = $GLOBALS['phpgw']->db->f('lastread');
			$this->newstype  = $GLOBALS['phpgw']->db->f('newstype');
			$this->cachetime = $GLOBALS['phpgw']->db->f('cachetime');
			$this->listings  = $GLOBALS['phpgw']->db->f('listings');

			return True;
		}

		// determines if the headlines were cached less than $cachetime minutes ago
		function isCached()
		{
			$this->current_time = time();
			return (($this->current_time - $this->lastread) < ($this->cachetime * 60));
		}

		// get the links from the database
		function getLinksDB()
		{
			$GLOBALS['phpgw']->db->query('SELECT title, link FROM phpgw_headlines_cached '
				. ' WHERE site = '.intval($this->con), __LINE__, __FILE__);
		
			if (! $GLOBALS['phpgw']->db->num_rows())
			{
				$links = $this->getLinksSite();  // try from site again
				if (!$links)
				{
					$display = htmlspecialchars($this->display);
//					die("</table><b>error</b>: unable to get links for <br><a href=\""
//						. "$this->base_url\">$this->display</a>");
					return False;
				}
			}

			while ($GLOBALS['phpgw']->db->next_record())
			{
				$links[$GLOBALS['phpgw']->db->f('title')] = $GLOBALS['phpgw']->db->f('link');
			}
			return $links;
		}

		// get a new set of links from the site
		function getLinksSite()
		{
			// determine the options to properly extract the links
			$startat = '</image>';
			$linkstr = 'link';
			$exclude = '';


			switch ($this->newstype)
			{
				case 'rdf-chan': $startat = '</channel>'; break;
				case 'lt':       $linkstr = 'url'; break;
				case 'fm':       $exclude = 'quick finder'; break;
				case 'sf':       $startat = '</textinput>'; break;
				default: break;
			}

			// get the file that contains the links
			$lines = $GLOBALS['phpgw']->network->gethttpsocketfile($this->base_url.$this->newsfile);
			if (!$lines)
			{
				return False;
			}

			$startnum = 0;

			// determine which line to begin grabbing the links
			for ($i=0;$i<count($lines);$i++)
			{
				if (ereg($startat,$lines[$i],$regs))
				{
					$startnum = $i;
					break;
				}
			}

			// extract the links and assemble into array $links
			$links = array();
			for ($i=$startnum;$i<count($lines);$i++)
			{
				if (count($links)>=$this->listings)
				{
					break;
				}

				if (ereg("<title>(.*)</title>",$lines[$i],$regs))
				{
					if ($regs[1] == $exclude)
					{
						$i+=1;
						break;
					}
					$title = $regs[1];
					$title = ereg_replace("&amp;apos;","'",$this->codecv->auto2euc($title));
					$title = ereg_replace("&amp;quot;",'"',$title);		// XML Standard Entity
					$title = ereg_replace("&amp;",'&',$title);
				}
				
				if (ereg("<$linkstr>(.*)</$linkstr>",$lines[$i],$regs))
				{
					$links[$title] = $regs[1];
				}
			}

			return $links;
		}

		// get a list of the sites
		function getList()
		{
			@set_time_limit(0);

			// determine the options to properly extract the links
			$startat = '</image>';
			$linkstr = 'link';
			$exclude = '';

			// get the file that contains the links
			// "http://www.phpgroupware.org/headlines.rdf";
			if ($GLOBALS['phpgw_info']['user']['preferences']['common']['lang'] != 'ja')
				$lines = $GLOBALS['phpgw']->network->gethttpsocketfile("http://phpgroupware.org/headlines.rdf");
			else
				$lines = $GLOBALS['phpgw']->network->gethttpsocketfile("http://downloads.phpgroupware.jp/headlines.rdf");
			if (!$lines)
			{
				return False;
			}

			$startnum = 0;

			// determine which line to begin grabbing the links
			for ($i=0;$i<count($lines);$i++)
			{
				if (ereg($startat,$lines[$i],$regs))
				{
					$startnum = $i;
					break;
				}
			}

			// extract the links and assemble into array $links
			$links = array();
			for ($i=$startnum,$j=0;$i<count($lines);$i++)
			{
				if (ereg("<title>(.*)</title>",$lines[$i],$regs))
				{
					if ($regs[1] == $exclude)
					{
						$i+=1;
						break;
					}
					$title[$j] = $this->codecv->auto2euc($regs[1]);
					$title[$j] = ereg_replace("&amp;apos;","'",$title[$j]);
					$title[$j] = ereg_replace("&amp;quot;",'"',$title[$j]);		// XML Standard Entity
				}
				elseif (ereg("<$linkstr>(.*)</$linkstr>",$lines[$i],$regs))
				{
					$links[$j] = $regs[1];
				}
				elseif (ereg("<description>(.*)</description>",$lines[$i],$regs))
				{
					$type[$j] = $this->codecv->auto2euc($regs[1]);
					$j++;
				}
			}

			$GLOBALS['phpgw']->db->transaction_begin();
			for ($i=0;$i<count($title);$i++)
			{
				$server = str_replace('http://','',$links[$i]);
				$file   = strstr($server,'/');
				$server = 'http://' . str_replace($file,'',$server);

				$GLOBALS['phpgw']->db->query('SELECT con,display,base_url,newsfile,newstype FROM phpgw_headlines_sites '
					. " WHERE display='".$GLOBALS['phpgw']->db->db_addslashes($title[$i]) . "'"
					. " AND base_url='" . $GLOBALS['phpgw']->db->db_addslashes($server) . "'"
					. " AND newsfile='" . $GLOBALS['phpgw']->db->db_addslashes($file) . "'",__LINE__,__FILE__);
				if ($GLOBALS['phpgw']->db->num_rows() == 0)
				{
					$GLOBALS['phpgw']->db->query("INSERT INTO phpgw_headlines_sites (display,base_url,newsfile,"
						. "newstype,lastread,cachetime,listings) VALUES("
						. "'" . $GLOBALS['phpgw']->db->db_addslashes($title[$i]) . "',"
						. "'" . $GLOBALS['phpgw']->db->db_addslashes($server) . "',"
						. "'" . $GLOBALS['phpgw']->db->db_addslashes($file) . "',"
						. "'" . $GLOBALS['phpgw']->db->db_addslashes($type[$i]) . "'"
						. ',0,60,20)',__LINE__,__FILE__);
					continue;
				}
				$GLOBALS['phpgw']->db->next_record();

				if ($GLOBALS['phpgw']->db->f('newstype') <> $type[$i])
				{
					$GLOBALS['phpgw']->db->query('UPDATE phpgw_headlines_sites '
						. " SET newstype='". $GLOBALS['phpgw']->db->db_addslashes($type[$i]) . "'"
						. ' WHERE con=' . intval($this->db->f('con')) ,__LINE__,__FILE__);
				}
			}
			$GLOBALS['phpgw']->db->transaction_commit();
		}

		// save the new set of links and update the cache time
		function saveToDB($links)
		{
			$GLOBALS['phpgw']->db->query("DELETE FROM phpgw_headlines_cached WHERE site=" . intval($this->con),__LINE__,__FILE__);

			// save links
			while (list($title,$link) = @each($links))
			{
				$link  = $GLOBALS['phpgw']->db->db_addslashes($link);
				$title = $this->codecv->auto2euc($GLOBALS['phpgw']->db->db_addslashes($title));
				$GLOBALS['phpgw']->db->query('INSERT INTO phpgw_headlines_cached '
					. 'VALUES(' . intval($this->con) . ",'$title','$link')", __LINE__, __FILE__);
			}		
		
			// save cache time
			$GLOBALS['phpgw']->db->query('UPDATE phpgw_headlines_sites SET lastread = ' . intval($this->current_time)
				. ' WHERE con=' . intval($this->con), __LINE__, __FILE__);
		}
	}


?>
