core.go 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293
  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. for rows.Next() {
  572. count++
  573. countResults++
  574. //this will get set if position of longest word of query is found within body
  575. pos := -1
  576. err := rows.Scan(&id, &url, &title, &description, &body)
  577. if err != nil {
  578. error.Error = err.Error()
  579. t, _ := template.ParseFiles("coreassets/error.html.go")
  580. t.Execute(w, error)
  581. }
  582. ids = append(ids,id)
  583. //find query inside body of page
  584. if exactMatch == false && (flagssetbyuser == 0 || flagssetbyuser + wordcount == flagssetbyuser){
  585. //remove the '*' if contained anywhere in query
  586. /*if strings.Contains(queryNoQuotes,"*"){
  587. queryNoQuotes = strings.Replace(queryNoQuotes, "*", "", -1)
  588. } */
  589. if len(requiredword) > 0 { //search for position of required word if any, else search for position of whole query
  590. pos = strings.Index(strings.ToLower(body), strings.ToLower(requiredword))
  591. } else if pos == -1 {
  592. pos = strings.Index(strings.ToLower(body), strings.ToLower(queryNoQuotesOrFlags))
  593. }
  594. if pos == -1 { //prepare to find position of longest query word (or required word) within body
  595. //remove the '*' at the end of the longest word if present
  596. if strings.Contains(longestWord, "*") {
  597. longestWord = strings.Replace(longestWord, "*", "", -1)
  598. }
  599. //search within body for position of longest query word.
  600. pos = strings.Index(strings.ToLower(body), strings.ToLower(longestWord))
  601. //not found?, set position to a different word, make sure there's no wildcard on it
  602. if pos == -1 && wordcount > 1 {
  603. if longestwordelementnum > 0 {
  604. words[0] = strings.Replace(words[0], "*", "", -1)
  605. pos = strings.Index(strings.ToLower(body), strings.ToLower(words[0]))
  606. }
  607. if longestwordelementnum == 0 {
  608. words[1] = strings.Replace(words[1], "*", "", -1)
  609. pos = strings.Index(strings.ToLower(body), strings.ToLower(words[1]))
  610. }
  611. }
  612. }
  613. } else { //if exact match, find position of query within body
  614. pos = strings.Index(strings.ToLower(body), strings.ToLower(queryNoQuotesOrFlags))
  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. for rows2.Next() {
  771. count++
  772. //this will get set if position of longest word of query is found within body
  773. pos := -1
  774. err := rows2.Scan(&id, &url, &title, &description, &body)
  775. if err != nil {
  776. error.Error = err.Error()
  777. t, _ := template.ParseFiles("coreassets/error.html.go")
  778. t.Execute(w, error)
  779. }
  780. //find query inside body of page
  781. if exactMatch == false && (flagssetbyuser == 0 || flagssetbyuser + wordcount == flagssetbyuser){
  782. if len(requiredword) > 0 { //search for position of required word if any, else search for position of whole query
  783. pos = strings.Index(strings.ToLower(body), strings.ToLower(requiredword))
  784. } else if pos == -1 {
  785. pos = strings.Index(strings.ToLower(body), strings.ToLower(queryNoQuotesOrFlags))
  786. }
  787. if pos == -1 { //prepare to find position of longest query word (or required word) within body
  788. //remove the '*' at the end of the longest word if present
  789. if strings.Contains(longestWord, "*") {
  790. longestWord = strings.Replace(longestWord, "*", "", -1)
  791. }
  792. //search within body for position of longest query word.
  793. pos = strings.Index(strings.ToLower(body), strings.ToLower(longestWord))
  794. //not found?, set position to a different word, make sure there's no wildcard on it
  795. if pos == -1 && wordcount > 1 {
  796. if longestwordelementnum > 0 {
  797. words[0] = strings.Replace(words[0], "*", "", -1)
  798. pos = strings.Index(strings.ToLower(body), strings.ToLower(words[0]))
  799. }
  800. if longestwordelementnum == 0 {
  801. words[1] = strings.Replace(words[1], "*", "", -1)
  802. pos = strings.Index(strings.ToLower(body), strings.ToLower(words[1]))
  803. }
  804. }
  805. }
  806. } else { //if exact match, find position of query within body
  807. pos = strings.Index(strings.ToLower(body), strings.ToLower(queryNoQuotesOrFlags))
  808. }
  809. //still not found?, set position to 0
  810. if pos == -1 {
  811. pos = 0
  812. }
  813. //Adjust position for runes within body
  814. pos = utf8.RuneCountInString(body[:pos])
  815. starttext := 0
  816. //ballpark := 0
  817. ballparktext := ""
  818. //figure out how much preceding text to use
  819. if pos < 32 {
  820. starttext = 0
  821. } else if pos > 25 {
  822. starttext = pos - 25
  823. } else if pos > 20 {
  824. starttext = pos - 15
  825. }
  826. //total length of the ballpark
  827. textlength := 180
  828. //populate the ballpark
  829. if pos >= 0 {
  830. ballparktext = substr(body, starttext, starttext+textlength)
  831. } //else{ ballpark = 0}//looks unused
  832. //find position of nearest Period
  833. //foundPeriod := true
  834. posPeriod := strings.Index(ballparktext, ". ") + starttext + 1
  835. //find position of nearest Space
  836. //foundSpace := true
  837. posSpace := strings.Index(ballparktext, " ") + starttext
  838. //if longest word in query is after a period+space within ballpark, reset starttext to that point
  839. if (pos - starttext) > posPeriod {
  840. starttext = posPeriod
  841. //populate the bodymatch
  842. if (pos - starttext) >= 0 {
  843. body = substr(body, starttext, starttext+textlength)
  844. } else {
  845. body = ""
  846. }
  847. } else if pos > posSpace { //else if longest word in query is after a space within ballpark, reset starttext to that point
  848. //else if(pos-starttext) > posSpace//else if longest word in query is after a space within ballpark, reset starttext to that point
  849. starttext = posSpace
  850. //populate the bodymatch
  851. if (pos - starttext) >= 0 {
  852. body = substr(body, starttext, starttext+textlength)
  853. } else {
  854. body = ""
  855. }
  856. } else //else just set the bodymatch to the ballparktext
  857. {
  858. //populate the bodymatch
  859. if (pos - starttext) >= 0 {
  860. body = ballparktext
  861. } else {
  862. body = ""
  863. }
  864. }
  865. tRes.Id = id
  866. tRes.Url = url
  867. tRes.Title = html.UnescapeString(title)
  868. tRes.Description = html.UnescapeString(description)
  869. tRes.Body = html.UnescapeString(body)
  870. if json == true {
  871. tRes.Title = JSONRealEscapeString(tRes.Title)
  872. tRes.Description = JSONRealEscapeString(tRes.Description)
  873. tRes.Body = JSONRealEscapeString(tRes.Body)
  874. }
  875. res.DBResults = append(res.DBResults, tRes)
  876. }
  877. defer rows2.Close()
  878. rows2.Close()
  879. }*/
  880. //=======================================================================================================================
  881. //http://go-database-sql.org/retrieving.html
  882. //Close DB
  883. db.Close()
  884. //allow the find more link
  885. if (countResults >= limInt || countResults > 2) && addWildcard == false{
  886. res.FindMore = true
  887. } else {
  888. res.FindMore = false
  889. }
  890. if(pageInt == 0){
  891. pageInt+=2
  892. }else{
  893. pageInt++;
  894. }
  895. res.Page = strconv.Itoa(pageInt)
  896. res.Query = m["q"][0] //get original unsafe query
  897. if json {
  898. w.Header().Set("Content-Type", "application/json")
  899. t, _ := template.ParseFiles("coreassets/json/results.json.go")
  900. t.Execute(w, res)
  901. } else {
  902. t, _ := template.ParseFiles("coreassets/results.html.go")
  903. t.Execute(w, res)
  904. }
  905. }
  906. }
  907. func settings(w http.ResponseWriter, r *http.Request) {
  908. //setup for error report
  909. error := errorReport{}
  910. //check if worksafe (adult content) cookie enabled.
  911. filterHTTPS := false
  912. worksafe := true
  913. worksafewasoff := false
  914. worksafeHTTPSCookie, err := r.Cookie("ws")
  915. if err != nil {
  916. worksafe = true
  917. filterHTTPS = false
  918. } else if worksafeHTTPSCookie.Value == "0" {
  919. worksafe = false
  920. filterHTTPS = false
  921. worksafewasoff = true
  922. } else if worksafeHTTPSCookie.Value == "1" {
  923. worksafe = true
  924. filterHTTPS = false
  925. } else if worksafeHTTPSCookie.Value == "2" {
  926. worksafe = false
  927. filterHTTPS = true
  928. worksafewasoff = true
  929. } else if worksafeHTTPSCookie.Value == "3" {
  930. worksafe = true
  931. filterHTTPS = true
  932. }
  933. //check if and what is the user posting
  934. switch r.Method {
  935. case "POST":
  936. if err := r.ParseForm(); err != nil {
  937. error.Error = err.Error()
  938. t, _ := template.ParseFiles("coreassets/error.html.go")
  939. t.Execute(w, error)
  940. }
  941. worksafebox := r.Form.Get("worksafe")
  942. agreecheck := r.Form.Get("agree")
  943. agreesubmit := r.Form.Get("agreesubmit")
  944. httpsbox := r.Form.Get("filterHTTPS")
  945. //if user agrees to terms to disable adult content, set cookie and return to index
  946. if agreecheck == "on" {
  947. worksafe = false
  948. //expiration := time.Now().Add(365 * 24 * time.Hour)
  949. if filterHTTPS == false {
  950. cookie := http.Cookie{Name: "ws", Value: "0", Path: "/"}
  951. http.SetCookie(w, &cookie)
  952. } else {
  953. cookie := http.Cookie{Name: "ws", Value: "2", Path: "/"}
  954. http.SetCookie(w, &cookie)
  955. }
  956. p := indexPage{}
  957. t, _ := template.ParseFiles("coreassets/settings/gohome.html")
  958. t.Execute(w, p)
  959. //else if worksafebox is checked, return to index with worksafe on
  960. } else if worksafebox == "on" || agreesubmit == "on" {
  961. //expiration := time.Now().Add(365 * 24 * time.Hour)
  962. if httpsbox != "on" {
  963. cookie := http.Cookie{Name: "ws", Value: "1", Path: "/"}
  964. http.SetCookie(w, &cookie)
  965. } else {
  966. cookie := http.Cookie{Name: "ws", Value: "3", Path: "/"}
  967. http.SetCookie(w, &cookie)
  968. }
  969. p := indexPage{}
  970. t, _ := template.ParseFiles("coreassets/settings/gohome.html")
  971. t.Execute(w, p)
  972. //else if worksafebox unchecked and no cookie, go to content agreement section
  973. } else if worksafebox != "on" && worksafewasoff == false && agreesubmit != "on" {
  974. p := indexPage{}
  975. if httpsbox == "on" {
  976. cookie := http.Cookie{Name: "ws", Value: "3", Path: "/"}
  977. http.SetCookie(w, &cookie)
  978. } else {
  979. cookie := http.Cookie{Name: "ws", Value: "1", Path: "/"}
  980. http.SetCookie(w, &cookie)
  981. }
  982. t, _ := template.ParseFiles("coreassets/settings/agree.html.go")
  983. t.Execute(w, p)
  984. //else if worksafebox unchecked and cookie alredy agreed, go back to index
  985. } else if worksafebox != "on" && worksafewasoff == true {
  986. if httpsbox == "on" {
  987. cookie := http.Cookie{Name: "ws", Value: "2", Path: "/"}
  988. http.SetCookie(w, &cookie)
  989. } else {
  990. cookie := http.Cookie{Name: "ws", Value: "0", Path: "/"}
  991. http.SetCookie(w, &cookie)
  992. }
  993. p := indexPage{}
  994. t, _ := template.ParseFiles("coreassets/settings/gohome.html")
  995. t.Execute(w, p)
  996. }
  997. default:
  998. //load the settings page if no post value
  999. settingspage := settingsPage{}
  1000. settingspage.Worksafe = worksafe
  1001. settingspage.FilterHTTPS = filterHTTPS
  1002. t, _ := template.ParseFiles("coreassets/settings/settings.html.go")
  1003. t.Execute(w, settingspage)
  1004. }
  1005. }
  1006. func surprise(w http.ResponseWriter, r *http.Request) {
  1007. surprise := surpriseURL{}
  1008. //check if worksafe+HTTPS cookie enabled.
  1009. filterHTTPS := false
  1010. worksafeHTTPSCookie, err := r.Cookie("ws")
  1011. if err != nil {
  1012. filterHTTPS = false
  1013. } else if worksafeHTTPSCookie.Value == "2" {
  1014. filterHTTPS = true
  1015. } else if worksafeHTTPSCookie.Value == "3" {
  1016. filterHTTPS = true
  1017. }
  1018. //setup for error report
  1019. error := errorReport{}
  1020. //init the db and set charset
  1021. db, err := sql.Open("mysql", "guest:qwer@/wiby?charset=utf8mb4")
  1022. if err != nil {
  1023. error.Error = err.Error()
  1024. t, _ := template.ParseFiles("coreassets/error.html.go")
  1025. t.Execute(w, error)
  1026. }
  1027. defer db.Close()
  1028. // Open doesn't open a connection. Validate DSN data:
  1029. err = db.Ping()
  1030. if err != nil {
  1031. error.Error = err.Error()
  1032. t, _ := template.ParseFiles("coreassets/error.html.go")
  1033. t.Execute(w, error)
  1034. }
  1035. //grab a random page
  1036. var sqlQuery string
  1037. if filterHTTPS == false {
  1038. sqlQuery = "select url from windex where worksafe = 1 and surprise = 1 order by rand() limit 1"
  1039. } else {
  1040. sqlQuery = "select url from windex where worksafe = 1 and surprise = 1 and http = 1 order by rand() limit 1"
  1041. }
  1042. rows, err := db.Query(sqlQuery)
  1043. if err != nil {
  1044. error.Error = err.Error()
  1045. t, _ := template.ParseFiles("coreassets/error.html.go")
  1046. t.Execute(w, error)
  1047. }
  1048. var url string
  1049. for rows.Next() {
  1050. err := rows.Scan(&url)
  1051. if err != nil {
  1052. error.Error = err.Error()
  1053. t, _ := template.ParseFiles("coreassets/error.html.go")
  1054. t.Execute(w, error)
  1055. }
  1056. surprise.Url = url
  1057. }
  1058. defer rows.Close()
  1059. rows.Close()
  1060. db.Close()
  1061. t, _ := template.ParseFiles("coreassets/surprise.html.go")
  1062. t.Execute(w, surprise)
  1063. }
  1064. func MysqlRealEscapeString(value string) string {
  1065. replace := map[string]string{"\\": "\\\\", "'": `\'`, "\\0": "\\\\0", "\n": "\\n", "\r": "\\r", `"`: `\"`, "\x1a": "\\Z"}
  1066. for b, a := range replace {
  1067. value = strings.Replace(value, b, a, -1)
  1068. }
  1069. return value
  1070. }
  1071. func JSONRealEscapeString(value string) string {
  1072. replace := map[string]string{"\\": "\\\\", "\t": "\\t", "\b": "\\b", "\n": "\\n", "\r": "\\r", "\f": "\\f" /*, `"`:`\"`*/}
  1073. for b, a := range replace {
  1074. value = strings.Replace(value, b, a, -1)
  1075. }
  1076. //remove control characters
  1077. buf := []rune(value)
  1078. for i, v := range buf {
  1079. if v < 32 || v == 127 {
  1080. buf[i]=32
  1081. }
  1082. }
  1083. return string(buf)
  1084. }
  1085. func substr(s string, start int, end int) string {
  1086. start_str_idx := 0
  1087. i := 0
  1088. for j := range s {
  1089. if i == start {
  1090. start_str_idx = j
  1091. }
  1092. if i == end {
  1093. return s[start_str_idx:j]
  1094. }
  1095. i++
  1096. }
  1097. return s[start_str_idx:]
  1098. }
  1099. func searchredirect(w http.ResponseWriter, r *http.Request, query string) {
  1100. //separate actual query from search redirect
  1101. actualquery := ""
  1102. redirect := ""
  1103. lenquery := len(query)
  1104. if strings.Index(query," ") > -1{
  1105. location := strings.Index(query, " !")
  1106. if location == -1 {
  1107. location = strings.Index(query, " &")
  1108. }
  1109. if location > -1 && strings.Index(query[location+1:lenquery], " ") == -1 { //redirect is at end of query
  1110. redirect = query[location+2 : lenquery]
  1111. actualquery = query[:location]
  1112. } else if (strings.Index(query, "!") == 0 || strings.Index(query, "&") == 0){ //redirect is at start of query
  1113. redirect = query[1:strings.Index(query, " ")]
  1114. actualquery = query[strings.Index(query, " ")+1:]
  1115. //fmt.Printf("\nRedirect: %s\nquery: %s\n",redirect,actualquery)
  1116. }
  1117. redirect = strings.ToLower(redirect)
  1118. }else if (query[0] == '!' || query[0] == '&') && lenquery > 1{
  1119. redirect = query[1:]
  1120. }
  1121. if redirect != "" {
  1122. //determine which search engine to redirect
  1123. if redirect == "g" { //if google text search
  1124. http.Redirect(w, r, "http://google.com/search?q="+actualquery, http.StatusSeeOther)
  1125. } else if redirect == "b" { //if bing text search
  1126. http.Redirect(w, r, "http://bing.com/search?q="+actualquery, http.StatusSeeOther)
  1127. } else if redirect == "gi" { //if google image search
  1128. http.Redirect(w, r, "http://www.google.com/search?tbm=isch&q="+actualquery, http.StatusSeeOther)
  1129. } else if redirect == "bi" { //if bing image search
  1130. http.Redirect(w, r, "http://www.bing.com/images/search?q="+actualquery, http.StatusSeeOther)
  1131. } else if redirect == "gv" { //if google video search
  1132. http.Redirect(w, r, "http://www.google.com/search?tbm=vid&q="+actualquery, http.StatusSeeOther)
  1133. } else if redirect == "bv" { //if bing video search
  1134. http.Redirect(w, r, "http://www.bing.com/videos/search?q="+actualquery, http.StatusSeeOther)
  1135. } else if redirect == "gm" { //if google maps search
  1136. http.Redirect(w, r, "http://www.google.com/maps/search/"+actualquery, http.StatusSeeOther)
  1137. } else if redirect == "bm" { //if bing maps search
  1138. http.Redirect(w, r, "http://www.bing.com/maps?q="+actualquery, http.StatusSeeOther)
  1139. }/* else {
  1140. http.Redirect(w, r, "/?q="+actualquery, http.StatusSeeOther)
  1141. }*/
  1142. }
  1143. }
  1144. func distributedQuery(con string, sqlQuery string, startID string, endID string, idListChan chan<- string) {
  1145. var id string
  1146. var idList string
  1147. count := 0
  1148. //defer wg.Done()
  1149. //init the db
  1150. db, err := sql.Open("mysql", con)
  1151. if err != nil {
  1152. idList = idList + "e" //will look for this when channels are processed
  1153. }
  1154. defer db.Close()
  1155. // If Open doesn't open a connection. Validate DSN data:
  1156. err = db.Ping()
  1157. if err != nil {
  1158. }
  1159. //fmt.Printf("%s\n", sqlQuery)
  1160. // Send the query
  1161. rows, err := db.Query(sqlQuery)
  1162. if err == nil {
  1163. for rows.Next() {
  1164. err := rows.Scan(&id)
  1165. if err != nil {
  1166. }
  1167. //idString = idstring + "id = " + id + " or "
  1168. idList += "," + id
  1169. count++
  1170. }
  1171. } else {
  1172. idList = idList + "e" //will look for this when channels are processed
  1173. fmt.Printf("%s", err)
  1174. }
  1175. //fmt.Printf("%s - %s\n", idList,con)
  1176. idListChan <- idList
  1177. }