Newer
Older
Digital_Repository / Repositories / statistics / scripts / eprints-usage_src.php
  1. <?php
  2.  
  3. /* NJS 2006-04-28
  4. In earlier versions of this script, which eprints to count was
  5. determined by comparing the request date of the eprint against the
  6. "lastproc" date of this script (i.e., minimum time unit one day).
  7. This was fine if you only ran the script once per day, but if you ran
  8. it more than that, it counted multiple times requests whose
  9. $request_date == $lastproc. For example, if you ran this script five
  10. times per day, all the downloads that occurred during that day would
  11. be counted EVERY TIME this script ran, thus overinflating your stats
  12. by a factor of up to five :(
  13. The solution is to use the full time stamp for comparison rather than
  14. just the date. This timestamp MUST include time zone information so
  15. that things don't get screwed up by daylight saving time. As long as
  16. this is done consistently, there's no need to do things like convert
  17. to GMT, for example.
  18. The very first thing we need to do is grab the current time stamp
  19. with time zone, which will later be stored in the database as the
  20. "lastproc" time. This needs to happen first so that we don't "lose"
  21. any requests that occur while the script is running.
  22. */
  23. $start_time = date('Y-m-d H:i:s O');
  24.  
  25. /* NJS 2007-01-30
  26. A further twist! The original script ignored log lines that had a
  27. date falling before $lastproc, i.e., if log line date < $lastproc
  28. then it's already been dealt with. This is all fine. However, it
  29. didn't bother checking for log lines that were written after the
  30. script started running (i.e. log line date >= $start_time).
  31. Why is this a problem? We're reading the live Apache log file, so
  32. it's quite likely that new lines will be written to it after the
  33. script has started (i.e., after $start_time). Suppose $start_time is
  34. '2006-06-15 14:03:15 +1200', $lastproc is '2006-06-15 12:03:15 +1200'
  35. (i.e., the script is run every two hours) and the log file contains
  36. lines with the following dates:
  37. '2006-06-15 10:03:15 +1200' [1] <-- written before $lastproc
  38. '2006-06-15 12:03:14 +1200' [2] <-- written before $lastproc
  39. '2006-06-15 13:03:15 +1200' [3] <-- written before $start_time
  40. '2006-06-15 14:03:14 +1200' [4] <-- written before $start_time
  41. '2006-06-15 14:03:15 +1200' [5] <-- written at $start_time
  42. '2006-06-15 14:03:16 +1200' [6] <-- written after $start_time
  43.  
  44. During this run, dates [1] and [2] are both < $lastproc and thus
  45. ignored. The remaining four dates ([4]--[6]) are >= $lastproc and
  46. thus processed.
  47.  
  48. Two hours later, the script runs again, this time with $start_time
  49. set to '2006-06-15 16:03:15 +1200' and $lastproc to '2006-06-15
  50. 14:03:15 +1200'. Dates [1] through [4] are all < $lastproc and
  51. thus ignored. However, dates [5] and [6] are both >= $lastproc
  52. and are processed a second time, resulting in a duplicate entry
  53. in the database.
  54. The solution is to ignore any log line entries that occur at or after
  55. (>=) $start_time. In the example above, this would mean that in the
  56. first run, dates [1], [2], [5] and [6] would be ignored and dates [3]
  57. and [4] processed. In the second run, dates [1]--[4] would be ignored
  58. and dates [5] and [6] processed.
  59. */
  60. $test_starttime = strtotime($start_time);
  61.  
  62.  
  63. // NJS 2005-12-09 Switched to GeoIP from GeoIP:IPfree.
  64. include("geoip.inc");
  65.  
  66. $gi = geoip_open("##GEOIP_DATABASE##",GEOIP_STANDARD);
  67.  
  68. /*
  69.  
  70. Apache log for ePrints uses this format:
  71. LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
  72.  
  73. If the log format differs the regular expression matching would need to be adjusted.
  74. Parse:
  75. ip
  76. date YYYY MM DD
  77. archive ID
  78.  
  79. */
  80.  
  81. // Web server log files
  82. $log_dir = '##APACHE_LOG_LOCATION##';
  83. $log_file = array(
  84. 'otago_eprints' => '##APACHE_LOG_NAME_1##',
  85. 'cardrona' => '##APACHE_LOG_NAME_2##',
  86. );
  87.  
  88.  
  89. // eprintstats db
  90. $sqlserver = 'localhost';
  91. $sqluser = 'eprintstatspriv';
  92. $sqlpass = 'AuldGrizzel';
  93. $sqldatabase = 'eprintstats';
  94.  
  95. /* NJS 2006-05-26
  96. SQL details of your ePrints installation(s). This has now been
  97. generalised to work with multiple archives. For each archive that you
  98. have, add an entry to this array in the following format:
  99.  
  100. 'archive_name' => array(
  101. 'sqlserver' => 'db_host',
  102. 'username' => 'archive_name',
  103. 'password' => 'password',
  104. ),
  105. */
  106. $eprintsdbs = array(
  107. 'otago_eprints' => array(
  108. 'sqlserver' => 'localhost',
  109. 'username' => 'otago_eprints',
  110. 'password' => 'DrSyntaxRidesAgain',
  111. ),
  112. 'cardrona' => array(
  113. 'sqlserver' => 'localhost',
  114. 'username' => 'cardrona',
  115. 'password' => 'chautquau',
  116. ),
  117. );
  118.  
  119. /* NJS 2005-12-16
  120. IP address ranges for your local Intranet(s). You can have multiple
  121. ranges of IP addresses, each with a different "country name", so that
  122. they will appear as separate entries in the by country stats pages.
  123. You should use a different country code for each range (ISO 3166-1
  124. specifies the range XA through XZ as "user-assignable", so you can use
  125. codes from there as necessary), and create flag icons as appropriate.
  126.  
  127. Each address range key is the name that will appear in the statistics
  128. database (the "country name"), followed by a comma, followed by the
  129. appropriate ISO 3166-1 country code as noted above. Each entry in the
  130. range is either a single IP address, or an array specifying a lower and
  131. upper bound for a contiguous IP address range (see example below).
  132.  
  133. All IP addresses must be converted to long values using the ip2long()
  134. function before being stored.
  135.  
  136. Note that address ranges may overlap. The script will use the first
  137. range that matches a given IP, so list the ranges in the correct order
  138. of precedence for your needs.
  139.  
  140. Example:
  141.  
  142. $local_IPs = array(
  143. 'Repository Admin,XA' => array(
  144. ip2long('192.168.1.5'),
  145. ip2long('192.168.1.22'),
  146. array(
  147. lower => ip2long('192.168.1.30'),
  148. upper => ip2long('192.168.1.35'),
  149. ),
  150. ),
  151. 'Our Intranet,XI' => array(
  152. array(
  153. lower => ip2long('192.168.1.0'),
  154. upper => ip2long('192.168.255.255'),
  155. ),
  156. ),
  157. );
  158.  
  159. 'Repository Admin' covers the IP addresses 192.168.1.5, 192.168.1.22 and
  160. the range 192.168.1.30 to 192.168.1.35, inclusive. 'Our Intranet' covers
  161. the range 192.168.1.0 to 192.168.255.255, inclusive. A machine will only
  162. match the 'Our Intranet' range if it first fails to match the
  163. 'Repository Admin' range.
  164. */
  165. $local_IPs = array(
  166. 'Repository Admin,XA' => array(
  167. ip2long('139.80.75.110'), // Nigel @ Uni
  168. ip2long('60.234.209.74'), // Nigel @ home
  169. ip2long('139.80.92.138'), // Monica & Jeremy
  170. ip2long('139.80.92.151'), // @ Uni
  171. ip2long('203.89.162.155'), // Monica @ home
  172. ip2long('139.80.81.50'), // eprints.otago.ac.nz
  173. ip2long('172.20.1.50'), // eprints.otago.ac.nz pre-switch
  174. ip2long('172.20.1.1'), // eprints.otago.ac.nz pre-switch
  175. ),
  176. 'Otago Intranet,XI' => array(
  177. array(
  178. 'lower' => ip2long('139.80.0.0'),
  179. 'upper' => ip2long('139.80.127.255'),
  180. ),
  181. ),
  182. );
  183.  
  184. /* NJS 2007-01-26
  185. Patterns to match various search engine bots. Ideally, we'd use a similar
  186. mechanism to the $local_IPs variable above, but this isn't feasible because
  187. we'd need to know the IP ranges for the likes of Google, for example. This
  188. clearly isn't possible in practice.
  189.  
  190. Fortunately, most search bots insert a readily identifiable string into
  191. the user-agent part of the HTTP response, which gets recorded in the Apache
  192. log file. We can look for these and re-code log entries as appropriate.
  193.  
  194. The format of this list is similar to that of the $local_IPs variable. The
  195. key is the "country name" (in this case the name of the search engine) plus
  196. an "X" ISO 3166-1 country code, separated by a comma. Each key value has an
  197. associated list of corresponding regular expressions that can occur in the
  198. user-agent part of the Apache log entry. If any one of these REs matches
  199. the user-agent part of the log entry, then we should re-code the country
  200. appropriately.
  201.  
  202. Note that this means that several of the "X" country codes are now reserved
  203. and can no longer be used in $local_IPs.
  204. */
  205. $bot_patterns = array(
  206. // Google (http://www.google.com/)
  207. 'Google,XG' => array(
  208. '/Googlebot/',
  209. '/http:\/\/www\.google\.com\/bot\.html/',
  210. ),
  211. // Windows Live Search (http://search.msn.com/)
  212. 'Windows Live Search,XM' => array(
  213. '/msnbot/',
  214. '/http:\/\/search\.msn\.com\/msnbot\.htm/',
  215. ),
  216. // Yahoo! (http://www.yahoo.com/)
  217. 'Yahoo!,XY' => array(
  218. '/Yahoo! Slurp/',
  219. '/YahooSeeker/',
  220. '/http:\/\/help\.yahoo\.com\/help\/us\/ysearch\/slurp/',
  221. '/yahooseeker-jp-mobile AT Yahoo!JAPAN/',
  222. ),
  223. // Ask.com (http://www.ask.com/)
  224. 'Ask.com,XJ' => array(
  225. '/Ask Jeeves\/Teoma/',
  226. '/http:\/\/about\.ask\.com\/en\/docs\/about\/webmasters\.shtml/',
  227. ),
  228. // Everything else I could find in our log files :)
  229. 'Other search engine,XZ' => array(
  230. // TAMU Internet Research Lab (http://irl.cs.tamu.edu/)
  231. '/http:\/\/irl\.cs\.tamu\.edu\/crawler/',
  232. // Alexa web search (http://www.alexa.com/)
  233. '/ia_archiver/',
  234. // TrueKnowledge for Web (http://www.authoritativeweb.com/)
  235. '/ConveraCrawler/',
  236. '/http:\/\/www\.authoritativeweb\.com\/crawl/',
  237. // Majestic 12 distributed search engine (http://www.majestic12.co.uk/)
  238. '/MJ12bot/',
  239. '/http:\/\/majestic12\.co\.uk\/bot\.php/',
  240. // Picsearch (http://www.picsearch.com/)
  241. '/psbot/',
  242. '/http:\/\/www\.picsearch\.com\/bot\.html/',
  243. // Exalead (http://www.exalead.com/search)
  244. '/Exabot/',
  245. // Cazoodle (note cazoodle.com doesn't exist)
  246. '/CazoodleBot Crawler/',
  247. '/http:\/\/www\.cazoodle\.com/',
  248. '/mqbot@cazoodle\.com/',
  249. // Gigablast (http://www.gigablast.com/)
  250. '/Gigabot/',
  251. '/http:\/\/www\.gigablast\.com\/spider\.html/',
  252. // Houxou (http://www.houxou.com/)
  253. '/HouxouCrawler/',
  254. '/http:\/\/www\.houxou\.com\/crawler/',
  255. '/crawler at houxou dot com/',
  256. // IBM Almaden Research Center Computer Science group (http://www.almaden.ibm.com/cs/)
  257. '/http:\/\/www\.almaden\.ibm\.com\/cs\/crawler/',
  258. // Goo? (http://help.goo.ne.jp/)
  259. '/ichiro/',
  260. '/http:\/\/help\.goo\.ne\.jp\/door\/crawler\.html/',
  261. // Daum Communications Corp (Korea)
  262. '/Edacious & Intelligent Web Robot/',
  263. '/Daum Communications Corp/',
  264. '/DAUM Web Robot/',
  265. '/MSIE is not me/',
  266. '/DAUMOA/',
  267. // Girafa (http://www.girafa.com/)
  268. '/[Gg]irafabot/',
  269. '/girafabot at girafa dot com/',
  270. '/http:\/\/www\.girafa\.com/',
  271. // The Generations Network (http://www.myfamilyinc.com/)
  272. '/MyFamilyBot/',
  273. '/http:\/\/www\.ancestry\.com\/learn\/bot\.aspx/',
  274. '/http:\/\/www\.myfamilyinc\.com/',
  275. // Naver? (http://www.naver.com/)
  276. '/NaverBot/',
  277. '/http:\/\/help\.naver\.com\/delete_main\.asp/',
  278. // WiseNut (http://www.wisenutbot.com/)
  279. '/ZyBorg/',
  280. '/wn-[0-9]+\.zyborg@looksmart\.net/',
  281. '/http:\/\/www\.WISEnutbot\.com/',
  282. // Accelobot (http://www.accelobot.com/)
  283. // This one seems particularly busy!
  284. '/heritrix/',
  285. '/http:\/\/www\.accelobot\.com/',
  286. // Seeqpod (http://www.seeqpod.com/)
  287. '/seeqpod-vertical-crawler/',
  288. '/http:\/\/www\.seeqpod\.com/',
  289. // University of Illinois at Urbana-Champaign, Computer Science (http://www.cs.uiuc.edu/)
  290. '/MQBOT Crawler/',
  291. '/http:\/\/falcon\.cs\.uiuc\.edu/',
  292. '/mqbot@cs\.uiuc\.edu/',
  293. // Microsoft Research (http://research.microsoft.com/)
  294. '/MSRBOT/',
  295. '/http:\/\/research\.microsoft\.com\/research\/sv\/msrbot\//',
  296. // Nusearch
  297. '/Nusearch Spider/',
  298. '/www\.nusearch\.com/',
  299. // SourceForge (http://www.sf.net/)
  300. '/nutch-agent@lists\.sourceforge\.net/',
  301. // Lucene (http://lucene.apache.org/)
  302. '/nutch-agent@lucene\.apache\.org/',
  303. '/raphael@unterreuth.de/',
  304. // Computer Science, University of Washington (http://cs.washington.edu/)
  305. '/Nutch running at UW/',
  306. '/http:\/\/crawlers\.cs\.washington\.edu\//',
  307. '/sycrawl@cs\.washington\.edu/',
  308. // Chikayama & Taura Laboratory, University of Tokyo (http://www.logos.ic.i.u-tokyo.ac.jp/)
  309. '/Shim-Crawler/',
  310. '/http:\/\/www\.logos\.ic\.i\.u-tokyo\.ac\.jp\/crawler\//',
  311. '/crawl@logos\.ic\.i\.u-tokyo\.ac\.jp/',
  312. // Sproose (http://www.sproose.com/)
  313. '/sproose bot/',
  314. '/http:\/\/www\.sproose\.com\/bot\.html/',
  315. '/crawler@sproose\.com/',
  316. // Turnitin (http://www.turnitin.com/)
  317. '/TurnitinBot/',
  318. '/http:\/\/www\.turnitin\.com\/robot\/crawlerinfo\.html/',
  319. // WISH Project (http://wish.slis.tsukuba.ac.jp/)
  320. '/wish-project/',
  321. '/http:\/\/wish\.slis\.tsukuba\.ac\.jp\//',
  322. // WWWster
  323. '/wwwster/',
  324. '/gue@cis\.uni-muenchen\.de/',
  325. // Forex Trading Network Organization (http://www.netforex.org/)
  326. '/Forex Trading Network Organization/',
  327. '/http:\/\/www\.netforex\.org/',
  328. '/info@netforex\.org/',
  329. // FunnelBack (http://www.funnelback.com/)
  330. '/FunnelBack/',
  331. '/http:\/\/www\.funnelback\.com\/robot\.html/',
  332. // Baidu (http://www.baidu.com/)
  333. '/Baiduspider/',
  334. '/http:\/\/www\.baidu\.com\/search\/spider\.htm/',
  335. // Brandimensions (http://www.brandimensions.com/)
  336. '/BDFetch/',
  337. // Blaiz Enterprises (http://www.blaiz.net/)
  338. '/Blaiz-Bee/',
  339. '/http:\/\/www\.blaiz\.net/',
  340. // Boitho/SearchDaimon (http://www.boitho.com/ or http://www.searchdaimon.com/)
  341. '/boitho\.com-dc/',
  342. '/http:\/\/www\.boitho\.com\/dcbot\.html/',
  343. // Celestial (OAI aggregator, see http://oai-perl.sourceforge.net/ for a little info)
  344. '/Celestial/',
  345. // Cipinet (http://www.cipinet.com/)
  346. '/CipinetBot/',
  347. '/http:\/\/www\.cipinet\.com\/bot\.html/',
  348. // iVia (http://ivia.ucr.edu/)
  349. '/CrawlerTest CrawlerTest/',
  350. '/http:\/\/ivia\.ucr\.edu\/useragents\.shtml/',
  351. // Encyclopedia of Keywords (http://keywen.com/)
  352. '/EasyDL/',
  353. '/http:\/\/keywen\.com\/Encyclopedia\/Bot/',
  354. // Everest-Vulcan Inc. (http://everest.vulcan.com/)
  355. '/Everest-Vulcan Inc/',
  356. '/http:\/\/everest\.vulcan\.com\/crawlerhelp/',
  357. // FactBites (http://www.factbites.com/)
  358. '/Factbot/',
  359. '/http:\/\/www\.factbites\.com\/webmasters\.php/',
  360. // Scirus (http://www.scirus.com/)
  361. '/Scirus scirus-crawler@fast\.no/',
  362. '/http:\/\/www\.scirus\.com\/srsapp\/contactus\//',
  363. // UOL (http://www.uol.com.br/)
  364. '/UOLCrawler/',
  365. '/soscrawler@uol\.com\.br/',
  366. // Always Updated (http://www.updated.com/)
  367. '/updated crawler/',
  368. '/crawler@updated\.com/',
  369. '/http:\/\/www\.updated\.com/',
  370. // FAST Enterprise Search (http://www.fast.no/)
  371. '/crawler@fast\.no/',
  372. '/FAST MetaWeb Crawler/',
  373. '/helpdesk at fastsearch dot com/',
  374. // Deutsche Wortschatz Portal (http://wortschatz.uni-leipzig.de/)
  375. '/findlinks/',
  376. '/http:\/\/wortschatz\.uni-leipzig\.de\/findlinks\//',
  377. // Gais (http://gais.cs.ccu.edu.tw/)
  378. '/Gaisbot/',
  379. '/robot[0-9]{2}@gais.cs.ccu.edu.tw/',
  380. '/http:\/\/gais\.cs\.ccu\.edu\.tw\/robot\.php/',
  381. // http://ilse.net/
  382. '/INGRID/',
  383. '/http:\/\/webmaster\.ilse\.nl\/jsp\/webmaster\.jsp/',
  384. // Krugle (http://corp.krugle.com/)
  385. '/Krugle\/Krugle/',
  386. '/Krugle web crawler/',
  387. '/http:\/\/corp\.krugle\.com\/crawler\/info\.html/',
  388. '/webcrawler@krugle\.com/',
  389. // WebWobot (http://www.webwobot.com/)
  390. '/ScollSpider/',
  391. '/http:\/\/www\.webwobot\.com/',
  392. // Omni-Explorer (http://www.omni-explorer.com/)
  393. '/OmniExplorer_Bot/',
  394. '/http:\/\/www\.omni-explorer\.com/',
  395. '/WorldIndexer/',
  396. // PageBull (http://www.pagebull.com/)
  397. '/Pagebull http:\/\/www\.pagebull\.com\//',
  398. // dir.com (http://dir.com/)
  399. '/Pompos/',
  400. '/http:\/\/dir\.com\/pompos\.html/',
  401. // Sensis (http://sensis.com.au/)
  402. '/Sensis Web Crawler/',
  403. '/search_comments\\\\at\\\\sensis\\\\dot\\\\com\\\\dot\\\\au/',
  404. // Shopwiki (http://www.shopwiki.com/)
  405. '/ShopWiki/',
  406. '/http:\/\/www\.shopwiki\.com\//',
  407. // Guruji (http://www.terrawiz.com/)
  408. '/TerrawizBot/',
  409. '/http:\/\/www\.terrawiz\.com\/bot\.html/',
  410. // Language Observatory Project (http://www.language-observatory.org/)
  411. '/UbiCrawler/',
  412. '/http:\/\/gii\.nagaokaut\.ac\.jp\/~ubi\//',
  413. // Unidentified
  414. '/[Bb]ot/',
  415. '/[Cc]rawler/',
  416. '/[Ss]pider/',
  417. '/larbin/', // also larbinSpider
  418. '/HTTrack/',
  419. '/voyager/',
  420. '/AcadiaUniversityWebCensusClient/',
  421. '/FeedChecker/',
  422. '/KnowItAll\(knowitall@cs\.washington\.edu\)/',
  423. '/Mediapartners-Google/',
  424. '/psycheclone/',
  425. '/topicblogs/',
  426. ),
  427. );
  428.  
  429. ###########################################
  430. ##
  431. ## No configuration required below here.
  432. ##
  433. ###########################################
  434.  
  435. $connect = mysql_pconnect ($sqlserver,$sqluser,$sqlpass);
  436. $db = mysql_select_db($sqldatabase,$connect) or die("Could not connect");
  437.  
  438. // First get the date of last update
  439. /* NJS 2006-04-28
  440. Changed this from order by timeinsert to order by id. The ID is
  441. always guaranteed to increase temporally, but is otherwise
  442. time-independent and thus not affected by things like daylight
  443. savings.
  444. */
  445. $query = "SELECT lastproc FROM lastproc ORDER BY id DESC LIMIT 1";
  446. $result = mysql_query($query,$connect);
  447. $num_rows = mysql_num_rows($result);
  448. if ($num_rows > 0) {
  449. $row = mysql_fetch_assoc($result);
  450. $lastproc = $row["lastproc"];
  451. // NJS 2007-01-30 Refactored $databaseA to more meaningful $test_lastproc.
  452. $test_lastproc = strtotime($lastproc);
  453. }
  454. else {
  455. $test_lastproc = 0;
  456. }
  457.  
  458. // NJS 2006-06-14: Generalised connection list for multiple archives.
  459. $eprints_connections = array();
  460. foreach ($eprintsdbs as $archive_name => $details)
  461. {
  462. $eprints_connections[$archive_name] =
  463. mysql_connect($details['sqlserver'],$details['username'],$details['password']);
  464. }
  465. $counter = 0;
  466. foreach($log_file as $archive_name=>$archive_log) {
  467. $logf = $log_dir . $archive_log;
  468. $handle = fopen($logf, "r");
  469. while (!feof($handle)) {
  470. $buffer = fgets($handle, 4096);
  471. // NJS 2005-11-25 Added regexp for EPrints short URLs.
  472. // NJS 2007-01-26 Added user-agent match to all regexps to enable bot detection.
  473. // NJS 2007-01-29 Added missing regexp for EPrints short URLs with domain names rather than IP addresses.
  474. if ((preg_match("/^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}) - - \[(.*?)\] \"GET \/archive\/0{1,8}(\d{1,4}).*? HTTP\/1..\" 200 .*(\"[^\"]+\")?$/i",$buffer,$matches)) ||
  475. (preg_match("/^(\S{1,}\.\S{1,}\.\S{1,}\.\S{1,}) - - \[(.*?)\] \"GET \/archive\/0{1,8}(\d{1,4}).*? HTTP\/1..\" 200 .*(\"[^\"]+\")?$/i",$buffer,$matches)) ||
  476. (preg_match("/^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}) - - \[(.*?)\] \"GET \/(\d{1,4}).*? HTTP\/1..\" 200 .*(\"[^\"]+\")?$/i",$buffer,$matches)) ||
  477. (preg_match("/^(\S{1,}\.\S{1,}\.\S{1,}\.\S{1,}) - - \[(.*?)\] \"GET \/(\d{1,4}).*? HTTP\/1..\" 200 .*(\"[^\"]+\")?$/i",$buffer,$matches)))
  478. {
  479. $counter++;
  480. $country_code = '';
  481. $country_name = '';
  482. $insertid = '';
  483. $eprint_name = '';
  484. $view_type = '';
  485. $uniquebits = '';
  486. /* NJS 2007-01-29
  487. Moved date checking to the start of the loop, as there's
  488. no point in doing any of the regexp checks if we've already
  489. processed this log entry and will discard it anyway.
  490. */
  491. $date = $matches[2];
  492. /* NJS 2006-04-28
  493. Switched to timestamp rather than date-based comparison.
  494. First, clean up the Apache request date into something
  495. that strtotime understands. Note that the Apache log
  496. dates include time zone info by default.
  497. */
  498. $date = preg_replace("/:/"," ",$date,1); // Change first ":" to " ".
  499. $date = preg_replace("/\//", " ", $date); // Change all "/" to " ".
  500. // NJS 2007-01-30 Refactored $databaseB to more meaningful
  501. // $test_logdate.
  502. $test_logdate = strtotime($date);
  503.  
  504. // NJS 2007-01-30 Added test for log dates >= $start_time.
  505. if ( ( $test_logdate < $test_lastproc ) ||
  506. ( $test_logdate >= $test_starttime ) )
  507. continue;
  508. // Convert to properly formatted date string.
  509. $request_date = date('Y-m-d H:i:s O', $test_logdate);
  510. /* NJS 2005-12-16
  511. Determine country code and name.
  512. Check whether the IP number falls into any of the local
  513. intranet ranges. If so, then use that.
  514. */
  515. $ip = $matches[1];
  516. $ip_long = ip2long($ip);
  517. $found_country = FALSE;
  518. foreach ($local_IPs as $id => $addresses)
  519. {
  520. foreach ($addresses as $ip_range)
  521. {
  522. if (is_array($ip_range)) // check against lower/upper bounds
  523. {
  524. $found_country = (($ip_long >= $ip_range['lower'])
  525. && ($ip_long <= $ip_range['upper']));
  526. break;
  527. }
  528. else if (is_long($ip_range)) // data type sanity check
  529. {
  530. $found_country = ($ip_long == $ip_range);
  531. break;
  532. }
  533. else // something is seriously broken, ignore this entry
  534. {
  535. print "Unsupported data type " . gettype($ip_range) .
  536. " (value " . $ip_range .
  537. ") in \$local_IPs (expected long).\n";
  538. continue;
  539. }
  540. }
  541. if ($found_country)
  542. {
  543. list($country_name, $country_code) = explode(',', $id);
  544. break;
  545. }
  546. }
  547. // Otherwise, fall back to GeoIP.
  548. if (!$found_country)
  549. {
  550. $country_code = geoip_country_code_by_addr($gi, $ip);
  551. $country_name = geoip_country_name_by_addr($gi, $ip);
  552. }
  553. // end NJS 2005-12-16
  554. /* NJS 2007-01-26
  555. Check whether this is a bot reference.
  556. */
  557. $user_agent = $matches[4];
  558. $found_country = FALSE;
  559. foreach ($bot_patterns as $id => $patterns)
  560. {
  561. foreach ($patterns as $pat)
  562. {
  563. if (preg_match($pat, $user_agent, $matches2))
  564. {
  565. $found_country = TRUE;
  566. break;
  567. }
  568. }
  569. if ($found_country)
  570. {
  571. list($country_name, $country_code) = explode(',', $id);
  572. break;
  573. }
  574. }
  575. // end NJS 2007-01-26
  576. // Now sort out the remaining bits and we're done.
  577. $eprint_id = $matches[3];
  578. $uniquebits = $buffer;
  579. // NJS 2005-11-25 Added regexp for EPrints short URLs.
  580. if(preg_match("/GET \/archive\/0{1,8}\d{1,4}\/\d\d\//i",$buffer) || preg_match("/GET \/\d{1,4}\/\d\d\//i",$buffer)) {
  581. $view_type = "download";
  582. } else {
  583. $view_type = "abstract";
  584. }
  585. if(isset($eprintname[$archive_name . $eprint_id])) {
  586. $eprint_name = $eprintname[$archive_name . $eprint_id];
  587. } else {
  588. $eprint_name = getePrintName($eprints_connections[$archive_name],$archive_name,$eprint_id);
  589. $eprintname[$archive_name . $eprint_id] = $eprint_name;
  590. }
  591. if($eprint_name=='') {
  592. // Do nothing.
  593. } else {
  594. $eprint_name = mysql_escape_string($eprint_name);
  595. /* NJS 2006-04-25
  596. Requests containing apostrophes (') are dumped by
  597. MySQL unless we escape them. Looking in the GeoIP
  598. files I also see country names with apostrophes, so
  599. escape that as well. Everything else should be fine.
  600. */
  601. $uniquebits = mysql_escape_string($uniquebits);
  602. $country_name = mysql_escape_string($country_name);
  603. // end NJS 2006-04-25
  604. $query = "
  605. INSERT INTO view (uniquebits,archive_name,ip,request_date,archiveid,country_code,country_name,view_type,eprint_name)
  606. VALUES('".$uniquebits."','".$archive_name."','".$ip."','".$request_date."',".$eprint_id.",'".$country_code."','".$country_name."','".$view_type."','".$eprint_name."')";
  607. $result = mysql_query($query,$connect);
  608. $insertid = mysql_insert_id($connect);
  609. }
  610.  
  611. } else {
  612. // print "NO match" . "\n";
  613. }
  614. }
  615. fclose($handle);
  616. }
  617.  
  618. /*
  619. Keep track of where we are. Should avoid duplication of results
  620. if the script is run more than once on the same log file
  621. */
  622.  
  623. // NJS 2006-04-28 Switched value inserted to $start_time instead of $request_date.
  624. $query = "INSERT into lastproc (lastproc) values('".$start_time."')";
  625. $result = mysql_query($query,$connect);
  626.  
  627. #print "Records counted: $counter\n";
  628. #print "Last count: $request_date\n";
  629. foreach ($eprints_connections as $connection)
  630. {
  631. mysql_close($connection);
  632. }
  633. mysql_close($connect);
  634.  
  635. // Look up the title corresponding to the specified eprint id.
  636. function getePrintName($connection,$archive,$eprintid) {
  637. // NJS 2006-06-14: DB connection now passed as an argument.
  638. $db = mysql_select_db($archive,$connection);
  639. $query3 = "
  640. SELECT title
  641. FROM archive
  642. WHERE eprintid = $eprintid
  643. ";
  644. $result3 = mysql_query($query3,$connection);
  645. $title = '';
  646. $suffix = '';
  647. // NJS 2006-04-25 Added check for empty result, probably a deleted item.
  648. // Look in the deletion table for details.
  649. if (mysql_num_rows($result3) == 0) {
  650. $query3 = "
  651. SELECT title
  652. FROM deletion
  653. WHERE eprintid = $eprintid
  654. ";
  655. $result3 = mysql_query($query3,$connection);
  656. // If it's not in deletion, then we have no clue what it is.
  657. if (mysql_num_rows($result3) == 0) {
  658. $title = "Unknown item [$eprintid]";
  659. }
  660. else {
  661. $suffix = ' [deleted]';
  662. }
  663. }
  664. if ($title == '') {
  665. $row = mysql_fetch_assoc($result3);
  666. $row["title"] = trim($row["title"]);
  667. $row["title"] = preg_replace("/\s+/"," ",$row["title"]);
  668. $title = $row["title"];
  669. }
  670. return $title . $suffix;
  671. }
  672.  
  673. ?>
  674.