PageRenderTime 53ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/website/library/Zend/Search/Lucene/Index/SegmentInfo.php

https://bitbucket.org/efdac/e-forest_platform
PHP | 2130 lines | 1205 code | 309 blank | 616 comment | 337 complexity | 4b1227aadc2de77bea2eeb664cb83af8 MD5 | raw file
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Search_Lucene
  17. * @subpackage Index
  18. * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
  19. * @license http://framework.zend.com/license/new-bsd New BSD License
  20. * @version $Id: SegmentInfo.php 20096 2010-01-06 02:05:09Z bkarwin $
  21. */
  22. /** Zend_Search_Lucene_Index_TermsStream_Interface */
  23. require_once 'Zend/Search/Lucene/Index/TermsStream/Interface.php';
  24. /** Zend_Search_Lucene_Search_Similarity */
  25. require_once 'Zend/Search/Lucene/Search/Similarity.php';
  26. /** Zend_Search_Lucene_Index_FieldInfo */
  27. require_once 'Zend/Search/Lucene/Index/FieldInfo.php';
  28. /** Zend_Search_Lucene_Index_Term */
  29. require_once 'Zend/Search/Lucene/Index/Term.php';
  30. /** Zend_Search_Lucene_Index_TermInfo */
  31. require_once 'Zend/Search/Lucene/Index/TermInfo.php';
  32. /**
  33. * @category Zend
  34. * @package Zend_Search_Lucene
  35. * @subpackage Index
  36. * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
  37. * @license http://framework.zend.com/license/new-bsd New BSD License
  38. */
  39. class Zend_Search_Lucene_Index_SegmentInfo implements Zend_Search_Lucene_Index_TermsStream_Interface
  40. {
  41. /**
  42. * "Full scan vs fetch" boundary.
  43. *
  44. * If filter selectivity is less than this value, then full scan is performed
  45. * (since term entries fetching has some additional overhead).
  46. */
  47. const FULL_SCAN_VS_FETCH_BOUNDARY = 5;
  48. /**
  49. * Number of docs in a segment
  50. *
  51. * @var integer
  52. */
  53. private $_docCount;
  54. /**
  55. * Segment name
  56. *
  57. * @var string
  58. */
  59. private $_name;
  60. /**
  61. * Term Dictionary Index
  62. *
  63. * Array of arrays (Zend_Search_Lucene_Index_Term objects are represented as arrays because
  64. * of performance considerations)
  65. * [0] -> $termValue
  66. * [1] -> $termFieldNum
  67. *
  68. * Corresponding Zend_Search_Lucene_Index_TermInfo object stored in the $_termDictionaryInfos
  69. *
  70. * @var array
  71. */
  72. private $_termDictionary;
  73. /**
  74. * Term Dictionary Index TermInfos
  75. *
  76. * Array of arrays (Zend_Search_Lucene_Index_TermInfo objects are represented as arrays because
  77. * of performance considerations)
  78. * [0] -> $docFreq
  79. * [1] -> $freqPointer
  80. * [2] -> $proxPointer
  81. * [3] -> $skipOffset
  82. * [4] -> $indexPointer
  83. *
  84. * @var array
  85. */
  86. private $_termDictionaryInfos;
  87. /**
  88. * Segment fields. Array of Zend_Search_Lucene_Index_FieldInfo objects for this segment
  89. *
  90. * @var array
  91. */
  92. private $_fields;
  93. /**
  94. * Field positions in a dictionary.
  95. * (Term dictionary contains filelds ordered by names)
  96. *
  97. * @var array
  98. */
  99. private $_fieldsDicPositions;
  100. /**
  101. * Associative array where the key is the file name and the value is data offset
  102. * in a compound segment file (.csf).
  103. *
  104. * @var array
  105. */
  106. private $_segFiles;
  107. /**
  108. * Associative array where the key is the file name and the value is file size (.csf).
  109. *
  110. * @var array
  111. */
  112. private $_segFileSizes;
  113. /**
  114. * Delete file generation number
  115. *
  116. * -2 means autodetect latest delete generation
  117. * -1 means 'there is no delete file'
  118. * 0 means pre-2.1 format delete file
  119. * X specifies used delete file
  120. *
  121. * @var integer
  122. */
  123. private $_delGen;
  124. /**
  125. * Segment has single norms file
  126. *
  127. * If true then one .nrm file is used for all fields
  128. * Otherwise .fN files are used
  129. *
  130. * @var boolean
  131. */
  132. private $_hasSingleNormFile;
  133. /**
  134. * Use compound segment file (*.cfs) to collect all other segment files
  135. * (excluding .del files)
  136. *
  137. * @var boolean
  138. */
  139. private $_isCompound;
  140. /**
  141. * File system adapter.
  142. *
  143. * @var Zend_Search_Lucene_Storage_Directory_Filesystem
  144. */
  145. private $_directory;
  146. /**
  147. * Normalization factors.
  148. * An array fieldName => normVector
  149. * normVector is a binary string.
  150. * Each byte corresponds to an indexed document in a segment and
  151. * encodes normalization factor (float value, encoded by
  152. * Zend_Search_Lucene_Search_Similarity::encodeNorm())
  153. *
  154. * @var array
  155. */
  156. private $_norms = array();
  157. /**
  158. * List of deleted documents.
  159. * bitset if bitset extension is loaded or array otherwise.
  160. *
  161. * @var mixed
  162. */
  163. private $_deleted = null;
  164. /**
  165. * $this->_deleted update flag
  166. *
  167. * @var boolean
  168. */
  169. private $_deletedDirty = false;
  170. /**
  171. * True if segment uses shared doc store
  172. *
  173. * @var boolean
  174. */
  175. private $_usesSharedDocStore;
  176. /*
  177. * Shared doc store options.
  178. * It's an assotiative array with the following items:
  179. * - 'offset' => $docStoreOffset The starting document in the shared doc store files where this segment's documents begin
  180. * - 'segment' => $docStoreSegment The name of the segment that has the shared doc store files.
  181. * - 'isCompound' => $docStoreIsCompoundFile True, if compound file format is used for the shared doc store files (.cfx file).
  182. */
  183. private $_sharedDocStoreOptions;
  184. /**
  185. * Zend_Search_Lucene_Index_SegmentInfo constructor
  186. *
  187. * @param Zend_Search_Lucene_Storage_Directory $directory
  188. * @param string $name
  189. * @param integer $docCount
  190. * @param integer $delGen
  191. * @param array|null $docStoreOptions
  192. * @param boolean $hasSingleNormFile
  193. * @param boolean $isCompound
  194. */
  195. public function __construct(Zend_Search_Lucene_Storage_Directory $directory, $name, $docCount, $delGen = 0, $docStoreOptions = null, $hasSingleNormFile = false, $isCompound = null)
  196. {
  197. $this->_directory = $directory;
  198. $this->_name = $name;
  199. $this->_docCount = $docCount;
  200. if ($docStoreOptions !== null) {
  201. $this->_usesSharedDocStore = true;
  202. $this->_sharedDocStoreOptions = $docStoreOptions;
  203. if ($docStoreOptions['isCompound']) {
  204. $cfxFile = $this->_directory->getFileObject($docStoreOptions['segment'] . '.cfx');
  205. $cfxFilesCount = $cfxFile->readVInt();
  206. $cfxFiles = array();
  207. $cfxFileSizes = array();
  208. for ($count = 0; $count < $cfxFilesCount; $count++) {
  209. $dataOffset = $cfxFile->readLong();
  210. if ($count != 0) {
  211. $cfxFileSizes[$fileName] = $dataOffset - end($cfxFiles);
  212. }
  213. $fileName = $cfxFile->readString();
  214. $cfxFiles[$fileName] = $dataOffset;
  215. }
  216. if ($count != 0) {
  217. $cfxFileSizes[$fileName] = $this->_directory->fileLength($docStoreOptions['segment'] . '.cfx') - $dataOffset;
  218. }
  219. $this->_sharedDocStoreOptions['files'] = $cfxFiles;
  220. $this->_sharedDocStoreOptions['fileSizes'] = $cfxFileSizes;
  221. }
  222. }
  223. $this->_hasSingleNormFile = $hasSingleNormFile;
  224. $this->_delGen = $delGen;
  225. $this->_termDictionary = null;
  226. if ($isCompound !== null) {
  227. $this->_isCompound = $isCompound;
  228. } else {
  229. // It's a pre-2.1 segment or isCompound is set to 'unknown'
  230. // Detect if segment uses compound file
  231. require_once 'Zend/Search/Lucene/Exception.php';
  232. try {
  233. // Try to open compound file
  234. $this->_directory->getFileObject($name . '.cfs');
  235. // Compound file is found
  236. $this->_isCompound = true;
  237. } catch (Zend_Search_Lucene_Exception $e) {
  238. if (strpos($e->getMessage(), 'is not readable') !== false) {
  239. // Compound file is not found or is not readable
  240. $this->_isCompound = false;
  241. } else {
  242. throw new Zend_Search_Lucene_Exception($e->getMessage(), $e->getCode(), $e);
  243. }
  244. }
  245. }
  246. $this->_segFiles = array();
  247. if ($this->_isCompound) {
  248. $cfsFile = $this->_directory->getFileObject($name . '.cfs');
  249. $segFilesCount = $cfsFile->readVInt();
  250. for ($count = 0; $count < $segFilesCount; $count++) {
  251. $dataOffset = $cfsFile->readLong();
  252. if ($count != 0) {
  253. $this->_segFileSizes[$fileName] = $dataOffset - end($this->_segFiles);
  254. }
  255. $fileName = $cfsFile->readString();
  256. $this->_segFiles[$fileName] = $dataOffset;
  257. }
  258. if ($count != 0) {
  259. $this->_segFileSizes[$fileName] = $this->_directory->fileLength($name . '.cfs') - $dataOffset;
  260. }
  261. }
  262. $fnmFile = $this->openCompoundFile('.fnm');
  263. $fieldsCount = $fnmFile->readVInt();
  264. $fieldNames = array();
  265. $fieldNums = array();
  266. $this->_fields = array();
  267. for ($count=0; $count < $fieldsCount; $count++) {
  268. $fieldName = $fnmFile->readString();
  269. $fieldBits = $fnmFile->readByte();
  270. $this->_fields[$count] = new Zend_Search_Lucene_Index_FieldInfo($fieldName,
  271. $fieldBits & 0x01 /* field is indexed */,
  272. $count,
  273. $fieldBits & 0x02 /* termvectors are stored */,
  274. $fieldBits & 0x10 /* norms are omitted */,
  275. $fieldBits & 0x20 /* payloads are stored */);
  276. if ($fieldBits & 0x10) {
  277. // norms are omitted for the indexed field
  278. $this->_norms[$count] = str_repeat(chr(Zend_Search_Lucene_Search_Similarity::encodeNorm(1.0)), $docCount);
  279. }
  280. $fieldNums[$count] = $count;
  281. $fieldNames[$count] = $fieldName;
  282. }
  283. array_multisort($fieldNames, SORT_ASC, SORT_REGULAR, $fieldNums);
  284. $this->_fieldsDicPositions = array_flip($fieldNums);
  285. if ($this->_delGen == -2) {
  286. // SegmentInfo constructor is invoked from index writer
  287. // Autodetect current delete file generation number
  288. $this->_delGen = $this->_detectLatestDelGen();
  289. }
  290. // Load deletions
  291. $this->_deleted = $this->_loadDelFile();
  292. }
  293. /**
  294. * Load detetions file
  295. *
  296. * Returns bitset or an array depending on bitset extension availability
  297. *
  298. * @return mixed
  299. * @throws Zend_Search_Lucene_Exception
  300. */
  301. private function _loadDelFile()
  302. {
  303. if ($this->_delGen == -1) {
  304. // There is no delete file for this segment
  305. return null;
  306. } else if ($this->_delGen == 0) {
  307. // It's a segment with pre-2.1 format delete file
  308. // Try to load deletions file
  309. return $this->_loadPre21DelFile();
  310. } else {
  311. // It's 2.1+ format deleteions file
  312. return $this->_load21DelFile();
  313. }
  314. }
  315. /**
  316. * Load pre-2.1 detetions file
  317. *
  318. * Returns bitset or an array depending on bitset extension availability
  319. *
  320. * @return mixed
  321. * @throws Zend_Search_Lucene_Exception
  322. */
  323. private function _loadPre21DelFile()
  324. {
  325. require_once 'Zend/Search/Lucene/Exception.php';
  326. try {
  327. // '.del' files always stored in a separate file
  328. // Segment compound is not used
  329. $delFile = $this->_directory->getFileObject($this->_name . '.del');
  330. $byteCount = $delFile->readInt();
  331. $byteCount = ceil($byteCount/8);
  332. $bitCount = $delFile->readInt();
  333. if ($bitCount == 0) {
  334. $delBytes = '';
  335. } else {
  336. $delBytes = $delFile->readBytes($byteCount);
  337. }
  338. if (extension_loaded('bitset')) {
  339. return $delBytes;
  340. } else {
  341. $deletions = array();
  342. for ($count = 0; $count < $byteCount; $count++) {
  343. $byte = ord($delBytes[$count]);
  344. for ($bit = 0; $bit < 8; $bit++) {
  345. if ($byte & (1<<$bit)) {
  346. $deletions[$count*8 + $bit] = 1;
  347. }
  348. }
  349. }
  350. return $deletions;
  351. }
  352. } catch(Zend_Search_Lucene_Exception $e) {
  353. if (strpos($e->getMessage(), 'is not readable') === false) {
  354. throw new Zend_Search_Lucene_Exception($e->getMessage(), $e->getCode(), $e);
  355. }
  356. // There is no deletion file
  357. $this->_delGen = -1;
  358. return null;
  359. }
  360. }
  361. /**
  362. * Load 2.1+ format detetions file
  363. *
  364. * Returns bitset or an array depending on bitset extension availability
  365. *
  366. * @return mixed
  367. */
  368. private function _load21DelFile()
  369. {
  370. $delFile = $this->_directory->getFileObject($this->_name . '_' . base_convert($this->_delGen, 10, 36) . '.del');
  371. $format = $delFile->readInt();
  372. if ($format == (int)0xFFFFFFFF) {
  373. if (extension_loaded('bitset')) {
  374. $deletions = bitset_empty();
  375. } else {
  376. $deletions = array();
  377. }
  378. $byteCount = $delFile->readInt();
  379. $bitCount = $delFile->readInt();
  380. $delFileSize = $this->_directory->fileLength($this->_name . '_' . base_convert($this->_delGen, 10, 36) . '.del');
  381. $byteNum = 0;
  382. do {
  383. $dgap = $delFile->readVInt();
  384. $nonZeroByte = $delFile->readByte();
  385. $byteNum += $dgap;
  386. if (extension_loaded('bitset')) {
  387. for ($bit = 0; $bit < 8; $bit++) {
  388. if ($nonZeroByte & (1<<$bit)) {
  389. bitset_incl($deletions, $byteNum*8 + $bit);
  390. }
  391. }
  392. return $deletions;
  393. } else {
  394. for ($bit = 0; $bit < 8; $bit++) {
  395. if ($nonZeroByte & (1<<$bit)) {
  396. $deletions[$byteNum*8 + $bit] = 1;
  397. }
  398. }
  399. return (count($deletions) > 0) ? $deletions : null;
  400. }
  401. } while ($delFile->tell() < $delFileSize);
  402. } else {
  403. // $format is actually byte count
  404. $byteCount = ceil($format/8);
  405. $bitCount = $delFile->readInt();
  406. if ($bitCount == 0) {
  407. $delBytes = '';
  408. } else {
  409. $delBytes = $delFile->readBytes($byteCount);
  410. }
  411. if (extension_loaded('bitset')) {
  412. return $delBytes;
  413. } else {
  414. $deletions = array();
  415. for ($count = 0; $count < $byteCount; $count++) {
  416. $byte = ord($delBytes[$count]);
  417. for ($bit = 0; $bit < 8; $bit++) {
  418. if ($byte & (1<<$bit)) {
  419. $deletions[$count*8 + $bit] = 1;
  420. }
  421. }
  422. }
  423. return (count($deletions) > 0) ? $deletions : null;
  424. }
  425. }
  426. }
  427. /**
  428. * Opens index file stoted within compound index file
  429. *
  430. * @param string $extension
  431. * @param boolean $shareHandler
  432. * @throws Zend_Search_Lucene_Exception
  433. * @return Zend_Search_Lucene_Storage_File
  434. */
  435. public function openCompoundFile($extension, $shareHandler = true)
  436. {
  437. if (($extension == '.fdx' || $extension == '.fdt') && $this->_usesSharedDocStore) {
  438. $fdxFName = $this->_sharedDocStoreOptions['segment'] . '.fdx';
  439. $fdtFName = $this->_sharedDocStoreOptions['segment'] . '.fdt';
  440. if (!$this->_sharedDocStoreOptions['isCompound']) {
  441. $fdxFile = $this->_directory->getFileObject($fdxFName, $shareHandler);
  442. $fdxFile->seek($this->_sharedDocStoreOptions['offset']*8, SEEK_CUR);
  443. if ($extension == '.fdx') {
  444. // '.fdx' file is requested
  445. return $fdxFile;
  446. } else {
  447. // '.fdt' file is requested
  448. $fdtStartOffset = $fdxFile->readLong();
  449. $fdtFile = $this->_directory->getFileObject($fdtFName, $shareHandler);
  450. $fdtFile->seek($fdtStartOffset, SEEK_CUR);
  451. return $fdtFile;
  452. }
  453. }
  454. if( !isset($this->_sharedDocStoreOptions['files'][$fdxFName]) ) {
  455. require_once 'Zend/Search/Lucene/Exception.php';
  456. throw new Zend_Search_Lucene_Exception('Shared doc storage segment compound file doesn\'t contain '
  457. . $fdxFName . ' file.' );
  458. }
  459. if( !isset($this->_sharedDocStoreOptions['files'][$fdtFName]) ) {
  460. require_once 'Zend/Search/Lucene/Exception.php';
  461. throw new Zend_Search_Lucene_Exception('Shared doc storage segment compound file doesn\'t contain '
  462. . $fdtFName . ' file.' );
  463. }
  464. // Open shared docstore segment file
  465. $cfxFile = $this->_directory->getFileObject($this->_sharedDocStoreOptions['segment'] . '.cfx', $shareHandler);
  466. // Seek to the start of '.fdx' file within compound file
  467. $cfxFile->seek($this->_sharedDocStoreOptions['files'][$fdxFName]);
  468. // Seek to the start of current segment documents section
  469. $cfxFile->seek($this->_sharedDocStoreOptions['offset']*8, SEEK_CUR);
  470. if ($extension == '.fdx') {
  471. // '.fdx' file is requested
  472. return $cfxFile;
  473. } else {
  474. // '.fdt' file is requested
  475. $fdtStartOffset = $cfxFile->readLong();
  476. // Seek to the start of '.fdt' file within compound file
  477. $cfxFile->seek($this->_sharedDocStoreOptions['files'][$fdtFName]);
  478. // Seek to the start of current segment documents section
  479. $cfxFile->seek($fdtStartOffset, SEEK_CUR);
  480. return $fdtFile;
  481. }
  482. }
  483. $filename = $this->_name . $extension;
  484. if (!$this->_isCompound) {
  485. return $this->_directory->getFileObject($filename, $shareHandler);
  486. }
  487. if( !isset($this->_segFiles[$filename]) ) {
  488. require_once 'Zend/Search/Lucene/Exception.php';
  489. throw new Zend_Search_Lucene_Exception('Segment compound file doesn\'t contain '
  490. . $filename . ' file.' );
  491. }
  492. $file = $this->_directory->getFileObject($this->_name . '.cfs', $shareHandler);
  493. $file->seek($this->_segFiles[$filename]);
  494. return $file;
  495. }
  496. /**
  497. * Get compound file length
  498. *
  499. * @param string $extension
  500. * @return integer
  501. */
  502. public function compoundFileLength($extension)
  503. {
  504. if (($extension == '.fdx' || $extension == '.fdt') && $this->_usesSharedDocStore) {
  505. $filename = $this->_sharedDocStoreOptions['segment'] . $extension;
  506. if (!$this->_sharedDocStoreOptions['isCompound']) {
  507. return $this->_directory->fileLength($filename);
  508. }
  509. if( !isset($this->_sharedDocStoreOptions['fileSizes'][$filename]) ) {
  510. require_once 'Zend/Search/Lucene/Exception.php';
  511. throw new Zend_Search_Lucene_Exception('Shared doc store compound file doesn\'t contain '
  512. . $filename . ' file.' );
  513. }
  514. return $this->_sharedDocStoreOptions['fileSizes'][$filename];
  515. }
  516. $filename = $this->_name . $extension;
  517. // Try to get common file first
  518. if ($this->_directory->fileExists($filename)) {
  519. return $this->_directory->fileLength($filename);
  520. }
  521. if( !isset($this->_segFileSizes[$filename]) ) {
  522. require_once 'Zend/Search/Lucene/Exception.php';
  523. throw new Zend_Search_Lucene_Exception('Index compound file doesn\'t contain '
  524. . $filename . ' file.' );
  525. }
  526. return $this->_segFileSizes[$filename];
  527. }
  528. /**
  529. * Returns field index or -1 if field is not found
  530. *
  531. * @param string $fieldName
  532. * @return integer
  533. */
  534. public function getFieldNum($fieldName)
  535. {
  536. foreach( $this->_fields as $field ) {
  537. if( $field->name == $fieldName ) {
  538. return $field->number;
  539. }
  540. }
  541. return -1;
  542. }
  543. /**
  544. * Returns field info for specified field
  545. *
  546. * @param integer $fieldNum
  547. * @return Zend_Search_Lucene_Index_FieldInfo
  548. */
  549. public function getField($fieldNum)
  550. {
  551. return $this->_fields[$fieldNum];
  552. }
  553. /**
  554. * Returns array of fields.
  555. * if $indexed parameter is true, then returns only indexed fields.
  556. *
  557. * @param boolean $indexed
  558. * @return array
  559. */
  560. public function getFields($indexed = false)
  561. {
  562. $result = array();
  563. foreach( $this->_fields as $field ) {
  564. if( (!$indexed) || $field->isIndexed ) {
  565. $result[ $field->name ] = $field->name;
  566. }
  567. }
  568. return $result;
  569. }
  570. /**
  571. * Returns array of FieldInfo objects.
  572. *
  573. * @return array
  574. */
  575. public function getFieldInfos()
  576. {
  577. return $this->_fields;
  578. }
  579. /**
  580. * Returns actual deletions file generation number.
  581. *
  582. * @return integer
  583. */
  584. public function getDelGen()
  585. {
  586. return $this->_delGen;
  587. }
  588. /**
  589. * Returns the total number of documents in this segment (including deleted documents).
  590. *
  591. * @return integer
  592. */
  593. public function count()
  594. {
  595. return $this->_docCount;
  596. }
  597. /**
  598. * Returns number of deleted documents.
  599. *
  600. * @return integer
  601. */
  602. private function _deletedCount()
  603. {
  604. if ($this->_deleted === null) {
  605. return 0;
  606. }
  607. if (extension_loaded('bitset')) {
  608. return count(bitset_to_array($this->_deleted));
  609. } else {
  610. return count($this->_deleted);
  611. }
  612. }
  613. /**
  614. * Returns the total number of non-deleted documents in this segment.
  615. *
  616. * @return integer
  617. */
  618. public function numDocs()
  619. {
  620. if ($this->hasDeletions()) {
  621. return $this->_docCount - $this->_deletedCount();
  622. } else {
  623. return $this->_docCount;
  624. }
  625. }
  626. /**
  627. * Get field position in a fields dictionary
  628. *
  629. * @param integer $fieldNum
  630. * @return integer
  631. */
  632. private function _getFieldPosition($fieldNum) {
  633. // Treat values which are not in a translation table as a 'direct value'
  634. return isset($this->_fieldsDicPositions[$fieldNum]) ?
  635. $this->_fieldsDicPositions[$fieldNum] : $fieldNum;
  636. }
  637. /**
  638. * Return segment name
  639. *
  640. * @return string
  641. */
  642. public function getName()
  643. {
  644. return $this->_name;
  645. }
  646. /**
  647. * TermInfo cache
  648. *
  649. * Size is 1024.
  650. * Numbers are used instead of class constants because of performance considerations
  651. *
  652. * @var array
  653. */
  654. private $_termInfoCache = array();
  655. private function _cleanUpTermInfoCache()
  656. {
  657. // Clean 256 term infos
  658. foreach ($this->_termInfoCache as $key => $termInfo) {
  659. unset($this->_termInfoCache[$key]);
  660. // leave 768 last used term infos
  661. if (count($this->_termInfoCache) == 768) {
  662. break;
  663. }
  664. }
  665. }
  666. /**
  667. * Load terms dictionary index
  668. *
  669. * @throws Zend_Search_Lucene_Exception
  670. */
  671. private function _loadDictionaryIndex()
  672. {
  673. // Check, if index is already serialized
  674. if ($this->_directory->fileExists($this->_name . '.sti')) {
  675. // Load serialized dictionary index data
  676. $stiFile = $this->_directory->getFileObject($this->_name . '.sti');
  677. $stiFileData = $stiFile->readBytes($this->_directory->fileLength($this->_name . '.sti'));
  678. // Load dictionary index data
  679. if (($unserializedData = @unserialize($stiFileData)) !== false) {
  680. list($this->_termDictionary, $this->_termDictionaryInfos) = $unserializedData;
  681. return;
  682. }
  683. }
  684. // Load data from .tii file and generate .sti file
  685. // Prefetch dictionary index data
  686. $tiiFile = $this->openCompoundFile('.tii');
  687. $tiiFileData = $tiiFile->readBytes($this->compoundFileLength('.tii'));
  688. /** Zend_Search_Lucene_Index_DictionaryLoader */
  689. require_once 'Zend/Search/Lucene/Index/DictionaryLoader.php';
  690. // Load dictionary index data
  691. list($this->_termDictionary, $this->_termDictionaryInfos) =
  692. Zend_Search_Lucene_Index_DictionaryLoader::load($tiiFileData);
  693. $stiFileData = serialize(array($this->_termDictionary, $this->_termDictionaryInfos));
  694. $stiFile = $this->_directory->createFile($this->_name . '.sti');
  695. $stiFile->writeBytes($stiFileData);
  696. }
  697. /**
  698. * Scans terms dictionary and returns term info
  699. *
  700. * @param Zend_Search_Lucene_Index_Term $term
  701. * @return Zend_Search_Lucene_Index_TermInfo
  702. */
  703. public function getTermInfo(Zend_Search_Lucene_Index_Term $term)
  704. {
  705. $termKey = $term->key();
  706. if (isset($this->_termInfoCache[$termKey])) {
  707. $termInfo = $this->_termInfoCache[$termKey];
  708. // Move termInfo to the end of cache
  709. unset($this->_termInfoCache[$termKey]);
  710. $this->_termInfoCache[$termKey] = $termInfo;
  711. return $termInfo;
  712. }
  713. if ($this->_termDictionary === null) {
  714. $this->_loadDictionaryIndex();
  715. }
  716. $searchField = $this->getFieldNum($term->field);
  717. if ($searchField == -1) {
  718. return null;
  719. }
  720. $searchDicField = $this->_getFieldPosition($searchField);
  721. // search for appropriate value in dictionary
  722. $lowIndex = 0;
  723. $highIndex = count($this->_termDictionary)-1;
  724. while ($highIndex >= $lowIndex) {
  725. // $mid = ($highIndex - $lowIndex)/2;
  726. $mid = ($highIndex + $lowIndex) >> 1;
  727. $midTerm = $this->_termDictionary[$mid];
  728. $fieldNum = $this->_getFieldPosition($midTerm[0] /* field */);
  729. $delta = $searchDicField - $fieldNum;
  730. if ($delta == 0) {
  731. $delta = strcmp($term->text, $midTerm[1] /* text */);
  732. }
  733. if ($delta < 0) {
  734. $highIndex = $mid-1;
  735. } elseif ($delta > 0) {
  736. $lowIndex = $mid+1;
  737. } else {
  738. // return $this->_termDictionaryInfos[$mid]; // We got it!
  739. $a = $this->_termDictionaryInfos[$mid];
  740. $termInfo = new Zend_Search_Lucene_Index_TermInfo($a[0], $a[1], $a[2], $a[3], $a[4]);
  741. // Put loaded termInfo into cache
  742. $this->_termInfoCache[$termKey] = $termInfo;
  743. return $termInfo;
  744. }
  745. }
  746. if ($highIndex == -1) {
  747. // Term is out of the dictionary range
  748. return null;
  749. }
  750. $prevPosition = $highIndex;
  751. $prevTerm = $this->_termDictionary[$prevPosition];
  752. $prevTermInfo = $this->_termDictionaryInfos[$prevPosition];
  753. $tisFile = $this->openCompoundFile('.tis');
  754. $tiVersion = $tisFile->readInt();
  755. if ($tiVersion != (int)0xFFFFFFFE /* pre-2.1 format */ &&
  756. $tiVersion != (int)0xFFFFFFFD /* 2.1+ format */) {
  757. require_once 'Zend/Search/Lucene/Exception.php';
  758. throw new Zend_Search_Lucene_Exception('Wrong TermInfoFile file format');
  759. }
  760. $termCount = $tisFile->readLong();
  761. $indexInterval = $tisFile->readInt();
  762. $skipInterval = $tisFile->readInt();
  763. if ($tiVersion == (int)0xFFFFFFFD /* 2.1+ format */) {
  764. $maxSkipLevels = $tisFile->readInt();
  765. }
  766. $tisFile->seek($prevTermInfo[4] /* indexPointer */ - (($tiVersion == (int)0xFFFFFFFD)? 24 : 20) /* header size*/, SEEK_CUR);
  767. $termValue = $prevTerm[1] /* text */;
  768. $termFieldNum = $prevTerm[0] /* field */;
  769. $freqPointer = $prevTermInfo[1] /* freqPointer */;
  770. $proxPointer = $prevTermInfo[2] /* proxPointer */;
  771. for ($count = $prevPosition*$indexInterval + 1;
  772. $count <= $termCount &&
  773. ( $this->_getFieldPosition($termFieldNum) < $searchDicField ||
  774. ($this->_getFieldPosition($termFieldNum) == $searchDicField &&
  775. strcmp($termValue, $term->text) < 0) );
  776. $count++) {
  777. $termPrefixLength = $tisFile->readVInt();
  778. $termSuffix = $tisFile->readString();
  779. $termFieldNum = $tisFile->readVInt();
  780. $termValue = Zend_Search_Lucene_Index_Term::getPrefix($termValue, $termPrefixLength) . $termSuffix;
  781. $docFreq = $tisFile->readVInt();
  782. $freqPointer += $tisFile->readVInt();
  783. $proxPointer += $tisFile->readVInt();
  784. if( $docFreq >= $skipInterval ) {
  785. $skipOffset = $tisFile->readVInt();
  786. } else {
  787. $skipOffset = 0;
  788. }
  789. }
  790. if ($termFieldNum == $searchField && $termValue == $term->text) {
  791. $termInfo = new Zend_Search_Lucene_Index_TermInfo($docFreq, $freqPointer, $proxPointer, $skipOffset);
  792. } else {
  793. $termInfo = null;
  794. }
  795. // Put loaded termInfo into cache
  796. $this->_termInfoCache[$termKey] = $termInfo;
  797. if (count($this->_termInfoCache) == 1024) {
  798. $this->_cleanUpTermInfoCache();
  799. }
  800. return $termInfo;
  801. }
  802. /**
  803. * Returns IDs of all the documents containing term.
  804. *
  805. * @param Zend_Search_Lucene_Index_Term $term
  806. * @param integer $shift
  807. * @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter
  808. * @return array
  809. */
  810. public function termDocs(Zend_Search_Lucene_Index_Term $term, $shift = 0, $docsFilter = null)
  811. {
  812. $termInfo = $this->getTermInfo($term);
  813. if (!$termInfo instanceof Zend_Search_Lucene_Index_TermInfo) {
  814. if ($docsFilter !== null && $docsFilter instanceof Zend_Search_Lucene_Index_DocsFilter) {
  815. $docsFilter->segmentFilters[$this->_name] = array();
  816. }
  817. return array();
  818. }
  819. $frqFile = $this->openCompoundFile('.frq');
  820. $frqFile->seek($termInfo->freqPointer,SEEK_CUR);
  821. $docId = 0;
  822. $result = array();
  823. if ($docsFilter !== null) {
  824. if (!$docsFilter instanceof Zend_Search_Lucene_Index_DocsFilter) {
  825. require_once 'Zend/Search/Lucene/Exception.php';
  826. throw new Zend_Search_Lucene_Exception('Documents filter must be an instance of Zend_Search_Lucene_Index_DocsFilter or null.');
  827. }
  828. if (isset($docsFilter->segmentFilters[$this->_name])) {
  829. // Filter already has some data for the current segment
  830. // Make short name for the filter (which doesn't need additional dereferencing)
  831. $filter = &$docsFilter->segmentFilters[$this->_name];
  832. // Check if filter is not empty
  833. if (count($filter) == 0) {
  834. return array();
  835. }
  836. if ($this->_docCount/count($filter) < self::FULL_SCAN_VS_FETCH_BOUNDARY) {
  837. // Perform fetching
  838. // ---------------------------------------------------------------
  839. $updatedFilterData = array();
  840. for( $count=0; $count < $termInfo->docFreq; $count++ ) {
  841. $docDelta = $frqFile->readVInt();
  842. if( $docDelta % 2 == 1 ) {
  843. $docId += ($docDelta-1)/2;
  844. } else {
  845. $docId += $docDelta/2;
  846. // read freq
  847. $frqFile->readVInt();
  848. }
  849. if (isset($filter[$docId])) {
  850. $result[] = $shift + $docId;
  851. $updatedFilterData[$docId] = 1; // 1 is just a some constant value, so we don't need additional var dereference here
  852. }
  853. }
  854. $docsFilter->segmentFilters[$this->_name] = $updatedFilterData;
  855. // ---------------------------------------------------------------
  856. } else {
  857. // Perform full scan
  858. $updatedFilterData = array();
  859. for( $count=0; $count < $termInfo->docFreq; $count++ ) {
  860. $docDelta = $frqFile->readVInt();
  861. if( $docDelta % 2 == 1 ) {
  862. $docId += ($docDelta-1)/2;
  863. } else {
  864. $docId += $docDelta/2;
  865. // read freq
  866. $frqFile->readVInt();
  867. }
  868. if (isset($filter[$docId])) {
  869. $result[] = $shift + $docId;
  870. $updatedFilterData[$docId] = 1; // 1 is just a some constant value, so we don't need additional var dereference here
  871. }
  872. }
  873. $docsFilter->segmentFilters[$this->_name] = $updatedFilterData;
  874. }
  875. } else {
  876. // Filter is present, but doesn't has data for the current segment yet
  877. $filterData = array();
  878. for( $count=0; $count < $termInfo->docFreq; $count++ ) {
  879. $docDelta = $frqFile->readVInt();
  880. if( $docDelta % 2 == 1 ) {
  881. $docId += ($docDelta-1)/2;
  882. } else {
  883. $docId += $docDelta/2;
  884. // read freq
  885. $frqFile->readVInt();
  886. }
  887. $result[] = $shift + $docId;
  888. $filterData[$docId] = 1; // 1 is just a some constant value, so we don't need additional var dereference here
  889. }
  890. $docsFilter->segmentFilters[$this->_name] = $filterData;
  891. }
  892. } else {
  893. for( $count=0; $count < $termInfo->docFreq; $count++ ) {
  894. $docDelta = $frqFile->readVInt();
  895. if( $docDelta % 2 == 1 ) {
  896. $docId += ($docDelta-1)/2;
  897. } else {
  898. $docId += $docDelta/2;
  899. // read freq
  900. $frqFile->readVInt();
  901. }
  902. $result[] = $shift + $docId;
  903. }
  904. }
  905. return $result;
  906. }
  907. /**
  908. * Returns term freqs array.
  909. * Result array structure: array(docId => freq, ...)
  910. *
  911. * @param Zend_Search_Lucene_Index_Term $term
  912. * @param integer $shift
  913. * @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter
  914. * @return Zend_Search_Lucene_Index_TermInfo
  915. */
  916. public function termFreqs(Zend_Search_Lucene_Index_Term $term, $shift = 0, $docsFilter = null)
  917. {
  918. $termInfo = $this->getTermInfo($term);
  919. if (!$termInfo instanceof Zend_Search_Lucene_Index_TermInfo) {
  920. if ($docsFilter !== null && $docsFilter instanceof Zend_Search_Lucene_Index_DocsFilter) {
  921. $docsFilter->segmentFilters[$this->_name] = array();
  922. }
  923. return array();
  924. }
  925. $frqFile = $this->openCompoundFile('.frq');
  926. $frqFile->seek($termInfo->freqPointer,SEEK_CUR);
  927. $result = array();
  928. $docId = 0;
  929. $result = array();
  930. if ($docsFilter !== null) {
  931. if (!$docsFilter instanceof Zend_Search_Lucene_Index_DocsFilter) {
  932. require_once 'Zend/Search/Lucene/Exception.php';
  933. throw new Zend_Search_Lucene_Exception('Documents filter must be an instance of Zend_Search_Lucene_Index_DocsFilter or null.');
  934. }
  935. if (isset($docsFilter->segmentFilters[$this->_name])) {
  936. // Filter already has some data for the current segment
  937. // Make short name for the filter (which doesn't need additional dereferencing)
  938. $filter = &$docsFilter->segmentFilters[$this->_name];
  939. // Check if filter is not empty
  940. if (count($filter) == 0) {
  941. return array();
  942. }
  943. if ($this->_docCount/count($filter) < self::FULL_SCAN_VS_FETCH_BOUNDARY) {
  944. // Perform fetching
  945. // ---------------------------------------------------------------
  946. $updatedFilterData = array();
  947. for ($count = 0; $count < $termInfo->docFreq; $count++) {
  948. $docDelta = $frqFile->readVInt();
  949. if ($docDelta % 2 == 1) {
  950. $docId += ($docDelta-1)/2;
  951. if (isset($filter[$docId])) {
  952. $result[$shift + $docId] = 1;
  953. $updatedFilterData[$docId] = 1; // 1 is just a some constant value, so we don't need additional var dereference here
  954. }
  955. } else {
  956. $docId += $docDelta/2;
  957. if (isset($filter[$docId])) {
  958. $result[$shift + $docId] = $frqFile->readVInt();
  959. $updatedFilterData[$docId] = 1; // 1 is just a some constant value, so we don't need additional var dereference here
  960. }
  961. }
  962. }
  963. $docsFilter->segmentFilters[$this->_name] = $updatedFilterData;
  964. // ---------------------------------------------------------------
  965. } else {
  966. // Perform full scan
  967. $updatedFilterData = array();
  968. for ($count = 0; $count < $termInfo->docFreq; $count++) {
  969. $docDelta = $frqFile->readVInt();
  970. if ($docDelta % 2 == 1) {
  971. $docId += ($docDelta-1)/2;
  972. if (isset($filter[$docId])) {
  973. $result[$shift + $docId] = 1;
  974. $updatedFilterData[$docId] = 1; // 1 is just some constant value, so we don't need additional var dereference here
  975. }
  976. } else {
  977. $docId += $docDelta/2;
  978. if (isset($filter[$docId])) {
  979. $result[$shift + $docId] = $frqFile->readVInt();
  980. $updatedFilterData[$docId] = 1; // 1 is just some constant value, so we don't need additional var dereference here
  981. }
  982. }
  983. }
  984. $docsFilter->segmentFilters[$this->_name] = $updatedFilterData;
  985. }
  986. } else {
  987. // Filter doesn't has data for current segment
  988. $filterData = array();
  989. for ($count = 0; $count < $termInfo->docFreq; $count++) {
  990. $docDelta = $frqFile->readVInt();
  991. if ($docDelta % 2 == 1) {
  992. $docId += ($docDelta-1)/2;
  993. $result[$shift + $docId] = 1;
  994. $filterData[$docId] = 1; // 1 is just a some constant value, so we don't need additional var dereference here
  995. } else {
  996. $docId += $docDelta/2;
  997. $result[$shift + $docId] = $frqFile->readVInt();
  998. $filterData[$docId] = 1; // 1 is just a some constant value, so we don't need additional var dereference here
  999. }
  1000. }
  1001. $docsFilter->segmentFilters[$this->_name] = $filterData;
  1002. }
  1003. } else {
  1004. for ($count = 0; $count < $termInfo->docFreq; $count++) {
  1005. $docDelta = $frqFile->readVInt();
  1006. if ($docDelta % 2 == 1) {
  1007. $docId += ($docDelta-1)/2;
  1008. $result[$shift + $docId] = 1;
  1009. } else {
  1010. $docId += $docDelta/2;
  1011. $result[$shift + $docId] = $frqFile->readVInt();
  1012. }
  1013. }
  1014. }
  1015. return $result;
  1016. }
  1017. /**
  1018. * Returns term positions array.
  1019. * Result array structure: array(docId => array(pos1, pos2, ...), ...)
  1020. *
  1021. * @param Zend_Search_Lucene_Index_Term $term
  1022. * @param integer $shift
  1023. * @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter
  1024. * @return Zend_Search_Lucene_Index_TermInfo
  1025. */
  1026. public function termPositions(Zend_Search_Lucene_Index_Term $term, $shift = 0, $docsFilter = null)
  1027. {
  1028. $termInfo = $this->getTermInfo($term);
  1029. if (!$termInfo instanceof Zend_Search_Lucene_Index_TermInfo) {
  1030. if ($docsFilter !== null && $docsFilter instanceof Zend_Search_Lucene_Index_DocsFilter) {
  1031. $docsFilter->segmentFilters[$this->_name] = array();
  1032. }
  1033. return array();
  1034. }
  1035. $frqFile = $this->openCompoundFile('.frq');
  1036. $frqFile->seek($termInfo->freqPointer,SEEK_CUR);
  1037. $docId = 0;
  1038. $freqs = array();
  1039. if ($docsFilter !== null) {
  1040. if (!$docsFilter instanceof Zend_Search_Lucene_Index_DocsFilter) {
  1041. require_once 'Zend/Search/Lucene/Exception.php';
  1042. throw new Zend_Search_Lucene_Exception('Documents filter must be an instance of Zend_Search_Lucene_Index_DocsFilter or null.');
  1043. }
  1044. if (isset($docsFilter->segmentFilters[$this->_name])) {
  1045. // Filter already has some data for the current segment
  1046. // Make short name for the filter (which doesn't need additional dereferencing)
  1047. $filter = &$docsFilter->segmentFilters[$this->_name];
  1048. // Check if filter is not empty
  1049. if (count($filter) == 0) {
  1050. return array();
  1051. }
  1052. if ($this->_docCount/count($filter) < self::FULL_SCAN_VS_FETCH_BOUNDARY) {
  1053. // Perform fetching
  1054. // ---------------------------------------------------------------
  1055. for ($count = 0; $count < $termInfo->docFreq; $count++) {
  1056. $docDelta = $frqFile->readVInt();
  1057. if ($docDelta % 2 == 1) {
  1058. $docId += ($docDelta-1)/2;
  1059. $freqs[$docId] = 1;
  1060. } else {
  1061. $docId += $docDelta/2;
  1062. $freqs[$docId] = $frqFile->readVInt();
  1063. }
  1064. }
  1065. $updatedFilterData = array();
  1066. $result = array();
  1067. $prxFile = $this->openCompoundFile('.prx');
  1068. $prxFile->seek($termInfo->proxPointer, SEEK_CUR);
  1069. foreach ($freqs as $docId => $freq) {
  1070. $termPosition = 0;
  1071. $positions = array();
  1072. // we have to read .prx file to get right position for next doc
  1073. // even filter doesn't match current document
  1074. for ($count = 0; $count < $freq; $count++ ) {
  1075. $termPosition += $prxFile->readVInt();
  1076. $positions[] = $termPosition;
  1077. }
  1078. // Include into updated filter and into result only if doc is matched by filter
  1079. if (isset($filter[$docId])) {
  1080. $updatedFilterData[$docId] = 1; // 1 is just a some constant value, so we don't need additional var dereference here
  1081. $result[$shift + $docId] = $positions;
  1082. }
  1083. }
  1084. $docsFilter->segmentFilters[$this->_name] = $updatedFilterData;
  1085. // ---------------------------------------------------------------
  1086. } else {
  1087. // Perform full scan
  1088. for ($count = 0; $count < $termInfo->docFreq; $count++) {
  1089. $docDelta = $frqFile->readVInt();
  1090. if ($docDelta % 2 == 1) {
  1091. $docId += ($docDelta-1)/2;
  1092. $freqs[$docId] = 1;
  1093. } else {
  1094. $docId += $docDelta/2;
  1095. $freqs[$docId] = $frqFile->readVInt();
  1096. }
  1097. }
  1098. $updatedFilterData = array();
  1099. $result = array();
  1100. $prxFile = $this->openCompoundFile('.prx');
  1101. $prxFile->seek($termInfo->proxPointer, SEEK_CUR);
  1102. foreach ($freqs as $docId => $freq) {
  1103. $termPosition = 0;
  1104. $positions = array();
  1105. // we have to read .prx file to get right position for next doc
  1106. // even filter doesn't match current document
  1107. for ($count = 0; $count < $freq; $count++ ) {
  1108. $termPosition += $prxFile->readVInt();
  1109. $positions[] = $termPosition;
  1110. }
  1111. // Include into updated filter and into result only if doc is matched by filter
  1112. if (isset($filter[$docId])) {
  1113. $updatedFilterData[$docId] = 1; // 1 is just a some constant value, so we don't need additional var dereference here
  1114. $result[$shift + $docId] = $positions;
  1115. }
  1116. }
  1117. $docsFilter->segmentFilters[$this->_name] = $updatedFilterData;
  1118. }
  1119. } else {
  1120. // Filter doesn't has data for current segment
  1121. for ($count = 0; $count < $termInfo->docFreq; $count++) {
  1122. $docDelta = $frqFile->readVInt();
  1123. if ($docDelta % 2 == 1) {
  1124. $docId += ($docDelta-1)/2;
  1125. $freqs[$docId] = 1;
  1126. } else {
  1127. $docId += $docDelta/2;
  1128. $freqs[$docId] = $frqFile->readVInt();
  1129. }
  1130. }
  1131. $filterData = array();
  1132. $result = array();
  1133. $prxFile = $this->openCompoundFile('.prx');
  1134. $prxFile->seek($termInfo->proxPointer, SEEK_CUR);
  1135. foreach ($freqs as $docId => $freq) {
  1136. $filterData[$docId] = 1; // 1 is just a some constant value, so we don't need additional var dereference here
  1137. $termPosition = 0;
  1138. $positions = array();
  1139. for ($count = 0; $count < $freq; $count++ ) {
  1140. $termPosition += $prxFile->readVInt();
  1141. $positions[] = $termPosition;
  1142. }
  1143. $result[$shift + $docId] = $positions;
  1144. }
  1145. $docsFilter->segmentFilters[$this->_name] = $filterData;
  1146. }
  1147. } else {
  1148. for ($count = 0; $count < $termInfo->docFreq; $count++) {
  1149. $docDelta = $frqFile->readVInt();
  1150. if ($docDelta % 2 == 1) {
  1151. $docId += ($docDelta-1)/2;
  1152. $freqs[$docId] = 1;
  1153. } else {
  1154. $docId += $docDelta/2;
  1155. $freqs[$docId] = $frqFile->readVInt();
  1156. }
  1157. }
  1158. $result = array();
  1159. $prxFile = $this->openCompoundFile('.prx');
  1160. $prxFile->seek($termInfo->proxPointer, SEEK_CUR);
  1161. foreach ($freqs as $docId => $freq) {
  1162. $termPosition = 0;
  1163. $positions = array();
  1164. for ($count = 0; $count < $freq; $count++ ) {
  1165. $termPosition += $prxFile->readVInt();
  1166. $positions[] = $termPosition;
  1167. }
  1168. $result[$shift + $docId] = $positions;
  1169. }
  1170. }
  1171. return $result;
  1172. }
  1173. /**
  1174. * Load normalizatin factors from an index file
  1175. *
  1176. * @param integer $fieldNum
  1177. * @throws Zend_Search_Lucene_Exception
  1178. */
  1179. private function _loadNorm($fieldNum)
  1180. {
  1181. if ($this->_hasSingleNormFile) {
  1182. $normfFile = $this->openCompoundFile('.nrm');
  1183. $header = $normfFile->readBytes(3);
  1184. $headerFormatVersion = $normfFile->readByte();
  1185. if ($header != 'NRM' || $headerFormatVersion != (int)0xFF) {
  1186. require_once 'Zend/Search/Lucene/Exception.php';
  1187. throw new Zend_Search_Lucene_Exception('Wrong norms file format.');
  1188. }
  1189. foreach ($this->_fields as $fNum => $fieldInfo) {
  1190. if ($fieldInfo->isIndexed) {
  1191. $this->_norms[$fNum] = $normfFile->readBytes($this->_docCount);
  1192. }
  1193. }
  1194. } else {
  1195. $fFile = $this->openCompoundFile('.f' . $fieldNum);
  1196. $this->_norms[$fieldNum] = $fFile->readBytes($this->_docCount);
  1197. }
  1198. }
  1199. /**
  1200. * Returns normalization factor for specified documents
  1201. *
  1202. * @param integer $id
  1203. * @param string $fieldName
  1204. * @return float
  1205. */
  1206. public function norm($id, $fieldName)
  1207. {
  1208. $fieldNum = $this->getFieldNum($fieldName);
  1209. if ( !($this->_fields[$fieldNum]->isIndexed) ) {
  1210. return null;
  1211. }
  1212. if (!isset($this->_norms[$fieldNum])) {
  1213. $this->_loadNorm($fieldNum);
  1214. }
  1215. return Zend_Search_Lucene_Search_Similarity::decodeNorm( ord($this->_norms[$fieldNum][$id]) );
  1216. }
  1217. /**
  1218. * Returns norm vector, encoded in a byte string
  1219. *
  1220. * @param string $fieldName
  1221. * @return string
  1222. */
  1223. public function normVector($fieldName)
  1224. {
  1225. $fieldNum = $this->getFieldNum($fieldName);
  1226. if ($fieldNum == -1 || !($this->_fields[$fieldNum]->isIndexed)) {
  1227. $similarity = Zend_Search_Lucene_Search_Similarity::getDefault();
  1228. return str_repeat(chr($similarity->encodeNorm( $similarity->lengthNorm($fieldName, 0) )),
  1229. $this->_docCount);
  1230. }
  1231. if (!isset($this->_norms[$fieldNum])) {
  1232. $this->_loadNorm($fieldNum);
  1233. }
  1234. return $this->_norms[$fieldNum];
  1235. }
  1236. /**
  1237. * Returns true if any documents have been deleted from this index segment.
  1238. *
  1239. * @return boolean
  1240. */
  1241. public function hasDeletions()
  1242. {
  1243. return $this->_deleted !== null;
  1244. }
  1245. /**
  1246. * Returns true if segment has single norms file.
  1247. *
  1248. * @return boolean
  1249. */
  1250. public function hasSingleNormFile()
  1251. {
  1252. return $this->_hasSingleNormFile ? true : false;
  1253. }
  1254. /**
  1255. * Returns true if segment is stored using compound segment file.
  1256. *
  1257. * @return boolean
  1258. */
  1259. public function isCompound()
  1260. {
  1261. return $this->_isCompound;
  1262. }
  1263. /**
  1264. * Deletes a document from the index segment.
  1265. * $id is an internal document id
  1266. *
  1267. * @param integer
  1268. */
  1269. public function delete($id)
  1270. {
  1271. $this->_deletedDirty = true;
  1272. if (extension_loaded('bitset')) {
  1273. if ($this->_deleted === null) {
  1274. $this->_deleted = bitset_empty($id);
  1275. }
  1276. bitset_incl($this->_deleted, $id);
  1277. } else {
  1278. if ($this->_deleted === null) {
  1279. $this->_deleted = array();
  1280. }
  1281. $this->_deleted[$id] = 1;
  1282. }
  1283. }
  1284. /**
  1285. * Checks, that document is deleted
  1286. *
  1287. * @param integer
  1288. * @return boolean
  1289. */
  1290. public function isDeleted($id)
  1291. {
  1292. if ($this->_deleted === null) {
  1293. return false;
  1294. }
  1295. if (extension_loaded('bitset')) {
  1296. return bitset_in($this->_deleted, $id);
  1297. } else {
  1298. return isset($this->_deleted[$id]);
  1299. }
  1300. }
  1301. /**
  1302. * Detect latest delete generation
  1303. *
  1304. * Is actualy used from writeChanges() method or from the constructor if it's invoked from
  1305. * Index writer. In both cases index write lock is already obtained, so we shouldn't care
  1306. * about it
  1307. *
  1308. * @return integer
  1309. */
  1310. private function _detectLatestDelGen()
  1311. {
  1312. $delFileList = array();
  1313. foreach ($this->_directory->fileList() as $file) {
  1314. if ($file == $this->_name . '.del') {
  1315. // Matches <segment_name>.del file name
  1316. $delFileList[] = 0;
  1317. } else if (preg_match('/^' . $this->_name . '_([a-zA-Z0-9]+)\.del$/i', $file, $matches)) {
  1318. // Matches <segment_name>_NNN.del file names
  1319. $delFileList[] = (int)base_convert($matches[1], 36, 10);
  1320. }
  1321. }
  1322. if (count($delFileList) == 0) {
  1323. // There is no deletions file for current segment in the directory
  1324. // Set deletions file generation number to 1
  1325. return -1;
  1326. } else {
  1327. // There are some deletions files for current segment in the directory
  1328. // Set deletions file generation number to the highest nuber
  1329. return max($delFileList);
  1330. }
  1331. }
  1332. /**
  1333. * Write changes if it's necessary.
  1334. *
  1335. * This method must be invoked only from the Writer _updateSegments() method,
  1336. * so index Write lock has to be already obtained.
  1337. *
  1338. * @internal
  1339. * @throws Zend_Search_Lucene_Exceptions
  1340. */
  1341. public function writeChanges()
  1342. {
  1343. // Get new generation number
  1344. $latestDelGen = $this->_detectLatestDelGen();
  1345. if (!$this->_deletedDirty) {
  1346. // There was no deletions by current process
  1347. if ($latestDelGen == $this->_delGen) {
  1348. // Delete file hasn't been updated by any concurrent process
  1349. return;
  1350. } else if ($latestDelGen > $this->_delGen) {
  1351. // Delete file has been updated by some concurrent process
  1352. // Reload deletions file
  1353. $this->_delGen = $latestDelGen;
  1354. $this->_deleted = $this->_loadDelFile();
  1355. return;
  1356. } else {
  1357. require_once 'Zend/Search/Lucene/Exception.php';
  1358. throw new Zend_Search_Lucene_Exception('Delete file processing workflow is corrupted for the segment \'' . $this->_name . '\'.');
  1359. }
  1360. }
  1361. if ($latestDelGen > $this->_delGen) {
  1362. // Merge current deletions with latest deletions file
  1363. $this->_delGen = $latestDelGen;
  1364. $latestDelete = $this->_loadDelFile();
  1365. if (extension_loaded('bitset')) {
  1366. $this->_deleted = bitset_union($this->_deleted, $latestDelete);
  1367. } else {
  1368. $this->_deleted += $latestDelete;
  1369. }
  1370. }
  1371. if (extension_loaded('bitset')) {
  1372. $delBytes = $this->_deleted;
  1373. $bitCount = count(bitset_to_array($delBytes));
  1374. } else {
  1375. $byteCount = floor($this->_docCount/8)+1;
  1376. $delBytes = str_repeat(chr(0), $byteCount);
  1377. for ($count = 0; $count < $byteCount; $count++) {
  1378. $byte = 0;
  1379. for ($bit = 0; $bit < 8; $bit++) {
  1380. if (isset($this->_deleted[$count*8 + $bit])) {
  1381. $byte |= (1<<$bit);
  1382. }
  1383. }
  1384. $delBytes[$count] = chr($byte);
  1385. }
  1386. $bitCount = count($this->_deleted);
  1387. }
  1388. if ($this->_delGen == -1) {
  1389. // Set delete file generation number to 1
  1390. $this->_delGen = 1;
  1391. } else {
  1392. // Increase delete file generation number by 1
  1393. $this->_delGen++;
  1394. }
  1395. $delFile = $this->_directory->createFile($this->_name . '_' . base_convert($this->_delGen, 10, 36) . '.del');
  1396. $delFile->writeInt($this->_docCount);
  1397. $delFile->writeInt($bitCount);
  1398. $delFile->writeBytes($delBytes);
  1399. $this->_deletedDirty = false;
  1400. }
  1401. /**
  1402. * Term Dictionary File object for stream like terms reading
  1403. *
  1404. * @var Zend_Search_Lucene_Storage_File
  1405. */
  1406. private $_tisFile = null;
  1407. /**
  1408. * Actual offset of the .tis file data
  1409. *
  1410. * @var integer
  1411. */
  1412. private $_tisFileOffset;
  1413. /**
  1414. * Frequencies File object for stream like terms reading
  1415. *
  1416. * @var Zend_Search_Lucene_Storage_File
  1417. */
  1418. private $_frqFile = null;
  1419. /**
  1420. * Actual offset of the .frq file data
  1421. *
  1422. * @var integer
  1423. */
  1424. private $_frqFileOffset;
  1425. /**
  1426. * Positions File object for stream like terms reading
  1427. *
  1428. * @var Zend_Search_Lucene_Storage_File
  1429. */
  1430. private $_prxFile = null;
  1431. /**
  1432. * Actual offset of the .prx file in the compound file
  1433. *
  1434. * @var integer
  1435. */
  1436. private $_prxFileOffset;
  1437. /**
  1438. * Actual number of terms in term stream
  1439. *
  1440. * @var integer
  1441. */
  1442. private $_termCount = 0;
  1443. /**
  1444. * Overall number of terms in term stream
  1445. *
  1446. * @var integer
  1447. */
  1448. private $_termNum = 0;
  1449. /**
  1450. * Segment index interval
  1451. *
  1452. * @var integer
  1453. */
  1454. private $_indexInterval;
  1455. /**
  1456. * Segment skip interval
  1457. *
  1458. * @var integer
  1459. */
  1460. private $_skipInterval;
  1461. /**
  1462. * Last TermInfo in a terms stream
  1463. *
  1464. * @var Zend_Search_Lucene_Index_TermInfo
  1465. */
  1466. private $_lastTermInfo = null;
  1467. /**
  1468. * Last Term in a terms stream
  1469. *
  1470. * @var Zend_Search_Lucene_Index_Term
  1471. */
  1472. private $_lastTerm = null;
  1473. /**
  1474. * Map of the document IDs
  1475. * Used to get new docID after removing deleted documents.
  1476. * It's not very effective from memory usage point of view,
  1477. * but much more faster, then other methods
  1478. *
  1479. * @var array|null
  1480. */
  1481. private $_docMap = null;
  1482. /**
  1483. * An array of all term positions in the documents.
  1484. * Array structure: array( docId => array( pos1, pos2, ...), ...)
  1485. *
  1486. * Is set to null if term positions loading has to be skipped
  1487. *
  1488. * @var array|null
  1489. */
  1490. private $_lastTermPositions;
  1491. /**
  1492. * Terms scan mode
  1493. *
  1494. * Values:
  1495. *
  1496. * self::SM_TERMS_ONLY - terms are scanned, no additional info is retrieved
  1497. * self::SM_FULL_INFO - terms are scanned, frequency and position info is retrieved
  1498. * self::SM_MERGE_INFO - terms are scanned, frequency and position info is retrieved
  1499. * document numbers are compacted (shifted if segment has deleted documents)
  1500. *
  1501. * @var integer
  1502. */
  1503. private $_termsScanMode;
  1504. /** Scan modes */
  1505. const SM_TERMS_ONLY = 0; // terms are scanned, no additional info is retrieved
  1506. const SM_FULL_INFO = 1; // terms are scanned, frequency and position info is retrieved
  1507. const SM_MERGE_INFO = 2; // terms are scanned, frequency and position info is retrieved
  1508. // document numbers are compacted (shifted if segment contains deleted documents)
  1509. /**
  1510. * Reset terms stream
  1511. *
  1512. * $startId - id for the fist document
  1513. * $compact - remove deleted documents
  1514. *
  1515. * Returns start document id for the next segment
  1516. *
  1517. * @param integer $startId
  1518. * @param integer $mode
  1519. * @throws Zend_Search_Lucene_Exception
  1520. * @return integer
  1521. */
  1522. public function resetTermsStream(/** $startId = 0, $mode = self::SM_TERMS_ONLY */)
  1523. {
  1524. /**
  1525. * SegmentInfo->resetTermsStream() method actually takes two optional parameters:
  1526. * $startId (default value is 0)
  1527. * $mode (default value is self::SM_TERMS_ONLY)
  1528. */
  1529. $argList = func_get_args();
  1530. if (count($argList) > 2) {
  1531. require_once 'Zend/Search/Lucene/Exception.php';
  1532. throw new Zend_Search_Lucene_Exception('Wrong number of arguments');
  1533. } else if (count($argList) == 2) {
  1534. $startId = $argList[0];
  1535. $mode = $argList[1];
  1536. } else if (count($argList) == 1) {
  1537. $startId = $argList[0];
  1538. $mode = self::SM_TERMS_ONLY;
  1539. } else {
  1540. $startId = 0;
  1541. $mode = self::SM_TERMS_ONLY;
  1542. }
  1543. if ($this->_tisFile !== null) {
  1544. $this->_tisFile = null;
  1545. }
  1546. $this->_tisFile = $this->openCompoundFile('.tis', false);
  1547. $this->_tisFileOffset = $this->_tisFile->tell();
  1548. $tiVersion = $this->_tisFile->readInt();
  1549. if ($tiVersion != (int)0xFFFFFFFE /* pre-2.1 format */ &&
  1550. $tiVersion != (int)0xFFFFFFFD /* 2.1+ format */) {
  1551. require_once 'Zend/Search/Lucene/Exception.php';
  1552. throw new Zend_Search_Lucene_Exception('Wrong TermInfoFile file format');
  1553. }
  1554. $this->_termCount =
  1555. $this->_termNum = $this->_tisFile->readLong(); // Read terms count
  1556. $this->_indexInterval = $this->_tisFile->readInt(); // Read Index interval
  1557. $this->_skipInterval = $this->_tisFile->readInt(); // Read skip interval
  1558. if ($tiVersion == (int)0xFFFFFFFD /* 2.1+ format */) {
  1559. $maxSkipLevels = $this->_tisFile->readInt();
  1560. }
  1561. if ($this->_frqFile !== null) {
  1562. $this->_frqFile = null;
  1563. }
  1564. if ($this->_prxFile !== null) {
  1565. $this->_prxFile = null;
  1566. }
  1567. $this->_docMap = array();
  1568. $this->_lastTerm = new Zend_Search_Lucene_Index_Term('', -1);
  1569. $this->_lastTermInfo = new Zend_Search_Lucene_Index_TermInfo(0, 0, 0, 0);
  1570. $this->_lastTermPositions = null;
  1571. $this->_termsScanMode = $mode;
  1572. switch ($mode) {
  1573. case self::SM_TERMS_ONLY:
  1574. // Do nothing
  1575. break;
  1576. case self::SM_FULL_INFO:
  1577. // break intentionally omitted
  1578. case self::SM_MERGE_INFO:
  1579. $this->_frqFile = $this->openCompoundFile('.frq', false);
  1580. $this->_frqFileOffset = $this->_frqFile->tell();
  1581. $this->_prxFile = $this->openCompoundFile('.prx', false);
  1582. $this->_prxFileOffset = $this->_prxFile->tell();
  1583. for ($count = 0; $count < $this->_docCount; $count++) {
  1584. if (!$this->isDeleted($count)) {
  1585. $this->_docMap[$count] = $startId + (($mode == self::SM_MERGE_INFO) ? count($this->_docMap) : $count);
  1586. }
  1587. }
  1588. break;
  1589. default:
  1590. require_once 'Zend/Search/Lucene/Exception.php';
  1591. throw new Zend_Search_Lucene_Exception('Wrong terms scaning mode specified.');
  1592. break;
  1593. }
  1594. // Calculate next segment start id (since $this->_docMap structure may be cleaned by $this->nextTerm() call)
  1595. $nextSegmentStartId = $startId + (($mode == self::SM_MERGE_INFO) ? count($this->_docMap) : $this->_docCount);
  1596. $this->nextTerm();
  1597. return $nextSegmentStartId;
  1598. }
  1599. /**
  1600. * Skip terms stream up to specified term preffix.
  1601. *
  1602. * Prefix contains fully specified field info and portion of searched term
  1603. *
  1604. * @param Zend_Search_Lucene_Index_Term $prefix
  1605. * @throws Zend_Search_Lucene_Exception
  1606. */
  1607. public function skipTo(Zend_Search_Lucene_Index_Term $prefix)
  1608. {
  1609. if ($this->_termDictionary === null) {
  1610. $this->_loadDictionaryIndex();
  1611. }
  1612. $searchField = $this->getFieldNum($prefix->field);
  1613. if ($searchField == -1) {
  1614. /**
  1615. * Field is not presented in this segment
  1616. * Go to the end of dictionary
  1617. */
  1618. $this->_tisFile = null;
  1619. $this->_frqFile = null;
  1620. $this->_prxFile = null;
  1621. $this->_lastTerm = null;
  1622. $this->_lastTermInfo = null;
  1623. $this->_lastTermPositions = null;
  1624. return;
  1625. }
  1626. $searchDicField = $this->_getFieldPosition($searchField);
  1627. // search for appropriate value in dictionary
  1628. $lowIndex = 0;
  1629. $highIndex = count($this->_termDictionary)-1;
  1630. while ($highIndex >= $lowIndex) {
  1631. // $mid = ($highIndex - $lowIndex)/2;
  1632. $mid = ($highIndex + $lowIndex) >> 1;
  1633. $midTerm = $this->_termDictionary[$mid];
  1634. $fieldNum = $this->_getFieldPosition($midTerm[0] /* field */);
  1635. $delta = $searchDicField - $fieldNum;
  1636. if ($delta == 0) {
  1637. $delta = strcmp($prefix->text, $midTerm[1] /* text */);
  1638. }
  1639. if ($delta < 0) {
  1640. $highIndex = $mid-1;
  1641. } elseif ($delta > 0) {
  1642. $lowIndex = $mid+1;
  1643. } else {
  1644. // We have reached term we are looking for
  1645. break;
  1646. }
  1647. }
  1648. if ($highIndex == -1) {
  1649. // Term is out of the dictionary range
  1650. $this->_tisFile = null;
  1651. $this->_frqFile = null;
  1652. $this->_prxFile = null;
  1653. $this->_lastTerm = null;
  1654. $this->_lastTermInfo = null;
  1655. $this->_lastTermPositions = null;
  1656. return;
  1657. }
  1658. $prevPosition = $highIndex;
  1659. $prevTerm = $this->_termDictionary[$prevPosition];
  1660. $prevTermInfo = $this->_termDictionaryInfos[$prevPosition];
  1661. if ($this->_tisFile === null) {
  1662. // The end of terms stream is reached and terms dictionary file is closed
  1663. // Perform mini-reset operation
  1664. $this->_tisFile = $this->openCompoundFile('.tis', false);
  1665. if ($this->_termsScanMode == self::SM_FULL_INFO || $this->_termsScanMode == self::SM_MERGE_INFO) {
  1666. $this->_frqFile = $this->openCompoundFile('.frq', false);
  1667. $this->_prxFile = $this->openCompoundFile('.prx', false);
  1668. }
  1669. }
  1670. $this->_tisFile->seek($this->_tisFileOffset + $prevTermInfo[4], SEEK_SET);
  1671. $this->_lastTerm = new Zend_Search_Lucene_Index_Term($prevTerm[1] /* text */,
  1672. ($prevTerm[0] == -1) ? '' : $this->_fields[$prevTerm[0] /* field */]->name);
  1673. $this->_lastTermInfo = new Zend_Search_Lucene_Index_TermInfo($prevTermInfo[0] /* docFreq */,
  1674. $prevTermInfo[1] /* freqPointer */,
  1675. $prevTermInfo[2] /* proxPointer */,
  1676. $prevTermInfo[3] /* skipOffset */);
  1677. $this->_termCount = $this->_termNum - $prevPosition*$this->_indexInterval;
  1678. if ($highIndex == 0) {
  1679. // skip start entry
  1680. $this->nextTerm();
  1681. } else if ($prefix->field == $this->_lastTerm->field && $prefix->text == $this->_lastTerm->text) {
  1682. // We got exact match in the dictionary index
  1683. if ($this->_termsScanMode == self::SM_FULL_INFO || $this->_termsScanMode == self::SM_MERGE_INFO) {
  1684. $this->_lastTermPositions = array();
  1685. $this->_frqFile->seek($this->_lastTermInfo->freqPointer + $this->_frqFileOffset, SEEK_SET);
  1686. $freqs = array(); $docId = 0;
  1687. for( $count = 0; $count < $this->_lastTermInfo->docFreq; $count++ ) {
  1688. $docDelta = $this->_frqFile->readVInt();
  1689. if( $docDelta % 2 == 1 ) {
  1690. $docId += ($docDelta-1)/2;
  1691. $freqs[ $docId ] = 1;
  1692. } else {
  1693. $docId += $docDelta/2;
  1694. $freqs[ $docId ] = $this->_frqFile->readVInt();
  1695. }
  1696. }
  1697. $this->_prxFile->seek($this->_lastTermInfo->proxPointer + $this->_prxFileOffset, SEEK_SET);
  1698. foreach ($freqs as $docId => $freq) {
  1699. $termPosition = 0; $positions = array();
  1700. for ($count = 0; $count < $freq; $count++ ) {
  1701. $termPosition += $this->_prxFile->readVInt();
  1702. $positions[] = $termPosition;
  1703. }
  1704. if (isset($this->_docMap[$docId])) {
  1705. $this->_lastTermPositions[$this->_docMap[$docId]] = $positions;
  1706. }
  1707. }
  1708. }
  1709. return;
  1710. }
  1711. // Search term matching specified prefix
  1712. while ($this->_lastTerm !== null) {
  1713. if ( strcmp($this->_lastTerm->field, $prefix->field) > 0 ||
  1714. ($prefix->field == $this->_lastTerm->field && strcmp($this->_lastTerm->text, $prefix->text) >= 0) ) {
  1715. // Current term matches or greate than the pattern
  1716. return;
  1717. }
  1718. $this->nextTerm();
  1719. }
  1720. }
  1721. /**
  1722. * Scans terms dictionary and returns next term
  1723. *
  1724. * @return Zend_Search_Lucene_Index_Term|null
  1725. */
  1726. public function nextTerm()
  1727. {
  1728. if ($this->_tisFile === null || $this->_termCount == 0) {
  1729. $this->_lastTerm = null;
  1730. $this->_lastTermInfo = null;
  1731. $this->_lastTermPositions = null;
  1732. $this->_docMap = null;
  1733. // may be necessary for "empty" segment
  1734. $this->_tisFile = null;
  1735. $this->_frqFile = null;
  1736. $this->_prxFile = null;
  1737. return null;
  1738. }
  1739. $termPrefixLength = $this->_tisFile->readVInt();
  1740. $termSuffix = $this->_tisFile->readString();
  1741. $termFieldNum = $this->_tisFile->readVInt();
  1742. $termValue = Zend_Search_Lucene_Index_Term::getPrefix($this->_lastTerm->text, $termPrefixLength) . $termSuffix;
  1743. $this->_lastTerm = new Zend_Search_Lucene_Index_Term($termValue, $this->_fields[$termFieldNum]->name);
  1744. $docFreq = $this->_tisFile->readVInt();
  1745. $freqPointer = $this->_lastTermInfo->freqPointer + $this->_tisFile->readVInt();
  1746. $proxPointer = $this->_lastTermInfo->proxPointer + $this->_tisFile->readVInt();
  1747. if ($docFreq >= $this->_skipInterval) {
  1748. $skipOffset = $this->_tisFile->readVInt();
  1749. } else {
  1750. $skipOffset = 0;
  1751. }
  1752. $this->_lastTermInfo = new Zend_Search_Lucene_Index_TermInfo($docFreq, $freqPointer, $proxPointer, $skipOffset);
  1753. if ($this->_termsScanMode == self::SM_FULL_INFO || $this->_termsScanMode == self::SM_MERGE_INFO) {
  1754. $this->_lastTermPositions = array();
  1755. $this->_frqFile->seek($this->_lastTermInfo->freqPointer + $this->_frqFileOffset, SEEK_SET);
  1756. $freqs = array(); $docId = 0;
  1757. for( $count = 0; $count < $this->_lastTermInfo->docFreq; $count++ ) {
  1758. $docDelta = $this->_frqFile->readVInt();
  1759. if( $docDelta % 2 == 1 ) {
  1760. $docId += ($docDelta-1)/2;
  1761. $freqs[ $docId ] = 1;
  1762. } else {
  1763. $docId += $docDelta/2;
  1764. $freqs[ $docId ] = $this->_frqFile->readVInt();
  1765. }
  1766. }
  1767. $this->_prxFile->seek($this->_lastTermInfo->proxPointer + $this->_prxFileOffset, SEEK_SET);
  1768. foreach ($freqs as $docId => $freq) {
  1769. $termPosition = 0; $positions = array();
  1770. for ($count = 0; $count < $freq; $count++ ) {
  1771. $termPosition += $this->_prxFile->readVInt();
  1772. $positions[] = $termPosition;
  1773. }
  1774. if (isset($this->_docMap[$docId])) {
  1775. $this->_lastTermPositions[$this->_docMap[$docId]] = $positions;
  1776. }
  1777. }
  1778. }
  1779. $this->_termCount--;
  1780. if ($this->_termCount == 0) {
  1781. $this->_tisFile = null;
  1782. $this->_frqFile = null;
  1783. $this->_prxFile = null;
  1784. }
  1785. return $this->_lastTerm;
  1786. }
  1787. /**
  1788. * Close terms stream
  1789. *
  1790. * Should be used for resources clean up if stream is not read up to the end
  1791. */
  1792. public function closeTermsStream()
  1793. {
  1794. $this->_tisFile = null;
  1795. $this->_frqFile = null;
  1796. $this->_prxFile = null;
  1797. $this->_lastTerm = null;
  1798. $this->_lastTermInfo = null;
  1799. $this->_lastTermPositions = null;
  1800. $this->_docMap = null;
  1801. }
  1802. /**
  1803. * Returns term in current position
  1804. *
  1805. * @return Zend_Search_Lucene_Index_Term|null
  1806. */
  1807. public function currentTerm()
  1808. {
  1809. return $this->_lastTerm;
  1810. }
  1811. /**
  1812. * Returns an array of all term positions in the documents.
  1813. * Return array structure: array( docId => array( pos1, pos2, ...), ...)
  1814. *
  1815. * @return array
  1816. */
  1817. public function currentTermPositions()
  1818. {
  1819. return $this->_lastTermPositions;
  1820. }
  1821. }