ManageSearchEngines.php 27 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061
  1. <?php
  2. /**
  3. * This file contains all the screens that relate to search engines.
  4. *
  5. * Simple Machines Forum (SMF)
  6. *
  7. * @package SMF
  8. * @author Simple Machines http://www.simplemachines.org
  9. * @copyright 2011 Simple Machines
  10. * @license http://www.simplemachines.org/about/smf/license.php BSD
  11. *
  12. * @version 2.0
  13. */
  14. if (!defined('SMF'))
  15. die('Hacking attempt...');
  16. /**
  17. * Entry point for this section.
  18. */
  19. function SearchEngines()
  20. {
  21. global $context, $txt, $scripturl;
  22. isAllowedTo('admin_forum');
  23. loadLanguage('Search');
  24. loadTemplate('ManageSearch');
  25. $subActions = array(
  26. 'editspiders' => 'EditSpider',
  27. 'logs' => 'SpiderLogs',
  28. 'settings' => 'ManageSearchEngineSettings',
  29. 'spiders' => 'ViewSpiders',
  30. 'stats' => 'SpiderStats',
  31. );
  32. // Ensure we have a valid subaction.
  33. $context['sub_action'] = isset($_REQUEST['sa']) && isset($subActions[$_REQUEST['sa']]) ? $_REQUEST['sa'] : 'stats';
  34. $context['page_title'] = $txt['search_engines'];
  35. // Some more tab data.
  36. $context[$context['admin_menu_name']]['tab_data'] = array(
  37. 'title' => $txt['search_engines'],
  38. 'description' => $txt['search_engines_description'],
  39. );
  40. // Call the function!
  41. $subActions[$context['sub_action']]();
  42. }
  43. /**
  44. * This is really just the settings page.
  45. *
  46. * @param bool $return_config = false
  47. */
  48. function ManageSearchEngineSettings($return_config = false)
  49. {
  50. global $context, $txt, $modSettings, $scripturl, $sourcedir, $smcFunc;
  51. $config_vars = array(
  52. // How much detail?
  53. array('select', 'spider_mode', array($txt['spider_mode_off'], $txt['spider_mode_standard'], $txt['spider_mode_high'], $txt['spider_mode_vhigh']), 'onchange' => 'disableFields();'),
  54. 'spider_group' => array('select', 'spider_group', array($txt['spider_group_none'], $txt['membergroups_members'])),
  55. array('select', 'show_spider_online', array($txt['show_spider_online_no'], $txt['show_spider_online_summary'], $txt['show_spider_online_detail'], $txt['show_spider_online_detail_admin'])),
  56. );
  57. // Set up a message.
  58. $context['settings_message'] = '<span class="smalltext">' . sprintf($txt['spider_settings_desc'], $scripturl . '?action=admin;area=logs;sa=pruning;' . $context['session_var'] . '=' . $context['session_id']) . '</span>';
  59. // Do some javascript.
  60. $javascript_function = '
  61. function disableFields()
  62. {
  63. disabledState = document.getElementById(\'spider_mode\').value == 0;';
  64. foreach ($config_vars as $variable)
  65. if ($variable[1] != 'spider_mode')
  66. $javascript_function .= '
  67. if (document.getElementById(\'' . $variable[1] . '\'))
  68. document.getElementById(\'' . $variable[1] . '\').disabled = disabledState;';
  69. $javascript_function .= '
  70. }
  71. disableFields();';
  72. if ($return_config)
  73. return $config_vars;
  74. // We need to load the groups for the spider group thingy.
  75. $request = $smcFunc['db_query']('', '
  76. SELECT id_group, group_name
  77. FROM {db_prefix}membergroups
  78. WHERE id_group != {int:admin_group}
  79. AND id_group != {int:moderator_group}',
  80. array(
  81. 'admin_group' => 1,
  82. 'moderator_group' => 3,
  83. )
  84. );
  85. while ($row = $smcFunc['db_fetch_assoc']($request))
  86. $config_vars['spider_group'][2][$row['id_group']] = $row['group_name'];
  87. $smcFunc['db_free_result']($request);
  88. // Make sure it's valid - note that regular members are given id_group = 1 which is reversed in Load.php - no admins here!
  89. if (isset($_POST['spider_group']) && !isset($config_vars['spider_group'][2][$_POST['spider_group']]))
  90. $_POST['spider_group'] = 0;
  91. // We'll want this for our easy save.
  92. require_once($sourcedir . '/ManageServer.php');
  93. // Setup the template.
  94. $context['page_title'] = $txt['settings'];
  95. $context['sub_template'] = 'show_settings';
  96. // Are we saving them - are we??
  97. if (isset($_GET['save']))
  98. {
  99. checkSession();
  100. saveDBSettings($config_vars);
  101. recacheSpiderNames();
  102. redirectexit('action=admin;area=sengines;sa=settings');
  103. }
  104. // Final settings...
  105. $context['post_url'] = $scripturl . '?action=admin;area=sengines;save;sa=settings';
  106. $context['settings_title'] = $txt['settings'];
  107. $context['settings_insert_below'] = '
  108. <script type="text/javascript"><!-- // --><![CDATA[
  109. ' . $javascript_function . '
  110. // ]]></script>';
  111. // Prepare the settings...
  112. prepareDBSettingContext($config_vars);
  113. }
  114. /**
  115. * View a list of all the spiders we know about.
  116. */
  117. function ViewSpiders()
  118. {
  119. global $context, $txt, $sourcedir, $scripturl, $smcFunc;
  120. if (!isset($_SESSION['spider_stat']) || $_SESSION['spider_stat'] < time() - 60)
  121. {
  122. consolidateSpiderStats();
  123. $_SESSION['spider_stat'] = time();
  124. }
  125. // Are we adding a new one?
  126. if (!empty($_POST['addSpider']))
  127. return EditSpider();
  128. // User pressed the 'remove selection button'.
  129. elseif (!empty($_POST['removeSpiders']) && !empty($_POST['remove']) && is_array($_POST['remove']))
  130. {
  131. checkSession();
  132. // Make sure every entry is a proper integer.
  133. foreach ($_POST['remove'] as $index => $spider_id)
  134. $_POST['remove'][(int) $index] = (int) $spider_id;
  135. // Delete them all!
  136. $smcFunc['db_query']('', '
  137. DELETE FROM {db_prefix}spiders
  138. WHERE id_spider IN ({array_int:remove_list})',
  139. array(
  140. 'remove_list' => $_POST['remove'],
  141. )
  142. );
  143. $smcFunc['db_query']('', '
  144. DELETE FROM {db_prefix}log_spider_hits
  145. WHERE id_spider IN ({array_int:remove_list})',
  146. array(
  147. 'remove_list' => $_POST['remove'],
  148. )
  149. );
  150. $smcFunc['db_query']('', '
  151. DELETE FROM {db_prefix}log_spider_stats
  152. WHERE id_spider IN ({array_int:remove_list})',
  153. array(
  154. 'remove_list' => $_POST['remove'],
  155. )
  156. );
  157. cache_put_data('spider_search', null, 300);
  158. recacheSpiderNames();
  159. }
  160. // Get the last seens.
  161. $request = $smcFunc['db_query']('', '
  162. SELECT id_spider, MAX(last_seen) AS last_seen_time
  163. FROM {db_prefix}log_spider_stats
  164. GROUP BY id_spider',
  165. array(
  166. )
  167. );
  168. $context['spider_last_seen'] = array();
  169. while ($row = $smcFunc['db_fetch_assoc']($request))
  170. $context['spider_last_seen'][$row['id_spider']] = $row['last_seen_time'];
  171. $smcFunc['db_free_result']($request);
  172. $listOptions = array(
  173. 'id' => 'spider_list',
  174. 'items_per_page' => 20,
  175. 'base_href' => $scripturl . '?action=admin;area=sengines;sa=spiders',
  176. 'default_sort_col' => 'name',
  177. 'get_items' => array(
  178. 'function' => 'list_getSpiders',
  179. ),
  180. 'get_count' => array(
  181. 'function' => 'list_getNumSpiders',
  182. ),
  183. 'no_items_label' => $txt['spiders_no_entries'],
  184. 'columns' => array(
  185. 'name' => array(
  186. 'header' => array(
  187. 'value' => $txt['spider_name'],
  188. ),
  189. 'data' => array(
  190. 'function' => create_function('$rowData', '
  191. global $scripturl;
  192. return sprintf(\'<a href="%1$s?action=admin;area=sengines;sa=editspiders;sid=%2$d">%3$s</a>\', $scripturl, $rowData[\'id_spider\'], htmlspecialchars($rowData[\'spider_name\']));
  193. '),
  194. ),
  195. 'sort' => array(
  196. 'default' => 'spider_name',
  197. 'reverse' => 'spider_name DESC',
  198. ),
  199. ),
  200. 'last_seen' => array(
  201. 'header' => array(
  202. 'value' => $txt['spider_last_seen'],
  203. ),
  204. 'data' => array(
  205. 'function' => create_function('$rowData', '
  206. global $context, $txt;
  207. return isset($context[\'spider_last_seen\'][$rowData[\'id_spider\']]) ? timeformat($context[\'spider_last_seen\'][$rowData[\'id_spider\']]) : $txt[\'spider_last_never\'];
  208. '),
  209. ),
  210. ),
  211. 'user_agent' => array(
  212. 'header' => array(
  213. 'value' => $txt['spider_agent'],
  214. ),
  215. 'data' => array(
  216. 'db_htmlsafe' => 'user_agent',
  217. ),
  218. 'sort' => array(
  219. 'default' => 'user_agent',
  220. 'reverse' => 'user_agent DESC',
  221. ),
  222. ),
  223. 'ip_info' => array(
  224. 'header' => array(
  225. 'value' => $txt['spider_ip_info'],
  226. ),
  227. 'data' => array(
  228. 'db_htmlsafe' => 'ip_info',
  229. 'class' => 'smalltext',
  230. ),
  231. 'sort' => array(
  232. 'default' => 'ip_info',
  233. 'reverse' => 'ip_info DESC',
  234. ),
  235. ),
  236. 'check' => array(
  237. 'header' => array(
  238. 'value' => '<input type="checkbox" onclick="invertAll(this, this.form);" class="input_check" />',
  239. ),
  240. 'data' => array(
  241. 'sprintf' => array(
  242. 'format' => '<input type="checkbox" name="remove[]" value="%1$d" class="input_check" />',
  243. 'params' => array(
  244. 'id_spider' => false,
  245. ),
  246. ),
  247. 'style' => 'text-align: center',
  248. ),
  249. ),
  250. ),
  251. 'form' => array(
  252. 'href' => $scripturl . '?action=admin;area=sengines;sa=spiders',
  253. ),
  254. 'additional_rows' => array(
  255. array(
  256. 'position' => 'below_table_data',
  257. 'value' => '
  258. <input type="submit" name="addSpider" value="' . $txt['spiders_add'] . '" class="button_submit" />
  259. <input type="submit" name="removeSpiders" value="' . $txt['spiders_remove_selected'] . '" onclick="return confirm(\'' . $txt['spider_remove_selected_confirm'] . '\');" class="button_submit" />
  260. ',
  261. 'style' => 'text-align: right;',
  262. ),
  263. ),
  264. );
  265. require_once($sourcedir . '/Subs-List.php');
  266. createList($listOptions);
  267. $context['sub_template'] = 'show_list';
  268. $context['default_list'] = 'spider_list';
  269. }
  270. /**
  271. * Callback function for createList()
  272. */
  273. function list_getSpiders($start, $items_per_page, $sort)
  274. {
  275. global $smcFunc;
  276. $request = $smcFunc['db_query']('', '
  277. SELECT id_spider, spider_name, user_agent, ip_info
  278. FROM {db_prefix}spiders
  279. ORDER BY ' . $sort . '
  280. LIMIT ' . $start . ', ' . $items_per_page,
  281. array(
  282. )
  283. );
  284. $spiders = array();
  285. while ($row = $smcFunc['db_fetch_assoc']($request))
  286. $spiders[$row['id_spider']] = $row;
  287. $smcFunc['db_free_result']($request);
  288. return $spiders;
  289. }
  290. /**
  291. * Callback function for createList()
  292. */
  293. function list_getNumSpiders()
  294. {
  295. global $smcFunc;
  296. $request = $smcFunc['db_query']('', '
  297. SELECT COUNT(*) AS num_spiders
  298. FROM {db_prefix}spiders',
  299. array(
  300. )
  301. );
  302. list ($numSpiders) = $smcFunc['db_fetch_row']($request);
  303. $smcFunc['db_free_result']($request);
  304. return $numSpiders;
  305. }
  306. /**
  307. * Here we can add, and edit, spider info!
  308. */
  309. function EditSpider()
  310. {
  311. global $context, $smcFunc, $txt;
  312. // Some standard stuff.
  313. $context['id_spider'] = !empty($_GET['sid']) ? (int) $_GET['sid'] : 0;
  314. $context['page_title'] = $context['id_spider'] ? $txt['spiders_edit'] : $txt['spiders_add'];
  315. $context['sub_template'] = 'spider_edit';
  316. // Are we saving?
  317. if (!empty($_POST['save']))
  318. {
  319. checkSession();
  320. $ips = array();
  321. // Check the IP range is valid.
  322. $ip_sets = explode(',', $_POST['spider_ip']);
  323. foreach ($ip_sets as $set)
  324. {
  325. $test = ip2range(trim($set));
  326. if (!empty($test))
  327. $ips[] = $set;
  328. }
  329. $ips = implode(',', $ips);
  330. // Goes in as it is...
  331. if ($context['id_spider'])
  332. $smcFunc['db_query']('', '
  333. UPDATE {db_prefix}spiders
  334. SET spider_name = {string:spider_name}, user_agent = {string:spider_agent},
  335. ip_info = {string:ip_info}
  336. WHERE id_spider = {int:current_spider}',
  337. array(
  338. 'current_spider' => $context['id_spider'],
  339. 'spider_name' => $_POST['spider_name'],
  340. 'spider_agent' => $_POST['spider_agent'],
  341. 'ip_info' => $ips,
  342. )
  343. );
  344. else
  345. $smcFunc['db_insert']('insert',
  346. '{db_prefix}spiders',
  347. array(
  348. 'spider_name' => 'string', 'user_agent' => 'string', 'ip_info' => 'string',
  349. ),
  350. array(
  351. $_POST['spider_name'], $_POST['spider_agent'], $ips,
  352. ),
  353. array('id_spider')
  354. );
  355. // Order by user agent length.
  356. sortSpiderTable();
  357. cache_put_data('spider_search', null, 300);
  358. recacheSpiderNames();
  359. redirectexit('action=admin;area=sengines;sa=spiders');
  360. }
  361. // The default is new.
  362. $context['spider'] = array(
  363. 'id' => 0,
  364. 'name' => '',
  365. 'agent' => '',
  366. 'ip_info' => '',
  367. );
  368. // An edit?
  369. if ($context['id_spider'])
  370. {
  371. $request = $smcFunc['db_query']('', '
  372. SELECT id_spider, spider_name, user_agent, ip_info
  373. FROM {db_prefix}spiders
  374. WHERE id_spider = {int:current_spider}',
  375. array(
  376. 'current_spider' => $context['id_spider'],
  377. )
  378. );
  379. if ($row = $smcFunc['db_fetch_assoc']($request))
  380. $context['spider'] = array(
  381. 'id' => $row['id_spider'],
  382. 'name' => $row['spider_name'],
  383. 'agent' => $row['user_agent'],
  384. 'ip_info' => $row['ip_info'],
  385. );
  386. $smcFunc['db_free_result']($request);
  387. }
  388. }
  389. /**
  390. * Do we think the current user is a spider?
  391. * @todo Should this not be... you know... in a different file?
  392. */
  393. function SpiderCheck()
  394. {
  395. global $modSettings, $smcFunc;
  396. if (isset($_SESSION['id_robot']))
  397. unset($_SESSION['id_robot']);
  398. $_SESSION['robot_check'] = time();
  399. // We cache the spider data for five minutes if we can.
  400. if (!empty($modSettings['cache_enable']))
  401. $spider_data = cache_get_data('spider_search', 300);
  402. if (!isset($spider_data) || $spider_data === NULL)
  403. {
  404. $request = $smcFunc['db_query']('spider_check', '
  405. SELECT id_spider, user_agent, ip_info
  406. FROM {db_prefix}spiders',
  407. array(
  408. )
  409. );
  410. $spider_data = array();
  411. while ($row = $smcFunc['db_fetch_assoc']($request))
  412. $spider_data[] = $row;
  413. $smcFunc['db_free_result']($request);
  414. if (!empty($modSettings['cache_enable']))
  415. cache_put_data('spider_search', $spider_data, 300);
  416. }
  417. if (empty($spider_data))
  418. return false;
  419. // Only do these bits once.
  420. $ci_user_agent = strtolower($_SERVER['HTTP_USER_AGENT']);
  421. preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $_SERVER['REMOTE_ADDR'], $ip_parts);
  422. foreach ($spider_data as $spider)
  423. {
  424. // User agent is easy.
  425. if (!empty($spider['user_agent']) && strpos($ci_user_agent, strtolower($spider['user_agent'])) !== false)
  426. $_SESSION['id_robot'] = $spider['id_spider'];
  427. // IP stuff is harder.
  428. elseif (!empty($ip_parts))
  429. {
  430. $ips = explode(',', $spider['ip_info']);
  431. foreach ($ips as $ip)
  432. {
  433. $ip = ip2range($ip);
  434. if (!empty($ip))
  435. {
  436. foreach ($ip as $key => $value)
  437. {
  438. if ($value['low'] > $ip_parts[$key + 1] || $value['high'] < $ip_parts[$key + 1])
  439. break;
  440. elseif ($key == 3)
  441. $_SESSION['id_robot'] = $spider['id_spider'];
  442. }
  443. }
  444. }
  445. }
  446. if (isset($_SESSION['id_robot']))
  447. break;
  448. }
  449. // If this is low server tracking then log the spider here as oppossed to the main logging function.
  450. if (!empty($modSettings['spider_mode']) && $modSettings['spider_mode'] == 1 && !empty($_SESSION['id_robot']))
  451. logSpider();
  452. return !empty($_SESSION['id_robot']) ? $_SESSION['id_robot'] : 0;
  453. }
  454. /**
  455. * Log the spider presence online.
  456. * @todo Different file?
  457. */
  458. function logSpider()
  459. {
  460. global $smcFunc, $modSettings, $context;
  461. if (empty($modSettings['spider_mode']) || empty($_SESSION['id_robot']))
  462. return;
  463. // Attempt to update today's entry.
  464. if ($modSettings['spider_mode'] == 1)
  465. {
  466. $date = strftime('%Y-%m-%d', forum_time(false));
  467. $smcFunc['db_query']('', '
  468. UPDATE {db_prefix}log_spider_stats
  469. SET last_seen = {int:current_time}, page_hits = page_hits + 1
  470. WHERE id_spider = {int:current_spider}
  471. AND stat_date = {date:current_date}',
  472. array(
  473. 'current_date' => $date,
  474. 'current_time' => time(),
  475. 'current_spider' => $_SESSION['id_robot'],
  476. )
  477. );
  478. // Nothing updated?
  479. if ($smcFunc['db_affected_rows']() == 0)
  480. {
  481. $smcFunc['db_insert']('ignore',
  482. '{db_prefix}log_spider_stats',
  483. array(
  484. 'id_spider' => 'int', 'last_seen' => 'int', 'stat_date' => 'date', 'page_hits' => 'int',
  485. ),
  486. array(
  487. $_SESSION['id_robot'], time(), $date, 1,
  488. ),
  489. array('id_spider', 'stat_date')
  490. );
  491. }
  492. }
  493. // If we're tracking better stats than track, better stats - we sort out the today thing later.
  494. else
  495. {
  496. if ($modSettings['spider_mode'] > 2)
  497. {
  498. $url = $_GET + array('USER_AGENT' => $_SERVER['HTTP_USER_AGENT']);
  499. unset($url['sesc'], $url[$context['session_var']]);
  500. $url = serialize($url);
  501. }
  502. else
  503. $url = '';
  504. $smcFunc['db_insert']('insert',
  505. '{db_prefix}log_spider_hits',
  506. array('id_spider' => 'int', 'log_time' => 'int', 'url' => 'string'),
  507. array($_SESSION['id_robot'], time(), $url),
  508. array()
  509. );
  510. }
  511. }
  512. /**
  513. * This function takes any unprocessed hits and turns them into stats.
  514. */
  515. function consolidateSpiderStats()
  516. {
  517. global $smcFunc;
  518. $request = $smcFunc['db_query']('consolidate_spider_stats', '
  519. SELECT id_spider, MAX(log_time) AS last_seen, COUNT(*) AS num_hits
  520. FROM {db_prefix}log_spider_hits
  521. WHERE processed = {int:not_processed}
  522. GROUP BY id_spider, MONTH(log_time), DAYOFMONTH(log_time)',
  523. array(
  524. 'not_processed' => 0,
  525. )
  526. );
  527. $spider_hits = array();
  528. while ($row = $smcFunc['db_fetch_assoc']($request))
  529. $spider_hits[] = $row;
  530. $smcFunc['db_free_result']($request);
  531. if (empty($spider_hits))
  532. return;
  533. // Attempt to update the master data.
  534. $stat_inserts = array();
  535. foreach ($spider_hits as $stat)
  536. {
  537. // We assume the max date is within the right day.
  538. $date = strftime('%Y-%m-%d', $stat['last_seen']);
  539. $smcFunc['db_query']('', '
  540. UPDATE {db_prefix}log_spider_stats
  541. SET page_hits = page_hits + ' . $stat['num_hits'] . ',
  542. last_seen = CASE WHEN last_seen > {int:last_seen} THEN last_seen ELSE {int:last_seen} END
  543. WHERE id_spider = {int:current_spider}
  544. AND stat_date = {date:last_seen_date}',
  545. array(
  546. 'last_seen_date' => $date,
  547. 'last_seen' => $stat['last_seen'],
  548. 'current_spider' => $stat['id_spider'],
  549. )
  550. );
  551. if ($smcFunc['db_affected_rows']() == 0)
  552. $stat_inserts[] = array($date, $stat['id_spider'], $stat['num_hits'], $stat['last_seen']);
  553. }
  554. // New stats?
  555. if (!empty($stat_inserts))
  556. $smcFunc['db_insert']('ignore',
  557. '{db_prefix}log_spider_stats',
  558. array('stat_date' => 'date', 'id_spider' => 'int', 'page_hits' => 'int', 'last_seen' => 'int'),
  559. $stat_inserts,
  560. array('stat_date', 'id_spider')
  561. );
  562. // All processed.
  563. $smcFunc['db_query']('', '
  564. UPDATE {db_prefix}log_spider_hits
  565. SET processed = {int:is_processed}
  566. WHERE processed = {int:not_processed}',
  567. array(
  568. 'is_processed' => 1,
  569. 'not_processed' => 0,
  570. )
  571. );
  572. }
  573. /**
  574. * See what spiders have been up to.
  575. */
  576. function SpiderLogs()
  577. {
  578. global $context, $txt, $sourcedir, $scripturl, $smcFunc, $modSettings;
  579. // Load the template and language just incase.
  580. loadLanguage('Search');
  581. loadTemplate('ManageSearch');
  582. // Did they want to delete some entries?
  583. if (!empty($_POST['delete_entries']) && isset($_POST['older']))
  584. {
  585. checkSession();
  586. $deleteTime = time() - (((int) $_POST['older']) * 24 * 60 * 60);
  587. // Delete the entires.
  588. $smcFunc['db_query']('', '
  589. DELETE FROM {db_prefix}log_spider_hits
  590. WHERE log_time < {int:delete_period}',
  591. array(
  592. 'delete_period' => $deleteTime,
  593. )
  594. );
  595. }
  596. $listOptions = array(
  597. 'id' => 'spider_logs',
  598. 'items_per_page' => 20,
  599. 'title' => $txt['spider_logs'],
  600. 'no_items_label' => $txt['spider_logs_empty'],
  601. 'base_href' => $context['admin_area'] == 'sengines' ? $scripturl . '?action=admin;area=sengines;sa=logs' : $scripturl . '?action=admin;area=logs;sa=spiderlog',
  602. 'default_sort_col' => 'log_time',
  603. 'get_items' => array(
  604. 'function' => 'list_getSpiderLogs',
  605. ),
  606. 'get_count' => array(
  607. 'function' => 'list_getNumSpiderLogs',
  608. ),
  609. 'columns' => array(
  610. 'name' => array(
  611. 'header' => array(
  612. 'value' => $txt['spider'],
  613. ),
  614. 'data' => array(
  615. 'db' => 'spider_name',
  616. ),
  617. 'sort' => array(
  618. 'default' => 's.spider_name',
  619. 'reverse' => 's.spider_name DESC',
  620. ),
  621. ),
  622. 'log_time' => array(
  623. 'header' => array(
  624. 'value' => $txt['spider_time'],
  625. ),
  626. 'data' => array(
  627. 'function' => create_function('$rowData', '
  628. return timeformat($rowData[\'log_time\']);
  629. '),
  630. ),
  631. 'sort' => array(
  632. 'default' => 'sl.id_hit DESC',
  633. 'reverse' => 'sl.id_hit',
  634. ),
  635. ),
  636. 'viewing' => array(
  637. 'header' => array(
  638. 'value' => $txt['spider_viewing'],
  639. ),
  640. 'data' => array(
  641. 'db' => 'url',
  642. ),
  643. ),
  644. ),
  645. 'additional_rows' => array(
  646. array(
  647. 'position' => 'after_title',
  648. 'value' => $txt['spider_logs_info'],
  649. 'class' => 'smalltext',
  650. ),
  651. ),
  652. );
  653. require_once($sourcedir . '/Subs-List.php');
  654. createList($listOptions);
  655. // Now determine the actions of the URLs.
  656. if (!empty($context['spider_logs']['rows']))
  657. {
  658. $urls = array();
  659. // Grab the current /url.
  660. foreach ($context['spider_logs']['rows'] as $k => $row)
  661. {
  662. // Feature disabled?
  663. if (empty($row['viewing']['value']) && isset($modSettings['spider_mode']) && $modSettings['spider_mode'] < 3)
  664. $context['spider_logs']['rows'][$k]['viewing']['value'] = '<em>' . $txt['spider_disabled'] . '</em>';
  665. else
  666. $urls[$k] = array($row['viewing']['value'], -1);
  667. }
  668. // Now stick in the new URLs.
  669. require_once($sourcedir . '/Who.php');
  670. $urls = determineActions($urls, 'whospider_');
  671. foreach ($urls as $k => $new_url)
  672. {
  673. $context['spider_logs']['rows'][$k]['viewing']['value'] = $new_url;
  674. }
  675. }
  676. $context['page_title'] = $txt['spider_logs'];
  677. $context['sub_template'] = 'show_spider_logs';
  678. $context['default_list'] = 'spider_logs';
  679. }
  680. /**
  681. * Callback function for createList()
  682. */
  683. function list_getSpiderLogs($start, $items_per_page, $sort)
  684. {
  685. global $smcFunc;
  686. $request = $smcFunc['db_query']('', '
  687. SELECT sl.id_spider, sl.url, sl.log_time, s.spider_name
  688. FROM {db_prefix}log_spider_hits AS sl
  689. INNER JOIN {db_prefix}spiders AS s ON (s.id_spider = sl.id_spider)
  690. ORDER BY ' . $sort . '
  691. LIMIT ' . $start . ', ' . $items_per_page,
  692. array(
  693. )
  694. );
  695. $spider_logs = array();
  696. while ($row = $smcFunc['db_fetch_assoc']($request))
  697. $spider_logs[] = $row;
  698. $smcFunc['db_free_result']($request);
  699. return $spider_logs;
  700. }
  701. /**
  702. * Callback function for createList()
  703. */
  704. function list_getNumSpiderLogs()
  705. {
  706. global $smcFunc;
  707. $request = $smcFunc['db_query']('', '
  708. SELECT COUNT(*) AS num_logs
  709. FROM {db_prefix}log_spider_hits',
  710. array(
  711. )
  712. );
  713. list ($numLogs) = $smcFunc['db_fetch_row']($request);
  714. $smcFunc['db_free_result']($request);
  715. return $numLogs;
  716. }
  717. /**
  718. * Show the spider statistics.
  719. */
  720. function SpiderStats()
  721. {
  722. global $context, $txt, $sourcedir, $scripturl, $smcFunc;
  723. // Force an update of the stats every 60 seconds.
  724. if (!isset($_SESSION['spider_stat']) || $_SESSION['spider_stat'] < time() - 60)
  725. {
  726. consolidateSpiderStats();
  727. $_SESSION['spider_stat'] = time();
  728. }
  729. // Get the earliest and latest dates.
  730. $request = $smcFunc['db_query']('', '
  731. SELECT MIN(stat_date) AS first_date, MAX(stat_date) AS last_date
  732. FROM {db_prefix}log_spider_stats',
  733. array(
  734. )
  735. );
  736. list ($min_date, $max_date) = $smcFunc['db_fetch_row']($request);
  737. $smcFunc['db_free_result']($request);
  738. $min_year = (int) substr($min_date, 0, 4);
  739. $max_year = (int) substr($max_date, 0, 4);
  740. $min_month = (int) substr($min_date, 5, 2);
  741. $max_month = (int) substr($max_date, 5, 2);
  742. // Prepare the dates for the drop down.
  743. $date_choices = array();
  744. for ($y = $min_year; $y <= $max_year; $y++)
  745. for ($m = 1; $m <= 12; $m++)
  746. {
  747. // This doesn't count?
  748. if ($y == $min_year && $m < $min_month)
  749. continue;
  750. if ($y == $max_year && $m > $max_month)
  751. break;
  752. $date_choices[$y . $m] = $txt['months_short'][$m] . ' ' . $y;
  753. }
  754. // What are we currently viewing?
  755. $current_date = isset($_REQUEST['new_date']) && isset($date_choices[$_REQUEST['new_date']]) ? $_REQUEST['new_date'] : $max_date;
  756. // Prepare the HTML.
  757. $date_select = '
  758. ' . $txt['spider_stats_select_month'] . ':
  759. <select name="new_date" onchange="document.spider_stat_list.submit();">';
  760. if (empty($date_choices))
  761. $date_select .= '
  762. <option></option>';
  763. else
  764. foreach ($date_choices as $id => $text)
  765. $date_select .= '
  766. <option value="' . $id . '"' . ($current_date == $id ? ' selected="selected"' : '') . '>' . $text . '</option>';
  767. $date_select .= '
  768. </select>
  769. <noscript>
  770. <input type="submit" name="go" value="' . $txt['go'] . '" class="button_submit" />
  771. </noscript>';
  772. // If we manually jumped to a date work out the offset.
  773. if (isset($_REQUEST['new_date']))
  774. {
  775. $date_query = sprintf('%04d-%02d-01', substr($current_date, 0, 4), substr($current_date, 4));
  776. $request = $smcFunc['db_query']('', '
  777. SELECT COUNT(*) AS offset
  778. FROM {db_prefix}log_spider_stats
  779. WHERE stat_date < {date:date_being_viewed}',
  780. array(
  781. 'date_being_viewed' => $date_query,
  782. )
  783. );
  784. list ($_REQUEST['start']) = $smcFunc['db_fetch_row']($request);
  785. $smcFunc['db_free_result']($request);
  786. }
  787. $listOptions = array(
  788. 'id' => 'spider_stat_list',
  789. 'items_per_page' => 20,
  790. 'base_href' => $scripturl . '?action=admin;area=sengines;sa=stats',
  791. 'default_sort_col' => 'stat_date',
  792. 'get_items' => array(
  793. 'function' => 'list_getSpiderStats',
  794. ),
  795. 'get_count' => array(
  796. 'function' => 'list_getNumSpiderStats',
  797. ),
  798. 'no_items_label' => $txt['spider_stats_no_entries'],
  799. 'columns' => array(
  800. 'stat_date' => array(
  801. 'header' => array(
  802. 'value' => $txt['date'],
  803. ),
  804. 'data' => array(
  805. 'db' => 'stat_date',
  806. ),
  807. 'sort' => array(
  808. 'default' => 'stat_date',
  809. 'reverse' => 'stat_date DESC',
  810. ),
  811. ),
  812. 'name' => array(
  813. 'header' => array(
  814. 'value' => $txt['spider_name'],
  815. ),
  816. 'data' => array(
  817. 'db' => 'spider_name',
  818. ),
  819. 'sort' => array(
  820. 'default' => 's.spider_name',
  821. 'reverse' => 's.spider_name DESC',
  822. ),
  823. ),
  824. 'page_hits' => array(
  825. 'header' => array(
  826. 'value' => $txt['spider_stats_page_hits'],
  827. ),
  828. 'data' => array(
  829. 'db' => 'page_hits',
  830. ),
  831. 'sort' => array(
  832. 'default' => 'ss.page_hits',
  833. 'reverse' => 'ss.page_hits DESC',
  834. ),
  835. ),
  836. ),
  837. 'form' => array(
  838. 'href' => $scripturl . '?action=admin;area=sengines;sa=stats',
  839. 'name' => 'spider_stat_list',
  840. ),
  841. 'additional_rows' => array(
  842. array(
  843. 'position' => 'below_table_data',
  844. 'value' => $date_select,
  845. 'style' => 'text-align: right;',
  846. ),
  847. ),
  848. );
  849. require_once($sourcedir . '/Subs-List.php');
  850. createList($listOptions);
  851. $context['sub_template'] = 'show_list';
  852. $context['default_list'] = 'spider_stat_list';
  853. }
  854. /**
  855. * Callback function for createList()
  856. */
  857. function list_getSpiderStats($start, $items_per_page, $sort)
  858. {
  859. global $smcFunc;
  860. $request = $smcFunc['db_query']('', '
  861. SELECT ss.id_spider, ss.stat_date, ss.page_hits, s.spider_name
  862. FROM {db_prefix}log_spider_stats AS ss
  863. INNER JOIN {db_prefix}spiders AS s ON (s.id_spider = ss.id_spider)
  864. ORDER BY ' . $sort . '
  865. LIMIT ' . $start . ', ' . $items_per_page,
  866. array(
  867. )
  868. );
  869. $spider_stats = array();
  870. while ($row = $smcFunc['db_fetch_assoc']($request))
  871. $spider_stats[] = $row;
  872. $smcFunc['db_free_result']($request);
  873. return $spider_stats;
  874. }
  875. /**
  876. * Callback function for createList()
  877. */
  878. function list_getNumSpiderStats()
  879. {
  880. global $smcFunc;
  881. $request = $smcFunc['db_query']('', '
  882. SELECT COUNT(*) AS num_stats
  883. FROM {db_prefix}log_spider_stats',
  884. array(
  885. )
  886. );
  887. list ($numStats) = $smcFunc['db_fetch_row']($request);
  888. $smcFunc['db_free_result']($request);
  889. return $numStats;
  890. }
  891. /**
  892. * Recache spider names?
  893. */
  894. function recacheSpiderNames()
  895. {
  896. global $smcFunc;
  897. $request = $smcFunc['db_query']('', '
  898. SELECT id_spider, spider_name
  899. FROM {db_prefix}spiders',
  900. array(
  901. )
  902. );
  903. $spiders = array();
  904. while ($row = $smcFunc['db_fetch_assoc']($request))
  905. $spiders[$row['id_spider']] = $row['spider_name'];
  906. $smcFunc['db_free_result']($request);
  907. updateSettings(array('spider_name_cache' => serialize($spiders)));
  908. }
  909. /**
  910. * Sort the search engine table by user agent name to avoid misidentification of engine.
  911. */
  912. function sortSpiderTable()
  913. {
  914. global $smcFunc;
  915. db_extend('packages');
  916. // Add a sorting column.
  917. $smcFunc['db_add_column']('{db_prefix}spiders', array('name' => 'temp_order', 'size' => 8, 'type' => 'mediumint', 'null' => false));
  918. // Set the contents of this column.
  919. $smcFunc['db_query']('set_spider_order', '
  920. UPDATE {db_prefix}spiders
  921. SET temp_order = LENGTH(user_agent)',
  922. array(
  923. )
  924. );
  925. // Order the table by this column.
  926. $smcFunc['db_query']('alter_table_spiders', '
  927. ALTER TABLE {db_prefix}spiders
  928. ORDER BY temp_order DESC',
  929. array(
  930. 'db_error_skip' => true,
  931. )
  932. );
  933. // Remove the sorting column.
  934. $smcFunc['db_remove_column']('{db_prefix}spiders', 'temp_order');
  935. }
  936. ?>