source: extensions/EStat/estat_ajax.php @ 17737

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

First commit for EStat files

  • Property svn:executable set to *
File size: 78.1 KB
Line 
1<?php
2/*
3 * -----------------------------------------------------------------------------
4 * Plugin Name: EStat
5 * -----------------------------------------------------------------------------
6 * Author     : Grum
7 *   email    : grum@piwigo.org
8 *   website  : http://photos.grum.fr
9 *   PWG user : http://forum.piwigo.org/profile.php?id=3706
10 *
11 *   << May the Little SpaceFrog be with you ! >>
12 *
13 * -----------------------------------------------------------------------------
14 *
15 * See main.inc.php for release information
16 *
17 * manage all the ajax requests
18 * -----------------------------------------------------------------------------
19 */
20
21  // in this case, PHPWG_ROOT_PATH must be declared as an absolute path...
22  define('PHPWG_ROOT_PATH',dirname(dirname(dirname(__FILE__))).'/');
23  if(!defined('AJAX_CALL')) define('AJAX_CALL', true);
24
25  /*
26   * set ajax module in admin mode if request is used for admin interface
27   */
28  if(!isset($_REQUEST['ajaxfct'])) $_REQUEST['ajaxfct']='';
29  if(preg_match('/^admin\./i', $_REQUEST['ajaxfct'])) define('IN_ADMIN', true);
30
31  // the common.inc.php file loads all the main.inc.php plugins files
32  include_once(PHPWG_ROOT_PATH.'include/common.inc.php' );
33  include_once(PHPWG_PLUGINS_PATH.'GrumPluginClasses/classes/GPCAjax.class.inc.php');
34  include_once(PHPWG_PLUGINS_PATH.'GrumPluginClasses/classes/GPCUserAgent.class.inc.php');
35  include_once('estat_root.class.inc.php');
36
37  load_language('plugin.lang', ESTAT_PATH);
38
39
40  class EStat_Ajax extends EStat_root
41  {
42    const MAX_LOAD_LOG = 1000;
43
44    /**
45     * constructor
46     */
47    public function __construct($prefixeTable, $filelocation)
48    {
49      parent::__construct($prefixeTable, $filelocation);
50      $this->loadConfig();
51      $this->checkRequest();
52      $this->returnAjaxContent();
53    }
54
55    /**
56     * check the $_REQUEST values and set default values
57     *
58     */
59    protected function checkRequest()
60    {
61      global $user;
62
63      if(!isset($_REQUEST['errcode'])) $_REQUEST['errcode']='';
64      GPCAjax::checkToken();
65
66      // check if asked function is valid
67      if(!($_REQUEST[GPC_AJAX]=='admin.install.buildIpList' or
68           $_REQUEST[GPC_AJAX]=='admin.migrate.loadLogs' or
69           $_REQUEST[GPC_AJAX]=='admin.migrate.consolidate' or
70           $_REQUEST[GPC_AJAX]=='admin.migrate.finalize' or
71           $_REQUEST[GPC_AJAX]=='admin.stat.periodTreeList' or
72           $_REQUEST[GPC_AJAX]=='admin.stat.history.periodList' or
73           $_REQUEST[GPC_AJAX]=='admin.stat.history' or
74           $_REQUEST[GPC_AJAX]=='admin.stat.history.graphAllPeriods' or
75           $_REQUEST[GPC_AJAX]=='admin.stat.history.graphCurrentPeriod' or
76           $_REQUEST[GPC_AJAX]=='admin.stat.period' or
77           $_REQUEST[GPC_AJAX]=='admin.stat.period.graph' or
78           $_REQUEST[GPC_AJAX]=='admin.stat.ip' or
79           $_REQUEST[GPC_AJAX]=='admin.stat.ip.graphType' or
80           $_REQUEST[GPC_AJAX]=='admin.stat.ip.graphCountry' or
81           $_REQUEST[GPC_AJAX]=='admin.stat.category' or
82           $_REQUEST[GPC_AJAX]=='admin.stat.image' or
83           $_REQUEST[GPC_AJAX]=='admin.fct.validValues'
84           )) $_REQUEST[GPC_AJAX]='';
85
86      if(preg_match('/^admin\./i', $_REQUEST['ajaxfct']) and !is_admin()) $_REQUEST['ajaxfct']='';
87
88      if($_REQUEST[GPC_AJAX]!='')
89      {
90        switch($_REQUEST[GPC_AJAX])
91        {
92          case 'admin.install.buildIpList':
93            if(!isset($_REQUEST['start'])) $_REQUEST['ajaxfct']='';
94            break;
95          case 'admin.migrate.loadLogs':
96            if(!isset($_REQUEST['lastId'])) $_REQUEST['lastId']=0;
97            if(!isset($_REQUEST['period'])) $_REQUEST['period']='';
98
99            if(!is_numeric($_REQUEST['lastId']) or
100               $_REQUEST['period']=='' or
101               !preg_match('/\\d{4}-\\d{2}/i', $_REQUEST['period'])) $_REQUEST['ajaxfct']='';
102            break;
103          case 'admin.migrate.consolidate':
104            if(!isset($_REQUEST['period'])) $_REQUEST['period']='';
105            if(!isset($_REQUEST['process'])) $_REQUEST['process']=0;
106
107            if(!is_numeric($_REQUEST['process']) or
108               $_REQUEST['period']=='' or
109               !preg_match('/\\d{4}-\\d{2}/i', $_REQUEST['period'])) $_REQUEST['ajaxfct']='';
110            break;
111          case 'admin.migrate.finalize':
112            break;
113          case 'admin.stat.history.periodList':
114            break;
115          case 'admin.stat.periodTreeList':
116            break;
117          case 'admin.stat.history':
118            if(!isset($_REQUEST['period'])) $_REQUEST['period']='';
119            if(!isset($_REQUEST['currentPage'])) $_REQUEST['currentPage']=0;
120            if(!isset($_REQUEST['nbItemsPage'])) $_REQUEST['nbItemsPage']=0;
121
122            if(!isset($_REQUEST['sort']))
123                $_REQUEST['sort']=array(
124                    array('direction' => 'A', 'id' => 'date')
125                );
126
127            if(!isset($_REQUEST['filter'])) $_REQUEST['filter']=array();
128
129            if(!is_numeric($_REQUEST['currentPage']) or $_REQUEST['currentPage']<0) $_REQUEST['currentPage']=0;
130            if(!is_numeric($_REQUEST['nbItemsPage']) or $_REQUEST['nbItemsPage']<0) $_REQUEST['nbItemsPage']=50;
131
132            if($_REQUEST['period']=='') $_REQUEST['ajaxfct']='';
133            break;
134          case 'admin.stat.history.graphCurrentPeriod':
135            if(!isset($_REQUEST['period'])) $_REQUEST['period']='';
136            if($_REQUEST['period']=='') $_REQUEST['ajaxfct']='';
137            break;
138          case 'admin.stat.history.graphAllPeriods':
139            if(!isset($_REQUEST['period'])) $_REQUEST['period']='';
140            if(!isset($_REQUEST['nbMonth'])) $_REQUEST['nbMonth']=0;
141            break;
142          case 'admin.stat.period':
143            if(!isset($_REQUEST['period'])) $_REQUEST['period']='';
144            if(!isset($_REQUEST['currentPage'])) $_REQUEST['currentPage']=0;
145            if(!isset($_REQUEST['nbItemsPage'])) $_REQUEST['nbItemsPage']=0;
146
147            if(!isset($_REQUEST['sort']))
148                $_REQUEST['sort']=array(
149                    array('direction' => 'A', 'id' => 'year'),
150                    array('direction' => 'A', 'id' => 'month')
151                );
152
153            if(!isset($_REQUEST['additionalFilter'])) $_REQUEST['additionalFilter']=array();
154
155            if(!is_numeric($_REQUEST['currentPage']) or $_REQUEST['currentPage']<0) $_REQUEST['currentPage']=0;
156            if(!is_numeric($_REQUEST['nbItemsPage']) or $_REQUEST['nbItemsPage']<0) $_REQUEST['nbItemsPage']=50;
157
158            if($_REQUEST['period']=='') $_REQUEST['ajaxfct']='';
159            $_REQUEST['filter']=$_REQUEST['additionalFilter'];
160            break;
161          case 'admin.stat.period.graph':
162            if(!isset($_REQUEST['period'])) $_REQUEST['period']='';
163
164            if(!isset($_REQUEST['additionalFilter'])) $_REQUEST['additionalFilter']=array();
165
166            if($_REQUEST['period']=='') $_REQUEST['ajaxfct']='';
167            $_REQUEST['filter']=$_REQUEST['additionalFilter'];
168            break;
169          case 'admin.stat.ip':
170            if(!isset($_REQUEST['period'])) $_REQUEST['period']='a';
171            if(!isset($_REQUEST['currentPage'])) $_REQUEST['currentPage']=0;
172            if(!isset($_REQUEST['nbItemsPage'])) $_REQUEST['nbItemsPage']=0;
173
174            if(!isset($_REQUEST['group'])) $_REQUEST['group']=array();
175
176            if(!isset($_REQUEST['sort']))
177                $_REQUEST['sort']=array(
178                    array('direction' => 'A', 'id' => 'ip')
179                );
180
181            if(!isset($_REQUEST['additionalFilter'])) $_REQUEST['additionalFilter']=array();
182            if(!isset($_REQUEST['filter'])) $_REQUEST['filter']=array();
183
184            if(!is_numeric($_REQUEST['currentPage']) or $_REQUEST['currentPage']<0) $_REQUEST['currentPage']=0;
185            if(!is_numeric($_REQUEST['nbItemsPage']) or $_REQUEST['nbItemsPage']<0) $_REQUEST['nbItemsPage']=50;
186
187            if($_REQUEST['period']=='') $_REQUEST['ajaxfct']='';
188            $_REQUEST['filter']['additionalFilter']=$_REQUEST['additionalFilter'];
189            break;
190          case 'admin.stat.ip.graphType':
191            if(!isset($_REQUEST['period'])) $_REQUEST['period']='a';
192
193            if(!isset($_REQUEST['additionalFilter'])) $_REQUEST['additionalFilter']=array();
194
195            if($_REQUEST['period']=='') $_REQUEST['ajaxfct']='';
196            $_REQUEST['filter']=$_REQUEST['additionalFilter'];
197            break;
198          case 'admin.stat.ip.graphCountry':
199            if(!isset($_REQUEST['period'])) $_REQUEST['period']='a';
200
201            if(!isset($_REQUEST['additionalFilter'])) $_REQUEST['additionalFilter']=array();
202
203            if($_REQUEST['period']=='') $_REQUEST['ajaxfct']='';
204            $_REQUEST['filter']=$_REQUEST['additionalFilter'];
205            break;
206          case 'admin.stat.category':
207          case 'admin.stat.image':
208            if(!isset($_REQUEST['period'])) $_REQUEST['period']='a';
209            if(!isset($_REQUEST['currentPage'])) $_REQUEST['currentPage']=0;
210            if(!isset($_REQUEST['nbItemsPage'])) $_REQUEST['nbItemsPage']=0;
211
212            if(!isset($_REQUEST['group'])) $_REQUEST['group']=array();
213
214            if(!isset($_REQUEST['sort']))
215                $_REQUEST['sort']=array(
216                    array('direction' => 'A', 'id' => 'nbVisits')
217                );
218
219            if(!isset($_REQUEST['additionalFilter'])) $_REQUEST['additionalFilter']=array();
220            if(!isset($_REQUEST['filter'])) $_REQUEST['filter']=array();
221
222            if(!is_numeric($_REQUEST['currentPage']) or $_REQUEST['currentPage']<0) $_REQUEST['currentPage']=0;
223            if(!is_numeric($_REQUEST['nbItemsPage']) or $_REQUEST['nbItemsPage']<0) $_REQUEST['nbItemsPage']=50;
224
225            if($_REQUEST['period']=='') $_REQUEST['ajaxfct']='';
226            $_REQUEST['filter']['additionalFilter']=$_REQUEST['additionalFilter'];
227            break;
228          case 'admin.fct.validValues':
229            if(!isset($_REQUEST['domain'])) $_REQUEST['domain']='';
230            if(!isset($_REQUEST['filter'])) $_REQUEST['filter']='';
231
232            if(!($_REQUEST['domain']=='uaBrowser' or
233                 $_REQUEST['domain']=='uaEngine' or
234                 $_REQUEST['domain']=='uaOS' or
235                 $_REQUEST['domain']=='uaType' or
236                 $_REQUEST['domain']=='country'))
237              $_REQUEST[GPC_AJAX]='';
238            break;
239          default:
240            $_REQUEST[GPC_AJAX]='';
241            break;
242        }
243
244      }
245    } //checkRequest
246
247
248    /**
249     * return ajax content
250     */
251    protected function returnAjaxContent()
252    {
253      $result="<p class='errors'>An error has occured [".$_REQUEST[GPC_AJAX]."]</p>";
254      switch($_REQUEST[GPC_AJAX])
255      {
256        case 'admin.install.buildIpList':
257          $result=$this->ajax_estat_admin_installBuildIpList($_REQUEST['start']);
258          break;
259        case 'admin.migrate.loadLogs':
260          $result=$this->ajax_estat_admin_migrateLoadLogs($_REQUEST['period'], $_REQUEST['lastId']);
261          break;
262        case 'admin.migrate.consolidate':
263          $result=$this->ajax_estat_admin_migrateConsolidate($_REQUEST['period'], $_REQUEST['process']);
264          break;
265        case 'admin.migrate.finalize':
266          $result=$this->ajax_estat_admin_migrateFinalize();
267          break;
268        case 'admin.stat.history':
269          $result=$this->ajax_estat_admin_statHistory($_REQUEST['period'], $_REQUEST['filter'], $_REQUEST['sort'], $_REQUEST['currentPage'], $_REQUEST['nbItemsPage']);
270          break;
271        case 'admin.stat.history.graphCurrentPeriod':
272          $result=$this->ajax_estat_admin_statHistoryGraphCurrentPeriod($_REQUEST['period']);
273          break;
274        case 'admin.stat.history.graphAllPeriods':
275          $result=$this->ajax_estat_admin_statHistoryVisitsAllPeriods($_REQUEST['period'], $_REQUEST['nbMonth']);
276          break;
277        case 'admin.stat.period':
278          $result=$this->ajax_estat_admin_statPeriod($_REQUEST['period'], $_REQUEST['filter'], $_REQUEST['sort'], $_REQUEST['currentPage'], $_REQUEST['nbItemsPage']);
279          break;
280        case 'admin.stat.period.graph':
281          $result=$this->ajax_estat_admin_statPeriodGraph($_REQUEST['period'], $_REQUEST['filter']);
282          break;
283        case 'admin.stat.ip':
284          $result=$this->ajax_estat_admin_statIP($_REQUEST['period'], $_REQUEST['filter'], $_REQUEST['sort'], $_REQUEST['group'], $_REQUEST['currentPage'], $_REQUEST['nbItemsPage']);
285          break;
286        case 'admin.stat.ip.graphType':
287          $result=$this->ajax_estat_admin_statIPGraphType($_REQUEST['period'], $_REQUEST['filter']);
288          break;
289        case 'admin.stat.ip.graphCountry':
290          $result=$this->ajax_estat_admin_statIPGraphCountry($_REQUEST['period'], $_REQUEST['filter']);
291          break;
292        case 'admin.stat.category':
293          $result=$this->ajax_estat_admin_statCategory($_REQUEST['period'], $_REQUEST['filter'], $_REQUEST['sort'], $_REQUEST['group'], $_REQUEST['currentPage'], $_REQUEST['nbItemsPage']);
294          break;
295        case 'admin.stat.image':
296          $result=$this->ajax_estat_admin_statImage($_REQUEST['period'], $_REQUEST['filter'], $_REQUEST['sort'], $_REQUEST['group'], $_REQUEST['currentPage'], $_REQUEST['nbItemsPage']);
297          break;
298
299//revoir les id des fonctions
300        case 'admin.stat.history.periodList':
301          $result=$this->ajax_estat_admin_statHistoryPeriodList();
302          break;
303        case 'admin.stat.periodTreeList':
304          $result=$this->ajax_estat_admin_statPeriodTreeList();
305          break;
306        case 'admin.fct.validValues':
307          $result=$this->ajax_estat_admin_fctValidValues($_REQUEST['domain'], $_REQUEST['filter']);
308          break;
309      }
310      GPCAjax::returnResult($result);
311    }
312
313
314    /*------------------------------------------------------------------------*
315     *
316     * ADMIN FUNCTIONS
317     *
318     *----------------------------------------------------------------------- */
319
320    /**
321     * import IP country file process
322     *
323     * return an array of informations
324     *  'nb'      => nb IP range processed for this call
325     *  'nbTotal' => nb total of IP range processed from the begining
326     *
327     * @param Integer start: IP range start load
328     * @return Array
329     */
330    protected function ajax_estat_admin_installBuildIpList($start)
331    {
332      $returned=array(
333        'nb' => 0,
334        'nbTotal' => 0
335      );
336
337      $dbCountry=new StatDBCountry($this->fileStatDir, self::FILE_COUNTRY);
338      if($dbCountry->open(ASDF_OPEN_WRITE))
339      {
340        $returned['nb']=$dbCountry->loadIpFile(ESTAT_PATH.'data/ipCountry.bin', $start, 5000);
341        $returned['nbTotal']=$dbCountry->getInfoProperty('nfo', 'numberOfIP');
342        $dbCountry->close();
343      }
344      return(json_encode($returned));
345    }
346
347
348
349    /**
350     * Migration process: import data from the history table
351     *
352     * @param String $period : period to be imported 'YYYY-MM'
353     * @param Longint $lastId : id to start
354     * @return String : an array in json format
355     *                    'lastId' => (Integer) the last Id processed in the history table
356     *                    'nbLogs' => (Integer) number of logs processed
357     */
358    protected function ajax_estat_admin_migrateLoadLogs($period, $lastId)
359    {
360      if(substr($period,5)>'12' or substr($period,5)<'01') return(-1);
361      $year=substr($period, 0,4);
362      $month=substr($period, 5);
363
364      $sql="SELECT id, date, time, user_id, IP, section, category_id, tag_ids, image_id, image_type
365            FROM ".HISTORY_TABLE."
366            WHERE id > $lastId
367              AND YEAR(`date`) = $year
368              AND MONTH(`date`) = $month
369            ORDER BY id
370            LIMIT 0,".self::MAX_LOAD_LOG;
371
372      $nbLogs=0;
373      $lastId=0;
374
375      $result=pwg_query($sql);
376      if($result)
377      {
378        // define file stat for the year/month period, open it ans start transaction
379        $monthStatFile=new StatDBMonth($this->fileStatDir, self::FILE_MONTH);
380        $monthStatFile->setPeriod($year, $month);
381        $monthStatFile->open(ASDF_OPEN_WRITE);
382        $monthStatFile->startTransac();
383
384        if($monthStatFile->getInfoProperty('log', 'startImport')==null)
385          $monthStatFile->setInfoProperty('log', 'startImport', date('Y-m-d H:i:s'));
386
387        // try to define from reverse DNS if IP is a crawler or not
388        $ipList=new ReverseIP();
389        //$ipList->loadIPFile($this->fileStatDir.'tmpIpFile.dat');
390
391        // build list of data to import
392        $list=array();      // items from history
393        $break=false;
394        while(!$break and $tmp=pwg_db_fetch_assoc($result))
395        {
396          if(substr($tmp['date'],0,7)==$period)
397          {
398            $list[]=$tmp;
399            $nbLogs++;
400            $lastId=$tmp['id'];
401
402            if($ipList->getIP($tmp['IP'])==-1)
403              $ipList->addIP($tmp['IP']);
404          }
405          else $break=true;
406        }
407
408        //$ipList->saveIPFile();
409
410
411        foreach($list as $val)
412        {
413          $uaType=$ipList->getIP($val['IP']);
414
415
416
417          $log=array(
418            'date' => strtotime($val['date']." ".$val['time']),
419            'IPadress' => $val['IP'],
420            'userId' => $val['user_id'],
421            'catId'  => $val['category_id'],
422            'imageId'  => ($val['image_id']!=null)?$val['image_id']:0,
423            'tagsId' => $val['tag_ids'],
424            'section' => $val['section'],
425
426            'userAgent' => '',
427            'uaBrowser' => ($uaType==UA_BROWSER_TYPE_CRAWLER)?UA_BOT_UNKNOWN:UA_BROWSER_UNKNOWN,
428            'uaBrowserVersion' => '',
429            'uaEngine' => UA_ENGINE_UNKNOWN,
430            'uaEngineVersion' => '',
431            'uaOS' => UA_OS_UNKNOWN,
432            'uaOSVersion' => '',
433            'uaType' => $uaType
434          );
435          $monthStatFile->addLog($log);
436        }
437
438
439        $monthStatFile->setInfoProperty('log', 'stopImport', date('Y-m-d H:i:s'));
440
441        // commit changes and close the file
442        $monthStatFile->stopTransac();
443        $monthStatFile->close();
444
445        // if imported data are from a previous period, pack it
446        if($nbLogs<self::MAX_LOAD_LOG and $period!=date('Y-m'))
447        {
448          /*if($monthStatFile->pack()===true)
449            $monthStatFile->delete(ASDF_DELETE_UNPACKED);*/
450        }
451      }
452
453      return(
454        json_encode(
455          Array(
456            'lastId' => $lastId,
457            'nbLogs' => $nbLogs
458          )
459        )
460      );
461    }
462
463
464    /**
465     * Migration process: consolidate logs on Global file
466     *
467     * @param String $period : period to consolidate (YYYY-MM)
468     * @param Integer $process : step
469     */
470    protected function ajax_estat_admin_migrateConsolidate($period, $process)
471    {
472      if(substr($period,5)>'12' or substr($period,5)<'01') return(-1);
473      $year=substr($period, 0,4);
474      $month=substr($period, 5);
475
476      $gStatFile=new StatDBGlobal($this->fileStatDir, self::FILE_GLOBAL);
477      $gStatFile->setIpCountryFile(ESTAT_PATH.'data/ipCountry.db');
478      $gStatFile->open(ASDF_OPEN_WRITE);
479      if($gStatFile->getInfoProperty('log', 'startImport')==null)
480        $gStatFile->setInfoProperty('log', 'startImport', date('Y-m-d H:i:s'));
481      $gStatFile->buildStatPeriod($this->fileStatDir, self::FILE_MONTH, $year, $month);
482      $gStatFile->setInfoProperty('log', 'stopImport', date('Y-m-d H:i:s'));
483      $gStatFile->close();
484
485      return('Y');
486    }
487
488    /**
489     * Migration process: finalize the migration
490     */
491    protected function ajax_estat_admin_migrateFinalize()
492    {
493      $this->config['plugin.newInstall']='n';
494      $this->saveConfig();
495      return('Y');
496    }
497
498
499    /**
500     * Return a list of available history periods
501     * @return String : an array in json format
502     *                  'value' => (String) the period in 'YYYY-MM' format
503     *                  'cols'  => (Array)
504     *                                (String) FileName prefix
505     *                                (String) Number of events in log file
506     */
507    protected function ajax_estat_admin_statHistoryPeriodList()
508    {
509      global $lang;
510
511      $returned=array();
512
513      $gStatFile=new StatDBGlobal($this->fileStatDir, self::FILE_GLOBAL);
514      $gStatFile->open(ASDF_OPEN_READ);
515      $files=$gStatFile->getFilesList();
516      $gStatFile->close();
517
518      foreach($files as $file)
519      {
520        $returned[]=array(
521          'value' => sprintf('%04d%02d', $file['year'], $file['month']),
522          'cols' => array(
523                      $lang['month'][$file['month']].' '.$file['year'],
524                      $file['logs'].' '.l10n('estat_events')
525                    )
526        );
527      }
528
529      return(json_encode($returned));
530    }
531
532    /**
533     * return the logs events from a period
534     *
535     * @param String $period : the period to be processed 'YYYYMM'
536     * @param Array  $filter : filter options
537     * @param Integer $pageNumber : page number to return
538     * @return String : an array in json format
539     *                    (Array) events properties
540     *                      'date' => (String) date time in 'YYYY-MM-DD HH:II:SS' format
541     *                      'IpUserId' => (String) IP or user login
542     *                      'country' => (String) country code (ISO 3366-1)
543     *                      'catId' => (String) name of the album
544     *                      'imageId' => (String) name of image
545     *                      'tags' => (String) tags list
546     *                      'section' => (String) section name
547     *                      'uaEngine' => (String) browser: engine+version
548     *                      'uaBrowser' => (String) browser name+version
549     *                      'uaOS' => (String) browser os: name+version
550     *                      'uaType' => (String) browser type: name
551     *                      'userAgent' => (String) user agent string
552     */
553    protected function ajax_estat_admin_statHistory($period, $filterPost, $sort, $pageNumber, $nbItemsPage)
554    {
555      $year=substr($period,0,4);
556      $month=substr($period,4,2);
557
558      $filter=array();
559      foreach($filterPost as $val)
560      {
561        $filter[$val['id']]=$val;
562      }
563
564      // open db file for the period
565      $monthStatFile=new StatDBMonth($this->fileStatDir, self::FILE_MONTH);
566      $monthStatFile->setPeriod($year, $month);
567      $monthStatFile->open(ASDF_OPEN_READ);
568
569      // get history & total number of items
570      $returned=array(
571        'rows' => $monthStatFile->getLogs(ASDF_GET_ROWS, $pageNumber, $nbItemsPage, $filter, $sort),
572        'nbItems' => $monthStatFile->getLogs(ASDF_GET_COUNT, 0, 0, $filter, $sort)
573      );
574      $monthStatFile->close();
575
576      // prepare an EStat_IdList to buid a list of unique Id
577      $idList=new EStat_IdList(array('catId', 'imageId', 'tagsId', 'userId', 'IPadress'));
578      // $idAssoc will get the label associated to the id
579      $idAssoc=array(
580        'catId'=>array(),
581        'imageId'=>array(),
582        'tagsId'=>array(),
583        'userId'=>array(),
584        'IPadress'=>array()
585      );
586
587      // build list of unique Id
588      foreach($returned['rows'] as $row)
589      {
590        $idList->addItems(
591          array(
592            'catId' => $row['catId'],
593            'imageId' => $row['imageId'],
594            'tagsId' => $row['tagsId'],
595            'userId' => $row['userId'],
596            'IPadress' => $row['IPadress']
597          )
598        );
599      }
600
601
602      if(count($idList->getItems('catId')) > 0)
603        $this->prepareIdList($idAssoc, 'catId', "SELECT id, name FROM ".CATEGORIES_TABLE." WHERE id IN (".implode(',', $idList->getItems('catId')).") ORDER BY id;");
604
605      if(count($idList->getItems('imageId')) > 0)
606        $this->prepareIdList($idAssoc, 'imageId', "SELECT id, file AS name, path FROM ".IMAGES_TABLE." WHERE id IN (".implode(',', $idList->getItems('imageId')).") ORDER BY id;");
607
608      if(count($idList->getItems('tagsId')) > 0)
609        $this->prepareIdList($idAssoc, 'tagsId', "SELECT id, name FROM ".TAGS_TABLE." WHERE id IN (".implode(',', $idList->getItems('tagsId')).") ORDER BY id;");
610
611      if(count($idList->getItems('userId')) > 0)
612        $this->prepareIdList($idAssoc, 'userId', "SELECT id, username AS name FROM ".USERS_TABLE." WHERE id IN (".implode(',', $idList->getItems('userId')).") ORDER BY id;");
613
614      // for reverse DNS
615      if($this->config['logs.ipCountry']=='y')
616        $this->getIpInfos($idAssoc, $idList->getItems('IPadress'));
617
618      // complete the data
619      foreach($returned['rows'] as $key=>$row)
620      {
621        $userAgentNfo=GPCUserAgent::getProperties(
622            array(
623              UA_DATA_BROWSER => $row['uaBrowser'],
624              UA_DATA_BROWSER_TYPE => $row['uaType'],
625              UA_DATA_OS => $row['uaOS'],
626              UA_DATA_ENGINE => $row['uaEngine']
627            )
628          );
629
630        if($userAgentNfo[UA_DATA_ENGINE_NAME]=='Unknown') $userAgentNfo[UA_DATA_ENGINE_NAME]='ua_Unknown';
631        if($userAgentNfo[UA_DATA_BROWSER_NAME]=='Unknown') $userAgentNfo[UA_DATA_BROWSER_NAME]='ua_Unknown';
632        if($userAgentNfo[UA_DATA_OS_NAME]=='Unknown') $userAgentNfo[UA_DATA_OS_NAME]='ua_Unknown';
633
634        //$userAgent = UserAgent::parse($row['userAgent']);
635        $tmp=array(
636          'date' => date('Y-m-d H:i:s', $row['date']),
637          'IpUserId' => ($row['userId']==2)?$row['IPadress']:$this->getId($idAssoc, 'userId', $row['userId'], $row['IPadress'], 'name'),
638          //'country' => $row['country'],
639          'catId' => GPCCore::getUserLanguageDesc($this->getId($idAssoc, 'catId', $row['catId'], ($row['catId']==0)?'-':'?')),
640          'imageId' => $this->getId($idAssoc, 'imageId', $row['imageId'], ($row['imageId']==0)?'-':'?', 'name'),
641          'tags'  => $this->getId($idAssoc, 'tagsId', $row['tagsId'], '', 'name'),
642          'section' => l10n($row['section']),
643          'uaEngine' => l10n($userAgentNfo[UA_DATA_ENGINE_NAME]),
644          'uaBrowser' => l10n($userAgentNfo[UA_DATA_BROWSER_NAME]),
645          'uaOS' => l10n($userAgentNfo[UA_DATA_OS_NAME]),
646          'uaType' => l10n('ua_'.$userAgentNfo[UA_DATA_BROWSER_TYPE_NAME]),
647          'userAgent' => $row['userAgent']
648        );
649
650
651        if($userAgentNfo[UA_DATA_BROWSER_URL]!='')
652          $tmp['uaBrowser']='<a href="'.$userAgentNfo[UA_DATA_BROWSER_URL].'">'.$tmp['uaBrowser'].'</a>';
653
654        if($row['uaBrowserVersion']!='')
655          $tmp['uaBrowser'].=' <span class="version">'.$row['uaBrowserVersion'].'</span>';
656
657
658        if($userAgentNfo[UA_DATA_OS_URL]!='')
659          $tmp['uaOS']='<a href="'.$userAgentNfo[UA_DATA_OS_URL].'">'.$tmp['uaOS'].'</a>';
660
661        if($row['uaOSVersion']!='')
662          $tmp['uaOS'].=' <span class="version">'.$row['uaOSVersion'].'</span>';
663
664        if($userAgentNfo[UA_DATA_ENGINE_URL]!='')
665          $tmp['uaEngine']='<a href="'.$userAgentNfo[UA_DATA_ENGINE_URL].'">'.$tmp['uaEngine'].'</a>';
666
667        if($row['uaEngineVersion']!='')
668          $tmp['uaEngine'].=' <span class="version">'.$row['uaEngineVersion'].'</span>';
669
670        switch($tmp['catId'])
671        {
672          case '-':
673            break;
674          case '?':
675            $tmp['catId']=l10n('estat_unknown').'['.$row['catId'].']';
676            break;
677          default:
678            $tmp['catId']='<a href="'.GPCCore::urlBuild('admin.category', array('categoryId'=>$row['catId'])).'">'.$tmp['catId'].'</a>';
679            break;
680        }
681
682        $tmp['thumb']='';
683        switch($tmp['imageId'])
684        {
685          case '-':
686            break;
687          case '?':
688            $tmp['imageId']=l10n('estat_unknown').'['.$row['imageId'].']';
689            break;
690          default:
691            $tmp['imageId']='<a href="'.GPCCore::urlBuild('admin.picture', array('pictureId'=>$row['imageId'])).'">'.$tmp['imageId'].'</a>';
692            $imageNfo = new SrcImage(
693                          array(
694                            'id'=>$row['imageId'],
695                            'path'=>$this->getId($idAssoc, 'imageId', $row['imageId'], '', 'path')
696                          )
697                        );
698            $tmp['thumb']='./'.substr(DerivativeImage::url(IMG_THUMB, $imageNfo),strlen(PHPWG_ROOT_PATH));
699            break;
700        }
701
702        if($row['userId']==2)
703        {
704          $ipInfo=$this->getId($idAssoc, 'IPadress', $tmp['IpUserId'], '?');
705          if($this->config['logs.reverseDNS']=='y')
706          {/*
707            $reverseIp=$this->getId($idAssoc, 'IPadress', $tmp['IpUserId'], '?');
708            if($reverseIp!='?' and $reverseIp!='' and $reverseIp!=$tmp['IpUserId'])
709            {
710              $reverseIp=' ('.$reverseIp.')';
711            }
712            else
713            {
714              $reverseIp='';
715            }*/
716          }
717
718          if($ipInfo['country']!='--' and $ipInfo['country']!='XA')
719          {
720            $tmp['IpUserId'].='<span class="geoip">[<a href="http://www.geoiptool.com/fr/?IP='.$tmp['IpUserId'].'">'.$ipInfo['country'].'</a>]</span>';
721          }
722          else
723          {
724            //$tmp['IpUserId'].='<span class="geoip">[--]</span>';
725          }
726
727        }
728
729        $returned['rows'][$key]=array(
730          $tmp['date'],
731          $tmp['IpUserId'],
732          $tmp['catId'],
733          $tmp['imageId'],
734          $tmp['tags'],
735          $tmp['section'],
736          $tmp['uaBrowser'],
737          $tmp['uaEngine'],
738          $tmp['uaOS'],
739          $tmp['uaType'],
740          $tmp['userAgent'],
741          $tmp['thumb']
742        );
743      }
744      return(json_encode($returned));
745    }
746
747
748
749    /**
750     * return the number of logs events per day for the period
751     *
752     * @param String $period: period in 'YYYYMM' format
753     * @return String : an array in json format
754     *                    (Array)
755     *                      'axis' => (Array)  period as a formatted string
756     *                      'series' => (Array) serie values
757     *                      'maxValue' => (Integer) maximum value found on all series
758     */
759    protected function ajax_estat_admin_statHistoryGraphCurrentPeriod($period)
760    {
761      global $lang;
762
763      $returned=array(
764        'maxValue' => 0,
765        'axis' => array(),
766        'series' => array(
767                      'total'    => array(
768                                      'name' => l10n('estat_total'),
769                                      'nbVisits' => array()
770                                    ),
771                      'computer' => array(
772                                      'name' => l10n('ua_Computer'),
773                                      'nbVisits' => array()
774                                    ),
775                      'mobile'   => array(
776                                      'name' => l10n('ua_Mobile'),
777                                      'nbVisits' => array()
778                                    ),
779                      'crawler'  => array(
780                                      'name' => l10n('ua_Crawler'),
781                                      'nbVisits' => array()
782                                    ),
783                      'other' => array(
784                                      'name' => l10n('ua_Other'),
785                                      'nbVisits' => array()
786                                    )
787                    )
788      );
789
790      $year=substr($period, 0 ,4);
791      $month=substr($period, 4, 2);
792
793      // open db file for the period
794      $mStatFile=new StatDBMonth($this->fileStatDir, self::FILE_MONTH);
795      $mStatFile->setPeriod($year, $month);
796      $mStatFile->open(ASDF_OPEN_READ);
797
798      // get number of visits per type of user agent (mobile, computer, crawler, ...)
799      $data=$mStatFile->getStatUserAgent(ASDF_GET_ROWS, 0, 0,
800                                          array('day', 'uaValue'),
801                                          array('uaData' => array('operator'=>'=', 'value'=>UA_DATA_BROWSER_TYPE)),
802                                          array(
803                                            array('id'=>'day',  'direction'=>'A')
804                                          )
805                                        );
806      $mStatFile->close();
807
808      // nb of days for the period
809      $nbDay=$mStatFile->getNbDays();
810
811      // prepare data
812      $axis=array();
813      $series=array(
814          'total' => array(),
815          'computer' => array(),
816          'mobile' => array(),
817          'crawler' => array(),
818          'other' => array()
819        );
820
821      for($i=1;$i<=$nbDay;$i++)
822      {
823        $returned['axis'][]=$i;
824        $series['total'][$i]=0;
825        $series['computer'][$i]=0;
826        $series['mobile'][$i]=0;
827        $series['crawler'][$i]=0;
828        $series['other'][$i]=0;
829      }
830
831      foreach($data as $value)
832      {
833        $series['total'][$value['day']]+=$value['nbVisits'];
834        if($returned['maxValue']<$series['total'][$value['day']]) $returned['maxValue']=$series['total'][$value['day']];
835
836        switch($value['uaValue'])
837        {
838          case UA_BROWSER_TYPE_COMPUTER:
839            $series['computer'][$value['day']]+=$value['nbVisits'];
840            break;
841          case UA_BROWSER_TYPE_MOBILE:
842            $series['mobile'][$value['day']]+=$value['nbVisits'];
843            break;
844          case UA_BROWSER_TYPE_CRAWLER:
845            $series['crawler'][$value['day']]+=$value['nbVisits'];
846            break;
847          default:
848            $series['other'][$value['day']]+=$value['nbVisits'];
849            break;
850        }
851      }
852
853      // format axis (add day letter for sunday)
854      foreach($returned['axis'] as $key=>$day)
855      {
856        $period=$year.'-'.$month.'-'.$day;
857        if(date('w', strtotime($period))==0) $returned['axis'][$key]=l10n('letter_day_sunday').' '.$day;
858      }
859
860      // format series values
861      foreach($series as $serie=>$period)
862      {
863        foreach($period as $nbVisits)
864        {
865          $returned['series'][$serie]['nbVisits'][]=$nbVisits;
866        }
867      }
868
869      return(json_encode($returned));
870    }
871
872
873
874
875    /**
876     * return the number of logs events per period (for all periods)
877     *
878     * data can be filtered to retrieve informations from a limited range of $nbMonth around
879     * the $currentPeriod
880     *
881     * @param String $currentPeriod: current period (YYYYMM); no period=all periods
882     * @param Integer $nbMonth: number of month to retrieve; 0=all periods
883     * @return String : an array in json format
884     *                    (Array)
885     *                      'axis' => (Array)  period as a formatted string
886     *                      'series' => (Array) serie values
887     *                      'maxValue' => (Integer) maximum value found on all series
888     */
889    protected function ajax_estat_admin_statHistoryVisitsAllPeriods($currentPeriod='', $nbMonth=0)
890    {
891      if($currentPeriod!='' and $nbMonth>0)
892      {
893        $managePeriod=true;
894
895        $year=substr($currentPeriod,0,4);
896        $month=substr($currentPeriod,4,2);
897
898        $before=round($nbMonth/2,0);
899        $after=$nbMonth-$before-1;
900
901        $firstPeriod=date('Y-m', strtotime('-'.$before.' month', strtotime($year.'-'.$month.'-01')));
902        $lastPeriod=date('Y-m', strtotime('+'.$after.' month', strtotime($year.'-'.$month.'-01')));
903
904        $periodList=array();
905        for($i=0;$i<$nbMonth;$i++)
906        {
907          $period=date('Y-m', strtotime("+$i month", strtotime($firstPeriod.'-01')));
908          $periodList[$period]=array('y' => substr($period, 0, 4), 'm' => substr($period, 5, 2));
909        }
910      }
911      else
912      {
913        $managePeriod=false;
914        $before=0;
915        $after=0;
916        $year='';
917        $month='';
918        $firstPeriod='';
919        $lastPeriod='';
920        $periodList=array();
921      }
922
923      $returned=array(
924        'maxValue' => 0,
925        'axis' => array(),
926        'series' => array(
927                      'total'    => array(
928                                      'name' => l10n('estat_total'),
929                                      'nbVisits' => array()
930                                    ),
931                      'computer' => array(
932                                      'name' => l10n('ua_Computer'),
933                                      'nbVisits' => array()
934                                    ),
935                      'mobile'   => array(
936                                      'name' => l10n('ua_Mobile'),
937                                      'nbVisits' => array()
938                                    ),
939                      'crawler'  => array(
940                                      'name' => l10n('ua_Crawler'),
941                                      'nbVisits' => array()
942                                    ),
943                      'other' => array(
944                                      'name' => l10n('ua_Other'),
945                                      'nbVisits' => array()
946                                    )
947                    )
948      );
949
950      // open db file
951      $gStatFile=new StatDBGlobal($this->fileStatDir, self::FILE_GLOBAL);
952      $gStatFile->open(ASDF_OPEN_READ);
953
954      // get number of visits per type of user agent (mobile, computer, crawler, ...)
955      $data=$gStatFile->getStatUserAgent(ASDF_GET_ROWS, 0, 0,
956                                          array('year', 'month', 'uaValue'),
957                                          array('uaData' => array('operator'=>'=', 'value'=>UA_DATA_BROWSER_TYPE)),
958                                          array(
959                                            array('id'=>'year',  'direction'=>'A'),
960                                            array('id'=>'month',  'direction'=>'A')
961                                          )
962                                        );
963      $gStatFile->close();
964
965
966      // prepare data
967      $axis=array();
968      $series=array(
969          'total' => array(),
970          'computer' => array(),
971          'mobile' => array(),
972          'crawler' => array(),
973          'other' => array()
974        );
975      if($managePeriod)
976      {
977        foreach($periodList as $period=>$value)
978        {
979          $axis[$period]=$value;
980          $series['total'][$period]=0;
981          $series['computer'][$period]=0;
982          $series['mobile'][$period]=0;
983          $series['crawler'][$period]=0;
984          $series['other'][$period]=0;
985        }
986      }
987
988      foreach($data as $value)
989      {
990        $value['month']=sprintf('%02d', 1*$value['month']);
991        $period=$value['year'].'-'.$value['month'];
992
993        if($managePeriod and isset($periodList[$period]) or !$managePeriod)
994        {
995          if($managePeriod) $periodList[$period]=true;
996
997          if(!isset($axis[$period]))
998          {
999            $axis[$period]=array('y'=>$value['year'], 'm'=>$value['month']);
1000            $series['total'][$period]=0;
1001            $series['computer'][$period]=0;
1002            $series['mobile'][$period]=0;
1003            $series['crawler'][$period]=0;
1004            $series['other'][$period]=0;
1005          }
1006
1007          $series['total'][$period]+=$value['nbVisits'];
1008          if($returned['maxValue']<$series['total'][$period]) $returned['maxValue']=$series['total'][$period];
1009
1010          switch($value['uaValue'])
1011          {
1012            case UA_BROWSER_TYPE_COMPUTER:
1013              $series['computer'][$period]+=$value['nbVisits'];
1014              break;
1015            case UA_BROWSER_TYPE_MOBILE:
1016              $series['mobile'][$period]+=$value['nbVisits'];
1017              break;
1018            case UA_BROWSER_TYPE_CRAWLER:
1019              $series['crawler'][$period]+=$value['nbVisits'];
1020              break;
1021            default:
1022              $series['other'][$period]+=$value['nbVisits'];
1023              break;
1024          }
1025        }
1026      }
1027
1028      // format axis values "month [year]"
1029      $i=0;
1030      foreach($axis as $period)
1031      {
1032        if($period['m']==1 or $i==0)
1033        {
1034          $returned['axis'][]='('.$period['y'].') '.l10n('month_'.$period['m']);
1035        }
1036        else
1037        {
1038          $returned['axis'][]=l10n('month_'.$period['m']);
1039        }
1040        $i++;
1041      }
1042
1043      // format series values
1044      foreach($series as $serie=>$period)
1045      {
1046        foreach($period as $nbVisits)
1047        {
1048          $returned['series'][$serie]['nbVisits'][]=$nbVisits;
1049        }
1050      }
1051
1052      return(json_encode($returned));
1053    }
1054
1055
1056    /**
1057     * return the number of visits from a period
1058     *
1059     * @param String $period : the period to be processed
1060     *                          'allYear'    => process all year
1061     *                          'y-YYYY'     => process year YYYY
1062     *                          'ym-YYYYMM'  => process year/month YYYY/MM
1063     * @param Array  $filterPost : filter options
1064     * @param Integer $pageNumber : page number to return
1065     * @return String : an array in json format
1066     *                    (Array) visits properties
1067     *                      'period' => (String)
1068     *                      'nbPages' => (String) IP or user login
1069     *                      'nbCat' => (String) country code (ISO 3366-1)
1070     *                      'nbPhotos' => (String) name of the album
1071     *                      'nbIP' => (String) name of image
1072     */
1073    protected function ajax_estat_admin_statPeriod($period, $filterPost, $sort, $pageNumber, $nbItemsPage)
1074    {
1075      global $lang;
1076
1077      $periodType='';
1078      $year=null;
1079      $month=null;
1080
1081      $result=array(
1082        'rows'  => null,
1083        'total' => null
1084      );
1085      $returned=array(
1086        'rows'  => array(),
1087        'total' => array()
1088      );
1089      $fields=array(
1090        'rows' => array(),
1091        'total' => array()
1092      );
1093      $filter=array('uaData' => UA_DATA_BROWSER, 'catId' => array(), 'year'=>array(), 'month'=>array());
1094
1095      if(substr($period,0,3)=='ym-')
1096      {
1097        $periodType='ym';
1098        $year=substr($period,3,4)*1;
1099        $month=substr($period,7,2)*1;
1100        $fields['rows'][]='day';
1101      }
1102      elseif(substr($period,0,2)=='y-')
1103      {
1104        $periodType='y';
1105        $fields['rows'][]='month';
1106        $year=substr($period,2,4)*1;
1107      }
1108      else // all other values assume $period=='allYear'
1109      {
1110        $fields['rows'][]='year';
1111        $fields['total']=array();
1112      }
1113
1114      // filter on catId?
1115      if(isset($filterPost['catId']))
1116      {
1117        $filter['catId']=$this->buildCatIdFilter($filterPost['catId']);
1118      }
1119      if($year!=null)
1120        $filter['year']=array('operator' => '=', 'value' => $year);
1121      if($month!=null)
1122        $filter['month']=array('operator' => '=', 'value' => $month);
1123
1124      // open db file for the period
1125
1126      if($periodType=='ym')
1127      {
1128        $statFile=new StatDBMonth($this->fileStatDir, self::FILE_MONTH);
1129        $statFile->setPeriod($year, sprintf('%02d', $month));
1130      }
1131      else
1132      {
1133        $statFile=new StatDBGlobal($this->fileStatDir, self::FILE_GLOBAL);
1134      }
1135
1136
1137      $statFile->open(ASDF_OPEN_READ);
1138
1139      // get stats
1140      $result['rows']=$statFile->getStatPeriod($pageNumber, $nbItemsPage, $fields['rows'], $filter, $sort);
1141      // reformat stats for table
1142
1143      switch($periodType)
1144      {
1145        case 'ym':
1146          foreach($result['rows'] as $day => $values)
1147          {
1148            $returned['rows'][]=array(
1149              $day,
1150              $values['T'],
1151              $values['C'],
1152              $values['I'],
1153              $values['A'],
1154              $day
1155            );
1156          }
1157
1158          $tmp=$statFile->getStatPeriod(0, 0, $fields['total'], $filter, $sort);
1159          $returned['total']=array('', $tmp[0]['T'], $tmp[0]['C'], $tmp[0]['I'], $tmp[0]['A']);
1160          break;
1161        case 'y':
1162          foreach($result['rows'] as $year => $months)
1163          {
1164            foreach($months as $month => $values)
1165            {
1166              $returned['rows'][]=array(
1167                $lang['month'][$month],
1168                $values['T'],
1169                $values['C'],
1170                $values['I'],
1171                $values['A'],
1172                sprintf('%02d', $month)
1173              );
1174            }
1175          }
1176
1177          $tmp=$statFile->getStatPeriod(0, 0, $fields['total'], $filter, $sort);
1178          $returned['total']=array('', $tmp[0][0]['T'], $tmp[0][0]['C'], $tmp[0][0]['I'], $tmp[0][0]['A']);
1179          break;
1180        default:
1181          // all years...
1182          foreach($result['rows'] as $year => $values)
1183          {
1184            if($year>0)
1185            {
1186              $returned['rows'][]=array(
1187                $year,
1188                $values[0]['T'],
1189                $values[0]['C'],
1190                $values[0]['I'],
1191                $values[0]['A'],
1192                sprintf('%02d', $year)
1193              );
1194            }
1195          }
1196          $tmp=$statFile->getStatPeriod(0, 0, $fields['total'], $filter, $sort);
1197          $returned['total']=array('', $tmp[0][0]['T'], $tmp[0][0]['C'], $tmp[0][0]['I'], $tmp[0][0]['A']);
1198          break;
1199      }
1200
1201      $statFile->close();
1202      return(json_encode($returned));
1203    }
1204
1205
1206
1207
1208
1209    /**
1210     * return the number of visits from a period, formatted for a graph
1211     *
1212     * @param String $period : the period to be processed
1213     *                          'allYear'    => process all year
1214     *                          'y-YYYY'     => process year YYYY
1215     *                          'ym-YYYYMM'  => process year/month YYYY/MM
1216     * @param Array  $filterPost : filter options
1217     * @param Integer $pageNumber : page number to return
1218     * @return String : an array in json format
1219     *                    (Array)
1220     *                      'axis' => (Array)  period as a formatted string
1221     *                      'series' => (Array) serie values
1222     *                      'maxValue' => (Integer) maximum value found on all series
1223     */
1224    protected function ajax_estat_admin_statPeriodGraph($period, $filterPost)
1225    {
1226      global $lang;
1227
1228      $periodType='';
1229      $year=null;
1230      $month=null;
1231
1232      $returned=array(
1233        'maxValue' => 0,
1234        'axis' => array(),
1235        'series' => array(
1236                      'viewedPages' => array(
1237                                      'name' => l10n('estat_viewedPages'),
1238                                      'nbVisits' => array()
1239                                    ),
1240                      'viewedAlbums' => array(
1241                                      'name' => l10n('estat_viewedAlbums'),
1242                                      'nbVisits' => array()
1243                                    ),
1244                      'viewedImages' => array(
1245                                      'name' => l10n('estat_viewedImages'),
1246                                      'nbVisits' => array()
1247                                    ),
1248                      'uniqueIP'  => array(
1249                                      'name' => l10n('estat_uniqueIP'),
1250                                      'nbVisits' => array()
1251                                    )
1252                    )
1253      );
1254
1255      $filter=array('uaData' => UA_DATA_BROWSER, 'catId' => array(), 'year'=>array(), 'month'=>array() );
1256      $fields=array();
1257
1258      if(substr($period,0,3)=='ym-')
1259      {
1260        $periodType='ym';
1261        $year=substr($period,3,4)*1;
1262        $month=substr($period,7,2)*1;
1263        $fields[]='day';
1264      }
1265      elseif(substr($period,0,2)=='y-')
1266      {
1267        $periodType='y';
1268        $fields[]='month';
1269        $year=substr($period,2,4)*1;
1270      }
1271      else // all other values assume $period=='allYear'
1272      {
1273        $fields[]='year';
1274      }
1275
1276      // filter on catId?
1277      if(isset($filterPost['catId']))
1278      {
1279        $filter['catId']=$this->buildCatIdFilter($filterPost['catId']);
1280      }
1281      if($year)
1282        $filter['year']=array('operator' => '=', 'value' => $year);
1283      if($month)
1284        $filter['month']=array('operator' => '=', 'value' => $month);
1285
1286
1287      // open db file for the period
1288
1289      if($periodType=='ym')
1290      {
1291        $statFile=new StatDBMonth($this->fileStatDir, self::FILE_MONTH);
1292        $statFile->setPeriod($year, sprintf('%02d', $month));
1293      }
1294      else
1295      {
1296        $statFile=new StatDBGlobal($this->fileStatDir, self::FILE_GLOBAL);
1297      }
1298
1299
1300      $statFile->open(ASDF_OPEN_READ);
1301
1302      // get stats
1303      $result['rows']=$statFile->getStatPeriod(0, 0, $fields, $filter, null);
1304
1305
1306      // prepare data
1307      $axis=array();
1308      $series=array(
1309          'viewedPages' => array(),
1310          'viewedAlbums' => array(),
1311          'viewedImages' => array(),
1312          'uniqueIP' => array()
1313        );
1314
1315      switch($periodType)
1316      {
1317        case 'ym':
1318          foreach($result['rows'] as $day => $values)
1319          {
1320            if($returned['maxValue']<$values['T']) $returned['maxValue']=$values['T'];
1321            $returned['axis'][]=$day;
1322            $series['viewedPages'][$day]=$values['T'];
1323            $series['viewedAlbums'][$day]=$values['C'];
1324            $series['viewedImages'][$day]=$values['I'];
1325            $series['uniqueIP'][$day]=$values['A'];
1326          }
1327
1328          // format axis (add day letter for sunday)
1329          foreach($returned['axis'] as $key=>$day)
1330          {
1331            $period=$year.'-'.$month.'-'.$day;
1332            if(date('w', strtotime($period))==0) $returned['axis'][$key]=l10n('letter_day_sunday').' '.$day;
1333          }
1334          break;
1335        case 'y':
1336          foreach($result['rows'] as $year => $months)
1337          {
1338            foreach($months as $month => $values)
1339            {
1340              if($returned['maxValue']<$values['T']) $returned['maxValue']=$values['T'];
1341              $returned['axis'][]=$lang['month'][$month];
1342              $series['viewedPages'][$month]=$values['T'];
1343              $series['viewedAlbums'][$month]=$values['C'];
1344              $series['viewedImages'][$month]=$values['I'];
1345              $series['uniqueIP'][$month]=$values['A'];
1346            }
1347          }
1348          break;
1349        default:
1350          foreach($result['rows'] as $year => $values)
1351          {
1352            if($year>0)
1353            {
1354              if($returned['maxValue']<$values[0]['T']) $returned['maxValue']=$values[0]['T'];
1355              $returned['axis'][]=$year;
1356              $series['viewedPages'][$year]=$values[0]['T'];
1357              $series['viewedAlbums'][$year]=$values[0]['C'];
1358              $series['viewedImages'][$year]=$values[0]['I'];
1359              $series['uniqueIP'][$year]=$values[0]['A'];
1360            }
1361          }
1362          break;
1363      }
1364
1365      // format series values
1366      foreach($series as $serie=>$period)
1367      {
1368        foreach($period as $nbVisits)
1369        {
1370          $returned['series'][$serie]['nbVisits'][]=$nbVisits;
1371        }
1372      }
1373
1374      return(json_encode($returned));
1375    }
1376
1377
1378
1379
1380
1381    /**
1382     * return the detail for IP from a period
1383     *
1384     * @param String $period : the period to be processed
1385     *                          'allYear'    => process all year
1386     *                          'y-YYYY'     => process year YYYY
1387     *                          'ym-YYYYMM'  => process year/month YYYY/MM
1388     * @param Array  $filterPost : filter options
1389     * @param Array  $sort: sort options
1390     * @param Array  $group: grouped items; could be:
1391     *                        'IPadress'
1392     *                        'country'
1393     *                        'uaType'
1394     * @param Integer $pageNumber : page number to return
1395     * @return String : an array in json format
1396     *                    (Array)
1397     *                      'rows' => (Array)
1398     *                                  'IPadress' => (String)
1399     *                                  'country' => (String)
1400     *                                  'uaType' => (String)
1401     *                                  'nbVisits' => (Integer)
1402     *                      'total' => (Array)
1403     *                                  'IPadress' => (String) [empty]
1404     *                                  'country' => (String) [empty]
1405     *                                  'uaType' => (String) [empty]
1406     *                                  'nbVisits' => (Integer)
1407     *                      'nbItems' => (Integer)
1408     */
1409    protected function ajax_estat_admin_statIP($period, $filterPost, $sort, $group, $pageNumber, $nbItemsPage)
1410    {
1411      global $lang;
1412
1413      $year=null;
1414      $month=null;
1415
1416      $result=array(
1417        'rows'  => array(),
1418        'total' => array()
1419      );
1420      $returned=array(
1421        'rows'  => array(),
1422        'total' => array(),
1423        'nbItems' => 0
1424      );
1425      $fields=array(
1426        'rows' => array_diff(array('uaType', 'IPadress', 'country'), $group),
1427        'total' => array()
1428      );
1429      $filter=array();
1430
1431      if(substr($period,0,3)=='ym-')
1432      {
1433        $year=substr($period,3,4)*1;
1434        $month=substr($period,7,2)*1;
1435      }
1436      elseif(substr($period,0,2)=='y-')
1437      {
1438        $year=substr($period,2,4)*1;
1439      }
1440
1441      foreach($filterPost as $key => $val)
1442      {
1443        if($key==='additionalFilter')
1444        {
1445          if(isset($val['catId']))
1446            $filter['catId']=$this->buildCatIdFilter($val['catId']);
1447        }
1448        else
1449        {
1450          $filter[$val['id']]=$val;
1451        }
1452      }
1453
1454      if($year!=null)
1455        $filter['year']=array('operator' => '=', 'value' => $year);
1456      if($month!=null)
1457        $filter['month']=array('operator' => '=', 'value' => $month);
1458
1459      // open db file for the period
1460
1461
1462      $statFile=new StatDBGlobal($this->fileStatDir, self::FILE_GLOBAL);
1463
1464      $statFile->open(ASDF_OPEN_READ);
1465
1466      // get stats
1467      $result['rows']=$statFile->getStatIP(ASDF_GET_ROWS, $pageNumber, $nbItemsPage, $fields['rows'], $filter, $sort);
1468      $result['total']=$statFile->getStatIP(ASDF_GET_ROWS, 0, 0, array(), $filter, array());
1469
1470      foreach($result['rows'] as $row)
1471      {
1472        if(isset($row['uaType']))
1473        {
1474          $userAgentNfo=GPCUserAgent::getProperties(
1475              array(
1476                UA_DATA_BROWSER_TYPE => $row['uaType']
1477              )
1478            );
1479          $row['uaType']=l10n('ua_'.$userAgentNfo[UA_DATA_BROWSER_TYPE_NAME]);
1480        }
1481        else
1482        {
1483          $row['uaType']='';
1484        }
1485
1486        if(isset($row['country']))
1487        {
1488          $country='estat_country_'.strtoupper($row['country']);
1489          if(isset($lang[$country]))
1490          {
1491            $country="<span class='cCountryCode'>".$row['country'].'</span>'.$lang[$country];
1492          }
1493          else
1494          {
1495            $country="<span class='cCountryCode'>".$row['country'].'</span>';
1496          }
1497        }
1498        else
1499        {
1500          $country='';
1501          $row['country']='';
1502        }
1503
1504        if(isset($row['IPadress']))
1505        {
1506          if($row['country']!='--' and $row['country']!='XA')
1507          {
1508            $row['IPadress']='<a href="http://www.geoiptool.com/fr/?IP='.$row['IPadress'].'">'.$row['IPadress'].'</a>';
1509          }
1510        }
1511        else
1512        {
1513          $row['IPadress']='';
1514        }
1515
1516        $returned['rows'][]=array(
1517          $row['IPadress'],
1518          $country,
1519          $row['uaType'],
1520          sprintf('%d<span class="cPctCol">%0.2f%%</span>', $row['nbVisits'], 100*$row['nbVisits']/$result['total'][0]['nbVisits'])
1521        );
1522      }
1523
1524      $returned['total']=array(
1525        '', '', '',
1526        isset($result['total'][0]['nbVisits'])?$result['total'][0]['nbVisits']:'0'
1527      );
1528
1529      $returned['nbItems']=$statFile->getStatIP(ASDF_GET_COUNT, 0, 0, $fields['rows'], $filter, array());
1530
1531      $statFile->close();
1532      return(json_encode($returned));
1533    }
1534
1535
1536
1537    /**
1538     * return the detail needed to draw a GraphType for IP from a period
1539     *
1540     * @param String $period : the period to be processed
1541     *                          'allYear'    => process all year
1542     *                          'y-YYYY'     => process year YYYY
1543     *                          'ym-YYYYMM'  => process year/month YYYY/MM
1544     * @param Array  $filterPost : filter options
1545     * @return String : an array in json format
1546     *                    (Array)
1547     *                      'values'       => (Array) (Integer)
1548     *                      'valuesLabels' => (Array) (String)
1549     */
1550    protected function ajax_estat_admin_statIPGraphType($period, $filterPost)
1551    {
1552      global $lang;
1553
1554      $year=null;
1555      $month=null;
1556
1557      $returned=array(
1558        'values' => array(0,0,0,0,0),
1559        'valuesLabels' => array(
1560            l10n('ua_'.GPCUserAgentValues::$UA_BrowserInfo[UA_DATA_BROWSER_TYPE][UA_BROWSER_TYPE_CRAWLER]),
1561            l10n('ua_'.GPCUserAgentValues::$UA_BrowserInfo[UA_DATA_BROWSER_TYPE][UA_BROWSER_TYPE_COMPUTER]),
1562            l10n('ua_'.GPCUserAgentValues::$UA_BrowserInfo[UA_DATA_BROWSER_TYPE][UA_BROWSER_TYPE_MOBILE]),
1563            l10n('ua_'.GPCUserAgentValues::$UA_BrowserInfo[UA_DATA_BROWSER_TYPE][UA_BROWSER_TYPE_CONSOLE]),
1564            l10n('ua_'.GPCUserAgentValues::$UA_BrowserInfo[UA_DATA_BROWSER_TYPE][UA_BROWSER_TYPE_UNKNOWN])
1565        )
1566      );
1567      $fields=array('uaType');
1568
1569      $filter=array();
1570
1571      if(substr($period,0,3)=='ym-')
1572      {
1573        $year=substr($period,3,4)*1;
1574        $month=substr($period,7,2)*1;
1575      }
1576      elseif(substr($period,0,2)=='y-')
1577      {
1578        $year=substr($period,2,4)*1;
1579      }
1580
1581      if(isset($filterPost['catId']))
1582          $filter['catId']=$this->buildCatIdFilter($filterPost['catId']);
1583
1584      if($year!=null)
1585        $filter['year']=array('operator' => '=', 'value' => $year);
1586      if($month!=null)
1587        $filter['month']=array('operator' => '=', 'value' => $month);
1588
1589      $sort=array(
1590        array('id'=>'uaType', 'direction'=>'A')
1591      );
1592
1593      // open db file for the period
1594      $statFile=new StatDBGlobal($this->fileStatDir, self::FILE_GLOBAL);
1595
1596      $statFile->open(ASDF_OPEN_READ);
1597
1598      // get stats
1599      $result=$statFile->getStatIP(ASDF_GET_ROWS, 0, 0, $fields, $filter, $sort);
1600      $statFile->close();
1601
1602      $sum=0;
1603      foreach($result as $row)
1604      {
1605        switch($row['uaType'])
1606        {
1607          case UA_BROWSER_TYPE_CRAWLER:
1608            $key=0;
1609            break;
1610          case UA_BROWSER_TYPE_COMPUTER:
1611            $key=1;
1612            break;
1613          case UA_BROWSER_TYPE_MOBILE:
1614            $key=2;
1615            break;
1616          case UA_BROWSER_TYPE_CONSOLE:
1617            $key=3;
1618            break;
1619          case UA_BROWSER_TYPE_UNKNOWN:
1620            $key=4;
1621            break;
1622        }
1623
1624        $returned['values'][$key]=$row['nbVisits'];
1625        $sum+=$row['nbVisits'];
1626      }
1627
1628      foreach($returned['values'] as $key => $val)
1629      {
1630        if($val>0)
1631          $returned['valuesLabels'][$key].=sprintf(' (%0.2f%%)', 100*$val/$sum);
1632      }
1633
1634      return(json_encode($returned));
1635    }
1636
1637
1638
1639
1640
1641    /**
1642     * return the detail needed to draw a GraphCountry for IP from a period
1643     *
1644     * @param String $period : the period to be processed
1645     *                          'allYear'    => process all year
1646     *                          'y-YYYY'     => process year YYYY
1647     *                          'ym-YYYYMM'  => process year/month YYYY/MM
1648     * @param Array  $filterPost : filter options
1649     * @return String : an array in json format
1650     *                    (Array)
1651     *                      'values'       => (Array) (Integer)
1652     *                      'valuesLabels' => (Array) (String)
1653     */
1654    protected function ajax_estat_admin_statIPGraphCountry($period, $filterPost)
1655    {
1656      global $lang;
1657
1658      $year=null;
1659      $month=null;
1660
1661      $returned=array(
1662        'values' => array(),
1663        'valuesLabels' => array()
1664      );
1665      $fields=array('country');
1666
1667      $filter=array();
1668
1669      if(substr($period,0,3)=='ym-')
1670      {
1671        $year=substr($period,3,4)*1;
1672        $month=substr($period,7,2)*1;
1673      }
1674      elseif(substr($period,0,2)=='y-')
1675      {
1676        $year=substr($period,2,4)*1;
1677      }
1678
1679      if(isset($filterPost['catId']))
1680          $filter['catId']=$this->buildCatIdFilter($filterPost['catId']);
1681
1682      if($year!=null)
1683        $filter['year']=array('operator' => '=', 'value' => $year);
1684      if($month!=null)
1685        $filter['month']=array('operator' => '=', 'value' => $month);
1686
1687      // open db file for the period
1688      $statFile=new StatDBGlobal($this->fileStatDir, self::FILE_GLOBAL);
1689
1690      $statFile->open(ASDF_OPEN_READ);
1691
1692      // get stats
1693      $result=$statFile->getStatIP(ASDF_GET_ROWS, 0, 0, $fields, $filter);
1694      $statFile->close();
1695
1696      $sum=0;
1697      foreach($result as $row)
1698      {
1699        $sum+=$row['nbVisits'];
1700      }
1701
1702      $i=0;
1703      $nb=0;
1704      $other=-1;
1705      foreach($result as $row)
1706      {
1707        $pct=100*$row['nbVisits']/$sum;
1708
1709        if($i<9 and $pct>=0.5)
1710        {
1711          $country='estat_country_'.strtoupper($row['country']);
1712          if(isset($lang[$country]))
1713          {
1714            $country=$row['country'].' - '.$lang[$country];
1715          }
1716          else
1717          {
1718            $country=$row['country'];
1719          }
1720
1721          $country.=sprintf(' (%0.2f%%)', $pct);
1722
1723          $returned['values'][$i]=$row['nbVisits'];
1724          $returned['valuesLabels'][$i]=$country;
1725          $i++;
1726        }
1727        else
1728        {
1729          $nb++;
1730          $other=$i;
1731          if(!isset($returned['values'][$i]))
1732          {
1733            $returned['values'][$i]=0;
1734            $returned['valuesLabels'][$i]=l10n('estat_Other');
1735          }
1736          $returned['values'][$i]+=$row['nbVisits'];
1737        }
1738      }
1739
1740      if($other>-1)
1741      {
1742        $nbCountry=l10n('estat_country_nb');
1743        if($nb>1)
1744          $nbCountry=l10n('estat_countries_nb');
1745
1746        $returned['valuesLabels'][$other].=sprintf(' ('.$nbCountry.', %0.2f%%)', $nb, 100*$returned['values'][$other]/$sum );
1747      }
1748
1749      return(json_encode($returned));
1750    }
1751
1752
1753
1754
1755
1756    /**
1757     * return the detail for albums/categories from a period
1758     *
1759     * @param String $period : the period to be processed
1760     *                          'allYear'    => process all year
1761     *                          'y-YYYY'     => process year YYYY
1762     *                          'ym-YYYYMM'  => process year/month YYYY/MM
1763     * @param Array  $filterPost : filter options
1764     * @param Array  $sort: sort options
1765     * @param Array  $group: grouped items; could be:
1766     *                        'uaType'
1767     * @param Integer $pageNumber : page number to return
1768     * @return String : an array in json format
1769     *                    (Array)
1770     *                      'rows' => (Array)
1771     *                                  'category' => (String)
1772     *                                  'uaType' => (String)
1773     *                                  'nbVisits' => (Integer)
1774     *                      'total' => (Array)
1775     *                                  'category' => (String) [empty]
1776     *                                  'uaType' => (String) [empty]
1777     *                                  'nbVisits' => (Integer)
1778     *                      'nbItems' => (Integer)
1779     */
1780    protected function ajax_estat_admin_statCategory($period, $filterPost, $sort, $group, $pageNumber, $nbItemsPage)
1781    {
1782      global $lang;
1783
1784      $year=null;
1785      $month=null;
1786
1787      $result=array(
1788        'rows'  => array(),
1789        'total' => array()
1790      );
1791      $returned=array(
1792        'rows'  => array(),
1793        'total' => array(),
1794        'nbItems' => 0
1795      );
1796      $fields=array(
1797        'rows' => array_diff(array('catId', 'uaType'), $group),
1798        'total' => array()
1799      );
1800      $filter=array();
1801
1802      if(substr($period,0,3)=='ym-')
1803      {
1804        $year=substr($period,3,4)*1;
1805        $month=substr($period,7,2)*1;
1806      }
1807      elseif(substr($period,0,2)=='y-')
1808      {
1809        $year=substr($period,2,4)*1;
1810      }
1811
1812      foreach($filterPost as $key => $val)
1813      {
1814        if($key==='additionalFilter')
1815        {
1816          if(isset($val['catId']))
1817            $filter['catId']=$this->buildCatIdFilter($val['catId']);
1818        }
1819        else
1820        {
1821          $filter[$val['id']]=$val;
1822        }
1823      }
1824
1825      if($year!=null)
1826        $filter['year']=array('operator' => '=', 'value' => $year);
1827      if($month!=null)
1828        $filter['month']=array('operator' => '=', 'value' => $month);
1829
1830      // open db file for the period
1831
1832
1833      $statFile=new StatDBGlobal($this->fileStatDir, self::FILE_GLOBAL);
1834
1835      $statFile->open(ASDF_OPEN_READ);
1836
1837      // get stats
1838      $result['rows']=$statFile->getStatCat(ASDF_GET_ROWS, $pageNumber, $nbItemsPage, $fields['rows'], $filter, $sort);
1839      $result['total']=$statFile->getStatCat(ASDF_GET_ROWS, 0, 0, array(), $filter, array());
1840
1841      // prepare categories&images properties
1842      $idList=new EStat_IdList(array('catId', 'imageId'));
1843      $idAssoc=array(
1844        'catId'=>array(),
1845        'imageId'=>array()
1846      );
1847
1848      // first, build category_id list
1849      foreach($result['rows'] as $row)
1850      {
1851        $idList->addItems(array('catId' => $row['catId']));
1852      }
1853
1854      // get upper categories and complete category_id list
1855      if(count($idList->getItems('catId')) > 0)
1856      {
1857        $sql="SELECT DISTINCT uppercats FROM ".CATEGORIES_TABLE." WHERE id IN (".implode(',', $idList->getItems('catId')).");";
1858        $result2=pwg_query($sql);
1859        if($result2)
1860        {
1861          while($row=pwg_db_fetch_row($result2))
1862          {
1863            $ids=explode(',', $row[0]);
1864            foreach($ids as $id)
1865            {
1866              $idList->addItems(array('catId' => $id));
1867            }
1868          }
1869        }
1870      }
1871
1872      // get all needed properties for each category_id
1873      if(count($idList->getItems('catId')) > 0)
1874        $this->prepareIdList($idAssoc, 'catId', "SELECT id, name, uppercats, representative_picture_id FROM ".CATEGORIES_TABLE." WHERE id IN (".implode(',', $idList->getItems('catId')).") ORDER BY id;");
1875
1876      // prepare image_id informations (for category representative picture)
1877      $categories=$idList->getItems('catId');
1878      foreach($idAssoc['catId'] as $category)
1879      {
1880        if($category['representative_picture_id']!=null)
1881          $idList->addItems(array('imageId' => $category['representative_picture_id']));
1882      }
1883
1884      if(count($idList->getItems('imageId')) > 0)
1885        $this->prepareIdList($idAssoc, 'imageId', "SELECT id, file AS name, path FROM ".IMAGES_TABLE." WHERE id IN (".implode(',', $idList->getItems('imageId')).") ORDER BY id;");
1886
1887      foreach($result['rows'] as $row)
1888      {
1889        if(isset($row['uaType']))
1890        {
1891          $userAgentNfo=GPCUserAgent::getProperties(
1892              array(
1893                UA_DATA_BROWSER_TYPE => $row['uaType']
1894              )
1895            );
1896          $row['uaType']=l10n('ua_'.$userAgentNfo[UA_DATA_BROWSER_TYPE_NAME]);
1897        }
1898        else
1899        {
1900          $row['uaType']='';
1901        }
1902
1903
1904        if($row['catId']==0)
1905        {
1906          $categoryNfo=l10n('estat_special_category');
1907        }
1908        elseif($this->getId($idAssoc, 'catId', $row['catId'], '', 'name')=='')
1909        {
1910          $categoryNfo=l10n('estat_deleted_category');
1911        }
1912        else
1913        {
1914          $categoryNfo='<a href="'.GPCCore::urlBuild('admin.album', array('categoryId'=>$row['catId'])).'">'.$this->getId($idAssoc, 'catId', $row['catId'], '', 'name').'</a>';
1915        }
1916
1917        $uppercats=explode(',', $this->getId($idAssoc, 'catId', $row['catId'], null, 'uppercats'));
1918        if(count($uppercats)>1)
1919        {
1920          $categoryNfo=$this->getId($idAssoc, 'catId', $uppercats[count($uppercats)-2], '', 'name')." / ".$categoryNfo;
1921        }
1922
1923        $representativeUrl=$this->getId($idAssoc, 'catId', $row['catId'], null, 'representative_picture_id');
1924        if($representativeUrl!=null)
1925        {
1926          $imageNfo = new SrcImage(
1927                        array(
1928                          'id'=>$representativeUrl,
1929                          'path'=>$this->getId($idAssoc, 'imageId', $representativeUrl, '', 'path')
1930                        )
1931                      );
1932          $representativeUrl='./'.substr(DerivativeImage::url(IMG_THUMB, $imageNfo),strlen(PHPWG_ROOT_PATH));
1933        }
1934        else
1935        {
1936          $representativeUrl='';
1937        }
1938
1939
1940        $returned['rows'][]=array(
1941          $categoryNfo,
1942          $row['uaType'],
1943          sprintf('%d<span class="cPctCol">%0.2f%%</span>', $row['nbVisits'], 100*$row['nbVisits']/$result['total'][0]['nbVisits']),
1944          $representativeUrl
1945        );
1946      }
1947
1948      $returned['total']=array(
1949        '', '',
1950        isset($result['total'][0]['nbVisits'])?$result['total'][0]['nbVisits']:'0'
1951      );
1952
1953      $returned['nbItems']=$statFile->getStatCat(ASDF_GET_COUNT, 0, 0, $fields['rows'], $filter, array());
1954
1955      $statFile->close();
1956      return(json_encode($returned));
1957    }
1958
1959
1960
1961
1962
1963    /**
1964     * return the detail for images from a period
1965     *
1966     * @param String $period : the period to be processed
1967     *                          'allYear'    => process all year
1968     *                          'y-YYYY'     => process year YYYY
1969     *                          'ym-YYYYMM'  => process year/month YYYY/MM
1970     * @param Array  $filterPost : filter options
1971     * @param Array  $sort: sort options
1972     * @param Array  $group: grouped items; could be:
1973     *                        'uaType'
1974     * @param Integer $pageNumber : page number to return
1975     * @return String : an array in json format
1976     *                    (Array)
1977     *                      'rows' => (Array)
1978     *                                  'category' => (String)
1979     *                                  'uaType' => (String)
1980     *                                  'nbVisits' => (Integer)
1981     *                      'total' => (Array)
1982     *                                  'category' => (String) [empty]
1983     *                                  'uaType' => (String) [empty]
1984     *                                  'nbVisits' => (Integer)
1985     *                      'nbItems' => (Integer)
1986     */
1987    protected function ajax_estat_admin_statImage($period, $filterPost, $sort, $group, $pageNumber, $nbItemsPage)
1988    {
1989      global $lang;
1990
1991      $year=null;
1992      $month=null;
1993
1994      $result=array(
1995        'rows'  => array(),
1996        'total' => array()
1997      );
1998      $returned=array(
1999        'rows'  => array(),
2000        'total' => array(),
2001        'nbItems' => 0
2002      );
2003      $fields=array(
2004        'rows' => array_diff(array('imageId', 'catId', 'uaType'), $group),
2005        'total' => array()
2006      );
2007      $filter=array();
2008
2009      if(substr($period,0,3)=='ym-')
2010      {
2011        $year=substr($period,3,4)*1;
2012        $month=substr($period,7,2)*1;
2013      }
2014      elseif(substr($period,0,2)=='y-')
2015      {
2016        $year=substr($period,2,4)*1;
2017      }
2018
2019      foreach($filterPost as $key => $val)
2020      {
2021        if($key==='additionalFilter')
2022        {
2023          if(isset($val['catId']))
2024            $filter['catId']=$this->buildCatIdFilter($val['catId']);
2025        }
2026        else
2027        {
2028          $filter[$val['id']]=$val;
2029        }
2030      }
2031
2032      if($year!=null)
2033        $filter['year']=array('operator' => '=', 'value' => $year);
2034      if($month!=null)
2035        $filter['month']=array('operator' => '=', 'value' => $month);
2036
2037      // open db file for the period
2038
2039
2040      $statFile=new StatDBGlobal($this->fileStatDir, self::FILE_GLOBAL);
2041
2042      $statFile->open(ASDF_OPEN_READ);
2043
2044      // get stats
2045      $result['rows']=$statFile->getStatImages(ASDF_GET_ROWS, $pageNumber, $nbItemsPage, $fields['rows'], $filter, $sort);
2046      $result['total']=$statFile->getStatImages(ASDF_GET_ROWS, 0, 0, array(), $filter, array());
2047
2048      // prepare categories&images properties
2049      $idList=new EStat_IdList(array('catId', 'imageId'));
2050      $idAssoc=array(
2051        'catId'=>array(),
2052        'imageId'=>array()
2053      );
2054
2055      // first, build category_id list
2056      foreach($result['rows'] as $row)
2057      {
2058        $idList->addItems(array('catId' => $row['catId']));
2059        $idList->addItems(array('imageId' => $row['imageId']));
2060      }
2061
2062      // get all needed properties for each category_id
2063      if(count($idList->getItems('catId')) > 0)
2064        $this->prepareIdList($idAssoc, 'catId', "SELECT id, name FROM ".CATEGORIES_TABLE." WHERE id IN (".implode(',', $idList->getItems('catId')).") ORDER BY id;");
2065
2066      if(count($idList->getItems('imageId')) > 0)
2067        $this->prepareIdList($idAssoc, 'imageId', "SELECT id, file AS name, path FROM ".IMAGES_TABLE." WHERE id IN (".implode(',', $idList->getItems('imageId')).") ORDER BY id;");
2068
2069      foreach($result['rows'] as $row)
2070      {
2071        if(isset($row['uaType']))
2072        {
2073          $userAgentNfo=GPCUserAgent::getProperties(
2074              array(
2075                UA_DATA_BROWSER_TYPE => $row['uaType']
2076              )
2077            );
2078          $row['uaType']=l10n('ua_'.$userAgentNfo[UA_DATA_BROWSER_TYPE_NAME]);
2079        }
2080        else
2081        {
2082          $row['uaType']='';
2083        }
2084
2085        if($row['catId']==0)
2086        {
2087          $imageName=l10n('estat_special_category');
2088        }
2089        elseif($this->getId($idAssoc, 'catId', $row['catId'], '', 'name')=='')
2090        {
2091          $imageName=l10n('estat_deleted_category').' ['.$row['catId'].']';
2092        }
2093        else
2094        {
2095          $imageName='<a href="'.GPCCore::urlBuild('admin.album', array('categoryId'=>$row['catId'])).'">'.$this->getId($idAssoc, 'catId', $row['catId'], '', 'name').'</a>';
2096        }
2097        $imageName.=' / ';
2098
2099        $imageNfo=$this->getId($idAssoc, 'imageId', $row['imageId'], '', 'name');
2100        if($imageNfo!='')
2101        {
2102          $imageName.='<a href="'.GPCCore::urlBuild('admin.picture', array('pictureId'=>$row['imageId'])).'">'.$imageNfo.'</a>';
2103        }
2104        else
2105        {
2106          $imageName.=l10n('estat_deleted_image');
2107        }
2108
2109
2110        $imagePath=$this->getId($idAssoc, 'imageId', $row['imageId'], '', 'path');
2111        if($imagePath!='')
2112        {
2113          $imageNfo = new SrcImage(
2114                        array(
2115                          'id'=>$row['imageId'],
2116                          'path'=>$imagePath
2117                        )
2118                      );
2119          $imageUrl='./'.substr(DerivativeImage::url(IMG_THUMB, $imageNfo),strlen(PHPWG_ROOT_PATH));
2120        }
2121        else
2122        {
2123          $imageUrl='';
2124        }
2125
2126
2127        $returned['rows'][]=array(
2128          $imageName,
2129          $row['uaType'],
2130          sprintf('%d<span class="cPctCol">%0.2f%%</span>', $row['nbVisits'], 100*$row['nbVisits']/$result['total'][0]['nbVisits']),
2131          $imageUrl
2132        );
2133      }
2134
2135      $returned['total']=array(
2136        '', '',
2137        isset($result['total'][0]['nbVisits'])?$result['total'][0]['nbVisits']:'0'
2138      );
2139
2140      $returned['nbItems']=$statFile->getStatImages(ASDF_GET_COUNT, 0, 0, $fields['rows'], $filter, array());
2141
2142      $statFile->close();
2143      return(json_encode($returned));
2144    }
2145
2146
2147
2148
2149
2150
2151
2152    /**
2153     * Return a list of valid values for a given domain
2154     *
2155     * @param String $domain: domain of values
2156     * @return String: an array of values in json string
2157     *                  each values is an array('id'=>id, 'value'=>value)
2158     */
2159    protected function ajax_estat_admin_fctValidValues($domain, $filter)
2160    {
2161      $returned=array();
2162
2163      $id=-1;
2164      $idFilter=-1;
2165      switch($domain)
2166      {
2167        case 'uaBrowser':
2168          $id=UA_DATA_BROWSER;
2169          switch($filter)
2170          {
2171            case 'unknown':
2172              $idFilter=UA_BROWSER_TYPE_UNKNOWN;
2173              break;
2174            case 'crawler':
2175              $idFilter=UA_BROWSER_TYPE_CRAWLER;
2176              break;
2177            case 'computer':
2178              $idFilter=UA_BROWSER_TYPE_COMPUTER;
2179              break;
2180            case 'mobile':
2181              $idFilter=UA_BROWSER_TYPE_MOBILE;
2182              break;
2183            case 'console':
2184              $idFilter=UA_BROWSER_TYPE_CONSOLE;
2185              break;
2186          }
2187          break;
2188        case 'uaEngine':
2189          $id=UA_DATA_ENGINE;
2190          break;
2191        case 'uaOS':
2192          $id=UA_DATA_OS;
2193          switch($filter)
2194          {
2195            case 'unknown':
2196              $idFilter=UA_OS_TYPE_UNKNOWN;
2197              break;
2198            case 'linux':
2199              $idFilter=UA_OS_TYPE_LINUX;
2200              break;
2201            case 'bsd':
2202              $idFilter=UA_OS_TYPE_BSD;
2203              break;
2204            case 'unix':
2205              $idFilter=UA_OS_TYPE_UNIX;
2206              break;
2207            case 'windows':
2208              $idFilter=UA_OS_TYPE_WINDOWS;
2209              break;
2210            case 'OS2':
2211              $idFilter=UA_OS_TYPE_OS2;
2212              break;
2213          }
2214          break;
2215        case 'uaType':
2216          $id=UA_DATA_BROWSER_TYPE;
2217          break;
2218        case 'country':
2219          foreach($this->countryCodes as $countryCode)
2220          {
2221            $returned[]=array(
2222              'value' => $countryCode,
2223              'cols' => array(l10n('estat_country_'.$countryCode), "[$countryCode]")
2224            );
2225          }
2226          return(json_encode($returned));
2227          break;
2228      }
2229
2230
2231      foreach(GPCUserAgentValues::$UA_BrowserInfo[$id] as $key=>$value)
2232      {
2233        if($value[UA_PROP_NAME]=='Unknown') $value[UA_PROP_NAME]='ua_Unknown';
2234
2235        switch($domain)
2236        {
2237          case 'uaBrowser':
2238            if($idFilter==-1 or ($idFilter>-1 and $value[UA_PROP_TYPE]!=$idFilter))
2239                $returned[]=array(
2240                    'value' => $key,
2241                    'cols' => array(
2242                                l10n($value[UA_PROP_NAME]),
2243                                l10n('ua_'.GPCUserAgentValues::$UA_BrowserInfo[UA_DATA_BROWSER_TYPE][$value[UA_PROP_TYPE]])
2244                              )
2245                  );
2246            break;
2247          case 'uaOS':
2248            if(GPCUserAgentValues::$UA_BrowserInfo[UA_DATA_OS_TYPE][$value[UA_PROP_TYPE]]=='Unknown')
2249                GPCUserAgentValues::$UA_BrowserInfo[UA_DATA_OS_TYPE][$value[UA_PROP_TYPE]]='ua_Unknown';
2250            if($idFilter==-1 or ($idFilter>-1 and $value[UA_PROP_TYPE]!=$idFilter))
2251                $returned[]=array(
2252                    'value' => $key,
2253                    'cols' => array(
2254                                l10n($value[UA_PROP_NAME]),
2255                                l10n(GPCUserAgentValues::$UA_BrowserInfo[UA_DATA_OS_TYPE][$value[UA_PROP_TYPE]])
2256                              )
2257                  );
2258            break;
2259          case 'uaEngine':
2260            $returned[]=array(
2261                'value' => $key,
2262                'cols' => array(l10n($value[UA_PROP_NAME]))
2263              );
2264            break;
2265          case 'uaType':
2266            $returned[]=array(
2267                'value' => $key,
2268                'cols' => array(l10n('ua_'.$value))
2269              );
2270            break;
2271        }
2272      }
2273
2274      return(json_encode($returned));
2275    }
2276
2277
2278
2279    /**
2280     * retrieve all the availables periods in a tree list
2281     *
2282     * @return String: an array in a json string
2283     */
2284    private function ajax_estat_admin_statPeriodTreeList()
2285    {
2286      global $lang;
2287
2288      $returned=array(
2289        'items'=>array(
2290          0 => array(
2291            'id' => 'allYear',
2292            'name' => l10n('estat_allPeriods'),
2293            'nfo' => '',
2294            'level' => 0,
2295            'childs' => array()
2296          )
2297        )
2298      );
2299      $items=array();
2300
2301      $gStatFile=new StatDBGlobal($this->fileStatDir, self::FILE_GLOBAL);
2302      $gStatFile->open(ASDF_OPEN_READ);
2303      $files=$gStatFile->getFilesList();
2304      $gStatFile->close();
2305
2306      foreach($files as $file)
2307      {
2308        if(!isset($items[$file['year']]))
2309          $items[$file['year']]=array(
2310              'id' => 'y-'.$file['year'],
2311              'name' => $file['year'],
2312              'nfo' => '',
2313              'level' => 0,
2314              'childs' => array()
2315            );
2316
2317        $items[$file['year']]['childs'][]=array(
2318              'id' => sprintf('ym-%04d%02d', $file['year'], $file['month']),
2319              'name' => $lang['month'][$file['month']],
2320              'nfo' => '',
2321              'level' => 1,
2322              'childs' => array()
2323            );
2324      }
2325
2326
2327
2328      foreach($items as $item)
2329      {
2330
2331        $returned['items'][]=$item;
2332      }
2333
2334      return(json_encode($returned));
2335    }
2336
2337
2338    /*
2339     * -------------------------------------------------------------------------
2340     * -- private functions
2341     * -------------------------------------------------------------------------
2342     */
2343
2344
2345  } //class EStat_Ajax
2346
2347  $returned=new EStat_Ajax($prefixeTable, __FILE__);
2348?>
Note: See TracBrowser for help on using the repository browser.