source: extensions/AStat/astat_aip.class.inc.php @ 5423

Last change on this file since 5423 was 5423, checked in by grum, 14 years ago

Update the plugin for compatibility with Piwigo 2.1 and fix some bugs
feature 1192, feature 1344

  • Property svn:executable set to *
File size: 82.6 KB
Line 
1<?php
2/* -----------------------------------------------------------------------------
3  Plugin     : AStat.2
4  Author     : Grum
5    email    : grum@piwigo.org
6    website  : http://photos.grum.dnsalias.com
7
8    << May the Little SpaceFrog be with you ! >>
9  ------------------------------------------------------------------------------
10  See main.inc.php for release information
11
12  AI classe => manage integration in administration interface
13
14  --------------------------------------------------------------------------- */
15if (!defined('PHPWG_ROOT_PATH')) { die('Hacking attempt!'); }
16
17include_once('astat_aim.class.inc.php');
18include_once(PHPWG_ROOT_PATH.'admin/include/tabsheet.class.php');
19include_once(PHPWG_PLUGINS_PATH.'grum_plugins_classes-2/ajax.class.inc.php');
20
21class AStat_AIP extends AStat_AIM
22{
23  protected $tabsheet;
24  protected $list_periods = array('global', 'all', 'year', 'month', 'day');
25  protected $list_sortcat = array('page', 'picture', 'nbpicture');
26  protected $list_sortimg = array('picture', 'catname');
27  protected $list_sortip = array('page', 'picture', 'ip');
28  protected $ajax;
29
30  protected $catfilter;    //filter on categories
31  protected $max_width;
32  protected $seetimerequest;
33
34  function AStat_AIP($prefixeTable, $filelocation)
35  {
36    parent::__construct($prefixeTable, $filelocation);
37
38    $this->load_config();
39    $this->init_events();
40
41    $this->tabsheet = new tabsheet();
42    $this->tabsheet->add('stats_by_period',
43                          l10n('AStat_by_period'),
44                          $this->page_link.'&amp;fAStat_tabsheet=stats_by_period');
45    $this->tabsheet->add('stats_by_ip',
46                          l10n('AStat_by_ip'),
47                          $this->page_link.'&amp;fAStat_tabsheet=stats_by_ip');
48    $this->tabsheet->add('stats_by_category',
49                          l10n('AStat_by_category'),
50                          $this->page_link.'&amp;fAStat_tabsheet=stats_by_category');
51    $this->tabsheet->add('stats_by_image',
52                          l10n('AStat_by_image'),
53                          $this->page_link.'&amp;fAStat_tabsheet=stats_by_image');
54    $this->tabsheet->add('config',
55                          l10n('AStat_config'),
56                          $this->page_link.'&amp;fAStat_tabsheet=config');
57    $this->tabsheet->add('tools',
58                          l10n('AStat_tools'),
59                          $this->page_link.'&amp;fAStat_tabsheet=tools');
60
61    $this->ajax = new Ajax();
62  }
63
64  /*
65    initialize events call for the plugin
66  */
67  function init_events()
68  {
69    add_event_handler('loc_end_page_header', array(&$this->css, 'apply_CSS'));
70  }
71
72
73
74  /* ---------------------------------------------------------------------------
75  Public classe functions
76  --------------------------------------------------------------------------- */
77
78  /*
79    manage plugin integration into piwigo's admin interface
80  */
81  public function manage()
82  {
83    global $template;
84
85    $this->return_ajax_content();
86
87    $template->set_filename('plugin_admin_content', dirname(__FILE__)."/admin/astat_admin.tpl");
88
89    $this->init_request();
90
91    $this->make_filter_list($_REQUEST['fAStat_catfilter']);
92    if($_REQUEST['fAStat_catfilter']!="")
93    {
94      $this->page_link.="&amp;fAStat_catfilter=".$_REQUEST['fAStat_catfilter'];
95    }
96
97    if($_REQUEST['fAStat_tabsheet']=='stats_by_period')
98    {
99      $this->display_stats_by_period(
100          $_REQUEST['fAStat_all'],
101          $_REQUEST['fAStat_year'],
102          $_REQUEST['fAStat_month'],
103          $_REQUEST['fAStat_day'],
104          $this->my_config['AStat_MaxBarWidth'],
105          $this->my_config['AStat_SeeTimeRequests']
106      );
107    }
108    elseif($_REQUEST['fAStat_tabsheet']=='stats_by_ip')
109    {
110      if(isset($_REQUEST['fAStat_IP_BL']))
111      {
112        $this->add_ip_to_filter($_REQUEST['fAStat_IP_BL']);
113      }
114
115      $this->display_stats_by_ip(
116          $_REQUEST['fAStat_year'],
117          $_REQUEST['fAStat_month'],
118          $_REQUEST['fAStat_day'],
119          $this->my_config['AStat_MaxBarWidth'],
120          $this->my_config['AStat_NpIPPerPages'],
121          $_REQUEST['fAStat_page_number'],
122          $_REQUEST['fAStat_SortIP'],
123          $this->my_config['AStat_SeeTimeRequests']
124      );
125    }
126    elseif($_REQUEST['fAStat_tabsheet']=='stats_by_category')
127    {
128      $this->display_stats_by_category(
129          $_REQUEST['fAStat_year'],
130          $_REQUEST['fAStat_month'],
131          $_REQUEST['fAStat_day'],
132          $this->my_config['AStat_MaxBarWidth'],
133          $this->my_config['AStat_NpCatPerPages'],
134          $_REQUEST['fAStat_page_number'],
135          $this->my_config['AStat_ShowThumbCat'],
136          $_REQUEST['fAStat_SortCat'],
137          $this->my_config['AStat_SeeTimeRequests']
138      );
139    }
140    elseif($_REQUEST['fAStat_tabsheet']=='stats_by_image')
141    {
142      $this->display_stats_by_image(
143          $_REQUEST['fAStat_year'],
144          $_REQUEST['fAStat_month'],
145          $_REQUEST['fAStat_day'],
146          $this->my_config['AStat_MaxBarWidth'],
147          $this->my_config['AStat_NbImgPerPages'],
148          $_REQUEST['fAStat_page_number'],
149          $this->my_config['AStat_ShowThumbImg'],
150          $_REQUEST['fAStat_SortImg'],
151          $_REQUEST['fAStat_IP'],
152          $this->my_config['AStat_SeeTimeRequests']
153      );
154    }
155    elseif($_REQUEST['fAStat_tabsheet']=='config')
156    {
157      $this->display_config();
158    }
159    elseif($_REQUEST['fAStat_tabsheet']=='tools')
160    {
161      $this->display_tools();
162    }
163
164    $this->tabsheet->select($_REQUEST['fAStat_tabsheet']);
165    $this->tabsheet->assign();
166    $selected_tab=$this->tabsheet->get_selected();
167    $template->assign($this->tabsheet->get_titlename(), "[".$selected_tab['caption']."]");
168
169    $template_plugin["ASTAT_VERSION"] = "<i>AStat</i> ".l10n('AStat_version').ASTAT_VERSION;
170    $template_plugin["ASTAT_PAGE"] = $_REQUEST['fAStat_tabsheet'];
171
172    $template->assign('plugin', $template_plugin);
173    $template->assign_var_from_handle('ADMIN_CONTENT', 'plugin_admin_content');
174  }
175
176  /* ---------------------------------------------------------------------------
177  Private classe functions
178  --------------------------------------------------------------------------- */
179
180  /*
181    return ajax content
182  */
183  protected function return_ajax_content()
184  {
185    global $ajax, $template;
186
187    if(isset($_REQUEST['ajaxfct']))
188    {
189      //$this->debug("AJAXFCT:".$_REQUEST['ajaxfct']);
190      $result="<p class='errors'>An error has occured</p>";
191      switch($_REQUEST['ajaxfct'])
192      {
193        case 'astat_listip':
194          if(!isset($_REQUEST['ipfilter'])) $_REQUEST['ipfilter']="";
195          if(!isset($_REQUEST['exclude'])) $_REQUEST['exclude']="";
196          $result=$this->ajax_listip($_REQUEST['ipfilter'], $_REQUEST['exclude']);
197          break;
198      }
199      //$template->
200      $this->ajax->return_result($result);
201    }
202  }
203
204
205
206
207
208
209
210  private function init_request()
211  {
212    $default_request = array('all'=>'Y', 'year'=>'', 'month'=>'', 'day'=>'');
213
214    //initialise $REQUEST values if not defined
215    if(!array_key_exists('fAStat_tabsheet', $_REQUEST))
216    {
217      $_REQUEST['fAStat_tabsheet']='stats_by_period';
218    }
219    if(!array_key_exists('fAStat_defper', $_REQUEST))
220    {
221      $_REQUEST['fAStat_defper']='Y';
222    }
223    if(!array_key_exists('fAStat_SortCat', $_REQUEST))
224    {
225      $_REQUEST['fAStat_SortCat']=$this->my_config['AStat_DefaultSortCat'];
226    }
227    if(!array_key_exists('fAStat_SortImg', $_REQUEST))
228    {
229      $_REQUEST['fAStat_SortImg']=$this->my_config['AStat_DefaultSortImg'];
230    }
231    if(!array_key_exists('fAStat_SortIP', $_REQUEST))
232    {
233      $_REQUEST['fAStat_SortIP']=$this->my_config['AStat_DefaultSortIP'];
234    }
235    if(!array_key_exists('fAStat_page_number', $_REQUEST))
236    {
237      $_REQUEST['fAStat_page_number']='1';
238    }
239    if(!array_key_exists('fAStat_IP', $_REQUEST))
240    {
241      $_REQUEST['fAStat_IP']="";
242    }
243    if(!array_key_exists('fAStat_purge_history_date', $_REQUEST))
244    {
245      $_REQUEST['fAStat_purge_history_date']="";
246    }
247    if(!array_key_exists('fAStat_catfilter', $_REQUEST))
248    {
249      $_REQUEST['fAStat_catfilter']="";
250    }
251
252    if(($_REQUEST['fAStat_tabsheet']=='stats_by_period')&&($_REQUEST['fAStat_defper']=='Y'))
253    {
254      if($this->my_config['AStat_default_period']!='global')
255      {
256        $default_request['all'] = 'N';
257      }
258
259      if(($this->my_config['AStat_default_period']=='year')||
260        ($this->my_config['AStat_default_period']=='month')||
261        ($this->my_config['AStat_default_period']=='day'))
262      {
263        $default_request['year'] = date('Y');
264      }
265
266      if(($this->my_config['AStat_default_period']=='month')||
267        ($this->my_config['AStat_default_period']=='day'))
268      {
269        $default_request['month'] = date('n');
270      }
271
272      if($this->my_config['AStat_default_period']=='day')
273      {
274        $default_request['day'] = date('j');
275      }
276    }
277
278    if(!array_key_exists('fAStat_all', $_REQUEST))
279    {
280      $_REQUEST['fAStat_all']=$default_request['all'];
281    }
282    if(!array_key_exists('fAStat_year', $_REQUEST))
283    {
284      $_REQUEST['fAStat_year']=$default_request['year'];
285    }
286    if(!array_key_exists('fAStat_month', $_REQUEST))
287    {
288      $_REQUEST['fAStat_month']=$default_request['month'];
289    }
290    if(!array_key_exists('fAStat_day', $_REQUEST))
291    {
292      $_REQUEST['fAStat_day']=$default_request['day'];
293    }
294
295    $this->catfilter=$_REQUEST['fAStat_catfilter'];
296
297  } //init_request
298
299
300  /*
301    request functions
302
303    theses functions made SQL requests and returns datas
304  */
305
306
307  /*
308    Stat by period
309      Number of Pages
310      Number IP
311      Number of Images
312      by :
313        total
314        years
315        years/months
316        years/months/days
317        years/months/days/hours
318  */
319  private function stats_by_period($total, $year, $month, $day)
320  {
321    $returned = array();
322    $delta = 0;
323
324    $sql = " count(id) as NbPages, count(distinct IP) as NbIP,
325            count(image_id) as NbImg, count(distinct category_id) as NbCat ";
326    $sql_nfomax = ", MaxPages, MaxIP, MaxImg";
327    $sql_from = " from ".HISTORY_TABLE." ";
328    $sql_where = "";
329    $sql_order = "";
330    $sql_select = "";
331    $sql_group = "";
332    $sql_groupdef="";
333
334    if($day!="")
335    {
336      $sql_groupdef="HOUR(time) as GId,";
337      $sql_select="select HOUR(time) as GId, ";
338      $sql_where=" where YEAR(date) = $year and MONTH(date) = $month and DAY(date) = $day ";
339      $sql_group=" group by GId ";
340      $sql_order=" order by GId asc";
341
342      for($i=0;$i<24;$i++)
343      {
344        $returned[$i] = array(
345                          "GId" => $i,
346                          "NbPages" => 0,
347                          "NbIP" => 0,
348                          "NbImg" => 0,
349                          "NbCat"=>0,
350                          "MaxPages" => 0,
351                          "MaxIP" => 0,
352                          "MaxImg" => 0
353                        );
354      }
355    }
356    elseif($month!="")
357    {
358      $sql_groupdef="DAY(date) as GId,";
359      $sql_select="select DAY(date) as GId, ";
360      $sql_where=" where YEAR(date) = $year and MONTH(date) = $month ";
361      $sql_group=" group by GId ";
362      $sql_order=" order by GId asc";
363
364      $delta = 1;
365      $NbDays = strftime('%d', mktime(0,0,0,$month+1,0,$year));
366      for($i=0;$i<$NbDays;$i++)
367      {
368        $returned[$i] = array(
369                          "GId" => $i+1,
370                          "NbPages" => 0,
371                          "NbIP" => 0,
372                          "NbImg" => 0,
373                          "NbCat"=>0,
374                          "MaxPages" => 0,
375                          "MaxIP" => 0,
376                          "MaxImg" => 0
377                        );
378      }
379    }
380    elseif($year!="")
381    {
382      $sql_groupdef="MONTH(date) as GId,";
383      $sql_select="select MONTH(date) as GId, ";
384      $sql_where=" where YEAR(date) = $year ";
385      $sql_group=" group by GId ";
386      $sql_order=" order by GId asc ";
387
388      $delta = 1;
389      for($i=0;$i<12;$i++)
390      {
391        $returned[$i] = array(
392                          "GId" => $i+1,
393                          "NbPages" => 0,
394                          "NbIP" => 0,
395                          "NbImg" => 0,
396                          "NbCat"=>0,
397                          "MaxPages" => 0,
398                          "MaxIP" => 0,
399                          "MaxImg" => 0
400                        );
401      }
402    }
403    elseif($total!="Y")
404    {
405      $sql_groupdef="YEAR(date) as GId,";
406      $sql_select="select YEAR(date) as GId, ";
407      $sql_group=" group by GId ";
408      $sql_order=" order by GId desc";
409    }
410    else
411    {
412      $sql_select="select 'Tout' as GId, "; $sql_nfomax=", 0 as MaxPages, 0 as MaxIP, 0 as MaxImg";
413    }
414
415    if($this->catfilter!="")
416    {
417      $catfilter=$this->make_where_clause($this->catfilter);
418      ($sql_where=="")?$sql_where=" where ":$sql_where.=" and ";
419      $sql_where.=" category_id IN (".$catfilter.")";
420    }
421
422    if(($this->my_config['AStat_UseBlackList']!="false")&&($this->my_config['AStat_BlackListedIP']!=""))
423    {
424      ($sql_where=="")?$sql_where=" where ":$sql_where.=" AND ";
425      ($this->my_config['AStat_UseBlackList']=="true")?$sql_where .= " NOT ":"";
426      $sql_where .= $this->make_IP_where_clause($this->my_config['AStat_BlackListedIP']);
427    }
428
429    $sql_max=", (select max(n.MaxPages) as MaxPages, max(n.MaxIP) as MaxIP, max(n.MaxImg) as MaxImg
430        from (select ".$sql_groupdef." count(id) as MaxPages, count(distinct IP) as MaxIP, count(image_id) as MaxImg
431            from ".HISTORY_TABLE.$sql_where.$sql_group.") as n) as n ";
432    $sql=$sql_select.$sql.$sql_nfomax.$sql_from.$sql_max.$sql_where.$sql_group.$sql_order;
433
434    $result = pwg_query($sql);
435
436    $i=0;
437    while ($row = pwg_db_fetch_assoc($result))
438    {
439      if($year.$month.$day=="")
440      { $returned[$i] = $row; $i++; }
441      else
442      { $returned[$row["GId"]-$delta] = $row; }
443    }
444
445    return($returned);
446  } //stat by period
447
448  /*
449    Stats by IP
450      Number of Pages
451      Number of Images
452      by :
453        IP
454        IP/years
455        IP/years/months
456        IP/years/months/days
457  */
458  private function stats_by_ip($year, $month, $day, $nbipperpage, $pagenumber, $sortip)
459  {
460    $returned0 = array();
461    $sortlist = array(
462                  "page" => "NbPages desc",
463                  "picture" => "NbImg desc",
464                  "ip" => "IP_USER asc"
465                );
466
467    $sql_select="select SQL_CALC_FOUND_ROWS ";
468    $sql= " if(".HISTORY_TABLE.".user_id = 2, IP, if(".USERS_TABLE.".username is null, ' [".l10n("AStat_deleted_user")."]', CONCAT(' ', ".USERS_TABLE.".username))) as IP_USER, count(".HISTORY_TABLE.".id) as NbPages, count(image_id) as NbImg ";
469          $sql_nfomax = ", MaxPages, MaxImg";
470    $sql_from = " from ".HISTORY_TABLE." LEFT JOIN ".USERS_TABLE." ON ".HISTORY_TABLE.".user_id = ".USERS_TABLE.".id ";
471    $sql_where = "";
472    $sql_group=" group by IP_USER ";
473    $sql_order=" order by ".$sortlist[$sortip]." ";
474    $sql_limit=" limit ".(($pagenumber-1)* $nbipperpage).", ".$nbipperpage;
475
476
477    if($day!="")
478    {
479      $sql_where=" where YEAR(date) = $year and MONTH(date) = $month and DAY(date) = $day ";
480    }
481    elseif($month!="")
482    {
483      $sql_where=" where YEAR(date) = $year and MONTH(date) = $month ";
484    }
485    elseif($year!="")
486    {
487      $sql_where=" where YEAR(date) = $year ";
488    }
489    else
490    {
491      $sql_nfomax = ", 0 as MaxPages, 0 as MaxImg";
492    }
493
494    if($this->catfilter!="")
495    {
496      $catfilter=$this->make_where_clause($this->catfilter);
497      ($sql_where=="")?$sql_where=" where ":$sql_where.=" and ";
498      $sql_where.=" category_id IN (".$catfilter.")";
499    }
500
501    if(($this->my_config['AStat_UseBlackList']!="false")&&($this->my_config['AStat_BlackListedIP']!=""))
502    {
503      ($sql_where=="")?$sql_where=" where ":$sql_where.=" AND ";
504      ($this->my_config['AStat_UseBlackList']=="true")?$sql_where .= " NOT ":"";
505      $sql_where .= $this->make_IP_where_clause($this->my_config['AStat_BlackListedIP']);
506      $sql.=" , 'N' AS blacklist";
507    }
508    else
509    {
510      if($this->my_config['AStat_BlackListedIP']=='')
511      {
512        $sql.=" , 'N' AS blacklist";
513      }
514      else
515      {
516        $sql.=" , (CASE ";
517        $tmp=explode(',', $this->my_config['AStat_BlackListedIP']);
518        foreach($tmp as $key=>$val)
519        {
520          $sql.=" WHEN IP LIKE '".$val."' THEN 'Y' ";
521        }
522        $sql.="ELSE 'N' END) AS blacklist ";
523      }
524    }
525
526    $sql_max=", (select max(n.MaxPages) as MaxPages, max(n.MaxImg) as MaxImg
527        from (select if(".HISTORY_TABLE.".user_id = 2, IP, if(".USERS_TABLE.".username is null, '[".l10n("AStat_deleted_user")."]', ".USERS_TABLE.".username)) as IP_USER, count(".HISTORY_TABLE.".id) as MaxPages, count(image_id) as MaxImg
528            from ".HISTORY_TABLE." LEFT JOIN ".USERS_TABLE." ON ".HISTORY_TABLE.".user_id = ".USERS_TABLE.".id ".$sql_where.$sql_group.") as n) as n ";
529    $sql=$sql_select.$sql.$sql_nfomax.$sql_from.$sql_max.$sql_where.$sql_group.$sql_order.$sql_limit;
530
531
532    $result = pwg_query($sql);
533    $sql="select FOUND_ROWS()";
534
535    $i=0;
536    while ($row = pwg_db_fetch_assoc($result))
537    {
538      $returned0[$i] = $row; $i++;
539    }
540    $returned[0] = $returned0;
541
542    $result = pwg_query($sql);
543    if($result)
544    {
545      $row = pwg_db_fetch_row($result); $returned[1] = $row[0];
546    }
547    else
548    {
549      $returned[1] = -1;
550    }
551
552    return($returned);
553  } //stat by ip
554
555  /*
556    Stats per categories
557      %Pages
558      %Images
559      by :
560        Categories
561        Categories/years
562        Categories/years/months
563        Categories/years/months/day
564  */
565  private function stats_by_category($year, $month, $day, $nbipperpage, $pagenumber, $show_thumb, $sortcat)
566  {
567    $sortlist = array(
568                  "page" => "PctPages desc, PctImg desc",
569                  "picture" => "PctImg desc, PctPages desc",
570                  "nbpicture" => "RatioImg desc, PctPages desc"
571                );
572    $returned0 = array();
573
574    $sql_select="select SQL_CALC_FOUND_ROWS ";
575
576    $sql= "category_id, if(category_id > 0, ".CATEGORIES_TABLE.".name, section) as IdCat,
577  count(".HISTORY_TABLE.".id) as NbPages, MaxPages.somme, 100*(count(".HISTORY_TABLE.".id)/MaxPages.somme) as PctPages,
578  count(".HISTORY_TABLE.".image_id) as NbImg, MaxImg.somme, 100*(count(".HISTORY_TABLE.".image_id)/MaxImg.somme) as PctImg, ic2.nb_images as NbImgCat, (count(".HISTORY_TABLE.".image_id)/ic2.nb_images) as RatioImg, greatest(100*(count(".HISTORY_TABLE.".id)/MaxPages.somme), 100*(count(".HISTORY_TABLE.".image_id)/MaxImg.somme)) as MaxPct ";
579
580    if($show_thumb=='true')
581    {
582      $sql_thumb = ', '.IMAGES_TABLE.'.path as ThumbPath, '.IMAGES_TABLE.'.file as ThumbFile, '.IMAGES_TABLE.'.tn_ext as Extension';
583      $sql_fromthumb = "LEFT JOIN ".IMAGES_TABLE." ON ic2.representative_picture_id = ".IMAGES_TABLE.".id  ";
584    }
585    else
586    {
587      $sql_thumb = "";
588      $sql_fromthumb = "";
589    }
590
591    $sql_from = " from (".HISTORY_TABLE." LEFT JOIN ".CATEGORIES_TABLE." ON ".CATEGORIES_TABLE.".id = ".HISTORY_TABLE.".category_id),
592(select category_id as catid, count(image_id) as nb_images, representative_picture_id
593 from ".IMAGE_CATEGORY_TABLE.", ".CATEGORIES_TABLE."
594 where ".CATEGORIES_TABLE.".id = ".IMAGE_CATEGORY_TABLE.".category_id group by category_id) as ic2 ";
595    $sql_where = "";
596    $sql_group=" group by category_id, section ";
597    $sql_group2="";
598    $sql_order=" order by ".$sortlist[$sortcat];
599    $sql_limit=" limit ".(($pagenumber-1)* $nbipperpage).", ".$nbipperpage;
600
601    if($day!="")
602    {
603      $sql_where=" where YEAR(date) = $year and MONTH(date) = $month and DAY(date)= $day ";
604    }
605    elseif($month!="")
606    {
607      $sql_where=" where YEAR(date) = $year and MONTH(date) = $month ";
608    }
609    elseif($year!="")
610    {
611      $sql_where=" where YEAR(date) = $year ";
612    }
613    else { }
614
615    if($this->catfilter!="")
616    {
617      $catfilter=$this->make_where_clause($this->catfilter);
618      ($sql_where=="")?$sql_where=" where ":$sql_where.=" and ";
619      $sql_where.=" category_id IN (".$catfilter.")";
620    }
621
622    $sql_max=", (select count(id) as somme from ".HISTORY_TABLE.$sql_where.$sql_group2.") as MaxPages,
623          (select count(image_id) as somme from ".HISTORY_TABLE.$sql_where.$sql_group2.") as MaxImg ";
624
625    ($sql_where=="")?$sql_where=" where ":$sql_where.=" and ";
626    $sql_where .= "  ic2.catid = ".HISTORY_TABLE.".category_id ";
627
628    if(($this->my_config['AStat_UseBlackList']!="false")&&($this->my_config['AStat_BlackListedIP']!=""))
629    {
630      ($this->my_config['AStat_UseBlackList']=="true")?$sql_where .= " NOT ":"";
631      $sql_where .= $this->make_IP_where_clause($this->my_config['AStat_BlackListedIP']);
632    }
633
634    $sql=$sql_select.$sql.$sql_thumb.$sql_from.$sql_fromthumb.$sql_max.$sql_where.$sql_group.$sql_order.$sql_limit;
635
636    $result = pwg_query($sql);
637    $sql="select FOUND_ROWS()";
638
639    $i=0;
640    while ($row = pwg_db_fetch_assoc($result))
641    {
642      $returned0[$i] = $row; $i++;
643    }
644    $returned[0] = $returned0;
645
646    $result = pwg_query($sql);
647    if($result)
648    {
649      $row = pwg_db_fetch_row($result); $returned[1] = $row[0];
650    }
651    else
652    {
653      $returned[1] = -1;
654    }
655
656    return($returned);
657  } // stats per categories
658
659  /*
660    Stats by image
661      Num of view per image
662      %view on period
663      by :
664        Images
665        Images/years
666        Images/years/months
667        Images/years/months/days
668  */
669  private function stats_by_image($year, $month, $day, $nbipperpage, $pagenumber, $sortimg, $ip)
670  {
671    $sortlist = array(
672                  "picture" => "NbVues desc, CatName asc, ImgName asc, ImgId asc",
673                  "catname" => "CatName asc, ImgName asc, ImgId asc"
674                );
675    $returned0 = array();
676
677    $sql_select="select SQL_CALC_FOUND_ROWS ";
678
679
680    $sql=" image_id as ImgId, ".IMAGES_TABLE.".name as ImgName,
681        if(category_id > 0, ".CATEGORIES_TABLE.".name, section) as CatName,
682        ".HISTORY_TABLE.".category_id as IdCat, count(".HISTORY_TABLE.".image_id) as NbVues,
683        MaxImg.somme, 100*(count(".HISTORY_TABLE.".image_id)/MaxImg.somme) as PctImg,
684        ".IMAGES_TABLE.".path as ThumbPath, ".IMAGES_TABLE.".file as ThumbFile,
685        MaxImg2.somme as NbVuesMax, ".IMAGES_TABLE.".tn_ext as Extension ";
686
687    $sql_from = " from ((".HISTORY_TABLE." LEFT JOIN ".IMAGES_TABLE." ON
688  ".IMAGES_TABLE.".id = ".HISTORY_TABLE.".image_id) LEFT JOIN ".CATEGORIES_TABLE."
689  ON ".CATEGORIES_TABLE.".id = ".HISTORY_TABLE.".category_id) ";
690    $sql_from_ip="";
691
692    $sql_where = " where ".HISTORY_TABLE.".image_id is not null ";
693    $sql_group=" group by image_id, category_id ";
694    $sql_order=" order by ".$sortlist[$sortimg];
695    $sql_limit=" limit ".(($pagenumber-1)* $nbipperpage).", ".$nbipperpage;
696
697    if($day!="")
698    {
699      $sql_where.=" and YEAR(date) = $year and MONTH(date) = $month and DAY(date)= $day ";
700    }
701    elseif($month!="")
702    {
703      $sql_where.=" and YEAR(date) = $year and MONTH(date) = $month ";
704    }
705    elseif($year!="")
706    {
707      $sql_where.=" and YEAR(date) = $year ";
708    }
709    else { }
710
711    if($ip!="")
712    {
713      $sql_where.=" and ( ((IP = '$ip') and ( user_id = 2 ))  or (".USERS_TABLE.".username = '$ip') )";
714      $sql_from_ip=" LEFT JOIN ".USERS_TABLE." ON ".USERS_TABLE.".id = ".HISTORY_TABLE.".user_id ";
715    }
716
717    if($this->catfilter!="")
718    {
719      $catfilter=$this->make_where_clause($this->catfilter);
720      ($sql_where=="")?$sql_where=" where ":$sql_where.=" and ";
721      $sql_where.=" category_id IN (".$catfilter.")";
722    }
723
724    if(($this->my_config['AStat_UseBlackList']!="false")&&($this->my_config['AStat_BlackListedIP']!=""))
725    {
726      ($sql_where=="")?$sql_where=" where ":$sql_where.=" AND ";
727      ($this->my_config['AStat_UseBlackList']=="true")?$sql_where .= " NOT ":"";
728      $sql_where .= $this->make_IP_where_clause($this->my_config['AStat_BlackListedIP']);
729    }
730
731
732    $sql_max=", (select count(image_id) as somme from ".HISTORY_TABLE.$sql_from_ip.$sql_where.") as MaxImg, (select count(image_id) as somme from ".HISTORY_TABLE.$sql_from_ip.$sql_where." and ".HISTORY_TABLE.".image_id is not null group by image_id order by somme desc limit 0,1) as MaxImg2 ";
733
734    $sql=$sql_select.$sql.$sql_from.$sql_from_ip.$sql_max.$sql_where.$sql_group.$sql_order.$sql_limit;
735
736    $result = pwg_query($sql);
737    $sql="select FOUND_ROWS()";
738
739    $i=0;
740    while ($row = pwg_db_fetch_assoc($result))
741    {
742      $returned0[$i] = $row; $i++;
743    }
744    $returned[0] = $returned0;
745
746    $result = pwg_query($sql);
747    if($result)
748    {
749      $row = pwg_db_fetch_row($result); $returned[1] = $row[0];
750    }
751    else
752    {
753      $returned[1] = -1;
754    }
755
756    return($returned);
757  } //stat by images
758
759
760  /*
761    template related functions
762
763    theses functions call stat function, and display result with template usage
764  */
765
766
767
768  private function display_stats_by_period($total, $year, $month, $day, $max_width, $seetimerequest)
769  {
770    global $template;
771
772    $template->set_filename('body_page', dirname(__FILE__)."/admin/astat_by_period.tpl");
773
774
775    $template_datas=array();
776    $template_datarows=array();
777
778
779    /* requete */
780    //calc_time(true);
781    $stats = $this->stats_by_period($total, $year, $month, $day);
782    //$timerequest=calc_time(false);
783
784    $dir_links = "";
785    $a_links=array("global" => $this->page_link."&amp;fAStat_defper=N&amp;fAStat_all=Y",
786        "all" => $this->page_link."&amp;fAStat_defper=N&amp;fAStat_all=N",
787        "year" => $this->page_link."&amp;fAStat_defper=N&amp;fAStat_all=N&amp;fAStat_year=$year",
788        "month" => $this->page_link."&amp;fAStat_defper=N&amp;fAStat_all=N&amp;fAStat_year=$year&amp;fAStat_month=$month",
789        "day" => $this->page_link."&amp;fAStat_defper=N&amp;fAStat_all=N&amp;fAStat_year=$year&amp;fAStat_month=$month&amp;fAStat_day=$day");
790
791    $ip_links=array("all" => $this->page_link."&amp;fAStat_tabsheet=stats_by_ip",
792        "year" => $this->page_link."&amp;fAStat_tabsheet=stats_by_ip&amp;fAStat_year=",
793        "month" => $this->page_link."&amp;fAStat_tabsheet=stats_by_ip&amp;fAStat_year=$year&amp;fAStat_month=",
794        "day" => $this->page_link."&amp;fAStat_tabsheet=stats_by_ip&amp;fAStat_year=$year&amp;fAStat_month=$month&amp;fAStat_day=");
795
796    $cat_links=array("all" => $this->page_link."&amp;fAStat_tabsheet=stats_by_category",
797        "year" => $this->page_link."&amp;fAStat_tabsheet=stats_by_category&amp;fAStat_year=",
798        "month" => $this->page_link."&amp;fAStat_tabsheet=stats_by_category&amp;fAStat_year=$year&amp;fAStat_month=",
799        "day" => $this->page_link."&amp;fAStat_tabsheet=stats_by_category&amp;fAStat_year=$year&amp;fAStat_month=$month&amp;fAStat_day=");
800
801    $img_links=array("all" => $this->page_link."&amp;fAStat_tabsheet=stats_by_image",
802        "year" => $this->page_link."&amp;fAStat_tabsheet=stats_by_image&amp;fAStat_year=",
803        "month" => $this->page_link."&amp;fAStat_tabsheet=stats_by_image&amp;fAStat_year=$year&amp;fAStat_month=",
804        "day" => $this->page_link."&amp;fAStat_tabsheet=stats_by_image&amp;fAStat_year=$year&amp;fAStat_month=$month&amp;fAStat_day=");
805
806
807    /* period label + navigation links */
808    if($day!="")
809    {
810      $template_datas["PERIOD_LABEL"] = l10n("AStat_period_label_hours");
811      $template_datas["L_STAT_TITLE"] = $this->format_link(l10n("AStat_period_label_global"), $a_links["global"])." / ".$this->format_link(l10n("AStat_period_label_all"), $a_links["all"])." / ".$this->format_link($year, $a_links["year"])." / ".$this->format_link(l10n("AStat_month_of_year_".$month), $a_links["month"])." / ".l10n("AStat_day_of_week_".date("w",mktime(0, 0, 0, $month, $day, $year)))." $day";
812    }
813    elseif($month!="")
814    {
815      $template_datas["PERIOD_LABEL"] = l10n("AStat_period_label_days");
816      $template_datas["L_STAT_TITLE"] = $this->format_link(l10n("AStat_period_label_global"), $a_links["global"])." / ".$this->format_link(l10n("AStat_period_label_all"), $a_links["all"])." / ".$this->format_link($year, $a_links["year"])." / ".l10n("AStat_month_of_year_".$month);
817    }
818    elseif($year!="")
819    {
820      $template_datas["PERIOD_LABEL"] = l10n("AStat_period_label_months");
821      $template_datas["L_STAT_TITLE"] = $this->format_link(l10n("AStat_period_label_global"), $a_links["global"])." / ".$this->format_link(l10n("AStat_period_label_all"), $a_links["all"])." / ".$year;
822    }
823    elseif($total!="Y")
824    {
825      $template_datas["PERIOD_LABEL"] = l10n("AStat_period_label_years");
826      $template_datas["L_STAT_TITLE"] = $this->format_link(l10n("AStat_period_label_global"), $a_links["global"])." / ".l10n("AStat_period_label_all");
827    }
828    else
829    {
830      $template_datas["PERIOD_LABEL"] = l10n("AStat_period_label_all");
831      $template_datas["L_STAT_TITLE"] = l10n("AStat_period_label_global");
832    }
833    $template_datas["MAX_WIDTH"] = $max_width+10;
834    $template_datas["ASTAT_NFO_STAT"] = l10n("AStat_Nfo_Period");
835
836    if($seetimerequest=='true')
837    {
838      $template_datas["ASTAT_TIME_REQUEST"] = l10n('AStat_time_request_label').' '.$timerequest.'s';
839    }
840
841    /* tableau de stat */
842    for($i=0;$i<count($stats);$i++)
843    {
844      if($stats[$i]["MaxPages"] > 0)
845      {
846        $width_pages = ceil(($stats[$i]["NbPages"] * $max_width) / $stats[$i]["MaxPages"] );
847        $width_img = ceil(($stats[$i]["NbImg"] * $max_width) / $stats[$i]["MaxPages"] );
848        $width_ip = ceil(($stats[$i]["NbIP"] * $max_width) / $stats[$i]["MaxPages"] );
849        $width_cat = ceil(($stats[$i]["NbCat"] * $max_width) / $stats[$i]["MaxPages"] );
850      }
851      else
852      {
853        $width_pages = 0;
854        $width_img = 0;
855        $width_ip = 0;
856        $width_cat = 0;
857      }
858
859
860      if($day!="")
861      { // si jours sélectionné, heures affichées
862        $value=$stats[$i]["GId"];
863        $link="";
864        $value_ip="";
865        $value_cat="";
866        $value_img="";
867      }
868      elseif($month!="")
869      { // si mois sélectionné, jours affichés
870        $value = $stats[$i]["GId"]." (".l10n("AStat_day_of_week_".date("w",mktime(0, 0, 0, $month, $stats[$i]["GId"], $year))).")";
871        $link=$this->page_link."&amp;fAStat_defper=N&amp;fAStat_all=N&amp;fAStat_year=$year&amp;fAStat_month=$month&amp;fAStat_day=".$stats[$i]["GId"];
872        $value_ip=$ip_links["day"].$stats[$i]["GId"];
873        $value_cat=$cat_links["day"].$stats[$i]["GId"];
874        $value_img=$img_links["day"].$stats[$i]["GId"];
875      }
876      elseif($year!="")
877      { // si année sélectionnée, mois affichés
878        $value = l10n("AStat_month_of_year_".$stats[$i]["GId"]);
879        $link=$this->page_link."&amp;fAStat_defper=N&amp;fAStat_all=N&amp;fAStat_year=$year&amp;fAStat_month=".$stats[$i]["GId"];
880        $value_ip=$ip_links["month"].$stats[$i]["GId"];
881        $value_cat=$cat_links["month"].$stats[$i]["GId"];
882        $value_img=$img_links["month"].$stats[$i]["GId"];
883      }
884      elseif($total!="Y")
885      { // si total sélectionné, années affichées
886        $value = $stats[$i]["GId"];
887        $link=$this->page_link."&amp;fAStat_defper=N&amp;fAStat_all=N&amp;fAStat_year=".$stats[$i]["GId"];
888        $value_ip=$ip_links["year"].$stats[$i]["GId"];
889        $value_cat=$cat_links["year"].$stats[$i]["GId"];
890        $value_img=$img_links["year"].$stats[$i]["GId"];
891      }
892      else
893      {
894        $value=l10n("AStat_period_label_all");
895        $link=$this->page_link."&amp;fAStat_defper=N&amp;fAStat_all=N";
896        $value_ip=$ip_links["all"];
897        $value_cat=$cat_links["all"];
898        $value_img=$img_links["all"];
899      }
900
901
902      if((($stats[$i]["NbPages"] + $stats[$i]["NbImg"] + $stats[$i]["NbIP"])>0)&&($link!=""))
903      { $value=$this->format_link($value, $link); }
904
905      if((($stats[$i]["NbIP"])>0)&&($value_ip!=""))
906      { $value_ip=$this->format_link($stats[$i]["NbIP"], $value_ip); }
907      else
908      { $value_ip = $stats[$i]["NbIP"]; }
909
910      if((($stats[$i]["NbCat"])>0)&&($value_cat!=""))
911      { $value_cat=$this->format_link($stats[$i]["NbCat"], $value_cat); }
912      else
913      { $value_cat= $stats[$i]["NbCat"]; }
914
915      if((($stats[$i]["NbImg"])>0)&&($value_img!=""))
916      { $value_img=$this->format_link($stats[$i]["NbImg"], $value_img); }
917      else
918      { $value_img= $stats[$i]["NbImg"]; }
919
920
921
922      $template_datarows[]=array(
923        'VALUE' => $value,
924        'PAGES' => $stats[$i]["NbPages"],
925        'PICTURES' => $value_img,
926        'CATEGORIES' => $value_cat,
927        'IPVISIT' => $value_ip,
928        'WIDTH1' => $width_ip,
929        'WIDTH2' => $width_img,
930        'WIDTH3' => $width_pages,
931        'WIDTH4' => $width_cat,
932      );
933
934    }
935
936    $template->assign('datas', $template_datas);
937    $template->assign('datarows', $template_datarows);
938    $template->assign_var_from_handle('ASTAT_BODY_PAGE', 'body_page');
939  } //display_stats_by_period
940
941
942
943  /*
944    display stat by ip
945  */
946  private function display_stats_by_ip($year, $month, $day, $max_width, $nbipperpage, $pagenumber, $sortip, $seetimerequest)
947  {
948    global $template;
949
950    $template->set_filename('body_page', dirname(__FILE__)."/admin/astat_by_ip.tpl");
951
952
953    $template_datas=array();
954    $template_datarows=array();
955
956
957    /* requete */
958    //calc_time(true);
959    $returned = $this->stats_by_ip($year, $month, $day, $nbipperpage, $pagenumber, $sortip);
960    //$timerequest=calc_time(false);
961    $stats=$returned[0];
962    $nbfoundrows=$returned[1];
963    $nbpages=ceil($nbfoundrows / $nbipperpage);
964
965
966    $dir_links = "";
967    $page_link = "";
968    $a_links=array("global" => $this->page_link."&amp;fAStat_defper=N&amp;fAStat_all=Y",
969        "all" => $this->page_link."&amp;fAStat_defper=N&amp;fAStat_all=N",
970        "year" => $this->page_link."&amp;fAStat_defper=N&amp;fAStat_all=N&amp;fAStat_year=$year",
971        "month" => $this->page_link."&amp;fAStat_defper=N&amp;fAStat_all=N&amp;fAStat_year=$year&amp;fAStat_month=$month",
972        "day" => $this->page_link."&amp;fAStat_defper=N&amp;fAStat_all=N&amp;fAStat_year=$year&amp;fAStat_month=$month&amp;fAStat_day=$day");
973
974    $ip_links=array("all" => $this->page_link."&amp;fAStat_tabsheet=stats_by_ip",
975        "year" => $this->page_link."&amp;fAStat_tabsheet=stats_by_ip&amp;fAStat_year=$year",
976        "month" => $this->page_link."&amp;fAStat_tabsheet=stats_by_ip&amp;fAStat_year=$year&amp;fAStat_month=$month",
977        "day" => $this->page_link."&amp;fAStat_tabsheet=stats_by_ip&amp;fAStat_year=$year&amp;fAStat_month=$month&amp;fAStat_day=$day");
978
979    $img_links=array("all" => $this->page_link."&amp;fAStat_tabsheet=stats_by_image",
980        "year" => $this->page_link."&amp;fAStat_tabsheet=stats_by_image&amp;fAStat_year=$year",
981        "month" => $this->page_link."&amp;fAStat_tabsheet=stats_by_image&amp;fAStat_year=$year&amp;fAStat_month=$month",
982        "day" => $this->page_link."&amp;fAStat_tabsheet=stats_by_image&amp;fAStat_year=$year&amp;fAStat_month=$month&amp;fAStat_day=$day");
983
984
985    /* periode label + navigation links */
986    if($day!="")
987    {
988      $dir_links = $this->format_link(l10n("AStat_period_label_global"), $a_links["global"])." / ".$this->format_link(l10n("AStat_period_label_all"), $a_links["all"])." / ".$this->format_link($year, $a_links["year"])." / ".$this->format_link(l10n("AStat_month_of_year_".$month), $a_links["month"])." / ".l10n("AStat_day_of_week_".date("w",mktime(0, 0, 0, $month, $day, $year)))." $day";
989      $page_link=$ip_links["day"];
990      $img_link=$img_links["day"];
991    }
992    elseif($month!="")
993    {
994      $dir_links = $this->format_link(l10n("AStat_period_label_global"), $a_links["global"])." / ".$this->format_link(l10n("AStat_period_label_all"), $a_links["all"])." / ".$this->format_link($year, $a_links["year"])." / ".l10n("AStat_month_of_year_".$month);
995      $page_link=$ip_links["month"];
996      $img_link=$img_links["month"];
997    }
998    elseif($year!="")
999    {
1000      $dir_links = $this->format_link(l10n("AStat_period_label_global"), $a_links["global"])." / ".$this->format_link(l10n("AStat_period_label_all"), $a_links["all"])." / ".$year;
1001      $page_link=$ip_links["year"];
1002      $img_link=$img_links["year"];
1003    }
1004    else
1005    {
1006      $dir_links = $this->format_link(l10n("AStat_period_label_global"), $a_links["global"])." / ".l10n("AStat_period_label_all");
1007      $page_link=$ip_links["all"];
1008      $img_link=$img_links["all"];
1009    }
1010
1011
1012    if($nbpages>1) { $plural="s"; } else { $plural=""; }
1013    $pages_links=l10n("AStat_page".$plural."_label")." : ";
1014    for($i=1;$i<=$nbpages;$i++)
1015    {
1016      if($i==$pagenumber)
1017      { $pages_links.=" $i "; }
1018      else
1019      {
1020        $pages_links.=$this->format_link(" $i ", $page_link."&amp;fAStat_page_number=$i&amp;fAStat_SortIP=$sortip");
1021      }
1022    }
1023
1024    $template_datas["L_STAT_TITLE"] = $dir_links;
1025    $template_datas["MAX_WIDTH"]=$max_width+10;
1026    $template_datas["NB_TOTAL_IP"] = l10n('AStat_nb_total_ip')." : $nbfoundrows";
1027    $template_datas["PAGES_LINKS"] = $pages_links;
1028    $template_datas["ASTAT_NFO_STAT"]= l10n("AStat_Nfo_IP");
1029
1030    $template_datas["ASTAT_SORT_LABEL"] = l10n("AStat_SortIPLabel").strtolower(l10n("AStat_sortip_$sortip"));
1031
1032    $template_datas["ASTAT_LABEL_IP_label"] = $this->format_link(l10n("AStat_RefIPLabel"), $page_link."&amp;fAStat_SortIP=ip");
1033    $template_datas["ASTAT_LABEL_Pages_seen"] = $this->format_link(l10n("Pages seen"), $page_link."&amp;fAStat_SortIP=page");
1034    $template_datas["ASTAT_LABEL_Pictures_seen"] = $this->format_link(l10n("Pictures_seen"), $page_link."&amp;fAStat_SortIP=picture");
1035
1036    if($seetimerequest=='true')
1037    {
1038      $template_datas["ASTAT_TIME_REQUEST"] = l10n('AStat_time_request_label').' '.$timerequest.'s';
1039    }
1040
1041    for($i=0;$i<count($stats);$i++)
1042    {
1043        if($stats[$i]["MaxPages"] > 0)
1044      {
1045        $width_pages = ceil(($stats[$i]["NbPages"] * $max_width) / $stats[$i]["MaxPages"] );
1046        $width_img = ceil(($stats[$i]["NbImg"] * $max_width) / $stats[$i]["MaxPages"] );
1047      }
1048      else
1049      {
1050        $width_pages = 0;
1051        $width_img = 0;
1052      }
1053
1054
1055      if($this->is_ip($stats[$i]["IP_USER"]))
1056      {
1057        $ip_geolocalisation='<a href="http://www.geoiptool.com/fr/?IP='.$stats[$i]["IP_USER"].'" title="Geo IP localisation" target="_blank">['.l10n('AStat_IP_geolocalisation').'] </a>';
1058        $ip_adress='<a href="http://www.ripe.net/whois?form_type=simple&amp;full_query_string=&amp;searchtext='.$stats[$i]["IP_USER"].'+&amp;do_search=Search" title="Ripe Whois" target="_blank">'.$stats[$i]["IP_USER"].'</a>';
1059        $ip_blacklist=$page_link."&amp;fAStat_IP_BL=".$stats[$i]["IP_USER"];
1060
1061        if($pagenumber>1)
1062        {
1063          $ip_blacklist.="&amp;fAStat_page_number=$pagenumber";
1064        }
1065
1066        if($sortip!="page")
1067        {
1068          $ip_blacklist.="&amp;fAStat_SortIP=$sortip";
1069        }
1070
1071        if($stats[$i]["blacklist"]=='Y')
1072        {
1073          $ip_blacklist="[".l10n('AStat_IP_blacklist')."]";
1074        }
1075        else
1076        {
1077          $ip_blacklist=$this->format_link("[".l10n('AStat_IP_blacklist')."]", $ip_blacklist);
1078        }
1079      }
1080      else
1081      {
1082        $ip_geolocalisation='';
1083        $ip_adress=$stats[$i]["IP_USER"];
1084        $ip_blacklist='';
1085      }
1086
1087
1088
1089      $template_datarows[]=array(
1090        'ASTAT_IP_BLACKLIST' => $ip_blacklist,
1091        'ASTAT_IP_GEOLOCALISATION' => $ip_geolocalisation,
1092        'ASTAT_IP_ADRESS' => $ip_adress,
1093        'PAGES' => $stats[$i]["NbPages"],
1094        'PICTURES' => $this->format_link($stats[$i]["NbImg"], $img_link."&amp;fAStat_IP=".trim($stats[$i]["IP_USER"])),
1095        'WIDTH1' => $width_img,
1096        'WIDTH2' => $width_pages,
1097      );
1098    }
1099
1100    $template->assign('datas', $template_datas);
1101    $template->assign('datarows', $template_datarows);
1102    $template->assign_var_from_handle('ASTAT_BODY_PAGE', 'body_page');
1103  } // display_stat_by_ip
1104
1105
1106
1107
1108
1109  /*
1110    display stat by category
1111  */
1112  private function display_stats_by_category($year, $month, $day, $max_width, $nbipperpage, $pagenumber,$showthumb, $sortcat, $seetimerequest)
1113  {
1114    global $template, $conf;
1115
1116    $template->set_filename('body_page', dirname(__FILE__)."/admin/astat_by_category.tpl");
1117
1118    $template_datas=array();
1119    $template_datarows=array();
1120
1121    /* requete */
1122    //calc_time(true);
1123    $returned = $this->stats_by_category($year, $month, $day, $nbipperpage, $pagenumber, $showthumb, $sortcat);
1124    //$timerequest=calc_time(false);
1125    $stats=$returned[0];
1126    $nbfoundrows=$returned[1];
1127    $nbpages=ceil($nbfoundrows / $nbipperpage);
1128
1129
1130    $dir_links = "";
1131    $page_link = "";
1132    $a_links=array("global" => $this->page_link."&amp;fAStat_defper=N&amp;fAStat_all=Y",
1133        "all" => $this->page_link."&amp;fAStat_defper=N&amp;fAStat_all=N",
1134        "year" => $this->page_link."&amp;fAStat_defper=N&amp;fAStat_all=N&amp;fAStat_year=$year",
1135        "month" => $this->page_link."&amp;fAStat_defper=N&amp;fAStat_all=N&amp;fAStat_year=$year&amp;fAStat_month=$month",
1136        "day" => $this->page_link."&amp;fAStat_defper=N&amp;fAStat_all=N&amp;fAStat_year=$year&amp;fAStat_month=$month&amp;fAStat_day=$day");
1137
1138    $cat_links=array("all" => $this->page_link."&amp;fAStat_tabsheet=stats_by_category",
1139        "year" => $this->page_link."&amp;fAStat_tabsheet=stats_by_category&amp;fAStat_year=$year",
1140        "month" => $this->page_link."&amp;fAStat_tabsheet=stats_by_category&amp;fAStat_year=$year&amp;fAStat_month=$month",
1141        "day" => $this->page_link."&amp;fAStat_tabsheet=stats_by_category&amp;fAStat_year=$year&amp;fAStat_month=$month&amp;fAStat_day=$day");
1142
1143    /* make navigation links */
1144    if($day!="")
1145    {
1146      $dir_links = $this->format_link(l10n("AStat_period_label_global"), $a_links["global"])." / ".$this->format_link(l10n("AStat_period_label_all"), $a_links["all"])." / ".$this->format_link($year, $a_links["year"])." / ".$this->format_link(l10n("AStat_month_of_year_".$month), $a_links["month"])." / ".l10n("AStat_day_of_week_".date("w",mktime(0, 0, 0, $month, $day, $year)))." $day";
1147      $page_link=$cat_links["day"];
1148    }
1149    elseif($month!="")
1150    {
1151      $dir_links = $this->format_link(l10n("AStat_period_label_global"), $a_links["global"])." / ".$this->format_link(l10n("AStat_period_label_all"), $a_links["all"])." / ".$this->format_link($year, $a_links["year"])." / ".l10n("AStat_month_of_year_".$month);
1152      $page_link=$cat_links["month"];
1153    }
1154    elseif($year!="")
1155    {
1156      $dir_links = $this->format_link(l10n("AStat_period_label_global"), $a_links["global"])." / ".$this->format_link(l10n("AStat_period_label_all"), $a_links["all"])." / ".$year;
1157      $page_link=$cat_links["year"];
1158    }
1159    else
1160    {
1161      $dir_links = $this->format_link(l10n("AStat_period_label_global"), $a_links["global"])." / ".l10n("AStat_period_label_all");
1162      $page_link=$cat_links["all"];
1163    }
1164
1165
1166    if($nbpages>1)
1167    {
1168      $plural="s";
1169    }
1170    else
1171    {
1172      $plural="";
1173    }
1174
1175    $pages_links=l10n("AStat_page".$plural."_label")." : ";
1176    for($i=1;$i<=$nbpages;$i++)
1177    {
1178      if($i==$pagenumber)
1179      {
1180        $pages_links.=" $i ";
1181      }
1182      else
1183      {
1184        $pages_links.=$this->format_link(" $i ", $page_link."&amp;fAStat_SortCat=$sortcat&amp;fAStat_page_number=$i");
1185      }
1186    }
1187
1188
1189    /* navigation */
1190    $template_datas["L_STAT_TITLE"] = $dir_links;
1191    $template_datas["MAX_WIDTH"] = $max_width;
1192    $template_datas["NB_TOTAL_CATEGORY"] = l10n('AStat_nb_total_category')." : $nbfoundrows";
1193    $template_datas["PAGES_LINKS"] = $pages_links;
1194    $template_datas["ASTAT_NFO_STAT"] = l10n("AStat_Nfo_Category");
1195    $template_datas["ASTAT_SORT_LABEL"] = l10n("AStat_SortCatLabel").strtolower(l10n("AStat_sortcat_$sortcat"));
1196
1197    $template_datas["ASTAT_LABEL_pct_Pages_seen"] = $this->format_link(l10n("pct_Pages_seen"), $page_link."&amp;fAStat_SortCat=page");
1198    $template_datas["ASTAT_LABEL_pct_Pictures_seen"] = $this->format_link(l10n("pct_Pictures_seen"), $page_link."&amp;fAStat_SortCat=picture");
1199    $template_datas["ASTAT_LABEL_ratio_Pictures_seen"] = $this->format_link(l10n("ratio_Pictures_seen"), $page_link."&amp;fAStat_SortCat=nbpicture");
1200
1201    if($seetimerequest=='true')
1202    {
1203      $template_datas["ASTAT_TIME_REQUEST"] = l10n('AStat_time_request_label').' '.$timerequest.'s';
1204    }
1205
1206    for($i=0;$i<count($stats);$i++)
1207    {
1208      $width_pages = ceil(($stats[$i]["PctPages"] * $max_width)/100);
1209      $width_img = ceil(($stats[$i]["PctImg"] * $max_width)/100 );
1210
1211      if($showthumb=='true')
1212      {
1213        $filethumb=$this->change_file_ext($stats[$i]["ThumbFile"], $stats[$i]["Extension"]);
1214        $filethumb=str_replace($stats[$i]["ThumbFile"],"thumbnail/".$conf['prefix_thumbnail'].$filethumb,$stats[$i]["ThumbPath"]); }
1215      else
1216      {
1217        $filethumb='';
1218      }
1219
1220      if($stats[$i]["category_id"]>0)
1221      { $category = $this->format_link($stats[$i]["IdCat"], PHPWG_ROOT_PATH."index.php?/category/".$stats[$i]["category_id"]); }
1222      else
1223      {
1224        $category = "<i>".l10n('AStat_section_label').' : ';
1225        if(l10n('AStat_section_'.$stats[$i]["IdCat"])!='AStat_section_'.$stats[$i]["IdCat"])
1226        {
1227          $category.=l10n('AStat_section_'.$stats[$i]["IdCat"]);
1228        }
1229        else
1230        {
1231          $category.=sprintf(l10n('AStat_section_unknown'), $stats[$i]["IdCat"]);
1232        }
1233
1234        $category.="</i>";
1235      }
1236
1237      $template_datarows[]=array(
1238        'THUMBJPG' => $filethumb,
1239        'CATEGORY' => $category,
1240        'PCTPAGES' => $stats[$i]["PctPages"],
1241        'PCTPICTURES' => $stats[$i]["PctImg"],
1242        'RATIOPICTURES' => $stats[$i]["RatioImg"],
1243        'WIDTH1' => $width_img,
1244        'WIDTH2' => $width_pages,
1245      );
1246    }
1247
1248    $template->assign('datas', $template_datas);
1249    $template->assign('datarows', $template_datarows);
1250    $template->assign_var_from_handle('ASTAT_BODY_PAGE', 'body_page');
1251  } // display_stat_by_category
1252
1253
1254
1255  /* ------------------------------------------------------------------------------------------
1256      display stats for images
1257      ------------------------------------------------------------------------------------------ */
1258  function display_stats_by_image($year, $month, $day, $max_width, $nbipperpage, $pagenumber,$showthumb, $sortimg, $ip, $seetimerequest)
1259  {
1260    global $template, $conf;
1261
1262    $template->set_filename('body_page', dirname(__FILE__)."/admin/astat_by_image.tpl");
1263
1264
1265    $template_datas=array();
1266    $template_datarows=array();
1267
1268
1269    //calc_time(true);
1270    $returned = $this->stats_by_image($year, $month, $day, $nbipperpage, $pagenumber, $sortimg, $ip);
1271    //$timerequest=calc_time(false);
1272    $stats=$returned[0];
1273    $nbfoundrows=$returned[1];
1274    $nbpages=ceil($nbfoundrows / $nbipperpage);
1275
1276    $dir_links = "";
1277    $page_link = "";
1278    $a_links=array("global" => $this->page_link."&amp;fAStat_defper=N&amp;fAStat_all=Y",
1279        "all" => $this->page_link."&amp;fAStat_defper=N&amp;fAStat_all=N",
1280        "year" => $this->page_link."&amp;fAStat_defper=N&amp;fAStat_all=N&amp;fAStat_year=$year",
1281        "month" => $this->page_link."&amp;fAStat_defper=N&amp;fAStat_all=N&amp;fAStat_year=$year&amp;fAStat_month=$month",
1282        "day" => $this->page_link."&amp;fAStat_defper=N&amp;fAStat_all=N&amp;fAStat_year=$year&amp;fAStat_month=$month&amp;fAStat_day=$day");
1283
1284    $img_links=array("all" => $this->page_link."&amp;fAStat_tabsheet=stats_by_image",
1285        "year" => $this->page_link."&amp;fAStat_tabsheet=stats_by_image&amp;fAStat_year=$year",
1286        "month" => $this->page_link."&amp;fAStat_tabsheet=stats_by_image&amp;fAStat_year=$year&amp;fAStat_month=$month",
1287        "day" => $this->page_link."&amp;fAStat_tabsheet=stats_by_image&amp;fAStat_year=$year&amp;fAStat_month=$month&amp;fAStat_day=$day");
1288
1289    /* navigation links */
1290    if($day!="")
1291    {
1292      $dir_links = $this->format_link(l10n("AStat_period_label_global"), $a_links["global"])." / ".$this->format_link(l10n("AStat_period_label_all"), $a_links["all"])." / ".$this->format_link($year, $a_links["year"])." / ".$this->format_link(l10n("AStat_month_of_year_".$month), $a_links["month"])." / ".l10n("AStat_day_of_week_".date("w",mktime(0, 0, 0, $month, $day, $year)))." $day";
1293      $page_link=$img_links["day"];
1294    }
1295    elseif($month!="")
1296    {
1297      $dir_links = $this->format_link(l10n("AStat_period_label_global"), $a_links["global"])." / ".$this->format_link(l10n("AStat_period_label_all"), $a_links["all"])." / ".$this->format_link($year, $a_links["year"])." / ".l10n("AStat_month_of_year_".$month);
1298      $page_link=$img_links["month"];
1299    }
1300    elseif($year!="")
1301    {
1302      $dir_links = $this->format_link(l10n("AStat_period_label_global"), $a_links["global"])." / ".$this->format_link(l10n("AStat_period_label_all"), $a_links["all"])." / ".$year;
1303      $page_link=$img_links["year"];
1304    }
1305    else
1306    {
1307      $dir_links = $this->format_link(l10n("AStat_period_label_global"), $a_links["global"])." / ".l10n("AStat_period_label_all");
1308      $page_link=$img_links["all"];
1309    }
1310
1311    if($ip!="")
1312    {
1313      $dir_links.= " [IP : $ip]";
1314    }
1315
1316
1317    if($nbpages>1) { $plural="s"; } else { $plural=""; }
1318    $pages_links=l10n("AStat_page".$plural."_label")." : ";
1319    for($i=1;$i<=$nbpages;$i++)
1320    {
1321      if($i==$pagenumber)
1322      { $pages_links.=" $i "; }
1323      else
1324      {
1325        if($ip!="") { $ip_link="&amp;fAStat_IP=$ip"; } else { $ip_link=""; }
1326        $pages_links.=$this->format_link(" $i ", $page_link."&amp;fAStat_SortImg=$sortimg&amp;fAStat_page_number=$i".$ip_link);
1327      }
1328    }
1329
1330
1331    /* navigation */
1332    $template_datas["L_STAT_TITLE"] = $dir_links;
1333    $template_datas["MAX_WIDTH"] = $max_width;
1334    $template_datas["NB_TOTAL_IMAGE"] = l10n('AStat_nb_total_image')." : $nbfoundrows";
1335    $template_datas["PAGES_LINKS"] = $pages_links;
1336    $template_datas["ASTAT_NFO_STAT"] = l10n("AStat_Nfo_Image");
1337    $template_datas["ASTAT_SORT_LABEL"] = l10n("AStat_SortImgLabel").strtolower(l10n("AStat_sortimg_$sortimg"));
1338
1339    $template_datas["ASTAT_LABEL_AStat_RefImageLabel"] = $this->format_link(l10n("AStat_RefImageLabel"), $page_link."&amp;fAStat_SortImg=catname");
1340    $template_datas["ASTAT_LABEL_Pictures_seen"] = $this->format_link(l10n("Pictures_seen"), $page_link."&amp;fAStat_SortImg=picture");
1341    $template_datas["ASTAT_LABEL_pct_Pictures_seen"] = l10n("pct_Pictures_seen");
1342
1343    if($seetimerequest=='true')
1344    {
1345      $template_datas["ASTAT_TIME_REQUEST"] = l10n('AStat_time_request_label').' '.$timerequest.'s';
1346    }
1347
1348    for($i=0;$i<count($stats);$i++)
1349    {
1350      $width_pages = ceil(($stats[$i]["NbVues"] * $max_width)/$stats[$i]["NbVuesMax"] );
1351      $width_img = ceil(($stats[$i]["PctImg"] * $max_width)/100 );
1352
1353      if($showthumb=='true')
1354      {
1355        $filethumb=$this->change_file_ext($stats[$i]["ThumbFile"], $stats[$i]["Extension"]);
1356        $filethumb=str_replace($stats[$i]["ThumbFile"],"thumbnail/".$conf['prefix_thumbnail'].$filethumb,$stats[$i]["ThumbPath"]);
1357      }
1358      else
1359      {
1360        $filethumb='';
1361      }
1362
1363
1364      if($stats[$i]["IdCat"]>0)
1365      {
1366        $image_links = $this->format_link($stats[$i]["CatName"], PHPWG_ROOT_PATH."index.php?/category/".$stats[$i]["IdCat"])." / ";
1367        if($stats[$i]["ImgName"]!="")
1368        {
1369          $image_links.=$this->format_link($stats[$i]["ImgName"], PHPWG_ROOT_PATH."picture.php?/".$stats[$i]["ImgId"]."/category/".$stats[$i]["IdCat"]);
1370        }
1371        else
1372        {
1373          if($stats[$i]["ThumbFile"]!="")
1374          {
1375            $image_links.=$this->format_link("[ ".$stats[$i]["ThumbFile"]." ]", PHPWG_ROOT_PATH."picture.php?/".$stats[$i]["ImgId"]."/category/".$stats[$i]["IdCat"]);
1376          }
1377          else
1378          {
1379            $image_links=l10n('AStat_deleted_picture')." [ Id #".$stats[$i]["ImgId"]." ]";
1380          }
1381        }
1382      }
1383      else
1384      {
1385        $image_links = "<i>".l10n('AStat_section_label').' : ';
1386        if(l10n('AStat_section_'.$stats[$i]["CatName"])!='AStat_section_'.$stats[$i]["CatName"])
1387        {
1388          $image_links.=l10n('AStat_section_'.$stats[$i]["CatName"]);
1389        }
1390        else
1391        {
1392          $image_links.=sprintf(l10n('AStat_section_unknown'), $stats[$i]["CatName"]);
1393        }
1394
1395        $image_links.="</i> / ";
1396
1397        if($stats[$i]["ImgName"]!="")
1398        {
1399          $image_links.=$stats[$i]["ImgName"];
1400        }
1401        else
1402        {
1403          if($stats[$i]["ThumbFile"]!="")
1404          {
1405            $image_links.="[ ".$stats[$i]["ThumbFile"]." ]";
1406          }
1407          else
1408          {
1409            $image_links=l10n('AStat_deleted_picture')." [ Id #".$stats[$i]["ImgId"]." ]";
1410          }
1411        }
1412      }
1413
1414
1415
1416      $template_datarows[]=array(
1417        'THUMBJPG' => $filethumb,
1418        'IMAGE' => $image_links,
1419        'NBPICTURES' => $stats[$i]["NbVues"],
1420        'PCTPICTURES' => $stats[$i]["PctImg"],
1421        'WIDTH1' => $width_img,
1422        'WIDTH2' => $width_pages,
1423      );
1424    }
1425
1426    $template->assign('datas', $template_datas);
1427    $template->assign('datarows', $template_datarows);
1428    $template->assign_var_from_handle('ASTAT_BODY_PAGE', 'body_page');
1429  } // display_stat_by_image
1430
1431
1432
1433
1434  private function add_ip_to_filter($ip)
1435  {
1436    if(strpos($this->my_config['AStat_BlackListedIP'].",", $ip.",")===false)
1437    {
1438      ($this->my_config['AStat_BlackListedIP']!='')?$this->my_config['AStat_BlackListedIP'].=",":"";
1439      $this->my_config['AStat_BlackListedIP'].=$ip;
1440      $this->save_config();
1441    }
1442  }
1443
1444
1445  /*
1446    display config page
1447  */
1448  private function display_config()
1449  {
1450    global $template, $page;
1451
1452    $save_status=false;
1453
1454    if(isset($_POST['submit']))
1455    {
1456      if(!is_adviser())
1457      {
1458        reset($this->my_config);
1459        while (list($key, $val) = each($this->my_config))
1460        {
1461          if(isset($_POST['f_'.$key]))
1462          {
1463            $this->my_config[$key] = $_POST['f_'.$key];
1464          }
1465        }
1466        if($this->save_config())
1467        {
1468          array_push($page['infos'], l10n('AStat_config_saved'));
1469        }
1470        else
1471        {
1472          array_push($page['errors'], l10n('AStat_adviser_not_authorized'));
1473        }
1474      }
1475      else
1476      {
1477        array_push($page['errors'], l10n('AStat_adviser_not_authorized'));
1478      }
1479    }
1480
1481    $template->set_filename('body_page', dirname(__FILE__).'/admin/astat_config.tpl');
1482
1483    $template_datas=array();
1484    $template_list_values=array();
1485    $template_list_labels=array();
1486
1487    //standards inputs zones
1488    reset($this->my_config);
1489    while (list($key, $val) = each($this->my_config))
1490    {
1491      $template_datas["f_".$key]=$val;
1492    }
1493
1494    //
1495    $template_datas['ajaxurl']=$this->page_link;
1496
1497    // define selected item for lists zones
1498    $template_datas['AStat_periods_selected']=$this->my_config['AStat_default_period'];
1499    $template_datas['AStat_defaultsortcat_selected']=$this->my_config['AStat_DefaultSortCat'];
1500    $template_datas['AStat_defaultsortip_selected']=$this->my_config['AStat_DefaultSortIP'];
1501    $template_datas['AStat_defaultsortimg_selected']=$this->my_config['AStat_DefaultSortImg'];
1502
1503    $template_datas['AStat_showthumbcat_selected']=$this->my_config['AStat_ShowThumbCat'];
1504    $template_datas['AStat_showthumbimg_selected']=$this->my_config['AStat_ShowThumbImg'];
1505    $template_datas['AStat_UseBlackList_selected']=$this->my_config['AStat_UseBlackList'];
1506
1507    // making lists zones
1508    // default period
1509    reset($this->list_periods);
1510    while (list($key, $val) = each($this->list_periods))
1511    {
1512      $template_list_values['periods'][]=$val;
1513      $template_list_labels['periods'][]=l10n('AStat_PeriodPerDefault_'.$val);
1514    }
1515    // default category order
1516    reset($this->list_sortcat);
1517    while (list($key, $val) = each($this->list_sortcat))
1518    {
1519      $template_list_values['sortcat'][]=$val;
1520      $template_list_labels['sortcat'][]=l10n('AStat_sortcat_'.$val);
1521    }
1522    // default ip order
1523    reset($this->list_sortip);
1524    while (list($key, $val) = each($this->list_sortip))
1525    {
1526      $template_list_values['sortip'][]=$val;
1527      $template_list_labels['sortip'][]=l10n('AStat_sortip_'.$val);
1528    }
1529    // default picture order
1530    reset($this->list_sortimg);
1531    while (list($key, $val) = each($this->list_sortimg))
1532    {
1533      $template_list_values['sortimg'][]=$val;
1534      $template_list_labels['sortimg'][]=l10n('AStat_sortimg_'.$val);
1535    }
1536
1537    /* yes/no lists */
1538    $template_list_values['yesno'][]='true';
1539    $template_list_labels['yesno'][]=l10n('AStat_yesno_true');
1540    $template_list_values['yesno'][]='false';
1541    $template_list_labels['yesno'][]=l10n('AStat_yesno_false');
1542
1543    $template_list_values['enableddisabled'][]='true';
1544    $template_list_values['enableddisabled'][]='false';
1545    $template_list_values['enableddisabled'][]='invert';
1546    $template_list_labels['enableddisabled'][]=l10n('AStat_enableddisabled_true');
1547    $template_list_labels['enableddisabled'][]=l10n('AStat_enableddisabled_false');
1548    $template_list_labels['enableddisabled'][]=l10n('AStat_enableddisabled_invert');
1549
1550    $template_datas["L_STAT_TITLE"]=l10n('AStat_config_title');
1551
1552    $template->assign("datas", $template_datas);
1553    $template->assign("AStat_periods_list_values", $template_list_values['periods']);
1554    $template->assign("AStat_periods_list_labels", $template_list_labels['periods']);
1555    $template->assign("AStat_defaultsortip_list_values", $template_list_values['sortip']);
1556    $template->assign("AStat_defaultsortip_list_labels", $template_list_labels['sortip']);
1557    $template->assign("AStat_defaultsortcat_list_values", $template_list_values['sortcat']);
1558    $template->assign("AStat_defaultsortcat_list_labels", $template_list_labels['sortcat']);
1559    $template->assign("AStat_defaultsortimg_list_values", $template_list_values['sortimg']);
1560    $template->assign("AStat_defaultsortimg_list_labels", $template_list_labels['sortimg']);
1561    $template->assign("AStat_yesno_list_values", $template_list_values['yesno']);
1562    $template->assign("AStat_yesno_list_labels", $template_list_labels['yesno']);
1563    $template->assign("AStat_enableddisabled_list_values", $template_list_values['enableddisabled']);
1564    $template->assign("AStat_enableddisabled_list_labels", $template_list_labels['enableddisabled']);
1565
1566    $template->assign_var_from_handle('ASTAT_BODY_PAGE', 'body_page');
1567  } // display_config
1568
1569
1570
1571  /*
1572    display tools page
1573  */
1574  private function display_tools()
1575  {
1576    global $template, $page;
1577
1578    $action_result=array('result' => '', 'action' => '', 'msg' => '', 'nfo' => '');
1579
1580    $template->set_filename('body_page', dirname(__FILE__).'/admin/astat_tools.tpl');
1581
1582    $template_datas=array();
1583
1584    // >> PURGE HISTORY --------------------------------------------------------
1585    if(isset($_POST['apply_tool_purge_history']))
1586    {
1587      if(!is_adviser())
1588      {
1589        $action_result['action']='AStat_tools_purge_history';
1590        $action_result['result']='false';
1591        $action_result['msg']='AStat_tools_result_ko';
1592
1593        $ok_to_purge=true;
1594        if($_REQUEST['fAStat_purge_history_type']=='bydate')
1595        {
1596          // may be this functionnality could be optimized with pcre functions
1597          $date=explode('/', $_REQUEST['fAStat_purge_history_date']);
1598          if(!isset($date[0])) { $date[0]=0; }
1599          if(!isset($date[1])) { $date[1]=0; }
1600          if(!isset($date[2])) { $date[2]=0; }
1601
1602          $purge_date=mktime(0,0,0,$date[1],$date[0],$date[2]);
1603          $fparam=date("Y-m-d", mktime(0,0,0,$date[1],$date[0],$date[2]));
1604
1605          if(date("d/m/Y", $purge_date)!=$_REQUEST['fAStat_purge_history_date'])
1606          {
1607            $action_result['nfo']='AStat_tools_invalid_date';
1608            $ok_to_purge=false;
1609          }
1610          elseif(date("Ymd", $purge_date)>=date("Ymd"))
1611          {
1612            $action_result['nfo']='AStat_tools_invalid_date2';
1613            $ok_to_purge=false;
1614          }
1615        }
1616        elseif($_REQUEST['fAStat_purge_history_type']=='byipid0')
1617        {
1618          $fparam=$this->my_config['AStat_BlackListedIP'];
1619        }
1620        else
1621        {
1622          $fparam="";
1623        }
1624
1625        if($ok_to_purge)
1626        {
1627          $result=$this->do_purge_history( $fparam, $_REQUEST['fAStat_purge_history_type']);
1628          if($result)
1629          {
1630            $action_result['result']='true';
1631            $action_result['msg']='AStat_tools_result_ok';
1632          }
1633        }
1634      }
1635      else
1636      {
1637        array_push($page['errors'], l10n('AStat_adviser_not_authorized'));
1638      }
1639    }
1640    // << PURGE HISTORY --------------------------------------------------------
1641
1642    // >> DELETED_PICTURE ------------------------------------------------------
1643    elseif(isset($_POST['apply_tool_deleted_picture_resync']))
1644    {
1645      if(!is_adviser())
1646      {
1647        $action_result['action']='AStat_tools_deleted_picture';
1648        $action_result['result']='false';
1649        $action_result['msg']='AStat_tools_result_ko';
1650
1651        if($_POST['fAStat_tools_deleted_picture_action']=='prepare')
1652        {
1653          if($this->prepare_AStat_picture_table())
1654          {
1655            $action_result['result']='true';
1656            $action_result['msg']='AStat_tools_result_ok';
1657            $action_result['nfo']='AStat_tools_deleted_picture_ok0';
1658          }
1659          else
1660          {
1661            $action_result['nfo']='AStat_tools_deleted_picture_error0';
1662          }
1663        }
1664        elseif($_POST['fAStat_tools_deleted_picture_action']=='apply')
1665        {
1666          if($this->apply_AStat_picture_table())
1667          {
1668            $action_result['result']='true';
1669            $action_result['msg']='AStat_tools_result_ok';
1670            $action_result['nfo']='AStat_tools_deleted_picture_ok1';
1671          }
1672          else
1673          {
1674            $action_result['nfo']='AStat_tools_deleted_picture_error1';
1675          }
1676        }
1677      }
1678      else
1679      {
1680        array_push($page['errors'], l10n('AStat_adviser_not_authorized'));
1681      }
1682    }
1683    //
1684    elseif(isset($_POST['apply_tool_deleted_picture']))
1685    {
1686      if(!is_adviser())
1687      {
1688        $action_result['action']='AStat_tools_deleted_picture';
1689        $action_result['result']='false';
1690        $action_result['msg']='AStat_tools_result_ko';
1691
1692        $nfo = $this->tools_deleted_picture('to0');
1693        if($nfo[0]==1)
1694        {
1695          $action_result['result']='true';
1696          $action_result['msg']='AStat_tools_result_ok';
1697        }
1698      }
1699      else
1700      {
1701        array_push($page['errors'], l10n('AStat_adviser_not_authorized'));
1702      }
1703    }
1704    // << DELETED_PICTURE ------------------------------------------------------
1705
1706    // >> DELETED_CATEGORY -----------------------------------------------------
1707    elseif(isset($_POST['apply_tool_deleted_category']))
1708    {
1709      if(!is_adviser())
1710      {
1711        $action_result['action']='AStat_tools_deleted_category';
1712        $action_result['result']='false';
1713        $action_result['msg']='AStat_tools_result_ko';
1714
1715        $nfo = $this->tools_deleted_category('to0');
1716        if($nfo[0]==1)
1717        {
1718          $action_result['result']='true';
1719          $action_result['msg']='AStat_tools_result_ok';
1720        }
1721      }
1722      else
1723      {
1724        array_push($page['errors'], l10n('AStat_adviser_not_authorized'));
1725      }
1726    }
1727    // << DELETED_CATEGORY -----------------------------------------------------
1728
1729    // >> DELETED USER ---------------------------------------------------------
1730    elseif(isset($_POST['apply_tool_deleted_user']))
1731    {
1732      if(!is_adviser())
1733      {
1734        $action_result['action']='AStat_tools_deleted_user';
1735        $action_result['result']='false';
1736        $action_result['msg']='AStat_tools_result_ko';
1737
1738        $nfo = $this->tools_deleted_user('resynchro');
1739        if($nfo[0]==1)
1740        {
1741          $action_result['result']='true';
1742          $action_result['msg']='AStat_tools_result_ok';
1743        }
1744      }
1745      else
1746      {
1747        array_push($page['errors'], l10n('AStat_adviser_not_authorized'));
1748      }
1749    }
1750    // << DELETED USER ---------------------------------------------------------
1751
1752
1753    // >> DISPLAY DELETED_PICTURE NFO ------------------------------------------
1754    $table_exists=$this->verify_AStat_picture_table_status();
1755    if($table_exists==true)
1756    {
1757      $template_datas["ASTAT_DELETED_PICTURE_DO_ACTION"] = "checked";
1758      $template_datas["ASTAT_DELETED_PICTURE_PREPARE"] = "disabled";
1759    }
1760    else
1761    {
1762      $template_datas["ASTAT_DELETED_PICTURE_PREPARE"]="checked";
1763      $template_datas["ASTAT_DELETED_PICTURE_DO_ACTION"]="disabled";
1764    }
1765
1766    $nfo=$this->count_AStat_picture_table();
1767    $template_datas["ASTAT_DELETED_PICTURE_NFO_NB"] = sprintf(l10n('AStat_tools_deleted_picture_nfo_nb'), $nfo[1], $nfo[2]);
1768
1769    $nfo = $this->tools_deleted_picture('analyse');
1770    if($nfo[0]>0)
1771    {
1772      $list='';
1773      for($i=0;$i<count($nfo[2]);$i++)
1774      {
1775        if($nfo[2][$i][0]>1) { $s='s'; } else { $s=''; }
1776        $list.="<li>image_id #".$nfo[2][$i][1]." : ".$nfo[2][$i][0]." ".l10n("AStat_event$s")."</li>";
1777      }
1778      $template_datas["ASTAT_DELETED_PICTURE_NFO"] = sprintf(l10n('AStat_tools_deleted_picture_nfo1'), $nfo[0], $nfo[1], $list);
1779      //function not yet implemented
1780      $template_datas['AStat_deleted_picture_submit0'] = 'yes';
1781    }
1782    else
1783    {
1784      $template_datas["ASTAT_DELETED_PICTURE_NFO"] = l10n('AStat_tools_deleted_picture_nfo2');
1785    }
1786    // << DISPLAY DELETED_PICTURE NFO ------------------------------------------
1787
1788    // >> DISPLAY DELETED_CATEGORY NFO -----------------------------------------
1789    $nfo = $this->tools_deleted_category('analyse');
1790    if($nfo[0]>0)
1791    {
1792      $list='';
1793      for($i=0;$i<count($nfo[2]);$i++)
1794      {
1795        if($nfo[2][$i][0]>1) { $s='s'; } else { $s=''; }
1796        $list.="<li>category_id #".$nfo[2][$i][1]." : ".$nfo[2][$i][0]." ".l10n("AStat_event$s")."</li>";
1797      }
1798      $template_datas["ASTAT_DELETED_CATEGORY_NFO"] = sprintf(l10n('AStat_tools_deleted_category_nfo1'), $nfo[0], $nfo[1], $list);
1799      //function not yet implemented
1800      $template_datas['AStat_deleted_category_submit0'] = 'yes';
1801    }
1802    else
1803    {
1804      $template_datas["ASTAT_DELETED_CATEGORY_NFO"] = l10n('AStat_tools_deleted_category_nfo2');
1805    }
1806    // << DISPLAY DELETED_CATEGORY NFO -----------------------------------------
1807
1808    // >> DISPLAY DELETED USER NFO ---------------------------------------------
1809    $nfo = $this->tools_deleted_user('analyse');
1810    if($nfo[0]>0)
1811    {
1812      $list='';
1813      for($i=0;$i<count($nfo[2]);$i++)
1814      {
1815        if($nfo[2][$i][0]>1) { $s='s'; } else { $s=''; }
1816        $list.="<li>user_id #".$nfo[2][$i][1]." : ".$nfo[2][$i][0]." ".l10n("AStat_event$s")."</li>";
1817      }
1818      $template_datas["ASTAT_DELETED_USER_NFO"] = sprintf(l10n('AStat_tools_deleted_user_nfo1'), $nfo[0], $nfo[1], $list);
1819      $template_datas['AStat_deleted_user_submit'] = 'yes';
1820    }
1821    else
1822    {
1823      $template_datas["ASTAT_DELETED_USER_NFO"] = l10n('AStat_tools_deleted_user_nfo2');
1824    }
1825    // << DISPLAY DELETED USER NFO ---------------------------------------------
1826
1827
1828    // >> DISPLAY GENERAL NFO --------------------------------------------------
1829    $nfo = $this->tools_general_nfo();
1830    if($nfo[0]>0)
1831    {
1832      $template_datas["ASTAT_GENERAL_NFO"] = sprintf(l10n('AStat_tools_general_nfo_nfo'),
1833              $nfo[0],
1834              $this->formatoctet($nfo[3]+$nfo[4], "A", " ", 2, true),
1835              $this->formatoctet($nfo[3], "A", " ", 2, true),
1836              $this->formatoctet($nfo[4], "A", " ", 2, true),
1837              date(l10n('AStat_date_time_format'), strtotime($nfo[2])),
1838              date(l10n('AStat_date_time_format'), strtotime($nfo[1])) );
1839      $template_datas["ASTAT_MINDATE"]=date("m/d/Y",strtotime($nfo[2]));
1840    }
1841
1842    $nfo=$this->purge_history_count_imageid0();
1843    $template_datas["ASTAT_PURGE_HISTORY_IMAGE_NFO"] = sprintf(l10n('AStat_tools_purge_history_imageid0'), $nfo);
1844    if($nfo==0)
1845    {
1846      $template_datas["ASTAT_PURGE_HISTORY_IMAGE_DISABLED"] = " disabled ";
1847    }
1848    $nfo=$this->purge_history_count_categoryid0();
1849    $template_datas["ASTAT_PURGE_HISTORY_CATEGORY_NFO"] = sprintf(l10n('AStat_tools_purge_history_categoryid0'), $nfo);
1850    if($nfo==0)
1851    {
1852      $template_datas["ASTAT_PURGE_HISTORY_CATEGORY_DISABLED"] = " disabled ";
1853    }
1854    $nfo=$this->purge_history_count_ipid0();
1855    $template_datas["ASTAT_PURGE_HISTORY_IP_NFO"] = sprintf(l10n('AStat_tools_purge_history_ipid0'), $nfo[1], $nfo[0]);
1856    if($nfo[0]==0)
1857    {
1858      $template_datas["ASTAT_PURGE_HISTORY_IP_DISABLED"] = " disabled ";
1859    }
1860    // << GENERAL NFO ----------------------------------------------------------
1861
1862
1863    if($action_result['result']!='')
1864    {
1865      if($action_result['result']=='true')
1866      {
1867        $value="<p class='infos'>";
1868      }
1869      else
1870      {
1871        $value="<p class='errors'>";
1872      }
1873      $value.="<i>".l10n($action_result['action'])."</i><br>".l10n($action_result['msg'])."<br>";
1874
1875      if($action_result['nfo']!='')
1876      {
1877        $value.="[".l10n($action_result['nfo'])."]</p>";
1878      }
1879
1880      $template_datas["ASTAT_RESULT_OK"] = $value;
1881    }
1882
1883    $template_datas["L_STAT_TITLE"] = l10n('AStat_tools_title');
1884
1885    $template->assign('datas', $template_datas);
1886    $template->assign_var_from_handle('ASTAT_BODY_PAGE', 'body_page');
1887  } // display_tools
1888
1889
1890  /*
1891    tools functions
1892  */
1893
1894
1895
1896  /*
1897    tools : deleted_user
1898    allow to force HISTORY_TABLE.user_id at  2 (guest) for records with user ident
1899    doesn't exist anymore in the USERS_TABLE
1900
1901    Two usages :
1902      - analyse : return infos about records wich need to be updated
1903          * number of users
1904          * number of records in HISTORY_TABLE
1905          * the users list
1906      - resynchro : update table
1907  */
1908  private function tools_deleted_user($mode)
1909  {
1910    $returned = array(-1,0,'');
1911
1912    if($mode=='analyse')
1913    {
1914      $sql="SELECT count(id) as NbRecord, user_id ";
1915      $sql.=" FROM ".HISTORY_TABLE;
1916      $sql.=" WHERE ".HISTORY_TABLE.".user_id NOT IN (SELECT id FROM ".USERS_TABLE.") ";
1917      $sql.=" GROUP BY user_id ORDER BY NbRecord";
1918      $result=pwg_query($sql);
1919      if($result)
1920      {
1921        $returned[0]=0;
1922        while ($row = pwg_db_fetch_row($result))
1923        {
1924          $returned[2][$returned[0]][0] = $row[0];
1925          $returned[2][$returned[0]][1] = $row[1];
1926          $returned[0]++;
1927          $returned[1]+=$row[0];
1928        }
1929
1930      }
1931    }
1932    elseif($mode=='resynchro')
1933    {
1934      $sql="UPDATE ".HISTORY_TABLE." SET user_id = 2 ";
1935      $sql.=" WHERE ".HISTORY_TABLE.".user_id NOT IN (SELECT id FROM ".USERS_TABLE.") ";
1936      $result=pwg_query($sql);
1937      if($result)
1938      { $returned[0]=1; }
1939    }
1940    return($returned);
1941  }
1942
1943
1944  /*
1945    tools : deleted_picture
1946    analyse history to find deleted pictures
1947    Two functions :
1948      - analyse : return infos
1949          * number of pictures
1950          * number of record in HISTORY_TABLE
1951          * pictures list
1952      - to0 : update picture ident to  0
1953  */
1954  private function tools_deleted_picture($mode)
1955  {
1956    $returned = array(-1,0,'');
1957
1958    if($mode=='analyse')
1959    {
1960      $sql="SELECT count(id) as NbRecord, image_id ";
1961      $sql.=" FROM ".HISTORY_TABLE;
1962      $sql.=" WHERE ".HISTORY_TABLE.".image_id NOT IN (SELECT id FROM ".IMAGES_TABLE.") and image_id > 0 ";
1963      $sql.=" GROUP BY image_id ORDER BY NbRecord";
1964      $result=pwg_query($sql);
1965
1966      if($result)
1967      {
1968        $returned[0]=0;
1969        while ($row = pwg_db_fetch_row($result))
1970        {
1971          $returned[2][$returned[0]][0] = $row[0];
1972          $returned[2][$returned[0]][1] = $row[1];
1973          $returned[0]++;
1974          $returned[1]+=$row[0];
1975        }
1976
1977      }
1978    }
1979    elseif($mode=='to0')
1980    {
1981      $sql="UPDATE ".HISTORY_TABLE."
1982        SET image_id = 0
1983        WHERE ".HISTORY_TABLE.".image_id > 0
1984          AND ".HISTORY_TABLE.".image_id NOT IN (SELECT id FROM ".IMAGES_TABLE.")";
1985      $result=pwg_query($sql);
1986
1987      if($result)
1988      {
1989        $returned[0]=1;
1990      }
1991    }
1992    return($returned);
1993  }
1994
1995
1996  /*
1997    tools : deleted_category
1998    analyse history to find deleted categories
1999    Two functions :
2000      - analyse : return infos
2001          * number of category
2002          * number of record in HISTORY_TABLE
2003          * catgories list
2004      - to0 : update categories ident to 0
2005  */
2006  private function tools_deleted_category($mode)
2007  {
2008    $returned = array(-1,0,'');
2009
2010    if($mode=='analyse')
2011    {
2012      $sql="SELECT count(id) as NbRecord, category_id ";
2013      $sql.=" FROM ".HISTORY_TABLE;
2014      $sql.=" WHERE ".HISTORY_TABLE.".category_id NOT IN (SELECT id FROM ".CATEGORIES_TABLE.") and category_id > 0";
2015      $sql.=" GROUP BY category_id ORDER BY NbRecord";
2016      $result=pwg_query($sql);
2017
2018      if($result)
2019      {
2020        $returned[0]=0;
2021        while ($row = pwg_db_fetch_row($result))
2022        {
2023          $returned[2][$returned[0]][0] = $row[0];
2024          $returned[2][$returned[0]][1] = $row[1];
2025          $returned[0]++;
2026          $returned[1]+=$row[0];
2027        }
2028
2029      }
2030    }
2031    elseif($mode=='to0')
2032    {
2033      $sql="UPDATE ".HISTORY_TABLE."
2034        SET category_id = NULL, section = 'deleted_cat'
2035        WHERE ".HISTORY_TABLE.".category_id > 0
2036          AND ".HISTORY_TABLE.".category_id NOT IN (SELECT id FROM ".CATEGORIES_TABLE.")";
2037      $result=pwg_query($sql);
2038
2039      if($result)
2040      {
2041        $returned[0]=1;
2042      }
2043    }
2044    return($returned);
2045  }
2046
2047
2048  /*
2049    tools : general_nfo
2050    return infos about historic
2051      0 : nulber of records
2052      1 : date of newest record
2053      2 : date of oldesr record
2054      3 : table size
2055      4 : index size
2056  */
2057  private function tools_general_nfo()
2058  {
2059    $returned = array(-1,'','',0,0);
2060
2061    $sql="SELECT count(id) AS NbRecord, MAX(concat(date,' ', time)) AS LastDate, MIN(concat(date,' ', time)) AS FirstDate ";
2062    $sql.=" FROM ".HISTORY_TABLE;
2063    $result=pwg_query($sql);
2064    if($result)
2065    {
2066      $row = pwg_db_fetch_row($result);
2067      if(is_array($row))
2068      {
2069        $returned = $row;
2070        $sql="SHOW TABLE STATUS LIKE '".HISTORY_TABLE."';";
2071        $result=pwg_query($sql);
2072        if($result)
2073        {
2074          $row2=pwg_db_fetch_assoc($result);
2075          array_push($returned, $row2['Data_length'], $row2['Index_length']);
2076        }
2077      }
2078    }
2079    return($returned);
2080  }
2081
2082
2083  /*
2084    tools : do_purge_history
2085    do a purge of history table :
2086    - $purgetype='bydate' : purge all record wich date is less than given date
2087    - $purgetype='byimageid0' : with and image_id = 0
2088  ------------------------------------------------------------------------------------ */
2089  private function do_purge_history($param, $purgetype)
2090  {
2091    if($purgetype=='bydate')
2092    {
2093      $sql="DELETE FROM ".HISTORY_TABLE." WHERE date < '$param'";
2094    }
2095    elseif($purgetype=='byimageid0')
2096    {
2097      $sql="DELETE FROM ".HISTORY_TABLE." WHERE image_id = 0";
2098    }
2099    elseif($purgetype=='bycategoryid0')
2100    {
2101      $sql="DELETE FROM ".HISTORY_TABLE." WHERE category_id is null and section='deleted_cat'";
2102    }
2103    elseif($purgetype=='byipid0')
2104    {
2105      $sql="DELETE FROM ".HISTORY_TABLE." WHERE ".$this->make_IP_where_clause($param);
2106    }
2107    else
2108    {
2109      return(false);
2110    }
2111
2112    $result=pwg_query($sql);
2113    if($result)
2114    {
2115      $sql="OPTIMIZE TABLE ".HISTORY_TABLE;
2116      $result=pwg_query($sql);
2117      return($result);
2118    }
2119    return(false);
2120  }
2121
2122  private function purge_history_count_imageid0()
2123  {
2124    $sql="SELECT COUNT(id) FROM ".HISTORY_TABLE." WHERE image_id = 0";
2125    $result=pwg_query($sql);
2126    if($result)
2127    {
2128      $row=pwg_db_fetch_row($result);
2129      return($row[0]);
2130    }
2131    return(0);
2132  }
2133
2134  private function purge_history_count_categoryid0()
2135  {
2136    $sql="SELECT COUNT(id) FROM ".HISTORY_TABLE." WHERE category_id is null and section = 'deleted_cat'" ;
2137    $result=pwg_query($sql);
2138    if($result)
2139    {
2140      $row=pwg_db_fetch_row($result);
2141      return($row[0]);
2142    }
2143    return(0);
2144  }
2145
2146  private function purge_history_count_ipid0()
2147  {
2148    if($this->my_config['AStat_BlackListedIP']!="")
2149    {
2150      $list=explode(',', $this->my_config['AStat_BlackListedIP']);
2151    }
2152    else
2153    {
2154      $list=array();
2155    }
2156
2157    $returned=array(0,count($list));
2158
2159    if($this->my_config['AStat_BlackListedIP']!='')
2160    {
2161      $sql="SELECT COUNT(id)
2162            FROM ".HISTORY_TABLE."
2163            WHERE ".$this->make_IP_where_clause($this->my_config['AStat_BlackListedIP']);
2164      $result=pwg_query($sql);
2165      if($result)
2166      {
2167        $row=pwg_db_fetch_row($result);
2168        $returned[0]=$row[0];
2169      }
2170    }
2171    return($returned);
2172  }
2173
2174
2175  /*
2176    tools : deleted_picture
2177    > verify_AStat_picture_table_status :
2178    > prepare_AStat_picture_table :
2179  */
2180  private function verify_AStat_picture_table_status()
2181  {
2182    global $prefixeTable;
2183
2184    $sql="SHOW TABLE STATUS LIKE '".$prefixeTable."AStat_picture'";
2185    $result=pwg_query($sql);
2186    if($result)
2187    {
2188      if(pwg_db_num_rows($result)==1)
2189      {
2190        return(true);
2191      }
2192    }
2193    return(false);
2194  }
2195
2196  private function prepare_AStat_picture_table()
2197  {
2198    global $prefixeTable;
2199
2200    $sql="CREATE TABLE ".$prefixeTable."AStat_picture (PRIMARY KEY (id), KEY ifile(file))
2201      SELECT id, file
2202      FROM ".IMAGES_TABLE;
2203    $result=pwg_query($sql);
2204    if($result)
2205    {
2206      return(true);
2207    }
2208    return(false);
2209  }
2210
2211  private function count_AStat_picture_table()
2212  {
2213    global $prefixeTable;
2214    $returned=array(false,0,0);
2215
2216    if($this->verify_AStat_picture_table_status())
2217    {
2218      $sql="SELECT count(DISTINCT ".$prefixeTable."AStat_picture.id), count(".HISTORY_TABLE.".id)
2219        FROM ".HISTORY_TABLE.", ".$prefixeTable."AStat_picture
2220        WHERE ".HISTORY_TABLE.".image_id = ".$prefixeTable."AStat_picture.id
2221        AND ".HISTORY_TABLE.".image_id NOT IN (SELECT id FROM ".IMAGES_TABLE.")
2222        ORDER BY ".$prefixeTable."AStat_picture.id";
2223      $result=pwg_query($sql);
2224      if($result)
2225      {
2226        if(pwg_db_num_rows($result)>0)
2227        {
2228          $row=pwg_db_fetch_row($result);
2229          $returned[0]=true;
2230          $returned[1]=$row[0];
2231          $returned[2]=$row[1];
2232        }
2233      }
2234    }
2235    return($returned);
2236  }
2237
2238  private function apply_AStat_picture_table()
2239  {
2240    global $prefixeTable;
2241    $returned=false;
2242
2243    $sql="CREATE TABLE ".$prefixeTable."AStat_picture2 (PRIMARY KEY (OldId))
2244      SELECT AStat_tmp.id as OldId , ".IMAGES_TABLE.".id as NewId, ".IMAGES_TABLE.".storage_category_id as NewCatId
2245      FROM (SELECT DISTINCT ".$prefixeTable."AStat_picture.*
2246        FROM ".HISTORY_TABLE.", ".$prefixeTable."AStat_picture
2247        WHERE ".HISTORY_TABLE.".image_id = ".$prefixeTable."AStat_picture.id
2248        AND ".HISTORY_TABLE.".image_id NOT IN (SELECT id FROM ".IMAGES_TABLE.")
2249        ORDER BY ".$prefixeTable."AStat_picture.id
2250      ) as AStat_tmp
2251      LEFT JOIN ".IMAGES_TABLE." ON AStat_tmp.file = ".IMAGES_TABLE.".file";
2252    $result=pwg_query($sql);
2253    if($result)
2254    {
2255      $sql="UPDATE ".HISTORY_TABLE.", ".$prefixeTable."AStat_picture2, ".IMAGES_TABLE."
2256        SET ".HISTORY_TABLE.".image_id = ".$prefixeTable."AStat_picture2.NewId,
2257            ".HISTORY_TABLE.".category_id = ".$prefixeTable."AStat_picture2.NewCatId
2258        WHERE ".$prefixeTable."AStat_picture2.OldId = ".HISTORY_TABLE.".image_id";
2259      $result=pwg_query($sql);
2260      if($result)
2261      {
2262        $returned=true;
2263      }
2264      $sql="DROP TABLE IF EXISTS ".$prefixeTable."AStat_picture2";
2265      $result=pwg_query($sql);
2266      $sql="DROP TABLE IF EXISTS ".$prefixeTable."AStat_picture";
2267      $result=pwg_query($sql);
2268    }
2269    return($returned);
2270  }
2271
2272
2273
2274
2275  /*
2276    generics functions
2277  */
2278
2279  /*
2280    this function make filter list and apply template
2281
2282      $selected : category_id of selected item ("" if none)
2283  */
2284  private function make_filter_list($selected="")
2285  {
2286    global $template;
2287
2288    $template_datarows_values=array();
2289    $template_datarows_labels=array();
2290    $template_hiddenrows=array();
2291
2292
2293    $template_datarows_values[]="";
2294    $template_datarows_labels[]=l10n("AStat_nofilter");
2295
2296    $sql="SELECT id, name, global_rank FROM ".CATEGORIES_TABLE." order by global_rank";
2297    $result = pwg_query($sql);
2298    if($result)
2299    {
2300      while ($row = pwg_db_fetch_assoc($result))
2301      {
2302        $text=str_repeat('&nbsp;&nbsp;', substr_count($row['global_rank'], '.'));
2303        $template_datarows_values[]=$row['id'];
2304        $template_datarows_labels[]=$text.$row['name'];
2305      }
2306    }
2307
2308    $query=explode('&', $_SERVER['QUERY_STRING']);
2309    foreach($query as $key => $value)
2310    {
2311      $nfo=explode('=', $value);
2312      $template_hiddenrows[]=array(
2313          'VALUE' => urldecode($nfo[1]),
2314          'NAME' => $nfo[0]
2315      );
2316    }
2317
2318    $template->assign('ASTAT_LINK', $_SERVER['SCRIPT_NAME']);
2319    $template->assign('f_AStat_catfilter_list_values', $template_datarows_values);
2320    $template->assign('f_AStat_catfilter_list_labels', $template_datarows_labels);
2321    $template->assign('f_AStat_catfilter_selected', $selected);
2322    $template->assign('f_AStat_parameters', $template_hiddenrows);
2323  } //make_filter_list
2324
2325
2326  /*
2327    this function make SELECT "WHERE" clause for filter list
2328
2329      $selected : category_id of selected item ("" if none)
2330  */
2331  private function make_where_clause($catfilter)
2332  {
2333    $returned=array();
2334    $sql="SELECT id, ".CATEGORIES_TABLE.".global_rank
2335          FROM ".CATEGORIES_TABLE.",
2336               (SELECT global_rank FROM ".CATEGORIES_TABLE." WHERE id = '".$catfilter."') as tmp1
2337          WHERE ".CATEGORIES_TABLE.".global_rank LIKE CONCAT(tmp1.global_rank, '%')
2338          ORDER BY ".CATEGORIES_TABLE.".global_rank";
2339    $result = pwg_query($sql);
2340
2341    if($result)
2342    {
2343      while ($row = pwg_db_fetch_row($result))
2344      {
2345        $returned[]=$row[0];
2346      }
2347    }
2348
2349    return(implode(',', $returned));
2350  }
2351
2352
2353  /*
2354    format text : <a href="$link">$value</a>
2355  */
2356  private function format_link($value, $link)
2357  {
2358    return("<a href='$link'>$value</a>");
2359  }
2360
2361  /*
2362    return true if IP adress is given
2363  */
2364  private function is_IP($ip)
2365  {  //basic test, maybe a pcre will be more appropriate...
2366    $tmp=explode('.', $ip);
2367    if(count($tmp)!=4)
2368    { return (false); }
2369
2370    for($i=0;$i<4;$i++)
2371    {
2372      if(!is_numeric($tmp[$i])) { return (false); }
2373    }
2374    return (true);
2375  }
2376
2377  /*
2378    change filename extension
2379  */
2380  private function change_file_ext($file, $newext)
2381  {  //filename can be <filename.truc.jpeg> for example
2382    $tmp = explode('.', $file);
2383    if(count($tmp)>1) { $tmp[count($tmp)-1] = $newext; }
2384    return implode('.', $tmp);
2385  }
2386
2387  /*
2388      format number $octets with unit
2389      $format = "A" : auto
2390                "O" : o
2391                "K" : Ko
2392                "M" : Mo
2393                "G" : Go
2394      $thsep = thousand separator
2395      $prec = number of decimal
2396      $unitevis = true/false > renvoi l'unité ou non dans le résultat
2397  */
2398  private function formatoctet($octets, $format="A", $thsep=" ", $prec=2, $unitevis=true)
2399  {
2400    if($format=="A")
2401    {
2402    if($octets<1024)
2403    { $format="O"; }
2404    elseif($octets<1024000)
2405    { $format="K"; }
2406    elseif($octets<1024000000)
2407    { $format="M"; }
2408    else
2409    { $format="G"; }
2410    }
2411    switch($format)
2412    {
2413    case "O":
2414      $unite="o"; $div=1;
2415      break;
2416    case "K":
2417      $unite="Ko"; $div=1024;
2418      break;
2419    case "M":
2420      $unite="Mo"; $div=1024000;
2421      break;
2422    case "G":
2423      $unite="Go"; $div=1024000000;
2424      break;
2425    }
2426
2427    $retour=number_format($octets/$div, $prec, '.', $thsep);
2428    if($unitevis)
2429    { $retour.=" ".$unite; }
2430    return($retour);
2431  }
2432
2433  private function make_IP_where_clause($list)
2434  {
2435    $returned="";
2436
2437    $tmp=explode(",", $list);
2438    foreach($tmp as $key=>$val)
2439    {
2440      if($returned!="") { $returned.=" OR "; }
2441      $returned.=" IP LIKE '".$val."' ";
2442    }
2443    if($returned!="")
2444    {
2445      $returned ="(".$returned.")";
2446    }
2447    return($returned);
2448  }
2449
2450
2451  /* ---------------------------------------------------------------------------
2452   * AJAX functions
2453   * ------------------------------------------------------------------------- */
2454  protected function ajax_listip($filter, $exclude)
2455  {
2456    $sql="SELECT IP, COUNT(id) as NbEvents FROM ".HISTORY_TABLE;
2457
2458    $where=array();
2459    if($filter!="")
2460    {
2461      $where[]=" IP LIKE '".$filter."' ";
2462    }
2463    if($exclude!="")
2464    {
2465      $where[]=" NOT ".$this->make_IP_where_clause($exclude);
2466    }
2467    if(count($where)>0)
2468    {
2469      $sql.=" WHERE ".implode(" AND ", $where);
2470    }
2471    $sql.=" GROUP BY IP ORDER BY NbEvents desc, IP asc LIMIT 0,100";
2472
2473    $list="<select multiple id='iipsellist'>";
2474    $result=pwg_query($sql);
2475    if($result)
2476    {
2477      while($row=pwg_db_fetch_assoc($result))
2478      {
2479        $list.="<option value='".$row['IP']."'>".$row['IP'].str_repeat("&nbsp;", 15-strlen($row['IP']))."&nbsp;&nbsp;&nbsp;&nbsp;(".$row['NbEvents'].")</option>";
2480      }
2481    }
2482    $list.="</select>";
2483
2484    return($list);
2485  }
2486
2487
2488} // AStat_AI class
2489
2490
2491?>
Note: See TracBrowser for help on using the repository browser.