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

Last change on this file since 14919 was 10264, checked in by grum, 13 years ago

bug:2146
Compatibility with Piwigo 2.2

  • Property svn:executable set to *
File size: 82.8 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().'&amp;fAStat_tabsheet=stats_by_period');
44    $this->tabsheet->add('stats_by_ip',
45                          l10n('AStat_by_ip'),
46                          $this->getAdminLink().'&amp;fAStat_tabsheet=stats_by_ip');
47    $this->tabsheet->add('stats_by_category',
48                          l10n('AStat_by_category'),
49                          $this->getAdminLink().'&amp;fAStat_tabsheet=stats_by_category');
50    $this->tabsheet->add('stats_by_image',
51                          l10n('AStat_by_image'),
52                          $this->getAdminLink().'&amp;fAStat_tabsheet=stats_by_image');
53    $this->tabsheet->add('config',
54                          l10n('AStat_config'),
55                          $this->getAdminLink().'&amp;fAStat_tabsheet=config');
56    $this->tabsheet->add('tools',
57                          l10n('AStat_tools'),
58                          $this->getAdminLink().'&amp;fAStat_tabsheet=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($_REQUEST['fAStat_tabsheet']=='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($_REQUEST['fAStat_tabsheet']=='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($_REQUEST['fAStat_tabsheet']=='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($_REQUEST['fAStat_tabsheet']=='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($_REQUEST['fAStat_tabsheet']=='config')
161    {
162      $this->display_config();
163    }
164    elseif($_REQUEST['fAStat_tabsheet']=='tools')
165    {
166      $this->display_tools();
167    }
168
169    $this->tabsheet->select($_REQUEST['fAStat_tabsheet']);
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"] = $_REQUEST['fAStat_tabsheet'];
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('fAStat_tabsheet', $_REQUEST))
220    {
221      $_REQUEST['fAStat_tabsheet']='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(($_REQUEST['fAStat_tabsheet']=='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 ThumbPath, '.IMAGES_TABLE.'.file as ThumbFile, '.IMAGES_TABLE.'.tn_ext as Extension';
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 ThumbPath, ".IMAGES_TABLE.".file as ThumbFile,
689        MaxImg2.somme as NbVuesMax, ".IMAGES_TABLE.".tn_ext as Extension ";
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()."&amp;fAStat_tabsheet=stats_by_ip",
796        "year" => $this->getAdminLink()."&amp;fAStat_tabsheet=stats_by_ip&amp;fAStat_year=",
797        "month" => $this->getAdminLink()."&amp;fAStat_tabsheet=stats_by_ip&amp;fAStat_year=$year&amp;fAStat_month=",
798        "day" => $this->getAdminLink()."&amp;fAStat_tabsheet=stats_by_ip&amp;fAStat_year=$year&amp;fAStat_month=$month&amp;fAStat_day=");
799
800    $cat_links=array("all" => $this->getAdminLink()."&amp;fAStat_tabsheet=stats_by_category",
801        "year" => $this->getAdminLink()."&amp;fAStat_tabsheet=stats_by_category&amp;fAStat_year=",
802        "month" => $this->getAdminLink()."&amp;fAStat_tabsheet=stats_by_category&amp;fAStat_year=$year&amp;fAStat_month=",
803        "day" => $this->getAdminLink()."&amp;fAStat_tabsheet=stats_by_category&amp;fAStat_year=$year&amp;fAStat_month=$month&amp;fAStat_day=");
804
805    $img_links=array("all" => $this->getAdminLink()."&amp;fAStat_tabsheet=stats_by_image",
806        "year" => $this->getAdminLink()."&amp;fAStat_tabsheet=stats_by_image&amp;fAStat_year=",
807        "month" => $this->getAdminLink()."&amp;fAStat_tabsheet=stats_by_image&amp;fAStat_year=$year&amp;fAStat_month=",
808        "day" => $this->getAdminLink()."&amp;fAStat_tabsheet=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()."&amp;fAStat_tabsheet=stats_by_ip",
979        "year" => $this->getAdminLink()."&amp;fAStat_tabsheet=stats_by_ip&amp;fAStat_year=$year",
980        "month" => $this->getAdminLink()."&amp;fAStat_tabsheet=stats_by_ip&amp;fAStat_year=$year&amp;fAStat_month=$month",
981        "day" => $this->getAdminLink()."&amp;fAStat_tabsheet=stats_by_ip&amp;fAStat_year=$year&amp;fAStat_month=$month&amp;fAStat_day=$day");
982
983    $img_links=array("all" => $this->getAdminLink()."&amp;fAStat_tabsheet=stats_by_image",
984        "year" => $this->getAdminLink()."&amp;fAStat_tabsheet=stats_by_image&amp;fAStat_year=$year",
985        "month" => $this->getAdminLink()."&amp;fAStat_tabsheet=stats_by_image&amp;fAStat_year=$year&amp;fAStat_month=$month",
986        "day" => $this->getAdminLink()."&amp;fAStat_tabsheet=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()."&amp;fAStat_tabsheet=stats_by_category",
1143        "year" => $this->getAdminLink()."&amp;fAStat_tabsheet=stats_by_category&amp;fAStat_year=$year",
1144        "month" => $this->getAdminLink()."&amp;fAStat_tabsheet=stats_by_category&amp;fAStat_year=$year&amp;fAStat_month=$month",
1145        "day" => $this->getAdminLink()."&amp;fAStat_tabsheet=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=$this->change_file_ext($stats[$i]["ThumbFile"], $stats[$i]["Extension"]);
1218        $filethumb=str_replace($stats[$i]["ThumbFile"],"thumbnail/".$conf['prefix_thumbnail'].$filethumb,$stats[$i]["ThumbPath"]); }
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()."&amp;fAStat_tabsheet=stats_by_image",
1289        "year" => $this->getAdminLink()."&amp;fAStat_tabsheet=stats_by_image&amp;fAStat_year=$year",
1290        "month" => $this->getAdminLink()."&amp;fAStat_tabsheet=stats_by_image&amp;fAStat_year=$year&amp;fAStat_month=$month",
1291        "day" => $this->getAdminLink()."&amp;fAStat_tabsheet=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=$this->change_file_ext($stats[$i]["ThumbFile"], $stats[$i]["Extension"]);
1360        $filethumb=str_replace($stats[$i]["ThumbFile"],"thumbnail/".$conf['prefix_thumbnail'].$filethumb,$stats[$i]["ThumbPath"]);
1361      }
1362      else
1363      {
1364        $filethumb='';
1365      }
1366
1367
1368      if($stats[$i]["IdCat"]>0)
1369      {
1370        $image_links = $this->format_link($stats[$i]["CatName"], PHPWG_ROOT_PATH."index.php?/category/".$stats[$i]["IdCat"])." / ";
1371        if($stats[$i]["ImgName"]!="")
1372        {
1373          $image_links.=$this->format_link($stats[$i]["ImgName"], PHPWG_ROOT_PATH."picture.php?/".$stats[$i]["ImgId"]."/category/".$stats[$i]["IdCat"]);
1374        }
1375        else
1376        {
1377          if($stats[$i]["ThumbFile"]!="")
1378          {
1379            $image_links.=$this->format_link("[ ".$stats[$i]["ThumbFile"]." ]", PHPWG_ROOT_PATH."picture.php?/".$stats[$i]["ImgId"]."/category/".$stats[$i]["IdCat"]);
1380          }
1381          else
1382          {
1383            $image_links=l10n('AStat_deleted_picture')." [ Id #".$stats[$i]["ImgId"]." ]";
1384          }
1385        }
1386      }
1387      else
1388      {
1389        $image_links = "<i>".l10n('AStat_section_label').' : ';
1390        if(l10n('AStat_section_'.$stats[$i]["CatName"])!='AStat_section_'.$stats[$i]["CatName"])
1391        {
1392          $image_links.=l10n('AStat_section_'.$stats[$i]["CatName"]);
1393        }
1394        else
1395        {
1396          $image_links.=sprintf(l10n('AStat_section_unknown'), $stats[$i]["CatName"]);
1397        }
1398
1399        $image_links.="</i> / ";
1400
1401        if($stats[$i]["ImgName"]!="")
1402        {
1403          $image_links.=$stats[$i]["ImgName"];
1404        }
1405        else
1406        {
1407          if($stats[$i]["ThumbFile"]!="")
1408          {
1409            $image_links.="[ ".$stats[$i]["ThumbFile"]." ]";
1410          }
1411          else
1412          {
1413            $image_links=l10n('AStat_deleted_picture')." [ Id #".$stats[$i]["ImgId"]." ]";
1414          }
1415        }
1416      }
1417
1418
1419
1420      $template_datarows[]=array(
1421        'THUMBJPG' => $filethumb,
1422        'IMAGE' => $image_links,
1423        'NBPICTURES' => $stats[$i]["NbVues"],
1424        'PCTPICTURES' => $stats[$i]["PctImg"],
1425        'WIDTH1' => $width_img,
1426        'WIDTH2' => $width_pages,
1427      );
1428    }
1429
1430    $template->assign('datas', $template_datas);
1431    $template->assign('datarows', $template_datarows);
1432    $template->assign_var_from_handle('ASTAT_BODY_PAGE', 'body_page');
1433  } // display_stat_by_image
1434
1435
1436
1437
1438  private function add_ip_to_filter($ip)
1439  {
1440    if(strpos($this->config['AStat_BlackListedIP'].",", $ip.",")===false)
1441    {
1442      ($this->config['AStat_BlackListedIP']!='')?$this->config['AStat_BlackListedIP'].=",":"";
1443      $this->config['AStat_BlackListedIP'].=$ip;
1444      $this->saveConfig();
1445    }
1446  }
1447
1448
1449  /*
1450    display config page
1451  */
1452  private function display_config()
1453  {
1454    global $template, $page;
1455
1456    $save_status=false;
1457
1458    if(isset($_POST['submit']))
1459    {
1460      if(!is_adviser())
1461      {
1462        reset($this->config);
1463        while (list($key, $val) = each($this->config))
1464        {
1465          if(isset($_POST['f_'.$key]))
1466          {
1467            $this->config[$key] = $_POST['f_'.$key];
1468          }
1469        }
1470        if($this->saveConfig())
1471        {
1472          array_push($page['infos'], l10n('AStat_config_saved'));
1473        }
1474        else
1475        {
1476          array_push($page['errors'], l10n('AStat_adviser_not_authorized'));
1477        }
1478      }
1479      else
1480      {
1481        array_push($page['errors'], l10n('AStat_adviser_not_authorized'));
1482      }
1483    }
1484
1485    $template->set_filename('body_page', dirname(__FILE__).'/admin/astat_config.tpl');
1486
1487    $template_datas=array();
1488    $template_list_values=array();
1489    $template_list_labels=array();
1490
1491    //standards inputs zones
1492    reset($this->config);
1493    while (list($key, $val) = each($this->config))
1494    {
1495      $template_datas["f_".$key]=$val;
1496    }
1497
1498    //
1499    $template_datas['ajaxurl']=$this->getAdminLink();
1500
1501    // define selected item for lists zones
1502    $template_datas['AStat_periods_selected']=$this->config['AStat_default_period'];
1503    $template_datas['AStat_defaultsortcat_selected']=$this->config['AStat_DefaultSortCat'];
1504    $template_datas['AStat_defaultsortip_selected']=$this->config['AStat_DefaultSortIP'];
1505    $template_datas['AStat_defaultsortimg_selected']=$this->config['AStat_DefaultSortImg'];
1506
1507    $template_datas['AStat_showthumbcat_selected']=$this->config['AStat_ShowThumbCat'];
1508    $template_datas['AStat_showthumbimg_selected']=$this->config['AStat_ShowThumbImg'];
1509    $template_datas['AStat_UseBlackList_selected']=$this->config['AStat_UseBlackList'];
1510
1511    // making lists zones
1512    // default period
1513    reset($this->list_periods);
1514    while (list($key, $val) = each($this->list_periods))
1515    {
1516      $template_list_values['periods'][]=$val;
1517      $template_list_labels['periods'][]=l10n('AStat_PeriodPerDefault_'.$val);
1518    }
1519    // default category order
1520    reset($this->list_sortcat);
1521    while (list($key, $val) = each($this->list_sortcat))
1522    {
1523      $template_list_values['sortcat'][]=$val;
1524      $template_list_labels['sortcat'][]=l10n('AStat_sortcat_'.$val);
1525    }
1526    // default ip order
1527    reset($this->list_sortip);
1528    while (list($key, $val) = each($this->list_sortip))
1529    {
1530      $template_list_values['sortip'][]=$val;
1531      $template_list_labels['sortip'][]=l10n('AStat_sortip_'.$val);
1532    }
1533    // default picture order
1534    reset($this->list_sortimg);
1535    while (list($key, $val) = each($this->list_sortimg))
1536    {
1537      $template_list_values['sortimg'][]=$val;
1538      $template_list_labels['sortimg'][]=l10n('AStat_sortimg_'.$val);
1539    }
1540
1541    /* yes/no lists */
1542    $template_list_values['yesno'][]='true';
1543    $template_list_labels['yesno'][]=l10n('AStat_yesno_true');
1544    $template_list_values['yesno'][]='false';
1545    $template_list_labels['yesno'][]=l10n('AStat_yesno_false');
1546
1547    $template_list_values['enableddisabled'][]='true';
1548    $template_list_values['enableddisabled'][]='false';
1549    $template_list_values['enableddisabled'][]='invert';
1550    $template_list_labels['enableddisabled'][]=l10n('AStat_enableddisabled_true');
1551    $template_list_labels['enableddisabled'][]=l10n('AStat_enableddisabled_false');
1552    $template_list_labels['enableddisabled'][]=l10n('AStat_enableddisabled_invert');
1553
1554    $template_datas["L_STAT_TITLE"]=l10n('AStat_config_title');
1555
1556    $template->assign("datas", $template_datas);
1557    $template->assign("AStat_periods_list_values", $template_list_values['periods']);
1558    $template->assign("AStat_periods_list_labels", $template_list_labels['periods']);
1559    $template->assign("AStat_defaultsortip_list_values", $template_list_values['sortip']);
1560    $template->assign("AStat_defaultsortip_list_labels", $template_list_labels['sortip']);
1561    $template->assign("AStat_defaultsortcat_list_values", $template_list_values['sortcat']);
1562    $template->assign("AStat_defaultsortcat_list_labels", $template_list_labels['sortcat']);
1563    $template->assign("AStat_defaultsortimg_list_values", $template_list_values['sortimg']);
1564    $template->assign("AStat_defaultsortimg_list_labels", $template_list_labels['sortimg']);
1565    $template->assign("AStat_yesno_list_values", $template_list_values['yesno']);
1566    $template->assign("AStat_yesno_list_labels", $template_list_labels['yesno']);
1567    $template->assign("AStat_enableddisabled_list_values", $template_list_values['enableddisabled']);
1568    $template->assign("AStat_enableddisabled_list_labels", $template_list_labels['enableddisabled']);
1569
1570    $template->assign_var_from_handle('ASTAT_BODY_PAGE', 'body_page');
1571  } // display_config
1572
1573
1574
1575  /*
1576    display tools page
1577  */
1578  private function display_tools()
1579  {
1580    global $template, $page;
1581
1582    $action_result=array('result' => '', 'action' => '', 'msg' => '', 'nfo' => '');
1583
1584    $template->set_filename('body_page', dirname(__FILE__).'/admin/astat_tools.tpl');
1585
1586    $template_datas=array();
1587
1588    // >> PURGE HISTORY --------------------------------------------------------
1589    if(isset($_POST['apply_tool_purge_history']))
1590    {
1591      if(!is_adviser())
1592      {
1593        $action_result['action']='AStat_tools_purge_history';
1594        $action_result['result']='false';
1595        $action_result['msg']='AStat_tools_result_ko';
1596
1597        $ok_to_purge=true;
1598        if($_REQUEST['fAStat_purge_history_type']=='bydate')
1599        {
1600          // may be this functionnality could be optimized with pcre functions
1601          $date=explode('/', $_REQUEST['fAStat_purge_history_date']);
1602          if(!isset($date[0])) { $date[0]=0; }
1603          if(!isset($date[1])) { $date[1]=0; }
1604          if(!isset($date[2])) { $date[2]=0; }
1605
1606          $purge_date=mktime(0,0,0,$date[1],$date[0],$date[2]);
1607          $fparam=date("Y-m-d", mktime(0,0,0,$date[1],$date[0],$date[2]));
1608
1609          if(date("d/m/Y", $purge_date)!=$_REQUEST['fAStat_purge_history_date'])
1610          {
1611            $action_result['nfo']='AStat_tools_invalid_date';
1612            $ok_to_purge=false;
1613          }
1614          elseif(date("Ymd", $purge_date)>=date("Ymd"))
1615          {
1616            $action_result['nfo']='AStat_tools_invalid_date2';
1617            $ok_to_purge=false;
1618          }
1619        }
1620        elseif($_REQUEST['fAStat_purge_history_type']=='byipid0')
1621        {
1622          $fparam=$this->config['AStat_BlackListedIP'];
1623        }
1624        else
1625        {
1626          $fparam="";
1627        }
1628
1629        if($ok_to_purge)
1630        {
1631          $result=$this->do_purge_history( $fparam, $_REQUEST['fAStat_purge_history_type']);
1632          if($result)
1633          {
1634            $action_result['result']='true';
1635            $action_result['msg']='AStat_tools_result_ok';
1636          }
1637        }
1638      }
1639      else
1640      {
1641        array_push($page['errors'], l10n('AStat_adviser_not_authorized'));
1642      }
1643    }
1644    // << PURGE HISTORY --------------------------------------------------------
1645
1646    // >> DELETED_PICTURE ------------------------------------------------------
1647    elseif(isset($_POST['apply_tool_deleted_picture_resync']))
1648    {
1649      if(!is_adviser())
1650      {
1651        $action_result['action']='AStat_tools_deleted_picture';
1652        $action_result['result']='false';
1653        $action_result['msg']='AStat_tools_result_ko';
1654
1655        if($_POST['fAStat_tools_deleted_picture_action']=='prepare')
1656        {
1657          if($this->prepare_AStat_picture_table())
1658          {
1659            $action_result['result']='true';
1660            $action_result['msg']='AStat_tools_result_ok';
1661            $action_result['nfo']='AStat_tools_deleted_picture_ok0';
1662          }
1663          else
1664          {
1665            $action_result['nfo']='AStat_tools_deleted_picture_error0';
1666          }
1667        }
1668        elseif($_POST['fAStat_tools_deleted_picture_action']=='apply')
1669        {
1670          if($this->apply_AStat_picture_table())
1671          {
1672            $action_result['result']='true';
1673            $action_result['msg']='AStat_tools_result_ok';
1674            $action_result['nfo']='AStat_tools_deleted_picture_ok1';
1675          }
1676          else
1677          {
1678            $action_result['nfo']='AStat_tools_deleted_picture_error1';
1679          }
1680        }
1681      }
1682      else
1683      {
1684        array_push($page['errors'], l10n('AStat_adviser_not_authorized'));
1685      }
1686    }
1687    //
1688    elseif(isset($_POST['apply_tool_deleted_picture']))
1689    {
1690      if(!is_adviser())
1691      {
1692        $action_result['action']='AStat_tools_deleted_picture';
1693        $action_result['result']='false';
1694        $action_result['msg']='AStat_tools_result_ko';
1695
1696        $nfo = $this->tools_deleted_picture('to0');
1697        if($nfo[0]==1)
1698        {
1699          $action_result['result']='true';
1700          $action_result['msg']='AStat_tools_result_ok';
1701        }
1702      }
1703      else
1704      {
1705        array_push($page['errors'], l10n('AStat_adviser_not_authorized'));
1706      }
1707    }
1708    // << DELETED_PICTURE ------------------------------------------------------
1709
1710    // >> DELETED_CATEGORY -----------------------------------------------------
1711    elseif(isset($_POST['apply_tool_deleted_category']))
1712    {
1713      if(!is_adviser())
1714      {
1715        $action_result['action']='AStat_tools_deleted_category';
1716        $action_result['result']='false';
1717        $action_result['msg']='AStat_tools_result_ko';
1718
1719        $nfo = $this->tools_deleted_category('to0');
1720        if($nfo[0]==1)
1721        {
1722          $action_result['result']='true';
1723          $action_result['msg']='AStat_tools_result_ok';
1724        }
1725      }
1726      else
1727      {
1728        array_push($page['errors'], l10n('AStat_adviser_not_authorized'));
1729      }
1730    }
1731    // << DELETED_CATEGORY -----------------------------------------------------
1732
1733    // >> DELETED USER ---------------------------------------------------------
1734    elseif(isset($_POST['apply_tool_deleted_user']))
1735    {
1736      if(!is_adviser())
1737      {
1738        $action_result['action']='AStat_tools_deleted_user';
1739        $action_result['result']='false';
1740        $action_result['msg']='AStat_tools_result_ko';
1741
1742        $nfo = $this->tools_deleted_user('resynchro');
1743        if($nfo[0]==1)
1744        {
1745          $action_result['result']='true';
1746          $action_result['msg']='AStat_tools_result_ok';
1747        }
1748      }
1749      else
1750      {
1751        array_push($page['errors'], l10n('AStat_adviser_not_authorized'));
1752      }
1753    }
1754    // << DELETED USER ---------------------------------------------------------
1755
1756
1757    // >> DISPLAY DELETED_PICTURE NFO ------------------------------------------
1758    $table_exists=$this->verify_AStat_picture_table_status();
1759    if($table_exists==true)
1760    {
1761      $template_datas["ASTAT_DELETED_PICTURE_DO_ACTION"] = "checked";
1762      $template_datas["ASTAT_DELETED_PICTURE_PREPARE"] = "disabled";
1763    }
1764    else
1765    {
1766      $template_datas["ASTAT_DELETED_PICTURE_PREPARE"]="checked";
1767      $template_datas["ASTAT_DELETED_PICTURE_DO_ACTION"]="disabled";
1768    }
1769
1770    $nfo=$this->count_AStat_picture_table();
1771    $template_datas["ASTAT_DELETED_PICTURE_NFO_NB"] = sprintf(l10n('AStat_tools_deleted_picture_nfo_nb'), $nfo[1], $nfo[2]);
1772
1773    $nfo = $this->tools_deleted_picture('analyse');
1774    if($nfo[0]>0)
1775    {
1776      $list='';
1777      for($i=0;$i<count($nfo[2]);$i++)
1778      {
1779        if($nfo[2][$i][0]>1) { $s='s'; } else { $s=''; }
1780        $list.="<li>image_id #".$nfo[2][$i][1]." : ".$nfo[2][$i][0]." ".l10n("AStat_event$s")."</li>";
1781      }
1782      $template_datas["ASTAT_DELETED_PICTURE_NFO"] = sprintf(l10n('AStat_tools_deleted_picture_nfo1'), $nfo[0], $nfo[1], $list);
1783      //function not yet implemented
1784      $template_datas['AStat_deleted_picture_submit0'] = 'yes';
1785    }
1786    else
1787    {
1788      $template_datas["ASTAT_DELETED_PICTURE_NFO"] = l10n('AStat_tools_deleted_picture_nfo2');
1789    }
1790    // << DISPLAY DELETED_PICTURE NFO ------------------------------------------
1791
1792    // >> DISPLAY DELETED_CATEGORY NFO -----------------------------------------
1793    $nfo = $this->tools_deleted_category('analyse');
1794    if($nfo[0]>0)
1795    {
1796      $list='';
1797      for($i=0;$i<count($nfo[2]);$i++)
1798      {
1799        if($nfo[2][$i][0]>1) { $s='s'; } else { $s=''; }
1800        $list.="<li>category_id #".$nfo[2][$i][1]." : ".$nfo[2][$i][0]." ".l10n("AStat_event$s")."</li>";
1801      }
1802      $template_datas["ASTAT_DELETED_CATEGORY_NFO"] = sprintf(l10n('AStat_tools_deleted_category_nfo1'), $nfo[0], $nfo[1], $list);
1803      //function not yet implemented
1804      $template_datas['AStat_deleted_category_submit0'] = 'yes';
1805    }
1806    else
1807    {
1808      $template_datas["ASTAT_DELETED_CATEGORY_NFO"] = l10n('AStat_tools_deleted_category_nfo2');
1809    }
1810    // << DISPLAY DELETED_CATEGORY NFO -----------------------------------------
1811
1812    // >> DISPLAY DELETED USER NFO ---------------------------------------------
1813    $nfo = $this->tools_deleted_user('analyse');
1814    if($nfo[0]>0)
1815    {
1816      $list='';
1817      for($i=0;$i<count($nfo[2]);$i++)
1818      {
1819        if($nfo[2][$i][0]>1) { $s='s'; } else { $s=''; }
1820        $list.="<li>user_id #".$nfo[2][$i][1]." : ".$nfo[2][$i][0]." ".l10n("AStat_event$s")."</li>";
1821      }
1822      $template_datas["ASTAT_DELETED_USER_NFO"] = sprintf(l10n('AStat_tools_deleted_user_nfo1'), $nfo[0], $nfo[1], $list);
1823      $template_datas['AStat_deleted_user_submit'] = 'yes';
1824    }
1825    else
1826    {
1827      $template_datas["ASTAT_DELETED_USER_NFO"] = l10n('AStat_tools_deleted_user_nfo2');
1828    }
1829    // << DISPLAY DELETED USER NFO ---------------------------------------------
1830
1831
1832    // >> DISPLAY GENERAL NFO --------------------------------------------------
1833    $nfo = $this->tools_general_nfo();
1834    if($nfo[0]>0)
1835    {
1836      $template_datas["ASTAT_GENERAL_NFO"] = sprintf(l10n('AStat_tools_general_nfo_nfo'),
1837              $nfo[0],
1838              $this->formatoctet($nfo[3]+$nfo[4], "A", " ", 2, true),
1839              $this->formatoctet($nfo[3], "A", " ", 2, true),
1840              $this->formatoctet($nfo[4], "A", " ", 2, true),
1841              date(l10n('AStat_date_time_format'), strtotime($nfo[2])),
1842              date(l10n('AStat_date_time_format'), strtotime($nfo[1])) );
1843      $template_datas["ASTAT_MINDATE"]=date("m/d/Y",strtotime($nfo[2]));
1844    }
1845
1846    $nfo=$this->purge_history_count_imageid0();
1847    $template_datas["ASTAT_PURGE_HISTORY_IMAGE_NFO"] = sprintf(l10n('AStat_tools_purge_history_imageid0'), $nfo);
1848    if($nfo==0)
1849    {
1850      $template_datas["ASTAT_PURGE_HISTORY_IMAGE_DISABLED"] = " disabled ";
1851    }
1852    $nfo=$this->purge_history_count_categoryid0();
1853    $template_datas["ASTAT_PURGE_HISTORY_CATEGORY_NFO"] = sprintf(l10n('AStat_tools_purge_history_categoryid0'), $nfo);
1854    if($nfo==0)
1855    {
1856      $template_datas["ASTAT_PURGE_HISTORY_CATEGORY_DISABLED"] = " disabled ";
1857    }
1858    $nfo=$this->purge_history_count_ipid0();
1859    $template_datas["ASTAT_PURGE_HISTORY_IP_NFO"] = sprintf(l10n('AStat_tools_purge_history_ipid0'), $nfo[1], $nfo[0]);
1860    if($nfo[0]==0)
1861    {
1862      $template_datas["ASTAT_PURGE_HISTORY_IP_DISABLED"] = " disabled ";
1863    }
1864    // << GENERAL NFO ----------------------------------------------------------
1865
1866
1867    if($action_result['result']!='')
1868    {
1869      if($action_result['result']=='true')
1870      {
1871        $value="<p class='infos'>";
1872      }
1873      else
1874      {
1875        $value="<p class='errors'>";
1876      }
1877      $value.="<i>".l10n($action_result['action'])."</i><br>".l10n($action_result['msg'])."<br>";
1878
1879      if($action_result['nfo']!='')
1880      {
1881        $value.="[".l10n($action_result['nfo'])."]</p>";
1882      }
1883
1884      $template_datas["ASTAT_RESULT_OK"] = $value;
1885    }
1886
1887    $template_datas["L_STAT_TITLE"] = l10n('AStat_tools_title');
1888
1889    $template->assign('datas', $template_datas);
1890    $template->assign_var_from_handle('ASTAT_BODY_PAGE', 'body_page');
1891  } // display_tools
1892
1893
1894  /*
1895    tools functions
1896  */
1897
1898
1899
1900  /*
1901    tools : deleted_user
1902    allow to force HISTORY_TABLE.user_id at  2 (guest) for records with user ident
1903    doesn't exist anymore in the USERS_TABLE
1904
1905    Two usages :
1906      - analyse : return infos about records wich need to be updated
1907          * number of users
1908          * number of records in HISTORY_TABLE
1909          * the users list
1910      - resynchro : update table
1911  */
1912  private function tools_deleted_user($mode)
1913  {
1914    $returned = array(-1,0,'');
1915
1916    if($mode=='analyse')
1917    {
1918      $sql="SELECT count(id) as NbRecord, user_id ";
1919      $sql.=" FROM ".HISTORY_TABLE;
1920      $sql.=" WHERE ".HISTORY_TABLE.".user_id NOT IN (SELECT id FROM ".USERS_TABLE.") ";
1921      $sql.=" GROUP BY user_id ORDER BY NbRecord";
1922      $result=pwg_query($sql);
1923      if($result)
1924      {
1925        $returned[0]=0;
1926        while ($row = pwg_db_fetch_row($result))
1927        {
1928          $returned[2][$returned[0]][0] = $row[0];
1929          $returned[2][$returned[0]][1] = $row[1];
1930          $returned[0]++;
1931          $returned[1]+=$row[0];
1932        }
1933
1934      }
1935    }
1936    elseif($mode=='resynchro')
1937    {
1938      $sql="UPDATE ".HISTORY_TABLE." SET user_id = 2 ";
1939      $sql.=" WHERE ".HISTORY_TABLE.".user_id NOT IN (SELECT id FROM ".USERS_TABLE.") ";
1940      $result=pwg_query($sql);
1941      if($result)
1942      { $returned[0]=1; }
1943    }
1944    return($returned);
1945  }
1946
1947
1948  /*
1949    tools : deleted_picture
1950    analyse history to find deleted pictures
1951    Two functions :
1952      - analyse : return infos
1953          * number of pictures
1954          * number of record in HISTORY_TABLE
1955          * pictures list
1956      - to0 : update picture ident to  0
1957  */
1958  private function tools_deleted_picture($mode)
1959  {
1960    $returned = array(-1,0,'');
1961
1962    if($mode=='analyse')
1963    {
1964      $sql="SELECT count(id) as NbRecord, image_id ";
1965      $sql.=" FROM ".HISTORY_TABLE;
1966      $sql.=" WHERE ".HISTORY_TABLE.".image_id NOT IN (SELECT id FROM ".IMAGES_TABLE.") and image_id > 0 ";
1967      $sql.=" GROUP BY image_id ORDER BY NbRecord";
1968      $result=pwg_query($sql);
1969
1970      if($result)
1971      {
1972        $returned[0]=0;
1973        while ($row = pwg_db_fetch_row($result))
1974        {
1975          $returned[2][$returned[0]][0] = $row[0];
1976          $returned[2][$returned[0]][1] = $row[1];
1977          $returned[0]++;
1978          $returned[1]+=$row[0];
1979        }
1980
1981      }
1982    }
1983    elseif($mode=='to0')
1984    {
1985      $sql="UPDATE ".HISTORY_TABLE."
1986        SET image_id = 0
1987        WHERE ".HISTORY_TABLE.".image_id > 0
1988          AND ".HISTORY_TABLE.".image_id NOT IN (SELECT id FROM ".IMAGES_TABLE.")";
1989      $result=pwg_query($sql);
1990
1991      if($result)
1992      {
1993        $returned[0]=1;
1994      }
1995    }
1996    return($returned);
1997  }
1998
1999
2000  /*
2001    tools : deleted_category
2002    analyse history to find deleted categories
2003    Two functions :
2004      - analyse : return infos
2005          * number of category
2006          * number of record in HISTORY_TABLE
2007          * catgories list
2008      - to0 : update categories ident to 0
2009  */
2010  private function tools_deleted_category($mode)
2011  {
2012    $returned = array(-1,0,'');
2013
2014    if($mode=='analyse')
2015    {
2016      $sql="SELECT count(id) as NbRecord, category_id ";
2017      $sql.=" FROM ".HISTORY_TABLE;
2018      $sql.=" WHERE ".HISTORY_TABLE.".category_id NOT IN (SELECT id FROM ".CATEGORIES_TABLE.") and category_id > 0";
2019      $sql.=" GROUP BY category_id ORDER BY NbRecord";
2020      $result=pwg_query($sql);
2021
2022      if($result)
2023      {
2024        $returned[0]=0;
2025        while ($row = pwg_db_fetch_row($result))
2026        {
2027          $returned[2][$returned[0]][0] = $row[0];
2028          $returned[2][$returned[0]][1] = $row[1];
2029          $returned[0]++;
2030          $returned[1]+=$row[0];
2031        }
2032
2033      }
2034    }
2035    elseif($mode=='to0')
2036    {
2037      $sql="UPDATE ".HISTORY_TABLE."
2038        SET category_id = NULL, section = 'deleted_cat'
2039        WHERE ".HISTORY_TABLE.".category_id > 0
2040          AND ".HISTORY_TABLE.".category_id NOT IN (SELECT id FROM ".CATEGORIES_TABLE.")";
2041      $result=pwg_query($sql);
2042
2043      if($result)
2044      {
2045        $returned[0]=1;
2046      }
2047    }
2048    return($returned);
2049  }
2050
2051
2052  /*
2053    tools : general_nfo
2054    return infos about historic
2055      0 : nulber of records
2056      1 : date of newest record
2057      2 : date of oldesr record
2058      3 : table size
2059      4 : index size
2060  */
2061  private function tools_general_nfo()
2062  {
2063    $returned = array(-1,'','',0,0);
2064
2065    $sql="SELECT count(id) AS NbRecord, MAX(concat(date,' ', time)) AS LastDate, MIN(concat(date,' ', time)) AS FirstDate ";
2066    $sql.=" FROM ".HISTORY_TABLE;
2067    $result=pwg_query($sql);
2068    if($result)
2069    {
2070      $row = pwg_db_fetch_row($result);
2071      if(is_array($row))
2072      {
2073        $returned = $row;
2074        $sql="SHOW TABLE STATUS LIKE '".HISTORY_TABLE."';";
2075        $result=pwg_query($sql);
2076        if($result)
2077        {
2078          $row2=pwg_db_fetch_assoc($result);
2079          array_push($returned, $row2['Data_length'], $row2['Index_length']);
2080        }
2081      }
2082    }
2083    return($returned);
2084  }
2085
2086
2087  /*
2088    tools : do_purge_history
2089    do a purge of history table :
2090    - $purgetype='bydate' : purge all record wich date is less than given date
2091    - $purgetype='byimageid0' : with and image_id = 0
2092  ------------------------------------------------------------------------------------ */
2093  private function do_purge_history($param, $purgetype)
2094  {
2095    if($purgetype=='bydate')
2096    {
2097      $sql="DELETE FROM ".HISTORY_TABLE." WHERE date < '$param'";
2098    }
2099    elseif($purgetype=='byimageid0')
2100    {
2101      $sql="DELETE FROM ".HISTORY_TABLE." WHERE image_id = 0";
2102    }
2103    elseif($purgetype=='bycategoryid0')
2104    {
2105      $sql="DELETE FROM ".HISTORY_TABLE." WHERE category_id is null and section='deleted_cat'";
2106    }
2107    elseif($purgetype=='byipid0')
2108    {
2109      $sql="DELETE FROM ".HISTORY_TABLE." WHERE ".$this->make_IP_where_clause($param);
2110    }
2111    else
2112    {
2113      return(false);
2114    }
2115
2116    $result=pwg_query($sql);
2117    if($result)
2118    {
2119      $sql="OPTIMIZE TABLE ".HISTORY_TABLE;
2120      $result=pwg_query($sql);
2121      return($result);
2122    }
2123    return(false);
2124  }
2125
2126  private function purge_history_count_imageid0()
2127  {
2128    $sql="SELECT COUNT(id) FROM ".HISTORY_TABLE." WHERE image_id = 0";
2129    $result=pwg_query($sql);
2130    if($result)
2131    {
2132      $row=pwg_db_fetch_row($result);
2133      return($row[0]);
2134    }
2135    return(0);
2136  }
2137
2138  private function purge_history_count_categoryid0()
2139  {
2140    $sql="SELECT COUNT(id) FROM ".HISTORY_TABLE." WHERE category_id is null and section = 'deleted_cat'" ;
2141    $result=pwg_query($sql);
2142    if($result)
2143    {
2144      $row=pwg_db_fetch_row($result);
2145      return($row[0]);
2146    }
2147    return(0);
2148  }
2149
2150  private function purge_history_count_ipid0()
2151  {
2152    if($this->config['AStat_BlackListedIP']!="")
2153    {
2154      $list=explode(',', $this->config['AStat_BlackListedIP']);
2155    }
2156    else
2157    {
2158      $list=array();
2159    }
2160
2161    $returned=array(0,count($list));
2162
2163    if($this->config['AStat_BlackListedIP']!='')
2164    {
2165      $sql="SELECT COUNT(id)
2166            FROM ".HISTORY_TABLE."
2167            WHERE ".$this->make_IP_where_clause($this->config['AStat_BlackListedIP']);
2168      $result=pwg_query($sql);
2169      if($result)
2170      {
2171        $row=pwg_db_fetch_row($result);
2172        $returned[0]=$row[0];
2173      }
2174    }
2175    return($returned);
2176  }
2177
2178
2179  /*
2180    tools : deleted_picture
2181    > verify_AStat_picture_table_status :
2182    > prepare_AStat_picture_table :
2183  */
2184  private function verify_AStat_picture_table_status()
2185  {
2186    global $prefixeTable;
2187
2188    $sql="SHOW TABLE STATUS LIKE '".$prefixeTable."AStat_picture'";
2189    $result=pwg_query($sql);
2190    if($result)
2191    {
2192      if(pwg_db_num_rows($result)==1)
2193      {
2194        return(true);
2195      }
2196    }
2197    return(false);
2198  }
2199
2200  private function prepare_AStat_picture_table()
2201  {
2202    global $prefixeTable;
2203
2204    $sql="CREATE TABLE ".$prefixeTable."AStat_picture (PRIMARY KEY (id), KEY ifile(file))
2205      SELECT id, file
2206      FROM ".IMAGES_TABLE;
2207    $result=pwg_query($sql);
2208    if($result)
2209    {
2210      return(true);
2211    }
2212    return(false);
2213  }
2214
2215  private function count_AStat_picture_table()
2216  {
2217    global $prefixeTable;
2218    $returned=array(false,0,0);
2219
2220    if($this->verify_AStat_picture_table_status())
2221    {
2222      $sql="SELECT count(DISTINCT ".$prefixeTable."AStat_picture.id), count(".HISTORY_TABLE.".id)
2223        FROM ".HISTORY_TABLE.", ".$prefixeTable."AStat_picture
2224        WHERE ".HISTORY_TABLE.".image_id = ".$prefixeTable."AStat_picture.id
2225        AND ".HISTORY_TABLE.".image_id NOT IN (SELECT id FROM ".IMAGES_TABLE.")
2226        ORDER BY ".$prefixeTable."AStat_picture.id";
2227      $result=pwg_query($sql);
2228      if($result)
2229      {
2230        if(pwg_db_num_rows($result)>0)
2231        {
2232          $row=pwg_db_fetch_row($result);
2233          $returned[0]=true;
2234          $returned[1]=$row[0];
2235          $returned[2]=$row[1];
2236        }
2237      }
2238    }
2239    return($returned);
2240  }
2241
2242  private function apply_AStat_picture_table()
2243  {
2244    global $prefixeTable;
2245    $returned=false;
2246
2247    $sql="CREATE TABLE ".$prefixeTable."AStat_picture2 (PRIMARY KEY (OldId))
2248      SELECT AStat_tmp.id as OldId , ".IMAGES_TABLE.".id as NewId, ".IMAGES_TABLE.".storage_category_id as NewCatId
2249      FROM (SELECT DISTINCT ".$prefixeTable."AStat_picture.*
2250        FROM ".HISTORY_TABLE.", ".$prefixeTable."AStat_picture
2251        WHERE ".HISTORY_TABLE.".image_id = ".$prefixeTable."AStat_picture.id
2252        AND ".HISTORY_TABLE.".image_id NOT IN (SELECT id FROM ".IMAGES_TABLE.")
2253        ORDER BY ".$prefixeTable."AStat_picture.id
2254      ) as AStat_tmp
2255      LEFT JOIN ".IMAGES_TABLE." ON AStat_tmp.file = ".IMAGES_TABLE.".file";
2256    $result=pwg_query($sql);
2257    if($result)
2258    {
2259      $sql="UPDATE ".HISTORY_TABLE.", ".$prefixeTable."AStat_picture2, ".IMAGES_TABLE."
2260        SET ".HISTORY_TABLE.".image_id = ".$prefixeTable."AStat_picture2.NewId,
2261            ".HISTORY_TABLE.".category_id = ".$prefixeTable."AStat_picture2.NewCatId
2262        WHERE ".$prefixeTable."AStat_picture2.OldId = ".HISTORY_TABLE.".image_id";
2263      $result=pwg_query($sql);
2264      if($result)
2265      {
2266        $returned=true;
2267      }
2268      $sql="DROP TABLE IF EXISTS ".$prefixeTable."AStat_picture2";
2269      $result=pwg_query($sql);
2270      $sql="DROP TABLE IF EXISTS ".$prefixeTable."AStat_picture";
2271      $result=pwg_query($sql);
2272    }
2273    return($returned);
2274  }
2275
2276
2277
2278
2279  /*
2280    generics functions
2281  */
2282
2283  /*
2284    this function make filter list and apply template
2285
2286      $selected : category_id of selected item ("" if none)
2287  */
2288  private function make_filter_list($selected="")
2289  {
2290    global $template;
2291
2292    $template_datarows_values=array();
2293    $template_datarows_labels=array();
2294    $template_hiddenrows=array();
2295
2296
2297    $template_datarows_values[]="";
2298    $template_datarows_labels[]=l10n("AStat_nofilter");
2299
2300    $sql="SELECT id, name, global_rank FROM ".CATEGORIES_TABLE." order by global_rank";
2301    $result = pwg_query($sql);
2302    if($result)
2303    {
2304      while ($row = pwg_db_fetch_assoc($result))
2305      {
2306        $text=str_repeat('&nbsp;&nbsp;', substr_count($row['global_rank'], '.'));
2307        $template_datarows_values[]=$row['id'];
2308        $template_datarows_labels[]=$text.$row['name'];
2309      }
2310    }
2311
2312    $query=explode('&', $_SERVER['QUERY_STRING']);
2313    foreach($query as $key => $value)
2314    {
2315      $nfo=explode('=', $value);
2316      $template_hiddenrows[]=array(
2317          'VALUE' => urldecode($nfo[1]),
2318          'NAME' => $nfo[0]
2319      );
2320    }
2321
2322    $template->assign('ASTAT_LINK', $_SERVER['SCRIPT_NAME']);
2323    $template->assign('f_AStat_catfilter_list_values', $template_datarows_values);
2324    $template->assign('f_AStat_catfilter_list_labels', $template_datarows_labels);
2325    $template->assign('f_AStat_catfilter_selected', $selected);
2326    $template->assign('f_AStat_parameters', $template_hiddenrows);
2327  } //make_filter_list
2328
2329
2330  /*
2331    this function make SELECT "WHERE" clause for filter list
2332
2333      $selected : category_id of selected item ("" if none)
2334  */
2335  private function make_where_clause($catfilter)
2336  {
2337    $returned=array();
2338    $sql="SELECT id, ".CATEGORIES_TABLE.".global_rank
2339          FROM ".CATEGORIES_TABLE.",
2340               (SELECT global_rank FROM ".CATEGORIES_TABLE." WHERE id = '".$catfilter."') as tmp1
2341          WHERE ".CATEGORIES_TABLE.".global_rank LIKE CONCAT(tmp1.global_rank, '%')
2342          ORDER BY ".CATEGORIES_TABLE.".global_rank";
2343    $result = pwg_query($sql);
2344
2345    if($result)
2346    {
2347      while ($row = pwg_db_fetch_row($result))
2348      {
2349        $returned[]=$row[0];
2350      }
2351    }
2352
2353    return(implode(',', $returned));
2354  }
2355
2356
2357  /*
2358    format text : <a href="$link">$value</a>
2359  */
2360  private function format_link($value, $link)
2361  {
2362    return("<a href='$link'>$value</a>");
2363  }
2364
2365  /*
2366    return true if IP adress is given
2367  */
2368  private function is_IP($ip)
2369  {  //basic test, maybe a pcre will be more appropriate...
2370    $tmp=explode('.', $ip);
2371    if(count($tmp)!=4)
2372    { return (false); }
2373
2374    for($i=0;$i<4;$i++)
2375    {
2376      if(!is_numeric($tmp[$i])) { return (false); }
2377    }
2378    return (true);
2379  }
2380
2381  /*
2382    change filename extension
2383  */
2384  private function change_file_ext($file, $newext)
2385  {  //filename can be <filename.truc.jpeg> for example
2386    $tmp = explode('.', $file);
2387    if(count($tmp)>1) { $tmp[count($tmp)-1] = $newext; }
2388    return implode('.', $tmp);
2389  }
2390
2391  /*
2392      format number $octets with unit
2393      $format = "A" : auto
2394                "O" : o
2395                "K" : Ko
2396                "M" : Mo
2397                "G" : Go
2398      $thsep = thousand separator
2399      $prec = number of decimal
2400      $unitevis = true/false > renvoi l'unité ou non dans le résultat
2401  */
2402  private function formatoctet($octets, $format="A", $thsep=" ", $prec=2, $unitevis=true)
2403  {
2404    if($format=="A")
2405    {
2406    if($octets<1024)
2407    { $format="O"; }
2408    elseif($octets<1024000)
2409    { $format="K"; }
2410    elseif($octets<1024000000)
2411    { $format="M"; }
2412    else
2413    { $format="G"; }
2414    }
2415    switch($format)
2416    {
2417    case "O":
2418      $unite="o"; $div=1;
2419      break;
2420    case "K":
2421      $unite="Ko"; $div=1024;
2422      break;
2423    case "M":
2424      $unite="Mo"; $div=1024000;
2425      break;
2426    case "G":
2427      $unite="Go"; $div=1024000000;
2428      break;
2429    }
2430
2431    $retour=number_format($octets/$div, $prec, '.', $thsep);
2432    if($unitevis)
2433    { $retour.=" ".$unite; }
2434    return($retour);
2435  }
2436
2437  private function make_IP_where_clause($list)
2438  {
2439    $returned="";
2440
2441    $tmp=explode(",", $list);
2442    foreach($tmp as $key=>$val)
2443    {
2444      if($returned!="") { $returned.=" OR "; }
2445      $returned.=" IP LIKE '".$val."' ";
2446    }
2447    if($returned!="")
2448    {
2449      $returned ="(".$returned.")";
2450    }
2451    return($returned);
2452  }
2453
2454
2455  /* ---------------------------------------------------------------------------
2456   * AJAX functions
2457   * ------------------------------------------------------------------------- */
2458  protected function ajax_listip($filter, $exclude)
2459  {
2460    $sql="SELECT IP, COUNT(id) as NbEvents FROM ".HISTORY_TABLE;
2461
2462    $where=array();
2463    if($filter!="")
2464    {
2465      $where[]=" IP LIKE '".$filter."' ";
2466    }
2467    if($exclude!="")
2468    {
2469      $where[]=" NOT ".$this->make_IP_where_clause($exclude);
2470    }
2471    if(count($where)>0)
2472    {
2473      $sql.=" WHERE ".implode(" AND ", $where);
2474    }
2475    $sql.=" GROUP BY IP ORDER BY NbEvents desc, IP asc LIMIT 0,100";
2476
2477    $list="<select multiple id='iipsellist'>";
2478    $result=pwg_query($sql);
2479    if($result)
2480    {
2481      while($row=pwg_db_fetch_assoc($result))
2482      {
2483        $list.="<option value='".$row['IP']."'>".$row['IP'].str_repeat("&nbsp;", 15-strlen($row['IP']))."&nbsp;&nbsp;&nbsp;&nbsp;(".$row['NbEvents'].")</option>";
2484      }
2485    }
2486    $list.="</select>";
2487
2488    return($list);
2489  }
2490
2491
2492} // AStat_AI class
2493
2494
2495?>
Note: See TracBrowser for help on using the repository browser.