<?
/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
* Class		:	main
* Version :	1.0
* Date    :	07 October 2005
* Author  :	Darwish A. Khalil
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/

// Class Definition
class main
{
	var $trace;

	// Constructor of the class
  function main()
  {
  	global $trace;
  	$this->trace = $trace;
	}

	// This function is used to retrieve the tree of the sitemap
  function getSiteMap()
  {
  	global $language;

    $query  = "SELECT sms1.*, sms2.Facet ParentFacet, sms2.MenuLeft ";
		$query .= "FROM sitemap_section sms1 Left JOIN sitemap_section sms2 ";
		$query .= "ON sms1.ParentID = sms2.SiteMapSectionID ";
		$query .= "Where sms1.MenuLeft=1 And sms1.Language = '$language' ";
		$query .= "ORDER BY sms1.Facet";
		// exit($query);
    $result = mysql_query($query);
    return $result;
	}

	// This function is used to retrieve name of the menu parent
  function getParentName($SMSID)
  {
    $query  = "Select Name ParentName From sitemap_section ";
    $query .= "Where SiteMapSectionID = $SMSID";
    $result = mysql_query($query);
    $row = mysql_fetch_object($result);
    return $row->ParentName;
	}

	// This function is used to retrieve the parent items of the main menu
  function getMenuParentItems()
  {
  	global $language;

    $query  = "
    						SELECT SiteMapSectionID, Facet, Name, DisplayMode
    						From sitemap_section
    						Where ParentID is Null And Language = '$language' And Enabled = 1
    						Order By Facet
    					";
		// exit($query);
    $result = mysql_query($query);
    return $result;
	}

	// This function is used to check if a certain link has sublinks or not
  function hasSubLinks($Facet)
  {
    $query  = "Select SiteMapSectionID From sitemap_section ";
    $query .= "Where Facet Like '$Facet.%'";
    $result = mysql_query($query);
    // exit($query);
    if (mysql_num_rows($result)>0) {
			return true;
		}
		return false;
	}

	// This function is used to check if a certain link has materials or not
  function hasMaterials($SMSID)
  {
  	if (!empty($SMSID))
  	{
    	$query  = "Select MaterialID From material_sitemap_section ";
    	$query .= "Where SiteMapSectionID = $SMSID";
    	$result = mysql_query($query);
    	//echo($query);
    	if (mysql_num_rows($result)>0) {
				return true;
			}
		}
		return false;
	}

	// This function is used to retrieve name of a certain location
  function getLocationName($SMSID, $language)
  {
    $query  = "Select Name LocationName From sitemap_section ";
    $query .= "Where SiteMapSectionID = $SMSID";
    $result = mysql_query($query);
    $row = mysql_fetch_object($result);
    return $row->LocationName;
	}

	// This function is used to retrieve the full path (navigation location bar) of a certail material
	function getMaterialFullPath($SMSID, $language, $isContent = true, $class='NavigationLink')
	{
		// Generate the full path
		$name = ""; $i=1;
		while (!empty($SMSID))
		{
			$result = $this->getLocationInfo($SMSID,$language);
			$row = mysql_fetch_object($result);
			$SMSID = $row->ParentID;
			$name[$i] = $row->Name;
			$location[$i] = $row->SMSID;
			$display_mode[$i] = $row->DisplayMode;
			$i++;
		}
		//---------------------------------------------------------------------------
		$n = ($isContent) ? 1 : 0;
		if (count($name)>$n)
		{
			//---------------------------------------------------------------------------------------
			if (($name[count($name)] == "Home Page") || ($name[count($name)] == "������ ��������"))
			{
	  		$page_name = "home.php";
	  	}
	  	else
	  	{
	  		$page_name = ($display_mode[count($name)]==0) ? "contents1.php" : "contents.php";
	  	}
	  	//---------------------------------------------------------------------------------------
			//if ( ($this->hasMaterials($location[count($name)])) || ($display_mode[count($name)]==1) ) {
			if ( $this->hasMaterials($location[count($name)]) ) {
				$path = "<a href='../Home/".$page_name."?id=".$location[count($name)]."' class='$class'>".$name[count($name)]."</a>";
			}else{
				$path = $name[count($name)];
			}
			$page_title = $name[count($name)];
			//---------------------------------------------------------------------------------------
			for ($i=count($name)-1; $i>=1; $i--)
			{
				$page_name = ($display_mode[$i]==0) ? "contents1.php" : "contents.php";
				if ($i>1)
				{
					//if ( ($this->hasMaterials($location[$i])) || ($display_mode[$i]==1) ) {
					if ( $this->hasMaterials($location[$i]) ) {
						$link = "<a href='../Home/".$page_name."?id=$location[$i]' class='$class'>".$name[$i]."</a>";
					}else{
						$link = $name[$i];
					}
					$path = $path . " &#187; " . $link;
				}
				else
				{
					//$path = $path . " &#187; " . $name[$i];
					if ($display_mode[$i]==1) {
						$link = "<a href='../Home/".$page_name."?id=$location[$i]' class='$class'>".$name[$i]."</a>";
					}else{
						$link = $name[$i];
					}
					$path = $path . " &#187; " . $link;
				}
				$page_title = $page_title . " &#187; " . $name[$i];
			}
		}
		else
		{
			$page_title = $path = $name[1];
		}
		//---------------------------------------------------------------------------
		$MyPath['NAVIGATION_PATH'] = $path;
		$MyPath['PAGE_TITLE'] = $page_title;

		return $MyPath;
	}

	// This function is used to check if a certain location exists or not
  function isExistLocation($SMSID)
  {
    $query  = "Select SiteMapSectionID From sitemap_section ";
    $query .= "Where SiteMapSectionID = $SMSID";
    $result = mysql_query($query);
    // exit( $query);
    if (mysql_num_rows($result)>0) {
			return true;
		}
		return false;
	}

	// This function is used to retrieve the materials in a certain location
  function getLocationMaterials($SMSID, $Language)
  {
  	// Get the number of items to be shown in this location and in which way (priority or date)
  	$query  = "Select Materials_Priority, Materials_EntryDate From sitemap_section ";
  	$query .= "Where SiteMapSectionID = $SMSID";
  	$result = mysql_query($query);

  	$row = mysql_fetch_object($result);

  	if ($row->Materials_Priority != -1)
  	{
  		$sOrderBy  = "Priority";
  		$nMaterials = $row->Materials_Priority;
  	}
  	else
  	{
  		$sOrderBy   = "DataEntryDate DESC";
  		$nMaterials = $row->Materials_EntryDate;
  	}

  	// Get n materials in this location
    $query  = "SELECT M.*, MT.Name Type, MSS.Priority ";
		$query .= "FROM material M, material_types MT, material_sitemap_section MSS ";
		$query .= "Where M.TypeID = MT.TypeID And M.MaterialID = MSS.MaterialID ";
		$query .= "And MSS.SiteMapSectionID = $SMSID And M.Language = '$Language' And MSS.Enabled = 1 ";
		$query .= "ORDER BY $sOrderBy, TimeStamp DESC ";
		$query .= "Limit 0,$nMaterials";
    $result = mysql_query($query);
    // exit($query);
    return $result;
	}

	// This function is used to retrieve the attachments of a certain material
	function getMaterialAttachments($MaterialID)
	{
		$query  = "Select A.AttachmentID, T.Name TypeName, ";
		$query .= "A.Name, A.FileName, A.Date, A.Description, A.Source, A.Extension ";
		$query .= "From attachment A, attachment_types T ";
		$query .= "Where A.TypeID = T.TypeID And A.MaterialID = $MaterialID And A.Deleted = 0 ";
		$query .= "Order By A.Date Desc, A.AttachmentID DESC, A.TypeID";
		// exit($query);
    $result = mysql_query($query);
    return $result;
	}

	// This function is used to retrieve a list of all enabled text ads to be used on the right panel
  function getTextAds($category_id = 1)
	{
    $query = "Select * From textads Where Enabled = 1";
    $result = mysql_query($query);
    return $result;
  }

	// This function is used to get the top n latest news
  function getLatestNews($n = -1)
	{
    $query  = "Select * From latest_news Where Enabled = 1 Order By UpdateDate DESC, ID ";
    $query .= "Limit $n";
    $result = mysql_query($query);
    return $result;
  }

  // This function is used to get the specified latest new
  function getThisLatestNew($id)
  {
    $query = "Select * From latest_news Where Enabled = 1 And ID = $id";
    $result = mysql_query($query);
    return $result;
  }

  // This function is used to get the SiteMapSectionID of the Home Page
  function getHomePageLocationID()
  {
  	global $language;

  	$query  = "Select SiteMapSectionID From sitemap_section Where ";

  	if ($language == 'ar')
  	{
	  	$query .= "Name Like '%������ ��������%' Or Name Like '%�������%' ";
    	$query .= "Or Name Like '%������ ������%' Or Name Like '%������ ������%' Or Name Like '��������'";
    }
    else if ($language == 'en')
    {
    	$query .= "Name Like '%Home Page%' Or Name Like '%Main Page%' Or Name Like 'Home'";
    }
    //--------------------------------------------------------------------------------------------------
    $query .= "And Language = '$language'";
    //echo( $query);
    //--------------------------------------------------------------------------------------------------
    $result = mysql_query($query);
    if (mysql_num_rows($result)>0)
    {
			$row = mysql_fetch_object($result);
			return $row->SiteMapSectionID;
		}
		return -1;
  }

	// This function is used to get the information of a certain location
	function getLocationInfo($SMSID, $language)
  {
    $query  = "Select SiteMapSectionID SMSID, ParentID, Name, DisplayMode From sitemap_section ";
    $query .= "Where SiteMapSectionID = $SMSID";
    $result = mysql_query($query);
    return $result;
	}

	/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
	*                             Home Page Functions
	*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/

	// This function is used to retrieve a list of all entries to be shown in the home page
  function getAllEntries($language)
  {
    $query  = "Select M.Title, H.MaterialID, H.ID, H.PictureName, H.Description, H.Priority, H.Enabled ";
    $query .= "From material M, homepage_entries H ";
    $query .= "Where M.MaterialID = H.MaterialID and H.Language = '$language' ";
    $query .= "Order By H.Priority, H.DateTime DESC";
   	// echo $query;
    $result = mysql_query($query);
    return $result;
	}

	/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
	*                             Common Functions
	*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/

	// This function is used to retrieve the available custom controls in a certain location
	function getCustomControls($LocationID)
	{
		global $language;

		$query  = "Select * From control Where LocationID = $LocationID ";
		$query .= "And Language = '$language' And Enabled = 1 ";
		$query .= "Order By Priority ASC, DateTime DESC";
		$result = mysql_query($query);
    return $result;
	}

	// This function is used to check if a certain control has materials or not
	function isControlHasMaterials($ControlID)
	{
		$query  = "Select ID From control_material ";
    $query .= "Where ControlID = $ControlID";
    $result = mysql_query($query);
    // exit( $query);
    if (mysql_num_rows($result)>0) {
			return true;
		}
		return false;
	}

	// This function is used to retrieve the materials of a certain control
  function getControlMaterials($ControlID)
  {
    $query  = "Select * From control_material Where ControlID = $ControlID ";
    $query .= "Order By Priority ASC, TimeStamp DESC";
    // echo( $query );
    $result = mysql_query($query);
    return $result;
	}

	// This function is used to get the info of a certain material
	function getMaterialInfo($MaterialID)
  {
    $query = "Select Title, Author From material Where MaterialID = $MaterialID";
    $result = mysql_query($query);
    return $result;
	}

	// This function is used to get the name of a certain location
	function getMaterialsLocationInfo($SiteMapSectionID)
  {
    $query = "Select Name, DisplayMode From sitemap_section Where SiteMapSectionID = $SiteMapSectionID";
   	$result = mysql_query($query);
    return $result;
	}

	// This function is used to know when the website has been last updated
	function getLastUpdateDateTime()
	{
		$query  = "Select DATE_FORMAT(TimeStamp,'%d-%m-%Y - %H:%i') DateTime From material ";
    $query .= "Order By TimeStamp DESC Limit 1";
    // echo( $query );
    $result = mysql_query($query);
    if (mysql_num_rows($result) > 0)
    {
    	$row = mysql_fetch_object($result);
    	$strDateTime = $row->DateTime;
    }
    else
    {
    	$strDateTime = "";
    }
    return $strDateTime;
	}

	// This function is used to get the last n recently added attachments.
	function getRecentlyAddedAttachments($n, $language)
	{
		$query  = "Select Name, FileName, DATE_FORMAT(A.Date,'%d/%m/%Y') AttachmentDate ";
		$query .= "From attachment A, material M ";
		$query .= "Where A.MaterialID = M.MaterialID And M.Language = '$language' ";
		$query .= "And A.Deleted = 0 ";
    $query .= "Order By AttachmentDate DESC, Name ASC Limit $n";
    // echo( $query );
    $result = mysql_query($query);
    return $result;
	}

	// This function is used to retrieve all the attachments of the whole site
	function getAllAttachments($language, $start=-1, $num=-1)
	{
		$query  = "Select A.AttachmentID, T.Name TypeName,, A.Name, A.FileName, ";
		$query .= "A.Date, A.Description, A.Source, A.Extension, M.Title, M.MaterialID ";
		$query .= "From attachment A, attachment_types T, material M ";
		$query .= "Where A.TypeID = T.TypeID And A.MaterialID = M.MaterialID ";
		$query .= "And A.Deleted = 0 And M.Language = '$language' ";
		$query .= "Order By A.Date Desc, A.Name ASC, A.TypeID ";

		if (($start!=-1) && ($num!=-1)) {
      $query .= "Limit $start,$num";
		}

		// echo($query);
    $result = mysql_query($query);
    return $result;
	}

	// This function is used to retrieve the display mode of a certain page
	function getPageDisplayMode($SiteMapSectionID)
	{
		$query  = "Select DisplayMode From sitemap_section ";
    $query .= "Where SiteMapSectionID = $SiteMapSectionID";
    // echo( $query );
    $result = mysql_query($query);
    $row = mysql_fetch_object($result);
    return $row->DisplayMode;
	}

	/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
	*                             Become a Reseller Page Functions
	*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/
	function SendMail($objReseller, $requestID)
	{
		global $lang;
		global $config;

		include_once "mail.class.php";

		// Prepare headers for sending an html mail
		$headers  = "MIME-Version: 1.0\r\n";
		$headers .= "Content-type: text/html; charset=windows-1256\r\n";
		$headers .= "From:" . $objReseller->Email . "\r\n";
		// $headers .= "CC:" . $config['EMAIL_CC1'] . "\r\n";
		$headers .= "BCC:" . $config['EMAIL_BCC'] . "\r\n";

		$to = $config['EMAIL_TO'];
		$subject = sprintf($lang['Become_Reseller_Request'],$requestID);

		$message = $this->GenerateMessage($objReseller);

		// exit($message);

		//Send Message
		if(eregi("win",strtolower(PHP_OS)))
		{
			$msg = new email();
	 		$msg->send_mail(0, $to, $subject, $message, $headers);
		}
    elseif(eregi("linux",strtolower(PHP_OS)))
    {
			@mail($to, $subject, $message, $headers);
		}
	}

	function GenerateMessage($objReseller)
	{
		global $lang;
		global $language;

		$objReseller->Fax = (!empty($objReseller->Fax)) ? $objReseller->Fax : "------";
		$objReseller->Mobile = (!empty($objReseller->Mobile)) ? $objReseller->Mobile : "------";
		$objReseller->Notes = (!empty($objReseller->Notes)) ? $objReseller->Notes : "------";
		$objReseller->Email = (!empty($objReseller->Email)) ? "<a href='mailto:".$objReseller->Email."'>".$objReseller->Email."</a>" : "------";
		$countryName = $this->getCountryName($objReseller->CountryID);

		$flag = "../Flags/" . strtolower($objReseller->CountryID) . ".gif";
		$flag = file_exists($flag) ? strtolower($objReseller->CountryID).".gif" : "-.gif";

		$salesAmount = $this->getSalesAmount($objReseller->SalesAmountID);

		$msg = "
		<html dir=".$lang['DIRECTION'].">
			<head>
				<style type='text/css'>
					body { color: #595a55; font-family: Tahoma, Verdana; background-color: #EEEEEE; }
					td, pre { color: #595a55; font-family: Tahoma, Verdana; font-size: 12px; text-align: justify; }
					a { color: #eb5300; font-size: 11px; font-weight: bold; }
					a:link { color: #eb5300; text-decoration: none; }
					a:hover { color: #4777a7; text-decoration: underline; }
					a:visited { color: #eb5300; text-decoration: none; }
					.bold { font-weight: bold; }
					.Title { color: #1e6599; font-weight: bold; }
					.SenderName { color: #C60000; font-weight: bold; }
				</style>
			</head>
			<body>
				<table border='0' cellpadding='2' cellspacing='0' width='100%'>";

			if (!empty($objReseller->Name))
			{
				$msg .= "
					<tr>
						<td>".sprintf($lang['MessageHeader'], $objReseller->Name, $countryName, "<img alt='' src='https://www.softcall.me/Flags/$flag'>")."</td>
					</tr>
					<tr>
						<td height='10'></td>
					</tr>";
			}

			$msg .= "
					<tr>
						<td class='Title'>".$lang['MessageFooter']."</td>
					</tr>
					<tr>
						<td height='5'></td>
					</tr>
					<tr>
						<td><span class='bold'>".$lang['Company'].":</span> ".$objReseller->Company."</td>
					</tr>
					<tr>
						<td><span class='bold'>".$lang['Address'].":</span> ".$objReseller->Address."</td>
					</tr>
					<tr>
						<td><span class='bold'>".$lang['BusinessType'].":</span> <span dir='ltr'>".$objReseller->BusinessType."</span></td>
					</tr>
					<tr>
						<td><span class='bold'>".$lang['Email'].":</span> <span dir='ltr'>".$objReseller->Email."</span></td>
					</tr>
					<tr>
						<td><span class='bold'>".$lang['Phone'].":</span> <span dir='ltr'>".$objReseller->Phone."</span></td>
					</tr>
					<tr>
						<td><span class='bold'>".$lang['Fax'].":</span> <span dir='ltr'>".$objReseller->Fax."</span></td>
					</tr>
					<tr>
						<td><span class='bold'>".$lang['Mobile'].":</span> <span dir='ltr'>".$objReseller->Mobile."</span></td>
					</tr>
					<tr>
						<td><span class='bold'>".$lang['SalesAmount'].":</span> <span dir='ltr'>".$salesAmount."</span></td>
					</tr>
					<tr>
						<td><span class='bold'>".$lang['Notes'].":</span></td>
					</tr>
					<tr>
						<td>".nl2br($objReseller->Notes)."</td>
					</tr>
				</table>
			</body>
		</html>";

		return stripslashes($msg);
	}

	//This function is used to get Countries List
	function getCountryList()
	{
		global $language;

		$query  = "SELECT c_ID CountryID, c_Name_".$language." CountryName FROM country ";
		$query .= "ORDER BY c_Name_".$language;
		$result = mysql_query($query);
		return $result;
	}

	// This function is used to retrieve the country name of a certain country iso code
	function getCountryName($countryID)
	{
		global $language;

		$query  = "Select c_Name_".$language." CountryName FROM country Where c_ID = '$countryID'";
    // echo( $query );
    return mysql_result(mysql_query($query), 0, 0);
	}

	// This function is used to retrieve the estimated sales amount per month
	function getSalesAmount($salesAmountID)
	{
		global $language;

		$query  = "Select SalesAmountPerMonth FROM sales_amount Where SalesAmountID = " . $salesAmountID;
    // echo( $query );
    $result = mysql_query($query);
    $row = mysql_fetch_object($result);
    return $row->SalesAmountPerMonth;
	}

	// This function is used to retrieve the keywords
  function getKeywords()
  {
    $query = "Select EnglishKeywords From keywords";
    $result = mysql_query($query);
    $row = mysql_fetch_object($result);
    return $row->EnglishKeywords;
  }

  // This function is used to print a certain percentage of the keywords
  function printKeywords($delm, $percentage)
  {
  	if (!is_int($percentage) || $percentage<0 || $percentage>95)
  	{
  		$n = 0.30;
  	}
  	else
  	{
  		$n = (100-$percentage)/100;
  	}

  	$str_keywords = $this->getKeywords();

  	$keywords_array = explode($delm,$str_keywords);
  	$max = count($keywords_array);
  	$num = $n*$max;
    for($i=0;$i<$num;$i++) {
      srand((double) microtime() * 10000000);
      $index = rand(0,$max);
      $keywords_array1 = array_splice($keywords_array,$index,1);
			$keywords_array = array_diff($keywords_array,$keywords_array1);
    }
    sort($keywords_array,SORT_STRING);
    $keywords_list = implode($delm,$keywords_array);
    return trim(str_replace("\r\n", "", $keywords_list));
	}

	// This function is used to save information about users visiting our website
  function setUsersLog($user_name)
  {
    $user_ip = mysql_real_escape_string($_SERVER['REMOTE_ADDR']);
    $previous_url = mysql_real_escape_string($_SERVER['HTTP_REFERER']);
    $visited_url = mysql_real_escape_string("https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
    if ($previous_url <> $visited_url)
    {
    	// Retrieve the country name according to the user ip
    	$IP = sprintf("%u", ip2long($user_ip));
			$query = "SELECT ISO_Code, ISO_Name FROM userslog_ip2ctry WHERE IP_From <= " . $IP  . " AND IP_To >= " . $IP;
			// echo $query;
			$result = mysql_query($query);
			if (!$result) {
    		die('Invalid query: ' . mysql_error());
			}
			if ( mysql_num_rows($result) > 0 )
			{
				$row = mysql_fetch_object($result);
				$iso_code = $row->ISO_Code;
				$country = $row->ISO_Name;
			}
			else
			{
				$iso_code = '';
				$country = '';
			}
			// Log Visit
      $query = "Insert Into userslog (UserIP, PreviousURL, VisitedURL, ISO_Code, Country, UserName) ";
      $query .= "Values ('$user_ip','$previous_url','$visited_url','$iso_code','$country','$user_name')";
      // echo $query;
      mysql_query($query) or die(mysql_error());
    }
  }

  // This function is used to retrieve the counrty iso code, and name of each visitor
  function getVisitorCountryInfo()
  {
  	// $this->trace->info('Getting visitor country info', 'main');

    $user_ip = addslashes($_SERVER['REMOTE_ADDR']);

  	// Retrieve the country name according to the user ip
  	$IP = sprintf("%u", ip2long($user_ip));

		$query = "SELECT ISO_Code, ISO_Name FROM userslog_ip2ctry WHERE IP_From <= " . $IP  . " AND IP_To >= " . $IP;
		// echo $query;
		$result = mysql_query($query);
		if (!$result) {
  		die('Invalid query: ' . mysql_error());
		}
		if ( mysql_num_rows($result) > 0 )
		{
			$row = mysql_fetch_object($result);
			$countryInfo[0] = strtolower($row->ISO_Code);
			$countryInfo[1] = $row->ISO_Name;
		}
		else
		{
			$countryInfo[0] = '-';
			$countryInfo[1] = '';
		}

		return $countryInfo;
  }

}

?>