Opera 12.15 Source Code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

VisitedSearch.cpp 66KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678
  1. /* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
  2. **
  3. ** Copyright (C) 1995-2011 Opera Software ASA. All rights reserved.
  4. **
  5. ** This file is part of the Opera web browser.
  6. ** It may not be distributed under any circumstances.
  7. */
  8. #include "core/pch.h"
  9. #ifdef VISITED_PAGES_SEARCH
  10. #include "modules/search_engine/VisitedSearch.h"
  11. #include "modules/pi/OpSystemInfo.h"
  12. #include "modules/pi/system/OpFolderLister.h"
  13. #include "modules/util/opfile/opfile.h"
  14. #include "modules/util/tempbuf.h"
  15. #include "modules/search_engine/WordHighlighter.h"
  16. #include "modules/search_engine/WordSegmenter.h"
  17. #include "modules/search_engine/UniCompressor.h"
  18. #include "modules/search_engine/VSIterator.h"
  19. #include "modules/search_engine/VSUtil.h"
  20. #include "modules/search_engine/ACTUtil.h"
  21. #if defined(USE_OP_THREAD_TOOLS) && defined(VPS_WRAPPER)
  22. #include "modules/pi/OpThreadTools.h"
  23. #endif // USE_OP_THREAD_TOOLS && VPS_WRAPPER
  24. #define MAX_DOC_WORDS 5000
  25. #define STOPWORD_DOC_COUNT 500
  26. // max size in MB if no size is specified
  27. #define DEFAULT_MAX_SIZE 1024
  28. // flush timing
  29. #define DELAY_MSG_PREFLUSH 240000
  30. #define PREFLUSH_LIMIT 100
  31. #define DELAY_PREFLUSH 200
  32. #define DELAY_PREFLUSH_FLUSH 30000
  33. #define FLUSH_LIMIT 100
  34. #define DELAY_FLUSH 150
  35. #define DELAY_FLUSH_COMMIT 30000
  36. #define DELAY_COMMIT_PREFLUSH 180000
  37. #define NUM_RETRIES 5
  38. #define ERROR_RETRY_MS 5000
  39. #define BUSY_RETRY_MS 10000
  40. /*****************************************************************************
  41. open/close */
  42. VisitedSearch::VisitedSearch(void) : m_index(&RankIndex::CompareId, &PtrDescriptor<RankIndex>::Destruct),
  43. m_cache(&FileWord::LessThan, &PtrDescriptor<FileWord>::Destruct),
  44. m_preflush(&FileWord::LessThan, &PtrDescriptor<FileWord>::Destruct),
  45. m_pending(),
  46. m_meta(&PtrDescriptor<RecordHandleRec>::Destruct),
  47. m_meta_pf(&PtrDescriptor<RecordHandleRec>::Destruct)
  48. {
  49. #if defined SEARCH_ENGINE_LOG && (SEARCH_ENGINE_LOG & SEARCH_ENGINE_LOG_VISITEDSEARCH)
  50. m_log = NULL;
  51. #endif
  52. m_flags = 0;
  53. m_max_size = INVALID_FILE_LENGTH;
  54. m_subindex_size = INVALID_FILE_LENGTH;
  55. m_pos = 0;
  56. m_flush_errors = 0;
  57. }
  58. CHECK_RESULT(static OP_STATUS ScanDir(TVector<int> &subdirs, const uni_char *directory));
  59. static OP_STATUS ScanDir(TVector<int> &subdirs, const uni_char *directory)
  60. {
  61. OpFolderLister *lister;
  62. const uni_char *fname;
  63. uni_char *endptr;
  64. int num;
  65. OpString path;
  66. OP_BOOLEAN exists;
  67. OP_STATUS err;
  68. RETURN_IF_ERROR(exists = BlockStorage::FileExists(directory));
  69. if (exists == OpBoolean::IS_FALSE)
  70. return OpStatus::OK;
  71. RETURN_OOM_IF_NULL(path.Reserve((int)uni_strlen(directory) + 7 + (int)op_strlen(FNAME_WB)));
  72. RETURN_OOM_IF_NULL(lister = OpFile::GetFolderLister(OPFILE_ABSOLUTE_FOLDER, UNI_L("*"), directory));
  73. while (lister->Next())
  74. {
  75. fname = lister->GetFileName();
  76. num = uni_strtoul(fname, &endptr, 10);
  77. RETURN_IF_ERROR(path.Set(directory));
  78. RETURN_IF_ERROR(path.AppendFormat(UNI_L("%c%.04i%c%s"), PATHSEPCHAR, num, PATHSEPCHAR, UNI_L(FNAME_WB)));
  79. RETURN_IF_ERROR(exists = BlockStorage::FileExists(path.CStr()));
  80. if (lister->IsFolder() && uni_strlen(fname) == 4 && endptr - fname == 4 && exists == OpBoolean::IS_TRUE)
  81. {
  82. if (OpStatus::IsError(err = subdirs.Insert(num)))
  83. {
  84. OP_DELETE(lister);
  85. return err;
  86. }
  87. }
  88. }
  89. OP_DELETE(lister);
  90. return OpStatus::OK;
  91. }
  92. OP_STATUS VisitedSearch::Open(const uni_char *directory)
  93. {
  94. short i, pos;
  95. RankIndex *r;
  96. OP_STATUS err;
  97. TVector<int> subdirs;
  98. time_t min_time, modif_time;
  99. OpFileLength total_size;
  100. // if (m_max_size < MAX_VISITED_SEARCH_SUBINDEX_SIZE * 2097152)
  101. // return OpStatus::ERR;
  102. {
  103. // Do not listen to these messages when the wrapper is present, the wrapper will make sure
  104. // the messages are posted and read in a threadsafe manner.
  105. #ifndef VPS_WRAPPER
  106. OpMessage msg[] = {MSG_VISITEDSEARCH_PREFLUSH, MSG_VISITEDSEARCH_FLUSH, MSG_VISITEDSEARCH_COMMIT};
  107. RETURN_IF_ERROR(g_main_message_handler->SetCallBackList(this, (MH_PARAM_1)this, msg, 3));
  108. #endif // !VPS_WRAPPER
  109. }
  110. if (OpStatus::IsError(err = ScanDir(subdirs, directory)))
  111. {
  112. #ifndef VPS_WRAPPER
  113. g_main_message_handler->UnsetCallBacks(this);
  114. #endif // !VPS_WRAPPER
  115. return err;
  116. }
  117. if (OpStatus::IsError(err = m_index.Reserve(subdirs.GetSize())))
  118. {
  119. #ifndef VPS_WRAPPER
  120. g_main_message_handler->UnsetCallBacks(this);
  121. #endif // !VPS_WRAPPER
  122. return err;
  123. }
  124. #if defined SEARCH_ENGINE_LOG && (SEARCH_ENGINE_LOG & SEARCH_ENGINE_LOG_VISITEDSEARCH)
  125. OpString journalname;
  126. RETURN_IF_ERROR(journalname.SetConcat(directory, UNI_L(PATHSEP), UNI_L("vps.log")));
  127. if (m_log != NULL)
  128. OP_DELETE(m_log);
  129. SearchEngineLog::ShiftLogFile(10, journalname);
  130. if ((m_log = SearchEngineLog::CreateLog(SearchEngineLog::File, journalname.CStr())) == NULL)
  131. return OpStatus::ERR;
  132. #endif
  133. min_time = (time_t)-1;
  134. pos = 0;
  135. total_size = 0;
  136. for (i = subdirs.GetCount() - 1; i >= 0; --i)
  137. {
  138. if ((r = OP_NEW(RankIndex, ())) == NULL)
  139. {
  140. #ifndef VPS_WRAPPER
  141. g_main_message_handler->UnsetCallBacks(this);
  142. #endif // !VPS_WRAPPER
  143. m_index.Clear();
  144. return OpStatus::ERR_NO_MEMORY;
  145. }
  146. #if defined SEARCH_ENGINE_LOG && (SEARCH_ENGINE_LOG & SEARCH_ENGINE_LOG_VISITEDSEARCH)
  147. if (OpStatus::IsError(RankIndex::LogSubDir(m_log, directory, subdirs[i])))
  148. {
  149. #ifndef VPS_WRAPPER
  150. g_main_message_handler->UnsetCallBacks(this);
  151. #endif // !VPS_WRAPPER
  152. OP_DELETE(r);
  153. m_index.Clear();
  154. return err;
  155. }
  156. #endif
  157. if (OpStatus::IsError(err = r->Open(directory, subdirs[i])))
  158. {
  159. #ifndef VPS_WRAPPER
  160. g_main_message_handler->UnsetCallBacks(this);
  161. #endif // !VPS_WRAPPER
  162. OP_DELETE(r);
  163. m_index.Clear();
  164. return err;
  165. }
  166. modif_time = r->ModifTime();
  167. OP_ASSERT(modif_time != (time_t)-1);
  168. // this is the latest subindex
  169. if (modif_time != (time_t)-1 && (min_time == (time_t)-1 || min_time < modif_time))
  170. {
  171. min_time = modif_time;
  172. pos = 0;
  173. }
  174. if (!r->m_wordbag.IsNativeEndian())
  175. {
  176. OpStatus::Ignore(r->Clear());
  177. OP_DELETE(r);
  178. }
  179. else if (OpStatus::IsError(err = m_index.Insert(pos, r)))
  180. {
  181. #ifndef VPS_WRAPPER
  182. g_main_message_handler->UnsetCallBacks(this);
  183. #endif // !VPS_WRAPPER
  184. OP_DELETE(r);
  185. m_index.Clear();
  186. return err;
  187. }
  188. else {
  189. ++pos;
  190. if (m_max_size == INVALID_FILE_LENGTH)
  191. total_size += r->Size();
  192. }
  193. }
  194. if (m_index.GetCount() == 0)
  195. {
  196. if ((r = OP_NEW(RankIndex, ())) == NULL)
  197. {
  198. #ifndef VPS_WRAPPER
  199. g_main_message_handler->UnsetCallBacks(this);
  200. #endif // !VPS_WRAPPER
  201. return OpStatus::ERR_NO_MEMORY;
  202. }
  203. if (OpStatus::IsError(err = r->Open(directory, 0)))
  204. {
  205. #ifndef VPS_WRAPPER
  206. g_main_message_handler->UnsetCallBacks(this);
  207. #endif // !VPS_WRAPPER
  208. OP_DELETE(r);
  209. return err;
  210. }
  211. if (OpStatus::IsError(err = m_index.Add(r)))
  212. {
  213. #ifndef VPS_WRAPPER
  214. g_main_message_handler->UnsetCallBacks(this);
  215. #endif // !VPS_WRAPPER
  216. OP_DELETE(r);
  217. return err;
  218. }
  219. }
  220. if (m_max_size == INVALID_FILE_LENGTH)
  221. {
  222. if (total_size > DEFAULT_MAX_SIZE * 1048576)
  223. m_max_size = total_size;
  224. else
  225. m_max_size = DEFAULT_MAX_SIZE * 1048576;
  226. m_subindex_size = m_max_size / 10;
  227. }
  228. #if 0 // #ifdef _DEBUG
  229. TVector<RankId> wordlist(&(RankId::CompareId));
  230. SearchIterator<ACT::PrefixResult> *res;
  231. int j;
  232. int wb_block_size, meta_block_size;
  233. register OpFileLength block_pos, vector_pos;
  234. for (i = m_index.GetCount() - 1; i >= 0; --i)
  235. {
  236. res = m_index[i]->m_act.PrefixCaseSearch("");
  237. OP_ASSERT(res != NULL);
  238. // freshly created ACT
  239. if (res->End())
  240. {
  241. OP_DELETE(res);
  242. continue;
  243. }
  244. wb_block_size = m_index[i]->m_wordbag.GetBlockSize();
  245. meta_block_size = m_index[i]->m_metadata.GetBlockSize();
  246. do {
  247. vector_pos = res->Get().id * wb_block_size;
  248. wordlist.SetCount(m_index[i]->m_wordbag.DataLength(vector_pos) / sizeof(RankId));
  249. m_index[i]->m_wordbag.ReadApnd(wordlist.Ptr(), wordlist.GetCount() * sizeof(RankId), vector_pos);
  250. OP_ASSERT(wordlist.GetCount() > 0);
  251. for (j = wordlist.GetCount() - 1; j >= 0; --j)
  252. {
  253. block_pos = wordlist[j].data[1] * meta_block_size;
  254. OP_ASSERT(m_index[i]->m_metadata.IsStartBlock(block_pos));
  255. }
  256. } while (res->Next());
  257. OP_DELETE(res);
  258. }
  259. #endif
  260. #if defined SEARCH_ENGINE_LOG && (SEARCH_ENGINE_LOG & SEARCH_ENGINE_LOG_VISITEDSEARCH)
  261. if (m_log != NULL)
  262. m_log->Write(SearchEngineLog::Debug, "Open", UNI_L("%s"), directory);
  263. #endif
  264. return OpStatus::OK;
  265. }
  266. void VisitedSearch::SetMaxSize(OpFileLength max_size)
  267. {
  268. #if defined SEARCH_ENGINE_LOG && (SEARCH_ENGINE_LOG & SEARCH_ENGINE_LOG_VISITEDSEARCH)
  269. if (m_log != NULL)
  270. m_log->Write(SearchEngineLog::Debug, "SetMaxSize", "%f", (double)max_size);
  271. #endif
  272. if (max_size == INVALID_FILE_LENGTH || (max_size >> 24) > 1048576)
  273. max_size = DEFAULT_MAX_SIZE;
  274. m_max_size = max_size * 1048576;
  275. m_subindex_size = m_max_size / 10;
  276. CheckMaxSize_RemoveOldIndexes();
  277. }
  278. void VisitedSearch::SetMaxItems(int max_items)
  279. {
  280. if (max_items < 0)
  281. SetMaxSize(INVALID_FILE_LENGTH);
  282. else if (max_items < 20)
  283. SetMaxSize(0);
  284. else {
  285. max_items *= 25600; // 1 URL took roughly 25KB when I measured
  286. SetMaxSize((max_items + 1048575) / 1048576);
  287. }
  288. }
  289. OP_STATUS VisitedSearch::Close(BOOL force_close)
  290. {
  291. OP_STATUS err;
  292. if (m_index.GetCount() == 0)
  293. {
  294. m_cache.Clear();
  295. m_preflush.Clear();
  296. #ifndef VPS_WRAPPER
  297. g_main_message_handler->UnsetCallBacks(this);
  298. #endif // !VPS_WRAPPER
  299. return OpStatus::OK;
  300. }
  301. OpStatus::Ignore(Commit());
  302. if (m_meta.GetCount() > 0 || m_meta_pf.GetCount() > 0 || (m_flags & Flushed) != 0)
  303. {
  304. err = Commit();
  305. if (!force_close)
  306. RETURN_IF_ERROR(err);
  307. }
  308. else
  309. err = OpStatus::OK;
  310. #if defined SEARCH_ENGINE_LOG && (SEARCH_ENGINE_LOG & SEARCH_ENGINE_LOG_VISITEDSEARCH)
  311. if (m_log != NULL)
  312. {
  313. m_log->Write(SearchEngineLog::Debug, "Close", "");
  314. OP_DELETE(m_log);
  315. m_log = NULL;
  316. }
  317. #endif
  318. m_index.Clear();
  319. #ifndef VPS_WRAPPER
  320. g_main_message_handler->UnsetCallBacks(this);
  321. #endif // !VPS_WRAPPER
  322. return err;
  323. }
  324. OP_STATUS VisitedSearch::Clear(BOOL reopen)
  325. {
  326. int i;
  327. OpString path;
  328. m_cache.Clear();
  329. m_preflush.Clear();
  330. m_meta.Clear();
  331. m_meta_pf.Clear();
  332. if (m_index.GetCount() == 0)
  333. return OpStatus::OK;
  334. RETURN_IF_ERROR(path.Set(m_index[0]->m_wordbag.GetFullName()));
  335. path.Delete(path.Length() - 6 - (int)op_strlen(FNAME_WB)); // the main directory
  336. for (i = m_index.GetCount() - 1; i >= 0; --i)
  337. RETURN_IF_ERROR(m_index[i]->Clear());
  338. m_index.Clear();
  339. for (i = 0; i < (int)m_pending.GetCount(); i++)
  340. m_pending[i]->Invalidate(); // The indexes are gone, invalidate all pending records
  341. m_flags = 0;
  342. m_pos = 0;
  343. m_flush_errors = 0;
  344. if (!reopen)
  345. {
  346. OpStatus::Ignore(BlockStorage::DeleteFile(path.CStr()));
  347. return OpStatus::OK;
  348. }
  349. #ifndef VPS_WRAPPER
  350. g_main_message_handler->UnsetCallBacks(this);
  351. #endif // !VPS_WRAPPER
  352. return Open(path.CStr());
  353. }
  354. /*****************************************************************************
  355. RecordHandle */
  356. VisitedSearch::RecordHandle VisitedSearch::CreateRecord(const char *url, const uni_char *title)
  357. {
  358. RecordHandleRec *cursor;
  359. OP_STATUS err;
  360. if (!IsOpen())
  361. return NULL;
  362. if ((cursor = OP_NEW(RecordHandleRec, (m_index[0]))) == NULL)
  363. return NULL;
  364. cursor->m_word_count = 0;
  365. #if defined SEARCH_ENGINE_LOG && (SEARCH_ENGINE_LOG & SEARCH_ENGINE_LOG_VISITEDSEARCH)
  366. if (m_log != NULL)
  367. {
  368. m_log->Write(SearchEngineLog::Debug, "CreateRecord", "%X %s", (INTPTR)cursor, url);
  369. if (title != NULL)
  370. m_log->Write(SearchEngineLog::Debug, "record title", UNI_L("%X %s"), (INTPTR)cursor, title);
  371. }
  372. #endif
  373. if (OpStatus::IsError(err = RankIndex::SetupCursor(*cursor)))
  374. goto visitedsearch_create_record;
  375. if (OpStatus::IsError(err = cursor->Create()))
  376. goto visitedsearch_create_record;
  377. if (OpStatus::IsError(err = cursor->GetField("visited").SetValue(op_time(NULL))))
  378. goto visitedsearch_create_record;
  379. if (OpStatus::IsError(err = cursor->GetField("invalid").SetValue(0)))
  380. goto visitedsearch_create_record;
  381. if (OpStatus::IsError(err = cursor->GetField("url").SetStringValue(url)))
  382. goto visitedsearch_create_record;
  383. if (title != NULL)
  384. {
  385. if (OpStatus::IsError(err = cursor->GetField("title").SetStringValue(title)))
  386. goto visitedsearch_create_record;
  387. if (OpStatus::IsError(err = IndexTextBlock(cursor, title, RANK_TITLE)))
  388. goto visitedsearch_create_record;
  389. }
  390. if (OpStatus::IsError(err = IndexURL(cursor, url, RANK_TITLE)))
  391. goto visitedsearch_create_record;
  392. if (OpStatus::IsError(err = m_pending.Add(cursor)))
  393. goto visitedsearch_create_record;
  394. return cursor;
  395. visitedsearch_create_record:
  396. #if defined SEARCH_ENGINE_LOG && (SEARCH_ENGINE_LOG & SEARCH_ENGINE_LOG_VISITEDSEARCH)
  397. if (m_log != NULL)
  398. m_log->Write(SearchEngineLog::Warning, "CreateRecord failed", "%X", (INTPTR)cursor);
  399. #endif
  400. OP_DELETE(cursor);
  401. return NULL;
  402. }
  403. OP_STATUS VisitedSearch::AddTitle(RecordHandle handle, const uni_char *title)
  404. {
  405. int old_word_count;
  406. if (title == NULL || *title == 0)
  407. return OpStatus::OK;
  408. if (handle->IsInvalid())
  409. return OpStatus::ERR;
  410. if (handle->GetField("title").GetSize() > 0)
  411. return OpStatus::OK;
  412. #if defined SEARCH_ENGINE_LOG && (SEARCH_ENGINE_LOG & SEARCH_ENGINE_LOG_VISITEDSEARCH)
  413. if (m_log != NULL)
  414. m_log->Write(SearchEngineLog::Debug, "record title", UNI_L("%X %s"), (INTPTR)handle, title);
  415. #endif
  416. RETURN_IF_ERROR(handle->GetField("title").SetStringValue(title));
  417. old_word_count = handle->m_word_count;
  418. RETURN_IF_ERROR(IndexTextBlock(handle, title, RANK_TITLE));
  419. handle->m_word_count = old_word_count; // word count is not changed by title
  420. return OpStatus::OK;
  421. }
  422. OP_STATUS VisitedSearch::AddWord(VisitedSearch::RecordHandle handle, const uni_char *text, float ranking)
  423. {
  424. WordRank w(text, ranking);
  425. OP_STATUS ret = handle->m_word_list.Add(w);
  426. if (OpStatus::IsError(ret))
  427. {
  428. w.Destroy();
  429. return ret;
  430. }
  431. return OpStatus::OK;
  432. }
  433. OP_STATUS VisitedSearch::IndexTextBlock(VisitedSearch::RecordHandle handle, const uni_char *text, float ranking, BOOL fine_segmenting)
  434. {
  435. WordSegmenter msgtok(fine_segmenting ? WordSegmenter::FineSegmenting : 0);
  436. OpString word;
  437. OP_BOOLEAN e;
  438. register const uni_char *chk;
  439. UINT16 hash;
  440. if (!text || !*text)
  441. return OpStatus::OK;
  442. RETURN_IF_ERROR(msgtok.Set(text));
  443. RETURN_IF_ERROR(e = msgtok.GetNextToken(word));
  444. while (e == OpBoolean::IS_TRUE && handle->m_word_count <= MAX_DOC_WORDS)
  445. {
  446. word.MakeUpper();
  447. // it isn't expected to have invalid ACT characters here, but let's rather check anyway
  448. for (chk = word.CStr(); *chk != 0; ++chk)
  449. if ((UINT16)*chk <= FIRST_CHAR)
  450. break;
  451. if (*chk != 0)
  452. {
  453. RETURN_IF_ERROR(e = msgtok.GetNextToken(word));
  454. continue;
  455. }
  456. RETURN_IF_ERROR(AddWord(handle, word.CStr(), ranking));
  457. ++(handle->m_word_count);
  458. RETURN_IF_ERROR(e = msgtok.GetNextToken(word));
  459. }
  460. handle->GetField("hash").GetValue(&hash);
  461. while (*text != 0)
  462. {
  463. hash *= 101;
  464. hash ^= *text;
  465. ++text;
  466. }
  467. RETURN_IF_ERROR(handle->GetField("hash").SetValue(hash));
  468. return OpStatus::OK;
  469. }
  470. OP_STATUS VisitedSearch::IndexURL(VisitedSearch::RecordHandle handle, const char *url, float ranking)
  471. {
  472. OpString url16;
  473. uni_char *end, *dot, *domain;
  474. int words_indexed;
  475. unsigned offset = 0;
  476. if ((op_strnicmp(url, "http://", 7) == 0) && url[7] != 0)
  477. offset = 7;
  478. else if ((op_strnicmp(url, "https://", 8) == 0) && url[8] != 0)
  479. offset = 8;
  480. if (offset == 0)
  481. return OpStatus::OK;
  482. RETURN_IF_ERROR(url16.SetFromUTF8(url));
  483. domain = (uni_char *)url16.CStr() + offset;
  484. if ((end = uni_strchr(domain, '/')) == NULL)
  485. if ((end = uni_strchr(domain, '?')) == NULL)
  486. if ((end = uni_strchr(domain, '#')) == NULL)
  487. end = domain + uni_strlen(domain);
  488. // Domain is case-insensitive. For the purpose of fine-grained word-segmenting below, don't consider camelcasing here relevant
  489. for (uni_char *p = domain; p < end; p++)
  490. *p = uni_tolower(*p);
  491. RETURN_IF_ERROR(AddTextBlock(handle, url16.CStr(), ranking)); // Add whole url as is, also to plaintext field in case of phrase filtering
  492. handle->m_plaintext.Append(UNI_L("\r")); // Add "excerpt boundary" (repurposing CR) so that highlighted excerpts don't include url unnecessarily
  493. RETURN_IF_ERROR(IndexTextBlock(handle, url16.CStr(), ranking, TRUE)); // Add again using fine-grained word-segmenting (CORE-44206)
  494. // Remove path, replace "http://" with "site:"
  495. *end = 0;
  496. url16.Delete(0, offset);
  497. RETURN_IF_ERROR(url16.Insert(0, "site:"));
  498. url16.MakeUpper();
  499. words_indexed = 0;
  500. while ((dot = uni_strchr(url16.CStr() + 5, '.')) != NULL)
  501. {
  502. RETURN_IF_ERROR(AddWord(handle, url16.CStr(), ranking));
  503. // attempt to index "hp" from "www.hp.co.uk", "yahoo" from "yahoo.com.au",
  504. // "yahoo" from "au.yahoo.com" and "maps", "google" from "maps.google.com"
  505. *dot = 0;
  506. if (!uni_str_eq(url16.CStr() + 5, "WWW") && !uni_str_eq(url16.CStr() + 5, "COM") &&
  507. (words_indexed == 1 || uni_strlen(url16.CStr() + 5) > 3))
  508. RETURN_IF_ERROR(AddWord(handle, url16.CStr() + 5, ranking));
  509. ++words_indexed;
  510. *dot = '.';
  511. url16.Delete(5, (int)(dot - url16.CStr() - 4));
  512. }
  513. if (url16[5] != 0 && !uni_str_eq(url16.CStr() + 5, "COM"))
  514. {
  515. RETURN_IF_ERROR(AddWord(handle, url16.CStr(), ranking));
  516. }
  517. return OpStatus::OK;
  518. }
  519. static OP_STATUS AppendWithoutCR(TempBuffer &buf, const uni_char *text)
  520. {
  521. const uni_char *pos;
  522. while ((pos = uni_strchr(text, '\r')) != 0)
  523. {
  524. // Replacing CR ('\r') with space as CR has been repurposed for "excerpt boundary"
  525. RETURN_IF_ERROR(buf.Append(text, pos-text));
  526. RETURN_IF_ERROR(buf.Append(UNI_L(" ")));
  527. text = pos+1;
  528. }
  529. return buf.Append(text);
  530. }
  531. OP_STATUS VisitedSearch::AddTextBlock(VisitedSearch::RecordHandle handle, const uni_char *text, float ranking, BOOL is_continuation)
  532. {
  533. if (handle->IsInvalid())
  534. return OpStatus::ERR;
  535. OP_ASSERT(handle->GetField("plaintext").GetSize() == 0); // operation on a closed handle!
  536. #ifdef _DEBUG // we are lucky now, but it can also crash
  537. if (handle->GetField("plaintext").GetSize() != 0) // if there would be a PreFlush..Commit between CloseRecord and here
  538. return OpStatus::OK; // so this cannot be tolerated
  539. #endif
  540. #if defined SEARCH_ENGINE_LOG && (SEARCH_ENGINE_LOG & SEARCH_ENGINE_LOG_VISITEDSEARCH)
  541. if (m_log != NULL)
  542. {
  543. m_log->Write(SearchEngineLog::Debug, "AddTextBlock", "%X %f", (INTPTR)handle, (double)ranking);
  544. m_log->Write(SearchEngineLog::Debug, "text block", uni_strlen(text), text);
  545. }
  546. #endif
  547. // only index the first MAX_DOC_WORDS from a document
  548. if (handle->m_word_count > MAX_DOC_WORDS)
  549. return OpStatus::OK;
  550. const uni_char* t = text;
  551. while (*text == '\r' || *text == '\n' || *text == ' ' || *text == '\t')
  552. ++text;
  553. if (text != t)
  554. is_continuation = FALSE;
  555. if (!is_continuation && handle->m_plaintext.Length() != 0)
  556. OpStatus::Ignore(handle->m_plaintext.Append(UNI_L("\n")));
  557. OpStatus::Ignore(AppendWithoutCR(handle->m_plaintext, text));
  558. return IndexTextBlock(handle, text, ranking);
  559. }
  560. static void RemoveHandle(TVector<FileWord *> &cache, VisitedSearch::RecordHandle handle)
  561. {
  562. int i, j;
  563. for (i = cache.GetCount() - 1; i >= 0; --i)
  564. {
  565. for (j = cache[i]->file_ids->GetCount() - 1; j >= 0; --j)
  566. {
  567. if (cache[i]->file_ids->Get(j).h == handle)
  568. cache[i]->file_ids->Delete(j);
  569. }
  570. if (cache[i]->file_ids->GetCount() == 0)
  571. cache.Delete(i);
  572. }
  573. }
  574. // Finds the record of the previous version of the document
  575. OP_STATUS VisitedSearch::FindLastIndex(UINT32 *prev, UINT16 *prev_idx, const char *url, RankIndex *current_index)
  576. {
  577. int i, ipos, ipos_end;
  578. char *tail_url;
  579. ipos = m_index.Find(current_index);
  580. OP_ASSERT(ipos < (int)m_index.GetCount() && m_index[ipos] == current_index);
  581. ipos_end = ipos + (int)m_index.GetCount();
  582. for (i = ipos; i < ipos_end; ++i)
  583. {
  584. RankIndex *index = m_index[i % m_index.GetCount()];
  585. if ((*prev = index->m_url.CaseSearch(url)) != 0)
  586. {
  587. RETURN_IF_ERROR(RankIndex::GetTail(&tail_url, *prev, index));
  588. int words_equal = ACT::WordsEqual(tail_url, url);
  589. OP_DELETEA(tail_url);
  590. if (words_equal == -1)
  591. {
  592. *prev_idx = index->m_id;
  593. break;
  594. }
  595. else {
  596. *prev = 0;
  597. }
  598. }
  599. }
  600. return OpStatus::OK;
  601. }
  602. OP_STATUS VisitedSearch::InsertHandle(VisitedSearch::RecordHandle handle)
  603. {
  604. int i;
  605. for (i = handle->m_word_list.GetCount() - 1; i >= 0; --i)
  606. {
  607. if (handle->m_word_list[i].word != NULL) // there was out of memory - ignore
  608. RETURN_IF_ERROR(Insert(m_cache, handle, handle->m_word_list[i].word, handle->m_word_list[i].rank));
  609. }
  610. handle->m_word_list.Clear();
  611. return OpStatus::OK;
  612. }
  613. OP_STATUS VisitedSearch::CompressText(VisitedSearch::RecordHandle handle)
  614. {
  615. if (handle->m_plaintext.Length() != 0)
  616. {
  617. UniCompressor uc;
  618. unsigned char *ctext;
  619. int csize;
  620. OP_STATUS err;
  621. RETURN_IF_ERROR(uc.InitCompDict());
  622. size_t len = handle->m_plaintext.Length() * 3 + 6;
  623. RETURN_OOM_IF_NULL(ctext = OP_NEWA(unsigned char, len));
  624. csize = uc.Compress(ctext, handle->m_plaintext.GetStorage());
  625. err = handle->GetField("plaintext").SetValue(ctext, csize);
  626. OP_DELETEA(ctext);
  627. RETURN_IF_ERROR(err);
  628. handle->m_plaintext.Clear();
  629. }
  630. return OpStatus::OK;
  631. }
  632. OP_STATUS VisitedSearch::CloseRecord(VisitedSearch::RecordHandle handle)
  633. {
  634. int i;
  635. UINT16 prev_idx = 0;
  636. UINT32 prev = 0;
  637. UINT16 hash, prev_hash;
  638. const char *url;
  639. OP_BOOLEAN err;
  640. #if defined SEARCH_ENGINE_LOG && (SEARCH_ENGINE_LOG & SEARCH_ENGINE_LOG_VISITEDSEARCH)
  641. if (m_log != NULL)
  642. m_log->Write(SearchEngineLog::Debug, "CloseRecord", "%X", (INTPTR)handle);
  643. #endif
  644. // ignore empty documents
  645. if (handle->m_word_count <= 0)
  646. {
  647. OP_ASSERT(m_pending.GetCount() > 0);
  648. m_pending.RemoveByItem(handle);
  649. OP_DELETE(handle);
  650. return OpStatus::OK;
  651. }
  652. if (!IsOpen() || handle->IsInvalid())
  653. {
  654. AbortRecord(handle);
  655. return OpStatus::ERR;
  656. }
  657. url = (const char *)handle->GetField("url").GetAddress();
  658. // finish preflushing if the URL being closed is being preflushed as well
  659. if ((m_flags & PreFlushing) != 0)
  660. {
  661. for (i = m_meta_pf.GetCount() - 1; i >= 0; --i)
  662. {
  663. if (ACT::WordsEqual(url, (const char *)m_meta_pf[i]->GetField("url").GetAddress()) == -1)
  664. {
  665. if ((err = PreFlush()) != OpBoolean::IS_TRUE)
  666. {
  667. AbortRecord(handle);
  668. return err;
  669. }
  670. break;
  671. }
  672. }
  673. }
  674. // find previous occurence of this URL
  675. if (OpStatus::IsError(err = FindLastIndex(&prev, &prev_idx, url, handle->m_index)))
  676. {
  677. OP_ASSERT(m_pending.GetCount() > 0);
  678. m_pending.RemoveByItem(handle);
  679. OP_DELETE(handle);
  680. return err;
  681. }
  682. // update chain of previous occurences
  683. if (prev != 0)
  684. {
  685. RETURN_IF_ERROR(handle->GetField("prev").SetValue(prev));
  686. RETURN_IF_ERROR(handle->GetField("prev_idx").SetValue(prev_idx));
  687. if (prev_idx == handle->m_index->m_id)
  688. {
  689. if (!handle->m_index->m_metadata.Read(&prev_hash, 2, ((OpFileLength)prev) * handle->m_index->m_metadata.GetBlockSize()))
  690. {
  691. AbortRecord(handle);
  692. return OpStatus::ERR;
  693. }
  694. handle->GetField("hash").GetValue(&hash);
  695. // ignore unchanged
  696. if (hash == prev_hash)
  697. {
  698. RemoveHandle(m_cache, handle);
  699. // nothing will get indexed except the time
  700. handle->m_word_count = 0;
  701. handle->m_word_list.Clear();
  702. handle->m_plaintext.Clear();
  703. }
  704. }
  705. }
  706. // insert words into caches
  707. if (OpStatus::IsError(err = InsertHandle(handle)))
  708. {
  709. AbortRecord(handle);
  710. return err;
  711. }
  712. // remove same URLs in cache
  713. for (i = m_meta.GetCount() - 1; i >= 0; --i)
  714. {
  715. RecordHandle meta = m_meta[i];
  716. if (ACT::WordsEqual(url, (const char *)meta->GetField("url").GetAddress()) == -1)
  717. {
  718. RemoveHandle(m_cache, meta);
  719. m_meta.Delete(i);
  720. }
  721. }
  722. // compress the plaintext
  723. OP_ASSERT(handle->GetField("plaintext").GetSize() == 0);
  724. if (OpStatus::IsError(err = CompressText(handle)))
  725. {
  726. AbortRecord(handle);
  727. return err;
  728. }
  729. if (OpStatus::IsError(m_meta.Add(handle)))
  730. {
  731. AbortRecord(handle);
  732. return OpStatus::ERR_NO_MEMORY;
  733. }
  734. if ((m_flags & (PreFlushing | PreFlushed | Flushed)) == 0 && m_meta.GetCount() == 1)
  735. PostMessage(MSG_VISITEDSEARCH_PREFLUSH, (MH_PARAM_1)this, 0, DELAY_MSG_PREFLUSH);
  736. OP_ASSERT(m_pending.GetCount() > 0);
  737. m_pending.RemoveByItem(handle);
  738. return OpStatus::OK;
  739. }
  740. void VisitedSearch::AbortRecord(VisitedSearch::RecordHandle handle)
  741. {
  742. RemoveHandle(m_cache, handle);
  743. OP_ASSERT(m_pending.GetCount() > 0);
  744. m_pending.RemoveByItem(handle);
  745. OP_DELETE(handle);
  746. }
  747. OP_STATUS VisitedSearch::AssociateThumbnail(const char *url, const void *picture, int size)
  748. {
  749. int i;
  750. ACT::WordID pos;
  751. char *tail_url;
  752. if (!IsOpen())
  753. return OpStatus::ERR;
  754. if ((m_flags & (PreFlushing | PreFlushed | Flushed)) != 0)
  755. {
  756. RETURN_IF_ERROR(Commit());
  757. }
  758. for (i = m_pending.GetCount() - 1; i >= 0; --i)
  759. {
  760. if (ACT::WordsEqual(url, (const char *)m_pending[i]->GetField("url").GetAddress()) == -1)
  761. return m_pending[i]->GetField("thumbnail").SetValue(picture, size);
  762. }
  763. for (i = m_meta.GetCount() - 1; i >= 0; --i)
  764. {
  765. if (ACT::WordsEqual(url, (const char *)m_meta[i]->GetField("url").GetAddress()) == -1)
  766. return m_meta[i]->GetField("thumbnail").SetValue(picture, size);
  767. }
  768. for (i = 0; (unsigned)i < m_index.GetCount(); ++i)
  769. {
  770. pos = m_index[i]->m_url.CaseSearch(url);
  771. RETURN_IF_ERROR(RankIndex::GetTail(&tail_url, pos, m_index[i]));
  772. if (ACT::WordsEqual(tail_url, url) != -1)
  773. pos = 0;
  774. OP_DELETEA(tail_url);
  775. if (pos != 0)
  776. {
  777. OP_STATUS err;
  778. BSCursor cursor(&m_index[i]->m_metadata);
  779. RETURN_IF_ERROR(RankIndex::SetupCursor(cursor));
  780. RETURN_IF_ERROR(cursor.Goto(pos));
  781. RETURN_IF_ERROR(cursor["thumbnail"].SetValue(picture, size));
  782. RETURN_IF_ERROR(m_index[i]->m_metadata.BeginTransaction());
  783. if (OpStatus::IsError(err = cursor.Flush()))
  784. OpStatus::Ignore(m_index[i]->m_metadata.Rollback());
  785. else if (OpStatus::IsError(err = m_index[i]->m_metadata.Commit()))
  786. OpStatus::Ignore(m_index[i]->m_metadata.Rollback());
  787. return err;
  788. }
  789. }
  790. return OpStatus::ERR_NO_SUCH_RESOURCE;
  791. }
  792. OP_STATUS VisitedSearch::AssociateFileName(const char *url, const uni_char *fname)
  793. {
  794. int i;
  795. ACT::WordID pos;
  796. char *tail_url;
  797. if (!IsOpen())
  798. return OpStatus::ERR;
  799. if ((m_flags & (PreFlushing | PreFlushed | Flushed)) != 0)
  800. {
  801. RETURN_IF_ERROR(Commit());
  802. }
  803. for (i = m_pending.GetCount() - 1; i >= 0; --i)
  804. {
  805. if (ACT::WordsEqual(url, (const char *)m_pending[i]->GetField("url").GetAddress()) == -1)
  806. return m_pending[i]->GetField("filename").SetStringValue(fname);
  807. }
  808. for (i = m_meta.GetCount() - 1; i >= 0; --i)
  809. {
  810. if (ACT::WordsEqual(url, (const char *)m_meta[i]->GetField("url").GetAddress()) == -1)
  811. return m_meta[i]->GetField("filename").SetStringValue(fname);
  812. }
  813. for (i = 0; (unsigned)i < m_index.GetCount(); ++i)
  814. {
  815. pos = m_index[i]->m_url.CaseSearch(url);
  816. RETURN_IF_ERROR(RankIndex::GetTail(&tail_url, pos, m_index[i]));
  817. if (ACT::WordsEqual(tail_url, url) != -1)
  818. pos = 0;
  819. OP_DELETEA(tail_url);
  820. if (pos != 0)
  821. {
  822. OP_STATUS err;
  823. BSCursor cursor(&m_index[i]->m_metadata);
  824. RETURN_IF_ERROR(RankIndex::SetupCursor(cursor));
  825. RETURN_IF_ERROR(cursor.Goto(pos));
  826. RETURN_IF_ERROR(cursor["filename"].SetStringValue(fname));
  827. RETURN_IF_ERROR(m_index[i]->m_metadata.BeginTransaction());
  828. if (OpStatus::IsError(err = cursor.Flush()))
  829. OpStatus::Ignore(m_index[i]->m_metadata.Rollback());
  830. else if (OpStatus::IsError(err = m_index[i]->m_metadata.Commit()))
  831. OpStatus::Ignore(m_index[i]->m_metadata.Rollback());
  832. return err;
  833. }
  834. }
  835. return OpStatus::ERR_NO_SUCH_RESOURCE;
  836. }
  837. /*****************************************************************************
  838. flush */
  839. void VisitedSearch::CancelPreFlushItem(int i)
  840. {
  841. RemoveHandle(m_preflush, m_meta_pf[i]);
  842. m_meta_pf.Delete(i);
  843. }
  844. OP_STATUS VisitedSearch::WriteMetadata(void)
  845. {
  846. OP_BOOLEAN err;
  847. int i, j;
  848. BSCursor previous;
  849. UINT32 prev;
  850. UINT16 prev_idx;
  851. UINT32 last_visited;
  852. #ifdef _DEBUG
  853. int prev_size;
  854. #endif
  855. #if defined SEARCH_ENGINE_LOG && (SEARCH_ENGINE_LOG & SEARCH_ENGINE_LOG_VISITEDSEARCH)
  856. if (m_log != NULL)
  857. m_log->Write(SearchEngineLog::Debug, "WriteMetadata", "");
  858. #endif
  859. RETURN_IF_ERROR(RankIndex::SetupCursor(previous));
  860. for (i = m_meta_pf.GetCount() - 1; i >= 0; --i)
  861. {
  862. RecordHandle meta = m_meta_pf[i];
  863. meta->GetField("prev").GetValue(&prev);
  864. if (prev != 0)
  865. {
  866. meta->GetField("prev_idx").GetValue(&prev_idx);
  867. j = 0;
  868. RankIndex *index = 0;
  869. while (j < (int)m_index.GetCount() && (index = m_index[j])->m_id != prev_idx)
  870. ++j;
  871. if (j >= (int)m_index.GetCount() || index->m_metadata.GetFileSize() / index->m_metadata.GetBlockSize() <= prev )
  872. {
  873. OP_ASSERT(0);
  874. CancelPreFlushItem(i);
  875. continue;
  876. }
  877. previous.SetStorage(&(index->m_metadata));
  878. #ifdef _DEBUG
  879. prev_size = index->m_metadata.DataLength(index->m_metadata.GetBlockSize() * ((OpFileLength)prev));
  880. #endif
  881. err = previous.Goto(prev);
  882. if (err == OpStatus::ERR_PARSING_FAILED)
  883. {
  884. OP_ASSERT(0);
  885. CancelPreFlushItem(i);
  886. continue;
  887. }
  888. else
  889. RETURN_IF_ERROR(err);
  890. if (meta->m_word_count == 0)
  891. {
  892. // update visited time and alldoc
  893. previous["visited"].GetValue(&last_visited);
  894. err = index->m_alldoc.Delete(IdTime(last_visited, prev));
  895. if (err == OpBoolean::IS_FALSE && !index->m_alldoc.Empty())
  896. err = OpStatus::OK;
  897. OP_ASSERT(err != OpStatus::OK);
  898. if (err == OpBoolean::IS_FALSE)
  899. err = OpStatus::ERR_NO_SUCH_RESOURCE;
  900. if (err != OpBoolean::IS_TRUE)
  901. return err;
  902. meta->GetField("visited").GetValue(&last_visited);
  903. RETURN_IF_ERROR(previous["visited"].SetValue(last_visited));
  904. RETURN_IF_ERROR(previous.Flush());
  905. #ifdef _DEBUG
  906. OP_ASSERT(previous.GetID() == prev);
  907. OP_ASSERT(index->m_metadata.DataLength(index->m_metadata.GetBlockSize() * ((OpFileLength)prev)) == prev_size);
  908. #endif
  909. RETURN_IF_ERROR(meta->m_index->m_alldoc.Insert(IdTime(last_visited, prev)));
  910. CancelPreFlushItem(i);
  911. continue;
  912. }
  913. else {
  914. // setup prev/next
  915. if (previous["filename"].GetSize() > 0)
  916. {
  917. // sparc?
  918. // RETURN_IF_ERROR(meta->GetField("filename").SetStringValue((const uni_char *)previous["filename"].GetAddress()));
  919. RETURN_IF_ERROR(meta->GetField("filename").SetValue(previous["filename"].GetAddress(), previous["filename"].GetSize()));
  920. }
  921. RETURN_IF_ERROR(meta->GetField("invalid").SetValue(0)); // *(const unsigned char *)previous["invalid"].GetAddress()
  922. RETURN_IF_ERROR(meta->Flush());
  923. meta->GetField("visited").GetValue(&last_visited);
  924. OP_ASSERT((UINT32)meta->GetID() != 0);
  925. RETURN_IF_ERROR(meta->m_index->m_alldoc.Insert(IdTime(last_visited, (UINT32)meta->GetID())));
  926. RETURN_IF_ERROR(previous["next_idx"].SetValue(meta->m_index->m_id));
  927. RETURN_IF_ERROR(previous["next"].SetValue(meta->GetID()));
  928. RETURN_IF_ERROR(meta->m_index->m_url.AddCaseWord((const char *)meta->GetField("url").GetAddress(),
  929. (ACT::WordID)(meta->GetID())));
  930. }
  931. RETURN_IF_ERROR(previous.Flush());
  932. #ifdef _DEBUG
  933. OP_ASSERT(previous.GetID() == prev);
  934. OP_ASSERT(index->m_metadata.DataLength(index->m_metadata.GetBlockSize() * ((OpFileLength)prev)) == prev_size);
  935. #endif
  936. }
  937. else {
  938. RETURN_IF_ERROR(meta->Flush());
  939. meta->GetField("visited").GetValue(&last_visited);
  940. OP_ASSERT((UINT32)meta->GetID() != 0);
  941. RETURN_IF_ERROR(meta->m_index->m_alldoc.Insert(IdTime(last_visited, (UINT32)meta->GetID())));
  942. RETURN_IF_ERROR(meta->m_index->m_url.AddCaseWord((const char *)meta->GetField("url").GetAddress(),
  943. (ACT::WordID)(meta->GetID())));
  944. }
  945. }
  946. return OpStatus::OK;
  947. }
  948. OP_BOOLEAN VisitedSearch::PreFlush(int max_ms)
  949. {
  950. int i;
  951. OP_STATUS err;
  952. UINT32 old_pos;
  953. double time_limit;
  954. unsigned wb_block_size;
  955. FileWord *preflush_item;
  956. if (!IsOpen())
  957. return OpStatus::ERR;
  958. if ((m_flags & PreFlushing) == 0 && m_meta.GetCount() == 0)
  959. {
  960. m_flags |= PreFlushed;
  961. m_flags &= ~PreFlushing;
  962. return OpBoolean::IS_TRUE;
  963. }
  964. #if defined SEARCH_ENGINE_LOG && (SEARCH_ENGINE_LOG & SEARCH_ENGINE_LOG_VISITEDSEARCH)
  965. if (m_log != NULL)
  966. m_log->Write(SearchEngineLog::Debug, "PreFlush", "(%i) %i", max_ms, m_pos);
  967. #endif
  968. time_limit = g_op_time_info->GetWallClockMS() + max_ms;
  969. for (i = 0; i < (int)m_meta.GetCount(); ++i)
  970. {
  971. RankIndex *index = m_meta[i]->m_index;
  972. if (!index->m_metadata.InTransaction())
  973. {
  974. RETURN_IF_ERROR(index->m_wordbag.BeginTransaction());
  975. RETURN_IF_ERROR(index->m_metadata.BeginTransaction());
  976. BOOL flUseNUR = (m_flags & UseNUR) != 0;
  977. index->m_act.SetNURFlush(flUseNUR);
  978. index->m_alldoc.SetNURFlush(flUseNUR);
  979. index->m_url.SetNURFlush(flUseNUR);
  980. }
  981. }
  982. // prepare caches
  983. if ((m_flags & PreFlushing) == 0)
  984. {
  985. m_preflush.TakeOver(m_cache);
  986. m_meta_pf.TakeOver(m_meta);
  987. m_flags |= PreFlushing;
  988. // metadata and document list
  989. if (OpStatus::IsError(err = WriteMetadata()))
  990. return AbortPreFlush(err);
  991. m_pos = m_preflush.GetCount();
  992. }
  993. if (max_ms > 0 && g_op_time_info->GetWallClockMS() >= time_limit)
  994. return OpBoolean::IS_FALSE;
  995. wb_block_size = m_index[0]->m_wordbag.GetBlockSize();
  996. // insert
  997. while (--m_pos >= 0)
  998. {
  999. TVector<RankId> rank_vec(&RankId::CompareId);
  1000. preflush_item = m_preflush[m_pos];
  1001. #ifdef _DEBUG
  1002. for (unsigned debi = 0; debi < preflush_item->file_ids->GetCount(); ++debi)
  1003. {
  1004. const uni_char *word = preflush_item->word;
  1005. const RecordHandleRec *handle = preflush_item->file_ids->Get(debi).h;
  1006. uni_char *str, *title = NULL;
  1007. OpString url;
  1008. UniCompressor uc;
  1009. unsigned len = uc.Length((const unsigned char *)handle->GetField("plaintext").GetAddress()) + 1;
  1010. str = OP_NEWA(uni_char, len);
  1011. if (str)
  1012. {
  1013. uc.Decompress(str, (const unsigned char *)handle->GetField("plaintext").GetAddress(), handle->GetField("plaintext").GetSize());
  1014. uni_strupr(str);
  1015. }
  1016. uni_char *upper = handle->GetField("title").CopyStringValue(&title);
  1017. if (upper)
  1018. uni_strupr(upper);
  1019. if (OpStatus::IsError(err = url.SetFromUTF8((const char *)handle->GetField("url").GetAddress())) || !str || !upper)
  1020. {
  1021. OP_DELETEA(title);
  1022. OP_DELETEA(str);
  1023. return AbortPreFlush(err);
  1024. }
  1025. url.MakeUpper();
  1026. // (const uni_char *)(preflush_item->file_ids->Get(debi).h->GetField("plaintext").GetAddress()), preflush_item->word
  1027. PhraseMatcher matcher;
  1028. if (uni_strnicmp(word, "site:", 5) == 0)
  1029. {
  1030. if (OpStatus::IsSuccess(matcher.Init(word+5, PhraseMatcher::NoPhrases)))
  1031. OP_ASSERT(matcher.Matches(url.CStr()));
  1032. }
  1033. else
  1034. {
  1035. if (OpStatus::IsSuccess(matcher.Init(word, PhraseMatcher::NoPhrases)))
  1036. OP_ASSERT(matcher.Matches(str) || matcher.Matches(title) || matcher.Matches(url.CStr()));
  1037. }
  1038. OP_DELETEA(title);
  1039. OP_DELETEA(str);
  1040. }
  1041. #endif
  1042. preflush_item->file_pos = preflush_item->index->m_act.Search(preflush_item->word);
  1043. // stopword
  1044. if (preflush_item->file_pos == (UINT32)-1)
  1045. continue;
  1046. OP_ASSERT(preflush_item->file_ids->GetCount() > 0);
  1047. if (OpStatus::IsError(err = rank_vec.Reserve(preflush_item->file_ids->GetCount())))
  1048. return AbortPreFlush(err);
  1049. for (i = preflush_item->file_ids->GetCount() - 1; i >= 0; --i)
  1050. {
  1051. OP_ASSERT((UINT32)preflush_item->file_ids->Get(i).h->GetID() != 0);
  1052. #ifdef _DEBUG
  1053. if (preflush_item->index->m_metadata.IsStartBlocksSupported())
  1054. {
  1055. OP_ASSERT(preflush_item->index->m_metadata.IsStartBlock(((OpFileLength)preflush_item->file_ids->Get(i).h->GetID()) * preflush_item->index->m_metadata.GetBlockSize()));
  1056. }
  1057. #endif
  1058. if (OpStatus::IsError(err = rank_vec.Add(RankId(preflush_item->file_ids->Get(i).rank, (UINT32)preflush_item->file_ids->Get(i).h->GetID()))))
  1059. return AbortPreFlush(err);
  1060. }
  1061. old_pos = preflush_item->file_pos;
  1062. if (preflush_item->index->m_doc_count > STOPWORD_DOC_COUNT && old_pos != 0 &&
  1063. preflush_item->index->m_wordbag.DataLength(old_pos * wb_block_size) / sizeof(RankId) > preflush_item->index->m_doc_count / 2)
  1064. {
  1065. if (!preflush_item->index->m_wordbag.Delete(old_pos * wb_block_size))
  1066. return AbortPreFlush(OpStatus::ERR_NO_DISK);
  1067. preflush_item->file_pos = (UINT32)(-1); // mark the stopword
  1068. rank_vec.Clear();
  1069. }
  1070. // add the file ids to m_wordbag here
  1071. else if ((preflush_item->file_pos = (UINT32)(preflush_item->index->m_wordbag.Append(rank_vec.Ptr(), rank_vec.GetCount() * sizeof(RankId),
  1072. old_pos * wb_block_size) / wb_block_size)) == 0)
  1073. return AbortPreFlush(OpStatus::ERR_NO_DISK);
  1074. OP_ASSERT(preflush_item->file_pos != 0);
  1075. // update ACT for new words or if the position changed
  1076. if (old_pos != preflush_item->file_pos)
  1077. {
  1078. err = preflush_item->index->m_act.AddWord(preflush_item->word, preflush_item->file_pos);
  1079. switch (err)
  1080. {
  1081. case OpBoolean::IS_FALSE:
  1082. case OpBoolean::IS_TRUE:
  1083. break;
  1084. case OpStatus::OK: // empty/invalid word
  1085. if (preflush_item->index->m_wordbag.Delete(preflush_item->file_pos))
  1086. break;
  1087. err = OpStatus::ERR_NO_DISK;
  1088. default:
  1089. return AbortPreFlush(err);
  1090. }
  1091. // update new data for this word in m_cache
  1092. i = m_cache.Search(preflush_item);
  1093. if (i < (int)m_cache.GetCount() && uni_strcmp(preflush_item->word, m_cache[i]->word) == 0)
  1094. m_cache[i]->file_pos = preflush_item->file_pos;
  1095. }
  1096. if (max_ms > 0 && g_op_time_info->GetWallClockMS() >= time_limit)
  1097. return OpBoolean::IS_FALSE;
  1098. }
  1099. for (i = 0; i < (int)m_index.GetCount(); ++i)
  1100. {
  1101. RankIndex *index = m_index[i];
  1102. if (index->m_metadata.InTransaction())
  1103. {
  1104. if ((err = index->m_act.Flush(BSCache::JournalAll)) != OpBoolean::IS_TRUE)
  1105. return AbortPreFlush(err);
  1106. if ((err = index->m_alldoc.Flush(BSCache::JournalAll)) != OpBoolean::IS_TRUE)
  1107. return AbortPreFlush(err);
  1108. if ((err = index->m_url.Flush(BSCache::JournalAll)) != OpBoolean::IS_TRUE)
  1109. return AbortPreFlush(err);
  1110. }
  1111. }
  1112. m_flags |= PreFlushed;
  1113. m_flags &= ~PreFlushing;
  1114. return OpBoolean::IS_TRUE;
  1115. }
  1116. // discard the data being written
  1117. OP_STATUS VisitedSearch::AbortPreFlush(OP_STATUS err)
  1118. {
  1119. int i;
  1120. OP_ASSERT(0); // this could normally happen only on out of memory or disk
  1121. #if defined SEARCH_ENGINE_LOG && (SEARCH_ENGINE_LOG & SEARCH_ENGINE_LOG_VISITEDSEARCH)
  1122. if (m_log != NULL)
  1123. m_log->Write(SearchEngineLog::Warning, "AbortPreFlush", "(%i)", err);
  1124. #endif
  1125. m_meta_pf.Clear();
  1126. for (i = 0; i < (int)m_index.GetCount(); ++i)
  1127. {
  1128. RankIndex *index = m_index[i];
  1129. if (index->m_metadata.InTransaction())
  1130. OpStatus::Ignore(index->Rollback());
  1131. }
  1132. m_preflush.Clear();
  1133. m_flags &= ~PreFlushing;
  1134. return err;
  1135. }
  1136. OP_STATUS VisitedSearch::Flush(int max_ms)
  1137. {
  1138. int i;
  1139. OP_STATUS err;
  1140. double time_limit;
  1141. if (!IsOpen())
  1142. return OpStatus::ERR;
  1143. #if defined SEARCH_ENGINE_LOG && (SEARCH_ENGINE_LOG & SEARCH_ENGINE_LOG_VISITEDSEARCH)
  1144. if (m_log != NULL)
  1145. m_log->Write(SearchEngineLog::Debug, "Flush", "(%i) %i", max_ms, m_index.GetCount());
  1146. #endif
  1147. time_limit = g_op_time_info->GetWallClockMS() + max_ms;
  1148. // call PreFlush if it wasn't called
  1149. if ((m_flags & PreFlushed) == 0 || (m_flags & PreFlushing) != 0)
  1150. {
  1151. m_flags |= UseNUR;
  1152. err = PreFlush(max_ms);
  1153. m_flags ^= UseNUR;
  1154. RETURN_IF_ERROR(err);
  1155. if (err == OpBoolean::IS_FALSE)
  1156. return err;
  1157. }
  1158. for (i = 0; i < (int)m_index.GetCount(); ++i)
  1159. {
  1160. RankIndex *index = m_index[i];
  1161. if (index->m_metadata.InTransaction())
  1162. {
  1163. if (index->m_alldoc.GetItemCount() > 0)
  1164. {
  1165. switch (err = index->m_alldoc.Flush(BSCache::ReleaseAll, (int)(time_limit - g_op_time_info->GetWallClockMS())))
  1166. {
  1167. case OpBoolean::IS_FALSE:
  1168. return OpBoolean::IS_FALSE;
  1169. case OpBoolean::IS_TRUE:
  1170. break;
  1171. default:
  1172. return AbortFlush(err);
  1173. }
  1174. }
  1175. if (index->m_act.GetItemCount() > 0)
  1176. {
  1177. // This closes the journal files
  1178. switch (err = index->m_act.Flush(BSCache::ReleaseAll, (int)(time_limit - g_op_time_info->GetWallClockMS())))
  1179. {
  1180. case OpBoolean::IS_FALSE:
  1181. return OpBoolean::IS_FALSE;
  1182. case OpBoolean::IS_TRUE:
  1183. break;
  1184. default:
  1185. return AbortFlush(err);
  1186. }
  1187. if (OpStatus::IsError(err = index->m_act.SaveStatus()))
  1188. return AbortFlush(err);
  1189. }
  1190. if (index->m_url.GetItemCount() > 0)
  1191. {
  1192. // This closes the journal files
  1193. switch (err = index->m_url.Flush(BSCache::ReleaseAll, (int)(time_limit - g_op_time_info->GetWallClockMS())))
  1194. {
  1195. case OpBoolean::IS_FALSE:
  1196. return OpBoolean::IS_FALSE;
  1197. case OpBoolean::IS_TRUE:
  1198. break;
  1199. default:
  1200. return AbortFlush(err);
  1201. }
  1202. }
  1203. }
  1204. }
  1205. m_preflush.Clear();
  1206. for (i = m_meta_pf.GetCount() - 1; i >= 0; --i)
  1207. ++(m_meta_pf[i]->m_index->m_doc_count);
  1208. m_meta_pf.Clear();
  1209. m_flags ^= PreFlushed;
  1210. m_flags |= Flushed;
  1211. return OpBoolean::IS_TRUE;
  1212. }
  1213. // discard the data being written
  1214. OP_STATUS VisitedSearch::AbortFlush(OP_STATUS err)
  1215. {
  1216. int i;
  1217. OP_ASSERT(0); // this could normally happen only on out of memory or disk
  1218. #if defined SEARCH_ENGINE_LOG && (SEARCH_ENGINE_LOG & SEARCH_ENGINE_LOG_VISITEDSEARCH)
  1219. if (m_log != NULL)
  1220. m_log->Write(SearchEngineLog::Warning, "AbortFlush", "(%i)", err);
  1221. #endif
  1222. m_meta_pf.Clear(); // Clear m_meta_pf without deleting the items
  1223. for (i = 0; i < (int)m_index.GetCount(); ++i)
  1224. {
  1225. RankIndex *index = m_index[i];
  1226. if (index->m_metadata.InTransaction())
  1227. OpStatus::Ignore(index->Rollback());
  1228. }
  1229. m_preflush.Clear();
  1230. m_flags &= ~PreFlushed;
  1231. return err;
  1232. }
  1233. OP_STATUS VisitedSearch::Commit(void)
  1234. {
  1235. int i;
  1236. OpFileLength subsize;
  1237. TVector<int> subdirs;
  1238. if (!IsOpen())
  1239. return OpStatus::ERR;
  1240. #if defined SEARCH_ENGINE_LOG && (SEARCH_ENGINE_LOG & SEARCH_ENGINE_LOG_VISITEDSEARCH)
  1241. if (m_log != NULL)
  1242. m_log->Write(SearchEngineLog::Debug, "Commit", "");
  1243. #endif
  1244. if ((m_flags & Flushed) == 0)
  1245. {
  1246. RETURN_IF_ERROR(Flush());
  1247. }
  1248. for (i = 0; i < (int)m_index.GetCount(); ++i)
  1249. {
  1250. RankIndex *index = m_index[i];
  1251. if (index->m_metadata.InTransaction())
  1252. {
  1253. RETURN_IF_ERROR(index->m_act.Commit());
  1254. RETURN_IF_ERROR(index->m_wordbag.Commit());
  1255. RETURN_IF_ERROR(index->m_alldoc.Commit());
  1256. RETURN_IF_ERROR(index->m_metadata.Commit());
  1257. RETURN_IF_ERROR(index->m_url.Commit());
  1258. }
  1259. }
  1260. m_flags ^= Flushed;
  1261. subsize = m_index[0]->Size();
  1262. if (subsize >= m_subindex_size)
  1263. {
  1264. OpString path;
  1265. RankIndex *r;
  1266. if (OpStatus::IsError(path.Set(m_index[0]->m_wordbag.GetFullName())))
  1267. return OpStatus::OK; // prefer to report a successfull data commit
  1268. path.Delete(path.Length() - 6 - (int)op_strlen(FNAME_WB)); // the main directory
  1269. RETURN_VALUE_IF_ERROR(subdirs.Reserve(m_index.GetCount()), OpStatus::OK);
  1270. for (i = m_index.GetCount() - 1; i >= 0; --i)
  1271. RETURN_VALUE_IF_ERROR(subdirs.Add(m_index[i]->m_id), OpStatus::OK);
  1272. RETURN_VALUE_IF_ERROR(subdirs.Sort(), OpStatus::OK);
  1273. if (subdirs[0] != 0)
  1274. i = 0;
  1275. else {
  1276. i = 1;
  1277. while (i < (int)subdirs.GetCount() && subdirs[i - 1] + 1 == subdirs[i])
  1278. ++i;
  1279. }
  1280. if ((r = OP_NEW(RankIndex, ())) == NULL)
  1281. return OpStatus::OK;
  1282. if (OpStatus::IsError(r->Open(path.CStr(), i)))
  1283. OP_DELETE(r);
  1284. else if (OpStatus::IsError(m_index.Insert(0, r)))
  1285. {
  1286. r->Close();
  1287. OP_DELETE(r);
  1288. }
  1289. }
  1290. CheckMaxSize_RemoveOldIndexes();
  1291. return OpStatus::OK;
  1292. }
  1293. /*****************************************************************************
  1294. insert utility */
  1295. // cache is m_word_cache and m_backup_cache if Flush is in progress (PreFlushing is set)
  1296. // word must already be in uppercase
  1297. OP_STATUS VisitedSearch::Insert(TVector<FileWord *> &cache, RecordHandle h, const uni_char *word, float rank)
  1298. {
  1299. int i;
  1300. FileWord *w, fw;
  1301. const uni_char **srch = &word;;
  1302. fw.word = const_cast<uni_char*>(word);
  1303. i = cache.Search(&fw);
  1304. fw.word = NULL; // Avoid OP_DELETE
  1305. if (i >= (int)cache.GetCount() || FileWord::LessThan(&srch, &(cache[i]))) // not found
  1306. {
  1307. RETURN_OOM_IF_NULL(w = FileWord::Create(word, rank, h));
  1308. OP_STATUS err;
  1309. if (OpStatus::IsError(err = cache.Insert(i, w)))
  1310. {
  1311. OP_DELETE(w);
  1312. return err;
  1313. }
  1314. }
  1315. else {
  1316. RETURN_IF_ERROR(cache[i]->Add(rank, h));
  1317. }
  1318. return OpStatus::OK;
  1319. }
  1320. /*****************************************************************************
  1321. search */
  1322. VisitedSearch::Result::Result(void)
  1323. {
  1324. url = NULL;
  1325. title = NULL;
  1326. thumbnail = NULL;
  1327. thumbnail_size = 0;
  1328. filename = NULL;
  1329. compressed_plaintext = NULL;
  1330. compressed_plaintext_size = 0;
  1331. plaintext = NULL;
  1332. visited = 0;
  1333. ranking = 0;
  1334. id = (UINT32)(-1);
  1335. invalid = FALSE;
  1336. prev_idx = 0;
  1337. prev = 0;
  1338. next_idx = 0;
  1339. next = 0;
  1340. }
  1341. static char *op_ndup(const char *s)
  1342. {
  1343. char *dup;
  1344. size_t len = op_strlen(s) + 1;
  1345. if ((dup = OP_NEWA(char, len)) == NULL)
  1346. return NULL;
  1347. op_memcpy(dup, s, len);
  1348. return dup;
  1349. }
  1350. static uni_char *uni_ndup(const uni_char *s)
  1351. {
  1352. uni_char *dup;
  1353. size_t len = uni_strlen(s) + 1;
  1354. if ((dup = OP_NEWA(uni_char, len)) == NULL)
  1355. return NULL;
  1356. op_memcpy(dup, s, len << 1);
  1357. return dup;
  1358. }
  1359. OP_STATUS VisitedSearch::Result::Assign(void *dst_, const void *src_)
  1360. {
  1361. VisitedSearch::Result *dst = static_cast<VisitedSearch::Result *>(dst_);
  1362. const VisitedSearch::Result *src = static_cast<const VisitedSearch::Result *>(src_);
  1363. dst->url = NULL;
  1364. if (src->url != NULL)
  1365. RETURN_OOM_IF_NULL(dst->url = op_ndup(src->url));
  1366. dst->title = NULL;
  1367. if (src->title != NULL &&
  1368. (dst->title = uni_ndup(src->title)) == NULL)
  1369. {
  1370. DeleteResult(dst);
  1371. return OpStatus::ERR_NO_MEMORY;
  1372. }
  1373. dst->thumbnail = NULL;
  1374. dst->thumbnail_size = src->thumbnail_size;
  1375. if (src->thumbnail != NULL)
  1376. {
  1377. if ((dst->thumbnail = OP_NEWA(unsigned char, src->thumbnail_size)) == NULL)
  1378. {
  1379. DeleteResult(dst);
  1380. return OpStatus::ERR_NO_MEMORY;
  1381. }
  1382. op_memcpy(dst->thumbnail, src->thumbnail, src->thumbnail_size);
  1383. }
  1384. dst->filename = NULL;
  1385. if (src->filename != NULL &&
  1386. (dst->filename = uni_ndup(src->filename)) == NULL)
  1387. {
  1388. DeleteResult(dst);
  1389. return OpStatus::ERR_NO_MEMORY;
  1390. }
  1391. dst->compressed_plaintext = NULL;
  1392. dst->compressed_plaintext_size = src->compressed_plaintext_size;
  1393. if (src->compressed_plaintext != NULL)
  1394. {
  1395. if ((dst->compressed_plaintext = OP_NEWA(unsigned char, src->compressed_plaintext_size)) == NULL)
  1396. {
  1397. DeleteResult(dst);
  1398. return OpStatus::ERR_NO_MEMORY;
  1399. }
  1400. op_memcpy(dst->compressed_plaintext, src->compressed_plaintext, src->compressed_plaintext_size);
  1401. }
  1402. dst->plaintext = NULL;
  1403. if (src->plaintext != NULL &&
  1404. (dst->plaintext = uni_ndup(src->plaintext)) == NULL)
  1405. {
  1406. DeleteResult(dst);
  1407. return OpStatus::ERR_NO_MEMORY;
  1408. }
  1409. dst->visited = src->visited;
  1410. dst->ranking = src->ranking;
  1411. dst->id = src->id;
  1412. dst->invalid = src->invalid;
  1413. dst->prev_idx = src->prev_idx;
  1414. dst->prev = src->prev;
  1415. dst->next_idx = src->next_idx;
  1416. dst->next = src->next;
  1417. return OpStatus::OK;
  1418. }
  1419. OP_STATUS VisitedSearch::Result::SetCompressedPlaintext(const unsigned char *buf, int size)
  1420. {
  1421. compressed_plaintext = NULL;
  1422. compressed_plaintext_size = size;
  1423. if (size > 0)
  1424. {
  1425. RETURN_OOM_IF_NULL(compressed_plaintext = OP_NEWA(unsigned char, size));
  1426. op_memcpy(compressed_plaintext, buf, size);
  1427. }
  1428. return OpStatus::OK;
  1429. }
  1430. uni_char *VisitedSearch::Result::GetPlaintext() const
  1431. {
  1432. if (plaintext || !compressed_plaintext)
  1433. return plaintext;
  1434. UniCompressor uc;
  1435. unsigned len = uc.Length(compressed_plaintext) + 1;
  1436. plaintext = OP_NEWA(uni_char, len);
  1437. if (!plaintext)
  1438. return NULL;
  1439. if (uc.Decompress(plaintext, compressed_plaintext, compressed_plaintext_size) == 0)
  1440. {
  1441. OP_ASSERT(0); // error in compressed data?
  1442. OP_DELETEA(plaintext);
  1443. plaintext = NULL;
  1444. }
  1445. OP_DELETEA(compressed_plaintext);
  1446. compressed_plaintext = NULL;
  1447. compressed_plaintext_size = 0;
  1448. return plaintext;
  1449. }
  1450. OP_STATUS VisitedSearch::Result::ReadResult(VisitedSearch::Result &res, BlockStorage *metadata)
  1451. {
  1452. BSCursor c(metadata);
  1453. RETURN_IF_ERROR(RankIndex::SetupCursor(c));
  1454. RETURN_IF_ERROR(c.Goto(res.id));
  1455. if (c["url"].CopyStringValue(&(res.url)) == NULL)
  1456. {
  1457. OP_ASSERT(c["url"].GetSize() > 0);
  1458. return OpStatus::ERR_NO_MEMORY;
  1459. }
  1460. res.title = NULL;
  1461. if (c["title"].GetSize() > 0)
  1462. RETURN_OOM_IF_NULL(c["title"].CopyStringValue(&(res.title)));
  1463. res.filename = NULL;
  1464. if (c["filename"].GetSize() > 0)
  1465. RETURN_OOM_IF_NULL(c["filename"].CopyStringValue(&(res.filename)));
  1466. res.compressed_plaintext = NULL;
  1467. res.compressed_plaintext_size = 0;
  1468. res.plaintext = NULL;
  1469. if (c["plaintext"].GetSize() > 0)
  1470. {
  1471. RETURN_IF_ERROR(res.SetCompressedPlaintext((const unsigned char *)c["plaintext"].GetAddress(), c["plaintext"].GetSize()));
  1472. }
  1473. res.thumbnail = NULL;
  1474. res.thumbnail_size = 0;
  1475. if (c["thumbnail"].GetSize() > 0)
  1476. {
  1477. res.thumbnail_size = c["thumbnail"].GetSize();
  1478. RETURN_OOM_IF_NULL(res.thumbnail = OP_NEWA(unsigned char, res.thumbnail_size));
  1479. c["thumbnail"].GetValue(res.thumbnail, res.thumbnail_size);
  1480. }
  1481. c["visited"].GetValue(&(res.visited));
  1482. c["invalid"].GetValue(&(res.invalid));
  1483. c["prev_idx"].GetValue(&(res.prev_idx));
  1484. c["prev"].GetValue(&(res.prev));
  1485. c["next_idx"].GetValue(&(res.next_idx));
  1486. c["next"].GetValue(&(res.next));
  1487. return OpStatus::OK;
  1488. }
  1489. BOOL VisitedSearch::Result::Later(const void *left_, const void *right_)
  1490. {
  1491. const VisitedSearch::Result *left = static_cast<const VisitedSearch::Result *>(left_);
  1492. const VisitedSearch::Result *right = static_cast<const VisitedSearch::Result *>(right_);
  1493. if (left->visited == right->visited)
  1494. {
  1495. if (left->id == (UINT32)-1 ||
  1496. right->id == (UINT32)-1)
  1497. return op_strcmp(left->url, right->url) != 0;
  1498. return left->id > right->id;
  1499. }
  1500. return left->visited > right->visited;
  1501. }
  1502. BOOL VisitedSearch::Result::CompareId(const void *left_, const void *right_)
  1503. {
  1504. const VisitedSearch::Result *left = static_cast<const VisitedSearch::Result *>(left_);
  1505. const VisitedSearch::Result *right = static_cast<const VisitedSearch::Result *>(right_);
  1506. return left->id > right->id;
  1507. }
  1508. void VisitedSearch::Result::DeleteResult(void *item_) // fields only get deleted when Result is destructed from the internal Vector
  1509. {
  1510. VisitedSearch::Result *item = static_cast<VisitedSearch::Result *>(item_);
  1511. if (item->url != NULL)
  1512. {
  1513. OP_DELETEA(item->url);
  1514. item->url = NULL;
  1515. }
  1516. if (item->title != NULL)
  1517. {
  1518. OP_DELETEA(item->title);
  1519. item->title = NULL;
  1520. }
  1521. if (item->thumbnail != NULL)
  1522. {
  1523. OP_DELETEA(item->thumbnail);
  1524. item->thumbnail = NULL;
  1525. }
  1526. if (item->filename != NULL)
  1527. {
  1528. OP_DELETEA(item->filename);
  1529. item->filename = NULL;
  1530. }
  1531. if (item->plaintext != NULL)
  1532. {
  1533. OP_DELETEA(item->plaintext);
  1534. item->plaintext = NULL;
  1535. }
  1536. if (item->compressed_plaintext != NULL)
  1537. {
  1538. OP_DELETEA(item->compressed_plaintext);
  1539. item->compressed_plaintext = NULL;
  1540. }
  1541. }
  1542. #ifdef ESTIMATE_MEMORY_USED_AVAILABLE
  1543. size_t VisitedSearch::Result::EstimateMemoryUsed(const void *item_)
  1544. {
  1545. const VisitedSearch::Result *item = reinterpret_cast<const VisitedSearch::Result *>(item_);
  1546. size_t sum = 0;
  1547. if (item->url)
  1548. sum += (op_strlen(item->url)+1)*sizeof(char) + 2*sizeof(size_t);
  1549. if (item->title)
  1550. sum += (uni_strlen(item->title)+1)*sizeof(uni_char) + 2*sizeof(size_t);
  1551. if (item->thumbnail)
  1552. sum += item->thumbnail_size*sizeof(unsigned char) + 2*sizeof(size_t);
  1553. if (item->filename != NULL)
  1554. sum += (uni_strlen(item->filename)+1)*sizeof(uni_char) + 2*sizeof(size_t);
  1555. if (item->compressed_plaintext != NULL)
  1556. sum += item->compressed_plaintext_size*sizeof(unsigned char) + 2*sizeof(size_t);
  1557. if (item->plaintext != NULL)
  1558. sum += (uni_strlen(item->plaintext)+1)*sizeof(uni_char) + 2*sizeof(size_t);
  1559. return sum +
  1560. sizeof(item->url) +
  1561. sizeof(item->title) +
  1562. sizeof(item->thumbnail) +
  1563. sizeof(item->thumbnail_size) +
  1564. sizeof(item->filename) +
  1565. sizeof(item->compressed_plaintext) +
  1566. sizeof(item->compressed_plaintext_size) +
  1567. sizeof(item->plaintext) +
  1568. sizeof(item->visited) +
  1569. sizeof(item->ranking) +
  1570. sizeof(item->id) +
  1571. sizeof(item->invalid) +
  1572. sizeof(item->prev_idx) +
  1573. sizeof(item->prev) +
  1574. sizeof(item->next_idx) +
  1575. sizeof(item->next);
  1576. }
  1577. #endif
  1578. SearchIterator<VisitedSearch::Result> *VisitedSearch::Search(const uni_char *text, Sort sort_by, int phrase_flags)
  1579. {
  1580. QueryIteratorBase *tmp_it;
  1581. AllDocIterator *ad_it;
  1582. TVector<SearchIterator<VisitedSearch::Result> *> sub_results(&PtrDescriptor<SearchIterator<VisitedSearch::Result> >::Destruct);
  1583. MultiOrIterator *mo;
  1584. SearchIterator<VisitedSearch::Result> *result = NULL, *tmp_result;
  1585. WordSegmenter msgtok;
  1586. const uni_char *s_tmp;
  1587. TVector<uni_char *> *words;
  1588. int i, j;
  1589. UINT32 idx;
  1590. CacheIterator *cit;
  1591. if (!IsOpen())
  1592. return NULL;
  1593. if ((m_flags & (PreFlushing /*| PreFlushed | Flushed*/)) != 0)
  1594. {
  1595. switch (Commit())
  1596. {
  1597. case OpStatus::OK:
  1598. break;
  1599. case OpStatus::ERR_NO_DISK:
  1600. AbortFlush();
  1601. break;
  1602. default:
  1603. OP_ASSERT(0); // this is not supposed to happen; may be out of memory?
  1604. return NULL;
  1605. }
  1606. }
  1607. RETURN_VALUE_IF_ERROR(sub_results.Reserve(m_index.GetCount() + (m_cache.GetCount() > 0)), NULL);
  1608. if (uni_strni_eq_upper(text, "SITE:", 5) && op_isalpha(text[5]))
  1609. s_tmp = text;
  1610. else if ((s_tmp = uni_stristr(text, " SITE:")) != NULL && op_isalpha(s_tmp[6]))
  1611. ++s_tmp;
  1612. else
  1613. s_tmp = NULL;
  1614. OpString querytext;
  1615. RETURN_VALUE_IF_ERROR(querytext.Set(text), NULL);
  1616. if (s_tmp != NULL)
  1617. {
  1618. OpString sitetext;
  1619. const uni_char *sitestart, *siteend;
  1620. uni_char *sitedup;
  1621. sitestart = querytext.CStr() + (s_tmp - text);
  1622. do {
  1623. siteend = sitestart + 5;
  1624. while (op_isalpha(*siteend) || *siteend == '.')
  1625. ++siteend;
  1626. if ((s_tmp = uni_stristr(siteend, " SITE:")) != NULL && op_isalpha(s_tmp[6]))
  1627. {
  1628. ++s_tmp;
  1629. querytext.Delete((int)(sitestart - querytext.CStr()), (int)(siteend - sitestart));
  1630. sitestart = uni_stristr(querytext.CStr(), " SITE:") + 1;
  1631. }
  1632. else
  1633. s_tmp = NULL;
  1634. } while (s_tmp != NULL);
  1635. RETURN_VALUE_IF_ERROR(sitetext.Set(sitestart, (int)(siteend - sitestart)), NULL);
  1636. querytext.Delete((int)(sitestart - querytext.CStr()), (int)(siteend - sitestart));
  1637. RETURN_VALUE_IF_ERROR(msgtok.Set(querytext), NULL);
  1638. if ((words = msgtok.Parse()) == NULL)
  1639. return NULL;
  1640. if ((sitedup = uni_ndup(sitetext.CStr())) == NULL)
  1641. {
  1642. OP_DELETE(words);
  1643. return NULL;
  1644. }
  1645. if (OpStatus::IsError(words->Add(sitedup)))
  1646. {
  1647. OP_DELETEA(sitedup);
  1648. OP_DELETE(words);
  1649. return NULL;
  1650. }
  1651. }
  1652. else {
  1653. RETURN_VALUE_IF_ERROR(msgtok.Set(text), NULL);
  1654. if ((words = msgtok.Parse()) == NULL)
  1655. return NULL;
  1656. }
  1657. if (sort_by == Autocomplete)
  1658. {
  1659. if (words->GetCount() == 0)
  1660. {
  1661. OP_DELETE(words);
  1662. return OP_NEW(EmptyIterator<VisitedSearch::Result>, ());
  1663. }
  1664. sort_by = RankSort;
  1665. }
  1666. // return all documents from all indexes
  1667. if (words->GetCount() == 0)
  1668. {
  1669. for (i = m_index.GetCount() - 1; i >= 0; --i)
  1670. {
  1671. if ((ad_it = OP_NEW(AllDocIterator, (m_index[i]))) == NULL)
  1672. {
  1673. OP_DELETE(words);
  1674. return NULL;
  1675. }
  1676. if (OpStatus::IsError(ad_it->Init()) ||
  1677. OpStatus::IsError(sub_results.Add(ad_it)))
  1678. {
  1679. OP_DELETE(ad_it);
  1680. OP_DELETE(words);
  1681. return NULL;
  1682. }
  1683. }
  1684. }
  1685. else {
  1686. for (i = m_index.GetCount() - 1; i >= 0; --i)
  1687. {
  1688. RankIndex *index = m_index[i];
  1689. if (sort_by == RankSort)
  1690. tmp_it = OP_NEW(RankIterator, (index));
  1691. else
  1692. tmp_it = OP_NEW(TimeIterator, (index));
  1693. if (tmp_it == NULL)
  1694. {
  1695. OP_DELETE(words);
  1696. return NULL;
  1697. }
  1698. for (j = words->GetCount() - 1; j >= 0; --j)
  1699. {
  1700. idx = index->m_act.Search(words->Get(j));
  1701. // not found
  1702. if (idx == 0)
  1703. break;
  1704. if (idx == (UINT32)-1)
  1705. continue;
  1706. if (OpStatus::IsError(tmp_it->AddWord(idx)))
  1707. {
  1708. OP_DELETE(tmp_it);
  1709. OP_DELETE(words);
  1710. return NULL;
  1711. }
  1712. }
  1713. if (j >= 0)
  1714. {
  1715. OP_DELETE(tmp_it);
  1716. continue;
  1717. }
  1718. if (OpStatus::IsError(tmp_it->Init()) ||
  1719. OpStatus::IsError(sub_results.Add(tmp_it)))
  1720. {
  1721. OP_DELETE(tmp_it);
  1722. OP_DELETE(words);
  1723. return NULL;
  1724. }
  1725. }
  1726. }
  1727. if (m_cache.GetCount() > 0)
  1728. {
  1729. if ((cit = OP_NEW(CacheIterator, (sort_by == RankSort && words->GetCount() > 0 ? &DefDescriptor<VisitedSearch::Result>::Compare : &VisitedSearch::Result::Later))) == NULL)
  1730. {
  1731. OP_DELETE(words);
  1732. return NULL;
  1733. }
  1734. for (i = (int)words->GetCount() - 1; i >= 0; --i)
  1735. uni_strupr(words->Get(i));
  1736. if (OpStatus::IsError(cit->Init(m_cache, words)))
  1737. {
  1738. OP_DELETE(words);
  1739. OP_DELETE(cit);
  1740. return NULL;
  1741. }
  1742. }
  1743. else
  1744. cit = NULL;
  1745. OP_DELETE(words);
  1746. // nothing found
  1747. if (sub_results.GetCount() == 0)
  1748. {
  1749. if (cit == NULL)
  1750. return OP_NEW(EmptyIterator<VisitedSearch::Result>, ());
  1751. tmp_result = cit;
  1752. }
  1753. else
  1754. {
  1755. if (sub_results.GetCount() == 1 && cit == NULL)
  1756. {
  1757. tmp_result = sub_results.Remove(0);
  1758. }
  1759. else
  1760. {
  1761. if (cit != NULL)
  1762. RETURN_VALUE_IF_ERROR(sub_results.Add(cit), NULL);
  1763. if ((mo = OP_NEW(MultiOrIterator, ())) == NULL)
  1764. return NULL;
  1765. if (sort_by == RankSort)
  1766. mo->Set(sub_results, &DefDescriptor<VisitedSearch::Result>::Compare);
  1767. else
  1768. mo->Set(sub_results, &VisitedSearch::Result::Later);
  1769. tmp_result = mo;
  1770. }
  1771. }
  1772. #ifdef SEARCH_ENGINE_PHRASESEARCH
  1773. if ((phrase_flags & PhraseMatcher::AllPhrases) != 0)
  1774. {
  1775. PhraseFilter<VisitedSearch::Result> *phrase_filter = OP_NEW(PhraseFilter<VisitedSearch::Result>, (querytext.CStr(), m_doc_source, phrase_flags));
  1776. if(phrase_filter)
  1777. {
  1778. result = OP_NEW(FilterIterator<VisitedSearch::Result>, (tmp_result, phrase_filter));
  1779. if (result == NULL)
  1780. {
  1781. OP_DELETE(phrase_filter);
  1782. OP_DELETE(tmp_result);
  1783. }
  1784. }
  1785. }
  1786. else
  1787. result = tmp_result;
  1788. #else
  1789. result = tmp_result;
  1790. #endif
  1791. return result;
  1792. }
  1793. SearchIterator<VisitedSearch::Result> *VisitedSearch::FastPrefixSearch(const uni_char *text, int phrase_flags)
  1794. {
  1795. WordSegmenter ws;
  1796. TVector<uni_char *> *parsed_text;
  1797. BOOL last_is_prefix, prefix_search = TRUE;
  1798. ChainIterator *it;
  1799. CacheIterator *cit = NULL;
  1800. SearchIterator<VisitedSearch::Result> *result = NULL;
  1801. int i;
  1802. RETURN_VALUE_IF_ERROR(ws.Set(text), NULL);
  1803. if ((parsed_text = ws.Parse(&last_is_prefix)) == NULL)
  1804. return NULL;
  1805. if (!last_is_prefix)
  1806. prefix_search = FALSE;
  1807. for (i = (int)parsed_text->GetCount() - 1; i >= 0; --i)
  1808. uni_strupr(parsed_text->Get(i));
  1809. if (m_cache.GetCount() > 0 && parsed_text->GetCount() > 0)
  1810. {
  1811. if ((cit = OP_NEW(CacheIterator, (&VisitedSearch::Result::Later))) == NULL)
  1812. {
  1813. OP_DELETE(parsed_text);
  1814. return NULL;
  1815. }
  1816. if (OpStatus::IsError(cit->Init(m_cache, parsed_text, prefix_search)))
  1817. {
  1818. OP_DELETE(parsed_text);
  1819. OP_DELETE(cit);
  1820. return NULL;
  1821. }
  1822. if (cit->End())
  1823. {
  1824. OP_DELETE(cit);
  1825. cit = NULL;
  1826. }
  1827. }
  1828. if ((it = OP_NEW(ChainIterator, ())) == NULL)
  1829. {
  1830. OP_DELETE(parsed_text);
  1831. return NULL;
  1832. }
  1833. if (OpStatus::IsError(it->Init(*parsed_text, m_index, cit, prefix_search)))
  1834. {
  1835. OP_DELETE(parsed_text);
  1836. OP_DELETE(it);
  1837. return NULL;
  1838. }
  1839. OP_DELETE(parsed_text);
  1840. #ifdef SEARCH_ENGINE_PHRASESEARCH
  1841. if ((phrase_flags & PhraseMatcher::AllPhrases) != 0)
  1842. {
  1843. PhraseFilter<VisitedSearch::Result> *phrase_filter = OP_NEW(PhraseFilter<VisitedSearch::Result>, (text, m_doc_source, phrase_flags | PhraseMatcher::PrefixSearch));
  1844. if(phrase_filter)
  1845. {
  1846. result = OP_NEW(FilterIterator<VisitedSearch::Result>, (it, phrase_filter));
  1847. if (result == NULL)
  1848. {
  1849. OP_DELETE(phrase_filter);
  1850. OP_DELETE(it);
  1851. }
  1852. }
  1853. }
  1854. else
  1855. result = it;
  1856. #else
  1857. result = it;
  1858. #endif
  1859. return result;
  1860. }
  1861. OP_STATUS VisitedSearch::InvalidateResult(const Result &row)
  1862. {
  1863. unsigned i;
  1864. OP_BOOLEAN found;
  1865. IdTime tst;
  1866. if (!IsOpen())
  1867. return OpStatus::ERR;
  1868. i = 0;
  1869. while (i < m_index.GetCount())
  1870. {
  1871. tst.data[IDTIME_ID] = row.id;
  1872. tst.data[IDTIME_VISITED] = (UINT32)row.visited;
  1873. RETURN_IF_ERROR(found = m_index[i]->m_alldoc.Search(tst));
  1874. if (found == OpBoolean::IS_TRUE)
  1875. break;
  1876. ++i;
  1877. }
  1878. if (i >= m_index.GetCount())
  1879. return OpStatus::OK;
  1880. // transaction is not necessary, but progressing transaction is not broken
  1881. // return m_index[i]->m_metadata.Update(&c_true, 6, 1, (OpFileLength)(row.id) * m_index[i]->m_metadata.GetBlockSize()) ? OpStatus::OK : OpStatus::ERR_NO_DISK;
  1882. return WipeData(row.id, i);
  1883. }
  1884. OP_STATUS VisitedSearch::InvalidateUrl(const uni_char *url)
  1885. {
  1886. OpString8 utf8_str;
  1887. RETURN_IF_ERROR(utf8_str.SetUTF8FromUTF16(url));
  1888. return InvalidateUrl(utf8_str.CStr());
  1889. }
  1890. OP_STATUS VisitedSearch::InvalidateUrl(const char *url)
  1891. {
  1892. int i;
  1893. ACT::WordID pos;
  1894. char *tail_url;
  1895. if (!IsOpen())
  1896. return OpStatus::ERR;
  1897. if ((m_flags & (PreFlushing | PreFlushed | Flushed)) != 0)
  1898. {
  1899. RETURN_IF_ERROR(Commit());
  1900. }
  1901. for (i = 0; (unsigned)i < m_index.GetCount(); ++i)
  1902. {
  1903. RankIndex *index = m_index[i];
  1904. pos = index->m_url.CaseSearch(url);
  1905. RETURN_IF_ERROR(RankIndex::GetTail(&tail_url, pos, index));
  1906. if (ACT::WordsEqual(tail_url, url) != -1)
  1907. pos = 0;
  1908. OP_DELETEA(tail_url);
  1909. if (pos != 0)
  1910. RETURN_IF_ERROR(WipeData(pos, i));
  1911. }
  1912. return OpStatus::OK;
  1913. }
  1914. CHECK_RESULT(static OP_STATUS WipeCursor(BSCursor &cursor));
  1915. static OP_STATUS WipeCursor(BSCursor &cursor)
  1916. {
  1917. int uc_len;
  1918. UniCompressor uc;
  1919. unsigned char nothing[8]; /* ARRAY OK 2010-09-24 roarl */
  1920. uc_len = (int)uc.Compress(nothing, UNI_L(" "));
  1921. OP_ASSERT(uc_len < (int)sizeof(nothing));
  1922. RETURN_IF_ERROR(cursor["invalid"].SetValue(1));
  1923. RETURN_IF_ERROR(cursor["hash"].SetValue(0));
  1924. RETURN_IF_ERROR(cursor["next"].SetValue(0));
  1925. RETURN_IF_ERROR(cursor["next_idx"].SetValue(0));
  1926. RETURN_IF_ERROR(cursor["prev"].SetValue(0));
  1927. RETURN_IF_ERROR(cursor["prev_idx"].SetValue(0));
  1928. op_memset((char *)cursor["title"].GetAddress(), 0, cursor["title"].GetSize());
  1929. op_memset((char *)cursor["plaintext"].GetAddress(), 0, cursor["plaintext"].GetSize());
  1930. op_memset((char *)cursor["url"].GetAddress(), 0, cursor["url"].GetSize());
  1931. if (cursor["plaintext"].GetSize() > uc_len)
  1932. op_memcpy((unsigned char *)cursor["plaintext"].GetAddress(), nothing, uc_len);
  1933. return cursor.Flush();
  1934. }
  1935. OP_STATUS VisitedSearch::WipeData(BSCursor::RowID id, unsigned short r_index)
  1936. {
  1937. BSCursor cursor(&m_index[r_index]->m_metadata);
  1938. BSCursor::RowID next, prev;
  1939. unsigned short next_idx, prev_idx;
  1940. RETURN_IF_ERROR(RankIndex::SetupCursor(cursor));
  1941. RETURN_IF_ERROR(cursor.Goto(id));
  1942. cursor["next"].GetValue(&next);
  1943. cursor["next_idx"].GetValue(&next_idx);
  1944. cursor["prev"].GetValue(&prev);
  1945. cursor["prev_idx"].GetValue(&prev_idx);
  1946. RETURN_IF_ERROR(WipeCursor(cursor));
  1947. while (prev != 0 && prev_idx == r_index)
  1948. {
  1949. BSCursor bc(&m_index[r_index]->m_metadata);
  1950. RETURN_IF_ERROR(RankIndex::SetupCursor(bc));
  1951. RETURN_IF_ERROR(bc.Goto(prev));
  1952. bc["prev"].GetValue(&prev);
  1953. bc["prev_idx"].GetValue(&prev_idx);
  1954. RETURN_IF_ERROR(WipeCursor(bc));
  1955. }
  1956. while (next != 0 && next_idx == r_index)
  1957. {
  1958. BSCursor bc(&m_index[r_index]->m_metadata);
  1959. RETURN_IF_ERROR(RankIndex::SetupCursor(bc));
  1960. RETURN_IF_ERROR(bc.Goto(next));
  1961. bc["next"].GetValue(&next);
  1962. bc["next_idx"].GetValue(&next_idx);
  1963. RETURN_IF_ERROR(WipeCursor(bc));
  1964. }
  1965. return OpStatus::OK;
  1966. }
  1967. void VisitedSearch::CheckMaxSize_RemoveOldIndexes()
  1968. {
  1969. int i, j;
  1970. OpFileLength total_size = 0;
  1971. for (i = m_index.GetCount() - 1; i >= 0; --i)
  1972. total_size += m_index[i]->Size();
  1973. i = m_index.GetCount() - 1;
  1974. while (total_size > m_max_size && (i > 0 || (m_max_size == 0 && i == 0)))
  1975. {
  1976. RankIndex *r = m_index[i];
  1977. if (r->m_metadata.InTransaction())
  1978. return;
  1979. // Check if the subindex is referenced
  1980. // - ignore m_pending records... may be left behind by NSL documents, see CORE-29064
  1981. for (j = m_meta.GetCount() - 1; j >= 0; --j)
  1982. if (m_meta[j]->m_index == r)
  1983. return;
  1984. for (j = m_meta_pf.GetCount() - 1; j >= 0; --j)
  1985. if (m_meta_pf[j]->m_index == r)
  1986. return;
  1987. // Remove it
  1988. total_size -= r->Size();
  1989. if (OpStatus::IsError(r->Clear()))
  1990. return;
  1991. for (j = m_pending.GetCount() - 1; j >= 0; --j)
  1992. if (m_pending[j]->m_index == r)
  1993. m_pending[j]->Invalidate(); // This index is gone
  1994. m_index.Delete(i);
  1995. --i;
  1996. }
  1997. }
  1998. OP_STATUS VisitedSearch::WordSearch(const uni_char *prefix, uni_char **result, int *result_size)
  1999. {
  2000. unsigned i;
  2001. int max_result;
  2002. if (!IsOpen())
  2003. return OpStatus::ERR;
  2004. max_result = *result_size;
  2005. *result_size = 0;
  2006. for (i = 0; i < m_index.GetCount() && max_result > *result_size; ++i)
  2007. *result_size += m_index[i]->m_act.PrefixWords(result + *result_size, prefix, max_result - *result_size);
  2008. return OpStatus::OK;
  2009. }
  2010. void VisitedSearch::HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2)
  2011. {
  2012. if (par1 != (MH_PARAM_1)this)
  2013. return;
  2014. if (!IsOpen())
  2015. return;
  2016. switch (msg)
  2017. {
  2018. case MSG_VISITEDSEARCH_PREFLUSH:
  2019. if ((m_flags & Flushed) != 0)
  2020. {
  2021. if (m_meta.GetCount() > 0)
  2022. PostMessage(MSG_VISITEDSEARCH_COMMIT, (MH_PARAM_1)this, 0, 0);
  2023. break;
  2024. }
  2025. if ((m_flags & PreFlushed) != 0)
  2026. {
  2027. PostMessage(MSG_VISITEDSEARCH_FLUSH, (MH_PARAM_1)this, 0, DELAY_PREFLUSH);
  2028. break;
  2029. }
  2030. switch (PreFlush(PREFLUSH_LIMIT))
  2031. {
  2032. case OpBoolean::IS_TRUE:
  2033. PostMessage(MSG_VISITEDSEARCH_FLUSH, (MH_PARAM_1)this, 0, DELAY_PREFLUSH_FLUSH);
  2034. m_flush_errors = 0;
  2035. break;
  2036. case OpBoolean::IS_FALSE:
  2037. PostMessage(MSG_VISITEDSEARCH_PREFLUSH, (MH_PARAM_1)this, 0, DELAY_PREFLUSH);
  2038. m_flush_errors = 0;
  2039. break;
  2040. case OpStatus::ERR_NO_DISK:
  2041. AbortFlush();
  2042. break;
  2043. case OpStatus::ERR_NO_ACCESS:
  2044. PostMessage(MSG_VISITEDSEARCH_PREFLUSH, (MH_PARAM_1)this, 0, BUSY_RETRY_MS);
  2045. break;
  2046. default: // error - try again
  2047. if (++m_flush_errors > NUM_RETRIES)
  2048. AbortFlush();
  2049. else
  2050. PostMessage(MSG_VISITEDSEARCH_PREFLUSH, (MH_PARAM_1)this, 0, ERROR_RETRY_MS);
  2051. }
  2052. break;
  2053. case MSG_VISITEDSEARCH_FLUSH:
  2054. if ((m_flags & PreFlushing) != 0)
  2055. {
  2056. PostMessage(MSG_VISITEDSEARCH_PREFLUSH, (MH_PARAM_1)this, 0, 0);
  2057. break;
  2058. }
  2059. if ((m_flags & Flushed) != 0)
  2060. {
  2061. PostMessage(MSG_VISITEDSEARCH_COMMIT, (MH_PARAM_1)this, 0, DELAY_FLUSH);
  2062. break;
  2063. }
  2064. switch (Flush(FLUSH_LIMIT))
  2065. {
  2066. case OpBoolean::IS_TRUE:
  2067. PostMessage(MSG_VISITEDSEARCH_COMMIT, (MH_PARAM_1)this, 0, DELAY_FLUSH_COMMIT);
  2068. m_flush_errors = 0;
  2069. break;
  2070. case OpBoolean::IS_FALSE:
  2071. PostMessage(MSG_VISITEDSEARCH_FLUSH, (MH_PARAM_1)this, 0, DELAY_FLUSH);
  2072. m_flush_errors = 0;
  2073. break;
  2074. case OpStatus::ERR_NO_DISK:
  2075. AbortFlush();
  2076. break;
  2077. default: // error - try again
  2078. if (++m_flush_errors > NUM_RETRIES)
  2079. AbortFlush();
  2080. else
  2081. {
  2082. PostMessage(MSG_VISITEDSEARCH_FLUSH, (MH_PARAM_1)this, 0, ERROR_RETRY_MS);
  2083. }
  2084. }
  2085. break;
  2086. case MSG_VISITEDSEARCH_COMMIT:
  2087. if ((m_flags & Flushed) == 0)
  2088. {
  2089. if (m_meta.GetCount() > 0)
  2090. PostMessage(MSG_VISITEDSEARCH_PREFLUSH, (MH_PARAM_1)this, 0, 0);
  2091. break;
  2092. }
  2093. if (OpStatus::IsError(Commit()))
  2094. {
  2095. if (++m_flush_errors > NUM_RETRIES)
  2096. AbortFlush();
  2097. else
  2098. PostMessage(MSG_VISITEDSEARCH_PREFLUSH, (MH_PARAM_1)this, 0, ERROR_RETRY_MS);
  2099. }
  2100. else {
  2101. m_flush_errors = 0;
  2102. if (m_meta.GetCount() > 0)
  2103. PostMessage(MSG_VISITEDSEARCH_PREFLUSH, (MH_PARAM_1)this, 0, DELAY_COMMIT_PREFLUSH);
  2104. }
  2105. break;
  2106. }
  2107. }
  2108. void VisitedSearch::PostMessage(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2, unsigned long delay)
  2109. {
  2110. #if defined(USE_OP_THREAD_TOOLS) && defined(VPS_WRAPPER)
  2111. g_thread_tools->PostMessageToMainThread(msg, par1, par2, delay);
  2112. #else
  2113. g_main_message_handler->PostMessage(msg, par1, par2, delay);
  2114. #endif // USE_OP_THREAD_TOOLS && VPS_WRAPPER
  2115. }
  2116. void VisitedSearch::AbortFlush(void)
  2117. {
  2118. int i;
  2119. m_meta_pf.Clear();
  2120. for (i = 0; i < (int)m_index.GetCount(); ++i)
  2121. {
  2122. RankIndex *index = m_index[i];
  2123. if (index->m_metadata.InTransaction())
  2124. OpStatus::Ignore(index->Rollback());
  2125. }
  2126. m_preflush.Clear();
  2127. m_flags = 0;
  2128. }
  2129. OP_STATUS VisitedSearch::SearchResult::CopyFrom(const VisitedSearch::Result & result,
  2130. VisitedSearch::SearchSpec * search_spec)
  2131. {
  2132. RETURN_IF_ERROR(url.Set(result.url));
  2133. RETURN_IF_ERROR(title.Set(result.title));
  2134. thumbnail_size = result.thumbnail_size;
  2135. OP_DELETEA(thumbnail);
  2136. RETURN_OOM_IF_NULL(thumbnail = OP_NEWA(unsigned char, thumbnail_size));
  2137. op_memcpy(thumbnail, result.thumbnail, thumbnail_size);
  2138. RETURN_IF_ERROR(filename.Set(result.filename));
  2139. visited = result.visited;
  2140. ranking = result.ranking;
  2141. WordHighlighter word_highlighter;
  2142. RETURN_IF_ERROR(word_highlighter.Init(search_spec->query.CStr()));
  2143. RETURN_IF_ERROR(word_highlighter.AppendHighlight(excerpt,
  2144. result.GetPlaintext(),
  2145. search_spec->max_chars,
  2146. search_spec->start_tag,
  2147. search_spec->end_tag,
  2148. search_spec->prefix_ratio
  2149. ));
  2150. return OpStatus::OK;
  2151. }
  2152. #endif // VISITED_PAGES_SEARCH