root/wp-slimstat-ex/tags/1.4/wp-slimstat-ex.php

Revision 114, 18.3 KB (checked in by 082net, 2 years ago)

## wp-slimstat-ex ##

SSPins::_filterIntervalLink now supports filter strings
Includes some bug fixes

Line 
1<?php
2/*
3Plugin Name: WP-SlimStat-Ex
4Plugin URI: http://082net.com/tag/wp-slimstat-ex/
5Description: Track your blog stats. Based on <a href="http://www.duechiacchiere.it/">Mr. Coolmann</a>'s <a href="http://www.duechiacchiere.it/wp-slimstat/">Wp-SlimStat</a>.
6Version: 1.4
7Author: Cheon, Young-Min
8Author URI: http://082net.com/
9*/
10
11/*
12ABOUT MODIFICATION ::
13        Almost php and sql codes has written by Mr. Coolmann(http://www.duechiacchiere.it)
14        What I've done is intergrating Ajax, constructing Pins(plugable panel) condition and some little patches.
15        Thanks, Coolmann.
16
17License ::
18/*
19This program is free software; you can redistribute it and/or
20modify it under the terms of the GNU General Public License
21as published by the Free Software Foundation; either version 2
22of the License, or (at your option) any later version.
23
24This program is distributed in the hope that it will be useful,
25but WITHOUT ANY WARRANTY; without even the implied warranty of
26MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
27GNU General Public License for more details.
28
29http://www.gnu.org/licenses/gpl.txt
30
31You should have received a copy of the GNU General Public License
32along with this program; if not, write to the Free Software
33Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
34______________________________________________________________*/
35
36/*
37Original Authors(others) ::
38MooTools :: http://mootools.net by Mad4Milk (http://mad4milk.net/).
39icons :: Mark James(http://www.famfamfam.com/)
40Ajax.History :: Siegfried Puchbauer <rails-spinoffs@lists.rubyonrails.org>
41SweetTitles :: Dustin Diaz (http://www.dustindiaz.com)
42*/
43
44// Protect the script from direct access
45if ( !defined('ABSPATH') ) {
46        header("Location: /");
47        exit();
48}
49
50// WP 1.5 comfortable
51if(!function_exists('is_admin')):
52function is_admin(){
53        return (strstr($_SERVER['PHP_SELF'], 'wp-admin/'));
54}
55endif;
56
57define('SLIMSTATPATH',  realpath( dirname( __FILE__ ) ) . '/');
58define('wp_slimstat_ex',  'wp_slimstat_ex');
59
60// include SlimStat config file
61include_once(SLIMSTATPATH . 'wp-slimstat-ex-config.php');
62
63// WP 2.1 always includes streams.php and gettext.php
64if ($wp_version < 2.1 && ( !defined(WPLANG) || '' == constant('WPLANG') )) {
65        include_once(ABSPATH . WPINC . '/streams.php');
66        include_once(ABSPATH . WPINC . '/gettext.php');
67}
68
69// localize plugin
70load_plugin_textdomain('wp-slimstat-ex', 'wp-content/plugins/'.dirname($SlimCfg->base).'/lang');
71
72class wp_slimstat_ex {
73
74        function admin_head() {
75                global $SlimCfg, $wp_version;
76                $load_js = "";
77                // Javascript
78                if($wp_version < 2.1 && $SlimCfg->option['use_ajax']) { // load js for before WP 2.1
79                        $js_before = '<script type="text/javascript" src="'.$SlimCfg->pluginURL.'/js/';
80                        $js_after = '"></script>'."\n";
81                        $load_js .= $js_before.'prototype.js?ver=1.5.0_rc0'.$js_after;
82                        $load_js .= $js_before.'moo.fx.js?ver=2.0'.$js_after;
83                        $load_js .= $js_before.'ajax.history.js?ver='.$SlimCfg->version.$js_after;
84//                      $load_js .= $js_before.'dhtmlHistory.js?ver='.$SlimCfg->version.$js_after;
85                        $load_js .= $js_before.'ajax-slimstat-proto.js?ver='.$SlimCfg->version.$js_after;
86                        if($SlimCfg->option['nice_titles']) {
87                                $load_js .= $js_before.'addEvent.js?ver='.$SlimCfg->version.$js_after;
88                                $load_js .= $js_before.'sweetTitles?ver='.$SlimCfg->version.$js_after;
89                        }
90                }
91                // CSS
92                $load_css = '<link rel="stylesheet" type="text/css" media="screen" href="'.$SlimCfg->pluginURL.'/css/slimstat.css?ver='.$SlimCfg->version.'" />';
93                $load_css .= ($SlimCfg->option['nice_titles'])?"\n".'<link rel="stylesheet" type="text/css" media="screen" href="'.$SlimCfg->pluginURL.'/css/sweetTitles.css?ver='.$SlimCfg->version.'" />':'';
94                // Print it
95                echo "\n".'<!-- Added by Wp-SlimStat-Ex '.$SlimCfg->version.' -->'."\n".$load_js.$load_css."\n";
96        }
97
98        function enqueue_script_admin() {
99                global $SlimCfg;
100                $src_path = $SlimCfg->pluginURL.'/js/';
101                wp_register_script('moo.fx', $src_path.'moo.fx.js', array('prototype'), '2.0');
102                wp_register_script('ajax.history', $src_path.'ajax.history.js', array('prototype'), $SlimCfg->version);
103                wp_enqueue_script('ajax-slimstat-proto', $src_path.'ajax-slimstat-proto.js', array('prototype', 'moo.fx','ajax.history'), $SlimCfg->version);
104                if($SlimCfg->option['nice_titles']) {
105                        wp_register_script('addEvent', $src_path.'addEvent.js', false, $SlimCfg->version);
106                        wp_enqueue_script('sweetTitles', $src_path.'sweetTitles.js', array('addEvent'), $SlimCfg->version);
107                }
108        }
109
110        function enqueue_script_blog() {
111                global $SlimCfg;
112                if(is_admin())
113                        return;
114                $js_path = $SlimCfg->pluginURL.'/js/';
115                switch($SlimCfg->option['blog_js']) {
116                        case 'prototype':
117                        default:
118                        wp_register_script('moo.fx', $js_path.'moo.fx.js', array('prototype'), '2.0');
119                        wp_enqueue_script('ajax-slimstat-proto', $js_path.'ajax-slimstat-proto.js', array('prototype', 'moo.fx'), $SlimCfg->version);
120                        break;
121                        case 'mootools':
122                        $depth = false;
123                        if(class_exists('wpInsertScripts')){ // wp-scripts plugins support
124                                $op = get_option('wp_scripts');
125                                $depth = ($op['baselib'] == 'mootools' && $op['moo_ver'])?array('mootools-Effects', 'mootools-Remote'):$depth;
126                        }
127                        wp_enqueue_script('ajax-slimstat-moo', $js_path.'ajax-slimstat-moo.js', $depth, $SlimCfg->version);
128                        break;
129                }
130        }
131
132        function admin_footer() {
133                global $SlimCfg;
134                $script = '<script type="text/javascript"><!--'."\n";
135                // use dhtmHistory for ajax history
136/*              $script .= 'function initdhtmlHistory() {';
137                $script .= '    dhtmlHistory.initialize();';
138                $script .= '    dhtmlHistory.addListener(function(hash){SlimStat.ajax(hash);});';
139                $script .= '    SlimStat.panel('1');';
140                $script .= '}';
141                $script .= 'var SlimStatLoader = initdhtmlHistory();'."\n";*/
142                // use Ajax.History for ajax history
143                $script .= 'var historyHandler = Ajax.History.initialize({'."\n\t";
144                $script .= 'callback: function(hash){SlimStat.ajax(hash);},'."\n\t";
145                $script .= 'iframeSrc: "'.$SlimCfg->pluginURL.'/js/_blank.html"});'."\n";
146                $script .= 'var SlimStatLoader = SlimStat.panel(\'1\');'."\n";
147                $script .= '//--!></script>'."\n";
148                echo $script;
149        }
150
151        function wp_head() {
152                global $SlimCfg, $wp_version;
153                $load_js = '';
154                // Javascript
155                if($wp_version < 2.1 && $SlimCfg->option['blog_stats'] && $SlimCfg->option['blog_js'] !== 'none') {
156                        $js_before = '<script type="text/javascript" src="'.$SlimCfg->pluginURL.'/js/';
157                        $js_after = '"></script>'."\n\t";
158                        $load_js = $js_before.'ajax-slimstat-'.(($SlimCfg->option['blog_js'] == 'mootools')?'moo':'proto').'.js?ver='.$SlimCfg->version.$js_after;
159                        $load_js .= ($SlimCfg->option['blog_js'] == 'prototype')?$js_before.'moo.fx.js?ver=2.0'.$js_after:'';
160                }
161                // CSS
162                $load_css = '<link rel="stylesheet" type="text/css" media="screen" href="'.$SlimCfg->pluginURL.'/css/slimstat-blog.css.php'.((!$SlimCfg->option['blog_stats'])?'?load=simple':'').'" />';
163                // Print it
164                echo "\n\t".'<!-- Added by Wp-SlimStat-Ex '.$SlimCfg->version.' -->'."\n\t".$load_js.$load_css."\n";
165        }
166
167        function option_page() {
168                global $SlimCfg;
169                if (function_exists('add_options_page')) {
170                        add_options_page("SlimStat", "SlimStat", 9, dirname(__FILE__).'/wp-slimstat-ex-options.php');
171                }
172        }
173
174        function is_slimstat_page () {
175                global $SlimCfg;
176                return (strpos($_GET['page'], $SlimCfg->base) !== false);
177        }
178
179        function _createSlimTable($table = 'stats', $check_only = false) {
180            global $wpdb, $SlimCfg;
181
182                switch($table) {
183                        case 'country':
184                                $createTable = $SlimCfg->table_countries;
185                                $myTableStatsQuery = "CREATE TABLE `$createTable` (
186                                        `ip_from` int(10) unsigned default 0,
187                                        `ip_to` int(10) unsigned default 0,
188                                        `country_code` char(2) default '',
189                                        KEY `ip_from_to_idx` (`ip_from`,`ip_to`)
190                                        )";
191                                break;
192                        case 'feed':
193                                $createTable = $SlimCfg->table_feed;
194                                $myTableStatsQuery = "CREATE TABLE `$createTable` (
195                                        `id` int(11) unsigned NOT NULL auto_increment,
196                                        `remote_ip` int unsigned default 0,
197                                        `language` varchar(5) default '',
198                                        `country` varchar(2) default '',
199                                        `domain` varchar(255) default '',
200                                        `referer` varchar(255) default '',
201                                        `searchterms` varchar(255) default '',
202                                        `resource` varchar(255) default '',
203                                        `platform` TINYINT default -1,
204                                        `browser` SMALLINT default -1,
205                                        `version` varchar(15) default '',
206                                        `visit` int(10) unsigned NOT NULL default '0',
207                                        `dt` int(10) unsigned default 0,
208                                        UNIQUE KEY `id` (`id`),
209                                        KEY `searchterms` (`searchterms`),
210                                        KEY `visit` (`visit`),
211                                        KEY `resource_total` (`resource`, `dt`),
212                                        KEY `dt_total` (`dt`,`remote_ip`)
213                                        ) PACK_KEYS=1 ";
214                                break;
215                        case 'date':
216                                $createTable = $SlimCfg->table_dt;
217                                $myTableStatsQuery = "CREATE TABLE `$createTable` (
218                                        `dt_start` int(10) unsigned NOT NULL default 0,
219                                        `dt_end` int(10) unsigned NOT NULL default 0,
220                                        `hits` int(10) unsigned NOT NULL default 0,
221                                        `visits` int(10) unsigned NOT NULL default 0,
222                                        `uniques` int(10) unsigned NOT NULL default 0,
223                                        `type` smallint(2) unsigned NOT NULL default 0,
224                                        KEY `dt_total` (`dt_start`, `dt_end`, `type`)
225                                        )";
226                                break;
227                        case 'pins':
228                                $createTable = $SlimCfg->table_pins;
229                                $myTableStatsQuery = "CREATE TABLE `$createTable` (
230                                        `id` int(11) unsigned NOT NULL auto_increment,
231                                        `name` tinytext NOT NULL,
232                                        `title` tinytext default '',
233                                        `author` tinytext NOT NULL,
234                                        `url` varchar(200) NOT NULL default '',
235                                        `text` varchar(255) default '',
236                                        `modules` longtext NOT NULL,
237                                        `version` varchar(15) default '',
238                                        `active` int(1) NOT NULL default 0,
239                                        UNIQUE KEY `id` (`id`)
240                                        )";
241                                break;
242                        case 'stats': default:
243                                $createTable = $SlimCfg->table_stats;
244                                $myTableStatsQuery = "CREATE TABLE `$createTable` (
245                                        `id` int(11) unsigned NOT NULL auto_increment,
246                                        `remote_ip` int unsigned default 0,
247                                        `language` varchar(5) default '',
248                                        `country` varchar(2) default '',
249                                        `domain` varchar(255) default '',
250                                        `referer` varchar(255) default '',
251                                        `searchterms` varchar(255) default '',
252                                        `resource` varchar(255) default '',
253                                        `platform` TINYINT default -1,
254                                        `browser` SMALLINT default -1,
255                                        `version` varchar(15) default '',
256                                        `visit` int(10) unsigned NOT NULL default '0',
257                                        `dt` int(10) unsigned NOT NULL default '0',
258                                        UNIQUE KEY `id` (`id`),
259                                        KEY `referer` (`referer`),
260                                        KEY `country` (`country`),
261                                        KEY `searchterms` (`searchterms`),
262                                        KEY `visit` (`visit`),
263                                        KEY `resource_total` (`resource`, `dt`),
264                                        KEY `dt_total` (`dt`,`remote_ip`)
265                                        ) PACK_KEYS=1" ;
266                                break;
267                }
268                // This is the schema for data about visits.
269
270                if(!$check_only) {
271                        // Check if table is already there
272                        foreach ($wpdb->get_col("SHOW TABLES", 0) as $table ) {
273                                if ($table == $createTable) {
274                                        return false;
275                                }
276                        }
277
278                        // Ok, let's proceed
279                        if ( $wpdb->query( $myTableStatsQuery ) === false ) {
280                                return false;
281                        }
282                }
283                // Just to be sure, we check that tables were actually created
284                foreach ( $wpdb->get_col("SHOW TABLES", 0) as $table ) {
285                        if ( $table == $createTable ) {
286                                return true;
287                        }
288                }
289                return false;
290        }
291        // end createSlimTable
292
293        function _importCountriesData() {
294                global $wpdb, $SlimCfg;
295
296                $myCountryFile = "wp-slimstat.csv";
297
298                // To avoid problems with SAFE_MODE, we will not use is_file
299                // of file_exists, but a loop through current directory
300                $isCountryFile = false;
301                $myFileHandle = opendir(dirname(__FILE__));
302                while ( false !== ($myFileName = readdir($myFileHandle)) && !$isCountryFile ) {
303                        if ( $myCountryFile == $myFileName ) {
304                                $isCountryFile = true;
305                        }
306                }
307                closedir($myFileHandle);
308
309                // If there is already a (not empty) country table, skip import
310                $myCountryRows = $wpdb->get_var("SELECT COUNT(*) FROM `$SlimCfg->table_countries`", 0);
311                if ( $myCountryRows > 0 && $myCountryRows !== false ) {
312                        return false;
313                }
314
315                // Import file, if exists
316                if ( $isCountryFile ) {
317                        // Allow plenty of time for this to happen
318                        @set_time_limit( 180 ); 
319
320                        // Remove all the rows
321                        $myQuery = "TRUNCATE `$SlimCfg->table_countries`";
322
323                        if ( $wpdb->query( $myQuery ) === false ) {
324                                return false;
325                        }
326
327                        $myCountryDataStr = "";
328                        $fd = fopen( dirname(__FILE__)."/".$myCountryFile, "r" );
329
330                        while ( !feof( $fd ) ) {
331                                $myCountryDataStr .= fread( $fd, 4096 );
332                                $myStringToSplit = strrev( strstr( strrev( $myCountryDataStr ), "\n" ) );
333                                $myCountryDataStr = substr( $myCountryDataStr, strlen( $myStringToSplit ) );
334                                $myCountryDataArray = explode( "\n", $myStringToSplit );
335                                foreach ( $myCountryDataArray as $aCountryDatum ) {
336                                        $fields = explode( ",", $aCountryDatum, 3 );
337                                        if ( sizeof( $fields ) == 3 ) {
338                                                $myQuery = 
339                                                        "INSERT INTO `$SlimCfg->table_countries` (
340                                                                `ip_from`, `ip_to`, `country_code` )
341                                                                VALUES ( \"".implode( "\", \"", $fields )."\" 
342                                                        )";
343
344                                                        $wpdb->query( $myQuery );
345                                        }
346                                }
347                        }
348                        fclose( $fd );
349                        return true;
350                }
351                else return false;
352
353        } 
354        // end importCountriesData
355
356        function setup() { 
357                // set options if not exists
358                if(!get_option('wp_slimstat_ex')) {
359                        $options['tracking'] = 1;
360                        $options['usepins'] = 1;
361                        $options['cachelimit'] = 0;
362                        $options['guesstitle'] = 1;
363                        $options['dbmaxage'] = 0;
364                        $options['limitrows'] = 30;
365                        $options['iptohost'] = 0;
366                        $options['whois'] = 1;
367                        $options['meta'] = 0;
368                        $options['visit_type'] = 'uniques';
369                        $options['count_type'] = 'hits';
370                        $options['stats_type'] = 'all';
371                        $options['time_offset'] = 0;
372                        $options['ignore'] = "";
373                        $options['use_ajax'] = 1;
374                        $options['blog_stats'] = 0;
375                        $options['blog_js'] = 'none';
376                        $options['nice_titles'] = 1;
377                        add_option('wp_slimstat_ex', $options);
378                }
379
380                $isStatsCreated = wp_slimstat_ex::_createSlimTable('stats');
381                $isFeedCreated = wp_slimstat_ex::_createSlimTable('feed');
382                $isDtCreated = wp_slimstat_ex::_createSlimTable('date');
383                $isPinCreated = wp_slimstat_ex::_createSlimTable('pins');
384
385                if ($SlimCfg->external_iptc !== 'external')
386                        $isCountriesCreated = wp_slimstat_ex::_createSlimTable('country');
387
388                // Now import data for "country to ip" conversion
389                if ( $isCountriesCreated && $SlimCfg->external_iptc !== 'external' ) {
390                        wp_slimstat_ex::_importCountriesData();
391                }
392        }// end setup
393
394}
395// end of class wp_slimstat_ex
396
397/* Setup, Option Page, Load CSS & Javascripts
398-------------------------------------------*/
399// setup WP-SlimStat-Ex
400if($wp_version < 2) {
401        if (isset($_GET['activate']) && $_GET['activate'] == 'true') {
402                add_action( 'init', array( 'wp_slimstat_ex', 'setup' ) );
403        }
404} else {
405        add_action('activate_'.$SlimCfg->_basename(__FILE__), array('wp_slimstat_ex', 'setup'));
406}
407// load css and js on admin panel
408if (wp_slimstat_ex::is_slimstat_page()) {
409        add_action('admin_head', array('wp_slimstat_ex', 'admin_head'), 20);
410        if($SlimCfg->option['use_ajax']) {
411                add_action('admin_footer', array('wp_slimstat_ex', 'admin_footer'));
412                if($wp_version >= 2.1)
413                        add_action('init', array('wp_slimstat_ex', 'enqueue_script_admin'));
414        }
415}
416// option page
417add_action('admin_menu', array('wp_slimstat_ex', 'option_page'));
418// load js and css on blog
419if($SlimCfg->option['blog_stats'] || $SlimCfg->option['meta']) 
420        add_action('wp_head', array('wp_slimstat_ex', 'wp_head'), 20);
421if($wp_version >= 2.1 && $SlimCfg->option['blog_stats'] && $SlimCfg->option['blog_js'] !== 'none')
422        add_action('wp_print_scripts', array('wp_slimstat_ex', 'enqueue_script_blog'));
423
424/* Tracking
425-------------------------------------------*/
426include_once(SLIMSTATPATH . 'lib/track.php');
427add_action( 'shutdown', array( &$SSTrack, 'slimtrack' ) );
428
429/* Include libs
430-------------------------------------------*/
431require_once(SLIMSTATPATH . 'lib/functions.php');
432
433if(is_admin()) {
434        require_once(SLIMSTATPATH . 'lib/display.php');
435
436        /* Stats Display
437        -------------------------------------------*/
438        $wpSSDisplay =& SSDisplay::get_instance();
439        add_action('admin_menu', array(&$wpSSDisplay,'add_tab'));
440        unset($wpSSDisplay);
441}
442
443if($SlimCfg->option['meta']) {
444        add_action('wp_meta', array('SSFunction', 'simple_hvu'));
445}
446
447/* Print Stats on Blog
448------------------------------------------------------------------------*/
449
450function wpSSBlogStats($IDs = array(1,2,3), $echo = true) {
451        global $SlimCfg, $wpdb;
452        if(is_array($IDs) && !empty($IDs)) {
453                if($SlimCfg->option['blog_js'] == 'none' || !$SlimCfg->option['blog_js'])
454                        $SlimCfg->option['use_ajax'] = false; // instance option
455                require_once(SLIMSTATPATH . 'lib/modules.php');
456                require_once(SLIMSTATPATH . 'lib/pins.php');
457                $wrapper = '<a id="ajax_request" href="'.$SlimCfg->ajaxReq.'"></a>';
458                $wrapper .= '<a id="slm2" name="slm2"></a>'."\n";
459                $wrapper .= '<div id="wp_slimstat">'."\n";
460                $nav = '<p class="module_nav">'.__('Modules', 'wp-slimstat-ex').' : ';
461                $output = '';
462                foreach($IDs as $id) {
463                        $module = SSFunction::id2module($id);
464                        if($module) {
465                                $output .= call_user_func(array('SSModule', $module), '(1 = 1)');
466                                $nav .= '[ <a href="#module_'.$id.'">'.SSFunction::get_title($id).'</a> ] ';
467                        } elseif($id > 10000) {
468                                $pinid = floor($id/100) - 100;
469                                $mo = $id - (($pinid+100)*100) - 1;
470                                $pin = SSFunction::pin_mod_info($pinid);
471                                if($pin && isset($pin['modules'][$mo])) {
472                                        $file = SLIMSTATPATH . 'pins/'. $pin['name'] . '/pin.php';
473                                        require_once($file);
474                                        eval('$'.$pin["name"].' =& new $pin["name"]();'."\n");
475                                        eval('$output .= $'.$pin["name"].'->'.$pin["modules"][$mo]["name"].'(\'(1 = 1)\');'."\n");
476                                        $nav .= '[ <a href="#module_'.$id.'">'.$pin["modules"][$mo]["title"].'</a> ] ';
477                                } else 
478                                        $output .= '<p>Wrong module ID '.$id.'</p>';
479                        }
480                } 
481                $nav .= '<span id="slimloading"> ( Loading... ) </span>';
482                $nav .= '</p>';
483        $wrapper .= $nav.$output.'</div>';
484        if($echo) 
485                echo $wrapper;
486        else 
487                return $wrapper;
488        }
489}
490
491if($SlimCfg->option['blog_stats']) :
492
493function wpSSBlogStats_Replace($m) {
494        $m = trim($m[2]);
495        if(empty($m))
496                $IDs = array(1,2,3);
497        else 
498                $IDs = explode(',', str_replace(array('|', ' '), '', $m));
499        return wpSSBlogStats($IDs, false);
500}
501
502function wpSSBlogStats_Filter($content) {
503        return preg_replace_callback('/(<p>)*\s*{SLIMSTAT(.*?)}\s*\n*(<\/p>)*/', 'wpSSBlogStats_Replace', $content);
504}
505
506add_filter('the_content', 'wpSSBlogStats_Filter', 10);
507
508endif; // if opiton['blog_stats']
509
510function print_simple_hvu($wrap="") {
511        SSFunction::simple_hvu($wrap);
512}
513
514?>
Note: See TracBrowser for help on using the browser.