Home | History | Annotate | Line # | Download | only in makemandb
apropos-utils.c revision 1.4
      1  1.4    wiz /*	$NetBSD: apropos-utils.c,v 1.4 2012/04/15 15:56:52 wiz Exp $	*/
      2  1.1  joerg /*-
      3  1.1  joerg  * Copyright (c) 2011 Abhinav Upadhyay <er.abhinav.upadhyay (at) gmail.com>
      4  1.1  joerg  * All rights reserved.
      5  1.1  joerg  *
      6  1.1  joerg  * This code was developed as part of Google's Summer of Code 2011 program.
      7  1.1  joerg  *
      8  1.1  joerg  * Redistribution and use in source and binary forms, with or without
      9  1.1  joerg  * modification, are permitted provided that the following conditions
     10  1.1  joerg  * are met:
     11  1.1  joerg  *
     12  1.1  joerg  * 1. Redistributions of source code must retain the above copyright
     13  1.1  joerg  *    notice, this list of conditions and the following disclaimer.
     14  1.1  joerg  * 2. Redistributions in binary form must reproduce the above copyright
     15  1.1  joerg  *    notice, this list of conditions and the following disclaimer in
     16  1.1  joerg  *    the documentation and/or other materials provided with the
     17  1.1  joerg  *    distribution.
     18  1.1  joerg  *
     19  1.1  joerg  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
     20  1.1  joerg  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
     21  1.1  joerg  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
     22  1.1  joerg  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
     23  1.1  joerg  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
     24  1.1  joerg  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
     25  1.1  joerg  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
     26  1.1  joerg  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
     27  1.1  joerg  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
     28  1.1  joerg  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
     29  1.1  joerg  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     30  1.1  joerg  * SUCH DAMAGE.
     31  1.1  joerg  */
     32  1.1  joerg 
     33  1.1  joerg #include <sys/cdefs.h>
     34  1.4    wiz __RCSID("$NetBSD: apropos-utils.c,v 1.4 2012/04/15 15:56:52 wiz Exp $");
     35  1.1  joerg 
     36  1.1  joerg #include <sys/stat.h>
     37  1.1  joerg 
     38  1.1  joerg #include <assert.h>
     39  1.1  joerg #include <ctype.h>
     40  1.1  joerg #include <err.h>
     41  1.1  joerg #include <math.h>
     42  1.1  joerg #include <stdio.h>
     43  1.1  joerg #include <stdlib.h>
     44  1.1  joerg #include <string.h>
     45  1.1  joerg #include <util.h>
     46  1.1  joerg #include <zlib.h>
     47  1.1  joerg 
     48  1.1  joerg #include "apropos-utils.h"
     49  1.1  joerg #include "mandoc.h"
     50  1.1  joerg #include "sqlite3.h"
     51  1.1  joerg 
     52  1.1  joerg typedef struct orig_callback_data {
     53  1.1  joerg 	void *data;
     54  1.1  joerg 	int (*callback) (void *, const char *, const char *, const char *,
     55  1.1  joerg 		const char *, size_t);
     56  1.1  joerg } orig_callback_data;
     57  1.1  joerg 
     58  1.1  joerg typedef struct inverse_document_frequency {
     59  1.1  joerg 	double value;
     60  1.1  joerg 	int status;
     61  1.1  joerg } inverse_document_frequency;
     62  1.1  joerg 
     63  1.1  joerg /* weights for individual columns */
     64  1.1  joerg static const double col_weights[] = {
     65  1.1  joerg 	2.0,	// NAME
     66  1.1  joerg 	2.00,	// Name-description
     67  1.1  joerg 	0.55,	// DESCRIPTION
     68  1.1  joerg 	0.10,	// LIBRARY
     69  1.1  joerg 	0.001,	//RETURN VALUES
     70  1.1  joerg 	0.20,	//ENVIRONMENT
     71  1.1  joerg 	0.01,	//FILES
     72  1.1  joerg 	0.001,	//EXIT STATUS
     73  1.1  joerg 	2.00,	//DIAGNOSTICS
     74  1.1  joerg 	0.05,	//ERRORS
     75  1.1  joerg 	0.00,	//md5_hash
     76  1.1  joerg 	1.00	//machine
     77  1.1  joerg };
     78  1.1  joerg 
     79  1.1  joerg /*
     80  1.1  joerg  * lower --
     81  1.1  joerg  *  Converts the string str to lower case
     82  1.1  joerg  */
     83  1.1  joerg char *
     84  1.1  joerg lower(char *str)
     85  1.1  joerg {
     86  1.1  joerg 	assert(str);
     87  1.1  joerg 	int i = 0;
     88  1.1  joerg 	char c;
     89  1.1  joerg 	while (str[i] != '\0') {
     90  1.1  joerg 		c = tolower((unsigned char) str[i]);
     91  1.1  joerg 		str[i++] = c;
     92  1.1  joerg 	}
     93  1.1  joerg 	return str;
     94  1.1  joerg }
     95  1.1  joerg 
     96  1.1  joerg /*
     97  1.1  joerg * concat--
     98  1.1  joerg *  Utility function. Concatenates together: dst, a space character and src.
     99  1.1  joerg * dst + " " + src
    100  1.1  joerg */
    101  1.1  joerg void
    102  1.1  joerg concat(char **dst, const char *src)
    103  1.1  joerg {
    104  1.1  joerg 	concat2(dst, src, strlen(src));
    105  1.1  joerg }
    106  1.1  joerg 
    107  1.1  joerg void
    108  1.1  joerg concat2(char **dst, const char *src, size_t srclen)
    109  1.1  joerg {
    110  1.1  joerg 	size_t total_len, dst_len;
    111  1.1  joerg 	assert(src != NULL);
    112  1.1  joerg 
    113  1.1  joerg 	/* If destination buffer dst is NULL, then simply strdup the source buffer */
    114  1.1  joerg 	if (*dst == NULL) {
    115  1.1  joerg 		*dst = estrdup(src);
    116  1.1  joerg 		return;
    117  1.1  joerg 	}
    118  1.1  joerg 
    119  1.1  joerg 	dst_len = strlen(*dst);
    120  1.1  joerg 	/*
    121  1.1  joerg 	 * NUL Byte and separator space
    122  1.1  joerg 	 */
    123  1.1  joerg 	total_len = dst_len + srclen + 2;
    124  1.1  joerg 
    125  1.1  joerg 	*dst = erealloc(*dst, total_len);
    126  1.1  joerg 
    127  1.1  joerg 	/* Append a space at the end of dst */
    128  1.1  joerg 	(*dst)[dst_len++] = ' ';
    129  1.1  joerg 
    130  1.1  joerg 	/* Now, copy src at the end of dst */
    131  1.1  joerg 	memcpy(*dst + dst_len, src, srclen + 1);
    132  1.1  joerg }
    133  1.1  joerg 
    134  1.1  joerg void
    135  1.1  joerg close_db(sqlite3 *db)
    136  1.1  joerg {
    137  1.1  joerg 	sqlite3_close(db);
    138  1.1  joerg 	sqlite3_shutdown();
    139  1.1  joerg }
    140  1.1  joerg 
    141  1.1  joerg /*
    142  1.1  joerg  * create_db --
    143  1.1  joerg  *  Creates the database schema.
    144  1.1  joerg  */
    145  1.1  joerg static int
    146  1.1  joerg create_db(sqlite3 *db)
    147  1.1  joerg {
    148  1.1  joerg 	const char *sqlstr = NULL;
    149  1.1  joerg 	char *schemasql;
    150  1.1  joerg 	char *errmsg = NULL;
    151  1.1  joerg 
    152  1.1  joerg /*------------------------ Create the tables------------------------------*/
    153  1.1  joerg 
    154  1.1  joerg #if NOTYET
    155  1.1  joerg 	sqlite3_exec(db, "PRAGMA journal_mode = WAL", NULL, NULL, NULL);
    156  1.1  joerg #else
    157  1.1  joerg 	sqlite3_exec(db, "PRAGMA journal_mode = DELETE", NULL, NULL, NULL);
    158  1.1  joerg #endif
    159  1.1  joerg 
    160  1.1  joerg 	schemasql = sqlite3_mprintf("PRAGMA user_version = %d",
    161  1.1  joerg 	    APROPOS_SCHEMA_VERSION);
    162  1.1  joerg 	sqlite3_exec(db, schemasql, NULL, NULL, &errmsg);
    163  1.1  joerg 	if (errmsg != NULL)
    164  1.1  joerg 		goto out;
    165  1.1  joerg 	sqlite3_free(schemasql);
    166  1.1  joerg 
    167  1.1  joerg 	sqlstr = "CREATE VIRTUAL TABLE mandb USING fts4(section, name, "
    168  1.1  joerg 			    "name_desc, desc, lib, return_vals, env, files, "
    169  1.1  joerg 			    "exit_status, diagnostics, errors, md5_hash UNIQUE, machine, "
    170  1.1  joerg 			    "compress=zip, uncompress=unzip, tokenize=porter); "	//mandb
    171  1.1  joerg 			"CREATE TABLE IF NOT EXISTS mandb_meta(device, inode, mtime, "
    172  1.1  joerg 			    "file UNIQUE, md5_hash UNIQUE, id  INTEGER PRIMARY KEY); "
    173  1.1  joerg 				//mandb_meta
    174  1.1  joerg 			"CREATE TABLE IF NOT EXISTS mandb_links(link, target, section, "
    175  1.1  joerg 			    "machine); ";	//mandb_links
    176  1.1  joerg 
    177  1.1  joerg 	sqlite3_exec(db, sqlstr, NULL, NULL, &errmsg);
    178  1.1  joerg 	if (errmsg != NULL)
    179  1.1  joerg 		goto out;
    180  1.1  joerg 
    181  1.1  joerg 	sqlstr = "CREATE INDEX IF NOT EXISTS index_mandb_links ON mandb_links "
    182  1.1  joerg 			"(link); "
    183  1.1  joerg 			"CREATE INDEX IF NOT EXISTS index_mandb_meta_dev ON mandb_meta "
    184  1.1  joerg 			"(device, inode)";
    185  1.1  joerg 	sqlite3_exec(db, sqlstr, NULL, NULL, &errmsg);
    186  1.1  joerg 	if (errmsg != NULL)
    187  1.1  joerg 		goto out;
    188  1.1  joerg 	return 0;
    189  1.1  joerg 
    190  1.1  joerg out:
    191  1.1  joerg 	warnx("%s", errmsg);
    192  1.1  joerg 	free(errmsg);
    193  1.1  joerg 	sqlite3_close(db);
    194  1.1  joerg 	sqlite3_shutdown();
    195  1.1  joerg 	return -1;
    196  1.1  joerg }
    197  1.1  joerg 
    198  1.1  joerg /*
    199  1.1  joerg  * zip --
    200  1.1  joerg  *  User defined Sqlite function to compress the FTS table
    201  1.1  joerg  */
    202  1.1  joerg static void
    203  1.1  joerg zip(sqlite3_context *pctx, int nval, sqlite3_value **apval)
    204  1.1  joerg {
    205  1.1  joerg 	int nin;
    206  1.1  joerg 	long int nout;
    207  1.1  joerg 	const unsigned char * inbuf;
    208  1.1  joerg 	unsigned char *outbuf;
    209  1.1  joerg 
    210  1.1  joerg 	assert(nval == 1);
    211  1.1  joerg 	nin = sqlite3_value_bytes(apval[0]);
    212  1.1  joerg 	inbuf = (const unsigned char *) sqlite3_value_blob(apval[0]);
    213  1.1  joerg 	nout = nin + 13 + (nin + 999) / 1000;
    214  1.1  joerg 	outbuf = emalloc(nout);
    215  1.1  joerg 	compress(outbuf, (unsigned long *) &nout, inbuf, nin);
    216  1.1  joerg 	sqlite3_result_blob(pctx, outbuf, nout, free);
    217  1.1  joerg }
    218  1.1  joerg 
    219  1.1  joerg /*
    220  1.1  joerg  * unzip --
    221  1.1  joerg  *  User defined Sqlite function to uncompress the FTS table.
    222  1.1  joerg  */
    223  1.1  joerg static void
    224  1.1  joerg unzip(sqlite3_context *pctx, int nval, sqlite3_value **apval)
    225  1.1  joerg {
    226  1.1  joerg 	unsigned int rc;
    227  1.1  joerg 	unsigned char *outbuf;
    228  1.1  joerg 	z_stream stream;
    229  1.1  joerg 
    230  1.1  joerg 	assert(nval == 1);
    231  1.1  joerg 	stream.next_in = __UNCONST(sqlite3_value_blob(apval[0]));
    232  1.1  joerg 	stream.avail_in = sqlite3_value_bytes(apval[0]);
    233  1.1  joerg 	stream.avail_out = stream.avail_in * 2 + 100;
    234  1.1  joerg 	stream.next_out = outbuf = emalloc(stream.avail_out);
    235  1.1  joerg 	stream.zalloc = NULL;
    236  1.1  joerg 	stream.zfree = NULL;
    237  1.1  joerg 
    238  1.1  joerg 	if (inflateInit(&stream) != Z_OK) {
    239  1.1  joerg 		free(outbuf);
    240  1.1  joerg 		return;
    241  1.1  joerg 	}
    242  1.1  joerg 
    243  1.1  joerg 	while ((rc = inflate(&stream, Z_SYNC_FLUSH)) != Z_STREAM_END) {
    244  1.1  joerg 		if (rc != Z_OK ||
    245  1.1  joerg 		    (stream.avail_out != 0 && stream.avail_in == 0)) {
    246  1.1  joerg 			free(outbuf);
    247  1.1  joerg 			return;
    248  1.1  joerg 		}
    249  1.1  joerg 		outbuf = erealloc(outbuf, stream.total_out * 2);
    250  1.1  joerg 		stream.next_out = outbuf + stream.total_out;
    251  1.1  joerg 		stream.avail_out = stream.total_out;
    252  1.1  joerg 	}
    253  1.1  joerg 	if (inflateEnd(&stream) != Z_OK) {
    254  1.1  joerg 		free(outbuf);
    255  1.1  joerg 		return;
    256  1.1  joerg 	}
    257  1.1  joerg 	outbuf = erealloc(outbuf, stream.total_out);
    258  1.1  joerg 	sqlite3_result_text(pctx, (const char *) outbuf, stream.total_out, free);
    259  1.1  joerg }
    260  1.1  joerg 
    261  1.1  joerg /* init_db --
    262  1.1  joerg  *   Prepare the database. Register the compress/uncompress functions and the
    263  1.1  joerg  *   stopword tokenizer.
    264  1.1  joerg  *	 db_flag specifies the mode in which to open the database. 3 options are
    265  1.1  joerg  *   available:
    266  1.1  joerg  *   	1. DB_READONLY: Open in READONLY mode. An error if db does not exist.
    267  1.1  joerg  *  	2. DB_READWRITE: Open in read-write mode. An error if db does not exist.
    268  1.1  joerg  *  	3. DB_CREATE: Open in read-write mode. It will try to create the db if
    269  1.1  joerg  *			it does not exist already.
    270  1.1  joerg  *  RETURN VALUES:
    271  1.1  joerg  *		The function will return NULL in case the db does not exist and DB_CREATE
    272  1.1  joerg  *  	was not specified. And in case DB_CREATE was specified and yet NULL is
    273  1.1  joerg  *  	returned, then there was some other error.
    274  1.1  joerg  *  	In normal cases the function should return a handle to the db.
    275  1.1  joerg  */
    276  1.1  joerg sqlite3 *
    277  1.1  joerg init_db(int db_flag)
    278  1.1  joerg {
    279  1.1  joerg 	sqlite3 *db = NULL;
    280  1.1  joerg 	sqlite3_stmt *stmt;
    281  1.1  joerg 	struct stat sb;
    282  1.1  joerg 	int rc;
    283  1.1  joerg 	int create_db_flag = 0;
    284  1.1  joerg 
    285  1.1  joerg 	/* Check if the database exists or not */
    286  1.1  joerg 	if (!(stat(DBPATH, &sb) == 0 && S_ISREG(sb.st_mode))) {
    287  1.1  joerg 		/* Database does not exist, check if DB_CREATE was specified, and set
    288  1.1  joerg 		 * flag to create the database schema
    289  1.1  joerg 		 */
    290  1.1  joerg 		if (db_flag != (MANDB_CREATE)) {
    291  1.1  joerg 			warnx("Missing apropos database. "
    292  1.1  joerg 			      "Please run makemandb to create it.");
    293  1.1  joerg 			return NULL;
    294  1.1  joerg 		}
    295  1.1  joerg 		create_db_flag = 1;
    296  1.1  joerg 	}
    297  1.1  joerg 
    298  1.1  joerg 	/* Now initialize the database connection */
    299  1.1  joerg 	sqlite3_initialize();
    300  1.1  joerg 	rc = sqlite3_open_v2(DBPATH, &db, db_flag, NULL);
    301  1.1  joerg 
    302  1.1  joerg 	if (rc != SQLITE_OK) {
    303  1.1  joerg 		warnx("%s", sqlite3_errmsg(db));
    304  1.1  joerg 		sqlite3_shutdown();
    305  1.1  joerg 		return NULL;
    306  1.1  joerg 	}
    307  1.1  joerg 
    308  1.1  joerg 	if (create_db_flag && create_db(db) < 0) {
    309  1.1  joerg 		warnx("%s", "Unable to create database schema");
    310  1.1  joerg 		goto error;
    311  1.1  joerg 	}
    312  1.1  joerg 
    313  1.1  joerg 	rc = sqlite3_prepare_v2(db, "PRAGMA user_version", -1, &stmt, NULL);
    314  1.1  joerg 	if (rc != SQLITE_OK) {
    315  1.3    apb 		warnx("Unable to query schema version: %s",
    316  1.3    apb 		    sqlite3_errmsg(db));
    317  1.1  joerg 		goto error;
    318  1.1  joerg 	}
    319  1.1  joerg 	if (sqlite3_step(stmt) != SQLITE_ROW) {
    320  1.1  joerg 		sqlite3_finalize(stmt);
    321  1.3    apb 		warnx("Unable to query schema version: %s",
    322  1.3    apb 		    sqlite3_errmsg(db));
    323  1.1  joerg 		goto error;
    324  1.1  joerg 	}
    325  1.1  joerg 	if (sqlite3_column_int(stmt, 0) != APROPOS_SCHEMA_VERSION) {
    326  1.1  joerg 		sqlite3_finalize(stmt);
    327  1.1  joerg 		warnx("Incorrect schema version found. "
    328  1.1  joerg 		      "Please run makemandb -f.");
    329  1.1  joerg 		goto error;
    330  1.1  joerg 	}
    331  1.1  joerg 	sqlite3_finalize(stmt);
    332  1.1  joerg 
    333  1.1  joerg 	sqlite3_extended_result_codes(db, 1);
    334  1.1  joerg 
    335  1.1  joerg 	/* Register the zip and unzip functions for FTS compression */
    336  1.1  joerg 	rc = sqlite3_create_function(db, "zip", 1, SQLITE_ANY, NULL, zip, NULL, NULL);
    337  1.1  joerg 	if (rc != SQLITE_OK) {
    338  1.3    apb 		warnx("Unable to register function: compress: %s",
    339  1.3    apb 		    sqlite3_errmsg(db));
    340  1.1  joerg 		goto error;
    341  1.1  joerg 	}
    342  1.1  joerg 
    343  1.1  joerg 	rc = sqlite3_create_function(db, "unzip", 1, SQLITE_ANY, NULL,
    344  1.1  joerg                                  unzip, NULL, NULL);
    345  1.1  joerg 	if (rc != SQLITE_OK) {
    346  1.3    apb 		warnx("Unable to register function: uncompress: %s",
    347  1.3    apb 		    sqlite3_errmsg(db));
    348  1.1  joerg 		goto error;
    349  1.1  joerg 	}
    350  1.1  joerg 	return db;
    351  1.1  joerg error:
    352  1.1  joerg 	sqlite3_close(db);
    353  1.1  joerg 	sqlite3_shutdown();
    354  1.1  joerg 	return NULL;
    355  1.1  joerg }
    356  1.1  joerg 
    357  1.1  joerg /*
    358  1.1  joerg  * rank_func --
    359  1.1  joerg  *  Sqlite user defined function for ranking the documents.
    360  1.1  joerg  *  For each phrase of the query, it computes the tf and idf and adds them over.
    361  1.1  joerg  *  It computes the final rank, by multiplying tf and idf together.
    362  1.1  joerg  *  Weight of term t for document d = (term frequency of t in d *
    363  1.1  joerg  *                                      inverse document frequency of t)
    364  1.1  joerg  *
    365  1.1  joerg  *  Term Frequency of term t in document d = Number of times t occurs in d /
    366  1.1  joerg  *	                                        Number of times t appears in all
    367  1.1  joerg  *											documents
    368  1.1  joerg  *
    369  1.1  joerg  *  Inverse document frequency of t = log(Total number of documents /
    370  1.1  joerg  *										Number of documents in which t occurs)
    371  1.1  joerg  */
    372  1.1  joerg static void
    373  1.1  joerg rank_func(sqlite3_context *pctx, int nval, sqlite3_value **apval)
    374  1.1  joerg {
    375  1.1  joerg 	inverse_document_frequency *idf = sqlite3_user_data(pctx);
    376  1.1  joerg 	double tf = 0.0;
    377  1.1  joerg 	const unsigned int *matchinfo;
    378  1.1  joerg 	int ncol;
    379  1.1  joerg 	int nphrase;
    380  1.1  joerg 	int iphrase;
    381  1.1  joerg 	int ndoc;
    382  1.1  joerg 	int doclen = 0;
    383  1.1  joerg 	const double k = 3.75;
    384  1.1  joerg 	/* Check that the number of arguments passed to this function is correct. */
    385  1.1  joerg 	assert(nval == 1);
    386  1.1  joerg 
    387  1.1  joerg 	matchinfo = (const unsigned int *) sqlite3_value_blob(apval[0]);
    388  1.1  joerg 	nphrase = matchinfo[0];
    389  1.1  joerg 	ncol = matchinfo[1];
    390  1.1  joerg 	ndoc = matchinfo[2 + 3 * ncol * nphrase + ncol];
    391  1.1  joerg 	for (iphrase = 0; iphrase < nphrase; iphrase++) {
    392  1.1  joerg 		int icol;
    393  1.1  joerg 		const unsigned int *phraseinfo = &matchinfo[2 + ncol+ iphrase * ncol * 3];
    394  1.1  joerg 		for(icol = 1; icol < ncol; icol++) {
    395  1.1  joerg 
    396  1.1  joerg 			/* nhitcount: number of times the current phrase occurs in the current
    397  1.1  joerg 			 *            column in the current document.
    398  1.1  joerg 			 * nglobalhitcount: number of times current phrase occurs in the current
    399  1.1  joerg 			 *                  column in all documents.
    400  1.1  joerg 			 * ndocshitcount:   number of documents in which the current phrase
    401  1.1  joerg 			 *                  occurs in the current column at least once.
    402  1.1  joerg 			 */
    403  1.1  joerg   			int nhitcount = phraseinfo[3 * icol];
    404  1.1  joerg 			int nglobalhitcount = phraseinfo[3 * icol + 1];
    405  1.1  joerg 			int ndocshitcount = phraseinfo[3 * icol + 2];
    406  1.1  joerg 			doclen = matchinfo[2 + icol ];
    407  1.1  joerg 			double weight = col_weights[icol - 1];
    408  1.1  joerg 			if (idf->status == 0 && ndocshitcount)
    409  1.1  joerg 				idf->value += log(((double)ndoc / ndocshitcount))* weight;
    410  1.1  joerg 
    411  1.1  joerg 			/* Dividing the tf by document length to normalize the effect of
    412  1.1  joerg 			 * longer documents.
    413  1.1  joerg 			 */
    414  1.1  joerg 			if (nglobalhitcount > 0 && nhitcount)
    415  1.1  joerg 				tf += (((double)nhitcount  * weight) / (nglobalhitcount * doclen));
    416  1.1  joerg 		}
    417  1.1  joerg 	}
    418  1.1  joerg 	idf->status = 1;
    419  1.1  joerg 
    420  1.1  joerg 	/* Final score = (tf * idf)/ ( k + tf)
    421  1.1  joerg 	 *	Dividing by k+ tf further normalizes the weight leading to better
    422  1.1  joerg 	 *  results.
    423  1.1  joerg 	 *  The value of k is experimental
    424  1.1  joerg 	 */
    425  1.1  joerg 	double score = (tf * idf->value/ ( k + tf)) ;
    426  1.1  joerg 	sqlite3_result_double(pctx, score);
    427  1.1  joerg 	return;
    428  1.1  joerg }
    429  1.1  joerg 
    430  1.1  joerg /*
    431  1.1  joerg  *  run_query --
    432  1.1  joerg  *  Performs the searches for the keywords entered by the user.
    433  1.1  joerg  *  The 2nd param: snippet_args is an array of strings providing values for the
    434  1.1  joerg  *  last three parameters to the snippet function of sqlite. (Look at the docs).
    435  1.1  joerg  *  The 3rd param: args contains rest of the search parameters. Look at
    436  1.1  joerg  *  arpopos-utils.h for the description of individual fields.
    437  1.1  joerg  *
    438  1.1  joerg  */
    439  1.1  joerg int
    440  1.1  joerg run_query(sqlite3 *db, const char *snippet_args[3], query_args *args)
    441  1.1  joerg {
    442  1.1  joerg 	const char *default_snippet_args[3];
    443  1.1  joerg 	char *section_clause = NULL;
    444  1.1  joerg 	char *limit_clause = NULL;
    445  1.1  joerg 	char *machine_clause = NULL;
    446  1.1  joerg 	char *query;
    447  1.1  joerg 	const char *section;
    448  1.1  joerg 	char *name;
    449  1.1  joerg 	const char *name_desc;
    450  1.1  joerg 	const char *machine;
    451  1.1  joerg 	const char *snippet;
    452  1.4    wiz 	const char *name_temp;
    453  1.4    wiz 	char *slash_ptr;
    454  1.1  joerg 	char *m = NULL;
    455  1.1  joerg 	int rc;
    456  1.1  joerg 	inverse_document_frequency idf = {0, 0};
    457  1.1  joerg 	sqlite3_stmt *stmt;
    458  1.1  joerg 
    459  1.1  joerg 	if (args->machine)
    460  1.1  joerg 		easprintf(&machine_clause, "AND machine = \'%s\' ", args->machine);
    461  1.1  joerg 
    462  1.1  joerg 	/* Register the rank function */
    463  1.1  joerg 	rc = sqlite3_create_function(db, "rank_func", 1, SQLITE_ANY, (void *)&idf,
    464  1.1  joerg 	                             rank_func, NULL, NULL);
    465  1.1  joerg 	if (rc != SQLITE_OK) {
    466  1.3    apb 		warnx("Unable to register the ranking function: %s",
    467  1.3    apb 		    sqlite3_errmsg(db));
    468  1.1  joerg 		sqlite3_close(db);
    469  1.1  joerg 		sqlite3_shutdown();
    470  1.3    apb 		exit(EXIT_FAILURE);
    471  1.1  joerg 	}
    472  1.1  joerg 
    473  1.1  joerg 	/* We want to build a query of the form: "select x,y,z from mandb where
    474  1.1  joerg 	 * mandb match :query [AND (section LIKE '1' OR section LIKE '2' OR...)]
    475  1.1  joerg 	 * ORDER BY rank DESC..."
    476  1.1  joerg 	 * NOTES: 1. The portion in square brackets is optional, it will be there
    477  1.1  joerg 	 * only if the user has specified an option on the command line to search in
    478  1.1  joerg 	 * one or more specific sections.
    479  1.1  joerg 	 * 2. I am using LIKE operator because '=' or IN operators do not seem to be
    480  1.1  joerg 	 * working with the compression option enabled.
    481  1.1  joerg 	 */
    482  1.1  joerg 
    483  1.1  joerg 	if (args->sec_nums) {
    484  1.1  joerg 		char *temp;
    485  1.1  joerg 		int i;
    486  1.1  joerg 
    487  1.1  joerg 		for (i = 0; i < SECMAX; i++) {
    488  1.1  joerg 			if (args->sec_nums[i] == 0)
    489  1.1  joerg 				continue;
    490  1.1  joerg 			easprintf(&temp, " OR section = \'%d\'", i + 1);
    491  1.1  joerg 			if (section_clause) {
    492  1.1  joerg 				concat(&section_clause, temp);
    493  1.1  joerg 				free(temp);
    494  1.1  joerg 			} else {
    495  1.1  joerg 				section_clause = temp;
    496  1.1  joerg 			}
    497  1.1  joerg 		}
    498  1.1  joerg 		if (section_clause) {
    499  1.1  joerg 			/*
    500  1.1  joerg 			 * At least one section requested, add glue for query.
    501  1.1  joerg 			 */
    502  1.1  joerg 			temp = section_clause;
    503  1.1  joerg 			/* Skip " OR " before first term. */
    504  1.1  joerg 			easprintf(&section_clause, " AND (%s)", temp + 4);
    505  1.1  joerg 			free(temp);
    506  1.1  joerg 		}
    507  1.1  joerg 	}
    508  1.1  joerg 	if (args->nrec >= 0) {
    509  1.1  joerg 		/* Use the provided number of records and offset */
    510  1.1  joerg 		easprintf(&limit_clause, " LIMIT %d OFFSET %d",
    511  1.1  joerg 		    args->nrec, args->offset);
    512  1.1  joerg 	}
    513  1.1  joerg 
    514  1.1  joerg 	if (snippet_args == NULL) {
    515  1.1  joerg 		default_snippet_args[0] = "";
    516  1.1  joerg 		default_snippet_args[1] = "";
    517  1.1  joerg 		default_snippet_args[2] = "...";
    518  1.1  joerg 		snippet_args = default_snippet_args;
    519  1.1  joerg 	}
    520  1.1  joerg 	query = sqlite3_mprintf("SELECT section, name, name_desc, machine,"
    521  1.1  joerg 	    " snippet(mandb, %Q, %Q, %Q, -1, 40 ),"
    522  1.1  joerg 	    " rank_func(matchinfo(mandb, \"pclxn\")) AS rank"
    523  1.1  joerg 	    " FROM mandb"
    524  1.1  joerg 	    " WHERE mandb MATCH %Q %s "
    525  1.1  joerg 	    "%s"
    526  1.1  joerg 	    " ORDER BY rank DESC"
    527  1.1  joerg 	    "%s",
    528  1.1  joerg 	    snippet_args[0], snippet_args[1], snippet_args[2], args->search_str,
    529  1.1  joerg 	    machine_clause ? machine_clause : "",
    530  1.1  joerg 	    section_clause ? section_clause : "",
    531  1.1  joerg 	    limit_clause ? limit_clause : "");
    532  1.1  joerg 
    533  1.1  joerg 	free(machine_clause);
    534  1.1  joerg 	free(section_clause);
    535  1.1  joerg 	free(limit_clause);
    536  1.1  joerg 
    537  1.1  joerg 	if (query == NULL) {
    538  1.1  joerg 		*args->errmsg = estrdup("malloc failed");
    539  1.1  joerg 		return -1;
    540  1.1  joerg 	}
    541  1.1  joerg 	rc = sqlite3_prepare_v2(db, query, -1, &stmt, NULL);
    542  1.1  joerg 	if (rc == SQLITE_IOERR) {
    543  1.1  joerg 		warnx("Corrupt database. Please rerun makemandb");
    544  1.1  joerg 		sqlite3_free(query);
    545  1.1  joerg 		return -1;
    546  1.1  joerg 	} else if (rc != SQLITE_OK) {
    547  1.1  joerg 		warnx("%s", sqlite3_errmsg(db));
    548  1.1  joerg 		sqlite3_free(query);
    549  1.1  joerg 		return -1;
    550  1.1  joerg 	}
    551  1.1  joerg 
    552  1.1  joerg 	while (sqlite3_step(stmt) == SQLITE_ROW) {
    553  1.1  joerg 		section = (const char *) sqlite3_column_text(stmt, 0);
    554  1.4    wiz 		name_temp = (const char *) sqlite3_column_text(stmt, 1);
    555  1.1  joerg 		name_desc = (const char *) sqlite3_column_text(stmt, 2);
    556  1.1  joerg 		machine = (const char *) sqlite3_column_text(stmt, 3);
    557  1.1  joerg 		snippet = (const char *) sqlite3_column_text(stmt, 4);
    558  1.4    wiz 		if ((slash_ptr = strrchr(name_temp, '/')) != NULL)
    559  1.4    wiz 			name_temp = slash_ptr + 1;
    560  1.1  joerg 		if (machine && machine[0]) {
    561  1.1  joerg 			m = estrdup(machine);
    562  1.1  joerg 			easprintf(&name, "%s/%s", lower(m),
    563  1.4    wiz 				name_temp);
    564  1.1  joerg 			free(m);
    565  1.1  joerg 		} else {
    566  1.1  joerg 			name = estrdup((const char *) sqlite3_column_text(stmt, 1));
    567  1.1  joerg 		}
    568  1.1  joerg 
    569  1.1  joerg 		(args->callback)(args->callback_data, section, name, name_desc, snippet,
    570  1.1  joerg 			strlen(snippet));
    571  1.1  joerg 
    572  1.1  joerg 		free(name);
    573  1.1  joerg 	}
    574  1.1  joerg 
    575  1.1  joerg 	sqlite3_finalize(stmt);
    576  1.1  joerg 	sqlite3_free(query);
    577  1.1  joerg 	return *(args->errmsg) == NULL ? 0 : -1;
    578  1.1  joerg }
    579  1.1  joerg 
    580  1.1  joerg /*
    581  1.1  joerg  * callback_html --
    582  1.1  joerg  *  Callback function for run_query_html. It builds the html output and then
    583  1.1  joerg  *  calls the actual user supplied callback function.
    584  1.1  joerg  */
    585  1.1  joerg static int
    586  1.1  joerg callback_html(void *data, const char *section, const char *name,
    587  1.1  joerg 	const char *name_desc, const char *snippet, size_t snippet_length)
    588  1.1  joerg {
    589  1.1  joerg 	const char *temp = snippet;
    590  1.1  joerg 	int i = 0;
    591  1.1  joerg 	size_t sz = 0;
    592  1.1  joerg 	int count = 0;
    593  1.1  joerg 	struct orig_callback_data *orig_data = (struct orig_callback_data *) data;
    594  1.1  joerg 	int (*callback) (void *, const char *, const char *, const char *,
    595  1.1  joerg 		const char *, size_t) = orig_data->callback;
    596  1.1  joerg 
    597  1.1  joerg 	/* First scan the snippet to find out the number of occurrences of {'>', '<'
    598  1.1  joerg 	 * '"', '&'}.
    599  1.1  joerg 	 * Then allocate a new buffer with sufficient space to be able to store the
    600  1.1  joerg 	 * quoted versions of the special characters {&gt;, &lt;, &quot;, &amp;}.
    601  1.1  joerg 	 * Copy over the characters from the original snippet to this buffer while
    602  1.1  joerg 	 * replacing the special characters with their quoted versions.
    603  1.1  joerg 	 */
    604  1.1  joerg 
    605  1.1  joerg 	while (*temp) {
    606  1.1  joerg 		sz = strcspn(temp, "<>\"&\002\003");
    607  1.1  joerg 		temp += sz + 1;
    608  1.1  joerg 		count++;
    609  1.1  joerg 	}
    610  1.1  joerg 	size_t qsnippet_length = snippet_length + count * 5;
    611  1.1  joerg 	char *qsnippet = emalloc(qsnippet_length + 1);
    612  1.1  joerg 	sz = 0;
    613  1.1  joerg 	while (*snippet) {
    614  1.1  joerg 		sz = strcspn(snippet, "<>\"&\002\003");
    615  1.1  joerg 		if (sz) {
    616  1.1  joerg 			memcpy(&qsnippet[i], snippet, sz);
    617  1.1  joerg 			snippet += sz;
    618  1.1  joerg 			i += sz;
    619  1.1  joerg 		}
    620  1.1  joerg 
    621  1.1  joerg 		switch (*snippet++) {
    622  1.1  joerg 		case '<':
    623  1.1  joerg 			memcpy(&qsnippet[i], "&lt;", 4);
    624  1.1  joerg 			i += 4;
    625  1.1  joerg 			break;
    626  1.1  joerg 		case '>':
    627  1.1  joerg 			memcpy(&qsnippet[i], "&gt;", 4);
    628  1.1  joerg 			i += 4;
    629  1.1  joerg 			break;
    630  1.1  joerg 		case '\"':
    631  1.1  joerg 			memcpy(&qsnippet[i], "&quot;", 6);
    632  1.1  joerg 			i += 6;
    633  1.1  joerg 			break;
    634  1.1  joerg 		case '&':
    635  1.1  joerg 			/* Don't perform the quoting if this & is part of an mdoc escape
    636  1.1  joerg 			 * sequence, e.g. \&
    637  1.1  joerg 			 */
    638  1.1  joerg 			if (i && *(snippet - 2) != '\\') {
    639  1.1  joerg 				memcpy(&qsnippet[i], "&amp;", 5);
    640  1.1  joerg 				i += 5;
    641  1.1  joerg 			} else {
    642  1.1  joerg 				qsnippet[i++] = '&';
    643  1.1  joerg 			}
    644  1.1  joerg 			break;
    645  1.1  joerg 		case '\002':
    646  1.1  joerg 			memcpy(&qsnippet[i], "<b>", 3);
    647  1.1  joerg 			i += 3;
    648  1.1  joerg 			break;
    649  1.1  joerg 		case '\003':
    650  1.1  joerg 			memcpy(&qsnippet[i], "</b>", 4);
    651  1.1  joerg 			i += 4;
    652  1.1  joerg 			break;
    653  1.1  joerg 		default:
    654  1.1  joerg 			break;
    655  1.1  joerg 		}
    656  1.1  joerg 	}
    657  1.1  joerg 	qsnippet[++i] = 0;
    658  1.1  joerg 	(*callback)(orig_data->data, section, name, name_desc,
    659  1.1  joerg 		(const char *)qsnippet,	qsnippet_length);
    660  1.1  joerg 	free(qsnippet);
    661  1.1  joerg 	return 0;
    662  1.1  joerg }
    663  1.1  joerg 
    664  1.1  joerg /*
    665  1.1  joerg  * run_query_html --
    666  1.1  joerg  *  Utility function to output query result in HTML format.
    667  1.1  joerg  *  It internally calls run_query only, but it first passes the output to it's
    668  1.1  joerg  *  own custom callback function, which preprocess the snippet for quoting
    669  1.1  joerg  *  inline HTML fragments.
    670  1.1  joerg  *  After that it delegates the call the actual user supplied callback function.
    671  1.1  joerg  */
    672  1.1  joerg int
    673  1.1  joerg run_query_html(sqlite3 *db, query_args *args)
    674  1.1  joerg {
    675  1.1  joerg 	struct orig_callback_data orig_data;
    676  1.1  joerg 	orig_data.callback = args->callback;
    677  1.1  joerg 	orig_data.data = args->callback_data;
    678  1.1  joerg 	const char *snippet_args[] = {"\002", "\003", "..."};
    679  1.1  joerg 	args->callback = &callback_html;
    680  1.1  joerg 	args->callback_data = (void *) &orig_data;
    681  1.1  joerg 	return run_query(db, snippet_args, args);
    682  1.1  joerg }
    683  1.1  joerg 
    684  1.1  joerg /*
    685  1.1  joerg  * callback_pager --
    686  1.1  joerg  *  A callback similar to callback_html. It overstrikes the matching text in
    687  1.1  joerg  *  the snippet so that it appears emboldened when viewed using a pager like
    688  1.1  joerg  *  more or less.
    689  1.1  joerg  */
    690  1.1  joerg static int
    691  1.1  joerg callback_pager(void *data, const char *section, const char *name,
    692  1.1  joerg 	const char *name_desc, const char *snippet, size_t snippet_length)
    693  1.1  joerg {
    694  1.1  joerg 	struct orig_callback_data *orig_data = (struct orig_callback_data *) data;
    695  1.1  joerg 	char *psnippet;
    696  1.1  joerg 	const char *temp = snippet;
    697  1.1  joerg 	int count = 0;
    698  1.1  joerg 	int i = 0;
    699  1.1  joerg 	size_t sz = 0;
    700  1.1  joerg 	size_t psnippet_length;
    701  1.1  joerg 
    702  1.1  joerg 	/* Count the number of bytes of matching text. For each of these bytes we
    703  1.1  joerg 	 * will use 2 extra bytes to overstrike it so that it appears bold when
    704  1.1  joerg 	 * viewed using a pager.
    705  1.1  joerg 	 */
    706  1.1  joerg 	while (*temp) {
    707  1.1  joerg 		sz = strcspn(temp, "\002\003");
    708  1.1  joerg 		temp += sz;
    709  1.1  joerg 		if (*temp == '\003') {
    710  1.1  joerg 			count += 2 * (sz);
    711  1.1  joerg 		}
    712  1.1  joerg 		temp++;
    713  1.1  joerg 	}
    714  1.1  joerg 
    715  1.1  joerg 	psnippet_length = snippet_length + count;
    716  1.1  joerg 	psnippet = emalloc(psnippet_length + 1);
    717  1.1  joerg 
    718  1.1  joerg 	/* Copy the bytes from snippet to psnippet:
    719  1.1  joerg 	 * 1. Copy the bytes before \002 as it is.
    720  1.1  joerg 	 * 2. The bytes after \002 need to be overstriked till we encounter \003.
    721  1.1  joerg 	 * 3. To overstrike a byte 'A' we need to write 'A\bA'
    722  1.1  joerg 	 */
    723  1.1  joerg 	while (*snippet) {
    724  1.1  joerg 		sz = strcspn(snippet, "\002");
    725  1.1  joerg 		memcpy(&psnippet[i], snippet, sz);
    726  1.1  joerg 		snippet += sz;
    727  1.1  joerg 		i += sz;
    728  1.1  joerg 
    729  1.1  joerg 		/* Don't change this. Advancing the pointer without reading the byte
    730  1.1  joerg 		 * is causing strange behavior.
    731  1.1  joerg 		 */
    732  1.1  joerg 		if (*snippet == '\002')
    733  1.1  joerg 			snippet++;
    734  1.1  joerg 		while (*snippet && *snippet != '\003') {
    735  1.1  joerg 			psnippet[i++] = *snippet;
    736  1.1  joerg 			psnippet[i++] = '\b';
    737  1.1  joerg 			psnippet[i++] = *snippet++;
    738  1.1  joerg 		}
    739  1.1  joerg 		if (*snippet)
    740  1.1  joerg 			snippet++;
    741  1.1  joerg 	}
    742  1.1  joerg 
    743  1.1  joerg 	psnippet[i] = 0;
    744  1.1  joerg 	(orig_data->callback)(orig_data->data, section, name, name_desc, psnippet,
    745  1.1  joerg 		psnippet_length);
    746  1.1  joerg 	free(psnippet);
    747  1.1  joerg 	return 0;
    748  1.1  joerg }
    749  1.1  joerg 
    750  1.1  joerg /*
    751  1.1  joerg  * run_query_pager --
    752  1.1  joerg  *  Utility function similar to run_query_html. This function tries to
    753  1.1  joerg  *  pre-process the result assuming it will be piped to a pager.
    754  1.1  joerg  *  For this purpose it first calls it's own callback function callback_pager
    755  1.1  joerg  *  which then delegates the call to the user supplied callback.
    756  1.1  joerg  */
    757  1.1  joerg int run_query_pager(sqlite3 *db, query_args *args)
    758  1.1  joerg {
    759  1.1  joerg 	struct orig_callback_data orig_data;
    760  1.1  joerg 	orig_data.callback = args->callback;
    761  1.1  joerg 	orig_data.data = args->callback_data;
    762  1.1  joerg 	const char *snippet_args[] = {"\002", "\003", "..."};
    763  1.1  joerg 	args->callback = &callback_pager;
    764  1.1  joerg 	args->callback_data = (void *) &orig_data;
    765  1.1  joerg 	return run_query(db, snippet_args, args);
    766  1.1  joerg }
    767