<?php

$reports["_NEWS"] = Array(
	"ClassName" => "News", 
	"Category" => "_VISITOR_TRENDS", 
	"icon" => "images/icons/32x32/clicktrails.png",
	"Options" => "daterangeField,profileselector,columnSelector",
	"Filename" => "news",
	"Distribution" => "Standard",
	"Order" => 1,
	"ReportVersion" => 1.0,
	"MinimumVersion" => 3.0,
	"EmailAlerts" => false,
	"Update" => false,
	"canAggregate" => false
);

Class News extends Report {
	
	function Settings() {		

		$this->displayReportButtons = false;
		$this->remove_outputmodes = array("all");

		$this->columnDefinitions[] = array("Label" => "_PAGEVIEWS", "icon" => "fa-sitemap");
		$this->columnDefinitions[] = array("Label" => "_VISITORS", "icon" => "fa-users");
		$this->columnDefinitions[] = array("Label" => "_COUNTRY_TRENDS", "icon" => "fa-globe");
		$this->columnDefinitions[] = array("Label" => "_PAGE_TRENDS", "icon" => "fa-file-text-o");
		$this->columnDefinitions[] = array("Label" => "_REFERRER_TRENDS", "icon" => "fa-link");
		$this->columnDefinitions[] = array("Label" => "_ERROR_TRENDS", "icon" => "fa-exclamation");
		$this->columnDefinitions[] = array("Label" => "_PERFORMANCE_TRENDS", "icon" => "fa-percent");
		$this->columnDefinitions[] = array("Label" => "_KEYWORD_TRENDS", "icon" => "fa-search");		
		$this->columnDefinitions[] = array("Label" => "_BOTS", "icon" => "fa-bug");
		$this->columnDefinitions[] = array("Label" => "_CRAWLER_TRENDS", "hide_column" => true, "icon" => "fa-android");
		//$this->columnDefinitions[] = array("Label" => "_SUSPICIOUS_TRAFFIC", "icon" => "fa-user-secret");

		if (!isset($this->threshold)) {
			$this->threshold = 30;	
		}
		if (!isset($this->sigma)) {
			$this->sigma = 1.5;	
		} else {
			$this->sigma = $this->sigma *1;	
		}

		if (isset($this->limit)) {
			// limit is not used and only set if the come from the menu, so tlet's make sure it really hides the crawler trends by default
			$this->columnDefinitions[9]["disable_line"] = true;
		}
		if ($this->to-86400 > time()) {
				// no reporting on future dates
				$this->to = mktime(23,59,59,date("m"),date("d"),date("Y"));
								
		}
		if (empty($this->sorting)) {
			$this->sorting=1;
		}
	}
	
	function GetReportData() {
		global $reports;		
		// we are gonna store all messages in this array
		$messages = [];

		// first, do visitors and pageviews
		$r = new $reports["_VISITORS_PER_DAY"]["ClassName"]();
		$r->from = $this->from;
		$r->to = $this->to;
		$data = $r->GetReportData();
		
		$pageviews = [];
		$visitors = [];
		foreach ($data as $key => $value) {
			$day = date("Ymd", strtotime($value[0]));
			$weekday = $this->Weekday($value[0]);
			// is it today?
			if ($day == date("Ymd",time()) ) {
				continue;
			}
			if (strtotime($value[0]) > time() ) {
				// no reporting on future events ;-)
				continue;				
			}
			
			$visitors[$weekday][]=$value[1];
		 	$pageviews[$weekday][]=$value[2];
		 	//$visitors[]=$value[1];
		 	//$pageviews[]=$value[2];
		}
		
		foreach ($data as $key => $value) {
			$day = date("Ymd", strtotime($value[0]));
			$weekday = $this->Weekday($value[0]);

			// is it today?
			if ($day == date("Ymd",time()) ) {
				$nonews = explode("...",_NO_NEWS_YET);
				$newstip = explode("...",_NEWS_TIP);				

				$messages[$day]['skip'] = $this->Timeitem($nonews[0]."...",$nonews[1], $icon="fa-sun-o", $class="bg-dark-gray");
				$messages[$day][] = $this->Timeitem($newstip[0],$newstip[1], $icon="fa-info", $class="bg-dark-gray");
				continue;
			}

			if (strtotime($value[0]) < $this->from ) {
				// we're not reporting on this date right now
				continue;				
			}

			if (strtotime($value[0]) > time() ) {
				// no reporting on future events ;-)
				continue;				
			}
			if ($value[2] == 0) {
				//no stats				
				$messages[$day]['skip'] = $this->Timeitem("<div style='color:red;'><strong>"._ALERT."</strong> "._NO_TRAFFIC_FOR_DAY."</div>", _NO_TRAFFIC_REASONS, $icon="fa-heartbeat", $class="bg-red");
				continue;
			}
			// pageviews
			if (!isset($this->columnDefinitions[0]["disable_line"])) {
				$sigma = $this->Sigma($pageviews[$weekday],$value[2]);
				//$sigma = $this->Sigma($pageviews,$value[2]);
			 	if (abs($sigma) > $this->sigma) {
			 		//dump($weekday);
			 		//dump($pageviews[$weekday]);
			 		$messages[$day][] = $this->MakeTimeitem(constant($this->columnDefinitions[0]["Label"]),$value[2],$this->mean,$sigma,"default");
			 	}
			}
		 	// visitors
		 	if (!isset($this->columnDefinitions[1]["disable_line"])) {
			 	$sigma = $this->Sigma($visitors[$weekday],$value[1]);
			 	//$sigma = $this->Sigma($visitors,$value[1]);
			 	if (abs($sigma) > $this->sigma) {
			 		$messages[$day][] = $this->MakeTimeitem(constant($this->columnDefinitions[1]["Label"]),$value[1],$this->mean,$sigma,"default");
			 	}
			}
		}
		
		// now, do countries
		if (!isset($this->columnDefinitions[2]["disable_line"])) {
			$r = new $reports["_COUNTRY_TRENDS"]["ClassName"]();
			$r->period="_DAYS";
			$r->limit=20;
			$r->from = $this->from;
			$r->to = $this->to;

			$data = $r->GetReportData();
			$icon = "fa-globe";
			$arrays = [];
			//dump($data);
			foreach ($data as $key => $value) {	
				$weekday = $this->Weekday($value[0]);			
				foreach($value as $k => $v) {				
					$arrays[$k][$weekday][] = $v;
				}
			}
			//dump($arrays);
			foreach ($data as $key => $value) {
				$day = date("Ymd", strtotime($value[0]));
				$weekday = $this->Weekday($value[0]);
				if (isset($messages[$day]['skip'])) {
					continue;
				}
				foreach($value as $k => $v) {		
					if ($k!=0) {
						$sigma = $this->Sigma($arrays[$k][$weekday],$v);
				 		if (abs($sigma) > $this->sigma && abs($v - $this->mean) > $this->threshold) {
				 			//dump($arrays[$k][$weekday]);

				 			$str ="visits from <a class='' onclick=\"popupActionMenu(event, '".urlencode($r->columnDefinitions[$k]['Label'])."', 'country');\" href=\"\" data-contextDate='{$value[0]}'>{$r->columnDefinitions[$k]['Label']}</a>";
				 			$messages[$day][] = $this->MakeTimeitem($str,$v,$this->mean,$sigma,$icon);
				 		}
				 	}
				}
			}
		}

		// now, do pages
		if (!isset($this->columnDefinitions[3]["disable_line"])) {
			$r = new $reports["_PAGE_TRENDS"]["ClassName"]();
			$r->period="_DAYS";
			$r->limit=20;
			$r->viewData ="pv";
			$data = $r->GetReportData();
			$icon = "fa-file-text-o";
			$arrays = [];		
			foreach ($data as $key => $value) {
				$weekday = $this->Weekday($value[0]);
				foreach($value as $k => $v) {				
					$arrays[$k][$weekday][] = $v;
				}
			}
			foreach ($data as $key => $value) {
				$day = date("Ymd", strtotime($value[0]));
				$weekday = $this->Weekday($value[0]);	
				if (isset($messages[$day]['skip'])) {
					continue;
				}
				foreach($value as $k => $v) {
					if ($k!=0) {												 
						$sigma = $this->Sigma($arrays[$k][$weekday],$v);

				 		if (abs($sigma) > $this->sigma && abs($v - $this->mean) > $this->threshold) {

				 			if ($r->columnDefinitions[$k]['Label']=="/") {$add=" (Home)"; } else { $add=""; }				 			

				 			$str =_PAGEVIEWS_ON." <a class='' data-contextDate='{$value[0]}' onclick=\"popupActionMenu(event, '".urlencode($r->columnDefinitions[$k]['Label'])."', 'page');\" href=\"\">{$r->columnDefinitions[$k]['Label']} $add</a>";
				 			$messages[$day][] = $this->MakeTimeitem($str,$v,$this->mean,$sigma,$icon);
				 		}
				 	}
				}
			}
		}

		// now, do referrers
		if (!isset($this->columnDefinitions[4]["disable_line"])) {
			$r = new $reports["_REFERRER_TRENDS"]["ClassName"]();
			$r->period="_DAYS";
			$r->limit=20;
			$data = $r->GetReportData();
			$icon = "fa-link";
			$arrays = [];		
			foreach ($data as $key => $value) {
				$weekday = $this->Weekday($value[0]);	
				foreach($value as $k => $v) {				
					$arrays[$k][$weekday][] = $v;
				}
			}
			foreach ($data as $key => $value) {
				$day = date("Ymd", strtotime($value[0]));
				$weekday = $this->Weekday($value[0]);
				if (isset($messages[$day]['skip'])) {
					continue;
				}
				foreach($value as $k => $v) {		
					if ($k!=0) {
						$sigma = $this->Sigma($arrays[$k][$weekday],$v);
				 		if (abs($sigma) > $this->sigma && abs($v - $this->mean) > $this->threshold) {

				 			if ($r->columnDefinitions[$k]['Label']=="-") { $add=" (no referrer)"; } else { $add =""; }				 			
				 			$str =_CLICKS_FROM." <a class='' data-contextDate='{$value[0]}' onclick=\"popupActionMenu(event, '".urlencode($r->columnDefinitions[$k]['Label'])."', 'referrer');\" href=\"\">{$r->columnDefinitions[$k]['Label']} $add</a>";
				 			$messages[$day][] = $this->MakeTimeitem($str,$v,$this->mean,$sigma,$icon);
				 		}
				 	}
				}
			}
		}

		// now, do errors
		if (!isset($this->columnDefinitions[5]["disable_line"])) {
			$r = new $reports["_ERROR_TRENDS"]["ClassName"]();
			$r->period="_DAYS";
			$r->limit=20;
			$data = $r->GetReportData();
			$icon = "fa-exclamation";
			$arrays = [];		
			foreach ($data as $key => $value) {
				$weekday = $this->Weekday($value[0]);
				foreach($value as $k => $v) {				
					$arrays[$k][$weekday][] = $v;
				}
			}
			foreach ($data as $key => $value) {
				$day = date("Ymd", strtotime($value[0]));
				$weekday = $this->Weekday($value[0]);
				if (isset($messages[$day]['skip'])) {
					continue;
				}
				foreach($value as $k => $v) {		
					if ($k!=0) {
						if (strpos($r->columnDefinitions[$k]['Label'], "302")!==false || strpos($r->columnDefinitions[$k]['Label'], "301")!==false) {
							continue;
						}
						//dump($r->columnDefinitions)	;
						$sigma = $this->Sigma($arrays[$k][$weekday],$v);
				 		if (abs($sigma) > $this->sigma && abs($v - $this->mean) > $this->threshold) {
				 			
				 			$str =_REQUESTS_WITH_STATUS." <a class='' data-contextDate='{$value[0]}' onclick=\"popupActionMenu(event, '".urlencode($r->columnDefinitions[$k]['Label'])."', 'error');\" href=\"\">{$r->columnDefinitions[$k]['Label']}</a>";
				 			$messages[$day][] = $this->MakeTimeitem($str,$v,$this->mean,$sigma,$icon);
				 		}
				 	}
				}
			}
		}

		if (!isset($this->columnDefinitions[6]["disable_line"])) {
			// now, do performance
			$r = new $reports["_PERFORMANCE_TRENDS"]["ClassName"]();
			$r->period="_DAYS";
			$r->limit=20;
			//$this->conversion_mode = _CONVERTED_VISITORS;
			$data = $r->GetReportData();
			$icon = "fa-percent";
			$arrays = [];		
			foreach ($data as $key => $value) {
				$weekday = $this->Weekday($value[0]);
				foreach($value as $k => $v) {				
					$arrays[$k][$weekday][] = $v;
				}
			}
			
			foreach ($data as $key => $value) {
				$day = date("Ymd", strtotime($value[0]));
				$weekday = $this->Weekday($value[0]);
				if (isset($messages[$day]['skip'])) {
					continue;
				}
				foreach($value as $k => $v) {		
					if ($k!=0) {
						//dump($r->columnDefinitions)	;
						$sigma = $this->Sigma($arrays[$k][$weekday],$v);
				 		if (abs($sigma) > $this->sigma && $v > 1) {	
				 			$str =_CONVERSIONS_TO_TARGET." <a class='' data-contextDate='{$value[0]}' onclick=\"popupActionMenu(event, '".urlencode($r->columnDefinitions[$k]['Label'])."', 'kpi');\" href=\"\">{$r->columnDefinitions[$k]['Label']}</a>";
				 			$messages[$day][] = $this->MakeTimeitem($str,$v,$this->mean,$sigma,$icon);
				 		}
				 	}
				}
			}
		}

		// now, do keywords
		if (!isset($this->columnDefinitions[7]["disable_line"])) {
			$r = new $reports["_KEYWORD_TRENDS"]["ClassName"]();
			$r->period="_DAYS";
			$r->limit=20;
			//$this->conversion_mode = _CONVERTED_VISITORS;
			$data = $r->GetReportData();
			$icon = "fa-search";
			$arrays = [];		
			foreach ($data as $key => $value) {
				$weekday = $this->Weekday($value[0]);
				foreach($value as $k => $v) {				
					$arrays[$k][$weekday][] = $v;
				}
			}
			foreach ($data as $key => $value) {
				$day = date("Ymd", strtotime($value[0]));
				$weekday = $this->Weekday($value[0]);
				if (isset($messages[$day]['skip'])) {
					continue;
				}
				foreach($value as $k => $v) {		
					if ($k!=0) {					
						$sigma = $this->Sigma($arrays[$k][$weekday],$v);			 		
						if (abs($sigma) > $this->sigma && abs($v - $this->mean) > ($this->threshold/2)) {							
				 			$str =_VISITS_FROM_SEARCH_TERM.": <a class='' data-contextDate='{$value[0]}' onclick=\"popupActionMenu(event, '".urlencode($r->columnDefinitions[$k]['Label'])."', 'keyword');\" href=\"\">{$r->columnDefinitions[$k]['Label']}</a>";
				 			$messages[$day][] = $this->MakeTimeitem($str,$v,$this->mean,$sigma,$icon);
				 		}
				 	}
				}
			}
		}

		// now, do overall crawler activity
		if (!isset($this->columnDefinitions[8]["disable_line"])) {
			$r = new $reports["_ALL_TRAFFIC_BY_DAY"]["ClassName"]();
			$r->period="_DAYS";
			$r->limit=20;
			$data = $r->GetReportData();
			$icon = "fa-bug";
			$crawlers = [];		
			foreach ($data as $key => $value) {
				//we want crawled pages
				$weekday = $this->Weekday($value[0]);
				$crawlers[$weekday][] = round( ($value[4]/100) * $value[2] );
			}
			foreach ($data as $key => $value) {
				$v = intval( ($value[4]/100) * $value[2] );
				$day = date("Ymd", strtotime($value[0]));
				$weekday = $this->Weekday($value[0]);
				if (isset($messages[$day]['skip'])) {
					continue;
				}
				$sigma = $this->Sigma($crawlers[$weekday],$v);
		 		if (abs($sigma) > $this->sigma && abs($v - $this->mean) > $this->threshold) {		 			
		 			$str =_REQUESTS_FROM." <a href='reports.php?labels=_CRAWLER_TRENDS&from=$this->from&to=$this->to&conf={$this->profile->profilename}' class='open_in_new_dialog' type='_CRAWLER_TRENDS'>Bots</a>";
		 			$messages[$day][] = $this->MakeTimeitem($str,$v,$this->mean,$sigma,$icon);
		 		}
				
			}
		}

		if (isset($this->showColumn9)) {
			// now, do individual crawlers
			$r = new $reports["_CRAWLER_TRENDS"]["ClassName"]();
			$r->period="_DAYS";
			$r->limit=20;
			$data = $r->GetReportData();
			$icon = "fa-android";
			$arrays = [];		
			foreach ($data as $key => $value) {
				$weekday = $this->Weekday($value[0]);
				foreach($value as $k => $v) {				
					$arrays[$k][$weekday][] = $v;
				}
			}
			foreach ($data as $key => $value) {
				$day = date("Ymd", strtotime($value[0]));
				$weekday = $this->Weekday($value[0]);
				if (isset($messages[$day]['skip'])) {
					continue;
				}
				foreach($value as $k => $v) {		
					if ($k!=0) {						
						$sigma = $this->Sigma($arrays[$k][$weekday],$v);
				 		if (abs($sigma) > $this->sigma && abs($v - $this->mean) > $this->threshold) {

				 			$str =_REQUESTS_FROM." bot: <a class='' data-contextDate='{$value[0]}' onclick=\"popupActionMenu(event, '".urlencode($r->columnDefinitions[$k]['Label'])."', 'crawler');\" href=\"\">{$r->columnDefinitions[$k]['Label']}</a>";
				 			$messages[$day][] = $this->MakeTimeitem($str,$v,$this->mean,$sigma,$icon);
				 		}
				 	}
				}
			}
		}

		// now, do overall suspicious activity
		// if (!isset($this->columnDefinitions[10]["disable_line"])) {
		// 	$r = new $reports["_SUSPICIOUS_TRAFFIC"]["ClassName"]();
		// 	$data = $r->GetReportData();
		// 	$icon = "fa-user-secret";
		// 	$suspect = [];		
		// 	foreach ($data as $key => $value) {
		// 		//we want crawled pages
		// 		$weekday = $this->Weekday($value[0]);
		// 		$suspect[$weekday][] = $value[2];
		// 	}
		// 	foreach ($data as $key => $value) {
		// 		$v = $value[2];
		// 		$day = date("Ymd", strtotime($value[0]));
		// 		$weekday = $this->Weekday($value[0]);
		// 		if (isset($messages[$day]['skip'])) {
		// 			continue;
		// 		}
		// 		$sigma = $this->Sigma($suspect[$weekday],$v);
		//  		if (abs($sigma) > $this->sigma && abs($v - $this->mean) > $this->threshold) {
		 			
		//  			$str ="<a class='open_in_new_dialog' type='_SUSPICIOUS_TRAFFIC' name='"._SUSPICIOUS_TRAFFIC."' rel='' href=\"reports.php?labels=_SUSPICIOUS_TRAFFIC&from=$this->from&to=$this->to&conf={$this->profile->profilename}\">suspicious visitors</a> ";
		//  			$messages[$day][] = $this->MakeTimeitem($str,$v,$this->mean,$sigma,$icon);
		//  		}
				
		// 	}
		// }
		if ($this->sorting==1) {
			krsort($messages);
		} else {
			ksort($messages);
		}		
		return $messages;
	}

	function Weekday($date) {
		$weekday = date("D", strtotime($date));
		if ($weekday == "Sat" || $weekday == "Sun") {
			return $weekday;
		} else {
			return "weekday";
		}
	}
	function DisplayReport() {		

		$this->ReportHeader();
		$messages = $this->GetReportData();
		
		?>
		<style>
		.bg-light-yellow { background-color: #FFB71C !important; color:#FFF !important; }
		.newslegend { margin-right: 6px; font-size:12px}
		.newslegend i { border-radius: 50%; width: 10px; height:10px; }
		.newslegendtopic i { border-radius: 50%; border:0; width:30px;height:30px;border: 1px solid #ccc; line-height: 30px; color:#666; cursor:pointer;}
		.newslegendtopic .selected { border: 1px solid #00C0EF;box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2); }

		.bg-inc-level1 { background-color: #436A39 !important; color:#BEFEAE !important; }
		.bg-inc-level2 { background-color: #22A302 !important; color:#e0e0e0 !important;}
		.bg-inc-level3 { background-color: #5DFD35 !important; color: #0F6402 !important;}

		</style>
		
		<div style="text-align:center">
			<span class='newslegend'><?php echo ucfirst(_INCREASE);?>:</span>
			<span class='newslegend'><i class="fa bg-inc-level1"></i> <?php echo _UNUSUAL;?></span>
			<span class='newslegend'><i class="fa bg-inc-level2"></i> <?php echo _EXTREME;?></span>
			<span class='newslegend'><i class="fa bg-inc-level3"></i> <?php echo _BIZARRE;?></span>			
			<br>
			<span class='newslegend'><?php echo ucfirst(_DECREASE);?>:</span>
			<span class='newslegend'><i class="fa bg-light-yellow"></i> <?php echo _UNUSUAL;?></span>
			<span class='newslegend'><i class="fa bg-orange"></i> <?php echo _EXTREME;?></span>
			<span class='newslegend'><i class="fa bg-red"></i> <?php echo _BIZARRE;?></span>
		</div>

		
		<div style="clear:both;">&nbsp;</div>

		<div style="text-align:center">	
			<span class='newslegend'>Show Topics:</span>
			<?php
			foreach ($this->columnDefinitions as $col) {
				if ($col['Label']=="_CRAWLER_TRENDS" && !isset($this->showColumn9)) {
					continue;
				} else if (isset($col['disable_line'])) {
					continue;
				}
				echo "<span class='newslegendtopic'><i class='fa {$col['icon']} selected' data-type='{$col['icon']}' title='".constant($col['Label'])."'></i> </span>";
			}
			?>			
		</div>
		
		<div style="clear:both;">&nbsp;</div>

		<?php

		echo '<ul class="news timeline">';
		foreach($messages as $day => $items) {
			$prettyday = date("D, d M Y",strtotime($day));
			$this->Timelabel($prettyday);
			foreach ($items as $message) {
				echo $message;
			}

		}
		echo '</ul>';
		//echo count($messages)." ";
		
	}

	function DisplayCustomForm() {
		
		// echo "<div class='form-group'>";
		// 	echo "<label for='sigma'>Sensitivity</label>";
		// 	echo "<input type=text class='form-control' name='sigma' id='sigma' value='{$this->sigma}' title='Any events below this sigma/z-score will be skipped.'>";
		// echo "</div>";

		echo "<div class='form-group'>";
			echo "<label for='sigma'>"._NEWS_SCORE."</label>";

			echo "<select id='sigma' class='form-control' name='sigma' title='"._NEWS_SCORE_LEVEL."'>";
					$sl= "<option value='1'>1.0 - "._NEWS_SCORE_LEVEL1."</option>";										
					$sl.= "<option value='1.5'>1.5 - "._NEWS_SCORE_LEVEL2."...</option>";
					$sl.= "<option value='2'>2.0 - "._NEWS_SCORE_LEVEL3."</option>";										
					$sl.= "<option value='2.5'>2.5 - "._NEWS_SCORE_LEVEL4."</option>";
					$sl.= "<option value='3'>3 - "._NEWS_SCORE_LEVEL5."</option>";
					$sl = str_replace("'$this->sigma'", "'$this->sigma' selected", $sl);
					echo $sl;
				
			echo "</select>";
		echo "</div>";		

		echo "<div class='form-group'>";
			echo "<label for='threshold'>"._NEWS_THRESH."</label>";
			echo "<input type=text class='form-control' name='threshold' id='threshold' value='{$this->threshold}' title='"._NEWS_THRESH_TITLE."'>";
		echo "</div>";

		echo "<div class='form-group'>";
			echo "<label for='sorting'>"._SORT."</label>";
			echo "<select id='sorting' class='form-control' name='sorting' title='"._NEWS_SORT_TITLE."'>";
					$sl= "<option value='1'>"._SORT_NEW_FIRST."</option>";										
					$sl.= "<option value='2'>"._SORT_CHRONO."</option>";
					$sl = str_replace("'$this->sorting'", "'$this->sorting' selected", $sl);
					echo $sl;
				
			echo "</select>";
		echo "</div>";

	}

	function Timelabel($str, $class="bg-blue") {		
		echo '<li class="time-label"><span class="'.$class.'">'.$str.' <i class="fa fa-angle-down"></i></span></li>'.PHP_EOL;
	}
	function Timeitem($headline, $txt, $icon="fa-sign-in", $class="bg-aqua") {		
		$item  = "<li><i class=\"fa $icon $class\" data-type='$icon'></i><div class=\"timeline-item\">";
		if (!empty($headline)) {		
        	$item .= "<h3 class=\"timeline-header\">$headline</h3>";
        }
        $item .= "<div class=\"timeline-body\"> $txt </div></div></li>".PHP_EOL;
        return $item;
		
	}
	function MakeTimeitem($metric_name, $val, $mean, $sigma, $icon="default", $data=false) {
		
		//choose an icon
		if ($icon == "default") {
			switch ($metric_name) {
				case 'Pageviews':
					$icon="fa-sitemap";
					$metric_name="<a href='reports.php?labels=_VISITORS_PER_DAY&from={$this->from}&to={$this->to}&conf={$this->profile->profilename}&pageviews=1' type='_VISITORS_PER_DAY' class='open_in_new_dialog'>$metric_name</a>"; 
					break;
				
				case 'Visitors':
					$icon="fa-users";
					$metric_name="<a href='reports.php?labels=_TREND_ANALYSIS&from={$this->from}&to={$this->to}&conf={$this->profile->profilename}' type='_TREND_ANALYSIS' class='open_in_new_dialog'>$metric_name</a>";	
					break;			

				default:
					$icon="fa-line-chart";
					break;
			}
		}
		

		//synonyms to make it look more organic
		$unusual_low[] = str_replace('$metric_name', $metric_name, _NEWS_ULOW1);
		$unusual_low[] = str_replace('$metric_name', $metric_name, _NEWS_ULOW2);
		$unusual_low[] = str_replace('$metric_name', ucfirst($metric_name), _NEWS_ULOW3);
		$unusual_low[] = str_replace('$metric_name', $metric_name, _NEWS_ULOW4);

		$extreme_low[] = str_replace('$metric_name', $metric_name, _NEWS_ELOW1);
		$extreme_low[] = str_replace('$metric_name', $metric_name, _NEWS_ELOW2);
		$extreme_low[] = str_replace('$metric_name', $metric_name, _NEWS_ELOW3);
		$extreme_low[] = str_replace('$metric_name', $metric_name, _NEWS_ELOW4);

		$unusual_high[] = str_replace('$metric_name', $metric_name, _NEWS_UHIGH1);
		$unusual_high[] = str_replace('$metric_name', $metric_name, _NEWS_UHIGH2);
		$unusual_high[] = str_replace('$metric_name', $metric_name, _NEWS_UHIGH3);
		$unusual_high[] = str_replace('$metric_name', $metric_name, _NEWS_UHIGH4);

		$extreme_high[] = str_replace('$metric_name', $metric_name, _NEWS_EHIGH1);
		$extreme_high[] = str_replace('$metric_name', ucfirst($metric_name), _NEWS_EHIGH2);
		$extreme_high[] = str_replace('$metric_name', $metric_name, _NEWS_EHIGH3);
		$extreme_high[] = str_replace('$metric_name', ucfirst($metric_name), _NEWS_EHIGH4);
		
		// make a headline
		if ($sigma <= -0.5 && $sigma > -2) {
			$headline = $unusual_low[rand(0,3)];
			$class="bg-light-yellow";
		}
		if ($sigma <= -2 && $sigma > -3) {
			$headline = $extreme_low[rand(0,3)];
			$class="bg-orange";
		}
		if ($sigma <= -3) {			
			$headline = str_replace('$metric_name', $metric_name, _NEWS_MELTDOWN);
			$class="bg-red";
		}
		if ($sigma >= 0.5 && $sigma < 2) {
			$headline = $unusual_high[rand(0,3)];
			$class="bg-inc-level1";
		}
		if ($sigma >= 2 && $sigma < 3) {
			$headline = $extreme_high[rand(0,3)];
			$class="bg-inc-level2";
		}
		
		if ($sigma >= 3) {			
			$headline = str_replace('$metric_name', $metric_name, _NEWS_OFFTHECHARTS);
			$class="bg-inc-level3";
		}

		// make a story text
		$diff =	number_format(($val / $mean * 100) - 100);
		if ($diff > 0) { 
			$diff = "<span class='text-success'>+".$diff."%</span>"; 
			$dicon = "fa-arrow-up success";
		} else {
			$diff = "<span class='text-danger'>".$diff."%</span>"; 
			$dicon = "fa-arrow-down danger";
		}
		
		if (is_float($val + 0)) {			
			$val = number_format($val,2);
		} else {
			$val = number_format($val);
		}
		if (is_float($mean + 0) && $mean < 10) {
			$mean = number_format($mean,2);
		} else {
			$mean = number_format($mean);
		}
		$datastr="";		
		if ($data!==false) {
			$c = count($data);
			$datastr = implode(", ",$data);
			$datastr = "Based on sigma score ".number_format($sigma,2)." using $c data points: $datastr";
		}
		$text= str_replace('XX', $val, _NEWS_COMPARE_NUM);
		$text= str_replace('YY', $mean, $text);
		$text = $text." <span class='pull-right' title='$datastr'><i class ='fa $dicon'></i> {$diff}</span>";
		if (!isset($headline)) {
			echo "$metric_name, $sigma";
		}
		return $this->Timeitem($headline, $text, $icon, $class);
	}
}