ManageSearchEngines.php 28 KB

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