* kumar mcmillan * * description: * do moon phase calculation stuff * You will see a slight drift in the cycle if you compare the results to other phase calculations... * this is probably because of different degrees of precision among phase periods used, as well as * float precision from computer to computer. It is more or less accurate and seems to always report the * correct phase name. Please let us know if you have any improvements, suggestions * or questions. Do not make modifications to this class in case the source changes (see moon-phase.php * for an example of usage). */ define('MP_NEW_MOON_NAME','New Moon'); define('MP_NEW_MOON_ID',0); define('MP_WAXING_CRESCENT_NAME','Waxing Crescent'); define('MP_WAXING_CRESCENT_ID',1); define('MP_FIRST_QUARTER_NAME','First Quarter Moon'); define('MP_FIRST_QUARTER_ID',2); define('MP_WAXING_GIBBOUS_NAME','Waxing Gibbous'); define('MP_WAXING_GIBBOUS_ID',3); define('MP_FULL_MOON_NAME','Full Moon'); define('MP_FULL_MOON_ID',4); define('MP_WANING_GIBBOUS_NAME','Waning Gibbous'); define('MP_WANING_GIBBOUS_ID',5); define('MP_THIRD_QUARTER_MOON_NAME','Third Quarter Moon'); define('MP_THIRD_QUARTER_MOON_ID',6); define('MP_WANING_CRESCENT_NAME','Waning Crescent'); define('MP_WANING_CRESCENT_ID',7); define('MP_DAY_IN_SECONDS', 60 * 60 * 24); class moonPhase { var $allMoonPhases = array(); var $dateAsTimeStamp; var $moonPhaseIDforDate; var $moonPhaseNameForDate; var $periodInDays = 29.53058867; // == complete moon cycle var $periodInSeconds = -1; // gets set when you ask for it var $someFullMoonDate; /* * CONSTRUCTOR * $timestamp (int) date of which to calculate a moon phase and relative phases for */ function moonPhase($timeStamp = -1) { $this->allMoonPhases = array( MP_NEW_MOON_NAME, MP_WAXING_CRESCENT_NAME, MP_FIRST_QUARTER_NAME, MP_WAXING_GIBBOUS_NAME, MP_FULL_MOON_NAME, MP_WANING_GIBBOUS_NAME, MP_THIRD_QUARTER_MOON_NAME, MP_WANING_CRESCENT_NAME); // set base date, that we know was a full moon: // (http://aa.usno.navy.mil/data/docs/MoonPhase.html) $this->someFullMoonDate = strtotime("August 22 2002 22:29 UT"); if($timeStamp == '' or $timeStamp == -1) $timeStamp = time(); $this->setDate($timeStamp); } // END function moonPhase($timeStamp = -1) { /* * PRIVATE * sets the moon phase ID and moon phase name internally */ function calcMoonPhase() { $position = $this->getPositionInCycle(); if($position >= 0.474 && $position <= 0.53) $phaseInfoForCurrentDate = array(MP_NEW_MOON_ID, MP_NEW_MOON_NAME); else if ($position >= 0.53 && $position <= 0.724) $phaseInfoForCurrentDate = array(MP_WAXING_CRESCENT_ID, MP_WAXING_CRESCENT_NAME); else if ($position >= 0.724 && $position <= 0.776) $phaseInfoForCurrentDate = array(MP_FIRST_QUARTER_ID, MP_FIRST_QUARTER_NAME); else if ($position >= 0.776 && $position <= 0.974) $phaseInfoForCurrentDate = array(MP_WAXING_GIBBOUS_ID, MP_WAXING_GIBBOUS_NAME); else if ($position >= 0.974 || $position <= 0.026) $phaseInfoForCurrentDate = array(MP_FULL_MOON_ID, MP_FULL_MOON_NAME); else if ($position >= 0.026 && $position <= 0.234) $phaseInfoForCurrentDate = array(MP_WANING_GIBBOUS_ID, MP_WANING_GIBBOUS_NAME); else if ($position >= 0.234 && $position <= 0.295) $phaseInfoForCurrentDate = array(MP_THIRD_QUARTER_MOON_ID, MP_THIRD_QUARTER_MOON_NAME); else if ($position >= 0.295 && $position <= 0.4739) $phaseInfoForCurrentDate = array(MP_WANING_CRESCENT_ID, MP_WANING_CRESCENT_NAME); list($this->moonPhaseIDforDate,$this->moonPhaseNameForDate) = $phaseInfoForCurrentDate; } // END function calcMoonPhase() { /* * PUBLIC * return (array) all moon phases as ID => Name */ function getAllMoonPhases() { return $this->allMoonPhases; } // END function getAllMoonPhases() { /* * PUBLIC */ function getBaseFullMoonDate() { return $this->someFullMoonDate; } // END function getBaseFullMoonDate() { /* * PUBLIC * return (int) timestamp of the current date being calculated */ function getDateAsTimeStamp() { return $this->dateAsTimeStamp; } // END function getDateAsTimeStamp() { /* * PUBLIC */ function getDaysUntilNextFullMoon() { $position = $this->getPositionInCycle(); return round((1 - $position) * $this->getPeriodInDays(), 2); } // ENDfunction getDaysUntilNextFullMoon() { /* * PUBLIC */ function getDaysUntilNextLastQuarterMoon() { $days = 0; $position = $this->getPositionInCycle(); if ($position < 0.25) $days = (0.25 - $position) * $this->getPeriodInDays(); else if ($position >= 0.25) $days = (1.25 - $position) * $this->getPeriodInDays(); return round($days, 1); } // END function getDaysUntilNextLastQuarterMoon() { /* * PUBLIC */ function getDaysUntilNextFirstQuarterMoon() { $days = 0; $position = $this->getPositionInCycle(); if ($position < 0.75) $days = (0.75 - $position) * $this->getPeriodInDays(); else if ($position >= 0.75) $days = (1.75 - $position) * $this->getPeriodInDays(); return round($days,1); } // END function getDaysUntilNextFirstQuarterMoon() { /* * PUBLIC */ function getDaysUntilNextNewMoon() { $days = 0; $position = $this->getPositionInCycle(); if ($position < 0.5) $days = (0.5 - $position) * $this->getPeriodInDays(); else if ($position >= 0.5) $days = (1.5 - $position) * $this->getPeriodInDays(); return round($days, 1); } // END function getDaysUntilNextNewMoon() { /* * PUBLIC * returns the percentage of how much lunar face is visible */ function getPercentOfIllumination() { // from http://www.lunaroutreach.org/cgi-src/qpom/qpom.c // C version: // return (1.0 - cos((2.0 * M_PI * phase) / (LPERIOD/ 86400.0))) / 2.0; $percentage = (1.0 + cos(2.0 * M_PI * $this->getPositionInCycle())) / 2.0; $percentage *= 100; $percentage = round($percentage,1) . '%'; return $percentage; } // END function getPercentOfIllumination() /* * PUBLIC */ function getPeriodInDays() { return $this->periodInDays; } // END function getPeriodInDays() { /* * PUBLIC */ function getPeriodInSeconds() { if($this->periodInSeconds > -1) return $this->periodInSeconds; // in case it was cached $this->periodInSeconds = $this->getPeriodInDays() * MP_DAY_IN_SECONDS; return $this->periodInSeconds; } // END function getPeriodInSeconds() { /* * PUBLIC */ function getPhaseID() { return $this->moonPhaseIDforDate; } // EMD function getPhaseID() { /* * PUBLIC * $ID (int) ID of phase, default is to get the phase for the current date passed in constructor */ function getPhaseName($ID = -1) { if($ID <= -1) return $this->moonPhaseNameForDate; // get name for this current date return $this->allMoonPhases[$ID]; // or.. get name for a specific ID } // END function getPhaseName() { /* * PUBLIC * return (float) number between 0 and 1. 0 or 1 is the beginning of a cycle (full moon) * and 0.5 is the middle of a cycle (new moon). */ function getPositionInCycle() { $diff = $this->getDateAsTimeStamp() - $this->getBaseFullMoonDate(); $periodInSeconds = $this->getPeriodInSeconds(); $position = ($diff % $periodInSeconds) / $periodInSeconds; if ($position < 0) $position = 1 + $position; return $position; } // END function getPositionInCycle() { /* * PUBLIC * $newStartingDateAsTimeStamp (int) set a new date to start the week at, or use the current date * return (array[6]) weekday timestamp => phase for weekday */ function getUpcomingWeekArray($newStartingDateAsTimeStamp = -1) { $newStartingDateAsTimeStamp = ($newStartingDateAsTimeStamp > -1) ? $newStartingDateAsTimeStamp : $this->getDateAsTimeStamp(); $moonPhaseObj = get_class($this); $weeklyPhase = new $moonPhaseObj($newStartingDateAsTimeStamp); $upcomingWeekArray = array(); for( $day = 0, $thisTimeStamp = $weeklyPhase->getDateAsTimeStamp(); $day < 7; $day++, $thisTimeStamp += MP_DAY_IN_SECONDS) { $weeklyPhase->setDate($thisTimeStamp); $upcomingWeekArray[$thisTimeStamp] = $weeklyPhase->getPhaseID(); } // END for($day = 0; $day < 7; $day++) { unset($weeklyPhase); return $upcomingWeekArray; } // END function getUpcomingWeekArray($newStartingDateAsTimeStamp = -1) { /* * PUBLIC * sets the internal date for calculation and calulates the moon phase for that date. * called from the constructor. * $timeStamp (int) date to set as unix timestamp */ function setDate($timeStamp = -1) { if($timeStamp == '' or $timeStamp == -1) $timeStamp = time(); $this->dateAsTimeStamp = $timeStamp; $this->calcMoonPhase(); } // END function setDate($timeStamp) { } // END class moonPhase { ?> > www.voegeli.li >> fly forward! >> // Date: 28-Oct-2005 // License/ // Usage: Open Source / for free //============================================================================ // DEPENDENCIES: // - It requires the class "xmlParser" (Be lucky: Also in the Archive file!) //============================================================================ // DESCRIPTION: // This Class gets Weather RSS from WEATHER.YAHOO.COM and parses it into // a weather object with usable attributes. Use it for: // // - Actual Situation (temperature/sunrise/sunset/Image...) // - Forecast Day 1 (temp low, high/text/date/day/image...) // - Forecast Day 2 (temp low, high/text/date/day/image...) // // PUBLIC METHODS // - parse() : Gets the XML File parses it and fills attributes // - parsecahed() : Much quicker!!! Writes a cached version to a local // file with expiry date! expiry date is calculated // with the given input parameter // //============================================================================ // SAMPLE: // - See the file "weather.test.php" in this archive for Santiago de Chile // // WEB GUI URL: http://weather.yahoo.com/forecast/CIXX0020_c.html?force_units=1 // RSS URL: http://xml.weather.yahoo.com/forecastrss?u=C&p=CIXX0020 // // The class needs one Attribute in the Constructor Method: // // $weather_chile = new weather("CIXX0020", 60); // // "CIXX0020" is the Yahoo code for Santiago de Chile. See WEB GUI URL above! // // "60" means 60 seconds until the cache expires. If not needed set = 0. // // GO TO WEATHER.YAHOO.COM and search for your desired weather location. If // found, click on the location link (must see the forecast). Now take // the code from the URL in your browsers address field. // //============================================================================ // Changes: // - 19.11.2005 MAV : XML Feed Structure from Yahoo changed. Adapted script. //============================================================================ // Visit http://dowdybrown.com , the contributor of the new version. Thank you // Matt for this great and better version of the yahoo weather class! You have // done a good job! //============================================================================ class weather { // ------------------- // ATTRIBUTES DECLARATION // ------------------- // HANDLING ATTRIBUTES var $locationcode; // Yahoo Code for Location var $allurl; // generated url with location var $parser; // Instance of Class XML Parser var $unit; // F or C / Fahrenheit or Celsius // CACHING ATTRIBUTES var $cache_expires; var $cache_lifetime; var $source; // cache or live var $forecast=array(); // ------------------- // CONSTRUCTOR METHOD // ------------------- function weather($location, $lifetime, $unit, $cachedir) { // Set Lifetime / Locationcode $this->cache_lifetime = $lifetime; $this->locationcode = $location; $this->unit = $unit; $this->cachedir = $cachedir; $this->filename = $cachedir . $location; } // ------------------- // FUNCTION PARSE // ------------------- function parse() { $this->allurl = "http://xml.weather.yahoo.com/forecastrss"; $this->allurl .= "?u=" . $this->unit; $this->allurl .= "&p=" . $this->locationcode; // Create Instance of XML Parser Class // and parse the XML File $this->parser = new xmlParser(); $this->parser->parse($this->allurl); $content=&$this->parser->output[0]['child'][0]['child']; foreach ($content as $item) { //print "
";
  //print_r($item);
  //print "

"; switch ($item['name']) { case 'TITLE': case 'LINK': case 'DESCRIPTION': case 'LANGUAGE': case 'LASTBUILDDATE': $this->forecast[$item['name']]=$item['content']; break; case 'YWEATHER:LOCATION': case 'YWEATHER:UNITS': case 'YWEATHER:ASTRONOMY': foreach ($item['attrs'] as $attr=>$value) $this->forecast[$attr]=$value; break; case 'IMAGE': break; case 'ITEM': foreach ($item['child'] as $detail) { switch ($detail['name']) { case 'GEO:LAT': case 'GEO:LONG': case 'PUBDATE': $this->forecast[$detail['name']]=$detail['content']; break; case 'YWEATHER:CONDITION': $this->forecast['CURRENT']=$detail['attrs']; break; case 'YWEATHER:FORECAST': array_push($this->forecast,$detail['attrs']); break; } } break; } } $this->source = 'live'; // FOR DEBUGGING PURPOSES //print "
";
//print_r($this->forecast);
//print "

"; } // ------------------- // WRITE OBJECT TO CACHE // ------------------- function writecache() { unset($this->parser); $this->cache_expires = time() + $this->cache_lifetime; $fp = fopen($this->filename, "w"); fwrite($fp, serialize($this)); fclose($fp); } // ------------------- // READ OBJECT FROM CACHE // ------------------- function readcache() { $content=@file_get_contents($this->filename); if ($content==false) return false; $intweather = unserialize($content); if ($intweather->cache_expires < time()) return false; $this->source = 'cache'; $this->forecast = $intweather->forecast; return true; } // ------------------- // FUNCTION PARSECACHED // ------------------- function parsecached() { if ($this->readcache()) return; $this->parse(); $this->writecache(); } } // class : end ?>xml_obj = xml_parser_create(); xml_set_object($this->xml_obj,$this); xml_set_character_data_handler($this->xml_obj, 'dataHandler'); xml_set_element_handler($this->xml_obj, "startHandler", "endHandler"); } // *** ---------------------------------------------------------------- function parse($path){ if (!($fp = fopen($path, "r"))) { die("Cannot open XML data file: $path"); return false; } while ($data = fread($fp, 4096)) { if (!xml_parse($this->xml_obj, $data, feof($fp))) { die(sprintf("XML error: %s at line %d", xml_error_string(xml_get_error_code($this->xml_obj)), xml_get_current_line_number($this->xml_obj))); xml_parser_free($this->xml_obj); } } return true; } // *** ---------------------------------------------------------------- function startHandler($parser, $name, $attribs){ $_content = array('name' => $name); if(!empty($attribs)) $_content['attrs'] = $attribs; array_push($this->output, $_content); } // *** ---------------------------------------------------------------- function dataHandler($parser, $data){ if(!empty($data)) { $_output_idx = count($this->output) - 1; $this->output[$_output_idx]['content'] = $data; } } // *** ---------------------------------------------------------------- function endHandler($parser, $name){ if(count($this->output) > 1) { $_data = array_pop($this->output); $_output_idx = count($this->output) - 1; $this->output[$_output_idx]['child'][] = $_data; } } // *** ---------------------------------------------------------------- function GetNodeByPath($path,$tree = false) { if ($tree) { $tree_to_search = $tree; } else { $tree_to_search = $this->output; } if ($path == "") { return null; } $arrPath = explode('/',$path); foreach($tree_to_search as $key => $val) { if (gettype($val) == "array") { $nodename = $val[name]; if ($nodename == $arrPath[0]) { if (count($arrPath) == 1) { return $val; } array_shift($arrPath); $new_path = implode($arrPath,"/"); return $this->GetNodeByPath($new_path,$val[child]); } } } } } // class : end ?> dbh = @mysql_connect($dbhost,$dbuser,$dbpassword); if ( ! $this->dbh ) { $this->print_error("
    Error establishing a database connection!
  1. Are you sure you have the correct user/password?
  2. Are you sure that you have typed the correct hostname?
  3. Are you sure that the database server is running?
"); } $this->select($dbname); } // ================================================================== // Select a DB (if another one needs to be selected) function select($db) { if ( !@mysql_select_db($db,$this->dbh)) { $this->print_error("
    Error selecting database $db!
  1. Are you sure it exists?
  2. Are you sure there is a valid database connection?
"); } } // ================================================================== // Print SQL/DB error. function print_error($str = "") { if ( !$str ) $str = mysql_error(); // If there is an error then take note of it print "
"; print "SQL/DB Error -- "; print "[$str]"; print "
"; } // ================================================================== // Basic Query - see docs for more detail function query($query, $output = OBJECT) { // Log how the function was called $this->func_call = "\$db->query(\"$query\", $output)"; // Kill this $this->last_result = null; $this->col_info = null; // Keep track of the last query for debug.. $this->last_query = $query; // Perform the query via std mysql_query function.. $this->result = mysql_query($query,$this->dbh); if ( mysql_error() ) { // If there is an error then take note of it.. $this->print_error(); } else { // In other words if this was a select statement.. if ( $this->result ) { // ======================================================= // Take note of column info $i=0; while ($i < @mysql_num_fields($this->result)) { $this->col_info[$i] = @mysql_fetch_field($this->result); $i++; } // ======================================================= // Store Query Results $i=0; while ( $row = @mysql_fetch_object($this->result) ) { // Store relults as an objects within main array $this->last_result[$i] = $row; $i++; } @mysql_free_result($this->result); // If there were results then return true for $db->query if ( $i ) { return true; } else { return false; } } } } // ================================================================== // Get one variable from the DB - see docs for more detail function get_var($query=null,$x=0,$y=0) { // Log how the function was called $this->func_call = "\$db->get_var(\"$query\",$x,$y)"; // If there is a query then perform it if not then use cached results.. if ( $query ) { $this->query($query); } // Extract var out of cached results based x,y vals if ( $this->last_result[$y] ) { $values = array_values(get_object_vars($this->last_result[$y])); } // If there is a value return it else return null return $values[$x]?$values[$x]:null; } // ================================================================== // Get one row from the DB - see docs for more detail function get_row($query=null,$y=0,$output=OBJECT) { // Log how the function was called $this->func_call = "\$db->get_row(\"$query\",$y,$output)"; // If there is a query then perform it if not then use cached results.. if ( $query ) { $this->query($query); } // If the output is an object then return object using the row offset.. if ( $output == OBJECT ) { return $this->last_result[$y]?$this->last_result[$y]:null; } // If the output is an associative array then return row as such.. elseif ( $output == ARRAY_A ) { return $this->last_result[$y]?get_object_vars($this->last_result[$y]):null; } // If the output is an numerical array then return row as such.. elseif ( $output == ARRAY_N ) { return $this->last_result[$y]?array_values(get_object_vars($this->last_result[$y])):null; } // If invalid output type was specified.. else { $this->print_error(" \$db->get_row(string query,int offset,output type) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N "); } } // ================================================================== // Function to get 1 column from the cached result set based in X index // se docs for usage and info function get_col($query=null,$x=0) { // If there is a query then perform it if not then use cached results.. if ( $query ) { $this->query($query); } // Extract the column values for ( $i=0; $i < count($this->last_result); $i++ ) { $new_array[$i] = $this->get_var(null,$x,$i); } return $new_array; } // ================================================================== // Return the the query as a result set - see docs for more details function get_results($query=null, $output = OBJECT) { // Log how the function was called $this->func_call = "\$db->get_results(\"$query\", $output)"; // If there is a query then perform it if not then use cached results.. if ( $query ) { $this->query($query); } // Send back array of objects. Each row is an object if ( $output == OBJECT ) { return $this->last_result; } elseif ( $output == ARRAY_A || $output == ARRAY_N ) { if ( $this->last_result ) { $i=0; foreach( $this->last_result as $row ) { $new_array[$i] = get_object_vars($row); if ( $output == ARRAY_N ) { $new_array[$i] = array_values($new_array[$i]); } $i++; } return $new_array; } else { return null; } } } // ================================================================== // Function to get column meta data info pertaining to the last query // see docs for more info and usage function get_col_info($info_type="name",$col_offset=-1) { if ( $this->col_info ) { if ( $col_offset == -1 ) { $i=0; foreach($this->col_info as $col ) { $new_array[$i] = $col->{$info_type}; $i++; } return $new_array; } else { return $this->col_info[$col_offset]->{$info_type}; } } } // ================================================================== // Dumps the contents of any input variable to screen in a nicely // formatted and easy to understand way - any type: Object, Var or Array function vardump($mixed) { echo "
"; echo "
";

			if ( ! $this->vardump_called )
			{
				echo "ezSQL (v".EZSQL_VERSION.") Variable Dump..\n\n";
			}

			print_r($mixed);
			echo "\n\nLast Query: ".($this->last_query?$this->last_query:"NULL")."\n";
			echo "Last Function Call: " . ($this->func_call?$this->func_call:"None")."\n";
			echo "Last Rows Returned: ".count($this->last_result)."\n";
			echo "
"; echo "\n
"; $this->vardump_called = true; } // Alias for the above function function dumpvars($mixed) { $this->vardump($mixed); } // ================================================================== // Displays the last query string that was sent to the database & a // table listing results (if there were any). // (abstracted into a seperate file to save server overhead). function debug() { echo "
"; // Only show ezSQL credits once.. if ( ! $this->debug_called ) { echo "ezSQL (v".EZSQL_VERSION.") Debug..

\n"; } echo "Query -- "; echo "[$this->last_query]

"; echo "Query Result.."; echo "

"; if ( $this->col_info ) { // ===================================================== // Results top rows echo ""; echo ""; for ( $i=0; $i < count($this->col_info); $i++ ) { echo ""; } echo ""; // ====================================================== // print main results if ( $this->last_result ) { $i=0; foreach ( $this->get_results(null,ARRAY_N) as $one_row ) { $i++; echo ""; foreach ( $one_row as $item ) { echo ""; } echo ""; } } // if last result else { echo ""; } echo "
(row){$this->col_info[$i]->type} {$this->col_info[$i]->max_length}
{$this->col_info[$i]->name}
$i$item
No Results
"; } // if col_info else { echo "No Results"; } echo "

"; $this->debug_called = true; } } $db = new db(EZSQL_DB_USER, EZSQL_DB_PASSWORD, EZSQL_DB_NAME, EZSQL_DB_HOST); ?>