├── LICENSE ├── README.md ├── composer.json └── suncalc.php /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | 341 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | SunCalc PHP 2 | =========== 3 | 4 | SunCalc is a tiny PHP library for calculating sun position, 5 | sunlight phases (times for sunrise, sunset, dusk, etc.), 6 | moon position and lunar phase for the given location and time, 7 | based on the JavaScript library created by [Vladimir Agafonkin](http://agafonkin.com/en) ([@mourner](https://github.com/mourner)). 8 | 9 | Most calculations are based on the formulas given in the excellent Astronomy Answers articles 10 | about [position of the sun](http://aa.quae.nl/en/reken/zonpositie.html) 11 | and [the planets](http://aa.quae.nl/en/reken/hemelpositie.html). 12 | You can read about different twilight phases calculated by SunCalc 13 | in the [Twilight article on Wikipedia](http://en.wikipedia.org/wiki/Twilight). 14 | 15 | 16 | ## Usage example 17 | 18 | ```php 19 | // initialise library class with date and coordinates today's sunlight times for Paris 20 | $sc = new AurorasLive\SunCalc(new DateTime(), 48.85, 2.35); 21 | 22 | // format sunrise time from the DateTime object 23 | $sunTimes = $sc->getSunTimes(); 24 | $sunriseStr = $sunTimes['sunrise']->format('H:i'); 25 | 26 | // get position of the sun (azimuth and altitude) at today's sunrise 27 | $sunrisePos = $sc->getPosition($sunTimes['sunrise']); 28 | 29 | // get sunrise azimuth in degrees 30 | $sunriseAzimuth = $sunrisePos->azimuth * 180 / M_PI; 31 | ``` 32 | 33 | 34 | 35 | ## Reference 36 | 37 | ### Sunlight times 38 | 39 | ```php 40 | AurorasLive\SunCalc :: getSunTimes() 41 | ``` 42 | 43 | Returns an array with the following indexes (each is a `DateTime` object): 44 | 45 | | Property | Description | 46 | | --------------- | ------------------------------------------------------------------------ | 47 | | `sunrise` | sunrise (top edge of the sun appears on the horizon) | 48 | | `sunriseEnd` | sunrise ends (bottom edge of the sun touches the horizon) | 49 | | `goldenHourEnd` | morning golden hour (soft light, best time for photography) ends | 50 | | `solarNoon` | solar noon (sun is in the highest position) | 51 | | `goldenHour` | evening golden hour starts | 52 | | `sunsetStart` | sunset starts (bottom edge of the sun touches the horizon) | 53 | | `sunset` | sunset (sun disappears below the horizon, evening civil twilight starts) | 54 | | `dusk` | dusk (evening nautical twilight starts) | 55 | | `nauticalDusk` | nautical dusk (evening astronomical twilight starts) | 56 | | `night` | night starts (dark enough for astronomical observations) | 57 | | `nadir` | nadir (darkest moment of the night, sun is in the lowest position) | 58 | | `nightEnd` | night ends (morning astronomical twilight starts) | 59 | | `nauticalDawn` | nautical dawn (morning nautical twilight starts) | 60 | | `dawn` | dawn (morning nautical twilight ends, morning civil twilight starts) | 61 | 62 | `SunCalc::times` property contains all currently defined times. 63 | 64 | 65 | ### Sun position 66 | 67 | ```php 68 | AurorasLive\SunCalc :: getSunPosition(/*DateTime*/ $timeAndDate) 69 | ``` 70 | 71 | Returns an object with the following properties: 72 | 73 | * `altitude`: sun altitude above the horizon in radians, 74 | e.g. `0` at the horizon and `PI/2` at the zenith (straight over your head) 75 | * `azimuth`: sun azimuth in radians (direction along the horizon, measured from south to west), 76 | e.g. `0` is south and `M_PI * 3/4` is northwest 77 | 78 | 79 | ### Moon position 80 | 81 | ```php 82 | AurorasLive\SunCalc :: getMoonPosition(/*DateTime*/ $timeAndDate) 83 | ``` 84 | 85 | Returns an object with the following properties: 86 | 87 | * `altitude`: moon altitude above the horizon in radians 88 | * `azimuth`: moon azimuth in radians 89 | * `distance`: distance to moon in kilometers 90 | 91 | 92 | ### Moon illumination 93 | 94 | ```php 95 | AurorasLive\SunCalc :: getMoonIllumination() 96 | ``` 97 | 98 | Returns an array with the following properties: 99 | 100 | * `fraction`: illuminated fraction of the moon; varies from `0.0` (new moon) to `1.0` (full moon) 101 | * `phase`: moon phase; varies from `0.0` to `1.0`, described below 102 | * `angle`: midpoint angle in radians of the illuminated limb of the moon reckoned eastward from the north point of the disk; 103 | the moon is waxing if the angle is negative, and waning if positive 104 | 105 | Moon phase value should be interpreted like this: 106 | 107 | | Phase | Name | 108 | | -----:| --------------- | 109 | | 0 | New Moon | 110 | | | Waxing Crescent | 111 | | 0.25 | First Quarter | 112 | | | Waxing Gibbous | 113 | | 0.5 | Full Moon | 114 | | | Waning Gibbous | 115 | | 0.75 | Last Quarter | 116 | | | Waning Crescent | 117 | 118 | ### Moon rise and set times 119 | 120 | ```php 121 | AurorasLive\SunCalc :: getMoonTimes($inUTC) 122 | ``` 123 | 124 | Returns an object with the following indexes: 125 | 126 | * `rise`: moonrise time as `DateTime` 127 | * `set`: moonset time as `DateTime` 128 | * `alwaysUp`: `true` if the moon never rises/sets and is always _above_ the horizon during the day 129 | * `alwaysDown`: `true` if the moon is always _below_ the horizon 130 | 131 | By default, it will search for moon rise and set during local user's day (from 0 to 24 hours). 132 | If `$inUTC` is set to true, it will instead search the specified date from 0 to 24 UTC hours. 133 | 134 | ## Changelog 135 | 136 | #### 0.0.2 — 21 Aug, 2018 137 | 138 | - Make this into a class and add a composer.json file to allow use with things like Laravel 139 | 140 | #### 0.0.1 — 29 Jul, 2017 141 | 142 | - Preserve original timezone when passing in dates 143 | 144 | #### 0.0.0 — 30 Dec, 2015 145 | 146 | - First commit. 147 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "auroras-live/suncalc-php", 3 | "description": "Sun and moon calculations for PHP", 4 | "type": "library", 5 | "license": "GPLv2", 6 | "autoload": { 7 | "files": [ 8 | "suncalc.php" 9 | ] 10 | }, 11 | "authors": [{ 12 | "name": "David Gray and Greg Seth", 13 | "email": "david@auroras.live" 14 | }], 15 | "require": {} 16 | } 17 | -------------------------------------------------------------------------------- /suncalc.php: -------------------------------------------------------------------------------- 1 | getTimestamp() / daySec - 0.5 + J1970; } 45 | function fromJulian($j, $d) { 46 | if (!is_nan($j)) { 47 | $dt = new \DateTime("@".round(($j + 0.5 - J1970) * daySec)); 48 | $dt->setTimezone($d->getTimezone()); 49 | return $dt; 50 | } 51 | } 52 | function toDays($date) { return toJulian($date) - J2000; } 53 | 54 | function rightAscension($l, $b) { return atan2(sin($l) * cos(e) - tan($b) * sin(e), cos($l)); } 55 | function declination($l, $b) { return asin(sin($b) * cos(e) + cos($b) * sin(e) * sin($l)); } 56 | 57 | function azimuth($H, $phi, $dec) { return atan2(sin($H), cos($H) * sin($phi) - tan($dec) * cos($phi)); } 58 | function altitude($H, $phi, $dec) { return asin(sin($phi) * sin($dec) + cos($phi) * cos($dec) * cos($H)); } 59 | 60 | function siderealTime($d, $lw) { return rad * (280.16 + 360.9856235 * $d) - $lw; } 61 | 62 | // calculations for sun times 63 | function julianCycle($d, $lw) { return round($d - J0 - $lw / (2 * PI)); } 64 | 65 | function approxTransit($Ht, $lw, $n) { return J0 + ($Ht + $lw) / (2 * PI) + $n; } 66 | function solarTransitJ($ds, $M, $L) { return J2000 + $ds + 0.0053 * sin($M) - 0.0069 * sin(2 * $L); } 67 | 68 | function hourAngle($h, $phi, $d) { return acos((sin($h) - sin($phi) * sin($d)) / (cos($phi) * cos($d))); } 69 | 70 | // returns set time for the given sun altitude 71 | function getSetJ($h, $lw, $phi, $dec, $n, $M, $L) { 72 | $w = hourAngle($h, $phi, $dec); 73 | $a = approxTransit($w, $lw, $n); 74 | return solarTransitJ($a, $M, $L); 75 | } 76 | 77 | // general sun calculations 78 | function solarMeanAnomaly($d) { return rad * (357.5291 + 0.98560028 * $d); } 79 | function eclipticLongitude($M) { 80 | 81 | $C = rad * (1.9148 * sin($M) + 0.02 * sin(2 * $M) + 0.0003 * sin(3 * $M)); // equation of center 82 | $P = rad * 102.9372; // perihelion of the Earth 83 | 84 | return $M + $C + $P + PI; 85 | } 86 | 87 | function hoursLater($date, $h) { 88 | $dt = clone $date; 89 | return $dt->add( new DateInterval('PT'.round($h*3600).'S') ); 90 | } 91 | 92 | class DecRa { 93 | public $dec; 94 | public $ra; 95 | 96 | function __construct($d, $r) { 97 | $this->dec = $d; 98 | $this->ra = $r; 99 | } 100 | } 101 | 102 | class DecRaDist extends DecRa { 103 | public $dist; 104 | 105 | function __construct($d, $r, $dist) { 106 | parent::__construct($d, $r); 107 | $this->dist = $dist; 108 | } 109 | } 110 | 111 | class AzAlt { 112 | public $azimuth; 113 | public $altitude; 114 | 115 | function __construct($az, $alt) { 116 | $this->azimuth = $az; 117 | $this->altitude = $alt; 118 | } 119 | } 120 | 121 | class AzAltDist extends AzAlt { 122 | public $dist; 123 | 124 | function __construct($az, $alt, $dist) { 125 | parent::__construct($az, $alt); 126 | $this->dist = $dist; 127 | } 128 | } 129 | 130 | function sunCoords($d) { 131 | 132 | $M = solarMeanAnomaly($d); 133 | $L = eclipticLongitude($M); 134 | 135 | return new DecRa( 136 | declination($L, 0), 137 | rightAscension($L, 0) 138 | ); 139 | } 140 | 141 | function moonCoords($d) { // geocentric ecliptic coordinates of the moon 142 | 143 | $L = rad * (218.316 + 13.176396 * $d); // ecliptic longitude 144 | $M = rad * (134.963 + 13.064993 * $d); // mean anomaly 145 | $F = rad * (93.272 + 13.229350 * $d); // mean distance 146 | 147 | $l = $L + rad * 6.289 * sin($M); // longitude 148 | $b = rad * 5.128 * sin($F); // latitude 149 | $dt = 385001 - 20905 * cos($M); // distance to the moon in km 150 | 151 | return new DecRaDist( 152 | declination($l, $b), 153 | rightAscension($l, $b), 154 | $dt 155 | ); 156 | } 157 | 158 | 159 | class SunCalc { 160 | 161 | var $date; 162 | var $lat; 163 | var $lng; 164 | 165 | // sun times configuration (angle, morning name, evening name) 166 | private $times = [ 167 | [-0.833, 'sunrise', 'sunset' ], 168 | [ -0.3, 'sunriseEnd', 'sunsetStart' ], 169 | [ -6, 'dawn', 'dusk' ], 170 | [ -12, 'nauticalDawn', 'nauticalDusk'], 171 | [ -18, 'nightEnd', 'night' ], 172 | [ 6, 'goldenHourEnd', 'goldenHour' ] 173 | ]; 174 | 175 | // adds a custom time to the times config 176 | private function addTime($angle, $riseName, $setName) { 177 | $this->times[] = [$angle, $riseName, $setName]; 178 | } 179 | 180 | function __construct($date, $lat, $lng) { 181 | $this->date = $date; 182 | $this->lat = $lat; 183 | $this->lng = $lng; 184 | } 185 | 186 | // calculates sun position for a given date and latitude/longitude 187 | function getSunPosition() { 188 | 189 | $lw = rad * -$this->lng; 190 | $phi = rad * $this->lat; 191 | $d = toDays($this->date); 192 | 193 | $c = sunCoords($d); 194 | $H = siderealTime($d, $lw) - $c->ra; 195 | 196 | return new AzAlt( 197 | azimuth($H, $phi, $c->dec), 198 | altitude($H, $phi, $c->dec) 199 | ); 200 | } 201 | 202 | // calculates sun times for a given date and latitude/longitude 203 | function getSunTimes() { 204 | 205 | $lw = rad * -$this->lng; 206 | $phi = rad * $this->lat; 207 | 208 | $d = toDays($this->date); 209 | $n = julianCycle($d, $lw); 210 | $ds = approxTransit(0, $lw, $n); 211 | 212 | $M = solarMeanAnomaly($ds); 213 | $L = eclipticLongitude($M); 214 | $dec = declination($L, 0); 215 | 216 | $Jnoon = solarTransitJ($ds, $M, $L); 217 | 218 | $result = [ 219 | 'solarNoon'=> fromJulian($Jnoon, $this->date), 220 | 'nadir' => fromJulian($Jnoon - 0.5, $this->date) 221 | ]; 222 | 223 | for ($i = 0, $len = count($this->times); $i < $len; $i += 1) { 224 | $time = $this->times[$i]; 225 | 226 | $Jset = getSetJ($time[0] * rad, $lw, $phi, $dec, $n, $M, $L); 227 | $Jrise = $Jnoon - ($Jset - $Jnoon); 228 | 229 | $result[$time[1]] = fromJulian($Jrise, $this->date); 230 | $result[$time[2]] = fromJulian($Jset, $this->date); 231 | } 232 | 233 | return $result; 234 | } 235 | 236 | 237 | function getMoonPosition($date) { 238 | $lw = rad * -$this->lng; 239 | $phi = rad * $this->lat; 240 | $d = toDays($date); 241 | 242 | $c = moonCoords($d); 243 | $H = siderealTime($d, $lw) - $c->ra; 244 | $h = altitude($H, $phi, $c->dec); 245 | 246 | // altitude correction for refraction 247 | $h = $h + rad * 0.017 / tan($h + rad * 10.26 / ($h + rad * 5.10)); 248 | 249 | return new AzAltDist( 250 | azimuth($H, $phi, $c->dec), 251 | $h, 252 | $c->dist 253 | ); 254 | } 255 | 256 | 257 | function getMoonIllumination() { 258 | 259 | $d = toDays($this->date); 260 | $s = sunCoords($d); 261 | $m = moonCoords($d); 262 | 263 | $sdist = 149598000; // distance from Earth to Sun in km 264 | 265 | $phi = acos(sin($s->dec) * sin($m->dec) + cos($s->dec) * cos($m->dec) * cos($s->ra - $m->ra)); 266 | $inc = atan2($sdist * sin($phi), $m->dist - $sdist * cos($phi)); 267 | $angle = atan2(cos($s->dec) * sin($s->ra - $m->ra), sin($s->dec) * cos($m->dec) - cos($s->dec) * sin($m->dec) * cos($s->ra - $m->ra)); 268 | 269 | return [ 270 | 'fraction' => (1 + cos($inc)) / 2, 271 | 'phase' => 0.5 + 0.5 * $inc * ($angle < 0 ? -1 : 1) / PI, 272 | 'angle' => $angle 273 | ]; 274 | } 275 | 276 | function getMoonTimes($inUTC=false) { 277 | $t = clone $this->date; 278 | if ($inUTC) $t->setTimezone(new \DateTimeZone('UTC')); 279 | 280 | $t->setTime(0, 0, 0); 281 | 282 | $hc = 0.133 * rad; 283 | $h0 = $this->getMoonPosition($t, $this->lat, $this->lng)->altitude - $hc; 284 | $rise = 0; 285 | $set = 0; 286 | 287 | // go in 2-hour chunks, each time seeing if a 3-point quadratic curve crosses zero (which means rise or set) 288 | for ($i = 1; $i <= 24; $i += 2) { 289 | $h1 = $this->getMoonPosition(hoursLater($t, $i), $this->lat, $this->lng)->altitude - $hc; 290 | $h2 = $this->getMoonPosition(hoursLater($t, $i + 1), $this->lat, $this->lng)->altitude - $hc; 291 | 292 | $a = ($h0 + $h2) / 2 - $h1; 293 | $b = ($h2 - $h0) / 2; 294 | $xe = -$b / (2 * $a); 295 | $ye = ($a * $xe + $b) * $xe + $h1; 296 | $d = $b * $b - 4 * $a * $h1; 297 | $roots = 0; 298 | 299 | if ($d >= 0) { 300 | $dx = sqrt($d) / (abs($a) * 2); 301 | $x1 = $xe - $dx; 302 | $x2 = $xe + $dx; 303 | if (abs($x1) <= 1) $roots++; 304 | if (abs($x2) <= 1) $roots++; 305 | if ($x1 < -1) $x1 = $x2; 306 | } 307 | 308 | if ($roots === 1) { 309 | if ($h0 < 0) $rise = $i + $x1; 310 | else $set = $i + $x1; 311 | 312 | } else if ($roots === 2) { 313 | $rise = $i + ($ye < 0 ? $x2 : $x1); 314 | $set = $i + ($ye < 0 ? $x1 : $x2); 315 | } 316 | 317 | if ($rise != 0 && $set != 0) break; 318 | 319 | $h0 = $h2; 320 | } 321 | 322 | $result = []; 323 | 324 | if ($rise != 0) $result['moonrise'] = hoursLater($t, $rise); 325 | if ($set != 0) $result['moonset'] = hoursLater($t, $set); 326 | 327 | if ($rise==0 && $set==0) $result[$ye > 0 ? 'alwaysUp' : 'alwaysDown'] = true; 328 | 329 | return $result; 330 | } 331 | } 332 | 333 | // tests 334 | /* 335 | $test = new SunCalc(new \DateTime(), 48.85, 2.35); 336 | print_r($test->getSunTimes()); 337 | print_r($test->getMoonIllumination()); 338 | print_r($test->getMoonTimes()); 339 | print_r(getMoonPosition(new \DateTime(), 48.85, 2.35)); 340 | */ 341 | --------------------------------------------------------------------------------