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

Last change on this file since 15342 was 15342, checked in by grum, 12 years ago

feature:2636 - Compatibility with Piwigo 2.4

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