PageRenderTime 40ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 0ms

/data/plugins/statistics/includes/functions/functions.php

https://bitbucket.org/lpservice-it/ljmc
PHP | 1025 lines | 618 code | 259 blank | 148 comment | 141 complexity | 807e7861116df367defbe0d26f3521f9 MD5 | raw file
Possible License(s): Apache-2.0, GPL-3.0, MIT
  1. <?php
  2. /*
  3. This is the primary set of functions used to calculate the statistics, they are available for other developers to call.
  4. NOTE: Many of the functions return an MySQL result object, using this object like a variable (ie. echo $result) will output
  5. the number of rows returned, but you can also use it an a foreach loop to to get the details of the rows.
  6. */
  7. // This function returns the current users online.
  8. function ljmc_statistics_useronline() {
  9. global $ljmcdb;
  10. return $ljmcdb->query("SELECT * FROM {$ljmcdb->prefix}statistics_useronline");
  11. }
  12. // This function get the visit statistics for a given time frame.
  13. function ljmc_statistics_visit($time, $daily = null) {
  14. // We need database and the global $LJMC_Statistics object access.
  15. global $ljmcdb, $LJMC_Statistics;
  16. // If we've been asked to do a daily count, it's a slightly different SQL query, so handle it separately.
  17. if( $daily == true ) {
  18. // Fetch the results from the database.
  19. $result = $ljmcdb->get_row("SELECT * FROM {$ljmcdb->prefix}statistics_visit WHERE `last_counter` = '{$LJMC_Statistics->Current_Date('Y-m-d', $time)}'");
  20. // If we have a result, return it, otherwise force a 0 to be returned instead of the logical FALSE that would otherwise be the case.
  21. if( $result) {
  22. return $result->visit;
  23. } else {
  24. return 0;
  25. }
  26. } else {
  27. // This function accepts several options for time parameter, each one has a unique SQL query string.
  28. // They're pretty self explanatory.
  29. switch($time) {
  30. case 'today':
  31. $result = $ljmcdb->get_var("SELECT SUM(visit) FROM {$ljmcdb->prefix}statistics_visit WHERE `last_counter` = '{$LJMC_Statistics->Current_Date('Y-m-d')}'");
  32. break;
  33. case 'yesterday':
  34. $result = $ljmcdb->get_var("SELECT SUM(visit) FROM {$ljmcdb->prefix}statistics_visit WHERE `last_counter` = '{$LJMC_Statistics->Current_Date('Y-m-d', -1)}'");
  35. break;
  36. case 'week':
  37. $result = $ljmcdb->get_var("SELECT SUM(visit) FROM {$ljmcdb->prefix}statistics_visit WHERE `last_counter` BETWEEN '{$LJMC_Statistics->Current_Date('Y-m-d', -7)}' AND '{$LJMC_Statistics->Current_Date('Y-m-d')}'");
  38. break;
  39. case 'month':
  40. $result = $ljmcdb->get_var("SELECT SUM(visit) FROM {$ljmcdb->prefix}statistics_visit WHERE `last_counter` BETWEEN '{$LJMC_Statistics->Current_Date('Y-m-d', -30)}' AND '{$LJMC_Statistics->Current_Date('Y-m-d')}'");
  41. break;
  42. case 'year':
  43. $result = $ljmcdb->get_var("SELECT SUM(visit) FROM {$ljmcdb->prefix}statistics_visit WHERE `last_counter` BETWEEN '{$LJMC_Statistics->Current_Date('Y-m-d', -360)}' AND '{$LJMC_Statistics->Current_Date('Y-m-d')}'");
  44. break;
  45. case 'total':
  46. $result = $ljmcdb->get_var("SELECT SUM(visit) FROM {$ljmcdb->prefix}statistics_visit");
  47. $result += $LJMC_Statistics->Get_Historical_Data( 'visits' );
  48. break;
  49. default:
  50. $result = $ljmcdb->get_var("SELECT SUM(visit) FROM {$ljmcdb->prefix}statistics_visit WHERE `last_counter` BETWEEN '{$LJMC_Statistics->Current_Date('Y-m-d', $time)}' AND '{$LJMC_Statistics->Current_Date('Y-m-d')}'");
  51. break;
  52. }
  53. }
  54. // If we have a result, return it, otherwise force a 0 to be returned instead of the logical FALSE that would otherwise be the case.
  55. if( $result == null ) { $result = 0; }
  56. return $result;
  57. }
  58. // This function gets the visitor statistics for a given time frame.
  59. function ljmc_statistics_visitor($time, $daily = null, $countonly = false) {
  60. // We need database and the global $LJMC_Statistics object access.
  61. global $ljmcdb, $LJMC_Statistics;
  62. $history = 0;
  63. $select = '*';
  64. $sqlstatement = '';
  65. // We often don't need the complete results but just the count of rows, if that's the case, let's have MySQL just count the results for us.
  66. if( $countonly == true ) { $select = 'count(last_counter)'; }
  67. // If we've been asked to do a daily count, it's a slightly different SQL query, so handle it seperatly.
  68. if( $daily == true ) {
  69. // Fetch the results from the database.
  70. $result = $ljmcdb->query( "SELECT {$select} FROM {$ljmcdb->prefix}statistics_visitor WHERE `last_counter` = '{$LJMC_Statistics->Current_Date('Y-m-d', $time)}'");
  71. return $result;
  72. } else {
  73. // This function accepts several options for time parameter, each one has a unique SQL query string.
  74. // They're pretty self explanatory.
  75. switch($time) {
  76. case 'today':
  77. $sqlstatement = "SELECT {$select} FROM {$ljmcdb->prefix}statistics_visitor WHERE `last_counter` = '{$LJMC_Statistics->Current_Date('Y-m-d')}'";
  78. break;
  79. case 'yesterday':
  80. $sqlstatement = "SELECT {$select} FROM {$ljmcdb->prefix}statistics_visitor WHERE `last_counter` = '{$LJMC_Statistics->Current_Date('Y-m-d', -1)}'";
  81. break;
  82. case 'week':
  83. $sqlstatement = "SELECT {$select} FROM {$ljmcdb->prefix}statistics_visitor WHERE `last_counter` BETWEEN '{$LJMC_Statistics->Current_Date('Y-m-d', -7)}' AND '{$LJMC_Statistics->Current_Date('Y-m-d')}'";
  84. break;
  85. case 'month':
  86. $sqlstatement = "SELECT {$select} FROM {$ljmcdb->prefix}statistics_visitor WHERE `last_counter` BETWEEN '{$LJMC_Statistics->Current_Date('Y-m-d', -30)}' AND '{$LJMC_Statistics->Current_Date('Y-m-d')}'";
  87. break;
  88. case 'year':
  89. $sqlstatement = "SELECT {$select} FROM {$ljmcdb->prefix}statistics_visitor WHERE `last_counter` BETWEEN '{$LJMC_Statistics->Current_Date('Y-m-d', -365)}' AND '{$LJMC_Statistics->Current_Date('Y-m-d')}'";
  90. break;
  91. case 'total':
  92. $sqlstatement = "SELECT {$select} FROM {$ljmcdb->prefix}statistics_visitor";
  93. $history = $LJMC_Statistics->Get_Historical_Data( 'visitors' );
  94. break;
  95. default:
  96. $sqlstatement = "SELECT {$select} FROM {$ljmcdb->prefix}statistics_visitor WHERE `last_counter` BETWEEN '{$LJMC_Statistics->Current_Date('Y-m-d', $time)}' AND '{$LJMC_Statistics->Current_Date('Y-m-d')}'";
  97. break;
  98. }
  99. }
  100. // Execute the SQL call, if we're only counting we can use get_var(), otherwise we use query().
  101. if( $countonly == true ) {
  102. $result = $ljmcdb->get_var( $sqlstatement );
  103. $result += $history;
  104. }
  105. else {
  106. $result = $ljmcdb->query( $sqlstatement );
  107. }
  108. return $result;
  109. }
  110. // This function returns the statistics for a given page.
  111. function ljmc_statistics_pages($time, $page_uri = '', $id = -1) {
  112. // We need database and the global $LJMC_Statistics object access.
  113. global $ljmcdb, $LJMC_Statistics;
  114. $history = 0;
  115. $sqlstatement = '';
  116. // If no page URI has been passed in, get the current page URI.
  117. if( $page_uri == '' ) { $page_uri = ljmc_statistics_get_uri(); }
  118. $page_uri_sql = esc_sql( $page_uri );
  119. // If a page/post ID has been passed, use it to select the rows, otherwise use the URI.
  120. // Note that a single page/post ID can have multiple URI's associated with it.
  121. if( $id != -1 ) {
  122. $page_sql = '`id` = ' . $id;
  123. $history_key = 'page';
  124. $history_id = $id;
  125. } else {
  126. $page_sql = "`URI` = '{$page_uri_sql}'";
  127. $history_key = 'uri';
  128. $history_id = $page_uri;
  129. }
  130. // This function accepts several options for time parameter, each one has a unique SQL query string.
  131. // They're pretty self explanatory.
  132. switch($time) {
  133. case 'today':
  134. $sqlstatement = "SELECT SUM(count) FROM {$ljmcdb->prefix}statistics_pages WHERE `date` = '{$LJMC_Statistics->Current_Date('Y-m-d')}' AND {$page_sql}";
  135. break;
  136. case 'yesterday':
  137. $sqlstatement = "SELECT SUM(count) FROM {$ljmcdb->prefix}statistics_pages WHERE `date` = '{$LJMC_Statistics->Current_Date('Y-m-d', -1)}' AND {$page_sql}";
  138. break;
  139. case 'week':
  140. $sqlstatement = "SELECT SUM(count) FROM {$ljmcdb->prefix}statistics_pages WHERE `date` BETWEEN '{$LJMC_Statistics->Current_Date('Y-m-d', -7)}' AND '{$LJMC_Statistics->Current_Date('Y-m-d')}' AND {$page_sql}";
  141. break;
  142. case 'month':
  143. $sqlstatement = "SELECT SUM(count) FROM {$ljmcdb->prefix}statistics_pages WHERE `date` BETWEEN '{$LJMC_Statistics->Current_Date('Y-m-d', -30)}' AND '{$LJMC_Statistics->Current_Date('Y-m-d')}' AND {$page_sql}";
  144. break;
  145. case 'year':
  146. $sqlstatement = "SELECT SUM(count) FROM {$ljmcdb->prefix}statistics_pages WHERE `date` BETWEEN '{$LJMC_Statistics->Current_Date('Y-m-d', -365)}' AND '{$LJMC_Statistics->Current_Date('Y-m-d')}' AND {$page_sql}";
  147. break;
  148. case 'total':
  149. $sqlstatement = "SELECT SUM(count) FROM {$ljmcdb->prefix}statistics_pages WHERE {$page_sql}";
  150. $history = $LJMC_Statistics->Get_Historical_Data( $history_key, $history_id );
  151. break;
  152. default:
  153. $sqlstatement = "SELECT SUM(count) FROM {$ljmcdb->prefix}statistics_pages WHERE `date` = '{$LJMC_Statistics->Current_Date('Y-m-d', $time)}' AND {$page_sql}";
  154. break;
  155. }
  156. // Since this function only every returns a count, just use get_var().
  157. $result = $ljmcdb->get_var( $sqlstatement );
  158. $result += $history;
  159. // If we have an empty result, return 0 instead of a blank.
  160. if( $result == '' ) { $result = 0; }
  161. return $result;
  162. }
  163. // This function converts a page URI to a page/post ID. It does this by looking up in the pages database
  164. // the URI and getting the associated ID. This will only work if the page has been visited at least once.
  165. function ljmc_statistics_uri_to_id( $uri ) {
  166. global $ljmcdb;
  167. // Create the SQL query to use.
  168. $sqlstatement = $ljmcdb->prepare( "SELECT id FROM {$ljmcdb->prefix}statistics_pages WHERE `URI` = %s AND id > 0", $uri );
  169. // Execute the query.
  170. $result = $ljmcdb->get_var( $sqlstatement );
  171. // If we returned a false or some other 0 equivalent value, make sure $result is set to an integer 0.
  172. if( $result == 0 ) { $result = 0; }
  173. return $result;
  174. }
  175. // We need a quick function to pass to usort to properly sort the most popular pages.
  176. function ljmc_stats_compare_uri_hits($a, $b) {
  177. return $a[1] < $b[1];
  178. }
  179. // This function returns a multi-dimensional array, with the total number of pages and an array or URI's sorted in order with their URI, count, id and title.
  180. function ljmc_statistics_get_top_pages() {
  181. global $ljmcdb;
  182. // Get every unique URI from the pages database.
  183. $result = $ljmcdb->get_results( "SELECT DISTINCT uri FROM {$ljmcdb->prefix}statistics_pages", ARRAY_N );
  184. $total = 0;
  185. $uris = array();
  186. // Now get the total page visit count for each unique URI.
  187. foreach( $result as $out ) {
  188. // Increment the total number of results.
  189. $total ++;
  190. // Retreive the post ID for the URI.
  191. $id = ljmc_statistics_uri_to_id( $out[0] );
  192. // Lookup the post title.
  193. $post = get_post($id);
  194. if( is_object( $post ) ) {
  195. $title = $post->post_title;
  196. }
  197. else {
  198. if( $out[0] == '/' ) {
  199. $title = get_bloginfo();
  200. }
  201. else {
  202. $title = '';
  203. }
  204. }
  205. // Add the current post to the array.
  206. $uris[] = array( $out[0], ljmc_statistics_pages( 'total', $out[0] ), $id, $title );
  207. }
  208. // If we have more than one result, let's sort them using usort.
  209. if( count( $uris ) > 1 ) {
  210. // Sort the URI's based on their hit count.
  211. usort( $uris, 'ljmc_stats_compare_uri_hits');
  212. }
  213. return array( $total, $uris );
  214. }
  215. // This function gets the current page URI.
  216. function ljmc_statistics_get_uri() {
  217. // Get the site's path from the URL.
  218. $site_uri = parse_url( site_url(), PHP_URL_PATH );
  219. // Get the current page URI.
  220. $page_uri = $_SERVER["REQUEST_URI"];
  221. // Strip the site's path from the URI.
  222. $page_uri = str_ireplace( $site_uri, '', $page_uri );
  223. // If we're at the root (aka the URI is blank), let's make sure to indicate it.
  224. if( $page_uri == '' ) { $page_uri = '/'; }
  225. return $page_uri;
  226. }
  227. // This function returns all unique user agents in the database.
  228. function ljmc_statistics_ua_list() {
  229. global $ljmcdb;
  230. $result = $ljmcdb->get_results("SELECT DISTINCT agent FROM {$ljmcdb->prefix}statistics_visitor", ARRAY_N);
  231. $Browers = array();
  232. foreach( $result as $out )
  233. {
  234. $Browsers[] = $out[0];
  235. }
  236. return $Browsers;
  237. }
  238. // This function returns the count of a given user agent in the database.
  239. function ljmc_statistics_useragent($agent) {
  240. global $ljmcdb;
  241. $result = $ljmcdb->get_var("SELECT COUNT(agent) FROM {$ljmcdb->prefix}statistics_visitor WHERE `agent` = '$agent'");
  242. return $result;
  243. }
  244. // This function returns all unique platform types from the database.
  245. function ljmc_statistics_platform_list() {
  246. global $ljmcdb;
  247. $result = $ljmcdb->get_results("SELECT DISTINCT platform FROM {$ljmcdb->prefix}statistics_visitor", ARRAY_N);
  248. $Platforms = array();
  249. foreach( $result as $out )
  250. {
  251. $Platforms[] = $out[0];
  252. }
  253. return $Platforms;
  254. }
  255. // This function returns the count of a given platform in the database.
  256. function ljmc_statistics_platform($platform) {
  257. global $ljmcdb;
  258. $result = $ljmcdb->get_var("SELECT COUNT(platform) FROM {$ljmcdb->prefix}statistics_visitor WHERE `platform` = '$platform'");
  259. return $result;
  260. }
  261. // This function returns all unique versions for a given agent from the database.
  262. function ljmc_statistics_agent_version_list($agent) {
  263. global $ljmcdb;
  264. $result = $ljmcdb->get_results("SELECT DISTINCT version FROM {$ljmcdb->prefix}statistics_visitor WHERE agent = '$agent'", ARRAY_N);
  265. $Versions = array();
  266. foreach( $result as $out )
  267. {
  268. $Versions[] = $out[0];
  269. }
  270. return $Versions;
  271. }
  272. // This function returns the statistcs for a given agent/version pair from the database.
  273. function ljmc_statistics_agent_version($agent, $version) {
  274. global $ljmcdb;
  275. $result = $ljmcdb->get_var("SELECT COUNT(version) FROM {$ljmcdb->prefix}statistics_visitor WHERE agent = '$agent' AND version = '$version'");
  276. return $result;
  277. }
  278. // This function returns an array or array's which define what search engines we should look for.
  279. //
  280. // By default will only return ones that have not been disabled by the user, this can be overridden by the $all parameter.
  281. //
  282. // Each sub array is made up of the following items:
  283. // name = The proper name of the search engine
  284. // translated = The proper name translated to the local language
  285. // tag = a short one word, all lower case, representation of the search engine
  286. // sqlpattern = either a single SQL style search pattern OR an array or search patterns to match the hostname in a URL against
  287. // regexpattern = either a single regex style search pattern OR an array or search patterns to match the hostname in a URL against
  288. // querykey = the URL key that contains the search string for the search engine
  289. // image = the name of the image file to associate with this search engine (just the filename, no path info)
  290. //
  291. function ljmc_statistics_searchengine_list( $all = false ) {
  292. GLOBAL $LJMC_Statistics;
  293. $default = $engines = array (
  294. 'ask' => array( 'name' => 'Ask.com', 'translated' => __('Ask.com', 'ljmc_statistics'), 'tag' => 'ask', 'sqlpattern' => '%ask.com%', 'regexpattern' => 'ask\.com', 'querykey' => 'q', 'image' => 'ask.png' ),
  295. 'baidu' => array( 'name' => 'Baidu', 'translated' => __('Baidu', 'ljmc_statistics'), 'tag' => 'baidu', 'sqlpattern' => '%baidu.com%', 'regexpattern' => 'baidu\.com', 'querykey' => 'wd', 'image' => 'baidu.png' ),
  296. 'bing' => array( 'name' => 'Bing', 'translated' => __('Bing', 'ljmc_statistics'), 'tag' => 'bing', 'sqlpattern' => '%bing.com%', 'regexpattern' => 'bing\.com', 'querykey' => 'q', 'image' => 'bing.png' ),
  297. 'clearch' => array( 'name' => 'clearch.org', 'translated' => __('clearch.org', 'ljmc_statistics'), 'tag' => 'clearch', 'sqlpattern' => '%clearch.org%', 'regexpattern' => 'clearch\.org', 'querykey' => 'q', 'image' => 'clearch.png' ),
  298. 'duckduckgo' => array( 'name' => 'DuckDuckGo', 'translated' => __('DuckDuckGo', 'ljmc_statistics'), 'tag' => 'duckduckgo', 'sqlpattern' => array('%duckduckgo.com%', '%ddg.gg%'), 'regexpattern' => array('duckduckgo\.com','ddg\.gg'), 'querykey' => 'q', 'image' => 'duckduckgo.png' ),
  299. 'google' => array( 'name' => 'Google', 'translated' => __('Google', 'ljmc_statistics'), 'tag' => 'google', 'sqlpattern' => '%google.%', 'regexpattern' => 'google\.', 'querykey' => 'q', 'image' => 'google.png' ),
  300. 'yahoo' => array( 'name' => 'Yahoo!', 'translated' => __('Yahoo!', 'ljmc_statistics'), 'tag' => 'yahoo', 'sqlpattern' => '%yahoo.com%', 'regexpattern' => 'yahoo\.com', 'querykey' => 'p', 'image' => 'yahoo.png' ),
  301. 'yandex' => array( 'name' => 'Yandex', 'translated' => __('Yandex', 'ljmc_statistics'), 'tag' => 'yandex', 'sqlpattern' => '%yandex.ru%', 'regexpattern' => 'yandex\.ru', 'querykey' => 'text', 'image' => 'yandex.png' )
  302. );
  303. if( $all == false ) {
  304. foreach( $engines as $key => $engine ) {
  305. if( $LJMC_Statistics->get_option( 'disable_se_' . $engine['tag'] ) ) { unset( $engines[$key] ); }
  306. }
  307. // If we've disabled all the search engines, reset the list back to default.
  308. if( count( $engines ) == 0 ) { $engines = $default; }
  309. }
  310. return $engines;
  311. }
  312. // This function will return the SQL WHERE clause for getting the search words for a given search engine.
  313. function ljmc_statistics_searchword_query ($search_engine = 'all') {
  314. GLOBAL $LJMC_Statistics;
  315. // Get a complete list of search engines
  316. $searchengine_list = ljmc_statistics_searchengine_list();
  317. $search_query = '';
  318. if( $LJMC_Statistics->get_option('search_converted') ) {
  319. // Are we getting results for all search engines or a specific one?
  320. if( strtolower($search_engine) == 'all' ) {
  321. // For all of them? Ok, look through the search engine list and create a SQL query string to get them all from the database.
  322. foreach( $searchengine_list as $key => $se ) {
  323. $search_query .= "( `engine` = '{$key}' AND `words` <> '' ) OR ";
  324. }
  325. // Trim off the last ' OR ' for the loop above.
  326. $search_query = substr( $search_query, 0, strlen( $search_query ) - 4 );
  327. } else {
  328. $search_query .= "`engine` = '{$search_engine}' AND `words` <> ''";
  329. }
  330. } else {
  331. // Are we getting results for all search engines or a specific one?
  332. if( strtolower($search_engine) == 'all' ) {
  333. // For all of them? Ok, look through the search engine list and create a SQL query string to get them all from the database.
  334. // NOTE: This SQL query can be *VERY* long.
  335. foreach( $searchengine_list as $se ) {
  336. // The SQL pattern for a search engine may be an array if it has to handle multiple domains (like google.com and google.ca) or other factors.
  337. if( is_array( $se['sqlpattern'] ) ) {
  338. foreach( $se['sqlpattern'] as $subse ) {
  339. $search_query .= "(`referred` LIKE '{$subse}{$se['querykey']}=%' AND `referred` NOT LIKE '{$subse}{$se['querykey']}=&%' AND `referred` NOT LIKE '{$subse}{$se['querykey']}=') OR ";
  340. }
  341. } else {
  342. $search_query .= "(`referred` LIKE '{$se['sqlpattern']}{$se['querykey']}=%' AND `referred` NOT LIKE '{$se['sqlpattern']}{$se['querykey']}=&%' AND `referred` NOT LIKE '{$se['sqlpattern']}{$se['querykey']}=') OR ";
  343. }
  344. }
  345. // Trim off the last ' OR ' for the loop above.
  346. $search_query = substr( $search_query, 0, strlen( $search_query ) - 4 );
  347. } else {
  348. // For just one? Ok, the SQL pattern for a search engine may be an array if it has to handle multiple domains (like google.com and google.ca) or other factors.
  349. if( is_array( $searchengine_list[$search_engine]['sqlpattern'] ) ) {
  350. foreach( $searchengine_list[$search_engine]['sqlpattern'] as $se ) {
  351. $search_query .= "(`referred` LIKE '{$se}{$searchengine_list[$search_engine]['querykey']}=%' AND `referred` NOT LIKE '{$se}{$searchengine_list[$search_engine]['querykey']}=&%' AND `referred` NOT LIKE '{$se}{$searchengine_list[$search_engine]['querykey']}=') OR ";
  352. }
  353. // Trim off the last ' OR ' for the loop above.
  354. $search_query = substr( $search_query, 0, strlen( $search_query ) - 4 );
  355. } else {
  356. $search_query .= "(`referred` LIKE '{$searchengine_list[$search_engine]['sqlpattern']}{$searchengine_list[$search_engine]['querykey']}=%' AND `referred` NOT LIKE '{$searchengine_list[$search_engine]['sqlpattern']}{$searchengine_list[$search_engine]['querykey']}=&%' AND `referred` NOT LIKE '{$searchengine_list[$search_engine]['sqlpattern']}{$searchengine_list[$search_engine]['querykey']}=')";
  357. }
  358. }
  359. }
  360. return $search_query;
  361. }
  362. // This function will return the SQL WHERE clause for getting the search engine.
  363. function ljmc_statistics_searchengine_query ($search_engine = 'all') {
  364. GLOBAL $LJMC_Statistics;
  365. // Get a complete list of search engines
  366. $searchengine_list = ljmc_statistics_searchengine_list();
  367. $search_query = '';
  368. if( $LJMC_Statistics->get_option('search_converted') ) {
  369. // Are we getting results for all search engines or a specific one?
  370. if( strtolower($search_engine) == 'all' ) {
  371. // For all of them? Ok, look through the search engine list and create a SQL query string to get them all from the database.
  372. foreach( $searchengine_list as $key => $se ) {
  373. $search_query .= "`engine` = '{$key}' OR ";
  374. }
  375. // Trim off the last ' OR ' for the loop above.
  376. $search_query = substr( $search_query, 0, strlen( $search_query ) - 4 );
  377. } else {
  378. $search_query .= "`engine` = '{$search_engine}'";
  379. }
  380. } else {
  381. // Are we getting results for all search engines or a specific one?
  382. if( strtolower($search_engine) == 'all' ) {
  383. // For all of them? Ok, look through the search engine list and create a SQL query string to get them all from the database.
  384. // NOTE: This SQL query can be long.
  385. foreach( $searchengine_list as $se ) {
  386. // The SQL pattern for a search engine may be an array if it has to handle multiple domains (like google.com and google.ca) or other factors.
  387. if( is_array( $se['sqlpattern'] ) ) {
  388. foreach( $se['sqlpattern'] as $subse ) {
  389. $search_query .= "`referred` LIKE '{$subse}' OR ";
  390. }
  391. } else {
  392. $search_query .= "`referred` LIKE '{$se['sqlpattern']}' OR ";
  393. }
  394. }
  395. // Trim off the last ' OR ' for the loop above.
  396. $search_query = substr( $search_query, 0, strlen( $search_query ) - 4 );
  397. } else {
  398. // For just one? Ok, the SQL pattern for a search engine may be an array if it has to handle multiple domains (like google.com and google.ca) or other factors.
  399. if( is_array( $searchengine_list[$search_engine]['sqlpattern'] ) ) {
  400. foreach( $searchengine_list[$search_engine]['sqlpattern'] as $se ) {
  401. $search_query .= "`referred` LIKE '{$se}' OR ";
  402. }
  403. // Trim off the last ' OR ' for the loop above.
  404. $search_query = substr( $search_query, 0, strlen( $search_query ) - 4 );
  405. }
  406. else {
  407. $search_query .= "`referred` LIKE '{$searchengine_list[$search_engine]['sqlpattern']}'";
  408. }
  409. }
  410. }
  411. return $search_query;
  412. }
  413. // This function will return a regular expression clause for matching one or more search engines.
  414. function ljmc_statistics_searchengine_regex ($search_engine = 'all') {
  415. // Get a complete list of search engines
  416. $searchengine_list = ljmc_statistics_searchengine_list();
  417. $search_query = '';
  418. // Are we getting results for all search engines or a specific one?
  419. if( strtolower($search_engine) == 'all' ) {
  420. foreach( $searchengine_list as $se ) {
  421. // The SQL pattern for a search engine may be an array if it has to handle multiple domains (like google.com and google.ca) or other factors.
  422. if( is_array( $se['regexpattern'] ) ) {
  423. foreach( $se['regexpattern'] as $subse ) {
  424. $search_query .= "{$subse}|";
  425. }
  426. } else {
  427. $search_query .= "{$se['regexpattern']}|";
  428. }
  429. }
  430. // Trim off the last '|' for the loop above.
  431. $search_query = substr( $search_query, 0, strlen( $search_query ) - 1 );
  432. } else {
  433. // For just one? Ok, the SQL pattern for a search engine may be an array if it has to handle multiple domains (like google.com and google.ca) or other factors.
  434. if( is_array( $searchengine_list[$search_engine]['regexpattern'] ) ) {
  435. foreach( $searchengine_list[$search_engine]['regexpattern'] as $se ) {
  436. $search_query .= "{$se}|";
  437. }
  438. // Trim off the last '|' for the loop above.
  439. $search_query = substr( $search_query, 0, strlen( $search_query ) - 1 );
  440. } else {
  441. $search_query .= $searchengine_list[$search_engine]['regexpattern'];
  442. }
  443. }
  444. // Add the brackets and return
  445. return "({$search_query})";
  446. }
  447. // This function will return the statistics for a given search engine.
  448. function ljmc_statistics_searchengine($search_engine = 'all', $time = 'total') {
  449. global $ljmcdb, $LJMC_Statistics;
  450. // Determine if we're using the old or new method of storing search engine info and build the appropriate table name.
  451. $tablename = $ljmcdb->prefix . 'statistics_';
  452. if( $LJMC_Statistics->get_option('search_converted') ) {
  453. $tablename .= 'search';
  454. } else {
  455. $tablename .= 'visitor';
  456. }
  457. // Get a complete list of search engines
  458. $search_query = ljmc_statistics_searchengine_query($search_engine);
  459. // This function accepts several options for time parameter, each one has a unique SQL query string.
  460. // They're pretty self explanatory.
  461. switch($time) {
  462. case 'today':
  463. $result = $ljmcdb->query("SELECT * FROM `{$tablename}` WHERE `last_counter` = '{$LJMC_Statistics->Current_Date('Y-m-d')}' AND {$search_query}");
  464. break;
  465. case 'yesterday':
  466. $result = $ljmcdb->query("SELECT * FROM `{$tablename}` WHERE `last_counter` = '{$LJMC_Statistics->Current_Date('Y-m-d', -1)}' AND {$search_query}");
  467. break;
  468. case 'week':
  469. $result = $ljmcdb->query("SELECT * FROM `{$tablename}` WHERE `last_counter` = '{$LJMC_Statistics->Current_Date('Y-m-d', -7)}' AND {$search_query}");
  470. break;
  471. case 'month':
  472. $result = $ljmcdb->query("SELECT * FROM `{$tablename}` WHERE `last_counter` = '{$LJMC_Statistics->Current_Date('Y-m-d', -30)}' AND {$search_query}");
  473. break;
  474. case 'year':
  475. $result = $ljmcdb->query("SELECT * FROM `{$tablename}` WHERE `last_counter` = '{$LJMC_Statistics->Current_Date('Y-m-d', -360)}' AND {$search_query}");
  476. break;
  477. case 'total':
  478. $result = $ljmcdb->query("SELECT * FROM `{$tablename}` WHERE {$search_query}");
  479. break;
  480. default:
  481. $result = $ljmcdb->query("SELECT * FROM `{$tablename}` WHERE `last_counter` = '{$LJMC_Statistics->Current_Date('Y-m-d', $time)}' AND {$search_query}");
  482. break;
  483. }
  484. return $result;
  485. }
  486. // This function will return the statistics for a given search engine for a given time frame.
  487. function ljmc_statistics_searchword($search_engine = 'all', $time = 'total') {
  488. global $ljmcdb, $LJMC_Statistics;
  489. // Determine if we're using the old or new method of storing search engine info and build the appropriate table name.
  490. $tablename = $ljmcdb->prefix . 'statistics_';
  491. if( $LJMC_Statistics->get_option('search_converted') ) {
  492. $tablename .= 'search';
  493. } else {
  494. $tablename .= 'visitor';
  495. }
  496. // Get a complete list of search engines
  497. $search_query = ljmc_statistics_searchword_query($search_engine);
  498. // This function accepts several options for time parameter, each one has a unique SQL query string.
  499. // They're pretty self explanatory.
  500. switch($time) {
  501. case 'today':
  502. $result = $ljmcdb->query("SELECT * FROM `{$tablename}` WHERE `last_counter` = '{$LJMC_Statistics->Current_Date('Y-m-d')}' AND {$search_query}");
  503. break;
  504. case 'yesterday':
  505. $result = $ljmcdb->query("SELECT * FROM `{$tablename}` WHERE `last_counter` = '{$LJMC_Statistics->Current_Date('Y-m-d', -1)}' AND {$search_query}");
  506. break;
  507. case 'week':
  508. $result = $ljmcdb->query("SELECT * FROM `{$tablename}` WHERE `last_counter` = '{$LJMC_Statistics->Current_Date('Y-m-d', -7)}' AND {$search_query}");
  509. break;
  510. case 'month':
  511. $result = $ljmcdb->query("SELECT * FROM `{$tablename}` WHERE `last_counter` = '{$LJMC_Statistics->Current_Date('Y-m-d', -30)}' AND {$search_query}");
  512. break;
  513. case 'year':
  514. $result = $ljmcdb->query("SELECT * FROM `{$tablename}` WHERE `last_counter` = '{$LJMC_Statistics->Current_Date('Y-m-d', -360)}' AND {$search_query}");
  515. break;
  516. case 'total':
  517. $result = $ljmcdb->query("SELECT * FROM `{$tablename}` WHERE {$search_query}");
  518. break;
  519. default:
  520. $result = $ljmcdb->query("SELECT * FROM `{$tablename}` WHERE `last_counter` = '{$LJMC_Statistics->Current_Date('Y-m-d', $time)}' AND {$search_query}");
  521. break;
  522. }
  523. return $result;
  524. }
  525. // This function will return the total number of posts in LJMC.
  526. function ljmc_statistics_countposts() {
  527. $count_posts = ljmc_count_posts('post');
  528. $ret = 0;
  529. if( is_object( $count_posts ) ) { $ret = $count_posts->publish; }
  530. return $ret;
  531. }
  532. // This function will return the total number of pages in LJMC.
  533. function ljmc_statistics_countpages() {
  534. $count_pages = ljmc_count_posts('page');
  535. $ret = 0;
  536. if( is_object($count_pages) ) { $ret = $count_pages->publish; }
  537. return $ret;
  538. }
  539. // This function will return the total number of comments in LJMC.
  540. function ljmc_statistics_countcomment() {
  541. global $ljmcdb;
  542. $countcomms = $ljmcdb->get_var("SELECT COUNT(*) FROM $ljmcdb->comments WHERE comment_approved = '1'");
  543. return $countcomms;
  544. }
  545. // This function will return the total number of spam comments *IF* akismet is installed.
  546. function ljmc_statistics_countspam() {
  547. return number_format_i18n(get_option('akismet_spam_count'));
  548. }
  549. // This function will return the total number of users in LJMC.
  550. function ljmc_statistics_countusers() {
  551. $result = count_users();
  552. return $result['total_users'];
  553. }
  554. // This function will return the last date a post was published on your site.
  555. function ljmc_statistics_lastpostdate() {
  556. global $ljmcdb, $LJMC_Statistics;
  557. $db_date = $ljmcdb->get_var("SELECT post_date FROM $ljmcdb->posts WHERE post_type='post' AND post_status='publish' ORDER BY ID DESC LIMIT 1");
  558. $date_format = get_option('date_format');
  559. return $LJMC_Statistics->Current_Date_i18n($date_format, $db_date, false);
  560. }
  561. // This function will return the average number of posts per day that are published on your site.
  562. // Alternatively if $days is set to true it returns the average number of days between posts on your site.
  563. function ljmc_statistics_average_post($days = false) {
  564. global $ljmcdb;
  565. $get_first_post = $ljmcdb->get_var("SELECT post_date FROM $ljmcdb->posts WHERE post_status = 'publish' ORDER BY post_date LIMIT 1");
  566. $get_total_post = $ljmcdb->get_var("SELECT COUNT(*) FROM $ljmcdb->posts WHERE post_status = 'publish' AND post_type = 'post'");
  567. $days_spend = intval((time() - strtotime($get_first_post) ) / 86400); // 86400 = 60 * 60 * 24 = number of seconds in a day
  568. if( $days == true ) {
  569. if( $get_total_post == 0 ) { $get_total_post = 1; } // Avoid divide by zero errors.
  570. return round( $days_spend / $get_total_post, 0 );
  571. }
  572. else {
  573. if( $days_spend == 0 ) { $days_spend = 1; } // Avoid divide by zero errors.
  574. return round($get_total_post / $days_spend, 2);
  575. }
  576. }
  577. // This function will return the average number of comments per day that are published on your site.
  578. // Alternatively if $days is set to true it returns the average number of days between comments on your site.
  579. function ljmc_statistics_average_comment($days = false) {
  580. global $ljmcdb;
  581. $get_first_comment = $ljmcdb->get_var("SELECT comment_date FROM $ljmcdb->comments ORDER BY comment_date LIMIT 1");
  582. $get_total_comment = $ljmcdb->get_var("SELECT COUNT(*) FROM $ljmcdb->comments WHERE comment_approved = '1'");
  583. $days_spend = intval((time() - strtotime($get_first_comment) ) / 86400); // 86400 = 60 * 60 * 24 = number of seconds in a day
  584. if( $days == true ) {
  585. if( $get_total_comment == 0 ) { $get_total_comment = 1; } // Avoid divide by zero errors.
  586. return round($days_spend / $get_total_comment, 0);
  587. }
  588. else {
  589. if( $days_spend == 0 ) { $days_spend = 1; } // Avoid divide by zero errors.
  590. return round($get_total_comment / $days_spend, 2);
  591. }
  592. }
  593. // This function will return the average number of users per day that are registered on your site.
  594. // Alternatively if $days is set to true it returns the average number of days between user registrations on your site.
  595. function ljmc_statistics_average_registeruser($days = false) {
  596. global $ljmcdb;
  597. $get_first_user = $ljmcdb->get_var("SELECT user_registered FROM $ljmcdb->users ORDER BY user_registered LIMIT 1");
  598. $get_total_user = $ljmcdb->get_var("SELECT COUNT(*) FROM $ljmcdb->users");
  599. $days_spend = intval((time() - strtotime($get_first_user) ) / 86400); // 86400 = 60 * 60 * 24 = number of seconds in a day
  600. if( $days == true ) {
  601. if( $get_total_user == 0 ) { $get_total_user = 1; } // Avoid divide by zero errors.
  602. return round($days_spend / $get_total_user, 0);
  603. }
  604. else {
  605. if( $days_spend == 0 ) { $days_spend = 1; } // Avoid divide by zero errors.
  606. return round($get_total_user / $days_spend, 2);
  607. }
  608. }
  609. // This function gets a countries map coordinates (latitude/longitude).
  610. function ljmc_statistics_get_gmap_coordinate($country, $coordinate) {
  611. global $CountryCoordinates, $LJMC_Statistics;
  612. // Check to see if the admin has told us to use Google to get the co-ordinates.
  613. if($LJMC_Statistics->get_option('google_coordinates')) {
  614. // Some clients can't handle mixed http/https pages so check to see if the page we're on has http
  615. // enabled, if so, use https instead just in case for the Google script.
  616. $protocol = "http";
  617. if( array_key_exists( 'HTTPS', $_SERVER ) ) {
  618. if( $_SERVER['HTTPS'] == 'on' ) { $protocol .= 's'; }
  619. }
  620. // This is google's API URL we'll be calling.
  621. $api_url = "{$protocol}://maps.google.com/maps/api/geocode/json?address={$country}&sensor=false";
  622. // There are two ways we can get the results form google, file_get_contents() and curl_exec().
  623. // However both are optional components of PHP so we need to check to see which one is available.
  624. if(function_exists('file_get_contents')) {
  625. // get_file_contents() is easier so it's first.
  626. $json = file_get_contents($api_url);
  627. $response = json_decode($json);
  628. if($response->status != 'OK')
  629. return false;
  630. } elseif(function_exists('curl_version')) {
  631. // cURL is a fine second option.
  632. $ch = curl_init();
  633. curl_setopt($ch, CURLOPT_URL, $api_url);
  634. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  635. $response = json_decode(curl_exec($ch));
  636. if($response->status != 'OK')
  637. return false;
  638. } else {
  639. // Opps, neither exists, we can't do anything.
  640. $response = false;
  641. }
  642. // If we have a response, get the co-ordinates.
  643. if( $response !== false ) {
  644. $result = $response->results[0]->geometry->location->{$coordinate};
  645. }
  646. else {
  647. $result = '';
  648. }
  649. } else {
  650. // If we're not using online looksups, load the country co-ordinates from our local copy.
  651. include_once( dirname( __FILE__ ) . "/country-coordinates.php");
  652. if( array_key_exists( $country, $CountryCoordinates ) ) {
  653. $result = $CountryCoordinates[$country][$coordinate];
  654. }
  655. else {
  656. $result = '';
  657. }
  658. }
  659. // If we couldn't find the co-ordinates, return 0.
  660. if( $result == '' ) { $result = '0'; }
  661. return $result;
  662. }
  663. // This function handle's the dashicons in the overview page.
  664. function ljmc_statistics_icons($dashicons, $icon_name) {
  665. global $ljmc_version;
  666. // Since versions of LJMC before 3.8 didn't have dashicons, don't use them in those versions.
  667. if( version_compare( $ljmc_version, '3.8-RC', '>=' ) || version_compare( $ljmc_version, '3.8', '>=' ) ) {
  668. return "<div class='dashicons {$dashicons}'></div>";
  669. } else {
  670. return "<img src='".plugins_url('statistics/assets/images/')."{$icon_name}.png'/>";
  671. }
  672. }
  673. // This function checks to see if all the PHP moduels we need for GeoIP exists.
  674. function ljmc_statistics_geoip_supported() {
  675. // Check to see if we can support the GeoIP code, requirements are:
  676. $enabled = true;
  677. // PHP 5.3
  678. if( !version_compare(phpversion(), LJMC_STATISTICS_REQUIRED_GEOIP_PHP_VERSION, '>') ) { $enabled = false; }
  679. // PHP's cURL extension installed
  680. if( !function_exists('curl_init') ) { $enabled = false; }
  681. // PHP's bcadd extension installed
  682. if( !function_exists('bcadd') ) { $enabled = false; }
  683. // PHP NOT running in safe mode
  684. if( ini_get('safe_mode') ) {
  685. // Double check php version, 5.4 and above don't support safe mode but the ini value may still be set after an upgrade.
  686. if( !version_compare(phpversion(), "5.4", '<') ) { $enabled = false; }
  687. }
  688. return $enabled;
  689. }
  690. function ljmc_statistics_date_range_selector( $page, $current, $range = array(), $desc = array(), $extrafields = '' ) {
  691. GLOBAL $LJMC_Statistics;
  692. ljmc_enqueue_script('jquery-ui-datepicker');
  693. ljmc_register_style("jquery-ui-smoothness-css", $LJMC_Statistics->plugin_url . "assets/css/jquery-ui-smoothness.css");
  694. ljmc_enqueue_style("jquery-ui-smoothness-css");
  695. if( count( $range ) == 0 ) {
  696. $range = array( 10, 20, 30, 60, 90, 180, 270, 365 );
  697. $desc = array( __('10 dienas', 'ljmc_statistics'), __('20 dienas', 'ljmc_statistics'), __('30 dienas', 'ljmc_statistics'), __('2 Mēneši', 'ljmc_statistics'), __('3 Mēneši', 'ljmc_statistics'), __('6 Mēneši', 'ljmc_statistics'), __('9 Mēneši', 'ljmc_statistics'), __('1 Gads', 'ljmc_statistics'));
  698. }
  699. if( count( $desc ) == 0 ) {
  700. $desc = $range;
  701. }
  702. $rcount = count( $range );
  703. $rangestart = $LJMC_Statistics->Real_Current_Date('m/d/Y', '-' . $current);
  704. $rangeend = $LJMC_Statistics->Real_Current_Date('m/d/Y');
  705. $bold = true;
  706. if( array_key_exists( 'rangestart', $_GET ) ) { $rangestart = $_GET['rangestart']; }
  707. if( array_key_exists( 'rangeend', $_GET ) ) { $rangeend = $_GET['rangeend']; }
  708. echo '<form method="get"><ul class="subsubsub">' . "\r\n";
  709. for( $i = 0; $i < $rcount; $i ++ ) {
  710. echo ' <li class="all"><a ';
  711. if( $current == $range[$i] ) { echo 'class="current" '; $bold = false;}
  712. echo 'href="?page=' . $page . '&hitdays=' . $range[$i] . '&rangestart=' . $rangestart . '&rangeend=' . $rangeend . $extrafields . '">' . $desc[$i] . '</a></li>';
  713. if( $i < $rcount - 1 ) {
  714. echo ' | ';
  715. }
  716. echo "\r\n";
  717. }
  718. echo ' | ';
  719. echo '<input type="hidden" name="hitdays" value="-1"><input type="hidden" name="page" value="' . $page . '">';
  720. parse_str( $extrafields, $parse );
  721. foreach( $parse as $key => $value ) {
  722. echo '<input type="hidden" name="' . $key . '" value="' . $value . '">';
  723. }
  724. if( $bold ) {
  725. echo ' <b>' . __('No', 'ljmc_statistics' ) . '</b> ';
  726. }
  727. else {
  728. echo ' ' . __('No', 'ljmc_statistics' ) . ': ';
  729. $rangeend = $LJMC_Statistics->Real_Current_Date('m/d/Y');
  730. $rangestart = $LJMC_Statistics->Real_Current_Date('m/d/Y','-'.$current);
  731. }
  732. echo '<input type="text" size="10" name="rangestart" id="datestartpicker" value="' . $rangestart. '" placeholder="' . __('MM/DD/GGGG', 'ljmc_statistics') .'"> '.__('līdz', 'ljmc_statistics').' <input type="text" size="10" name="rangeend" id="dateendpicker" value="' . $rangeend . '" placeholder="' . __('MM/DD/GGGG', 'ljmc_statistics') .'"> <input type="submit" value="'.__('Aiziet', 'ljmc_statistics').'" class="button-primary">' . "\r\n";
  733. echo '</ul><form>' . "\r\n";
  734. echo '<script>jQuery(function() { jQuery( "#datestartpicker" ).datepicker(); jQuery( "#dateendpicker" ).datepicker(); });</script>' . "\r\n";
  735. }
  736. function ljmc_statistics_date_range_calculator( $days, $start, $end ) {
  737. $daysToDisplay = $days;
  738. $rangestart = $start;
  739. $rangeend = $end;
  740. if( $daysToDisplay == -1 ) {
  741. $rangestart_utime = strtotime( $rangestart );
  742. $rangeend_utime = strtotime( $rangeend );
  743. $daysToDisplay = (int)( ( $rangeend_utime - $rangestart_utime ) / 24 / 60 / 60 );
  744. if( $rangestart_utime == FALSE || $rangeend_utime == FALSE ) {
  745. $daysToDisplay = 20;
  746. $rangeend_utime = time();
  747. $rangestart_utime = $rangeend_utime - ( $daysToDisplay * 24 * 60 * 60 );
  748. }
  749. }
  750. else {
  751. $rangeend_utime = time();
  752. $rangestart_utime = $rangeend_utime - ( $daysToDisplay * 24 * 60 * 60 );
  753. }
  754. return array( $daysToDisplay, $rangestart_utime, $rangeend_utime );
  755. }
  756. function ljmc_statitiscs_empty_table( $table_name = FALSE ) {
  757. global $ljmcdb;
  758. if( $table_name ) {
  759. $result = $ljmcdb->query('DELETE FROM ' . $table_name);
  760. if($result) {
  761. return sprintf(__('%s table data deleted successfully.', 'ljmc_statistics'), '<code>' . $table_name . '</code>');
  762. }
  763. }
  764. return sprintf(__('Error, %s not emptied!', 'ljmc_statistics'), $table_name );
  765. }