function nsp_MySubstr($str, $x, $y = 0) { if($y == 0) $y = strlen($str) - $x; if(function_exists('mb_substr')) return mb_substr($str, $x, $y); else return substr($str, $x, $y); } // Not use!!! commented by chab /** * Check if the argument is an IP addresses * * @param ip the ip to check * @return TRUE if it is an ip */ // function nsp_CheckIP($ip) { // return ( ! preg_match( "/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/", $ip)) ? FALSE : TRUE; // } /** * Decode the given url * * @param out_url the given url to decode * @return the decoded url ****************************************/ function nsp_DecodeURL($out_url) { if($out_url == '') { $out_url=__('Page','newstatpress').": Home"; } if(substr($out_url,0,4)=="cat=") { $out_url=__('Category','newstatpress').": ".get_cat_name(substr($out_url,4)); } if(substr($out_url,0,2)=="m=") { $out_url=__('Calendar','newstatpress').": ".substr($out_url,6,2)."/".substr($out_url,2,4); } if(substr($out_url,0,2)=="s=") { $out_url=__('Search','newstatpress').": ".substr($out_url,2); } if(substr($out_url,0,2)=="p=") { $subOut=substr($out_url,2); $post_id_7 = get_post($subOut, ARRAY_A); $out_url = $post_id_7['post_title']; } if(substr($out_url,0,8)=="page_id=") { $subOut=substr($out_url,8); $post_id_7=get_page($subOut, ARRAY_A); $out_url = __('Page','newstatpress').": ".$post_id_7['post_title']; } return $out_url; } function nsp_URL() { $urlRequested = (isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : '' ); if ( $urlRequested == "" ) { // SEO problem! $urlRequested = (isset($_SERVER["REQUEST_URI"]) ? $_SERVER["REQUEST_URI"] : '' ); } if(substr($urlRequested,0,2) == '/?') { $urlRequested=substr($urlRequested,2); } if($urlRequested == '/') { $urlRequested=''; } return $urlRequested; } /** * Convert data us to default format di Wordpress * * @param dt: date to convert * @return converted data ****************************************************/ function nsp_hdate($dt = "00000000") { return mysql2date(get_option('date_format'), substr($dt,0,4)."-".substr($dt,4,2)."-".substr($dt,6,2)); } function newstatpress_hdate($dt = "00000000") { return mysql2date(get_option('date_format'), nsp_MySubstr($dt, 0, 4) . "-" . nsp_MySubstr($dt, 4, 2) . "-" . nsp_MySubstr($dt, 6, 2)); } //--------------------------------------------------------------------------- // GET DATA from visitors Functions //--------------------------------------------------------------------------- /**TODO clean $accepted * Extracts the accepted language from browser headers */ function nsp_GetLanguage($accepted){ if(isset($_SERVER["HTTP_ACCEPT_LANGUAGE"])){ // Capture up to the first delimiter (, found in Safari) preg_match("/([^,;]*)/", $_SERVER["HTTP_ACCEPT_LANGUAGE"], $array_languages); // Fix some codes, the correct syntax is with minus (-) not underscore (_) return str_replace( "_", "-", strtolower( $array_languages[0] ) ); } return 'xx'; // Indeterminable language } // function nsp_GetLanguage($accepted) { // return substr($accepted,0,2); // } function nsp_GetQueryPairs($url){ $parsed_url = parse_url($url); $tab=parse_url($url); $host = $tab['host']; if(key_exists("query",$tab)){ $query=$tab["query"]; return explode("&",$query); } else {return null;} } /** * Get OS from the given argument * * @param arg the argument to parse for OS * @return the OS find in configuration file *******************************************/ function nsp_GetOs($arg) { global $newstatpress_dir; $arg=str_replace(" ","",$arg); $lines = file($newstatpress_dir.'/def/os.dat'); foreach($lines as $line_num => $os) { list($nome_os,$id_os)=explode("|",$os); if(strpos($arg,$id_os)===FALSE) continue; return $nome_os; // fount } return ''; } /** * Get OS logo from the given argument * * @param arg the argument to parse for OS * @return the OS find in configuration file *******************************************/ function nsp_GetOsImg($arg) { global $newstatpress_dir; $lines = file($newstatpress_dir.'/def/os.dat'); foreach($lines as $line_num => $os) { list($name_os,$id_os,$img_os)=explode("|",$os); if(strcmp($name_os,$arg)==0) return $img_os; } return ''; } /** * Get Browser from the given argument * * @param arg the argument to parse for Brower * @return the Browser find in configuration file ************************************************/ function nsp_GetBrowser($arg) { global $newstatpress_dir; $arg=str_replace(" ","",$arg); $lines = file($newstatpress_dir.'/def/browser.dat'); foreach($lines as $line_num => $browser) { list($nome,$id)=explode("|",$browser); if(strpos($arg,$id)===FALSE) continue; return $nome; // fount } return ''; } /** * Get Browser from the given argument * * @param arg the argument to parse for Brower * @return the Browser find in configuration file ************************************************/ function nsp_GetBrowserImg($arg) { global $newstatpress_dir; $lines = file($newstatpress_dir.'/def/browser.dat'); foreach($lines as $line_num => $browser) { list($name_browser,$id,$img_browser)=explode("|",$browser); //echo $name_browser; if(strcmp($name_browser,$arg)==0) return $img_browser; } return ''; } /** * Check if the given ip is to ban * * @param arg the ip to check * @return '' id the address is banned */ function nsp_CheckBanIP($arg){ global $newstatpress_dir; $lines = file($newstatpress_dir.'/def/banips.dat'); foreach($lines as $line_num => $banip) { if(strpos($arg,rtrim($banip,"\n"))===FALSE) continue; return ''; // this is banned } return $arg; } /** * Get the search engines * * @param refferer the url to test * @return the search engine present in the url */ function nsp_GetSE($referrer = null){ global $newstatpress_dir; $key = null; $lines = file($newstatpress_dir.'/def/searchengines.dat'); foreach($lines as $line_num => $se) { list($nome,$url,$key)=explode("|",$se); if(strpos($referrer,$url)===FALSE) continue; # find if $variables = nsp_GetQueryPairs(html_entity_decode($referrer)); $i = count($variables); while($i--){ $tab=explode("=",$variables[$i]); if($tab[0] == $key){return ($nome."|".urldecode($tab[1]));} } } return null; } /** * Get the spider from the given agent * * @param agent the agent string * @return agent the fount agent *************************************/ function nsp_GetSpider($agent = null){ global $newstatpress_dir; $agent=str_replace(" ","",$agent); $key = null; $lines = file($newstatpress_dir.'/def/spider.dat'); foreach($lines as $line_num => $spider) { list($nome,$key)=explode("|",$spider); if(strpos($agent,$key)===FALSE) continue; # fount return $nome; } return null; } /** * Get the previous month in 'YYYYMM' format * * @return the previous month */ function nsp_Lastmonth() { $ta = getdate(current_time('timestamp')); $year = $ta['year']; $month = $ta['mon']; --$month; // go back 1 month if( $month === 0 ): // if this month is Jan --$year; // go back a year $month = 12; // last month is Dec endif; // return in format 'YYYYMM' return sprintf( $year.'%02d', $month); } /** * Create or update the table * * @param action to do: update, create *************************************/ function nsp_BuildPluginSQLTable($action) { global $wpdb; global $wp_db_version; $table_name = nsp_TABLENAME; $charset_collate = $wpdb->get_charset_collate(); $index_list=array(array('Key_name'=>"spider_nation", 'Column_name'=>"(spider, nation)"), array('Key_name'=>"ip_date", 'Column_name'=>"(ip, date)"), array('Key_name'=>"agent", 'Column_name'=>"(agent)"), array('Key_name'=>"search", 'Column_name'=>"(search)"), array('Key_name'=>"referrer", 'Column_name'=>"(referrer)"), array('Key_name'=>"feed_spider_os", 'Column_name'=>"(feed, spider, os)"), array('Key_name'=>"os", 'Column_name'=>"(os)"), array('Key_name'=>"date_feed_spider", 'Column_name'=>"(date, feed, spider)"), array('Key_name'=>"feed_spider_browser", 'Column_name'=>"(feed, spider, browser)"), array('Key_name'=>"browser", 'Column_name'=>"(browser)") ); // Add by chab // IF the table is already created then DROP INDEX for update if ($action=='') $action='create'; $sql_createtable = " CREATE TABLE ". $table_name . " ( id mediumint(9) NOT NULL AUTO_INCREMENT, date int(8), time time, ip varchar(39), urlrequested varchar(250), agent varchar(250), referrer varchar(512), search varchar(250), nation varchar(2), os varchar(30), browser varchar(32), searchengine varchar(16), spider varchar(32), feed varchar(8), user varchar(16), timestamp timestamp DEFAULT 0, UNIQUE KEY id (id)"; if ($action=='create') { foreach ($index_list as $index) { $Key_name=$index['Key_name']; $Column_name=$index['Column_name']; $sql_createtable.=", INDEX $Key_name $Column_name"; } } elseif ($action=='update') { foreach ($index_list as $index) { $Key_name=$index['Key_name']; $Column_name=$index['Column_name']; if ($wpdb->query("SHOW INDEXES FROM $table_name WHERE Key_name ='$Key_name'")=='') { $sql_createtable.=",\n INDEX $Key_name $Column_name"; } } } $sql_createtable.=") $charset_collate;"; // echo $sql_createtable; if($wp_db_version >= 5540) $page = 'wp-admin/includes/upgrade.php'; else $page = 'wp-admin/upgrade'.'-functions.php'; require_once(ABSPATH . $page); dbDelta($sql_createtable); } /** * Get if this is a feed * * @param url the url to test * @return the kind of feed that is found *****************************************/ function nsp_IsFeed($url) { $tmp=get_bloginfo('rdf_url'); if ($tmp) { if (stristr($url,$tmp) != FALSE) { return 'RDF'; } } $tmp=get_bloginfo('rss2_url'); if ($tmp) { if (stristr($url,$tmp) != FALSE) { return 'RSS2'; } } $tmp=get_bloginfo('rss_url'); if ($tmp) { if (stristr($url,$tmp) != FALSE) { return 'RSS'; } } $tmp=get_bloginfo('atom_url'); if ($tmp) { if (stristr($url,$tmp) != FALSE) { return 'ATOM'; } } $tmp=get_bloginfo('comments_rss2_url'); if ($tmp) { if (stristr($url,$tmp) != FALSE) { return 'COMMENT'; } } $tmp=get_bloginfo('comments_atom_url'); if ($tmp) { if (stristr($url,$tmp) != FALSE) { return 'COMMENT'; } } if (stristr($url,'wp-feed.php') != FALSE) { return 'RSS2'; } if (stristr($url,'/feed/') != FALSE) { return 'RSS2'; } return ''; } /** * Insert statistic into the database * ************************************/ function nsp_StatAppend() { global $wpdb; $table_name = nsp_TABLENAME; global $userdata; global $_STATPRESS; wp_get_current_user(); $feed=''; // Time $timestamp = current_time('timestamp'); $vdate = gmdate("Ymd",$timestamp); $vtime = gmdate("H:i:s",$timestamp); $timestamp = date('Y-m-d H:i:s', $timestamp); // IP $ipAddress = $_SERVER['REMOTE_ADDR']; // BASIC detection -> to delete if it works // $ipAddress = htmlentities(nsp_GetUserIP()); // Is this IP blacklisted from file? if(nsp_CheckBanIP($ipAddress) == '') { return ''; } // Is this IP blacklisted from user? $to_ignore = get_option('newstatpress_ignore_ip', array()); foreach($to_ignore as $a_ip_range){ list ($ip_to_ignore, $mask) = @explode("/", trim($a_ip_range)); if (empty($mask)) $mask = 32; $long_ip_to_ignore = ip2long($ip_to_ignore); $long_mask = bindec( str_pad('', $mask, '1') . str_pad('', 32-$mask, '0') ); $long_masked_user_ip = ip2long($ipAddress) & $long_mask; $long_masked_ip_to_ignore = $long_ip_to_ignore & $long_mask; if ($long_masked_user_ip == $long_masked_ip_to_ignore) { return ''; } } if(get_option('newstatpress_cryptip')=='checked') { $ipAddress = crypt($ipAddress,nsp_TEXTDOMAIN); } // URL (requested) $urlRequested=nsp_URL(); if (preg_match("/.ico$/i", $urlRequested)) { return ''; } if (preg_match("/favicon.ico/i", $urlRequested)) { return ''; } if (preg_match("/.css$/i", $urlRequested)) { return ''; } if (preg_match("/.js$/i", $urlRequested)) { return ''; } if (stristr($urlRequested,"/wp-content/plugins") != FALSE) { return ''; } if (stristr($urlRequested,"/wp-content/themes") != FALSE) { return ''; } if (stristr($urlRequested,"/wp-admin/") != FALSE) { return ''; } $urlRequested=esc_sql($urlRequested); // Is a given permalink blacklisted? $to_ignore = get_option('newstatpress_ignore_permalink', array()); foreach($to_ignore as $a_filter){ if (!empty($urlRequested) && strpos($urlRequested, $a_filter) === 0) { return ''; } } $referrer = (isset($_SERVER['HTTP_REFERER']) ? htmlentities($_SERVER['HTTP_REFERER']) : ''); $referrer=esc_sql($referrer); $referrer=esc_html($referrer); $userAgent = (isset($_SERVER['HTTP_USER_AGENT']) ? htmlentities($_SERVER['HTTP_USER_AGENT']) : ''); $userAgent=esc_sql($userAgent); $userAgent=esc_html($userAgent); $spider=nsp_GetSpider($userAgent); if(($spider != '') and (get_option('newstatpress_donotcollectspider')=='checked')) { return ''; } # ininitalize to empty $searchengine=''; $search_phrase=''; if($spider != '') { $os=''; $browser=''; } else { // Trap feeds $feed=nsp_IsFeed(get_bloginfo('url').$_SERVER['REQUEST_URI']); // Get OS and browser $os=nsp_GetOs($userAgent); $browser=nsp_GetBrowser($userAgent); $exp_referrer=nsp_GetSE($referrer); if (isset($exp_referrer)) { list($searchengine,$search_phrase)=explode("|",$exp_referrer); } } // Country (ip2nation table) or language $countrylang=""; if($wpdb->get_var("SHOW TABLES LIKE 'ip2nation'") == 'ip2nation') { $sql='SELECT * FROM ip2nation WHERE ip < INET_ATON("'.$ipAddress.'") ORDER BY ip DESC LIMIT 0,1'; $qry = $wpdb->get_row($sql); $countrylang=$qry->country; } if($countrylang == '') { $countrylang=nsp_GetLanguage($_SERVER['HTTP_ACCEPT_LANGUAGE']); } // Auto-delete visits if... if(get_option('newstatpress_autodelete') != '') { $int = filter_var(get_option('newstatpress_autodelete'), FILTER_SANITIZE_NUMBER_INT); # secure action if ($int>=1) { $t=gmdate('Ymd', current_time('timestamp')-86400*$int*30); $results =$wpdb->query( "DELETE FROM " . $table_name . " WHERE date < '" . $t . "'"); } } // Auto-delete spiders visits if... if(get_option('newstatpress_autodelete_spiders') != '') { $int = filter_var(get_option('newstatpress_autodelete_spiders'), FILTER_SANITIZE_NUMBER_INT); # secure action if ($int>=1) { $t=gmdate('Ymd', current_time('timestamp')-86400*$int*30); $results =$wpdb->query( "DELETE FROM " . $table_name . " WHERE date < '" . $t . "' and feed='' and spider<>'' "); } } if ((!is_user_logged_in()) OR (get_option('newstatpress_collectloggeduser')=='checked')) { if (is_user_logged_in() AND (get_option('newstatpress_collectloggeduser')=='checked')) { $current_user = wp_get_current_user(); // Is a given name to ignore? $to_ignore = get_option('newstatpress_ignore_users', array()); foreach($to_ignore as $a_filter) { if ($current_user->user_login == $a_filter) { return ''; } } } if($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) { nsp_BuildPluginSQLTable(); } $login = $userdata ? $userdata->user_login : null; $insert = "INSERT INTO " . $table_name . "( date, time, ip, urlrequested, agent, referrer, search, nation, os, browser, searchengine, spider, feed, user, timestamp ) VALUES ( '$vdate', '$vtime', '$ipAddress', '$urlRequested', '".addslashes(strip_tags($userAgent))."', '$referrer','" . addslashes(strip_tags($search_phrase))."', '".$countrylang."', '$os', '$browser', '$searchengine', '$spider', '$feed', '$login', '$timestamp' )"; $results = $wpdb->query( $insert ); } } add_action('send_headers', 'nsp_StatAppend'); /** * Generate the Ajax code for the given variable * * @param var variable to get * @param limit optional limit value for query * @param flag optional flag value for checked * @param url optional url address ************************************************/ function nsp_generateAjaxVar($var, $limit=0, $flag='', $url='') { global $newstatpress_dir; $res = "_ "; return $res; } /** * Return the expanded vars into the give code. API to use for users. */ function NewStatPress_Print($body='') { return nsp_ExpandVarsInsideCode($body); } /** * Expand vars into the give code * * @param body the code where to look for variables to expand * @return the modified code ************************************************************/ function nsp_ExpandVarsInsideCode($body) { global $wpdb; $table_name = nsp_TABLENAME; $vars_list=array('visits', 'yvisits', 'mvisits', 'wvisits', 'totalvisits', 'totalpageviews', 'todaytotalpageviews', 'alltotalvisits' ); # look for $vars_list foreach($vars_list as $var) { if(strpos(strtolower($body),"%$var%") !== FALSE) { $body = str_replace("%$var%", nsp_GenerateAjaxVar($var), $body); } } # look for %thistotalvisits% if(strpos(strtolower($body),"%thistotalvisits%") !== FALSE) { $body = str_replace("%thistotalvisits%", nsp_GenerateAjaxVar("thistotalvisits", 0, '', nsp_URL()), $body); } # look for %since% if(strpos(strtolower($body),"%since%") !== FALSE) { $qry = $wpdb->get_results( "SELECT date FROM $table_name ORDER BY date LIMIT 1; "); $body = str_replace("%since%", nsp_hdate($qry[0]->date), $body); } # look for %os% if(strpos(strtolower($body),"%os%") !== FALSE) { $userAgent = (isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : ''); $os=nsp_GetOs($userAgent); $body = str_replace("%os%", $os, $body); } # look for %browser% if(strpos(strtolower($body),"%browser%") !== FALSE) { $browser=nsp_GetBrowser($userAgent); $body = str_replace("%browser%", $browser, $body); } # look for %ip% if(strpos(strtolower($body),"%ip%") !== FALSE) { $ipAddress = $_SERVER['REMOTE_ADDR']; $body = str_replace("%ip%", $ipAddress, $body); } # look for %visitorsonline% if(strpos(strtolower($body),"%visitorsonline%") !== FALSE) { $act_time = current_time('timestamp'); $from_time = date('Y-m-d H:i:s', strtotime('-4 minutes', $act_time)); $to_time = date('Y-m-d H:i:s', $act_time); $qry = $wpdb->get_results( "SELECT count(DISTINCT(ip)) AS visitors FROM $table_name WHERE spider='' AND feed='' AND date = '".gmdate("Ymd", $act_time)."' AND timestamp BETWEEN '$from_time' AND '$to_time'; "); $body = str_replace("%visitorsonline%", $qry[0]->visitors, $body); } # look for %usersonline% if(strpos(strtolower($body),"%usersonline%") !== FALSE) { $act_time = current_time('timestamp'); $from_time = date('Y-m-d H:i:s', strtotime('-4 minutes', $act_time)); $to_time = date('Y-m-d H:i:s', $act_time); $qry = $wpdb->get_results( "SELECT count(DISTINCT(ip)) AS users FROM $table_name WHERE spider='' AND feed='' AND date = '".gmdate("Ymd", $act_time)."' AND user<>'' AND timestamp BETWEEN '$from_time' AND '$to_time'; "); $body = str_replace("%usersonline%", $qry[0]->users, $body); } # look for %toppost% if(strpos(strtolower($body),"%toppost%") !== FALSE) { $qry = $wpdb->get_results( "SELECT urlrequested,count(*) AS totale FROM $table_name WHERE spider='' AND feed='' AND urlrequested LIKE '%p=%' GROUP BY urlrequested ORDER BY totale DESC LIMIT 1; "); $body = str_replace("%toppost%", nsp_DecodeURL($qry[0]->urlrequested), $body); } # look for %topbrowser% if(strpos(strtolower($body),"%topbrowser%") !== FALSE) { $qry = $wpdb->get_results( "SELECT browser,count(*) AS totale FROM $table_name WHERE spider='' AND feed='' GROUP BY browser ORDER BY totale DESC LIMIT 1; "); $body = str_replace("%topbrowser%", nsp_DecodeURL($qry[0]->browser), $body); } # look for %topos% if(strpos(strtolower($body),"%topos%") !== FALSE) { $qry = $wpdb->get_results( "SELECT os,count(*) AS totale FROM $table_name WHERE spider='' AND feed='' GROUP BY os ORDER BY totale DESC LIMIT 1; "); $body = str_replace("%topos%", nsp_DecodeURL($qry[0]->os), $body); } # look for %topsearch% if(strpos(strtolower($body),"%topsearch%") !== FALSE) { $qry = $wpdb->get_results( "SELECT search, count(*) AS csearch FROM $table_name WHERE search<>'' GROUP BY search ORDER BY csearch DESC LIMIT 1; "); $body = str_replace("%topsearch%", nsp_DecodeURL($qry[0]->search), $body); } return $body; } // TODO : if working, move the contents into the caller instead of this function /** * Get top posts * * @param limit: the number of post to show * @param showcounts: if checked show totals * @return result of extraction *******************************************/ function nsp_TopPosts($limit=5, $showcounts='checked') { return nsp_GenerateAjaxVar("widget_topposts", $limit, $showcounts); } /** * Build NewsStatPress Widgets: Stat and TopPosts * ************************************************/ function nsp_WidgetInit($args) { if ( !function_exists('wp_register_sidebar_widget') || !function_exists('wp_register_widget_control') ) return; // Statistics Widget control function nsp_WidgetStats_control() { global $nsp_widget_vars; $options = get_option('widget_newstatpress'); if ( !is_array($options) ) $options = array('title'=>'NewStatPress Stats', 'body'=>'Visits today: %visits%'); if ( isset($_POST['newstatpress-submit']) && $_POST['newstatpress-submit'] ) { $options['title'] = strip_tags(stripslashes($_POST['newstatpress-title'])); $options['body'] = stripslashes($_POST['newstatpress-body']); update_option('widget_newstatpress', $options); } $title = htmlspecialchars($options['title'], ENT_QUOTES); $body = htmlspecialchars($options['body'], ENT_QUOTES); // the form echo "

". __('Stats available: ', 'newstatpress') ."
"; foreach($nsp_widget_vars as $var) { echo "%$var[0]% "; _e($var[1], 'newstatpress'); echo " | "; } echo "

"; } function nsp_WidgetStats($args) { extract($args); $options = get_option('widget_newstatpress'); $title = $options['title']; $body = $options['body']; echo $before_widget; print($before_title . $title . $after_title); print nsp_ExpandVarsInsideCode($body); echo $after_widget; } wp_register_sidebar_widget('NewStatPress', 'NewStatPress Stats', 'nsp_WidgetStats'); wp_register_widget_control('NewStatPress', array('NewStatPress','widgets'), 'nsp_WidgetStats_control', 300, 210); // Top posts Widget control function nsp_WidgetTopPosts_control() { $options = get_option('widget_newstatpresstopposts'); if ( !is_array($options) ) { $options = array('title'=>'NewStatPress TopPosts', 'howmany'=>'5', 'showcounts'=>'checked'); } if ( isset($_POST['newstatpresstopposts-submit']) && $_POST['newstatpresstopposts-submit'] ) { $options['title'] = strip_tags(stripslashes($_POST['newstatpresstopposts-title'])); $options['howmany'] = stripslashes($_POST['newstatpresstopposts-howmany']); $options['showcounts'] = stripslashes($_POST['newstatpresstopposts-showcounts']); if($options['showcounts'] == "1") { $options['showcounts']='checked'; } update_option('widget_newstatpresstopposts', $options); } $title = htmlspecialchars($options['title'], ENT_QUOTES); $howmany = htmlspecialchars($options['howmany'], ENT_QUOTES); $showcounts = htmlspecialchars($options['showcounts'], ENT_QUOTES); // the form echo "

"; echo '

'; echo ''; } function nsp_WidgetTopPosts($args) { extract($args); $options = get_option('widget_newstatpresstopposts'); $title = htmlspecialchars($options['title'], ENT_QUOTES); $howmany = htmlspecialchars($options['howmany'], ENT_QUOTES); $showcounts = htmlspecialchars($options['showcounts'], ENT_QUOTES); echo $before_widget; print($before_title . $title . $after_title); print nsp_TopPosts($howmany,$showcounts); echo $after_widget; } wp_register_sidebar_widget('NewStatPress TopPosts', 'NewStatPress TopPosts', 'nsp_WidgetTopPosts'); wp_register_widget_control('NewStatPress TopPosts', array('NewStatPress TopPosts','widgets'), 'nsp_WidgetTopPosts_control', 300, 110); } add_action('plugins_loaded', 'nsp_WidgetInit'); function nsp_CalculateVariation($month,$lmonth) { $target = round($month / ( (date("d", current_time('timestamp')) - 1 + (date("H", current_time('timestamp')) + (date("i", current_time('timestamp')) + 1)/ 60.0) / 24.0)) * date("t", current_time('timestamp')) ); $monthchange = null; $added = null; if($lmonth <> 0) { $percent_change = round( 100 * ($month / $lmonth ) - 100,1); $percent_target = round( 100 * ($target / $lmonth ) - 100,1); if($percent_change >= 0) { $percent_change=sprintf("+%'04.1f", $percent_change); $monthchange = "($percent_change%)"; } else { $percent_change=sprintf("%'05.1f", $percent_change); $monthchange = "($percent_change%)"; } if($percent_target >= 0) { $percent_target=sprintf("+%'04.1f", $percent_target); $added = "($percent_target%)"; } else { $percent_target=sprintf("%'05.1f", $percent_target); $added = "($percent_target%)"; } } else { $monthchange = ""; $added = ""; } $calculated_result=array($monthchange,$target,$added); return $calculated_result; } function nsp_MakeOverview($print ='dashboard') { global $wpdb, $nsp_option_vars; $table_name = nsp_TABLENAME; $overview_table=''; global $nsp_option_vars; $offsets = get_option($nsp_option_vars['stats_offsets']['name']); // $since = NewStatPress_Print('%since%'); $since = nsp_ExpandVarsInsideCode('%since%'); $lastmonth = nsp_Lastmonth(); $thisyear = gmdate('Y', current_time('timestamp')); $thismonth = gmdate('Ym', current_time('timestamp')); $yesterday = gmdate('Ymd', current_time('timestamp')-86400); $today = gmdate('Ymd', current_time('timestamp')); $tlm[0]=substr($lastmonth,0,4); $tlm[1]=substr($lastmonth,4,2); $thisyearHeader = gmdate('Y', current_time('timestamp')); $lastmonthHeader = gmdate('M, Y',gmmktime(0,0,0,$tlm[1],1,$tlm[0])); $thismonthHeader = gmdate('M, Y', current_time('timestamp')); $yesterdayHeader = gmdate('d M', current_time('timestamp')-86400); $todayHeader = gmdate('d M', current_time('timestamp')); // build head table overview if ($print=='main') { //$overview_table.="

". __('Overview','newstatpress'). "

"; $overview_table.=""; } elseif ($print=='dashboard') { $overview_table.="
". __('Total since','newstatpress'). " ". __('This year','newstatpress'). " ". __('Last month','newstatpress'). " ". __('This month','newstatpress'). " ". __('Target This month','newstatpress'). " ". __('Yesterday','newstatpress'). " ". __('Today','newstatpress'). "
$since $thisyearHeader $lastmonthHeader $thismonthHeader $thismonthHeader $yesterdayHeader $todayHeader
"; } // build body table overview $overview_rows=array('visitors','visitors_feeds','pageview','feeds','spiders'); foreach ($overview_rows as $row) { switch($row) { case 'visitors' : $row2='DISTINCT ip'; $row_title=__('Visitors','newstatpress'); $sql_QueryTotal="SELECT count($row2) AS $row FROM $table_name WHERE feed='' AND spider=''"; break; case 'visitors_feeds' : $row2='DISTINCT ip'; $row_title=__('Visitors through Feeds','newstatpress'); $sql_QueryTotal="SELECT count($row2) AS $row FROM $table_name WHERE feed<>'' AND spider='' AND agent<>''"; break; case 'pageview' : $row2='date'; $row_title=__('Pageviews','newstatpress'); $sql_QueryTotal="SELECT count($row2) AS $row FROM $table_name WHERE feed='' AND spider=''"; break; case 'spiders' : $row2='date'; $row_title=__('Spiders','newstatpress'); $sql_QueryTotal="SELECT count($row2) AS $row FROM $table_name WHERE feed='' AND spider<>''"; break; case 'feeds' : $row2='date'; $row_title=__('Pageviews through Feeds','newstatpress'); $sql_QueryTotal="SELECT count($row2) AS $row FROM $table_name WHERE feed<>'' AND spider=''"; break; } // query requests $qry_total = $wpdb->get_row($sql_QueryTotal); $qry_tyear = $wpdb->get_row($sql_QueryTotal. " AND date LIKE '$thisyear%'"); if (get_option($nsp_option_vars['calculation']['name'])=='sum') { // alternative calculation by mouth: sum of unique visitors of each day $tot=0; $t = getdate(current_time('timestamp')); $year = $t['year']; $month = sprintf('%02d', $t['mon']); $day= $t['mday']; $totlm=0; for($k=$t['mon'];$k>0;$k--) { //current month } for($i=0;$i<$day;$i++) { $qry_daylmonth = $wpdb->get_row($sql_QueryTotal. " AND date LIKE '$lastmonth$i%'"); $qry_day=$wpdb->get_row($sql_QueryTotal. " AND date LIKE '$year$month$i%'"); $tot+=$qry_day->$row; $totlm+=$qry_daylmonth->$row; } // echo $totlm." ,"; $qry_tmonth->$row=$tot; $qry_lmonth->$row=$totlm; } else { // classic $qry_tmonth = $wpdb->get_row($sql_QueryTotal. " AND date LIKE '$thismonth%'"); $qry_lmonth = $wpdb->get_row($sql_QueryTotal. " AND date LIKE '$lastmonth%'"); } $qry_y = $wpdb->get_row($sql_QueryTotal. " AND date LIKE '$yesterday'"); $qry_t = $wpdb->get_row($sql_QueryTotal. " AND date LIKE '$today'"); $calculated_result=nsp_CalculateVariation($qry_tmonth->$row, $qry_lmonth->$row); switch($row) { case 'visitors' : $qry_total->$row=$qry_total->$row+$offsets['alltotalvisits']; break; case 'visitors_feeds' : $qry_total->$row=$qry_total->$row+$offsets['visitorsfeeds']; break; case 'pageview' : $qry_total->$row=$qry_total->$row+$offsets['pageviews']; break; case 'spiders' : $qry_total->$row=$qry_total->$row+$offsets['spy']; break; case 'feeds' : $qry_total->$row=$qry_total->$row+$offsets['pageviewfeeds']; break; } // build full current row $overview_table.=""; if ($print=='main') $overview_table.="\n"; if ($print=='main') $overview_table.="\n"; $overview_table.="\n"; $overview_table.="\n"; if ($print=='main') $overview_table.="\n"; $overview_table.="\n"; $overview_table.="\n"; $overview_table.=""; } if ($print=='dashboard'){ $overview_table.="
". __('M-1','newstatpress'). " ". __('M','newstatpress'). " ". __('Y','newstatpress'). " ". __('T','newstatpress'). "
$lastmonthHeader $thismonthHeader $yesterdayHeader $todayHeader
$row_title".$qry_total->$row."".$qry_tyear->$row."".$qry_lmonth->$row."".$qry_tmonth->$row. $calculated_result[0] ." $calculated_result[1] $calculated_result[2] ".$qry_y->$row."".$qry_t->$row."
"; } if ($print=='main'){ $overview_table.= "\n"; // print graph // last "N" days graph NEW $gdays=get_option('newstatpress_daysinoverviewgraph'); if($gdays == 0) { $gdays=20; } $start_of_week = get_option('start_of_week'); $maxxday = 0; for($gg=$gdays-1;$gg>=0;$gg--) { $date=gmdate('Ymd', current_time('timestamp')-86400*$gg); $qry_visitors = $wpdb->get_row("SELECT count(DISTINCT ip) AS total FROM $table_name WHERE feed='' AND spider='' AND date = '$date'"); $visitors[$gg] = $qry_visitors->total; $qry_pageviews = $wpdb->get_row("SELECT count(date) AS total FROM $table_name WHERE feed='' AND spider='' AND date = '$date'"); $pageviews[$gg]= $qry_pageviews->total; $qry_spiders = $wpdb->get_row("SELECT count(date) AS total FROM $table_name WHERE feed='' AND spider<>'' AND date = '$date'"); $spiders[$gg] = $qry_spiders->total; $qry_feeds = $wpdb->get_row("SELECT count(date) AS total FROM $table_name WHERE feed<>'' AND spider='' AND date = '$date'"); $feeds[$gg] = $qry_feeds->total; $total= $visitors[$gg] + $pageviews[$gg] + $spiders[$gg] + $feeds[$gg]; if ($total > $maxxday) $maxxday= $total; } if($maxxday == 0) { $maxxday = 1; } # Y $gd=(90/$gdays).'%'; $overview_graph=""; for($gg=$gdays-1;$gg>=0;$gg--) { $scale_factor=2; //2 : 200px in CSS $date=gmdate('Ymd', current_time('timestamp')-86400*$gg); $px_visitors = $scale_factor*(round($visitors[ $gg]*100/$maxxday)); $px_pageviews= $scale_factor*(round($pageviews[$gg]*100/$maxxday)); $px_spiders = $scale_factor*(round($spiders[ $gg]*100/$maxxday)); $px_feeds = $scale_factor*(round($feeds[ $gg]*100/$maxxday)); $px_white = $scale_factor*100 - $px_feeds - $px_spiders - $px_pageviews - $px_visitors; $overview_graph.="\n"; } $overview_graph.="
"; $overview_graph.="
"; if($start_of_week == gmdate('w',current_time('timestamp')-86400*$gg)) $overview_graph.="
"; else $overview_graph.="
"; $overview_graph.=gmdate('d', current_time('timestamp')-86400*$gg) . ' ' . gmdate('M', current_time('timestamp')-86400*$gg) . "
"; $overview_table=$overview_table.$overview_graph; } if ($print!=FALSE) print $overview_table; else return $overview_table; } register_activation_hook(__FILE__,'nsp_BuildPluginSQLTable'); ?> Simple tips to Get home financing By having a USDA Loan | UIL Pavia

Simple tips to Get home financing By having a USDA Loan

Simple tips to Get home financing By having a USDA Loan

This loan might help if you’re looking for rural home

USDA loans enables you to buy, renovate, or refinance a house in some communities that are rural the U.S. They’re readily available for both single-family and multi-family domiciles, in addition to community facilities and conservation jobs.

In general, USDA mortgages are made to “promote homeownership in underserved areas” consequently they are reserved for low- and earners that are moderate-income. They could either be released because of the U.S. Department of Agriculture or insured because of it, according to which loan system you might be qualified to receive. ? ?

Forms of USDA Loans

For buyers enthusiastic about a single-family house, there are 2 kinds of USDA loans to choose from—a direct USDA loan or an assured USDA loan.

Direct USDA loans are released by the U.S. Department of Agriculture it self and generally are available to just low- and borrowers that are very-low-income. Fully guaranteed USDA loans are released by an authorized lender but insured by the Department of Agriculture. This alleviates most of the danger towards the loan provider, permitting them to accept borrowers with lower fico scores, smaller down re payments, much less earnings.

Here are the differences that are main the 2 forms of loans. ? ? ? ? ? that is ?

Should be situated in a qualified rural area

Generally speaking 2,000 feet that are square less

No pool that is in-ground

Value cannot go beyond USDA loan restrictions when it comes to area

Should be not able to get that loan off their resources

Should never gain access to decent, safe, or sanitary housing

Must come under USDA earnings limits

Could be used to purchase, build, fix, renovate, or relocate home

Can be utilized in refinancing

Can cover closing expenses

May be used to purchase, build, fix, or rehabilitate a residential property

Can be utilized in refinancing

Can cover closing expenses

Direct USDA Loans Guaranteed USDA Loans
Lender USDA Approved USDA loan providers
Home Should be positioned in an qualified rural area

No value or cost limit

Borrower Eligibility Must come under USDA earnings limits
Use
Advance payment $0 $0
rates of interest as little as 1%, but 3% at the time of December 2019 changes, but may well not meet or exceed Fannie Mae 30-year, 90-day price plus 1%and rounded up. 25% in the day locked
Term 33- to 38-year payment duration repayment period that is 30-year

There’s also loan that is USDA for multi-family properties and companies, in addition to ecological tasks and community facilities, like hospitals, schools, fire division buildings, and much more. ? ?

Finally, you can find also loans that are sitemade for buying land for rural development) and USDA fix loans and funds. Fix loans and funds provide as much as $27,500 in funds to eliminate security and wellness dangers, enhance a property’s accessibility, while making repairs. ? ?

USDA Loan Eligibility

The biggest eligibility requirement for a USDA loan is the fact that home you’re purchasing, rehabilitating, or refinancing is found in an eligible area. To discover if a property you’re considering is eligible for USDA financing, check out the Department of Agriculture’s eligibility device, and choose the mortgage system you would like to make use of.

Here are one other eligibility needs you’ll need certainly to cope with.

  • Credit rating: usually 640 or more (can vary by loan provider, though) ? ?
  • PITI debt-to-income ratio: 29%
  • Total debt-to-income ratio: 41% ? ?

There could be eligibility that is additional dependent on which loan system you decide on. With direct USDA loans, for instance, you need to be struggling to find safe or housing that is sanitary along with other financing choices.

Advantages and disadvantages of USDA Loans

The greatest benefit of a USDA loan is it calls for no advance payment, making them less expensive than FHA loans. This is a large plus if you’re low on money or are experiencing difficulty money that is saving. Some USDA borrowers may additionally be in a position to move their closing costs to the loan stability, decreasing the up-front expenses of purchasing a property further.

USDA loans additionally offer low interest (only 1%) as well as on some loans, extended repayment durations as much as 38 years can be found.

Regarding the downs ? If money levels for Guaranteed loans are restricted by the end of this financial 12 months, applications are prioritized for first-time homebuyers. ? ?

Low interest

Less expensive than FHA loans

No advance payment

Makes it possible for one to fund closing expenses

Need an up-front and yearly guarantee cost

Restricted quantity available

Just granted by specific loan providers

USDA Loan Expenses

USDA loans come with closing expenses, much like any house purchase, though these vary according to your loan stability while the exact USDA program you’re making use of. In addition might be able to fund these and roll them into the loan.

Though USDA loans don’t require home loan insurance (like FHA loans do), they are doing have guarantee charges, which you’ll pay when at closing time then month-to-month, together with your home loan repayments. In many cases, perhaps you are in a position to finance the guarantee that is up-front and spread it across your loan term, too.

You may be able to roll those costs into the loan and finance them, too if you need special design features or equipment for a household member with a disability.

If you’re making use of your USDA loan for a unique construction home, then you’ll need certainly to protect the expenses of multiple “phase” inspections, too. These run at the least a hundred or so bucks each. ? ?

USDA Loan Costs

Refinancing By Having a USDA Loan

It is possible to make use of USDA loan to refinance a mortgage that is existing. They are available as Direct or Guaranteed loans, and there’s a good fast-tracked, “Streamlined” version of this system you can make use of in the event that you have a USDA home.

To be able to qualify, you’ll want to be present on your own home loan for at the least the final six to 12 months (with respect to the refinance system you decide on), along with your brand brand new interest ought to be the identical to or not as much as your existing one. In some cases, you may well be in a position to fund the closing expenses and guarantee that is up-front on your loan. ? ?

The Important Thing

Then contact a USDA-approved lender in your area to get started if you’re interested in using a USDA loan to purchase, repair, or renovate a rural property. Make sure to check around, as rates of interest and closing expenses can differ significantly from a single loan provider to another location.

Scrivi un commento

L'indirizzo email non sarà pubblicato.


*