core.go 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299
  1. package main
  2. import (
  3. "database/sql"
  4. "fmt"
  5. _ "github.com/go-sql-driver/mysql"
  6. "html"
  7. "html/template"
  8. "io/ioutil"
  9. "log"
  10. "net/http"
  11. "net/url"
  12. "strconv"
  13. "strings"
  14. "unicode/utf8"
  15. // "sync"
  16. // "time"
  17. )
  18. type indexPage struct{}
  19. type errorReport struct{ Error string }
  20. type surpriseURL struct{ Url string }
  21. type settingsPage struct{ Worksafe, FilterHTTPS bool }
  22. type MySQLResults struct{ Id, Url, Title, Description, Body string }
  23. type PageData struct {
  24. DBResults []MySQLResults
  25. Query, Page string
  26. FindMore bool
  27. }
  28. func main() {
  29. http.HandleFunc("/", handler)
  30. http.HandleFunc("/json", handler)
  31. http.HandleFunc("/json/", handler)
  32. http.HandleFunc("/surprise", surprise)
  33. http.HandleFunc("/surprise/", surprise)
  34. http.HandleFunc("/settings/", settings)
  35. http.HandleFunc("/settings", settings)
  36. log.Fatal(http.ListenAndServe("0.0.0.0:8080", nil)) //set IP to localhost if reverse proxy is on the same machine
  37. }
  38. //https://golang.org/pkg/net/http/#Request
  39. func handler(w http.ResponseWriter, r *http.Request) {
  40. //fmt.Fprintf(w, "%s %s \n", r.Method, r.URL)
  41. //fmt.Fprintf(w, "%s \n", r.URL.RawQuery)
  42. //Indicate whether or not you are using shard tables
  43. shards := true
  44. //check if worksafe+https cookie enabled.
  45. filterHTTPS := false
  46. worksafe := true
  47. worksafeHTTPSCookie, err := r.Cookie("ws")
  48. if err != nil {
  49. worksafe = true
  50. filterHTTPS = false
  51. } else if worksafeHTTPSCookie.Value == "0" {
  52. worksafe = false
  53. filterHTTPS = false
  54. } else if worksafeHTTPSCookie.Value == "1" {
  55. worksafe = true
  56. filterHTTPS = false
  57. } else if worksafeHTTPSCookie.Value == "2" {
  58. worksafe = false
  59. filterHTTPS = true
  60. } else if worksafeHTTPSCookie.Value == "3" {
  61. worksafe = true
  62. filterHTTPS = true
  63. }
  64. //setup for error report
  65. error := errorReport{}
  66. //Get the raw query
  67. m, _ := url.ParseQuery(r.URL.RawQuery)
  68. //Get the query parameters (q and o)
  69. //fmt.Fprintf(w,"%s\n%s\n", m["q"][0], m["o"][0])
  70. json := false
  71. if strings.Contains(r.URL.Path, "/json") {
  72. json = true
  73. if _, ok := m["nsfw"]; ok { //check if &nsfw added to json url
  74. worksafe = false
  75. }
  76. }
  77. query := ""
  78. queryNoQuotes := ""
  79. offset := "0"
  80. page := "0"
  81. //Check if query and page params exist
  82. if _, ok := m["q"]; ok {
  83. query = strings.Replace(m["q"][0], "'", "''", -1)
  84. queryNoQuotes = query
  85. }
  86. if _, ok := m["p"]; ok {//gets page num, will convert to offset further down
  87. page = strings.Replace(m["p"][0], "'", "''", -1)
  88. offset = page
  89. }
  90. lim := "12"
  91. // limDistributedInt :=
  92. if query == "" { //what do if no query found?
  93. //load index if no query detected
  94. if r.URL.Path == "/" {
  95. p := indexPage{}
  96. t, _ := template.ParseFiles("coreassets/form.html.go")
  97. t.Execute(w, p)
  98. } else if strings.Contains(r.URL.Path, "/json") { //load json info page if json selected
  99. p := indexPage{}
  100. t, _ := template.ParseFiles("coreassets/json/json.html.go")
  101. t.Execute(w, p)
  102. } else {
  103. p := indexPage{}
  104. t, _ := template.ParseFiles("coreassets/form.html.go")
  105. t.Execute(w, p)
  106. }
  107. } else {
  108. //Make sure offset is a number
  109. offsetInt, err := strconv.Atoi(offset)
  110. if err != nil {
  111. offset = "0"
  112. offsetInt = 0
  113. }
  114. //Make sure page is a number
  115. pageInt, err := strconv.Atoi(page)
  116. if err != nil {
  117. page = "0"
  118. pageInt = 0
  119. }
  120. //Convert lim to number
  121. limInt, _ := strconv.Atoi(lim)
  122. //convert page num to offset
  123. if offsetInt > 0 {
  124. offsetInt --;
  125. }
  126. offsetInt = offsetInt * limInt
  127. offset = strconv.Itoa(offsetInt)
  128. //get some details from the raw query
  129. var additions string
  130. querylen := len(query)
  131. //see if a search redirect (! or &) is used for a different search engine
  132. if json == false && (strings.Contains(m["q"][0],"!") || strings.Contains(m["q"][0],"&")){
  133. searchredirect(w, r, m["q"][0])
  134. }
  135. //phone users
  136. if query[querylen-1] == ' '{
  137. query = query[:querylen-1]
  138. queryNoQuotes = queryNoQuotes[:len(queryNoQuotes)-1]
  139. querylen = len(query)
  140. }
  141. if querylen > 1 && query[0] == ' '{
  142. query = query[1:querylen]
  143. queryNoQuotes = queryNoQuotes[1:len(queryNoQuotes)]
  144. querylen = len(query)
  145. }
  146. //check if user wants to limit search to a specific website
  147. sitePos := -1
  148. siteEnd := 0
  149. siteURL := ""
  150. if strings.Index(strings.ToLower(query), "site:") > -1 {
  151. //get url user wants to search and remove it from the query string
  152. sitePos = strings.Index(strings.ToLower(query), "site:")
  153. siteEnd = strings.Index(query[sitePos:], " ")
  154. //fmt.Printf("\n%d\n%d\n",sitePos,siteEnd)
  155. if siteEnd > -1 && sitePos > 1 { //site is not last part of query
  156. siteURL = query[sitePos+5 : siteEnd+sitePos]
  157. query = query[:sitePos-1] + query[siteEnd+sitePos:]
  158. queryNoQuotes = queryNoQuotes[:sitePos-1] + queryNoQuotes[siteEnd+sitePos:]
  159. additions = additions + "AND url LIKE '%" + siteURL + "%' "
  160. } else if siteEnd > -1 && sitePos == 0 { //site is at beginning
  161. siteURL = query[sitePos+5 : siteEnd]
  162. query = query[siteEnd+1:]
  163. queryNoQuotes = queryNoQuotes[siteEnd+1:]
  164. additions = additions + "AND url LIKE '%" + siteURL + "%' "
  165. } else if siteEnd < 0 && sitePos > 1 { //site is at end
  166. siteURL = query[sitePos+5:]
  167. query = query[:sitePos-1]
  168. queryNoQuotes = queryNoQuotes[:sitePos-1]
  169. additions = additions + "AND url LIKE '%" + siteURL + "%' "
  170. }else if querylen > 5{
  171. query = query[5:]
  172. }
  173. querylen = len(query)
  174. }
  175. //fmt.Printf("Addition: \n%s\nQuery: '%s'\n",additions,query)
  176. //see if user uses -https flag (instead of cookie settings option)
  177. if querylen > 7 && strings.ToLower(query[querylen-7:querylen]) == " -https" {
  178. filterHTTPS = true
  179. query = query[0 : querylen-7]
  180. querylen = len(query)
  181. }
  182. //check if user wants to search within a time window (day,week,month)
  183. option := ""
  184. //fmt.Printf("\n'%s'\n",query)
  185. location := strings.Index(query, " !")
  186. if location == -1 {
  187. location = strings.Index(query, " &")
  188. }
  189. if location > -1 && strings.Index(query[location+1:querylen], " ") == -1 { //option is at end of query
  190. option = query[location+2 : querylen]
  191. query = query[:location]
  192. queryNoQuotes = queryNoQuotes[:location]
  193. querylen = len(query)
  194. }else if querylen > 0 && (query[0] == '!' || query[0] == '&') && strings.Index(query, " ") > -1{ //option is at start of query
  195. option = query[1:strings.Index(query, " ")]
  196. query = query[strings.Index(query, " ")+1:]
  197. queryNoQuotes = queryNoQuotes[strings.Index(queryNoQuotes, " ")+1:]
  198. querylen = len(query)
  199. }
  200. option = strings.ToLower(option)
  201. if option != "" {
  202. if option == "td" { //day
  203. additions = additions + "AND date > NOW() - INTERVAL 1 DAY "
  204. } else if option == "tw" { //week
  205. additions = additions + "AND date > NOW() - INTERVAL 7 DAY "
  206. } else if option == "tm" { //month
  207. additions = additions + "AND date > NOW() - INTERVAL 30 DAY "
  208. } else if option == "ty" { //year
  209. additions = additions + "AND date > NOW() - INTERVAL 365 DAY "
  210. }
  211. }
  212. //check if worksafe and filterHTTPS flags set
  213. if worksafe == true {
  214. additions = additions + "AND worksafe = '1' "
  215. }
  216. if filterHTTPS == true {
  217. additions = additions + "AND http = '1' "
  218. }
  219. //search if query has quotes and remove them (so we can find the longest word in the query)
  220. exactMatch := false
  221. //queryNoQuotes := query
  222. if strings.Contains(query, "\"") {
  223. exactMatch = true
  224. queryNoQuotes = strings.TrimLeft(queryNoQuotes, "\"")
  225. getlastquote := strings.Split(queryNoQuotes, "\"")
  226. queryNoQuotes = getlastquote[0]
  227. //fmt.Printf("%s \n", queryNoQuotes)
  228. }
  229. //remove the '*' if contained anywhere in queryNoQuotes
  230. if strings.Contains(queryNoQuotes, "*") && exactMatch == false {
  231. queryNoQuotes = strings.Replace(queryNoQuotes, "*", "", -1)
  232. }
  233. //Prepare to find longest word in query
  234. words := strings.Split(queryNoQuotes, " ")
  235. longestWordLength := 0
  236. longestWord := ""
  237. wordcount := 0
  238. longestwordelementnum := 0
  239. queryNoQuotesOrFlags := queryNoQuotes
  240. requiredword := ""
  241. flags := ""
  242. flagssetbyuser := 0
  243. wordlen := 0
  244. numRequiredWords := 0
  245. //queryNoFlags := ""
  246. //first remove any flags inside var queryNoQuotes, also grab any required words (+ prefix)
  247. if strings.Contains(queryNoQuotes, "-") || strings.Contains(queryNoQuotes, "+") {
  248. queryNoQuotesOrFlags = ""
  249. for i, wordNoFlags := range words {
  250. if i > 0 && strings.HasPrefix(wordNoFlags, "-") == false && strings.HasPrefix(wordNoFlags, "+") == false { //add a space after
  251. queryNoQuotesOrFlags += " "
  252. }
  253. if strings.HasPrefix(wordNoFlags, "-") == false && strings.HasPrefix(wordNoFlags, "+") == false {
  254. queryNoQuotesOrFlags += wordNoFlags
  255. }
  256. if strings.HasPrefix(wordNoFlags, "+") == true && len(wordNoFlags) > 1 && requiredword == "" { //get requiredword
  257. requiredword = wordNoFlags[1:len(wordNoFlags)]
  258. }
  259. if i > 0 && strings.HasPrefix(wordNoFlags, "-") == true || strings.HasPrefix(wordNoFlags, "+") == true {
  260. flags += " " + wordNoFlags
  261. flagssetbyuser++
  262. if strings.HasPrefix(wordNoFlags, "+") == true {
  263. numRequiredWords++
  264. }
  265. }
  266. }
  267. }
  268. //now find longest word, and build extra locate statements for partial matches (when sorting results returned from replicas)
  269. partialLocate := ""
  270. locateWords := false
  271. words = strings.Split(queryNoQuotesOrFlags, " ")
  272. if exactMatch == false {
  273. for _, word := range words {
  274. if len(word) > longestWordLength {
  275. longestWordLength = len(word)
  276. longestWord = word
  277. longestwordelementnum = wordcount
  278. }
  279. if wordcount < 5 && len(word) > 3{
  280. if locateWords == false {
  281. partialLocate += " WHEN LOCATE('" + word + "', title) "
  282. }else{
  283. partialLocate += "OR LOCATE('" + word + "', title) "
  284. }
  285. locateWords=true
  286. }
  287. if word != ""{
  288. wordcount++
  289. }
  290. }
  291. if locateWords == true{
  292. partialLocate += "THEN 10"
  293. }
  294. }
  295. //fmt.Printf("\n%s",partialLocate)
  296. //create another query where all compatible words are marked as keywords
  297. reqwordQuery := ""
  298. for i, word := range words{
  299. wordlen = len(word)
  300. if i==0 && (strings.HasPrefix(word, "+") == true || strings.HasPrefix(word, "-") == true) && wordlen > 3{
  301. reqwordQuery += word
  302. }
  303. if i==0 && (strings.HasPrefix(word, "+") == false && strings.HasPrefix(word, "-") == false) {
  304. if wordlen > 2 {
  305. reqwordQuery += "+"
  306. }
  307. reqwordQuery += word
  308. }
  309. if i!=0 && (strings.HasPrefix(word, "+") == true || strings.HasPrefix(word, "-") == true) && wordlen > 3{
  310. reqwordQuery += " "
  311. reqwordQuery += word
  312. }
  313. if i!=0 && (strings.HasPrefix(word, "+") == false && strings.HasPrefix(word, "-") == false) {
  314. reqwordQuery += " "
  315. if wordlen > 2 {
  316. reqwordQuery += "+"
  317. }
  318. reqwordQuery += word
  319. }
  320. }
  321. reqwordQuery += flags
  322. //fmt.Fprintf(w,"%s\n%s\n", query,offset)
  323. //fmt.Printf("hai\n")
  324. //get copy of original query because we might have to modify it somewhat
  325. queryOriginal := query
  326. tRes := MySQLResults{}
  327. var res = PageData{}
  328. //Check if query is a url.
  329. urlDetected := false
  330. isURL := ""
  331. isURLlocate := ""
  332. if strings.Index(query, " ") == -1 && strings.Index(query, "\"") == -1 && strings.Index(query, ".") > -1 { //note this will also flag on file extensions
  333. if len(query) > 6 && (query[0:7] == "http://" || query[0:7] == "HTTP://") {
  334. query = query[7:]
  335. } else if len(query) > 7 && (query[0:8] == "https://" || query[0:8] == "HTTPS://") {
  336. query = query[8:]
  337. }
  338. if len(queryNoQuotes) > 6 && (queryNoQuotes[0:7] == "http://" || queryNoQuotes[0:7] == "HTTP://") {
  339. queryNoQuotes = queryNoQuotes[7:]
  340. } else if len(queryNoQuotes) > 7 && (queryNoQuotes[0:8] == "https://" || queryNoQuotes[0:8] == "HTTPS://") {
  341. queryNoQuotes = queryNoQuotes[8:]
  342. }
  343. query = "\"" + query + "\""
  344. urlDetected = true
  345. isURL = "WHEN MATCH(url) AGAINST('\"" + queryNoQuotes + "\"' IN BOOLEAN MODE) THEN 25"
  346. isURLlocate = "WHEN LOCATE('" + queryNoQuotesOrFlags + "', url) THEN 25"
  347. }
  348. //Check if query contains a hyphenated word. Will wrap quotes around hyphenated words that aren't part of a string which is already wraped in quotes.
  349. if (strings.Contains(queryNoQuotes, "-") || strings.Contains(queryNoQuotes, "+")) && urlDetected == false {
  350. hyphenwords := strings.Split(query, " ")
  351. query = ""
  352. quotes := 0
  353. for i, word := range hyphenwords {
  354. if strings.Contains(word, "\"") {
  355. quotes++
  356. }
  357. if ((strings.Contains(word, "-") && word[0] != '-') || (strings.Contains(word, "+") && word[0] != '+')) && quotes%2 == 0 { //if hyphen or plus exists, not a flag, not wrapped in quotes already
  358. word = "\"" + word + "\""
  359. }
  360. if i > 0 {
  361. query += " "
  362. }
  363. query += word
  364. }
  365. }
  366. //fmt.Printf(">%s<\n", query)
  367. //if no required words set, make the longest word in the query required.
  368. querywithrequiredword := ""
  369. if numRequiredWords == 0 && wordcount > 1 && longestWordLength > 2{
  370. querywithrequiredword = query + " +"
  371. querywithrequiredword = querywithrequiredword + longestWord
  372. }
  373. //perform full text search FOR InnoDB or MyISAM
  374. var sqlQuery, id, url, title, description, body, idList string
  375. rangeOffset := 0
  376. serverCount := 0
  377. var servers []string
  378. numServers := 0
  379. //parse res.csv
  380. noservers := false
  381. repLim, _ := strconv.Atoi(lim)
  382. repOffset, _ := strconv.Atoi(offset)
  383. repLimStr := ""
  384. repOffsetStr := ""
  385. shard := ""
  386. noresults := 0
  387. repsearchfail := 0
  388. var idListChans []chan string
  389. oneword := false
  390. if strings.Index(query, " ") == -1{
  391. oneword = true
  392. }
  393. resourceFile, err := ioutil.ReadFile("res.csv")
  394. if err != nil {
  395. noservers = true
  396. } else {
  397. if len(resourceFile) < 2 {
  398. noservers = true
  399. }
  400. }
  401. //this switches off use of multiple connections to process a one word query. Should remove this if the database grows significantly larger
  402. /*if strings.Contains(query, " ") == false && oneletterquery == 0 {
  403. noservers = true
  404. }*/
  405. queryWithQuotesAndFlags := "\"" + queryNoQuotesOrFlags + "\"" + flags
  406. //if query is just 1 or 2 letters, help make it work.
  407. if utf8.RuneCountInString(queryOriginal) < 3 {
  408. queryfix := "" + query + "*"
  409. query = queryfix
  410. queryWithQuotesAndFlags = queryfix
  411. reqwordQuery = queryfix
  412. }
  413. if strings.Contains(queryOriginal,"c++")==true || strings.Contains(queryOriginal,"C++")==true{ // :) :( :) :(
  414. exactMatch=true
  415. queryWithQuotesAndFlags += " +programming"
  416. if strings.Contains(queryOriginal," ")==true && longestWordLength>3{
  417. queryWithQuotesAndFlags += " +"
  418. queryWithQuotesAndFlags += longestWord
  419. }
  420. }
  421. querytouse := query
  422. if querywithrequiredword != ""{
  423. querytouse = querywithrequiredword
  424. }else if numRequiredWords > 0{
  425. querytouse = reqwordQuery
  426. }
  427. reqwordQuery_filtered := strings.Replace(reqwordQuery, "'", "", -1)
  428. //For a less restrictive search, replace only the first instance of reqwordQuery_filtered with querytouse_filtered in the SQL query used when calling the distributedQuery go routine
  429. querytouse_filtered := strings.Replace(querytouse, "'", "", -1)
  430. queryWithQuotesAndFlags_filtered := strings.Replace(queryWithQuotesAndFlags, "'", "", -1)
  431. if noservers == false {
  432. //send query to go routines.
  433. resourceFilestring := string(resourceFile)
  434. //just in case user is messing around res.csv with a text editor and the editor ads a line feed to the end of the file
  435. if len(resourceFilestring) > 0 && resourceFilestring[len(resourceFilestring)-1] == byte('\n') {
  436. resourceFilestring = resourceFilestring[0 : len(resourceFilestring)-1]
  437. }
  438. servers = strings.Split(resourceFilestring, "\n")
  439. numServers = len(servers)
  440. if(shards == false){
  441. //numServers must divide evenly into lim, or lim must divide evenly into numservers
  442. //if they do not, automatically adjust numServers until they divide evenly
  443. //calculate number of servers to use based on lim size
  444. if limInt > numServers {
  445. for limInt%numServers > 0 {
  446. numServers -= 1
  447. }
  448. } else if numServers > limInt {
  449. for numServers%limInt > 0 {
  450. numServers -= 1
  451. }
  452. }
  453. }
  454. //calculate limit and offset on distributed servers.
  455. if numServers < limInt {
  456. repLim = limInt / numServers
  457. } else {
  458. repLim = 1
  459. }
  460. repOffset = offsetInt / numServers
  461. //calculate rangeOffset (offset for the range of returned results, important if numServers > 2*lim)
  462. rangeOffset = offsetInt - (repOffset * numServers)
  463. repLimStr = strconv.Itoa(repLim)
  464. repOffsetStr = strconv.Itoa(repOffset)
  465. //create a channel for each available server
  466. for i := 0; i < numServers; i++ {
  467. idListChans = append(idListChans, make(chan string))
  468. }
  469. for _, server := range servers {
  470. serverSettings := strings.Split(server, ",")
  471. if len(serverSettings) == 4 { //if line contains all 4 settings
  472. //ip, database, startID, endID
  473. //create SQL connection string //db, err := sql.Open("mysql", "remote_guest:d0gemuchw0w@tcp(192.168.1.xxx:3306)/wiby?charset=utf8mb4")
  474. serverIP := serverSettings[0]
  475. shard = serverSettings[1]
  476. startID := serverSettings[2]
  477. endID := serverSettings[3]
  478. sqlString := "remote_guest:d0gemuchw0w@tcp(" + serverIP + ":3306)/wiby?charset=utf8mb4"
  479. // fmt.Printf("%s %s %s %d\n",sqlString,startID,endID,numServers)
  480. //send special distributed query, only need ID returned
  481. if(shards==false){//depricated
  482. /*if(exactMatch==false && urlDetected==false && oneword==false){
  483. sqlQuery = "SELECT id FROM windex WHERE id BETWEEN " + startID + " AND " + endID + " AND enable = '1' " + additions + "ORDER BY CASE WHEN MATCH(tags) AGAINST('" + queryWithQuotesAndFlags + "' IN BOOLEAN MODE) THEN 30 " + isURL + " WHEN MATCH(title) AGAINST('" + queryWithQuotesAndFlags + "' IN BOOLEAN MODE) AND Match(title) AGAINST('" + query + "' IN BOOLEAN MODE) THEN 20 WHEN MATCH(body) AGAINST('" + queryWithQuotesAndFlags + "' IN BOOLEAN MODE) THEN 19 WHEN MATCH(title) AGAINST('" + queryWithQuotesAndFlags + "' IN BOOLEAN MODE) THEN 16 WHEN MATCH(description) AGAINST('" + queryWithQuotesAndFlags + "' IN BOOLEAN MODE) THEN 15 WHEN Match(title) AGAINST('" + query + "' IN BOOLEAN MODE) THEN Match(title) AGAINST('" + query + "' IN BOOLEAN MODE) WHEN MATCH(body) AGAINST('" + query + "' IN BOOLEAN MODE) THEN 1 WHEN MATCH(url) AGAINST('" + query + "' IN BOOLEAN MODE) THEN 0 END DESC, id DESC LIMIT " + repLimStr + " OFFSET " + repOffsetStr + ""
  484. }else{
  485. sqlQuery = "SELECT id FROM windex WHERE id BETWEEN " + startID + " AND " + endID + " AND enable = '1' " + additions + "ORDER BY CASE WHEN MATCH(tags) AGAINST('" + queryWithQuotesAndFlags + "' IN BOOLEAN MODE) THEN 30 " + isURL + " WHEN MATCH(title) AGAINST('" + queryWithQuotesAndFlags + "' IN BOOLEAN MODE) THEN 20 WHEN MATCH(body) AGAINST('" + queryWithQuotesAndFlags + "' IN BOOLEAN MODE) THEN 19 WHEN MATCH(description) AGAINST('" + queryWithQuotesAndFlags + "' IN BOOLEAN MODE) THEN 15 WHEN MATCH(url) AGAINST('" + query + "' IN BOOLEAN MODE) THEN 0 END DESC, id DESC LIMIT " + repLimStr + " OFFSET " + repOffsetStr + ""
  486. }*/
  487. }else{
  488. if(exactMatch==false && urlDetected==false && oneword==false && flagssetbyuser + wordcount != flagssetbyuser){
  489. sqlQuery = "SELECT id FROM " + shard + " WHERE MATCH(tags, body, description, title, url) AGAINST('" + reqwordQuery_filtered + "' IN BOOLEAN MODE) AND enable = '1' " + additions + "ORDER BY CASE WHEN MATCH(tags) AGAINST('" + queryWithQuotesAndFlags + "' IN BOOLEAN MODE) THEN 30 " + isURL + " WHEN MATCH(title) AGAINST('" + queryWithQuotesAndFlags + "' IN BOOLEAN MODE) THEN 20 WHEN MATCH(body) AGAINST('" + queryWithQuotesAndFlags + "' IN BOOLEAN MODE) OR MATCH(description) AGAINST('" + queryWithQuotesAndFlags + "' IN BOOLEAN MODE) THEN 15 WHEN MATCH(title) AGAINST('" + reqwordQuery_filtered + "' IN BOOLEAN MODE) THEN 14 WHEN MATCH(title) AGAINST('" + querytouse_filtered + "' IN BOOLEAN MODE) THEN 13 END DESC, id DESC LIMIT " + repLimStr + " OFFSET " + repOffsetStr + ""
  490. }else{
  491. sqlQuery = "SELECT id FROM " + shard + " WHERE MATCH(tags, body, description, title, url) AGAINST('" + queryWithQuotesAndFlags_filtered + "' IN BOOLEAN MODE) AND enable = '1' " + additions + "ORDER BY CASE WHEN MATCH(tags) AGAINST('" + queryWithQuotesAndFlags_filtered + "' IN BOOLEAN MODE) THEN 30 " + isURL + " WHEN MATCH(title) AGAINST('" + queryWithQuotesAndFlags_filtered + "' IN BOOLEAN MODE) THEN 20 END DESC, id DESC LIMIT " + repLimStr + " OFFSET " + repOffsetStr + ""
  492. }
  493. }
  494. go distributedQuery(sqlString, sqlQuery, startID, endID, idListChans[serverCount])
  495. serverCount++
  496. }
  497. }
  498. for i := 0; i < serverCount; i++ {
  499. //wait for channels to complete and collect results
  500. idList += <-idListChans[i]
  501. }
  502. if len(idList) > 0 {
  503. switch strings.Contains(idList, "e") {
  504. case true:
  505. repsearchfail = 1
  506. default:
  507. idList = idList[1:len(idList)] //trim the first comma in the list
  508. }
  509. } else {
  510. noresults = 1
  511. }
  512. //fmt.Printf("\nChan: %s",idList)
  513. }
  514. //init the db and set charset
  515. //create SQL connection string
  516. db, err := sql.Open("mysql", "guest:qwer@/wiby?charset=utf8mb4")
  517. if err != nil {
  518. p := indexPage{}
  519. t, _ := template.ParseFiles("coreassets/error.html.go")
  520. t.Execute(w, p)
  521. }
  522. defer db.Close()
  523. // If Open doesn't open a connection. Validate DSN data:
  524. err = db.Ping()
  525. if err != nil {
  526. error.Error = err.Error()
  527. t, _ := template.ParseFiles("coreassets/error.html.go")
  528. t.Execute(w, error)
  529. }
  530. count := 0
  531. countResults := 0
  532. var ids[] string
  533. //if all went well with replication servers, send query to master containing idList and use the rangeOffset
  534. if numServers == serverCount && numServers > 0 && repsearchfail == 0 {
  535. sqlQuery = "SELECT id, url, title, description, body FROM windex WHERE id IN (" + idList + ") AND enable = '1' " + additions + "ORDER BY CASE WHEN LOCATE('" + queryNoQuotesOrFlags + "', tags) THEN 30 " + isURLlocate + " WHEN LOCATE('" + queryNoQuotesOrFlags + "', title) THEN 20 WHEN LOCATE('" + queryNoQuotesOrFlags + "', body) OR LOCATE('" + queryNoQuotesOrFlags + "', description) THEN 15" + partialLocate + " END DESC, id DESC LIMIT " + lim + " OFFSET " + strconv.Itoa(rangeOffset) + ""
  536. } else { //else, if no replication servers or there was some sort of error, just search the database locally instead
  537. if(exactMatch==false && urlDetected==false && oneword==false && flagssetbyuser + wordcount != flagssetbyuser){
  538. sqlQuery = "SELECT id, url, title, description, body FROM windex WHERE MATCH(tags, body, description, title, url) AGAINST('" + querytouse + "' IN BOOLEAN MODE) AND enable = '1' " + additions + "ORDER BY CASE WHEN MATCH(tags) AGAINST('" + queryWithQuotesAndFlags + "' IN BOOLEAN MODE) THEN 30 " + isURL + " WHEN MATCH(title) AGAINST('" + queryWithQuotesAndFlags + "' IN BOOLEAN MODE) THEN 20 WHEN MATCH(body) AGAINST('" + queryWithQuotesAndFlags + "' IN BOOLEAN MODE) OR MATCH(description) AGAINST('" + queryWithQuotesAndFlags + "' IN BOOLEAN MODE) THEN 15 WHEN MATCH(title) AGAINST('" + reqwordQuery + "' IN BOOLEAN MODE) THEN 14 WHEN MATCH(title) AGAINST('" + querytouse + "' IN BOOLEAN MODE) THEN 13 END DESC, id DESC LIMIT " + lim + " OFFSET " + offset + ""
  539. }else{
  540. if(shards==false){//depricated
  541. /*sqlQuery = "SELECT id, url, title, description, body FROM windex WHERE enable = '1' " + additions + "ORDER BY CASE WHEN MATCH(tags) AGAINST('" + queryWithQuotesAndFlags + "' IN BOOLEAN MODE) THEN 30 " + isURL + " WHEN MATCH(title) AGAINST('" + queryWithQuotesAndFlags + "' IN BOOLEAN MODE) THEN 20 WHEN MATCH(body) AGAINST('" + queryWithQuotesAndFlags + "' IN BOOLEAN MODE) THEN 19 WHEN MATCH(description) AGAINST('" + queryWithQuotesAndFlags + "' IN BOOLEAN MODE) THEN 15 WHEN MATCH(url) AGAINST('" + query + "' IN BOOLEAN MODE) THEN 0 END DESC, id DESC LIMIT " + lim + " OFFSET " + offset + ""*/
  542. }else{
  543. sqlQuery = "SELECT id, url, title, description, body FROM windex WHERE MATCH(tags, body, description, title, url) AGAINST('" + queryWithQuotesAndFlags + "' IN BOOLEAN MODE) AND enable = '1' " + additions + "ORDER BY CASE WHEN MATCH(tags) AGAINST('" + queryWithQuotesAndFlags + "' IN BOOLEAN MODE) THEN 30 " + isURL + " WHEN MATCH(title) AGAINST('" + queryWithQuotesAndFlags + "' IN BOOLEAN MODE) THEN 20 END DESC, id DESC LIMIT " + lim + " OFFSET " + offset + ""
  544. }
  545. }
  546. }
  547. switch noresults { //if noresults == 1, no results were found during search on active replication servers
  548. case 0:
  549. // Send the query
  550. rows, err := db.Query(sqlQuery)
  551. if err != nil {
  552. fmt.Printf("\n%s", err)
  553. res.Page = strconv.Itoa(0)
  554. res.Query = m["q"][0] //get original unsafe query
  555. if json {
  556. w.Header().Set("Content-Type", "application/json")
  557. t, _ := template.ParseFiles("coreassets/json/results.json.go")
  558. t.Execute(w, res)
  559. } else {
  560. t, _ := template.ParseFiles("coreassets/results.html.go")
  561. t.Execute(w, res)
  562. }
  563. //p := indexPage{}
  564. //t, _ := template.ParseFiles("coreassets/form.html.go")
  565. //t.Execute(w, p)
  566. return
  567. }
  568. if urlDetected == true {
  569. query = queryOriginal
  570. }
  571. wordtocheck := ""
  572. stringtofind := strings.ToLower(queryNoQuotesOrFlags)
  573. stringtofind = strings.Replace(stringtofind, "''", "'", -1)
  574. requiredwordtofind := strings.ToLower(requiredword)
  575. requiredwordtofind = strings.Replace(requiredwordtofind, "''", "'", -1)
  576. longestWordtofind := strings.ToLower(longestWord)
  577. longestWordtofind = strings.Replace(longestWordtofind, "''", "'", -1)
  578. for rows.Next() {
  579. count++
  580. countResults++
  581. //this will get set if position of longest word of query is found within body
  582. pos := -1
  583. err := rows.Scan(&id, &url, &title, &description, &body)
  584. if err != nil {
  585. error.Error = err.Error()
  586. t, _ := template.ParseFiles("coreassets/error.html.go")
  587. t.Execute(w, error)
  588. }
  589. ids = append(ids,id)
  590. //find query inside body of page
  591. if exactMatch == false && (numRequiredWords == 0 || numRequiredWords + wordcount == numRequiredWords){
  592. if len(requiredword) > 0 { //search for position of required word if any, else search for position of whole query
  593. pos = strings.Index(strings.ToLower(body), requiredwordtofind)
  594. } else if pos == -1 {
  595. pos = strings.Index(strings.ToLower(body), stringtofind)
  596. }
  597. if pos == -1 { //not found? find position of longest query word
  598. pos = strings.Index(strings.ToLower(body), longestWordtofind)
  599. //not found?, set position to a different word
  600. if pos == -1 && wordcount > 1 {
  601. if longestwordelementnum > 0 {
  602. //wordtocheck = strings.Replace(words[0], "*", "", -1)
  603. wordtocheck = strings.Replace(words[0], "''", "'", -1)
  604. pos = strings.Index(strings.ToLower(body), strings.ToLower(wordtocheck))
  605. }
  606. if longestwordelementnum == 0 {
  607. //wordtocheck = strings.Replace(words[1], "*", "", -1)
  608. wordtocheck = strings.Replace(words[1], "''", "'", -1)
  609. pos = strings.Index(strings.ToLower(body), strings.ToLower(wordtocheck))
  610. }
  611. }
  612. }
  613. } else { //if exact match, find position of query within body
  614. pos = strings.Index(strings.ToLower(body), stringtofind)
  615. }
  616. //still not found?, set position to 0
  617. if pos == -1 {
  618. pos = 0
  619. }
  620. //Adjust position for runes within body
  621. pos = utf8.RuneCountInString(body[:pos])
  622. starttext := 0
  623. //ballpark := 0
  624. ballparktext := ""
  625. //figure out how much preceding text to use
  626. if pos < 32 {
  627. starttext = 0
  628. } else if pos > 25 {
  629. starttext = pos - 25
  630. } else if pos > 20 {
  631. starttext = pos - 15
  632. }
  633. //total length of the ballpark
  634. textlength := 180
  635. //populate the ballpark
  636. if pos >= 0 {
  637. ballparktext = substr(body, starttext, starttext+textlength)
  638. } //else{ ballpark = 0}//looks unused
  639. //find position of nearest Period
  640. //foundPeriod := true
  641. posPeriod := strings.Index(ballparktext, ". ") + starttext + 1
  642. //find position of nearest Space
  643. //foundSpace := true
  644. posSpace := strings.Index(ballparktext, " ") + starttext
  645. //if longest word in query is after a period+space within ballpark, reset starttext to that point
  646. if (pos - starttext) > posPeriod {
  647. starttext = posPeriod
  648. //populate the bodymatch
  649. if (pos - starttext) >= 0 {
  650. body = substr(body, starttext, starttext+textlength)
  651. } else {
  652. body = ""
  653. }
  654. } else if pos > posSpace { //else if longest word in query is after a space within ballpark, reset starttext to that point
  655. //else if(pos-starttext) > posSpace//else if longest word in query is after a space within ballpark, reset starttext to that point
  656. starttext = posSpace
  657. //populate the bodymatch
  658. if (pos - starttext) >= 0 {
  659. body = substr(body, starttext, starttext+textlength)
  660. } else {
  661. body = ""
  662. }
  663. } else //else just set the bodymatch to the ballparktext
  664. {
  665. //populate the bodymatch
  666. if (pos - starttext) >= 0 {
  667. body = ballparktext
  668. } else {
  669. body = ""
  670. }
  671. }
  672. tRes.Id = id
  673. tRes.Url = url
  674. tRes.Title = html.UnescapeString(title)
  675. tRes.Description = html.UnescapeString(description)
  676. tRes.Body = html.UnescapeString(body)
  677. if json == true {
  678. tRes.Title = JSONRealEscapeString(tRes.Title)
  679. tRes.Description = JSONRealEscapeString(tRes.Description)
  680. tRes.Body = JSONRealEscapeString(tRes.Body)
  681. }
  682. res.DBResults = append(res.DBResults, tRes)
  683. }
  684. defer rows.Close()
  685. rows.Close()
  686. if count > 0 { //new search method may cause less than the limit of row results per page even if there are more results to come, so we force a full count
  687. count = limInt
  688. }
  689. } //end switch
  690. //================================================================================================================================
  691. //no results found (count==0), so do a wildcard search (repeat the above process) - this section will probably be removed, no longer useful
  692. addWildcard := false
  693. /*if count == 0 && offset == "0" && urlDetected == false && exactMatch == false {
  694. addWildcard = true
  695. query = strings.Replace(query, "\"", "", -1) //remove some things innodb gets fussy over
  696. query = strings.Replace(query, "*", "", -1)
  697. query = strings.Replace(query, "'", "", -1)
  698. queryNoQuotes = strings.Replace(queryNoQuotes, "\"", "", -1)
  699. queryNoQuotes = strings.Replace(queryNoQuotes, "*", "", -1)
  700. queryNoQuotes = strings.Replace(queryNoQuotes, "'", "", -1)
  701. query = query + "*"
  702. if shards == false{
  703. sqlQuery = "SELECT id, url, title, description, body FROM windex WHERE enable = '1' " + additions + "ORDER BY CASE WHEN MATCH(tags) AGAINST('" + query + "' IN BOOLEAN MODE) THEN 30 END DESC, id DESC LIMIT " + lim + " OFFSET " + offset + ""
  704. }else{
  705. sqlQuery = "SELECT id, url, title, description, body FROM windex WHERE Match(tags, body, description, title, url) Against('" + query + "' IN BOOLEAN MODE) AND enable = '1' " + additions + "ORDER BY CASE WHEN MATCH(tags) AGAINST('" + query + "' IN BOOLEAN MODE) THEN 30 END DESC, id DESC LIMIT " + lim + " OFFSET " + offset + ""
  706. }
  707. if repsearchfail == 0 && noservers == false {
  708. serverCount = 0
  709. idList = ""
  710. for _, server := range servers {
  711. serverSettings := strings.Split(server, ",")
  712. if len(serverSettings) == 4 { //if line contains all 4 settings
  713. //ip, database, startID, endID
  714. //create SQL connection string //db, err := sql.Open("mysql", "remote_guest:d0gemuchw0w@tcp(10.8.0.102:3306)/wiby?charset=utf8mb4")
  715. serverIP := serverSettings[0]
  716. shard := serverSettings[1]
  717. startID := serverSettings[2]
  718. endID := serverSettings[3]
  719. sqlString := "remote_guest:d0gemuchw0w@tcp(" + serverIP + ":3306)/wiby?charset=utf8mb4"
  720. //fmt.Printf("%s %s %s %d\n",sqlString,startID,endID,numServers)
  721. //send special distributed query, only need ID returned
  722. if(shards==false){//depricated
  723. sqlQuery = "SELECT id FROM windex WHERE id BETWEEN " + startID + " AND " + endID + " AND enable = '1' " + additions + " ORDER BY CASE WHEN MATCH(tags) AGAINST('" + query + "' IN BOOLEAN MODE) THEN 30 END DESC, id DESC LIMIT " + repLimStr + " OFFSET " + repOffsetStr + ""
  724. }else{
  725. sqlQuery = "SELECT id FROM " + shard + " WHERE Match(tags, body, description, title, url) Against('" + query + "' IN BOOLEAN MODE) AND enable = '1' " + additions + "ORDER BY CASE WHEN MATCH(tags) AGAINST('" + query + "' IN BOOLEAN MODE) THEN 30 END DESC, id DESC LIMIT " + repLimStr + " OFFSET " + repOffsetStr + ""
  726. }
  727. go distributedQuery(sqlString, sqlQuery, startID, endID, idListChans[serverCount])
  728. serverCount++
  729. }
  730. }
  731. for i := 0; i < serverCount; i++ {
  732. //wait for channels to complete and collect results
  733. idList += <-idListChans[i]
  734. }
  735. if len(idList) > 0 {
  736. switch strings.Contains(idList, "e") {
  737. case true:
  738. repsearchfail = 1
  739. default:
  740. idList = idList[1:len(idList)] //trim the first comma in the list
  741. }
  742. } else {
  743. noresults = 1
  744. }
  745. //if all went well with replication servers, send query to local database containing idList and use the rangeOffset
  746. if numServers == serverCount && numServers > 0 && repsearchfail == 0 {
  747. sqlQuery = "SELECT id, url, title, description, body FROM windex WHERE id IN (" + idList + ") AND enable = '1' " + additions + "ORDER BY CASE WHEN LOCATE('" + queryNoQuotes + "', tags) THEN 30 END DESC, id DESC LIMIT " + lim + " OFFSET " + strconv.Itoa(rangeOffset) + ""
  748. } else { //else, if no replication servers or there was some sort of error, search the whole local database instead
  749. if shards == false{
  750. sqlQuery = "SELECT id, url, title, description, body FROM windex WHERE enable = '1' " + additions + "ORDER BY CASE WHEN MATCH(tags) AGAINST('" + query + "' IN BOOLEAN MODE) THEN 30 END DESC, id DESC LIMIT " + lim + " OFFSET " + offset + ""
  751. }else{
  752. sqlQuery = "SELECT id, url, title, description, body FROM windex WHERE Match(tags, body, description, title, url) Against('" + query + "' IN BOOLEAN MODE) AND enable = '1' " + additions + "ORDER BY CASE WHEN MATCH(tags) AGAINST('" + query + "' IN BOOLEAN MODE) THEN 30 END DESC, id DESC LIMIT " + lim + " OFFSET " + offset + ""
  753. }
  754. }
  755. }
  756. rows2, err := db.Query(sqlQuery)
  757. if err != nil {
  758. res.Page = strconv.Itoa(0)
  759. res.Query = m["q"][0] //get original unsafe query
  760. if json {
  761. w.Header().Set("Content-Type", "application/json")
  762. t, _ := template.ParseFiles("coreassets/json/results.json.go")
  763. t.Execute(w, res)
  764. } else {
  765. t, _ := template.ParseFiles("coreassets/results.html.go")
  766. t.Execute(w, res)
  767. }
  768. return
  769. }
  770. wordtocheck := ""
  771. stringtofind := strings.ToLower(queryNoQuotesOrFlags)
  772. stringtofind = strings.Replace(stringtofind, "''", "'", -1)
  773. requiredwordtofind := strings.ToLower(requiredword)
  774. requiredwordtofind = strings.Replace(requiredwordtofind, "''", "'", -1)
  775. longestWordtofind := strings.ToLower(longestWord)
  776. longestWordtofind = strings.Replace(longestWordtofind, "''", "'", -1)
  777. for rows2.Next() {
  778. count++
  779. //this will get set if position of longest word of query is found within body
  780. pos := -1
  781. err := rows2.Scan(&id, &url, &title, &description, &body)
  782. if err != nil {
  783. error.Error = err.Error()
  784. t, _ := template.ParseFiles("coreassets/error.html.go")
  785. t.Execute(w, error)
  786. }
  787. //find query inside body of page
  788. if exactMatch == false && (numRequiredWords == 0 || numRequiredWords + wordcount == numRequiredWords){
  789. if len(requiredword) > 0 { //search for position of required word if any, else search for position of whole query
  790. pos = strings.Index(strings.ToLower(body), requiredwordtofind)
  791. } else if pos == -1 {
  792. pos = strings.Index(strings.ToLower(body), stringtofind)
  793. }
  794. if pos == -1 { //not found? find position of longest query word
  795. pos = strings.Index(strings.ToLower(body), longestWordtofind)
  796. //not found?, set position to a different word
  797. if pos == -1 && wordcount > 1 {
  798. if longestwordelementnum > 0 {
  799. //wordtocheck = strings.Replace(words[0], "*", "", -1)
  800. wordtocheck = strings.Replace(words[0], "''", "'", -1)
  801. pos = strings.Index(strings.ToLower(body), strings.ToLower(wordtocheck))
  802. }
  803. if longestwordelementnum == 0 {
  804. //wordtocheck = strings.Replace(words[1], "*", "", -1)
  805. wordtocheck = strings.Replace(words[1], "''", "'", -1)
  806. pos = strings.Index(strings.ToLower(body), strings.ToLower(wordtocheck))
  807. }
  808. }
  809. }
  810. } else { //if exact match, find position of query within body
  811. pos = strings.Index(strings.ToLower(body), stringtofind)
  812. }
  813. //still not found?, set position to 0
  814. if pos == -1 {
  815. pos = 0
  816. }
  817. //Adjust position for runes within body
  818. pos = utf8.RuneCountInString(body[:pos])
  819. starttext := 0
  820. //ballpark := 0
  821. ballparktext := ""
  822. //figure out how much preceding text to use
  823. if pos < 32 {
  824. starttext = 0
  825. } else if pos > 25 {
  826. starttext = pos - 25
  827. } else if pos > 20 {
  828. starttext = pos - 15
  829. }
  830. //total length of the ballpark
  831. textlength := 180
  832. //populate the ballpark
  833. if pos >= 0 {
  834. ballparktext = substr(body, starttext, starttext+textlength)
  835. } //else{ ballpark = 0}//looks unused
  836. //find position of nearest Period
  837. //foundPeriod := true
  838. posPeriod := strings.Index(ballparktext, ". ") + starttext + 1
  839. //find position of nearest Space
  840. //foundSpace := true
  841. posSpace := strings.Index(ballparktext, " ") + starttext
  842. //if longest word in query is after a period+space within ballpark, reset starttext to that point
  843. if (pos - starttext) > posPeriod {
  844. starttext = posPeriod
  845. //populate the bodymatch
  846. if (pos - starttext) >= 0 {
  847. body = substr(body, starttext, starttext+textlength)
  848. } else {
  849. body = ""
  850. }
  851. } else if pos > posSpace { //else if longest word in query is after a space within ballpark, reset starttext to that point
  852. //else if(pos-starttext) > posSpace//else if longest word in query is after a space within ballpark, reset starttext to that point
  853. starttext = posSpace
  854. //populate the bodymatch
  855. if (pos - starttext) >= 0 {
  856. body = substr(body, starttext, starttext+textlength)
  857. } else {
  858. body = ""
  859. }
  860. } else //else just set the bodymatch to the ballparktext
  861. {
  862. //populate the bodymatch
  863. if (pos - starttext) >= 0 {
  864. body = ballparktext
  865. } else {
  866. body = ""
  867. }
  868. }
  869. tRes.Id = id
  870. tRes.Url = url
  871. tRes.Title = html.UnescapeString(title)
  872. tRes.Description = html.UnescapeString(description)
  873. tRes.Body = html.UnescapeString(body)
  874. if json == true {
  875. tRes.Title = JSONRealEscapeString(tRes.Title)
  876. tRes.Description = JSONRealEscapeString(tRes.Description)
  877. tRes.Body = JSONRealEscapeString(tRes.Body)
  878. }
  879. res.DBResults = append(res.DBResults, tRes)
  880. }
  881. defer rows2.Close()
  882. rows2.Close()
  883. }*/
  884. //=======================================================================================================================
  885. //http://go-database-sql.org/retrieving.html
  886. //Close DB
  887. db.Close()
  888. //allow the find more link
  889. if (countResults >= limInt || countResults > 2) && addWildcard == false{
  890. res.FindMore = true
  891. } else {
  892. res.FindMore = false
  893. }
  894. if(pageInt == 0){
  895. pageInt+=2
  896. }else{
  897. pageInt++;
  898. }
  899. res.Page = strconv.Itoa(pageInt)
  900. res.Query = m["q"][0] //get original unsafe query
  901. if json {
  902. w.Header().Set("Content-Type", "application/json")
  903. t, _ := template.ParseFiles("coreassets/json/results.json.go")
  904. t.Execute(w, res)
  905. } else {
  906. t, _ := template.ParseFiles("coreassets/results.html.go")
  907. t.Execute(w, res)
  908. }
  909. }
  910. }
  911. func settings(w http.ResponseWriter, r *http.Request) {
  912. //setup for error report
  913. error := errorReport{}
  914. //check if worksafe (adult content) cookie enabled.
  915. filterHTTPS := false
  916. worksafe := true
  917. worksafewasoff := false
  918. worksafeHTTPSCookie, err := r.Cookie("ws")
  919. if err != nil {
  920. worksafe = true
  921. filterHTTPS = false
  922. } else if worksafeHTTPSCookie.Value == "0" {
  923. worksafe = false
  924. filterHTTPS = false
  925. worksafewasoff = true
  926. } else if worksafeHTTPSCookie.Value == "1" {
  927. worksafe = true
  928. filterHTTPS = false
  929. } else if worksafeHTTPSCookie.Value == "2" {
  930. worksafe = false
  931. filterHTTPS = true
  932. worksafewasoff = true
  933. } else if worksafeHTTPSCookie.Value == "3" {
  934. worksafe = true
  935. filterHTTPS = true
  936. }
  937. //check if and what is the user posting
  938. switch r.Method {
  939. case "POST":
  940. if err := r.ParseForm(); err != nil {
  941. error.Error = err.Error()
  942. t, _ := template.ParseFiles("coreassets/error.html.go")
  943. t.Execute(w, error)
  944. }
  945. worksafebox := r.Form.Get("worksafe")
  946. agreecheck := r.Form.Get("agree")
  947. agreesubmit := r.Form.Get("agreesubmit")
  948. httpsbox := r.Form.Get("filterHTTPS")
  949. //if user agrees to terms to disable adult content, set cookie and return to index
  950. if agreecheck == "on" {
  951. worksafe = false
  952. //expiration := time.Now().Add(365 * 24 * time.Hour)
  953. if filterHTTPS == false {
  954. cookie := http.Cookie{Name: "ws", Value: "0", Path: "/"}
  955. http.SetCookie(w, &cookie)
  956. } else {
  957. cookie := http.Cookie{Name: "ws", Value: "2", Path: "/"}
  958. http.SetCookie(w, &cookie)
  959. }
  960. p := indexPage{}
  961. t, _ := template.ParseFiles("coreassets/settings/gohome.html")
  962. t.Execute(w, p)
  963. //else if worksafebox is checked, return to index with worksafe on
  964. } else if worksafebox == "on" || agreesubmit == "on" {
  965. //expiration := time.Now().Add(365 * 24 * time.Hour)
  966. if httpsbox != "on" {
  967. cookie := http.Cookie{Name: "ws", Value: "1", Path: "/"}
  968. http.SetCookie(w, &cookie)
  969. } else {
  970. cookie := http.Cookie{Name: "ws", Value: "3", Path: "/"}
  971. http.SetCookie(w, &cookie)
  972. }
  973. p := indexPage{}
  974. t, _ := template.ParseFiles("coreassets/settings/gohome.html")
  975. t.Execute(w, p)
  976. //else if worksafebox unchecked and no cookie, go to content agreement section
  977. } else if worksafebox != "on" && worksafewasoff == false && agreesubmit != "on" {
  978. p := indexPage{}
  979. if httpsbox == "on" {
  980. cookie := http.Cookie{Name: "ws", Value: "3", Path: "/"}
  981. http.SetCookie(w, &cookie)
  982. } else {
  983. cookie := http.Cookie{Name: "ws", Value: "1", Path: "/"}
  984. http.SetCookie(w, &cookie)
  985. }
  986. t, _ := template.ParseFiles("coreassets/settings/agree.html.go")
  987. t.Execute(w, p)
  988. //else if worksafebox unchecked and cookie alredy agreed, go back to index
  989. } else if worksafebox != "on" && worksafewasoff == true {
  990. if httpsbox == "on" {
  991. cookie := http.Cookie{Name: "ws", Value: "2", Path: "/"}
  992. http.SetCookie(w, &cookie)
  993. } else {
  994. cookie := http.Cookie{Name: "ws", Value: "0", Path: "/"}
  995. http.SetCookie(w, &cookie)
  996. }
  997. p := indexPage{}
  998. t, _ := template.ParseFiles("coreassets/settings/gohome.html")
  999. t.Execute(w, p)
  1000. }
  1001. default:
  1002. //load the settings page if no post value
  1003. settingspage := settingsPage{}
  1004. settingspage.Worksafe = worksafe
  1005. settingspage.FilterHTTPS = filterHTTPS
  1006. t, _ := template.ParseFiles("coreassets/settings/settings.html.go")
  1007. t.Execute(w, settingspage)
  1008. }
  1009. }
  1010. func surprise(w http.ResponseWriter, r *http.Request) {
  1011. surprise := surpriseURL{}
  1012. //check if worksafe+HTTPS cookie enabled.
  1013. filterHTTPS := false
  1014. worksafeHTTPSCookie, err := r.Cookie("ws")
  1015. if err != nil {
  1016. filterHTTPS = false
  1017. } else if worksafeHTTPSCookie.Value == "2" {
  1018. filterHTTPS = true
  1019. } else if worksafeHTTPSCookie.Value == "3" {
  1020. filterHTTPS = true
  1021. }
  1022. //setup for error report
  1023. error := errorReport{}
  1024. //init the db and set charset
  1025. db, err := sql.Open("mysql", "guest:qwer@/wiby?charset=utf8mb4")
  1026. if err != nil {
  1027. error.Error = err.Error()
  1028. t, _ := template.ParseFiles("coreassets/error.html.go")
  1029. t.Execute(w, error)
  1030. }
  1031. defer db.Close()
  1032. // Open doesn't open a connection. Validate DSN data:
  1033. err = db.Ping()
  1034. if err != nil {
  1035. error.Error = err.Error()
  1036. t, _ := template.ParseFiles("coreassets/error.html.go")
  1037. t.Execute(w, error)
  1038. }
  1039. //grab a random page
  1040. var sqlQuery string
  1041. if filterHTTPS == false {
  1042. sqlQuery = "select url from windex where worksafe = 1 and surprise = 1 order by rand() limit 1"
  1043. } else {
  1044. sqlQuery = "select url from windex where worksafe = 1 and surprise = 1 and http = 1 order by rand() limit 1"
  1045. }
  1046. rows, err := db.Query(sqlQuery)
  1047. if err != nil {
  1048. error.Error = err.Error()
  1049. t, _ := template.ParseFiles("coreassets/error.html.go")
  1050. t.Execute(w, error)
  1051. }
  1052. var url string
  1053. for rows.Next() {
  1054. err := rows.Scan(&url)
  1055. if err != nil {
  1056. error.Error = err.Error()
  1057. t, _ := template.ParseFiles("coreassets/error.html.go")
  1058. t.Execute(w, error)
  1059. }
  1060. surprise.Url = url
  1061. }
  1062. defer rows.Close()
  1063. rows.Close()
  1064. db.Close()
  1065. t, _ := template.ParseFiles("coreassets/surprise.html.go")
  1066. t.Execute(w, surprise)
  1067. }
  1068. func MysqlRealEscapeString(value string) string {
  1069. replace := map[string]string{"\\": "\\\\", "'": `\'`, "\\0": "\\\\0", "\n": "\\n", "\r": "\\r", `"`: `\"`, "\x1a": "\\Z"}
  1070. for b, a := range replace {
  1071. value = strings.Replace(value, b, a, -1)
  1072. }
  1073. return value
  1074. }
  1075. func JSONRealEscapeString(value string) string {
  1076. replace := map[string]string{"\\": "\\\\", "\t": "\\t", "\b": "\\b", "\n": "\\n", "\r": "\\r", "\f": "\\f" /*, `"`:`\"`*/}
  1077. for b, a := range replace {
  1078. value = strings.Replace(value, b, a, -1)
  1079. }
  1080. //remove control characters
  1081. buf := []rune(value)
  1082. for i, v := range buf {
  1083. if v < 32 || v == 127 {
  1084. buf[i]=32
  1085. }
  1086. }
  1087. return string(buf)
  1088. }
  1089. func substr(s string, start int, end int) string {
  1090. start_str_idx := 0
  1091. i := 0
  1092. for j := range s {
  1093. if i == start {
  1094. start_str_idx = j
  1095. }
  1096. if i == end {
  1097. return s[start_str_idx:j]
  1098. }
  1099. i++
  1100. }
  1101. return s[start_str_idx:]
  1102. }
  1103. func searchredirect(w http.ResponseWriter, r *http.Request, query string) {
  1104. //separate actual query from search redirect
  1105. actualquery := ""
  1106. redirect := ""
  1107. lenquery := len(query)
  1108. if strings.Index(query," ") > -1{
  1109. location := strings.Index(query, " !")
  1110. if location == -1 {
  1111. location = strings.Index(query, " &")
  1112. }
  1113. if location > -1 && strings.Index(query[location+1:lenquery], " ") == -1 { //redirect is at end of query
  1114. redirect = query[location+2 : lenquery]
  1115. actualquery = query[:location]
  1116. } else if (strings.Index(query, "!") == 0 || strings.Index(query, "&") == 0){ //redirect is at start of query
  1117. redirect = query[1:strings.Index(query, " ")]
  1118. actualquery = query[strings.Index(query, " ")+1:]
  1119. //fmt.Printf("\nRedirect: %s\nquery: %s\n",redirect,actualquery)
  1120. }
  1121. redirect = strings.ToLower(redirect)
  1122. }else if (query[0] == '!' || query[0] == '&') && lenquery > 1{
  1123. redirect = query[1:]
  1124. }
  1125. if redirect != "" {
  1126. //determine which search engine to redirect
  1127. if redirect == "g" { //if google text search
  1128. http.Redirect(w, r, "http://google.com/search?q="+actualquery, http.StatusSeeOther)
  1129. } else if redirect == "b" { //if bing text search
  1130. http.Redirect(w, r, "http://bing.com/search?q="+actualquery, http.StatusSeeOther)
  1131. } else if redirect == "gi" { //if google image search
  1132. http.Redirect(w, r, "http://www.google.com/search?tbm=isch&q="+actualquery, http.StatusSeeOther)
  1133. } else if redirect == "bi" { //if bing image search
  1134. http.Redirect(w, r, "http://www.bing.com/images/search?q="+actualquery, http.StatusSeeOther)
  1135. } else if redirect == "gv" { //if google video search
  1136. http.Redirect(w, r, "http://www.google.com/search?tbm=vid&q="+actualquery, http.StatusSeeOther)
  1137. } else if redirect == "bv" { //if bing video search
  1138. http.Redirect(w, r, "http://www.bing.com/videos/search?q="+actualquery, http.StatusSeeOther)
  1139. } else if redirect == "gm" { //if google maps search
  1140. http.Redirect(w, r, "http://www.google.com/maps/search/"+actualquery, http.StatusSeeOther)
  1141. } else if redirect == "bm" { //if bing maps search
  1142. http.Redirect(w, r, "http://www.bing.com/maps?q="+actualquery, http.StatusSeeOther)
  1143. }/* else {
  1144. http.Redirect(w, r, "/?q="+actualquery, http.StatusSeeOther)
  1145. }*/
  1146. }
  1147. }
  1148. func distributedQuery(con string, sqlQuery string, startID string, endID string, idListChan chan<- string) {
  1149. var id string
  1150. var idList string
  1151. count := 0
  1152. //defer wg.Done()
  1153. //init the db
  1154. db, err := sql.Open("mysql", con)
  1155. if err != nil {
  1156. idList = idList + "e" //will look for this when channels are processed
  1157. }
  1158. defer db.Close()
  1159. // If Open doesn't open a connection. Validate DSN data:
  1160. err = db.Ping()
  1161. if err != nil {
  1162. }
  1163. //fmt.Printf("%s\n", sqlQuery)
  1164. // Send the query
  1165. rows, err := db.Query(sqlQuery)
  1166. if err == nil {
  1167. for rows.Next() {
  1168. err := rows.Scan(&id)
  1169. if err != nil {
  1170. }
  1171. //idString = idstring + "id = " + id + " or "
  1172. idList += "," + id
  1173. count++
  1174. }
  1175. } else {
  1176. idList = idList + "e" //will look for this when channels are processed
  1177. fmt.Printf("%s", err)
  1178. }
  1179. //fmt.Printf("%s - %s\n", idList,con)
  1180. idListChan <- idList
  1181. }