1<?php
2/*
3 * e107 website system
4 *
5 * Copyright (C) 2008-2013 e107 Inc (e107.org)
6 * Released under the terms and conditions of the
7 * GNU General Public License (http://www.gnu.org/licenses/gpl.txt)
8 *
9 *	Stats logging plugin - admin functions
10 *
11 */
12
13require_once('../../class2.php');
14
15if (!getperms('P') || !e107::isInstalled('log'))
16{
17	e107::redirect('admin');
18	exit;
19}
20
21
22if(e_AJAX_REQUEST && varset($_GET['action']) == 'rebuild')
23{
24	require_once(e_PLUGIN."log/consolidate.php");
25	$lgc = new logConsolidate;
26
27	$count = $_SESSION['stats_log_files_count'];
28	$file = $_SESSION['stats_log_files'][$count]['path'];
29	$totalFiles = $_SESSION['stats_log_files_total'] - 1;
30	//$process = true;
31
32	$lg = e107::getAdminLog();
33//	$lg->addDebug(print_r($logVals, true));
34
35
36	if($_SESSION['stats_log_files'][$count]['complete'] != 1)
37	{
38		$_SESSION['stats_log_files'][$count]['complete'] = 1;
39	//	$lg->addSuccess($count."/".$totalFiles."\t".$file." processing", false);
40	//	if($process)
41		if($lgc->processRawBackupLog($file, true))
42		{
43
44		//	sleep(3);
45			$lg->addSuccess($count."/".$totalFiles."\t".$file." processed.", false);
46			$_SESSION['stats_log_files'][$count]['complete'] = 1;
47			$_SESSION['stats_log_files_count']++;
48		}
49		else
50		{
51			$lg->addError($count."/".$totalFiles."\t".$file." failed.", false);
52		}
53	}
54	else
55	{
56		$lg->addWarning($count."/".$totalFiles."\t".$file." skipped", false);
57		$_SESSION['stats_log_files_count']++;
58	}
59
60
61	$totalOutput = round(( $count/ $totalFiles) * 100, 1);
62
63	if($totalOutput > 99.9)
64	{
65		echo 100;
66		if($lgc->collatePageTotalDB())
67		{
68			$lg->addSuccess("Processed All-Time PageTotal", false);
69		}
70		else
71		{
72			$lg->addError("Failed to Process All-Time PageTotal", false);
73		}
74
75		$lg->addSuccess("Processing Complete.", false);
76
77	}
78	else
79	{
80		echo $totalOutput;
81	}
82
83	$lg->toFile('SiteStatsUpgrade','Statistics Update Log', true);
84
85	exit;
86
87}
88
89define('LogFlagFile', 'LogFlag.php');
90
91e107::includeLan(e_PLUGIN.'log/languages/'.e_LANGUAGE.'.php');
92e107::includeLan(e_PLUGIN.'log/languages/'.e_LANGUAGE.'_admin.php');
93
94if(!is_writable(e_LOG))
95{
96	//$message = "<b>".ADSTAT_LAN_38."</b>";
97	e107::getMessage()->addError(ADSTAT_LAN_28);
98}
99
100e107::css('inline', 'td.last.options { padding-right:20px } ');
101
102	// Needed on Windoze platforms - not an ideal solution!
103	if (!function_exists('nl_langinfo'))
104	{
105		define('MON_1',86400);
106		define('MON_2',2764800);
107		define('MON_3',5443200);
108		define('MON_4',8035200);
109		define('MON_5',10800000);
110		define('MON_6',13392000);
111		define('MON_7',15811200);
112		define('MON_8',19008000);
113		define('MON_9',21168000);
114		define('MON_10',23760000);
115		define('MON_11',26352000);
116		define('MON_12',28944000);
117
118		function nl_langinfo($mon)
119		{
120			return date('F',$mon);
121		}
122	}
123
124
125
126
127	class log_adminArea extends e_admin_dispatcher
128	{
129
130		protected $modes = array(
131
132			'main'	=> array(
133				'controller' 	=> 'logstats_ui',
134				'path' 			=> null,
135				'ui' 			=> 'logstats_form_ui',
136				'uipath' 		=> null
137			),
138
139
140		);
141
142
143		protected $adminMenu = array(
144
145			'main/prefs'		=> array('caption'=> LAN_SETTINGS, 'perm' => 'P'),
146			'main/list'			=> array('caption'=> ADSTAT_LAN_48, 'perm' => 'P'),
147			'main/export'		=> array('caption'=> ADSTAT_LAN_36, 'perm' => 'P'),
148			'main/datasets'		=> array('caption'=> ADSTAT_LAN_63, 'perm' => 'P'),
149			'main/rempage'		=> array('caption'=> ADSTAT_LAN_26, 'perm' => 'P'),
150			'main/history'		=> array('caption'=> ADSTAT_LAN_69, 'perm' => 'P'),
151			'main/rebuild'      => array('caption'=> ADSTAT_LAN_87, 'perm'=> 'P'),
152		);
153
154
155
156
157
158		protected $adminMenuAliases = array(
159			'main/edit'	=> 'main/list'
160		);
161
162		protected $menuTitle = ADSTAT_L3;
163	}
164
165
166	// List of the non-page-based info which is gathered - historically only 'all-time' stats, now we support monthly as well
167	$stats_list = array('statBrowser'=>ADSTAT_LAN_6,'statOs'=>ADSTAT_LAN_7,'statScreen'=>ADSTAT_LAN_8,'statDomain'=>ADSTAT_LAN_9,'statReferer'=>ADSTAT_LAN_10,'statQuery'=>ADSTAT_LAN_11);
168
169	$separator_list = array(1 => ADSTAT_LAN_57, 2 => ADSTAT_LAN_58);
170	$separator_char = array(1 => ',', 2 => '|');
171	$quote_list = array(1 => ADSTAT_LAN_50, 2 => ADSTAT_LAN_55, 3 => ADSTAT_LAN_56);
172	$quote_char = array(1 => '', 2 => "'", 3 => '"');
173
174
175	//---------------------------------------------
176	//		Export data file
177	//---------------------------------------------
178	$export_filter = '';		// can be 'LIKE', 'REGEX', or simple equality
179	$export_type = $tp->toDB(varset($_POST['export_type'],'page'));				// Page data or one of the other bits of info
180	$export_date = intval(varset($_POST['export_date'],1));
181	$export2_date = intval(varset($_POST['export2_date'],3));
182	$export_year = intval(varset($_POST['export_year'],date('Y')));
183	$export_month = intval(varset($_POST['export_month'],date('m')));
184	$export_day = intval(varset($_POST['export_day'],date('j')));
185	$export_char = varset($_POST['export_char'], 1);
186	$export_quote = varset($_POST['export_quote'], 1);
187	$export_stripurl = varset($_POST['export_stripurl'], 0);
188
189
190
191
192
193
194
195
196	class logstats_ui extends e_admin_ui
197	{
198
199		protected $pluginTitle		= ADSTAT_L3;
200		protected $pluginName		= 'log';
201		//	protected $eventName		= 'log-logstats'; // remove comment to enable event triggers in admin.
202		protected $table			= 'logstats';
203		protected $pid				= 'log_uniqueid';
204		protected $perPage			= 10;
205		protected $batchDelete		= true;
206		//	protected $batchCopy		= true;
207		//	protected $sortField		= 'somefield_order';
208		//	protected $orderStep		= 10;
209		//	protected $tabs				= array('Tabl 1','Tab 2'); // Use 'tab'=>0  OR 'tab'=>1 in the $fields below to enable.
210		protected $listQry              = "SELECT * FROM `#logstats` WHERE `log_id` = 'pageTotal' OR (`log_id` REGEXP '^[0-9]' AND LENGTH(log_id) > 7 AND LENGTH(log_id) < 11) ";
211
212		//	protected $listQry      	= "SELECT * FROM `#tableName` WHERE field != '' "; // Example Custom Query. LEFT JOINS allowed. Should be without any Order or Limit.
213
214		protected $listOrder		= 'CASE log_id WHEN "pageTotal" THEN 9999 ELSE DATE(log_id) END DESC  ';
215
216
217		protected $fields 		= array (  'checkboxes' =>   array ( 'title' => '', 'type' => null, 'data' => null, 'width' => '5%', 'thclass' => 'center', 'forced' => '1', 'class' => 'center', 'toggle' => 'e-multiselect',  ),
218		                                    'log_uniqueid' =>   array ( 'title' => LAN_ID, 'data' => 'int', 'width' => '5%', 'help' => '', 'readParms' => '', 'writeParms' => '', 'class' => 'left', 'thclass' => 'left',  ),
219		                                    'log_id' =>   array ( 'title' => LAN_DATE, 'type' => 'method', 'data' => 'str', 'width' => 'auto', 'help' => '', 'readParms' => '', 'writeParms' => '', 'class' => 'left', 'thclass' => 'left',  ),
220		                                    'log_data' =>   array ( 'title' => ADSTAT_L21, 'type' => 'method', 'data' => 'str', 'width' => '20%', 'help' => '', 'readParms' => '', 'writeParms' => '', 'class' => 'right', 'thclass' => 'right',  ),
221		                                    'log_data2' =>   array ( 'title' => ADSTAT_L22, 'type' => 'method', 'data' => false, 'width' => '20%', 'help' => '', 'readParms' => '', 'writeParms' => '', 'class' => 'right', 'thclass' => 'right',  ),
222
223		                                    'options' =>   array ( 'title' => LAN_OPTIONS, 'type' => 'method', 'data' => null, 'width' => '15%', 'thclass' => 'right last', 'class' => 'right last', 'forced' => '1',  ),
224		);
225
226		protected $fieldpref = array();
227
228
229		//	protected $preftabs        = array('General', 'Other' );
230		protected $prefs = array(
231		);
232
233
234		public function init()
235		{
236			if(!empty($_POST['rebuild']))
237			{
238				require_once(e_PLUGIN.'log/consolidate.php');
239				$lgc = new logConsolidate();
240				$file = $_POST['rebuild']."_SiteStats.log";
241				$lgc->processRawBackupLog($file, true);
242			}
243
244			if(!empty($_POST['rebuildTotal']))
245			{
246				require_once(e_PLUGIN.'log/consolidate.php');
247				$lgc = new logConsolidate();
248
249				if($lgc->collatePageTotalDB())
250				{
251					e107::getMessage()->addSuccess(LAN_UPDATED);
252				}
253				else
254				{
255					e107::getMessage()->addError(LAN_UPDATED_FAILED);
256				}
257
258			}
259
260			// Set drop-down values (if any).
261			if (isset($_POST['updatesettings']))
262			{
263				$this->prefsPageSubmit();
264			}
265
266			if(isset($_POST['remSelP']))
267			{
268				$this->rempagePageSubmit();	 // Do the deletions - then redisplay the list of pages
269			}
270
271
272			if(isset($_POST['wipeSubmit']))
273			{
274				$this->wipe();
275			}
276		}
277
278
279		/**
280		 * Wipe accumulated stats
281		 */
282		private function wipe()
283		{
284			$sql = e107::getDb();
285
286			$logStr = '';
287			foreach($_POST['wipe'] as $key => $wipe)
288			{
289				switch($key)
290				{
291					case "statWipePage":
292						$sql->update("logstats", "log_data='' WHERE log_id='pageTotal' ");
293						$sql->update("logstats", "log_data='' WHERE log_id='statTotal' ");
294						$sql->update("logstats", "log_data='' WHERE log_id='statUnique' ");
295						break;
296
297					case "statWipeBrowser":
298						$sql->update("logstats", "log_data='' WHERE log_id='statBrowser' ");
299						break;
300
301					case "statWipeOs":
302						$sql->update("logstats", "log_data='' WHERE log_id='statOs' ");
303						break;
304
305					case "statWipeScreen":
306						$sql->update("logstats", "log_data='' WHERE log_id='statScreen' ");
307						break;
308
309					case "statWipeDomain":
310						$sql->update("logstats", "log_data='' WHERE log_id='statDomain' ");
311						break;
312
313					case "statWipeRefer":
314						$sql->update("logstats", "log_data='' WHERE log_id='statReferer' ");
315						break;
316
317					case "statWipeQuery":
318						$sql->update("logstats", "log_data='' WHERE log_id='statQuery' ");
319						break;
320
321				}
322
323				$logStr .= '[!br!]'.$key;
324			}
325
326			e107::getLog()->add('STAT_01',ADSTAT_LAN_81.$logStr,'');
327
328			e107::getMessage()->addSuccess(LAN_UPDATED);
329
330		}
331
332		private function get_for_delete($keep_year,$keep_month = 1, $filter='*')
333		{
334
335			$sql = e107::getDb();
336
337			global $stats_list;
338			$ret = array();
339			// Its tedious, but the filter criteria are sufficiently tricky that its probably best to read all records and decide what can go
340			if ($sql->select('logstats','log_id'))
341			{
342				while ($row = $sql->fetch())
343				{
344					$can_go = FALSE;
345					$check = FALSE;
346					$data_type = 'unknown';
347					$date_info = $row['log_id'];
348					if (($temp = strpos($date_info,':')) !== FALSE)
349					{  // its monthly browser stats and similar
350//	    echo "Checking {$date_info}, posn = {$temp} ";
351						$data_type = substr($date_info,0,$temp);
352						$date_info = substr($date_info,$temp+1);
353						$check = TRUE;
354//		echo "Date string: {$date_info}, data type: {$data_type}<br />";
355						if (isset($stats_list[$data_type])) $data_type = $stats_list[$data_type];
356					}
357					list($poss_year,$poss_month,$poss_day) = explode('-',$date_info.'--',3);
358					if (!$check)
359					{
360						if (is_numeric($poss_year))
361						{
362							$check = TRUE;
363							if ($poss_day > 0) $data_type = 'daily'; else $data_type = 'monthly';
364						}
365					}
366					if ($check)
367					{
368						if ($keep_year == $poss_year)
369						{
370							if (($poss_month > 0) && ($poss_month < $keep_month)) $can_go = TRUE;
371						}
372						elseif ($keep_year > $poss_year) $can_go = TRUE;
373					}
374					if ($can_go)
375					{
376						$ret[$row['log_id']] = $row['log_id']." - ".$data_type;
377					}
378				}
379			}
380
381			return $ret;
382
383		}
384
385		private function data_type_select($name,$value)
386		{
387			global $stats_list;
388
389			$ret = "<select name='{$name}' class='tbox'  onchange=\"settypebox(this.value);\">\n
390			<option value='page' ".($value == 'page' ? " selected='selected'" : "").">".ADSTAT_LAN_52."</option>\n";
391
392			foreach ($stats_list as $k=>$v)
393			{
394				$ret .= "<option value='{$k}' ".($value == $k ? " selected='selected'" : "").">{$v}</option>\n";
395			}
396			$ret .= "</select>\n";
397			return $ret;
398		}
399
400
401
402		private function gen_select($prompt,$name,$value)
403		{
404			$ret = "<div class='control-group clearfix' >
405	        <span class='pull-left float-left'>".$prompt."</span><span class='pull-right'><select name='{$name}' class='tbox'>\n
406			<option value='0' ".($value == 0 ? " selected='selected'" : "").">".ADSTAT_LAN_50."</option>\n
407			<option value='1' ".($value == 1 ? " selected='selected'" : "").">".ADSTAT_LAN_49."</option>\n
408			<option value='2' ".($value == 2 ? " selected='selected'" : "").">".ADSTAT_LAN_48."</option>\n
409			</select></span></div>";
410			return $ret;
411		}
412
413
414		function datasetsPage()
415		{
416			return $this->export('datasets');
417		}
418
419		function exportPage()
420		{
421			return $this->export('export');
422		}
423
424		private function export($action)
425		{
426			global $export_type, $export_date, $export2_date, $export_day, $export_month, $export_year, $separator_list,
427			       $export_char, $quote_list, $export_quote, $export_filter;
428
429			$frm = e107::getForm();
430			$sql = e107::getDb();
431
432			$text = "<div style='text-align:center'>";
433
434			if ($action == 'export')
435			{
436				$text .= "<form method='post' action='".e_PLUGIN."log/stats_csv.php?export'>";
437			}
438			else
439			{
440				$text .= "<form method='post' action='".e_SELF."?".e_QUERY."'>";
441			}
442
443			$text .= "<table class='table adminform'>
444			<colgroup>
445			  <col style='width:50%' />
446			  <col style='width:50%' />
447			</colgroup>
448			";
449
450			if ($action == 'export')
451			{
452				$text .= "<tr><td colspan = '2'>".ADSTAT_LAN_67."</td></tr>";
453			}
454			else
455			{
456				$text .= "<tr><td colspan = '2'>".ADSTAT_LAN_68."</td></tr>";
457			}
458
459			// Type of output data - page data, browser stats....
460			$text .= "<tr><td>".ADSTAT_LAN_51."</td><td>\n".$this->data_type_select('export_type',$export_type).'</td></tr>';
461				// Period selection type for page data
462			$text .= "<tr><td>".ADSTAT_LAN_41."</td><td>\n
463			<select class='tbox' name='export_date' id='export_date' onchange=\"setdatebox(this.value);\" ".($export_type=='page' ? "" : "style='display:none'" ).">\n
464			<option value='1' ".($export_date==1 ? " selected='selected'" : '') . ">".ADSTAT_LAN_42."</option>\n
465			<option value='2' ".($export_date==2 ? " selected='selected'" : '') . ">".ADSTAT_LAN_43."</option>\n
466			<option value='3' ".($export_date==3 ? " selected='selected'" : '') . ">".ADSTAT_LAN_44."</option>\n
467			<option value='4' ".($export_date==4 ? " selected='selected'" : '') . ">".ADSTAT_LAN_45."</option>\n
468			<option value='5' ".($export_date==5 ? " selected='selected'" : '') . ">".ADSTAT_LAN_62."</option>\n
469			</select>";
470
471			// Period selection type for non-page data
472			$text .= "
473				<select class='tbox' name='export2_date' id='export2_date' onchange=\"setdatebox(this.value);\"  ".($export_type=='page' ? "style='display:none'" : "").">\n
474				<option value='3'".($export2_date==3 ? " selected='selected'" : "").">".ADSTAT_LAN_44."</option>\n
475				<option value='4'".($export2_date==4 ? " selected='selected'" : "").">".ADSTAT_LAN_45."</option>\n
476				</select>";
477
478			$text .= "</td></tr>";
479
480
481
482			$text .= "<tr><td>".ADSTAT_LAN_46."</td><td>\n";
483
484
485					// Now put the various dropdowns - their visibility is controlled by the export_type dropdown
486
487					$text .= "<select class='tbox' name='export_day' id='export_day'>\n";
488					for ($i = 1; $i < 32; $i++)
489					{
490						$selected = $export_day == $i ? " selected='selected'" : "";
491						$text .= "<option value='{$i}' {$selected} >{$i}</option>\n";
492					};
493					$text .= "</select>\n&nbsp;&nbsp;&nbsp;";
494
495
496					$text .= "<select class='tbox' name='export_month' id='export_month'>\n";
497					for ($i = 1; $i < 13; $i++)
498					{
499						$selected = $export_month == $i ? " selected='selected'" : "";
500						$text .= "<option value='{$i}' {$selected}>".nl_langinfo(constant('MON_'.$i))."</option>\n";
501					};
502					$text .= "</select>\n&nbsp;&nbsp;&nbsp;";
503
504					$this_year = date("Y");
505					$text .= "<select class='tbox' name='export_year' id='export_year'>\n";
506					for ($i = $this_year; $i > $this_year - 6; $i--)
507					{
508						$selected = $export_year == $i ? " selected='selected'" : "";
509						$text .= "<option value='{$i}' {$selected}>{$i}</option>\n";
510					};
511					$text .= "</select>\n&nbsp;&nbsp;&nbsp;";
512
513					$text .= "<span id='export_cumulative' style='display: none'>".ADSTAT_LAN_53."</span>\n";
514
515					$text .= "</td></tr>";
516
517
518					if ($action == 'export')
519					{
520						// Separators, quotes
521						$text .= "<tr><td>".ADSTAT_LAN_59."</td><td>\n
522					<select class='tbox' name='export_char'>";
523
524						foreach ($separator_list as $k=>$v)
525						{
526							$selected = $export_char == $k ? " selected='selected'" : "";
527							$text .= "<option value='{$k}' {$selected}>{$v}</option>\n";
528						}
529						$text .= "</select>\n&nbsp;&nbsp;&nbsp;&nbsp;<select class='tbox' name='export_quote'>\n";
530						foreach ($quote_list as $k=>$v)
531						{
532							$selected = $export_quote == $k ? " selected='selected'" : "";
533							$text .= "<option value='{$k}'".$selected.">{$v}</option>\n";
534						}
535						$text .= "</select>\n</td></tr>";
536
537						$text .= "<tr>
538			<td>".ADSTAT_LAN_60."</td>
539			<td>".$frm->checkbox('export_stripurl', 1)."<span class='field-help'>".ADSTAT_LAN_61."</span></td>
540			</tr>";
541					}
542
543
544					if ($export_filter)
545					{
546						if (getperms('0')) $text .= "<tr><td>".ADSTAT_LAN_65."</td><td>".$export_filter."</td></tr>";
547						$sql ->select("logstats", "log_id", "{$export_filter} ");
548						$text .= "<tr><td>".ADSTAT_LAN_64."</td><td>";
549						while($row = $sql ->fetch())
550						{
551							$text .= $row['log_id']."<br />";
552						}
553						$text .= "</td></tr>";
554					}
555
556					$text .= "
557			</table>
558				<div class='buttons-bar center'>
559			".$frm->admin_button('create_export', ($action == 'export' ? LAN_CREATE : ADSTAT_LAN_66), 'update')."
560			</div>
561			</form>
562			</div>";
563
564			// Set up the date display boxes
565			$text .= "<script type=\"text/javascript\"> settypebox('{$export_type}');</script>";
566
567			return $text;
568			//$ns->tablerender(ADSTAT_LAN_40, $text);
569		}
570
571
572
573		private function rempagePageSubmit()
574		{
575
576			$ipAddresses = null;
577			$siteTotal = null;
578			$siteUnique = null;
579
580			$sql = e107::getDb();
581
582			$pageInfo = array();
583
584			$sql->select("logstats", "*", "log_id='pageTotal' ");
585			$row = $sql ->fetch();
586			$pageTotal = unserialize($row['log_data']);
587			$logfile = e_LOG."logp_".date("z.Y", time()).".php";
588
589			if(is_readable($logfile))
590			{
591				require($logfile);
592			}
593
594			foreach($_POST['remcb'] as $page)
595			{
596				unset($pageInfo[$page]);
597				unset($pageTotal[$page]);
598			}
599
600			$pagetotal = serialize($pageTotal);
601
602			if(!$sql->update("logstats", "log_data='{$pagetotal}' WHERE log_id='pageTotal' "))
603			{
604				$sql->insert("logstats", "0, 'pageTotal', '{$pagetotal}' ");
605			}
606
607			e107::getLog()->add('STAT_03',ADSTAT_LAN_80."[!br!]".implode("[!br!]",$_POST['remcb']),'');
608
609			$varStart = chr(36);
610			$quote = chr(34);
611
612			$data = chr(60)."?php\n". chr(47)."* e107 website system: Log file: ".date("z:Y", time())." *". chr(47)."\n\n".
613				$varStart."ipAddresses = ".$quote.$ipAddresses.$quote.";\n".
614				$varStart."siteTotal = ".$quote.$siteTotal.$quote.";\n".
615				$varStart."siteUnique = ".$quote.$siteUnique.$quote.";\n";
616
617			$loop = FALSE;
618			$data .= $varStart."pageInfo = array(\n";
619			foreach($pageInfo as $info)
620			{
621				$page = preg_replace("/(\?.*)|(\_.*)|(\.php)|(\s)|(\')|(\")|(eself)|(&nbsp;)/", "", basename ($info['url']));
622				$page = str_replace("\\", "", $page);
623				$info['url'] = preg_replace("/(\s)|(\')|(\")|(eself)|(&nbsp;)/", "", $info['url']);
624				$info['url'] = str_replace("\\", "", $info['url']);
625				$page = trim($page);
626				if($page && !strstr($page, "cache") && !strstr($page, "file:"))
627				{
628					if($loop){ $data .= ",\n"; }
629					$data .= $quote.$page.$quote." => array('url' => '".$info['url']."', 'ttl' => ".$info['ttl'].", 'unq' => ".$info['unq'].")";
630					$loop = 1;
631				}
632			}
633
634			$data .= "\n);\n\n?".  chr(62);
635
636			if ($handle = fopen($logfile, 'w'))
637			{
638				fwrite($handle, $data);
639			}
640			fclose($handle);
641		}
642
643
644
645		function rempagePage()
646		{
647			$sql = e107::getDb();
648			$frm = e107::getForm();
649			$pageInfo = array();
650			$tp = e107::getParser();
651
652			$logfile = e_LOG."logp_".date("z.Y", time()).".php";
653		//	$logfile = e_PLUGIN."log/logs/logp_".date("z.Y", time()).".php";
654			if(is_readable($logfile))
655			{
656				require($logfile);
657			}
658
659			$sql ->select("logstats", "*", "log_id='pageTotal' ");
660			$row = $sql ->fetch();
661			$pageTotal = unserialize($row['log_data']);
662
663
664
665			foreach($pageInfo as $url => $tmpcon)
666			{
667				$pageTotal[$url]['url'] = $tmpcon['url'];
668				$pageTotal[$url]['ttlv'] += $tmpcon['ttl'];
669				$pageTotal[$url]['unqv'] += $tmpcon['unq'];
670			}
671
672
673
674			$text = "
675			<form method='post' action='".e_REQUEST_URL."'>
676			<table class='table adminlist'>
677
678			<tr>
679			<th style='width:100px; text-align: center;'>".ADSTAT_LAN_30." ...</th>
680			<th style='width:100px' class='text-right'>".ADSTAT_LAN_86."</th>
681			<th style='width:30%' class='forumheader'>".ADSTAT_LAN_29."</th>
682			<th style='width:auto' class='forumheader'>URL</th>
683			</tr>
684			";
685
686			foreach($pageTotal as $key => $page)
687			{
688
689				list($name,$lang) = explode("|",$key);
690
691						$text .= "
692				<tr>
693				<td style='width:100px; text-align: center;'><input type='checkbox' name='remcb[]' value='{$key}' /></td>
694				<td class='text-right' style='width:100px'>".number_format($page['ttlv'])."</td>
695				<td style='width:30%'>{$name}</td>
696				<td style='width:auto'>".$tp->text_truncate($page['url'],100)."</td>
697
698				</tr>
699				";
700			}
701
702			$text .= "
703			</table>
704			<div class='buttons-bar center'>
705			".$frm->admin_button('remSelP', ADSTAT_LAN_31, 'delete')."
706			</form>
707
708			";
709
710			return $text;
711
712		//	$ns -> tablerender(ADSTAT_LAN_32, $text);
713		}
714
715
716		function rebuildPage()
717		{
718			$frm  = e107::getForm();
719			$mes = e107::getMessage();
720			$tp = e107::getParser();
721
722			$mes->addWarning(ADSTAT_LAN_84);
723			$text = $frm->open('rebuild');
724
725			$files = e107::getFile()->get_files(e_LOG."log",'_SiteStats\.log$');
726
727		//	print_a($_SESSION['stats_log_files']);
728
729			$_SESSION['stats_log_files'] = array();
730			$_SESSION['stats_log_files_count'] = 0;
731
732			foreach($files as $f)
733			{
734				$_SESSION['stats_log_files'][] = array('path'=> $f['fname'], 'complete'=>0);
735			}
736
737			$_SESSION['stats_log_files_total'] = count($_SESSION['stats_log_files']);
738
739		//	$text .=  //  . " log files have been found. Click the button below to process these files.</p>";
740			$mes->addWarning($tp->lanVars(ADSTAT_LAN_85, $_SESSION['stats_log_files_total'], true));
741
742			if(!empty($_SESSION['stats_log_files_total']))
743			{
744				$text .= $frm->progressBar('rebuild-progress',0,array("btn-label"=> ADSTAT_LAN_88, 'url'=>e_REQUEST_URI));
745			}
746
747			$text .= $frm->close();
748			return $text;
749
750
751		}
752
753
754
755		function historyPage()
756		{
757			$mes = e107::getMessage();
758			$frm = e107::getForm();
759			$sql = e107::getDb();
760
761			$mes->addWarning(ADSTAT_LAN_76);
762			$text = "
763
764			<form method='post' action='".e_SELF."?history'>
765			<table class='table adminlist'>
766			<colgroup>
767			  <col style='width:50%' />
768			  <col style='width:50%' />
769			</colgroup>";
770
771			$keep_month = varset($_POST['delete_month'],0);
772			$keep_year = varset($_POST['delete_year'],0);
773
774			if (isset($_POST['delete_history']))
775			{
776						$text .= "<tr><td>".ADSTAT_LAN_72."</td><td>".nl_langinfo(constant('MON_'.$keep_month))." ".$keep_year."</td></tr>
777				<tr><td colspan='2'  style='text-align:center' class='forumheader'>
778				<input type='hidden' name='delete_month' value='{$keep_month}' />
779				<input type='hidden' name='delete_year' value='{$keep_year}' />
780				".$frm->admin_button('actually_delete', LAN_CONFDELETE, 'delete')."<br />".ADSTAT_LAN_74."
781				</td></tr>";
782						$text .= "<tr><td>".ADSTAT_LAN_75."</td><td>".implode("<br />",$this->get_for_delete($keep_year,$keep_month))."</td></tr>";
783			}
784			else
785			{
786				if (isset($_POST['actually_delete']))
787				{
788							$delete_list = $this->get_for_delete($keep_year,$keep_month);
789							$logStr = '';
790							//	    $text .= "<tr><td colspan='2'>Data notionally deleted {$keep_month}-{$keep_year}</td></tr>";
791							$text .= "<tr><td>".ADSTAT_LAN_77."</td><td>";
792
793							foreach ($delete_list as $k => $v)
794							{
795								$sql->delete('logstats',"log_id='{$k}'");
796								$text .= $v."<br />";
797								$logStr .= "[!br!]{$k} => ".$v;
798							}
799
800							$text .= "</td></tr>";
801							e107::getLog()->add('STAT_04',ADSTAT_LAN_83.$logStr,'');
802				}
803
804				$text .= "<tr><td>".ADSTAT_LAN_70."</td>";
805				$text .= "<td><select class='tbox' name='delete_month'>\n";
806				$match_month = date("n");
807
808				for ($i = 1; $i < 13; $i++)
809				{
810					$selected = $match_month == $i ? " selected='selected'" : "";
811					$text .= "<option value='{$i}'".$selected.">".nl_langinfo(constant('MON_'.$i))."</option>\n";
812				}
813
814				$text .= "</select>\n&nbsp;&nbsp;&nbsp;";
815				$this_year = date("Y");
816
817				$text .= "<select class='tbox' name='delete_year' id='export_year'>\n";
818
819				for ($i = $this_year; $i > $this_year - 6; $i--)
820				{
821					$selected = ($this_year - 2) == $i ? " selected='selected'" : "";
822					$text .= "<option value='{$i}'{$selected}>{$i}</option>\n";
823				}
824
825				$text .= "</select>\n</td></tr>";
826			}
827
828			$text .= "</table>
829
830			<div class='buttons-bar center'>
831			".$frm->admin_button('delete_history',LAN_DELETE,'delete')."
832			</div>
833
834			</form>";
835
836			return $text;
837		//	$ns->tablerender(ADSTAT_LAN_69, $mes->render().$text);
838		}
839
840
841
842		private function prefsPageSubmit()
843		{
844
845				$statList = array(		// Type = 0 for direct text, 1 for integer
846					'statActivate' 		=> 0,
847					'statCountAdmin' 	=> 0,
848					'statUserclass' 	=> 0,
849					'statBrowser'		=> 1,
850					'statOs'			=> 1,
851					'statScreen' 		=> 1,
852					'statDomain' 		=> 1,
853					'statRefer' 		=> 1,
854					'statQuery' 		=> 1,
855					'statRecent' 		=> 1,
856					'statDisplayNumber' => 0,
857					'statPrevMonth'		=> 1
858				);
859				$logStr = '';
860
861				$pref = array();
862
863				foreach ($statList as $k => $type)
864				{
865					switch ($type)
866					{
867						case 0 : $pref[$k] = $_POST[$k]; break;
868						case 1 : $pref[$k] = intval($_POST[$k]); break;
869					}
870					$logStr .= "[!br!]{$k} => ".$pref[$k];
871				}
872
873				e107::getConfig()->setPref($pref)->save(false,true,true);
874
875				file_put_contents(e_LOG.LogFlagFile, "<?php\n\$logEnable={$pref['statActivate']};\n?>\n");		// Logging task uses to see if logging enabled
876				e107::getLog()->add('STAT_02',ADSTAT_LAN_82.$logStr,'');
877
878
879		}
880
881
882		public function prefsPage()
883		{
884
885			global $pref;
886
887			$frm = e107::getForm();
888
889			$text = "
890			<form method='post' action='".e_SELF."'>
891			<table class='table adminform'>
892			<colgroup>
893				<col style='width:40%' />
894				<col style='width:60%' />
895			</colgroup>
896
897			<tr>
898				<td>".ADSTAT_LAN_4."</td>
899				<td>".$frm->radio_switch('statActivate', $pref['statActivate'])."</td>
900			</tr>
901			<tr>
902				<td>".ADSTAT_LAN_18."</td>
903				<td>".r_userclass("statUserclass", $pref['statUserclass'],'off','public, member, admin, classes')."</td>
904			</tr>
905			<tr>
906				<td>".ADSTAT_LAN_20."</td>
907				<td>".$frm->radio_switch('statCountAdmin', $pref['statCountAdmin'])."</td>
908			</tr>
909			<tr>
910				<td>".ADSTAT_LAN_21."</td>
911				<td><input class='tbox' type='text' name='statDisplayNumber' size='8' value='".$pref['statDisplayNumber']."' maxlength='3' /></td>
912			</tr>
913			<tr>
914				<td>".ADSTAT_LAN_5."</td>
915				<td>
916				".$this->gen_select(ADSTAT_LAN_6, 'statBrowser',$pref['statBrowser'])
917				.$this->gen_select(ADSTAT_LAN_7, 'statOs',$pref['statOs'])
918				.$this->gen_select(ADSTAT_LAN_8, 'statScreen',$pref['statScreen'])
919				.$this->gen_select(ADSTAT_LAN_9, 'statDomain',$pref['statDomain'])
920				.$this->gen_select(ADSTAT_LAN_10, 'statRefer',$pref['statRefer'])
921				.$this->gen_select(ADSTAT_LAN_11, 'statQuery',$pref['statQuery'])
922				."<div class='clearfix' style='padding-bottom: 4px'><span class='pull-left float-left'>".ADSTAT_LAN_19."</span><span class='pull-right float-right'>
923				 ".$frm->radio_switch('statRecent', $pref['statRecent'])."</span></div>
924				</td>
925			</tr>
926
927			<tr>
928			<td>".ADSTAT_LAN_78."</td>
929				<td>".$frm->checkbox('statPrevMonth', 1, varset($pref['statPrevMonth'],0))."<span class='field-help'>".ADSTAT_LAN_79."</span></td>
930			</tr>
931			<tr>
932				<td>".ADSTAT_LAN_12."</td>
933				<td>
934					".$frm->checkbox('wipe[statWipePage]', 1, false, array('label'=> ADSTAT_LAN_14 ))."
935					".$frm->checkbox('wipe[statWipeBrowser]', 1, false, array('label'=>ADSTAT_LAN_6))."
936					".$frm->checkbox('wipe[statWipeOs]', 1, false, array('label'=> ADSTAT_LAN_7 ))."
937					".$frm->checkbox('wipe[statWipeScreen]', 1, false, array('label'=> ADSTAT_LAN_8 ))."
938					".$frm->checkbox('wipe[statWipeDomain]', 1, false, array('label'=> ADSTAT_LAN_9 ))."
939					".$frm->checkbox('wipe[statWipeRefer]', 1, false, array('label'=> ADSTAT_LAN_10 ))."
940					".$frm->checkbox('wipe[statWipeQuery]', 1, false, array('label'=> ADSTAT_LAN_11 ))."
941					<br />
942					".$frm->admin_button('wipeSubmit', LAN_RESET, 'delete')."<span class='field-help'>".ADSTAT_LAN_13."</span>
943				</td>
944			</tr>
945			<tr>
946				<td>".ADSTAT_LAN_26."</td>
947				<td>".$frm->admin_button('openRemPageD', ADSTAT_LAN_28, 'other')."<span class='field-help'>".ADSTAT_LAN_27."</span>	</td>
948			</tr>
949			</table>
950			<div class='buttons-bar center'>
951				".$frm->admin_button('updatesettings', LAN_UPDATE, 'update')."
952			</div>
953			</form>";
954
955			return $text;
956		//	$ns->tablerender(ADSTAT_LAN_16, $text);
957		}
958
959
960
961
962		/*
963			// optional - a custom page.
964			public function customPage()
965			{
966				$text = 'Hello World!';
967				return $text;
968
969			}
970		*/
971
972	}
973
974
975
976	class logstats_form_ui extends e_admin_form_ui
977	{
978
979		function log_id($curVal,$mode)
980		{
981			switch($mode)
982			{
983				case 'read': // List Page
984
985					if($curVal == 'pageTotal')
986					{
987						return ADSTAT_LAN_45; // All Time.
988					}
989
990					return $curVal;
991					break;
992
993				case 'write': // Edit Page
994					return '';
995					break;
996
997				case 'filter':
998				case 'batch':
999					return  array();
1000					break;
1001			}
1002
1003		}
1004
1005
1006		function parseLogData($type)
1007		{
1008			$row = $this->getController()->getListModel()->getData();
1009			$curVal = $row['log_data'];
1010
1011			if($row['log_id'] == 'pageTotal')
1012			{
1013				$tmp = unserialize($curVal);
1014
1015				$ttl = 0;
1016				$unq = 0;
1017
1018				foreach($tmp as $k=>$v)
1019				{
1020					$ttl += $v['ttlv'];
1021					$unq += $v['unqv'];
1022				}
1023
1024				if($type == 'total')
1025				{
1026					return number_format($ttl);
1027				}
1028				elseif($type == 'unique')
1029				{
1030					return  number_format($unq);
1031				}
1032
1033				return "<div class='col-md-2'>".ADSTAT_L21.": ".number_format($ttl)."</div><div class='col-md-2'>".ADSTAT_L22.": ".number_format($unq)."</div><div class='col-md-2'>Total Pages: ".number_format(count($tmp))."</div>";
1034
1035
1036				//	return print_a($tmp,true);
1037			}
1038
1039			if(!empty($curVal))
1040			{
1041				$tmp = explode(chr(1), $curVal, 3);
1042
1043				if($type == 'total')
1044				{
1045					return number_format($tmp[0]);
1046				}
1047				elseif($type == 'unique')
1048				{
1049					return  number_format($tmp[1]);
1050				}
1051
1052				// return "<div class='col-md-1'>".ADSTAT_L21.": ".number_format($tmp[0])."</div><div class='col-md-2'>".ADSTAT_L22.": ".number_format($tmp[1])."</div>";
1053			}
1054
1055		}
1056
1057		// Total Hits
1058		function log_data($curVal,$mode)
1059		{
1060
1061			switch($mode)
1062			{
1063				case 'read': // List Page
1064
1065					return $this->parseLogData('total');
1066					break;
1067
1068				case 'write': // Edit Page
1069					// return $this->text('log_data',$curVal, 255, 'size=large');
1070					break;
1071
1072				case 'filter':
1073				case 'batch':
1074					return  array();
1075					break;
1076			}
1077
1078			return null;
1079		}
1080
1081
1082		// unique hits
1083		function log_data2($curVal,$mode)
1084		{
1085
1086			switch($mode)
1087			{
1088				case 'read': // List Page
1089
1090					return $this->parseLogData('unique');
1091					break;
1092
1093				case 'write': // Edit Page
1094					// return $this->text('log_data',$curVal, 255, 'size=large');
1095					break;
1096
1097				case 'filter':
1098				case 'batch':
1099					return  array();
1100					break;
1101			}
1102
1103			return null;
1104		}
1105
1106
1107
1108		function options($curVal,$mode)
1109		{
1110			$row = $this->getController()->getListModel()->getData();
1111			$date = $row['log_id'];
1112
1113			if($date == 'pageTotal')
1114			{
1115				return $this->button('rebuildTotal', 1, 'delete', ADSTAT_LAN_89);
1116			}
1117
1118
1119			$unix = strtotime($date);
1120
1121			if(empty($unix))
1122			{
1123				return null;
1124			}
1125
1126			$datestamp = date("Y-m-d", $unix);
1127
1128			$file = e_LOG."log/".$datestamp."_SiteStats.log";
1129
1130			if(is_readable($file))
1131			{
1132				return $this->button('rebuild', $datestamp, 'delete', ADSTAT_LAN_89);
1133			}
1134			else
1135			{
1136				return null;
1137			}
1138
1139		}
1140
1141	}
1142
1143
1144	new log_adminArea();
1145
1146	require_once(e_ADMIN."auth.php");
1147	e107::getAdminUI()->runPage();
1148
1149	require_once(e_ADMIN."footer.php");
1150	exit;
1151
1152/*
1153
1154require_once(e_ADMIN.'auth.php');
1155
1156require_once(e_HANDLER.'userclass_class.php');
1157$frm = e107::getForm();
1158$mes = e107::getMessage();
1159
1160*/
1161
1162
1163if (e_QUERY)
1164{
1165	$sl_qs = explode('.', e_QUERY);
1166}
1167$action = varset($sl_qs[0],'config');
1168$params = varset($sl_qs[1],'');
1169
1170
1171
1172
1173if (isset($_POST['create_export']) && (($action == 'export') || ($action == 'datasets')))
1174{
1175	$first_date = 0;
1176	$last_date = 0;
1177	$date_error = FALSE;
1178	if ($export_type == 'page')
1179	{
1180		switch ($export_date)
1181		{
1182			case '1' :		//	Single day
1183				$first_date = gmmktime(0,0,0,$export_month,$export_day,$export_year);
1184				$last_date = $first_date+86399;
1185				$export_filter = " `log_id`='".date("Y-m-j",$first_date)."'";
1186				break;
1187			case '2' :		// Daily for a month
1188				$first_date = gmmktime(0,0,0,$export_month,1,$export_year);
1189				$last_date = gmmktime(0,0,0,$export_month+1,1,$export_year) - 1;
1190				$export_filter = " LEFT(`log_id`,8)='".gmstrftime("%Y-%m-",$first_date)."'";
1191				break;
1192			case '3' :		// Monthly for a Year
1193				$first_date = gmmktime(0,0,0,1,1,$export_year);
1194				$last_date = gmmktime(0,0,0,1,1,$export_year+1) - 1;
1195				$export_filter = " LENGTH(`log_id`)=7 AND LEFT(`log_id`,5)='".gmstrftime("%Y-",$first_date)."'";
1196				break;
1197			case '4' :		// Accumulated
1198			case '5' :
1199				$export_filter = "`log_id`='pageTotal'";
1200				$date_error = 'ignore';
1201				break;
1202		}
1203	}
1204	else
1205	{  // Calculate strings for non-page sources
1206		$prefix_len = 0;
1207		$export_date = $export2_date;
1208		if (isset($stats_list[$export_type]))
1209		{
1210			$prefix_len = strlen($export_type) + 1;
1211			switch ($export2_date)
1212			{
1213				case '3' :		// Monthly for a Year
1214					if ($prefix_len > 0)
1215					{
1216						$first_date = gmmktime(0,0,0,1,1,$export_year);
1217						$last_date = gmmktime(0,0,0,1,1,$export_year+1) - 1;
1218						$export_filter = " LENGTH(`log_id`)='".($prefix_len + 7)."' AND LEFT(`log_id`,".($prefix_len + 5).")='".$export_type.":".gmstrftime("%Y-",$first_date)."'";
1219					}
1220					break;
1221				case '4' :		// Accumulated
1222					$export_filter = " `log_id`='".$export_type."'";
1223					$date_error = 'ignore';
1224					break;
1225			}
1226		}
1227		else
1228		{
1229			$message = ADSTAT_LAN_54;
1230		}
1231	}
1232	if (($date_error != 'ignore') && (($first_date == 0) || ($last_date == 0) || $date_error))
1233	{
1234		$message = ADSTAT_LAN_47;
1235	}
1236}
1237
1238
1239
1240//---------------------------------------------
1241//		Remove page entries
1242//---------------------------------------------
1243if(isset($_POST['openRemPageD']))
1244{
1245  $action = 'rempage';
1246}
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257echo  $mes->render() ;
1258
1259
1260
1261
1262
1263
1264switch ($action)
1265{
1266  case 'config' :
1267
1268	break;  // case config
1269
1270  case 'rempage' :			// Remove pages
1271//	rempage();
1272    break;
1273
1274
1275  case 'export' :			// Export file
1276  case 'datasets' :
1277	//===========================================================
1278	//				EXPORT DATA
1279	//===========================================================
1280
1281    break;	// case 'export'
1282
1283  case 'history' :
1284	//===========================================================
1285	//				DELETE HISTORY
1286	//===========================================================
1287
1288    break;	// case 'history'
1289
1290}
1291
1292
1293require_once(e_ADMIN."footer.php");
1294
1295
1296function headerjs()
1297{
1298  $script_js = "<script type=\"text/javascript\">
1299	//<![CDATA[
1300	  var names = new Array();
1301	    names[0] = 'export_day';
1302	    names[1] = 'export_month';
1303	    names[2] = 'export_year';
1304	    names[3] = 'export_cumulative';
1305
1306	  var dispinfo = new Array();
1307		dispinfo[1] = new Array();		// Single day
1308		  dispinfo[1][0] = '';
1309		  dispinfo[1][1] = '';
1310		  dispinfo[1][2] = '';
1311		  dispinfo[1][3] = 'none';
1312
1313		dispinfo[2] = new Array();		// Month
1314		  dispinfo[2][0] = 'none';
1315		  dispinfo[2][1] = '';
1316		  dispinfo[2][2] = '';
1317		  dispinfo[2][3] = 'none';
1318
1319		dispinfo[3] = new Array();		// Year
1320		  dispinfo[3][0] = 'none';
1321		  dispinfo[3][1] = 'none';
1322		  dispinfo[3][2] = '';
1323		  dispinfo[3][3] = 'none';
1324
1325		dispinfo[4] = new Array();		// Specials
1326		  dispinfo[4][0] = 'none';
1327		  dispinfo[4][1] = 'none';
1328		  dispinfo[4][2] = 'none';
1329		  dispinfo[4][3] = '';
1330
1331
1332	function setdatebox(disptype)
1333	{
1334	  var target;
1335	  var j;
1336
1337	  if (disptype > 4) disptype = 4;
1338
1339	  for (j = 0; j < names.length; j++)
1340	  {
1341	    target = document.getElementById(names[j]).style;
1342		target.display = dispinfo[disptype][j];
1343	  }
1344	}
1345
1346	function settypebox(pagetype)
1347	{
1348	  var newdateformat = 1;
1349	  var target1 = document.getElementById('export_date');
1350	  var target2 = document.getElementById('export2_date');
1351	  if (pagetype == 'page')
1352	  {
1353	    target1.style.display = '';
1354	    target2.style.display = 'none';
1355		newdateformat = target1.value;
1356	  }
1357	  else
1358	  {
1359	    target1.style.display = 'none';
1360	    target2.style.display = '';
1361		newdateformat = target2.value;
1362	  }
1363	  setdatebox(newdateformat);
1364	}
1365
1366	//]]>
1367	</script>\n";
1368  return $script_js;
1369}
1370
1371
1372
1373//---------------------------------------------
1374//		Remove page entries - prompt/list
1375//---------------------------------------------
1376function rempage()
1377{
1378
1379}
1380
1381
1382//---------------------------------------------
1383//		Remove page entries - action
1384//---------------------------------------------
1385
1386
1387
1388
1389function admin_config_adminmenu()
1390{
1391  if (e_QUERY)
1392  {
1393	$tmp = explode(".", e_QUERY);
1394	$action = $tmp[0];
1395  }
1396  if (!isset($action) || ($action == "")) $action = "config";
1397
1398  $var['config']['text'] = ADSTAT_LAN_35;
1399  $var['config']['link'] = 'admin_config.php';
1400
1401  $var['export']['text'] = ADSTAT_LAN_36;
1402  $var['export']['link'] ='admin_config.php?export';
1403
1404//  $var['datasets']['text'] = ADSTAT_LAN_63;
1405//  $var['datasets']['link'] ='admin_config.php?datasets';
1406
1407  $var['rempage']['text'] = ADSTAT_LAN_26;
1408  $var['rempage']['link'] ='admin_config.php?rempage';
1409
1410  $var['history']['text'] = ADSTAT_LAN_69;
1411  $var['history']['link'] ='admin_config.php?history';
1412
1413  show_admin_menu(ADSTAT_LAN_39, $action, $var);
1414}
1415
1416
1417
1418