sTicKs23

MOD Sp Weather behind proxy

Mar 20th, 2026
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 21.89 KB | None | 0 0
  1. <?php
  2. /**
  3.  * @package mod_sp_weather
  4.  * @author JoomShaper http://www.joomshaper.com
  5.  * @copyright Copyright (c) 2010 - 2024 JoomShaper
  6.  * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 or later
  7. */
  8.  
  9. //no direct access
  10. defined ('_JEXEC') or die ('Restricted access');
  11.  
  12. use Joomla\CMS\Language\Text;
  13. use Joomla\CMS\Filesystem\Folder;
  14.  
  15. class modSPWeatherHelper {
  16.  
  17.     private $results = array('status'=> false);
  18.     private $errors  = false;
  19.     private $location;
  20.     private $forecast_limit;
  21.     private $getdataby;
  22.     private $location_id;
  23.     private $location_ip;
  24.     private $location_latlon;
  25.     private $api_key;
  26.     private $y_appid;
  27.     private $y_clientid;
  28.     private $y_clientsecret;
  29.     private $platform;
  30.     private $params;
  31.     private $moduleID;
  32.     private $moduledir;
  33.     private $api;
  34.     private $cache_time;
  35.     private $nightIDs = array(27,29,31,33);
  36.     private $iconURL = 'https://openweathermap.org/img/w/%s.png';
  37.  
  38.     /**
  39.     * Init Class Params
  40.     *
  41.     * @param object $params
  42.     * @param int $id
  43.     */
  44.     public function __construct($params, $id) {
  45.         $this->params           = $params;
  46.         $this->moduleID         = $id;
  47.         $this->moduledir        = basename(dirname(__FILE__));
  48.         $this->location         = str_replace(', ', ',', $this->params->get('location', 'London,GB'));
  49.         $this->forecast_limit   = $this->params->get('forecast', '7');
  50.         $this->getdataby        = $this->params->get('getdataby', 'locaion_name');
  51.         $this->location_id      = $this->params->get('locationid', '2643743');
  52.         $this->location_latlon  = $this->params->get('location_latlon', '48.139130, 11.580220');
  53.         $this->location_ip      = $this->params->get('location_ip', '88.198.50.103');
  54.         $this->platform         = $this->params->get('platform', 'openweathermap');
  55.         $this->cache_time       = $this->params->get('cacheTime', '900');
  56.         $this->api_key          = $this->params->get('api_key', '');
  57.         // yahoo
  58.         $this->y_appid        = $this->params->get('y_app_id', '3vYYEy30');
  59.         $this->y_clientid     = $this->params->get('y_client_id', 'dj0yJmk9NFZaM2lMQUpvWUlpJmQ9WVdrOU0zWlpXVVY1TXpBbWNHbzlNQS0tJnM9Y29uc3VtZXJzZWNyZXQmeD02ZQ--');
  60.         $this->y_clientsecret = $this->params->get('y_client_secret', 'f72fcfd3cbda626223778eb01af31f2cb1e2cfa9');
  61.  
  62.         //icon
  63.         if( $this->platform ==  'weatherbit' ) {
  64.             $this->iconURL = 'https://www.weatherbit.io/static/img/icons/%s.png';
  65.         } elseif( $this->platform ==  'darksky' ) {
  66.             $this->iconURL = 'https://darksky.net/images/weather-icons/%s.png';
  67.         } elseif( $this->platform ==  'yahoo' ) {
  68.             $this->iconURL = 'https://s.yimg.com/os/mit/media/m/weather/images/icons/l/%d%s-100567.png';
  69.         }
  70.  
  71.         // get current data
  72.         $this->results['current']  = $this->_getWeatherData('current');
  73.  
  74.         // load current
  75.         if($data_decode = json_decode($this->results['current'])) {
  76.             if ($this->platform == 'weatherbit') {
  77.                 if (isset($data_decode->data) && count((array)$data_decode->data)) {
  78.                     $this->results['status'] = true;
  79.                     $this->results['current'] = $data_decode;
  80.                 }
  81.             } elseif ($this->platform == 'darksky') {
  82.                 if (isset($data_decode->currently) && count((array)$data_decode->currently)) {
  83.                     $this->results['status'] = true;
  84.                     $this->results['current'] = $data_decode;
  85.                 }
  86.             } elseif ($this->platform == 'yahoo') {
  87.                 if (isset($data_decode->current) && count((array)$data_decode->current)) {
  88.                     $this->results['status'] = true;
  89.                     $this->results['current'] = $data_decode;
  90.                 }
  91.             } else {
  92.                 if (isset($data_decode->main) && count((array)$data_decode->main)) {
  93.                     $this->results['status'] = true;
  94.                     $this->results['current'] = $data_decode;
  95.                 }
  96.                 else
  97.                 {
  98.                     $this->results['status'] = true;
  99.                     $this->results['current'] = $data_decode->current;
  100.                 }
  101.             }
  102.         } else {
  103.             $this->throwError('CANNOT_DECODE_CURRENT_DATA');
  104.         }
  105.  
  106.         // get forecast
  107.         if($this->forecast_limit != 'disabled') { // if forecast is enable
  108.             $this->results['forecast']  = $this->_getWeatherData('forecast');
  109.             if($forecast_decode = json_decode($this->results['forecast']))  {
  110.                 if ($this->platform == 'weatherbit') {
  111.                     if( count((array)$forecast_decode->data) && $forecast_decode->data ) {
  112.                         $this->results['forecast_status'] = true;
  113.                         $this->results['forecast'] = (object) $forecast_decode;
  114.                     } else {
  115.                         $this->throwError('CANNOT_FIND_FORECAST_DATA');
  116.                     }
  117.                 } elseif ($this->platform == 'darksky') {
  118.                     if( count((array)$forecast_decode->daily->data) && $forecast_decode->daily->data ) {
  119.                         $this->results['forecast_status'] = true;
  120.                         $this->results['forecast'] = (object) $forecast_decode;
  121.                     } else {
  122.                         $this->throwError('CANNOT_FIND_FORECAST_DATA');
  123.                     }
  124.                 } elseif ($this->platform == 'yahoo') {
  125.                     if( count((array)$forecast_decode->forecasts) && $forecast_decode->forecasts ) {
  126.                         $this->results['forecast_status'] = true;
  127.                         $this->results['forecast'] = (object) $forecast_decode;
  128.                     } else {
  129.                         $this->throwError('CANNOT_FIND_FORECAST_DATA');
  130.                     }
  131.                 } else {
  132.                     if( count((array)$forecast_decode->daily) && $forecast_decode->daily ) {
  133.                         $this->results['forecast_status'] = true;
  134.                         $this->results['forecast'] = (object) $forecast_decode;
  135.                     } else {
  136.                         $this->throwError('CANNOT_FIND_FORECAST_DATA');
  137.                     }
  138.                 }
  139.             } else {
  140.                 $this->throwError('CANNOT_DECODE_FORECAST_DATA');
  141.             }
  142.         }
  143.  
  144.     }
  145.  
  146.     //Get Weather data
  147.     private function _getWeatherData($type = 'current') {
  148.         if($type == 'forecast') {
  149.             $this->forecast_limit +=1;
  150.             if ($this->platform == 'weatherbit') {
  151.                 if($this->getdataby == 'latlon') {
  152.                     $location_latlon = explode(',', str_replace(', ', ',', $this->location_latlon));
  153.                     $this->api = 'https://api.weatherbit.io/v2.0/forecast/daily?lat='. $location_latlon[0] .'&lon='. $location_latlon[1] .'&units=m&days='. $this->forecast_limit .'&key=' . $this->api_key;
  154.                 } elseif($this->getdataby == 'ip') {
  155.                     $this->api = 'https://api.weatherbit.io/v2.0/forecast/daily?ip='. $this->location_ip .'&units=m&days='. $this->forecast_limit .'&key=' . $this->api_key;
  156.                 } else {
  157.                     $this->api = 'https://api.weatherbit.io/v2.0/forecast/daily?city='. $this->location .'&units=m&days='. $this->forecast_limit .'&key=' . $this->api_key;
  158.                 }
  159.             } elseif ($this->platform == 'darksky') {
  160.                 $this->api  = 'https://api.darksky.net/forecast/' . $this->api_key .'/'. $this->location_latlon .'?exclude=currently,flags,hourly,minutely&lang=bn';
  161.             } elseif ($this->platform == 'yahoo') {
  162.                 $this->api  = 'https://weather-ydn-yql.media.yahoo.com/forecastrss';
  163.             } else {
  164.                 if ($this->getdataby == 'latlon')
  165.                 {
  166.                     $location_latlon = explode(',', str_replace(', ', ',', $this->location_latlon));
  167.                     $this->api  = 'https://api.openweathermap.org/data/2.5/onecall?lat='. $location_latlon[0] .'&lon='. $location_latlon[1] .'&exclude=current,minutely,hourly,alerts&units=metric&appid=' . $this->api_key;
  168.                 }
  169.             }
  170.         } else {
  171.             if ($this->platform == 'weatherbit') {
  172.                 if($this->getdataby == 'latlon') {
  173.                     $location_latlon = explode(',', str_replace(', ', ',', $this->location_latlon));
  174.                     $this->api  = 'https://api.weatherbit.io/v2.0/current?lat='. $location_latlon[0] .'&lon='. $location_latlon[1] .'&key=' . $this->api_key;
  175.                 } elseif($this->getdataby == 'ip') {
  176.                     $this->api  = 'https://api.weatherbit.io/v2.0/current?ip='. $this->location_ip .'&key=' . $this->api_key;
  177.                 } else {
  178.                     $this->api  = 'https://api.weatherbit.io/v2.0/current?city='. $this->location .'&key=' . $this->api_key;
  179.                 }
  180.             } elseif ($this->platform == 'darksky') {
  181.                 $this->api  = 'https://api.darksky.net/forecast/' . $this->api_key .'/'. $this->location_latlon .'?exclude=daily,flags,hourly,minutely';
  182.             } elseif ($this->platform == 'yahoo') {
  183.                 $this->api  = 'https://weather-ydn-yql.media.yahoo.com/forecastrss';
  184.             } else {
  185.                 if($this->getdataby == 'locaion_id') {
  186.                     $this->api       = 'http://api.openweathermap.org/data/2.5/weather?id='. $this->locationid .'&units=metric&appid=' . $this->api_key;
  187.                 }
  188.                 elseif ($this->getdataby == 'latlon')
  189.                 {
  190.                     $location_latlon = explode(',', str_replace(', ', ',', $this->location_latlon));
  191.                     $this->api  = 'https://api.openweathermap.org/data/2.5/onecall?lat='. $location_latlon[0] .'&lon='. $location_latlon[1] .'&exclude=minutely,hourly,daily,alerts&units=metric&appid=' . $this->api_key;
  192.                 }
  193.                 else {
  194.                     $this->api  = 'https://api.openweathermap.org/data/2.5/weather?q='. $this->location .'&units=metric&appid=' . $this->api_key;
  195.                 }
  196.             }
  197.         }
  198.  
  199.         $results['data'] = array();
  200.         // check cache dir or create cache dir
  201.         $cache_path = JPATH_CACHE.'/'.$this->moduledir;
  202.         if (!Folder::exists($cache_path)){
  203.             Folder::create(JPATH_CACHE.'/'.$this->moduledir.'/');
  204.         }
  205.  
  206.         if ($type == 'forecast') { // if data is forecast
  207.             $cache_file = JPATH_CACHE.'/'.$this->moduledir.'/'.$this->moduleID.'-'.'forecast.json';
  208.         } else { // if data is current weather
  209.             $cache_file = JPATH_CACHE.'/'.$this->moduledir.'/'.$this->moduleID.'-'.'current.json';
  210.         }
  211.  
  212.         // check cache file is exist and time isn't over:: default time is: 30 mins
  213.         if (file_exists($cache_file) && (filemtime($cache_file) > (time() - 60 * $this->cache_time ))) {
  214.             $results['data'] =  file_get_contents($cache_file);
  215.                 } else {
  216.             if($this->platform == 'yahoo') {
  217.                 $results['data'] = self::getYahooWeatherData();
  218.                 $data_decode = json_decode($results['data']);
  219.  
  220.                 if($data_decode) {
  221.                     if ($type == 'forecast') {
  222.                         $forecast_data = array();
  223.                         $forecast_data['location']  = $data_decode->location;
  224.                         $forecast_data['forecasts'] = $data_decode->forecasts;
  225.                         $results['data'] = json_encode($forecast_data);
  226.                     } else {
  227.                         $current_data = array();
  228.                         $current_data['location']   = $data_decode->location;
  229.                         $current_data['current']    = $data_decode->current_observation;
  230.                         $results['data']            = json_encode($current_data);
  231.                     }
  232.                 } else {
  233.                     $this->throwError($results['data'],'',true);
  234.                     return false;
  235.                 }
  236.  
  237.             } else {
  238.                 $results['data'] = $this->curl($this->api);
  239.                
  240.                 if ($results['data'] === false || empty($results['data'])) {
  241.                     $this->throwError('MAKESURE_FOPEN_OR_LCOATION', $this->platform);
  242.                 }
  243.             }
  244.  
  245.             if( isset($results['data']) && !empty($results['data']) && count((array)$results['data']) ) {
  246.                 file_put_contents($cache_file, $results['data'], LOCK_EX);
  247.             }
  248.         }
  249.  
  250.         return $results['data'];
  251.     }
  252.  
  253.     // *** **** Yahoo **** *** //
  254.     protected function buildBaseString($baseURI, $method, $params) {
  255.         $r = array();
  256.         ksort($params);
  257.         foreach($params as $key => $value) {
  258.             $r[] = "$key=" . rawurlencode($value);
  259.         }
  260.         return $method . "&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
  261.     }
  262.     protected function buildAuthorizationHeader($oauth) {
  263.         $r = 'Authorization: OAuth ';
  264.         $values = array();
  265.         foreach($oauth as $key=>$value) {
  266.             $values[] = "$key=\"" . rawurlencode($value) . "\"";
  267.         }
  268.         $r .= implode(', ', $values);
  269.         return $r;
  270.     }
  271.  
  272.     protected function getYahooWeatherData( ) {
  273.         $query = array(
  274.             'location' => $this->location,
  275.             'format' => 'json',
  276.         );
  277.         $oauth = array(
  278.             'oauth_consumer_key' => $this->y_clientid,
  279.             'oauth_nonce' => uniqid(mt_rand(1, 1000)),
  280.             'oauth_signature_method' => 'HMAC-SHA1',
  281.             'oauth_timestamp' => time(),
  282.             'oauth_version' => '1.0'
  283.         );
  284.         $base_info = self::buildBaseString($this->api, 'GET', array_merge($query, $oauth));
  285.  
  286.         $composite_key = rawurlencode($this->y_clientsecret) . '&';
  287.         $oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
  288.         $oauth['oauth_signature'] = $oauth_signature;
  289.         $header = array(
  290.             self::buildAuthorizationHeader($oauth),
  291.             'X-Yahoo-App-Id: ' . $this->y_appid
  292.         );
  293.         $options = array(
  294.             CURLOPT_HTTPHEADER => $header,
  295.             CURLOPT_HEADER => false,
  296.             CURLOPT_URL => $this->api . '?' . http_build_query($query),
  297.             CURLOPT_RETURNTRANSFER => true,
  298.             CURLOPT_SSL_VERIFYPEER => false
  299.         );
  300.         $ch = curl_init();
  301.         curl_setopt_array($ch, $options);
  302.         $response = curl_exec($ch);
  303.         curl_close($ch);
  304.         $return_data = json_decode($response);
  305.  
  306.         return $response;
  307.     }
  308.     // *** **** END::yahoo **** *** //
  309.  
  310.  
  311.     // Get Curl data
  312.     protected function curl($url) {
  313.         $ch = curl_init();
  314.         curl_setopt($ch, CURLOPT_URL, $url);
  315.         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  316.         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  317.         curl_setopt($ch, CURLOPT_TIMEOUT, 15);
  318.         $proxy = getenv('HTTPS_PROXY')
  319.             ?: getenv('https_proxy')
  320.             ?: getenv('HTTP_PROXY')
  321.             ?: getenv('http_proxy');
  322.         if ($proxy) {
  323.             curl_setopt($ch, CURLOPT_PROXY, $proxy);
  324.             curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
  325.             curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, true);
  326.         }
  327.         // avoid SSL issues via proxy
  328.         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  329.         curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  330.         $data = curl_exec($ch);
  331.         if ($data === false) {
  332.             die('CURL ERROR: ' . curl_error($ch));
  333.         }
  334.         curl_close($ch);
  335.         return $data;
  336.     }
  337.  
  338.     /**
  339.     * Convert numeric number to language
  340.     *
  341.     * @param int | string $number
  342.     * @return language formatted text
  343.     */
  344.     public function Numeric2Lang($number, $prefix = 'SP_') {
  345.         $number = (array) str_split($number);
  346.         $formated = '';
  347.         foreach($number as $no) {
  348.             if (ctype_digit($no)) {
  349.                 $formated.=Text::_($prefix . $no);
  350.             } else $formated.=$no;
  351.         }
  352.         return $formated;
  353.     }
  354.  
  355.  
  356.     /**
  357.     * Weather condition text converter
  358.     *
  359.     * @param string $text
  360.     * @return string
  361.     */
  362.     public function txt2lng($text) {
  363.         $trans = array(" " => "_", "/" => "_", "(" => "", ')'=>'');
  364.         $text = strtr($text, $trans);
  365.         return Text::_('SP_WEATHER_'.strtoupper($text));
  366.     }
  367.  
  368.     /**
  369.     * Convert temparature
  370.     *
  371.     * @param mixed $value
  372.     * @param mixed $unit
  373.     * @param mixed $tempType
  374.     */
  375.     public function convertUnit($value, $unit) {
  376.         $txt  = $this->Numeric2Lang($value);
  377.         $txt .= ( strtolower($unit)=='c') ? Text::_('SP_WEATHER_'. 'C') : Text::_('SP_WEATHER_'. 'F');
  378.         return $txt;
  379.     }
  380.  
  381.     /**
  382.     * weather condition to icon file name
  383.     *
  384.     * @param mixed $icon
  385.     * @param mixed $path
  386.     */
  387.     public function icon($condition) {
  388.         if($this->platform == 'yahoo') {
  389.             $condition = (int) $condition;
  390.             $at = in_array($condition, $this->nightIDs, true)?'n':'d';
  391.             $icon =  sprintf($this->iconURL,$condition,$at);
  392.             return  $icon;
  393.         } else {
  394.             return sprintf($this->iconURL, $condition);
  395.         }
  396.     }
  397.  
  398.     /**
  399.     * weather condition to icon font
  400.     *
  401.     * @param mixed $icon
  402.     * @param mixed $path
  403.     */
  404.     public function iconFont($condition = '') {
  405.         if($this->platform ==  'openweathermap') {
  406.             $night          = (strpos($condition, 'n') !== false) ?'-night':'';
  407.             $cond_number    = (int)substr($condition, 0, -1);
  408.             $fontIcon       = array(
  409.                 "0"     => 'other',
  410.                 "1"     => 'sunny',
  411.                 "2"     => 'cloudy',
  412.                 "3"     => 'mostly-cloudy',
  413.                 "4"     => 'partly-cloudy',
  414.                 "9"     => 'chance-of-storm',
  415.                 "10"    => 'rain',
  416.                 "11"    => 'thunderstorm',
  417.                 "13"    => 'snow',
  418.                 "50"    => 'foggy',
  419.             );
  420.             return $fontIcon[$cond_number] . $night;
  421.         } elseif($this->platform == 'yahoo') {
  422.             $night      = in_array($condition, $this->nightIDs, true)?'-night':'';
  423.             $fontIcon   = array(
  424.                 "0"     => 'other',
  425.                 "1"     => 'storm',
  426.                 "2"     => 'storm',
  427.                 "3"     => 'chance-of-storm',
  428.                 "4"     => 'thunderstorm',
  429.                 "5"     => 'rain-and-snow',
  430.                 "6"     => 'sleet',
  431.                 "7"     => 'sleet',
  432.                 "8"     => 'rain',
  433.                 "9"     => 'rain',
  434.                 "10"    => 'rain',
  435.                 "11"    => 'rain',
  436.                 "12"    => 'rain',
  437.                 "13"    => 'chance-of-snow',
  438.                 "14"    => 'snow',
  439.                 "15"    => 'snow',
  440.                 "16"    => 'snow',
  441.                 "17"    => 'chance-of-storm',
  442.                 "18"    => 'rain',
  443.                 "19"    => 'dusty',
  444.                 "20"    => 'foggy',
  445.                 "21"    => 'hazy',
  446.                 "22"    => 'smoke',
  447.                 "23"    => 'cloudy',
  448.                 "24"    => 'cloudy',
  449.                 "25"    => 'snow',
  450.                 "26"    => 'cloudy',
  451.                 "27"    => 'mostly-cloudy',
  452.                 "28"    => 'mostly-cloudy',
  453.                 "29"    => 'partly-cloudy',
  454.                 "30"    => 'partly-cloudy',
  455.                 "31"    => 'sunny',
  456.                 "32"    => 'sunny',
  457.                 "33"    => 'sunny',
  458.                 "34"    => 'partly-cloudy',
  459.                 "35"    => 'thunderstorm',
  460.                 "36"    => 'sunny',
  461.                 "37"    => 'thunderstorm',
  462.                 "38"    => 'chance-of-storm',
  463.                 "39"    => 'chance-of-storm',
  464.                 "40"    => 'rain',
  465.                 "41"    => 'snow',
  466.                 "42"    => 'snow',
  467.                 "43"    => 'snow',
  468.                 "44"    => 'partly-cloudy',
  469.                 "45"    => 'chance-of-storm',
  470.                 "46"    => 'chance-of-snow',
  471.                 "47"    => 'chance-of-storm',
  472.                 "3200"  => 'other'
  473.             );
  474.  
  475.             return $fontIcon[$condition] . $night;
  476.         }
  477.         // elseif($this->platform == 'weatherbit') {
  478.         //     echo '<pre>';
  479.         //     print_r($condition);
  480.         //     echo '</pre>';die();
  481.         // }
  482.  
  483.     }
  484.  
  485.     /**
  486.     * Run function to load data from source
  487.     * @return string
  488.     */
  489.     public function getData() {
  490.         return $this->results;
  491.     }
  492.  
  493.     // convert temperature
  494.     public function tempConvert($value, $convert_type = 'f') {
  495.         if($convert_type == 'f') { // convert celsius to fahrenheit (f for fahrenheit)
  496.             return $value * 1.8 + 32;
  497.         } else { // convert fahrenheit to celsius
  498.             return ($value - 32) / 1.8;
  499.         }
  500.     }
  501.  
  502.     // throw common error
  503.     public function throwError($message = 'COMMON', $platform = 'YAHOO', $custom_msg = false) {
  504.         if(!$this->errors) {
  505.             $this->errors = true;
  506.             $this->results['status'] = false;
  507.             $this->results['message']  = '';
  508.             if($platform) {
  509.                 $platform_error = Text::_('MOD_SPWEATHER_ERROR_PLATFORM_'. strtoupper($this->platform));
  510.             }
  511.             if ($message == 'INSERT_API_KEY') {
  512.                 $this->results['message'] .= '<p class="alert alert-warning">' . Text::_('MOD_SPWEATHER_ERROR_'. $message) .'</p>';
  513.             } elseif($custom_msg) {
  514.                 $this->results['message'] .= '<p class="alert alert-warning">' . $message .'</p>';
  515.             } else {
  516.                 $this->results['message'] .= '<p class="alert alert-warning">' . Text::_('MOD_SPWEATHER_ERROR_'. $message) . ' ' . Text::_('MOD_SPWEATHER_ERROR_LOCATION_ERROR') . ' '. $platform_error .'</p>';
  517.             }
  518.             echo $this->results['message'];
  519.         }
  520.     }
  521.  
  522. }
Add Comment
Please, Sign In to add comment