<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <!-- Using https://realfavicongenerator.net to generate this -->
  <link rel="apple-touch-icon" sizes="180x180" href="icons/apple-touch-icon.png">
  <link rel="icon" type="image/png" sizes="32x32" href="icons/favicon-32x32.png">
  <link rel="icon" type="image/png" sizes="16x16" href="icons/favicon-16x16.png">
  <link rel="manifest" href="icons/site.webmanifest">
  <link rel="mask-icon" href="icons/safari-pinned-tab.svg" color="#5bbad5">
  <meta name="msapplication-TileColor" content="#da532c">
  <meta name="theme-color" content="#ffffff">


  <link rel="stylesheet" href="data/css.css">
  <title>Dhamma Full Text Search</title>
	
  <script src="data/paliScriptConverter.js" defer></script>
  <script src="data/nbn.js" defer></script>
	
</head>

<body>
  <div id="uForm">
    <form method="POST" action="" enctype="multipart/form-data" style="padding: 5px;">

      <b>Dhamma Full Text Search v1.0.0</b>

      <table class="tCenter">
        <tr>
          <td class="tRight">
            <span class="greyText">Database</span>
            <label class="form-switch"><input type="radio" id="palitptk" name="database" value="palitptk"><i></i></label>
          </td>
          <td class="tLeft">Pāḷi tipiṭaka</td>
          <td class="tRight">
            <label disabled class="form-switch"><input type="radio" id="dictionary" name="database" value="dictionary"><i></i></label>
          </td>
          <td class="tLeft">Pāḷi Dictionary</td>
        </tr>
        <tr></tr>
        <tr></tr>
        <tr>
          <td class="tRight">
            <label disabled class="form-switch"><input checked type="radio" id="elibrary" name="database" value="elibrary"><i></i></label>
          </td>
          <td class="tLeft">Pa-Auk Manual</td>
          <td class="tRight">
            <label disabled class="form-switch"><input type="radio" id="ttpv_budsas.net" name="database" value="ttpv_budsas.net"><i></i></label>
          </td>
          <td class="tLeft">TTPViet - Budsas.net</td>
        </tr>
      </table>

      <!-- Select elements generated by Javascript must be inside this form element to allow $_POST to catch -->
      <!-- <p style="display:none;" id="buildPaliScriptMenu">Use static HTML code for faster</p> -->
      <p style="display:none;" id="buildPaliScriptMenu">
        <label for="uSelectScript">Pāḷi tipiṭaka display script</label>
        <select id="uSelectScript" name="uSelectScript">
          <option disabled="" value="">--Please choose an option--</option>
          <option value="si">Sinhala - සිංහල</option>
          <option value="hi">Devanagari - हिन्दी</option>
          <option value="ro">Roman - Roman</option>
          <option value="th">Thai - ไทย</option>
          <option value="lo">Laos - ລາວ</option>
          <option value="my">Myanmar - ဗမာစာ</option>
          <option value="km">Khmer - ភាសាខ្មែរ</option>
          <option value="be">Bengali - বাংলা</option>
          <option value="gm">Gurmukhi - ਗੁਰਮੁਖੀ</option>
          <option value="gj">Gujarati - ગુજરાતી</option>
          <option value="te">Telugu - తెలుగు</option>
          <option value="ka">Kannada - ಕನ್ನಡ</option>
          <option value="mm">Malayalam - മലയാളം</option>
          <option value="tt">Tai Tham - Tai Tham LN</option>
          <option value="br">Brahmi - Brāhmī</option>
          <option value="tb">Tibetan - བོད་སྐད།</option>
          <option value="cy">Cyrillic - кириллица</option>
        </select>
      </p>


      <textarea required rows="2" id="uType" name="uType" placeholder="can type Roman pāḷi with Velthuis scheme" value=""></textarea><br>
      <span id="clearText" onclick="clearTextArea()">Clear Text</span><br><br>

      <table class="tCenter">
        <tr>
          <td class="tRight">
            <span class="greyText">Search Mode</span>
            <label class="form-switch"><input checked type="radio" id="dts" name="sMode" value="dts" /><i></i></label>
          </td>
          <td class="tLeft">Word distance</td>
          <td class="tRight">
            <label class="form-switch"><input type="radio" id="fts" name="sMode" value="fts" /><i></i></label>
          </td>
          <td class="tLeft">Exactly match</td>
        </tr>
        <tr></tr>
        <tr></tr>
        <tr>
          <td class="tRight">
            <label class="form-switch"><input type="radio" id="sms" name="sMode" value="sms" /><i></i></label>
          </td>
          <td class="tLeft">Simple match</td>
          <td class="tRight">
            <label class="form-switch"><input type="radio" id="pfs" name="sMode" value="pfs" /><i></i></label>
          </td>
          <td class="tLeft">Prefix</td>
        </tr>
      </table>

      <br>Order by <label class="circleRadio"><input checked type="radio" id="rank" name="order" value="rank" /> Rank</label>
      <label class="circleRadio" style="font-weight:lighter;"><input type="radio" id="path" name="order" value="path" /> File path</label>
      <label class="circleRadio"><input type="radio" id="bm25" name="order" value="bm25" /> BM25</label>

      <table class="tCenter">
        <tr>
          <td class="tLeft">Word distance range</td>
          <td class="tLeft"><input id="dval" name="dval" value="10" placeholder="in distance mode" /></td>
        </tr>
        <tr>
          <td class="tLeft">Extract text length</td>
          <td class="tLeft"><input id="etl" name="etl" value="64" placeholder="Accept: 0-64" /></td>
        </tr>
        <tr>
          <td class="tLeft">Limit hit fragment</td>
          <td class="tLeft"><input id="limit" name="limit" value="999" placeholder="9999" /></td>
        </tr>
      </table>

      <br>
      <button id="searchButton" type="submit" onclick="onClickSubmit('uType','uType2')"> Search </button>
      <div style="display: none;">
        <!-- For converted pāḷi script  -->
        <textarea id="uType2" name="uType2" value=""></textarea>
      </div>
    </form>
  </div>

  <div id="allResults"><br>

    <?php

    /*--------------------------------
     * pnry 09 Nov 2020
     * Last modified: 19 Dec 2020
     * Github: https://github.com/vpnry/dhammafts
     * Live: https://sadhu.herokuapp.com
	 
     * Query for indexed sqlite3 fts5 db
     * License: for free distribution only; no responsibilites.

     * TODO: escapse some special chars like ,'` etc. in the query,
     * currently it does not work if the query contains these chars

     * Security notes:
     * ===============
     * The query syntax below may not be so secure, 
     * just quick and easy implement for localhost use.
     * Try to improve it if you want to use it in a serious online production.
     * -------------------------------*/

    mb_internal_encoding("UTF-8");

    if (isset($_POST['uType'])) {

      // table name: pn, columns: path, cont

      /*--------------------------------*/
      $typing = trim($_POST['uType']);
      $selectedDB = $_POST['database'];
      $selectedPScript = $_POST['uSelectScript'];
      $sMode = $_POST['sMode'];
      $dval = (int)$_POST['dval'];
      $etl = $_POST['etl'];
      $limit = $_POST['limit'];
      $sortBy = $_POST['order'];
      /*--------------------------------*/


      $sortByEchoRember = $sortBy;
      if ($sortBy == 'bm25') {
        $sortBy = "bm25(pn)";
        $sortByEchoRember = 'bm25';
      }

      $u1 = "<u>";
      $u2 = "</u>";
      if ($selectedPScript != 'ro' && $selectedDB == "palitptk") {
        $u1 = "@_@"; // Escapse pali converter as it also converts <u>
        $u2 = "@__@";
        $uType2 = trim($_POST['uType2']);
        if (strlen($uType2) > 0) {
          $typing = $uType2;
        }
      }

      $typingJS = str_replace('`', '\`', $typing);
      $typingEcho = $typing;
      $snippetType = "snippet(pn, 1, '" . $u1 . "', '" . $u2 . "', ' ~~ '," . $etl . ")";
      if ($etl > 64) {
        $etl = 64;
      } else if ($etl == 0) {
        $snippetType = "highlight(pn, 0, '', '')";
      }

      if ($selectedDB == 'palitptk') {
        $dbConnection = new SQLite3("data/tptk.sqlite3");
        include_once("data/tipitakaAppfileTitle.php");
      } else if ($selectedDB == 'ttpv_budsas.net') {
        $dbConnection = new SQLite3("data/ttpv_budsas.net.sqlite3");
      } else if ($selectedDB == 'elibrary') {
        $dbConnection = new SQLite3("data/paaukmed.sqlite3");
      } else if ($selectedDB == 'dictionary') {
        $dbConnection = new SQLite3("data/palidict.sqlite3");
      }



      // ----------------------------------------------------------
      // TODO: IMPROVE THIS ESCAPE STRING PROPERLY
      // ----------------------------------------------------------
      $typing = str_replace('"', '', $typing);
      $typing = SQLite3::escapeString($typing);

      if ($sMode == 'dts') {
        $sql = <<<NBN
SELECT path, $snippetType cont FROM pn WHERE cont MATCH 'NEAR("$typing", $dval)' ORDER BY $sortBy LIMIT $limit
NBN;
      } else if ($sMode == 'fts') {
        $sql = <<<NBN
SELECT path, $snippetType cont FROM pn WHERE cont MATCH '"$typing"' ORDER BY $sortBy LIMIT $limit
NBN;
      } else if ($sMode == 'sms') {
        // Thanks https://stackoverflow.com/a/1612015
        // MATCH "$typing" will simply list all docs that contain all of the word in the phrase
        // If the keywords contain any of ,.' and so on, it will yield errors
        $typing = preg_replace("/[^\p{L}\p{Nd}]+/u", " ", $typing);
        $typing = trim($typing);
        $sql = <<<NBN
SELECT path, $snippetType cont FROM pn WHERE cont MATCH "$typing" ORDER BY $sortBy LIMIT $limit
NBN;
      } else if ($sMode == 'pfs') {
        $sql = <<<NBN
SELECT path, $snippetType cont FROM pn WHERE cont MATCH '"$typing" * ' ORDER BY $sortBy LIMIT $limit
NBN;
      }

      $result = $dbConnection->query($sql);
      $merges = [];
      $totalHit = 0;
      while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
        $totalHit++;
        $p = $row['path'];
        // this extra append </b> fix bold issues
        $c = '<span class="fm" id="cc' . $totalHit . '"> <z>(' . $totalHit . ')</z> ' . $row['cont'] . ' </span></b>';
        if (array_key_exists($p, $merges)) {
          $merges[$p][] = $c;
        } else {
          $merges[$p] = [$c];
        }
      }

      $resultHTML = "";
      $totalFilesFound = 0;
      if (count($merges) > 0) {
        foreach ($merges as $k => $te) {
          $totalFilesFound++;
          $k = trim($k);
          $k = substr($k, 0, -4); //.txt
          $kMapTitle = $k;
          $fileLink = 'data/' . $k;
          $fcode = end(explode("/", $k));
          if ($selectedDB == 'palitptk') {
            $kMapTitle = $tipitakaAppfileTitle[$fcode] . " (" . $fcode . ")";
            $fileLink = 'https://tipitaka.app/?a=' . $fcode . '-1-' . $selectedPScript;
          } else if ($selectedDB == 'ttpv_budsas.net') {
            $klen = strlen($k);
            $isBudsasNet = substr($k, 3, 10); //vi/budsas.net
            if ($isBudsasNet == 'budsas.net') {
              $fileLink = 'https://' . substr($k, 3, $klen);
            } else {
              $fileLink = ' https://tamtangpaliviet.net/TTPV/' . substr($k, 8, $klen);
            }
          }
          // this extra prepend </b> fix bold issues
          $resultHTML .= '</b><div class="title" onclick="sh(' . $totalFilesFound . ')" id="te' . $totalFilesFound . '">' . '<c> ' . $totalFilesFound . '</c>' . '<d> Hits: {' . count($te) . '}</d><a target="_blank" href="' . $fileLink . '"> ' . $kMapTitle . "</a></div>";
          $resultHTML .= "\n<div class='hid' id='ce" . $totalFilesFound . "'>" . join("<br><br>\n", $te) . "\n</div><br>\n";
        }
      }


      $rememberChoice = <<<NBN
      <script>
        var totalFilesFound = $totalFilesFound;
        document.getElementById("$selectedDB").checked = true;
        document.getElementById("$sortByEchoRember").checked = true;
        document.getElementById("$sMode").checked = true;
        document.getElementById("uType").value = `$typingJS` ;
        document.getElementById("dval").value = $dval;
        document.getElementById("etl").value = $etl;
        document.getElementById("limit").value = $limit;
		if(document.getElementById("palitptk").checked) { document.getElementById("buildPaliScriptMenu").style.display = "";}
      </script>
NBN;

      echo $rememberChoice;

      if (count($merges) < 1) {
        echo "<div id='noResult'>No results!<br>Try again with <u><b>Simple match</b></u> or other search modes, or check your keywords again.<br>
        <br><b>Notes:</b> all keywords must be in <u><b>unicode</b></u>.<br>If your 'copy & paste' text from a certain book does not work here, try typing yourself again in <b>unicode</b>, normally a few words are enough!</div>";
        return;
      }


      // ----------------------------------------------------------
      // IF HAVE RESULT
      // ----------------------------------------------------------

      echo "Query: <code>" . $typingEcho . "</code><br>";
      echo "Code: <code>" . $sql . "</code><br>";
      echo "Limit hit setting: <b>" . $limit . "</b>";
      echo " | Total files: <b>" . $totalFilesFound . "</b> | Total hits: <b>" . $totalHit . "</b>";

      if ($totalHit == $limit) {
        echo (" | Need <u>more results?</u> Increase <b>Limit hit fragments</b>. 
        <div style='text-align: center; color:grey;'>Click on each title to hide/show its content. Or <button id='toggleButton' onclick='toggleHideAll(" . $totalFilesFound . ")'>Show All</button></div> <br>");
      } else {
        echo (" <div style='text-align: center; color:grey;'>Click on each title to hide/show its content. Or <button id='toggleButton' onclick='toggleHideAll(" . $totalFilesFound . ")'>Show All</button></div> <br>");
      }

      echo $resultHTML;

      if (($selectedPScript != 'ro') && ($selectedDB == 'palitptk')) {
        $convertPaliScript = <<<NBN
        <script>
          setTimeout(function () {convertPaliContent($totalFilesFound, $totalHit, "$selectedPScript");},500);
        </script>
NBN;
        echo $convertPaliScript;
      }
    } else {

      $velthuisTable = <<<NBN
		<div id='velthuis'>
		<table class="tCenter">
		<tr><th colspan=8>Modified Velthuis scheme:</th></tr>
	 	<tr>
		<td colspan=8>Type & get, example: aa => ā</td>
		</tr>
	 	<tr><td class="tCenter">aa</td><td class="tCenter">ā</td>
       	<td class="tCenter">ii</td><td class="tCenter">ī</td>
       	<td class="tCenter">uu</td><td class="tCenter">ū</td>
       	<td class="tCenter">m..</td><td class="tCenter">ṁ</td>
		</tr>
       	<tr><td class="tCenter">.m</td><td class="tCenter">ṃ</td>
       	<td class="tCenter">.n</td><td class="tCenter">ṇ</td>
       	<td class="tCenter">.d</td><td class="tCenter">ḍ</td>
       	<td class="tCenter">.l</td><td class="tCenter">ḷ</td>
		</tr>
       	<tr><td class="tCenter">.r</td><td class="tCenter">ṛ</td>
       	<td class="tCenter">.s</td><td class="tCenter">ṣ</td>
       	<td class="tCenter">s..</td><td class="tCenter">ś</td>
       	<td class="tCenter">.t</td><td class="tCenter">ṭ</td>
		</tr>
       	<tr><td class="tCenter">,,n</td><td class="tCenter">ñ</td>
       	<td class="tCenter">n..</td><td class="tCenter">ṅ</td>
		</tr>
    </table>
    </div>
NBN;

      echo ("<p class='center' ><a href='data/README.html'>Read me</a></p>");
      echo $velthuisTable;
    }



    ?>

    <br>

  </div>
</body>

</html>
