Exemplo n.º 1
0
/* perform put command */
static int procput(const char *path, const char *pkbuf, int pksiz, TCMAP *cols,
                   int omode, int dmode){
  TCTDB *tdb = tctdbnew();
  if(g_dbgfd != INVALID_HANDLE_VALUE) tctdbsetdbgfd(tdb, g_dbgfd);
  if(!tctdbsetcodecfunc(tdb, _tc_recencode, NULL, _tc_recdecode, NULL)) printerr(tdb);
  if(!tctdbopen(tdb, path, TDBOWRITER | omode)){
    printerr(tdb);
    tctdbdel(tdb);
    return 1;
  }
  bool err = false;
  char pknumbuf[TCNUMBUFSIZ];
  if(pksiz < 1){
    pksiz = sprintf(pknumbuf, "%lld", (long long)tctdbgenuid(tdb));
    pkbuf = pknumbuf;
  }
  const char *vbuf;
  switch(dmode){
    case -1:
      if(!tctdbputkeep(tdb, pkbuf, pksiz, cols)){
        printerr(tdb);
        err = true;
      }
      break;
    case 1:
      if(!tctdbputcat(tdb, pkbuf, pksiz, cols)){
        printerr(tdb);
        err = true;
      }
      break;
    case 10:
      vbuf = tcmapget2(cols, "_num");
      if(!vbuf) vbuf = "1";
      if(tctdbaddint(tdb, pkbuf, pksiz, tcatoi(vbuf)) == INT_MIN){
        printerr(tdb);
        err = true;
      }
      break;
    case 11:
      vbuf = tcmapget2(cols, "_num");
      if(!vbuf) vbuf = "1.0";
      if(isnan(tctdbadddouble(tdb, pkbuf, pksiz, tcatof(vbuf)))){
        printerr(tdb);
        err = true;
      }
      break;
    default:
      if(!tctdbput(tdb, pkbuf, pksiz, cols)){
        printerr(tdb);
        err = true;
      }
      break;
  }
  if(!tctdbclose(tdb)){
    if(!err) printerr(tdb);
    err = true;
  }
  tctdbdel(tdb);
  return err ? 1 : 0;
}
Exemplo n.º 2
0
void get_cb(struct evhttp_request *req, struct evbuffer *evb, void *ctx)
{
    const char *value, *name;
    char *uri, *json, *hash, *key; 
    struct evkeyvalq args;
    struct json_object *jsobj, *jsobj2, *jsobj3;
    TCMAP *cols;
    
    if (rdb == NULL) {
        evhttp_send_error(req, 503, "database not connected");
        return;
    }

    uri = evhttp_decode_uri(req->uri);
    evhttp_parse_query(uri, &args);
    free(uri);

    hash = (char *)evhttp_find_header(&args, "hash");
    key = (char *)evhttp_find_header(&args, "key");
    
    if (hash == NULL) {
        evhttp_send_error(req, 400, "hash is required");
        evhttp_clear_headers(&args);
        return;
    }
    
    jsobj = json_object_new_object();
    jsobj2 = json_object_new_object();
    cols = tcrdbtblget(rdb, hash, sizeof(hash));
    
    if (cols) {
        tcmapiterinit(cols);
        jsobj3 = json_object_new_object();
        
        
        if (key) {
            value = tcmapget2(cols, key);

            if (!value) {
                value = "";
            }
            
            json_object_object_add(jsobj2, key, json_object_new_string(value));
        } else {
            while ((name = tcmapiternext2(cols)) != NULL) {
                json_object_object_add(jsobj2, name, json_object_new_string(tcmapget2(cols, name)));
            }
        }
     
        json_object_object_add(jsobj, "status", json_object_new_string("ok"));
        json_object_object_add(jsobj, "results", jsobj2);
        
        tcmapdel(cols);
    } else {
        json_object_object_add(jsobj, "status", json_object_new_string("error"));
    }
   
    finalize_json(req, evb, &args, jsobj);
}
Exemplo n.º 3
0
/*
 * This checks if a user is currently logged in. It is called at the start
 * of each request.
 *
 * There are upto three checks performed:
 *
 * 1) The session_id cookie from the browser is checked with the stored
 *    session_id generated at login.
 * 2) The client_id from the browser (currently the user agent string) is
 *    checked against the stored client_id.
 *
 * 4) Optionally (enabled by default on the login screen) a check is made
 *    on the requesting ip address against the stored origin_ip that was
 *    used at login.
 *
 * If any of these checks fail, the request is denied and the user is
 * punted to the login screen.
 */
bool is_logged_in(void)
{
	char session_id[SID_LEN + 1];
	TCTDB *tdb;
	TDBQRY *qry;
	TCLIST *res;
	TCMAP *cols;
	int rsize;
	const char *rbuf;
	bool login_ok = false;

	if (!env_vars.http_cookie)
		goto out3;

	snprintf(session_id, sizeof(session_id), "%s",
						env_vars.http_cookie + 11);

	tdb = tctdbnew();
	tctdbopen(tdb, SESSION_DB, TDBOREADER);

	qry = tctdbqrynew(tdb);
	tctdbqryaddcond(qry, "session_id", TDBQCSTREQ, session_id);
	res = tctdbqrysearch(qry);
	if (tclistnum(res) == 0)
		goto out2;

	rbuf = tclistval(res, 0, &rsize);
	cols = tctdbget(tdb, rbuf, rsize);
	tcmapiterinit(cols);

	/* restrict_ip */
	if (atoi(tcmapget2(cols, "restrict_ip")) == 1) {
		/* origin_ip */
		if (strcmp(tcmapget2(cols, "origin_ip"),
					env_vars.remote_addr) != 0)
			goto out;
	}
	/* client_id */
	if (strcmp(tcmapget2(cols, "client_id"),
					env_vars.http_user_agent) != 0)
		goto out;

	/* We got here, all checks are OK */
	login_ok = true;

out:
	tcmapdel(cols);
out2:
	tctdbqrydel(qry);
	tclistdel(res);
	tctdbclose(tdb);
	tctdbdel(tdb);
out3:
	return login_ok;
}
Exemplo n.º 4
0
static VALUE cQuery_get(VALUE vself){
  int i, num, ksiz;
  const char *name, *col;
  VALUE vqry, vary, vcols;
  RDBQRY *qry;
  TCLIST *res;
  TCMAP *cols;
  vqry = rb_iv_get(vself, RDBQRYVNDATA);
  Data_Get_Struct(vqry, RDBQRY, qry);

  res = tcrdbqrysearchget(qry);
  num = tclistnum(res);
  vary = rb_ary_new2(num);
  for(i = 0; i < num; i++){
    vcols = rb_hash_new();
    cols = tcrdbqryrescols(res, i);
    if(cols){
      tcmapiterinit(cols);
      while((name = tcmapiternext(cols, &ksiz)) != NULL){
        col = tcmapget2(cols, name);
        if (ksiz == 0) name = "__id";
        rb_hash_aset(vcols, ID2SYM(rb_intern(name)), rb_str_new2(col));
      }
    }
    tcmapdel(cols);
    rb_ary_push(vary, vcols);
  }
  tclistdel(res);
  return vary;
}
Exemplo n.º 5
0
static PyObject *
search(PyObject *self, PyObject *args){
    TCTDB *tdb;
    int ecode, i, rsiz;
    const char *rbuf, *name;
    TCMAP *cols;
    TDBQRY *qry;
    TCLIST *res;

    const char *dbname;
    const char *sfield;
    const char *stext;
    const int *max;
    PyObject* pDict = PyDict_New();
    PyObject* pList = PyList_New(0);

    if (!PyArg_ParseTuple(args, "sssi", &dbname, &sfield, &stext,&max))
        return NULL;

    tdb = tctdbnew();
    
    if(!tctdbopen(tdb, dbname, TDBONOLCK | TDBOREADER)){
        ecode = tctdbecode(tdb);
        fprintf(stderr, "open error: %s\n", tctdberrmsg(ecode));
    }
    qry = tctdbqrynew(tdb);
    tctdbqryaddcond(qry, sfield, TDBQCSTREQ, stext);
    tctdbqrysetorder(qry, "savedate", TDBQOSTRDESC);
    tctdbqrysetlimit(qry, max, 0);
    res = tctdbqrysearch(qry);
    for(i = 0; i < tclistnum(res); i++){
        rbuf = tclistval(res, i, &rsiz);
        cols = tctdbget(tdb, rbuf, rsiz);
        if(cols){
          tcmapiterinit(cols);
          PyDict_SetItemString(pDict, "kid", Py_BuildValue("s",rbuf));
          while((name = tcmapiternext2(cols)) != NULL){
              PyDict_SetItemString(pDict, name, Py_BuildValue("s", tcmapget2(cols, name)));
          }
          PyList_Append(pList,pDict);
          pDict = PyDict_New();
          tcmapdel(cols);
        }
    }
    tclistdel(res);
    tctdbqrydel(qry);

    if(!tctdbclose(tdb)){
        ecode = tctdbecode(tdb);
        fprintf(stderr, "close error: %s\n", tctdberrmsg(ecode));
    }

    tctdbdel(tdb);

    return Py_BuildValue("O",pList);
}
Exemplo n.º 6
0
static PyObject *
tcmap2pydict(TCMAP *map)
{
    const char *kstr, *vstr;
    PyObject *dict, *value;
    
    dict = PyDict_New();
    
    if (dict == NULL)
    {
        PyErr_SetString(PyExc_MemoryError, "Could not allocate memory for dict.");
        return NULL;
    }
    
    tcmapiterinit(map);
    kstr = tcmapiternext2(map);
    
    while (kstr != NULL)
    {
        vstr = tcmapget2(map, kstr);
        
        if (vstr == NULL)
        {
            Py_DECREF(dict);
            PyErr_SetString(PyExc_MemoryError, "Could not allocate memory for map value.");
            return NULL;
        }
        
        value = PyString_FromString(vstr);
        
        if (value == NULL)
        {
            Py_DECREF(dict);
            PyErr_SetString(PyExc_MemoryError, "Could not allocate memory for dict value.");
            return NULL;
        }
        
        if (PyDict_SetItemString(dict, kstr, value) != 0)
        {
            Py_DECREF(value);
            Py_DECREF(dict);
            PyErr_SetString(PyExc_Exception, "Could not set dict item.");
            return NULL;
        }
        
        Py_DECREF(value);
        
        kstr = tcmapiternext2(map);
    }
    
    return dict;
}
Exemplo n.º 7
0
/* perform convert command */
static int procconvert(const char *ibuf, int isiz, int fmt,
                       const char *buri, const char *duri, bool page){
  TCMAP *cols = tcmapnew2(TINYBNUM);
  wikiload(cols, ibuf);
  if(fmt == FMTWIKI){
    TCXSTR *rbuf = tcxstrnew3(IOBUFSIZ);
    wikidump(rbuf, cols);
    fwrite(tcxstrptr(rbuf), 1, tcxstrsize(rbuf), stdout);
    tcxstrdel(rbuf);
  } else if(fmt == FMTTEXT){
    TCXSTR *rbuf = tcxstrnew3(IOBUFSIZ);
    if(page)
      tcxstrprintf(rbuf, "------------------------ Tokyo Promenade ------------------------\n");
    wikidumptext(rbuf, cols);
    if(page)
      tcxstrprintf(rbuf, "-----------------------------------------------------------------\n");
    fwrite(tcxstrptr(rbuf), 1, tcxstrsize(rbuf), stdout);
    tcxstrdel(rbuf);
  } else if(fmt == FMTHTML){
    TCXSTR *rbuf = tcxstrnew3(IOBUFSIZ);
    if(page){
      const char *name = tcmapget2(cols, "name");
      tcxstrprintf(rbuf, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
      tcxstrprintf(rbuf, "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\""
                   " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n");
      tcxstrprintf(rbuf, "<html xmlns=\"http://www.w3.org/1999/xhtml\""
                   " xml:lang=\"en\" lang=\"en\">\n");
      tcxstrprintf(rbuf, "<head>\n");
      tcxstrprintf(rbuf, "<meta http-equiv=\"Content-Type\""
                   " content=\"text/html; charset=UTF-8\" />\n");
      tcxstrprintf(rbuf, "<link rel=\"contents\" href=\"%@\" />\n", buri);
      tcxstrprintf(rbuf, "<title>%@</title>\n", name ? name : "Tokyo Promenade");
      tcxstrprintf(rbuf, "</head>\n");
      tcxstrprintf(rbuf, "<body>\n");
    }
    wikidumphtml(rbuf, cols, buri, 0, duri);
    if(page){
      tcxstrprintf(rbuf, "</body>\n");
      tcxstrprintf(rbuf, "</html>\n");
    }
    fwrite(tcxstrptr(rbuf), 1, tcxstrsize(rbuf), stdout);
    tcxstrdel(rbuf);
  }
  tcmapdel(cols);
  return 0;
}
Exemplo n.º 8
0
void panel_article_upload(struct env_t *_SERVER)
{
	const char *path, *file;

	if(tclistnum(_SERVER->_FILES) == 0)
	{
		puts("Content-type: text/html\r\n\r\n{\"error\":1, \"message\":\"文件上传失败\"}");
		return ;
	}
	
	file = tclistval2(_SERVER->_FILES, 0);
	path = tcmapget2(_SERVER->_COOKIE, "file");
	if(path == NULL)
	{
		printf("Set-Cookie: file=%s;\r\nContent-type: text/html\r\n\r\n{\"error\":0, \"url\":\"/files/%s\"}", file, file);
		return ;
	}

	printf("Set-Cookie: file=%s|%s;\r\nContent-type: text/html\r\n\r\n{\"error\":0, \"url\":\"/files/%s\"}", path, file, file);
}
Exemplo n.º 9
0
const char* 
xtc_mapget2(void* cols, const char* name)
{
        return tcmapget2(cols, name);
}
Exemplo n.º 10
0
/*
 * Sets up the user_session structure. This contains various bits of
 * information pertaining to the users session.
 */
void set_user_session(void)
{
	TCTDB *tdb;
	TDBQRY *qry;
	TCLIST *res;
	TCMAP *cols;
	int rsize;
	int primary_key_size;
	char pkbuf[256];
	char session_id[SID_LEN + 1];
	char login_at[21];
	char last_seen[21];
	char uid[11];
	char sid[21];
	char restrict_ip[2];
	char capabilities[4];
	char user_hdr[1025];
	char *xss_string;
	const char *rbuf;

	/*
	 * Don't assume the order we get the cookies back is the
	 * same order as we sent them.
	 */
	if (strncmp(env_vars.http_cookie, "session_id", 10) == 0)
		snprintf(session_id, sizeof(session_id), "%s",
						env_vars.http_cookie + 11);
	else
		snprintf(session_id, sizeof(session_id), "%s",
						env_vars.http_cookie + 88);

	tdb = tctdbnew();
	tctdbopen(tdb, SESSION_DB, TDBOREADER | TDBOWRITER);

	/* Get the users stored session */
	qry = tctdbqrynew(tdb);
	tctdbqryaddcond(qry, "session_id", TDBQCSTREQ, session_id);
	res = tctdbqrysearch(qry);

	rbuf = tclistval(res, 0, &rsize);
	cols = tctdbget(tdb, rbuf, rsize);
	tcmapiterinit(cols);

	memset(&user_session, 0, sizeof(user_session));
	snprintf(user_session.tenant, sizeof(user_session.tenant), "%s",
			tcmapget2(cols, "tenant"));
	user_session.sid = strtoull(tcmapget2(cols, "sid"), NULL, 10);
	user_session.uid = atoi(tcmapget2(cols, "uid"));
	user_session.username = strdup(tcmapget2(cols, "username"));
	user_session.name = strdup(tcmapget2(cols, "name"));
	user_session.login_at = atol(tcmapget2(cols, "login_at"));
	user_session.last_seen = time(NULL);
	snprintf(user_session.origin_ip, sizeof(user_session.origin_ip), "%s",
			tcmapget2(cols, "origin_ip"));
	user_session.client_id = strdup(tcmapget2(cols, "client_id"));
	snprintf(user_session.session_id, sizeof(user_session.session_id),
			"%s", tcmapget2(cols, "session_id"));
	snprintf(user_session.csrf_token, sizeof(user_session.csrf_token),
			"%s", tcmapget2(cols, "csrf_token"));
	user_session.restrict_ip = atoi(tcmapget2(cols, "restrict_ip"));
	user_session.capabilities = atoi(tcmapget2(cols, "capabilities"));

	tcmapdel(cols);
	tclistdel(res);
	tctdbqrydel(qry);

	/*
	 * Set the user header banner, which displays the users name, uid and
	 * whether they are an Approver and or Admin.
	 */
	xss_string = xss_safe_string(user_session.name);
	snprintf(user_hdr, sizeof(user_hdr), "<big><big> %s</big></big><small>"
				"<span class = \"lighter\"> (%d) </span>"
				"</small>", xss_string, user_session.uid);
	free(xss_string);
	if (IS_APPROVER() && IS_ADMIN())
		strncat(user_hdr, "<span class = \"t_red\">(Approver / Admin)"
					"</span>", 1024 - strlen(user_hdr));
	else if (IS_APPROVER())
		strncat(user_hdr, "<span class = \"t_red\">(Approver)"
					"</span>", 1024 - strlen(user_hdr));
	else if (IS_ADMIN())
		strncat(user_hdr, "<span class = \"t_red\">(Admin)"
					"</span>", 1024 - strlen(user_hdr));
	strncat(user_hdr, "&nbsp;", 1024 - strlen(user_hdr));
	user_session.user_hdr = strdup(user_hdr);

	/*
	 * We want to update the last_seen timestamp in the users session.
	 * This entails removing the old session first then storing the new
	 * updated session.
	 */
	qry = tctdbqrynew(tdb);
	tctdbqryaddcond(qry, "session_id", TDBQCSTREQ, session_id);
	res = tctdbqrysearch(qry);
	rbuf = tclistval(res, 0, &rsize);
	tctdbout(tdb, rbuf, strlen(rbuf));

	tclistdel(res);
	tctdbqrydel(qry);

	primary_key_size = sprintf(pkbuf, "%ld", (long)tctdbgenuid(tdb));
	snprintf(login_at, sizeof(login_at), "%ld", user_session.login_at);
	snprintf(last_seen, sizeof(last_seen), "%ld",
						user_session.last_seen);
	snprintf(uid, sizeof(uid), "%u", user_session.uid);
	snprintf(sid, sizeof(sid), "%llu", user_session.sid);
	snprintf(restrict_ip, sizeof(restrict_ip), "%d",
						user_session.restrict_ip);
	snprintf(capabilities, sizeof(capabilities), "%d",
						user_session.capabilities);
	cols = tcmapnew3("tenant", user_session.tenant,
			"sid", sid,
			"uid", uid,
			"username", user_session.username,
			"name", user_session.name,
			"login_at", login_at,
			"last_seen", last_seen,
			"origin_ip", user_session.origin_ip,
			"client_id", user_session.client_id,
			"session_id", user_session.session_id,
			"csrf_token", user_session.csrf_token,
			"restrict_ip", restrict_ip,
			"capabilities", capabilities,
			NULL);
	tctdbput(tdb, pkbuf, primary_key_size, cols);

	tcmapdel(cols);

	tctdbclose(tdb);
	tctdbdel(tdb);
}
Exemplo n.º 11
0
void panel_article_update(struct env_t *_SERVER)
{
	tpl_t        *tpl;
	TCLIST       *arr;
	char         *html, path[128], buf[128];

	sqlite3_stmt *stmt;
	time_t       visit;
	int          rc, i, type, pos, len, n;
	const char   *id, *title, *sortlevel, *content, *recommend, *keyword, *filename, *file, *post_time;


	if(tcmapget2(_SERVER->_POST, "Article_Update"))
	{
		file      = tcmapget2(_SERVER->_COOKIE, "file");
		id        = tcmapget2(_SERVER->_POST, "id");
		title     = tcmapget2(_SERVER->_POST, "title");
		content   = tcmapget2(_SERVER->_POST, "content");
		keyword   = tcmapget2(_SERVER->_POST, "keyword");
		filename  = tcmapget2(_SERVER->_POST, "filename");
		sortlevel = tcmapget2(_SERVER->_POST, "sortlevel");
		recommend = tcmapget2(_SERVER->_POST, "recommend");
		post_time = tcmapget2(_SERVER->_POST, "post_time");

		pos = strpos(content, "<!-- idx -->");
		pos = (pos == -1) ? strlen(content) : pos;
		rc = sqlite3_prepare(db, "UPDATE article SET title = ?, content = ?, catid = ?, keyword = ?, filename = ?, recommend = ?, position = ? WHERE art_id = ?;", -1, &stmt, NULL); 
		
		sqlite3_bind_text(stmt, 1, title,     -1, SQLITE_STATIC);
		sqlite3_bind_text(stmt, 2, content,   -1, SQLITE_STATIC);
		sqlite3_bind_text(stmt, 3, sortlevel, -1, SQLITE_STATIC);
		sqlite3_bind_text(stmt, 4, keyword,   -1, SQLITE_STATIC);
		sqlite3_bind_text(stmt, 5, filename,  -1, SQLITE_STATIC);

		sqlite3_bind_int(stmt, 6, atoi(recommend));
		sqlite3_bind_int(stmt, 7, pos);
		sqlite3_bind_int(stmt, 8, atoi(id));
		

		sqlite3_step(stmt); 
		sqlite3_finalize(stmt); 

		visit = atoi(post_time);

		if(file)
		{
			memset(buf,  0, sizeof(buf));
			memset(path, 0, sizeof(path));
			
			strftime(buf, sizeof(buf), "%Y/%m/%d", localtime(&visit));

			//如果有上传的文件,就把上传的文件,从临时目录移动目标目录
			len = snprintf(path, sizeof(path), "./attachment/%s/%llu/", buf, (long long unsigned int)id);
			
			if(!is_dir(path)) mkpath(_SERVER->mp, path, 0777);
			if(!strchr(file, '|'))
			{
				memset(buf,  0, sizeof(buf));
				snprintf(buf, sizeof(buf), "./files/%s", file);
				strcat(path, file);
				
			//	log_debug("panel_article_insert buf = %s\tpath = %s\r\n", buf, path);
				if(file_exists(buf)) rename(buf, path);
			}
			else
			{
				arr = explode("|", (char *)file);
				n   = tclistnum(arr);
				for(i=0; i<n; i++)
				{
					memset(buf,  0, sizeof(buf));
					filename = tclistval2(arr, i);
					snprintf(buf, sizeof(buf), "./files/%s", filename);

					path[len] = '\0';
					strcat(path, filename);

		//			log_debug("panel_article_insert explode buf = %s\tpath = %s\r\n", buf, path);

					if(file_exists(buf)) rename(buf, path);
				}
				tclistdel(arr);
			}
			
			path[len] = '\0';
			

			//更新图片附件的 路径
			rc = sqlite3_prepare(db, "UPDATE article SET content = replace(content, '/files/', ?) WHERE art_id = ?;", -1, &stmt, NULL);
			
			sqlite3_bind_text(stmt, 1, path+1,   -1, SQLITE_STATIC);
			sqlite3_bind_int(stmt, 2, atoi(id));
			sqlite3_step(stmt); 
			sqlite3_finalize(stmt); 
			
		}

#ifdef _BUILD_HTML
		memset(path, 0, sizeof(path));
		snprintf(path, sizeof(path), "./html/article/%s/%s.htm", sortlevel, id);
		if(file_exists(path))
			remove(path);

		memset(path, 0, sizeof(path));
		snprintf(path, sizeof(path), "./html/list/%s", sortlevel);
		ftw(path, fn, 500);
#endif
		printf("Content-type: text/html\r\n\r\n<script>alert('编辑成功!');window.location.href='/panel-article-list-%s.html';</script>", sortlevel);

		return ;
	}
	
	id = tclistval2(_SERVER->_GET, 3);
	if(id == NULL || !is_digit(id))
	{
		puts("Content-type: text/html\r\n\r\n<script>alert('请您选择要更新的文章');window.location.href='/panel-article-list-all.html';</script>");
		return ;
	}

	tpl = tpl_alloc();
	if (tpl_load(tpl, "./templets/panel/article_update.html") != TPL_OK)
    {
		printf("Content-type: text/html\r\n\r\n./templets/panel/article_update.html Error loading template file!");
        tpl_free(tpl);
		return ;
    }
	
	//加载分类的数据
	rc = sqlite3_prepare(db, "SELECT sortname, sortdir FROM category", -1, &stmt, NULL);
	
	tpl_select_section(tpl, "classic");
	while((rc = sqlite3_step(stmt)) == SQLITE_ROW)
	{
		for(i=0; i<sqlite3_column_count(stmt); i++)
		{
			tpl_set_field(tpl, sqlite3_column_name(stmt,i) ,sqlite3_column_text(stmt,i), strlen(sqlite3_column_text(stmt,i)));
		}
		tpl_append_section(tpl);
	}

	tpl_deselect_section(tpl);
	sqlite3_finalize(stmt);
	
	//加载需要编辑的数据
	rc = sqlite3_prepare(db, "SELECT * FROM article WHERE art_id = ?", -1, &stmt, NULL);
	sqlite3_bind_int(stmt, 1, atoi(id));

	while((rc = sqlite3_step(stmt)) == SQLITE_ROW)
	{
		for(i=0; i<sqlite3_column_count(stmt); i++)
		{
			type = sqlite3_column_type(stmt, i);
			switch(type)
			{
				case SQLITE_INTEGER:
					tpl_set_field_uint_global(tpl, sqlite3_column_name(stmt,i), sqlite3_column_int(stmt, i));
					break;
				case SQLITE_TEXT:
					tpl_set_field_global(tpl, sqlite3_column_name(stmt,i) ,sqlite3_column_text(stmt,i), strlen(sqlite3_column_text(stmt,i)));
					break;
			}
		}
	}

	sqlite3_finalize(stmt);


	html = mspace_malloc(_SERVER->mp, tpl_length(tpl) + 1);
    tpl_get_content(tpl, html);

	printf("Content-type: text/html\r\n\r\n%s", html);
	
	tpl_free(tpl);
	mspace_free(_SERVER->mp, html);
	
	tpl  = NULL;
}
Exemplo n.º 12
0
void panel_article_insert(struct env_t *_SERVER)
{
	time_t       visit;
	tpl_t        *tpl;
	TCLIST       *arr;
	char         *html, path[128], buf[128];
	
	sqlite3_int64   id;
	sqlite3_stmt    *stmt;
	int             rc, i, pos, n, len;
	const char      *title, *sortlevel, *content, *recommend, *keyword, *filename, *file;

	if(tcmapget2(_SERVER->_POST, "Article_Insert"))
	{
		visit     = time((time_t*)0);
		file      = tcmapget2(_SERVER->_COOKIE, "file");
		title     = tcmapget2(_SERVER->_POST,   "title");
		content   = tcmapget2(_SERVER->_POST,   "content");
		keyword   = tcmapget2(_SERVER->_POST,   "keyword");
		filename  = tcmapget2(_SERVER->_POST,   "filename");
		sortlevel = tcmapget2(_SERVER->_POST,   "sortlevel");
		recommend = tcmapget2(_SERVER->_POST,   "recommend");
		
		pos = strpos(content, "<!-- idx -->");
		pos = (pos == -1) ? strlen(content) : pos;
		rc  = sqlite3_prepare(db, "INSERT INTO article(title, content, catid, keyword, filename, recommend, post_time, position, hit, comment_num) VALUES(?, ?, ?, ?, ?, ?, ?, ?, 0, 0);", -1, &stmt, NULL); 
		
		sqlite3_bind_text(stmt, 1, title,     -1, SQLITE_STATIC);
		sqlite3_bind_text(stmt, 2, content,   -1, SQLITE_STATIC);
		sqlite3_bind_text(stmt, 3, sortlevel, -1, SQLITE_STATIC);
		sqlite3_bind_text(stmt, 4, keyword,   -1, SQLITE_STATIC);
		sqlite3_bind_text(stmt, 5, filename,  -1, SQLITE_STATIC);

		sqlite3_bind_int(stmt, 6, atoi(recommend));
		sqlite3_bind_int(stmt, 7, visit);
		sqlite3_bind_int(stmt, 8, pos);

		
		sqlite3_step(stmt); 
		sqlite3_finalize(stmt); 
		
		id = sqlite3_last_insert_rowid(db);
				
		if(file)
		{
			memset(buf,  0, sizeof(buf));
			memset(path, 0, sizeof(path));
			
			strftime(buf, sizeof(buf), "%Y/%m/%d", localtime(&visit));

			//如果有上传的文件,就把上传的文件,从临时目录移动目标目录
			len = snprintf(path, sizeof(path), "./attachment/%s/%llu/", buf, id);
			
			if(!is_dir(path)) mkpath(_SERVER->mp, path, 0777);
			if(!strchr(file, '|'))
			{
				memset(buf,  0, sizeof(buf));
				snprintf(buf, sizeof(buf), "./files/%s", file);
				strcat(path, file);
				
			//	log_debug("panel_article_insert buf = %s\tpath = %s\r\n", buf, path);
				if(file_exists(buf)) rename(buf, path);
			}
			else
			{
				arr = explode("|", (char *)file);
				n   = tclistnum(arr);
				for(i=0; i<n; i++)
				{
					memset(buf,  0, sizeof(buf));
					filename = tclistval2(arr, i);
					snprintf(buf, sizeof(buf), "./files/%s", filename);

					path[len] = '\0';
					strcat(path, filename);

		//			log_debug("panel_article_insert explode buf = %s\tpath = %s\r\n", buf, path);

					if(file_exists(buf)) rename(buf, path);
				}
				tclistdel(arr);
			}
			
			path[len] = '\0';
			

			//更新图片附件的 路径
			rc = sqlite3_prepare(db, "UPDATE article SET content = replace(content, '/files/', ?) WHERE art_id = ?;", -1, &stmt, NULL);
			
			sqlite3_bind_text(stmt,  1, path+1, -1, SQLITE_STATIC);
			sqlite3_bind_int64(stmt, 2, id);
			sqlite3_step(stmt); 
			sqlite3_finalize(stmt); 
			
		}
		

#ifdef _BUILD_HTML
		memset(path, 0, sizeof(path));
		snprintf(path, sizeof(path), "./html/list/%s", sortlevel);
		ftw(path, fn, 500);
#endif
		make_article_index(_SERVER);
		printf("Content-type: text/html\r\n\r\n<script>alert('添加成功!');window.location.href='/panel-article-list-%s.html';</script>", sortlevel);

		return ;
	}
	

	tpl = tpl_alloc();
	if (tpl_load(tpl, "./templets/panel/article_insert.html") != TPL_OK)
    {
		puts("Content-type: text/html\r\n\r\n./templets/panel/article_insert.html Error loading template file!");
        tpl_free(tpl);
		return ;
    }

	rc = sqlite3_prepare(db, "SELECT sortname, sortdir FROM category", -1, &stmt, NULL);
	
	tpl_select_section(tpl, "classic");
	while((rc = sqlite3_step(stmt)) == SQLITE_ROW)
	{
		for(i=0; i<sqlite3_column_count(stmt); i++)
		{
			tpl_set_field(tpl, sqlite3_column_name(stmt,i) ,sqlite3_column_text(stmt,i), strlen(sqlite3_column_text(stmt,i)));
		}

		tpl_append_section(tpl);
	}

	tpl_deselect_section(tpl);
	sqlite3_finalize(stmt);


	html = mspace_malloc(_SERVER->mp, tpl_length(tpl) + 1);
    tpl_get_content(tpl, html);

	printf("Content-type: text/html\r\n\r\n%s", html);
	
	tpl_free(tpl);
	mspace_free(_SERVER->mp, html);
	
	tpl  = NULL;
}
Exemplo n.º 13
0
void search_cb(struct evhttp_request *req, struct evbuffer *evb, void *ctx)
{
    char *uri, *json;
    double lat, lng, distance, minlat, minlng, maxlat, maxlng, miles, lat2, lng2;
    int x1, x2, y1, y2, id, max;
    int total;
    struct evkeyvalq args;
    int ecode, pksiz, i, rsiz;
    char pkbuf[256];
    char minx[8];
    char miny[8];
    char maxx[8];
    char maxy[8];
    const char *rbuf, *name, *buf;
    RDBQRY *query;
    TCLIST *result;
    TCMAP *cols;
    Geo_Result *georesultPtr, **georesults;
    struct json_object *jsobj, *jsobj2, *jsarr;

    if (rdb == NULL) {
        evhttp_send_error(req, 503, "database not connected");
        return;
    }

    uri = evhttp_decode_uri(req->uri);
    evhttp_parse_query(uri, &args);
    free(uri);

    argtof(&args, "lat", &lat, 0);
    argtof(&args, "lng", &lng, 0);
    argtof(&args, "miles", &miles, 0);
    argtoi(&args, "max", &max, 1);
    
    geo_box(lat, lng, miles, &minlat, &minlng, &maxlat, &maxlng);
    
    x1 = (minlat * 10000) + 1800000;
    y1 = (minlng * 10000) + 1800000;
    x2 = (maxlat * 10000) + 1800000;
    y2 = (maxlng * 10000) + 1800000;
    
    sprintf(minx, "%d", x1);
    sprintf(miny, "%d", y1);
    sprintf(maxx, "%d", x2);
    sprintf(maxy, "%d", y2);
        
    query = tcrdbqrynew(rdb);
    tcrdbqryaddcond(query, "x", RDBQCNUMGT, minx);
    tcrdbqryaddcond(query, "x", RDBQCNUMLT, maxx);
    tcrdbqryaddcond(query, "y", RDBQCNUMGT, miny);
    tcrdbqryaddcond(query, "y", RDBQCNUMLT, maxy);
    tcrdbqrysetorder(query, "x", RDBQONUMASC);
    
    cols = tcmapnew();
    result = tcrdbqrysearch(query);
    total = tclistnum(result);
    
    georesults = malloc(sizeof(Geo_Result *) * total);
    
    for(i = 0; i < total; i++){
        rbuf = tclistval(result, i, &rsiz);
        cols = tcrdbtblget(rdb, rbuf, rsiz);
        
        if (cols) {
            georesultPtr = malloc(sizeof(*georesultPtr));
            
            tcmapiterinit(cols);
            buf = tcmapget2(cols, "lat");
            lat2 = atof(buf);
            georesultPtr->latitude = lat2;
            buf = tcmapget2(cols, "lng");
            lng2 = atof(buf);
            georesultPtr->longitude = lng2;
            id = atoi(rbuf);
            georesultPtr->id = id;
            georesultPtr->data = strdup(tcmapget2(cols, "data"));
            distance = geo_distance(lat, lng, lat2, lng2);
            georesultPtr->distance = distance;
            georesults[i] = georesultPtr;
            tcmapdel(cols);
        }
    }
    
    tclistdel(result);
    tcrdbqrydel(query);
    
    qsort(georesults, total, sizeof(Geo_Result *), CmpElem);
    
    jsobj = json_object_new_object();
    jsarr = json_object_new_array();
    
    for(i = 0; i < total; i++){
        georesultPtr = georesults[i];

        if (i < max) {
            jsobj2 = json_object_new_object();
            json_object_object_add(jsobj2, "id", json_object_new_int(georesultPtr->id));
            json_object_object_add(jsobj2, "data", json_object_new_string(georesultPtr->data));
            json_object_object_add(jsobj2, "latitude", json_object_new_double(georesultPtr->latitude));
            json_object_object_add(jsobj2, "longitude", json_object_new_double(georesultPtr->longitude));
            json_object_object_add(jsobj2, "distance", json_object_new_double(georesultPtr->distance));
            json_object_array_add(jsarr, jsobj2);
        }
        free(georesultPtr->data);
        free(georesultPtr);
    }
    
    free(georesults);
    
    json_object_object_add(jsobj, "total", json_object_new_int(total));
    json_object_object_add(jsobj, "results", jsarr);
    
    finalize_json(req, evb, &args, jsobj);
}
Exemplo n.º 14
0
/* perform import command */
static int procimport(const char *dbpath, TCLIST *files, TCLIST *sufs){
  TCTDB *tdb = tctdbnew();
  if(!tctdbtune(tdb, TUNEBNUM, TUNEAPOW, TUNEFPOW, 0)){
    printdberr(tdb);
    tctdbdel(tdb);
    return 1;
  }
  if(!tctdbopen(tdb, dbpath, TDBOWRITER | TDBOCREAT)){
    printdberr(tdb);
    tctdbdel(tdb);
    return 1;
  }
  bool err = false;
  if(!tctdbsetindex(tdb, "name", TDBITLEXICAL | TDBITKEEP) && tctdbecode(tdb) != TCEKEEP){
    printdberr(tdb);
    err = true;
  }
  if(!tctdbsetindex(tdb, "cdate", TDBITDECIMAL | TDBITKEEP) && tctdbecode(tdb) != TCEKEEP){
    printdberr(tdb);
    err = true;
  }
  if(!tctdbsetindex(tdb, "mdate", TDBITDECIMAL | TDBITKEEP) && tctdbecode(tdb) != TCEKEEP){
    printdberr(tdb);
    err = true;
  }
  if(!tctdbsetindex(tdb, "xdate", TDBITDECIMAL | TDBITKEEP) && tctdbecode(tdb) != TCEKEEP){
    printdberr(tdb);
    err = true;
  }
  tclistinvert(files);
  char *fpath;
  while((fpath = tclistpop2(files)) != NULL){
    TCLIST *cfiles = tcreaddir(fpath);
    if(cfiles){
      tclistsort(cfiles);
      for(int i = tclistnum(cfiles) - 1; i >= 0; i--){
        const char *cfile = tclistval2(cfiles, i);
        bool hit = false;
        for(int j = 0; j < tclistnum(sufs); j++){
          if(tcstribwm(cfile, tclistval2(sufs, j))){
            hit = true;
            break;
          }
        }
        if(!hit) continue;
        char *lpath = tcsprintf("%s/%s", fpath, cfile);
        tclistpush2(files, lpath);
        tcfree(lpath);
      }
      tclistdel(cfiles);
    } else {
      int isiz;
      char *ibuf = tcreadfile(fpath, IOMAXSIZ, &isiz);
      if(ibuf){
        TCMAP *cols = tcmapnew2(TINYBNUM);
        wikiload(cols, ibuf);
        const char *name = tcmapget2(cols, "name");
        if(name && *name != '\0'){
          int64_t id = tcatoi(tcmapget4(cols, "id", ""));
          if(dbputart(tdb, id, cols)){
            id = tcatoi(tcmapget4(cols, "id", ""));
            printf("%s: imported: id=%lld name=%s\n", fpath, (long long)id, name);
          } else {
            printdberr(tdb);
            err = true;
          }
        } else {
          printf("%s: ignored because there is no name\n", fpath);
        }
        tcmapdel(cols);
        tcfree(ibuf);
      }
    }
    tcfree(fpath);
  }
  if(!tctdbclose(tdb)){
    printdberr(tdb);
    err = true;
  }
  tctdbdel(tdb);
  return err ? 1 : 0;
}