code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
#include <iostream> #include <vector>` #include <set> #include <algorithm> using std::vector; using std::cin; using std::cout; using std::set; using std::pair; using std::make_pair; using std::min; class Field { struct Point { int x, y, weight; Point(): x(0), y(0), weight(0){} Point(int new_x, int new_y, int new_weight): x(new_x), y(new_y), weight(new_weight) {} bool operator<(Point other) const { return weight < other.weight; } }; int height; int width; vector < vector <Point> > field; void make_neighbour_list(Point &point, vector <Point> &list) { if (point.x < height - 1) { list.push_back(field[point.x + 1][point.y]); } if (point.y < width - 1) { list.push_back(field[point.x][point.y + 1]); } } public: Field(int new_height, int new_weight) { height = new_height; width = new_weight; vector <Point> line(width); field.assign(height, line); for (int line = 0; line != height; ++line) { for (int col = 0; col != width; ++col) { int weight; cin >> weight; field[line][col] = Point(line, col, weight); } } } vector<Point> operator[](int &line) { return field[line]; } int find_path_width() { vector < vector <int> > path_weight; vector <int> line(width, 0); path_weight.assign(height, line); path_weight[0][0] = field[0][0].weight; for (int i = 0; i < height; ++i) { for (int j = 0; j < width; ++j) { if (!(i == 0 && j == 0)) { int up = 0; int left = 0; if (i > 0) { up = path_weight[i - 1][j]; } if (j > 0) { left = path_weight[i][j - 1]; } if (field[i][j].weight == 1) { path_weight[i][j] = (left + up) % 268435459; } } } } return (path_weight[height - 1][width - 1]); } }; int main () { int n, m; cin >> n >> m; Field field(n, m); cout << field.find_path_width(); }
1012-group-trunk
trunk/Pushin/Homework_2/1-2.cpp
C++
gpl3
1,938
#include <algorithm> #include <cstdio> #include <iostream> #include <vector> using std::cin; using std::cout; using std::vector; template <typename InputIterator> void iteration(InputIterator first, InputIterator last) { if (first == last) { return; } auto max_iterator = first, last_elem_iterator = last; --last_elem_iterator; for (auto index_iterator = first; index_iterator != last; ++index_iterator) { if (*index_iterator > *max_iterator) { max_iterator = index_iterator; } } iter_swap(last_elem_iterator, max_iterator); } void input(int &n, vector <int> &lst) { cin >> n; lst.resize(n); for (int i = 0; i < n; i++) { cin >> lst[i]; } } void output(const vector <int> &lst) { for (size_t i = 0; i < lst.size(); i++) { cout << lst[i] << ' '; } } int main() { vector <int> lst; int n; input(n, lst); iteration(lst.begin(), lst.end()); output(lst); return 0; }
1012-group-trunk
trunk/mokriy/A.cpp
C++
gpl3
997
#include <algorithm> #include <cstdio> #include <iostream> #include <vector> using std::cin; using std::cout; using std::vector; template <typename InputIterator, typename TKey> InputIterator my_partition(InputIterator begin, InputIterator end, TKey key) { auto iter = begin; while (begin != end) { if (*begin < key) { iter_swap(iter, begin); ++iter; } ++begin; } return iter; } void input(vector <int> &lst, int &x) { int n; cin >> n; lst.resize(n); for (int i = 0; i < n; i++) { cin >> lst[i]; } cin >> x; } void output(int a, int b) { cout << a << '\n' << b; } int main() { int x; vector <int> lst; input(lst, x); auto iter = my_partition(lst.begin(), lst.end(), x); output(iter - lst.begin(), lst.end() - iter); return 0; }
1012-group-trunk
trunk/mokriy/E.cpp
C++
gpl3
857
#include <algorithm> #include <cstdio> #include <iostream> #include <vector> using std::cin; using std::copy; using std::cout; using std::vector; template <typename InputIterator, typename OutputIterator> void my_merge(InputIterator first_begin, InputIterator first_end, InputIterator second_begin, InputIterator second_end, OutputIterator out_begin) { while (first_begin != first_end && second_begin != second_end) { if (*first_begin < *second_begin) { *out_begin = *first_begin; ++first_begin; } else { *out_begin = *second_begin; ++second_begin; } ++out_begin; } while (first_begin != first_end) { *out_begin = *first_begin; ++first_begin, ++out_begin; } while (second_begin != second_end) { *out_begin = *second_begin; ++second_begin, ++out_begin; } } template <typename InputIterator> void merge_sort(InputIterator begin, InputIterator end) { int length = end - begin; if (length <= 1) { return; } InputIterator middle = begin + length / 2; auto for_type = *begin; vector <decltype(for_type)> out(length); merge_sort(begin, middle); merge_sort(middle, end); my_merge(begin, middle, middle, end, out.begin()); copy(out.begin(), out.end(), begin); } void input(vector <int> &lst) { int n; cin >> n; lst.resize(n); for (int i = 0; i < n; i++) { cin >> lst[i]; } } void output(const vector <int> &lst) { for (size_t i = 0; i < lst.size(); i++) { cout << lst[i] << ' '; } } int main() { vector <int> lst; input(lst); merge_sort(lst.begin(), lst.end()); output(lst); return 0; }
1012-group-trunk
trunk/mokriy/D.cpp
C++
gpl3
1,748
#include <algorithm> #include <cstdio> #include <iostream> #include <vector> using std::cin; using std::cout; using std::vector; template <typename InputIterator, typename OutputIterator> void my_merge(InputIterator first_begin, InputIterator first_end, InputIterator second_begin, InputIterator second_end, OutputIterator out_begin) { while (first_begin != first_end && second_begin != second_end) { if (*first_begin < *second_begin) { *out_begin = *first_begin; ++first_begin; } else { *out_begin = *second_begin; ++second_begin; } ++out_begin; } while (first_begin != first_end) { *out_begin = *first_begin; ++first_begin, ++out_begin; } while (second_begin != second_end) { *out_begin = *second_begin; ++second_begin, ++out_begin; } } void input(vector <int> &lst) { int n; cin >> n; lst.resize(n); for (int i = 0; i < n; i++) { cin >> lst[i]; } } void output(const vector <int> &lst) { for (size_t i = 0; i < lst.size(); i++) { cout << lst[i] << ' '; } } int main() { vector <int> first_lst, second_lst, output_lst; input(first_lst); input(second_lst); output_lst.resize(first_lst.size() + second_lst.size()); my_merge(first_lst.begin(), first_lst.end(), second_lst.begin(), second_lst.end(), output_lst.begin()); output(output_lst); return 0; }
1012-group-trunk
trunk/mokriy/C.cpp
C++
gpl3
1,493
#include <algorithm> #include <cstdio> #include <iostream> #include <vector> using std::cin; using std::cout; using std::vector; template <typename InputIterator> void iteration(InputIterator first, InputIterator last) { if (first == last) { return; } auto max_iterator = first, last_elem_iterator = last; --last_elem_iterator; for (auto index_iterator = first; index_iterator != last; ++index_iterator) { if (*index_iterator > *max_iterator) { max_iterator = index_iterator; } } iter_swap(last_elem_iterator, max_iterator); } template <typename InputIterator> void my_sort(InputIterator first, InputIterator last) { for (auto end = last; first != end; --end) { iteration(first, end); } } void input(int &n, vector <int> &lst) { cin >> n; lst.resize(n); for (int i = 0; i < n; i++) { cin >> lst[i]; } } void output(const vector <int> &lst) { for (size_t i = 0; i < lst.size(); i++) { cout << lst[i] << ' '; } } int main() { vector <int> lst; int n; input(n, lst); my_sort(lst.begin(), lst.end()); output(lst); return 0; }
1012-group-trunk
trunk/mokriy/B.cpp
C++
gpl3
1,173
#include <iostream> #include <cstdio> #include <vector> using std::vector; using std::cin; using std::cout; using std::min; void input(vector <vector <int> > &cost, vector <vector <int> > &dp) { int n, m; cin >> n >> m; cost.resize(n); dp.resize(n); for (int i = 0; i < n; i++) { dp[i].resize(m); cost[i].resize(m); for (int j = 0; j < m; j++) { cin >> cost[i][j]; } } } void solution(const vector <vector <int> > &cost, vector <vector <int> > &dp) { dp[0][0] = cost[0][0]; for (int i = 1; i < cost.size(); i++) { dp[i][0] = dp[i - 1][0] + cost[i][0]; } for (int i = 1; i < cost[0].size(); i++) { dp[0][i] = dp[0][i - 1] + cost[0][i]; } for (int i = 1; i < cost.size(); i++) { for (int j = 1; j < cost[i].size(); j++) { dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + cost[i][j]; } } } void output(const vector <vector <int> > &dp) { cout << dp.back().back(); } int main() { vector <vector <int> > cost, dp; input(cost, dp); solution(cost, dp); output(dp); return 0; }
1012-group-trunk
trunk/mokriy/homework2/A.cpp
C++
gpl3
1,135
#include <iostream> #include <cstdio> #include <vector> #include <deque> #include <algorithm> using std::vector; using std::cin; using std::cout; using std::min; using std::pair; using std::reverse; void input(vector < vector <int> > &lst) { int n, a, b; cin >> n; lst.resize(2 * n); for (int i = 0; i < 2 * n; i += 2) { lst[i].push_back(i + 1); } cin >> a >> b; for (int i = 0; i < a; i++) { int x, y; cin >> x >> y; lst[2 * x - 1].push_back(2 * y - 2); } for (int i = 0; i < b; i++) { int x, y; cin >> x >> y; lst[2 * x - 2].push_back(2 * y - 1); lst[2 * y - 2].push_back(2 * x - 1); } } bool dfs(int s, const vector < vector <int> > &lst, vector <char> &used, vector <int> &topsort) { bool flag = true; used[s] = 1; for (int i = 0; i < lst[s].size(); i++) { int to = lst[s][i]; if (used[to] == 1) { return false; } if (!used[to]) { flag &= dfs(to, lst, used, topsort); } } used[s] = 2; topsort.push_back(s); return flag; } bool solution(const vector < vector <int> > &lst, vector <pair <int, int> > &segments) { bool flag = true; vector <int> topsort; vector <char> used(lst.size(), 0); for (int i = 0; i < lst.size(); i++) { if (!used[i]) { flag &= dfs(i, lst, used, topsort); } } reverse(topsort.begin(), topsort.end()); if (flag) { segments.resize(lst.size() / 2); for (int i = 0; i < topsort.size(); i++) { if(topsort[i] & 1) { segments[topsort[i] / 2].second = i; } else { segments[topsort[i] / 2].first = i; } } } return flag; } void output(bool answer, const vector <pair <int, int> > &segments) { if(!answer) { cout << "Impossible"; return; } for (int i = 0; i < segments.size(); i++) { cout << segments[i].first << ' ' << segments[i].second << '\n'; } } int main() { vector <pair <int, int> > segments; vector < vector <int> > lst; bool answer; input(lst); answer = solution(lst, segments); output(answer, segments); return 0; }
1012-group-trunk
trunk/mokriy/homework2/E.cpp
C++
gpl3
2,276
#include <iostream> #include <cstdio> #include <vector> #include <deque> using std::vector; using std::cin; using std::cout; using std::min; using std::pair; using std::deque; using std::make_pair; int dx[] = {0, 0, -1, 1}; int dy[] = {1, -1, 0, 0}; void input(vector < vector <int> > &matrix, pair <int, int> &s, pair <int, int> &f) { int m, n; cin >> n >> m; cin >> s.first >> s.second; cin >> f.first >> f.second; --s.first, --s.second, --f.first, --f.second; matrix.resize(n); for (int i = 0; i < n; i++) { matrix[i].resize(m); for (int j = 0; j < m; j++) { cin >> matrix[i][j]; } } } bool is_vertex(const pair <int, int> &a, int n, int m, const vector < vector <int> > &matrix, const vector < vector <int> > &dist) { return a.first >= 0 && a.second >= 0 && a.first < n && a.second < m && !matrix[a.first][a.second] && dist[a.first][a.second] == -1; } void bfs(const pair <int, int> &s, const vector < vector <int> > &matrix, vector < vector <int> > &dist) { int n = matrix.size(), m = matrix[0].size(); deque < pair <int, int> > Deque; dist[s.first][s.second] = 0; Deque.push_back(s); while (!Deque.empty()) { pair <int, int> k = Deque[0]; Deque.pop_front(); for (int i = 0; i < 4; i++) { pair <int, int> to = make_pair(k.first + dx[i], k.second + dy[i]); if(is_vertex(to, n, m, matrix, dist)) { dist[to.first][to.second] = dist[k.first][k.second] + 1; Deque.push_back(to); } } } } int solution(const vector < vector <int> > &matrix, pair <int, int> &s, pair <int, int> &f) { vector < vector <int> > dist; dist.resize(matrix.size()); for (int i = 0; i < dist.size(); i++) { dist[i].resize(matrix[i].size(), -1); } bfs(s, matrix, dist); return dist[f.first][f.second]; } void output(int answer) { if (answer == -1) { cout << "NO"; } else { cout << answer; } } int main() { vector < vector <int> > matrix; pair <int, int> s, f; int answer; input(matrix, s, f); answer = solution(matrix, s, f); output(answer); return 0; }
1012-group-trunk
trunk/mokriy/homework2/D.cpp
C++
gpl3
2,253
#include <iostream> #include <cstdio> #include <vector> using std::vector; using std::cin; using std::cout; using std::min; struct Point { int x, y; Point(int x = 0, int y = 0) : x(x), y(y) {} int dist(const Point &other) const { return (x - other.x) * (x - other.x) + (y - other.y) * (y - other.y); } }; void input(vector <Point> &lst, int &k) { int n; cin >> n >> k; lst.resize(n); for (int i = 0; i < n; i++) { cin >> lst[i].x >> lst[i].y; } } bool is_edge(Point a, Point b, int k) { return a.dist(b) <= k * k; } int dfs(int s, const vector <Point> &lst, vector <bool> &used, int k) { int cnt = 1; used[s] = true; for (int i = 0; i < lst.size(); i++) { if(!used[i] && is_edge(lst[s], lst[i], k)) { cnt += dfs(i, lst, used, k); } } return cnt; } bool solution(const vector <Point> &lst, int k) { vector <bool> used; used.assign(lst.size(), false); int cnt = dfs(0, lst, used, k); return cnt == lst.size(); } bool output(bool answer) { if(answer) { cout << "YES"; } else { cout << "NO"; } } int main() { vector <Point> lst; int k; bool answer; input(lst, k); answer = solution(lst, k); output(answer); return 0; }
1012-group-trunk
trunk/mokriy/homework2/C.cpp
C++
gpl3
1,299
#include <iostream> #include <cstdio> #include <vector> using std::vector; using std::cin; using std::cout; using std::min; const int MOD = 268435459; void input(vector <vector <int> > &open, vector <vector <int> > &dp) { int n, m; cin >> n >> m; open.resize(n); dp.resize(n); for (int i = 0; i < n; i++) { dp[i].resize(m); open[i].resize(m); for (int j = 0; j < m; j++) { cin >> open[i][j]; } } } void solution(const vector <vector <int> > &open, vector <vector <int> > &dp) { dp[0][0] = open[0][0]; for (int i = 1; i < open.size(); i++) { dp[i][0] = dp[i - 1][0] * open[i][0]; } for (int i = 1; i < open[0].size(); i++) { dp[0][i] = dp[0][i - 1] * open[0][i]; } for (int i = 1; i < open.size(); i++) { for (int j = 1; j < open[i].size(); j++) { dp[i][j] = (dp[i - 1][j] + dp[i][j - 1]) * open[i][j] % MOD; } } } void output(const vector <vector <int> > &dp) { cout << dp.back().back(); } int main() { vector <vector <int> > open, dp; input(open, dp); solution(open, dp); output(dp); return 0; }
1012-group-trunk
trunk/mokriy/homework2/B.cpp
C++
gpl3
1,168
#include <algorithm> #include <cstdio> #include <iostream> #include <vector> using std::cin; using std::cout; using std::vector; using std::pair; template <typename InputIterator, typename TKey> pair <InputIterator, InputIterator> my_partition(InputIterator begin, InputIterator end, TKey key) { auto left = begin; while (begin != end) { if (*begin < key) { iter_swap(left, begin); ++left; } ++begin; } auto right = begin = left; while (begin != end) { if (*begin == key) { iter_swap(right, begin); ++right; } ++begin; } return make_pair(left, right); } template <typename InputIterator> void qsort(InputIterator begin, InputIterator end) { int length = end - begin; if (length <= 1) { return; } auto pair_middle = my_partition(begin, end, *(begin + rand() % length)); qsort(begin, pair_middle.first); qsort(pair_middle.second, end); } void input(vector <int> &lst) { int n; cin >> n; lst.resize(n); for (int i = 0; i < n; i++) { cin >> lst[i]; } } void output(const vector <int> &lst) { for (size_t i = 0; i < lst.size(); i++) { cout << lst[i] << ' '; } } int main() { vector <int> lst; input(lst); qsort(lst.begin(), lst.end()); output(lst); return 0; }
1012-group-trunk
trunk/mokriy/F.cpp
C++
gpl3
1,431
#include <iostream> #include "Matrix.h" using namespace std; int main() { cout<<"Main"<<endl; return 0; }
12beseughauri-lab02
trunk/Main.cpp
C++
mit
116
class Matrix { int **matrix; int size; public: Matrix(); Matrix(int); void initialize(int[3][3]); void set(int,int,int); int get(int,int); Matrix* operator + (Matrix&); Matrix* operator - (Matrix&); Matrix* operator * (Matrix&); ~Matrix(); };
12beseughauri-lab02
trunk/Matrix.h
C++
mit
268
#include <limits.h> #include "Matrix.h" #include "gtest/gtest.h" TEST(Test1, Add_two_matrices) { Matrix A(3), B(3), *C; int input1[3][3] = {{1,3,2},{2,5,4},{6,7,1}}; int input2[3][3] = {{1,7,5},{3,5,5},{-1,4,-2}}; int output[3][3] = {{2,10,7},{5,10,9},{5,11,-1}}; A.initialize(input1); B.initialize(input2); C = A + B; for(int i=0; i<3; i++) for(int j=0; j<3; j++) EXPECT_EQ(C->get(i,j), output[i][j]); } TEST(Test2, Multiply_two_matrices) { Matrix A(3), B(3), *C; int input1[3][3] = {{1,3,2},{2,5,4},{6,7,1}}; int input2[3][3] = {{1,7,5},{3,5,5},{-1,4,-2}}; int output[3][3] = {{8,30,16},{13,55,27},{26,81,63}}; A.initialize(input1); B.initialize(input2); C = A * B; for(int i=0; i<3; i++) for(int j=0; j<3; j++) EXPECT_EQ(C->get(i,j), output[i][j]); } TEST(Test3, Multiply_and_Add) { Matrix A(3), B(3), C(3), *D; int input1[3][3] = {{1,3,2},{2,5,4},{6,7,1}}; int input2[3][3] = {{1,7,5},{3,5,5},{-1,4,-2}}; int input3[3][3] = {{-5,7,1},{9,-9,0},{3,2,-1}}; int output[3][3] = {{3,37,17},{22,46,27},{29,83,62}}; A.initialize(input1); B.initialize(input2); C.initialize(input3); D = *(A * B) + C; for(int i=0; i<3; i++) for(int j=0; j<3; j++) EXPECT_EQ(D->get(i,j), output[i][j]); }
12beseughauri-lab02
trunk/unittest.cc
C++
mit
1,234
#include <iostream> #include "Matrix.h" using namespace std; Matrix::Matrix() { } Matrix::Matrix(int n) { size = n; matrix = new int*[size]; for(int i=0; i<size; i++) matrix[i] = new int[size]; } void Matrix::initialize(int values[3][3]) { for(int i=0; i<size; i++) for(int j=0; j<size; j++) matrix[i][j] = values[i][j]; } void Matrix::set(int i, int j, int v) { matrix[i][j] = v; } int Matrix::get(int i, int j) { return matrix[i][j]; } Matrix* Matrix::operator + (Matrix& m) { Matrix *result = new Matrix(size); for(int i=0; i<size; i++) for(int j=0; j<size; j++) { int temp = this->matrix[i][j] + m.get(i,j); result->set(i,j,temp); } return result; } Matrix* Matrix::operator - (Matrix& m) { Matrix *result = new Matrix(size); for(int i=0; i<size; i++) for(int j=0; j<size; j++) { int temp = matrix[i][j] - m.get(i,j); result->set(i,j,temp); } return result; } Matrix* Matrix::operator * (Matrix& m) { Matrix *result = new Matrix(size); for(int i=0; i<size; i++) { for(int j=0; j<size; j++) { int temp = 0; for(int k=0; k<size; k++) temp += matrix[i][k]*m.get(k,j); result->set(i,j,temp); } } return result; } Matrix::~Matrix() { for(int i=0; i<size; i++) delete [] matrix[i]; delete [] matrix; }
12beseughauri-lab02
trunk/Matrix.cpp
C++
mit
1,359
#include<stdio.h> #include<string.h> #include<sqlite3.h> #include "dhcp_log.h" #include "dhcp_server.h" extern struct server_config gobal_config; int sqlite_ip_allocator(struct network_config *config) { INFO("==>sqlite_ip_allocate"); sqlite3 *db = NULL; int ret = sqlite3_open(gobal_config.ip_allocator_file, &db); if(SQLITE_OK != ret) { ERROR("***sqlite3_open ERROR!!! %s(%d)***", sqlite3_errmsg(db), ret); goto ERROR; } sqlite3_stmt *statement = NULL; //get gateway, netmask, dns1 & dns2 //create table network_config( //gateway text, //netmask text, //dns1 text, //dns2 text) ret = sqlite3_prepare(db, "select * from network_config", 128, &statement, NULL); if(SQLITE_OK != ret) { ERROR("***sqlite3_prepare ERROR!!! %s(%d)***", sqlite3_errmsg(db), ret); goto ERROR; } ret = sqlite3_step(statement); if(SQLITE_ROW != ret) { ERROR("***sqlite3_step ERROR!!! %s(%d)***", sqlite3_errmsg(db), ret); goto ERROR; } char asc_gateway[16] = {0}; char asc_netmask[16] = {0}; char asc_dns1[16] = {0}; char asc_dns2[16] = {0}; char asc_ip_address[16] = {0}; const char *value = sqlite3_column_text(statement, 0); strncpy(asc_gateway, value, 16); value = sqlite3_column_text(statement, 1); strncpy(asc_netmask, value, 16); value = sqlite3_column_text(statement, 2); strncpy(asc_dns1, value, 16); value = sqlite3_column_text(statement, 3); strncpy(asc_dns2, value, 16); sqlite3_finalize(statement); DEBUG("gateway=%s, netmask=%s, dns1=%s, dns2=%s", asc_gateway, asc_netmask, asc_dns1, asc_dns2); //convert mac address to 64-bit int. //the first 6 bytes of network_config.hardware_address //should be mac address. uint64_t mac = 0x0000000000000000; int i = 0; for(i = 0; i < 6; i++) { mac *= 0x100; DEBUG("mac=%lx", mac); mac += (uint8_t)config->hardware_address[i]; DEBUG("mac=%lx", mac); } DEBUG("mac address=%02x:%02x:%02x:%02x:%02x:%02x, integer value=%ld", (uint8_t)config->hardware_address[0], (uint8_t)config->hardware_address[1], (uint8_t)config->hardware_address[2], (uint8_t)config->hardware_address[3], (uint8_t)config->hardware_address[4], (uint8_t)config->hardware_address[5], mac); char sql[128] = {0}; snprintf(sql, 128, "select * from mac_ip where mac = %ld", mac); ret = sqlite3_prepare(db, sql, 128, &statement, NULL); if(SQLITE_OK != ret) { ERROR("***sqlite3_prepare ERROR!!! %s(%d)***", sqlite3_errmsg(db), ret); goto ERROR; } ret = sqlite3_step(statement); if(SQLITE_ROW != ret) { ERROR("***sqlite3_step ERROR!!! %s(%d)***", sqlite3_errmsg(db), ret); goto ERROR; } value = sqlite3_column_text(statement, 1); strncpy(asc_ip_address, value, 16); DEBUG("Allocate IP address: %s", asc_ip_address); sqlite3_finalize(statement); sqlite3_close(db); ip_asc2bytes(config->router, asc_gateway); ip_asc2bytes(config->netmask, asc_netmask); ip_asc2bytes(config->dns1, asc_dns1); ip_asc2bytes(config->dns2, asc_dns2); ip_asc2bytes(config->ip_address, asc_ip_address); INFO("sqlite_ip_allocator==>"); return 0; ERROR: WARN("***ERROR sqlite_ip_allocator==>***"); return -1; } ip_allocator ip_allocator_handler = &sqlite_ip_allocator;
0vishnutsuresh0-a
ip_allocator.c
C
asf20
3,356
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<errno.h> #include "dhcp_packet.h" #include "dhcp_log.h" char DHCP_MAGIC_COOKIE[4] = {0x63, 0x82, 0x53, 0x63}; //Caller need to free the memory used for the DHCP packet struct dhcp_packet *marshall(char buffer[], int offset, int length) { INFO("==>marshall, offset=%d, length=%d", offset, length); struct dhcp_packet *packet = NULL; //first check if the arguments is valid if(NULL == buffer) { ERROR("***BUFFER for marshall is NULL***"); goto ERROR; } if(length < BOOTP_ABSOLUTE_MIN_LEN) { ERROR("The length of dhcp packet is less than min size"); goto ERROR; } if(length > DHCP_MAX_MTU) { ERROR("The length of dhcp packet is more than max MTU"); goto ERROR; } packet = (struct dhcp_packet*)malloc(sizeof(struct dhcp_packet)); if(NULL == packet) { FATAL("***Allocate memory failed! %s(%d)***", strerror(errno), errno); goto ERROR; } memset(packet, 0, sizeof(struct dhcp_packet)); void* packet_begin = buffer + offset; //parse static part of packet memcpy(&(packet->op), packet_begin, 1); memcpy(&(packet->htype), packet_begin + 1, 1); memcpy(&(packet->hlen), packet_begin + 2, 1); memcpy(&(packet->hops), packet_begin + offset + 3, 1); memcpy(packet->xid, packet_begin + 4, 4); memcpy(packet->secs, packet_begin + 8, 2); memcpy(packet->flags, packet_begin + 10, 2); memcpy(packet->ciaddr, packet_begin + 12, 4); memcpy(packet->yiaddr, packet_begin + 16, 4); memcpy(packet->siaddr, packet_begin + 20, 4); memcpy(packet->giaddr, packet_begin + 24, 4); memcpy(packet->chaddr, packet_begin + 28, 16); memcpy(packet->sname, packet_begin + 44, 64); memcpy(packet->file, packet_begin + 108, 128); DEBUG("--------------DUMP DHCP PACKET-------------"); DEBUG("packet->op=%d", packet->op); DEBUG("packet->htype=%d", packet->htype); DEBUG("packet->hlen=%d", packet->hlen); DEBUG("packet->hops=%d", packet->hops); DEBUG("packet->xid=%x,%x,%x,%x", packet->xid[0], packet->xid[1], packet->xid[2], packet->xid[3]); DEBUG("packet->secs=%x,%x", packet->secs[0], packet->secs[1]); DEBUG("packet->flags=%x,%x", packet->flags[0], packet->flags[1]); DEBUG("packet->ciaddr=%x,%x,%x,%x", packet->ciaddr[0], packet->ciaddr[1], packet->ciaddr[2], packet->ciaddr[3]); DEBUG("packet->yiaddr=%x,%x,%x,%x", packet->yiaddr[0], packet->yiaddr[1], packet->yiaddr[2], packet->yiaddr[3]); DEBUG("packet->siaddr=%x,%x,%x,%x", packet->siaddr[0], packet->siaddr[1], packet->siaddr[2], packet->siaddr[3]); DEBUG("packet->giaddr=%x,%x,%x,%x", packet->giaddr[0], packet->giaddr[1], packet->giaddr[2], packet->giaddr[3]); DEBUG("packet->chaddr=%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x", packet->chaddr[0], packet->chaddr[1], packet->chaddr[2], packet->chaddr[3], packet->chaddr[4], packet->chaddr[5], packet->chaddr[6], packet->chaddr[7], packet->chaddr[8], packet->chaddr[9], packet->chaddr[10], packet->chaddr[11], packet->chaddr[12], packet->chaddr[13], packet->chaddr[14], packet->chaddr[15]); DEBUG("packet->sname=%s", packet->sname); DEBUG("packet->file=%s", packet->file); DEBUG("---------------------------------------------"); //check DHCP magic cookie char magic[4]; memcpy(magic, packet_begin + 236, 4); if(0 != memcmp(DHCP_MAGIC_COOKIE, magic, 4)) { ERROR("DHCP packet magic cookie is not matched!"); goto ERROR; } //parse options int options_offset = 240; //236 + 4 packet->options = NULL; struct dhcp_option *prev = NULL; while(1) { if(options_offset > length - 1) { break; } //code char code; memcpy(&code, packet_begin + options_offset, 1); options_offset++; DEBUG("dhcp option code=%d", code); if(DHO_PAD == code) { continue; } if(DHO_END == code) { INFO("dhcp option end"); break; } //length int len; char len_buff; memcpy(&len_buff, packet_begin + options_offset, 1); len = (int)len_buff; options_offset++; DEBUG("dhcp option length=%d", len); if(options_offset + len > length - 1) { WARN("The options length is more than packet length, but no end mark."); break; } //value struct dhcp_option * option = (struct dhcp_option*)malloc(sizeof(struct dhcp_option)); if(NULL == option) { FATAL("***Allocate memory failed! %s(%d)***", strerror(errno), errno); goto ERROR; } memset(option, 0, sizeof(struct dhcp_option)); option->code = code; option->length = len_buff; option->value = (char*)malloc(len); if(NULL == option->value) { FATAL("***Allocate memory failed! %s(%d)***", strerror(errno), errno); goto ERROR; } memcpy(option->value, buffer + options_offset, len); option->next = NULL; options_offset += len; //Add the option into the packet if(NULL == packet->options) { packet->options = option; } if(NULL != prev) { prev->next = option; } prev = option; } if(options_offset < length - 1) { packet->padding = (char*)malloc(length - options_offset); if(NULL == packet->padding) { FATAL("***Allocate memory failed! %s(%d)***", strerror(errno), errno); } else { memcpy(packet->padding, buffer + options_offset, length - options_offset - 1); } } else { packet->padding = NULL; } INFO("marshall==>"); return packet; ERROR: if(NULL != packet) { free_packet(packet); } WARN("***error!*** marshall==>"); return NULL; } //Use this function to free dhcp packet void free_packet(struct dhcp_packet *packet) { INFO("==>free_packet, packet=%d", packet); if(NULL == packet) { INFO("packet pointer is NULL, free_packet==>"); return; } if(NULL != packet->padding) { free(packet->padding); } struct dhcp_option *option = packet->options; while(NULL == option) { if(NULL != option->value) { free(option->value); } struct dhcp_option *current = option; option = current->next; free(current); } free(packet); INFO("free_packet==>"); return; } int serialize(struct dhcp_packet *packet, char buffer[], int length) { INFO("serialize==>, packet=%d", packet); if(NULL == packet) { INFO("packet pointer is NULL, ==>serialize"); return 0; } //calculate the total size of the packet //static part int packet_len = BOOTP_ABSOLUTE_MIN_LEN; //magic cookie packet_len += sizeof(DHCP_MAGIC_COOKIE); //options struct dhcp_option *option = packet->options; while(NULL != option) { packet_len += 2; packet_len += (int)option->length; option = option->next; } //end option packet_len++; //calculate padding length int padding_len = 0; if(packet_len < BOOTP_ABSOLUTE_MIN_LEN + DHCP_VEND_SIZE) { padding_len = DHCP_VEND_SIZE + BOOTP_ABSOLUTE_MIN_LEN - packet_len; packet_len = DHCP_VEND_SIZE + BOOTP_ABSOLUTE_MIN_LEN; } if(packet_len > length) { ERROR("Buffer size is less than packet length, buffer size=%d, packet length=%d", sizeof(buffer), packet_len); INFO("==>serialize"); return 0; } DEBUG("--------------DUMP DHCP PACKET-------------"); DEBUG("packet->op=%d", packet->op); DEBUG("packet->htype=%d", packet->htype); DEBUG("packet->hlen=%d", packet->hlen); DEBUG("packet->hops=%d", packet->hops); DEBUG("packet->xid=%x,%x,%x,%x", packet->xid[0], packet->xid[1], packet->xid[2], packet->xid[3]); DEBUG("packet->secs=%x,%x", packet->secs[0], packet->secs[1]); DEBUG("packet->flags=%x,%x", packet->flags[0], packet->flags[1]); DEBUG("packet->ciaddr=%x,%x,%x,%x", packet->ciaddr[0], packet->ciaddr[1], packet->ciaddr[2], packet->ciaddr[3]); DEBUG("packet->yiaddr=%x,%x,%x,%x", packet->yiaddr[0], packet->yiaddr[1], packet->yiaddr[2], packet->yiaddr[3]); DEBUG("packet->siaddr=%x,%x,%x,%x", packet->siaddr[0], packet->siaddr[1], packet->siaddr[2], packet->siaddr[3]); DEBUG("packet->giaddr=%x,%x,%x,%x", packet->giaddr[0], packet->giaddr[1], packet->giaddr[2], packet->giaddr[3]); DEBUG("packet->chaddr=%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x", packet->chaddr[0], packet->chaddr[1], packet->chaddr[2], packet->chaddr[3], packet->chaddr[4], packet->chaddr[5], packet->chaddr[6], packet->chaddr[7], packet->chaddr[8], packet->chaddr[9], packet->chaddr[10], packet->chaddr[11], packet->chaddr[12], packet->chaddr[13], packet->chaddr[14], packet->chaddr[15]); DEBUG("packet->sname=%s", packet->sname); DEBUG("packet->file=%s", packet->file); DEBUG("---------------------------------------------"); memcpy(buffer, &(packet->op), 1); memcpy(buffer + 1, &(packet->htype), 1); memcpy(buffer + 2, &(packet->hlen), 1); memcpy(buffer + 3, &(packet->hops), 1); memcpy(buffer + 4, packet->xid, 4); memcpy(buffer + 8, packet->secs, 2); memcpy(buffer + 10, packet->flags, 2); memcpy(buffer + 12, packet->ciaddr, 4); memcpy(buffer + 16, packet->yiaddr, 4); memcpy(buffer + 20, packet->siaddr, 4); memcpy(buffer + 24, packet->giaddr, 4); memcpy(buffer + 28, packet->chaddr, 16); memcpy(buffer + 44, packet->sname, 64); memcpy(buffer + 108, packet->file, 128); memcpy(buffer + 236, DHCP_MAGIC_COOKIE, 4); int options_offset = 240; option = packet->options; while(NULL != option) { DEBUG("dhcp option code=%d, length=%d", option->code, option->length); memcpy(buffer + options_offset, &(option->code), 1); options_offset++; memcpy(buffer + options_offset, &(option->length), 1); options_offset++; int len = (int)option->length; memcpy(buffer + options_offset, option->value, len); options_offset += len; option = option->next; } char dhcp_option_end = DHO_END; memcpy(buffer + options_offset, &dhcp_option_end, 1); options_offset++; if(padding_len > 0) { memset(buffer + options_offset, 0, padding_len); } INFO("total %d bytes writen, ==>serialize", packet_len); return packet_len; }
0vishnutsuresh0-a
dhcp_packet.c
C
asf20
9,675
#ifndef _DHCP_SERVER_H #define _DHCP_SERVER_H #include<stdint.h> #include<netinet/in.h> #include "dhcp_packet.h" #define BOOTP_REPLAY_PORT 68 #define BROADCAST_ADDRESS "255.255.255.255" #define CONFIG_SERVER_ADDRESS "server" #define CONFIG_LISTEN_PORT "listen_port" #define CONFIG_LEASE_TIME "lease_time" #define CONFIG_RENEW_TIME "renew_time" #define CONFIG_IP_ALLOCATOR_FILE "ip_allocator_file" struct server_config { char server[16]; uint16_t port; uint32_t lease; uint32_t renew; char ip_allocator_file[256]; }; struct raw_msg { char buff[DHCP_MAX_MTU]; uint32_t length; struct sockaddr_in address; int socket_fd; }; struct dhcp_packet *do_discover(struct dhcp_packet *request); struct dhcp_packet *do_request(struct dhcp_packet *request); struct dhcp_packet *do_release(struct dhcp_packet *request); struct dhcp_packet *do_inform(struct dhcp_packet *request); struct dhcp_packet *do_decline(struct dhcp_packet *request); struct dhcp_packet_handler { struct dhcp_packet *(*do_discover)(struct dhcp_packet *); struct dhcp_packet *(*do_inform)(struct dhcp_packet *); struct dhcp_packet *(*do_request)(struct dhcp_packet *); struct dhcp_packet *(*do_release)(struct dhcp_packet *); struct dhcp_packet *(*do_decline)(struct dhcp_packet *); }; int ip_asc2bytes(char bytes[], char* ip_address); int start_server(char *config_file); void *handle_msg(void *arg); struct dhcp_packet *dispatch(struct dhcp_packet *request); struct network_config { char hardware_address[16]; char ip_address[4]; char router[4]; char netmask[4]; char dns1[4]; char dns2[4]; }; typedef int (*ip_allocator)(struct network_config *); #endif
0vishnutsuresh0-a
dhcp_server.h
C
asf20
1,663
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<stdarg.h> #include<time.h> #include<sys/types.h> #include "dhcp_log.h" struct log_config gobal_file_config = { .log_enabled = 0, .log_level = 3, .log_file_dir = "/var/log", }; int log_init(char *config_file) { //parse configuration file FILE *file = fopen(config_file, "r"); if(NULL == file) { return -1; } char buffer[CONFIG_BUFFER_SIZE]; while(!feof(file)) { if(NULL != fgets(buffer, CONFIG_BUFFER_SIZE, file)) { int index = 0; for(; '\0' != buffer[index] && '=' != buffer[index]; index++); if('\0' == buffer[index]) { continue; } buffer[index] = '\0'; char *value_begin = buffer + index + 1; int value_length = strlen(value_begin); if(0 == strcmp(buffer, CONDIF_LOG_ENABLED)) { memcpy(&gobal_file_config.log_enabled, value_begin, 1); gobal_file_config.log_enabled = gobal_file_config.log_enabled - '0'; } else if(0 == strcmp(buffer, CONFIG_LOG_LEVEL)) { memcpy(&gobal_file_config.log_level, value_begin, 1); gobal_file_config.log_level = gobal_file_config.log_level - '0'; } else if(0 == strcmp(buffer, CONFIG_LOG_FILE_DIR)) { if('\n' == value_begin[value_length - 1]) { value_begin[value_length - 1] = '\0'; } strncpy(gobal_file_config.log_file_dir, value_begin , MAX_FILE_PATH); } } } fclose(file); } void dhcp_log(char level, const char *source, const char *func, int line, char *message, ...) { if(0 == gobal_file_config.log_enabled || level < gobal_file_config.log_level) { return; } time_t now; time(&now); struct tm *tm_now = gmtime(&now); char file_path[MAX_FILE_PATH] = {0}; snprintf(file_path, MAX_FILE_PATH, "%s/%s_%4d-%02d-%02d.log", gobal_file_config.log_file_dir, LOG_FILE_NAME_PREFIX, tm_now->tm_year + 1900, tm_now->tm_mon + 1, tm_now->tm_mday); FILE *log_file = fopen(file_path, "a+"); if(NULL == log_file) { return; } va_list arg_list; char buffer[LOG_BUFFER_SIZE]; va_start(arg_list, message); vsnprintf(buffer, LOG_BUFFER_SIZE, message, arg_list); va_end(arg_list); fprintf(log_file, "%4d-%02d-%02d %02d:%02d:%02d %s[%s][%d]\t%05d:%05d %5s %s\n", tm_now->tm_year + 1900, tm_now->tm_mon + 1, tm_now->tm_mday, tm_now->tm_hour, tm_now->tm_min, tm_now->tm_sec, source, func, line, getgid(), getpid(), log_level_string(level), buffer); fclose(log_file); } char * log_level_string(char log_level) { switch(log_level) { case LOG_INFO: return LOG_INFO_STRING; case LOG_DEBUG: return LOG_DEBUG_STRING; case LOG_WARN: return LOG_WARN_STRING; case LOG_ERROR: return LOG_ERROR_STRING; case LOG_FATAL: return LOG_FATAL_STRING; default: break; } return NULL; }
0vishnutsuresh0-a
dhcp_log.c
C
asf20
3,011
dhcp_server: server.o packet.o log.o ip_allocator.o cc -lpthread -lsqlite3 -g -o dhcp_server server.o packet.o log.o ip_allocator.o server.o: dhcp_server.c ip_allocator.c dhcp_log.h dhcp_server.h dhcp_packet.h cc -g -c dhcp_server.c -o server.o packet.o: dhcp_packet.c dhcp_log.h dhcp_packet.h cc -g -c dhcp_packet.c -o packet.o log.o: dhcp_log.c dhcp_log.h cc -g -c dhcp_log.c -o log.o ip_allocator.o: ip_allocator.c dhcp_server.h cc -lsqlite3 -g -c ip_allocator.c -o ip_allocator.o clean: rm dhcp_server server.o packet.o log.o ip_allocator.o
0vishnutsuresh0-a
Makefile
Makefile
asf20
556
#ifndef _DHCP_PACKET_H_ #define _DHCP_PACKET_H_ /** DHCP BOOTP CODES **/ #define BOOT_REQUEST 1 #define BOOT_REPLY 2 /** DHCP HTYPE CODE **/ #define HTYPE_ETHER 1 #define HTYPE_IEEE802 6 #define HTYPE_FDDI 8 #define HTYPE_IEEE1394 24 /** DHCP MESSAGE CODES **/ #define DHCP_DISCOVER 1 #define DHCP_OFFER 2 #define DHCP_REQUEST 3 #define DHCP_DECLINE 4 #define DHCP_ACK 5 #define DHCP_NAK 6 #define DHCP_RELEASE 7 #define DHCP_INFORM 8 #define DHCP_FORCE_RENEW 9 #define DHCP_LEASE_QUERY 10 #define DHCP_LEASE_UNASSIGNED 11 #define DHCP_LEASE_UNKNOWN 12 #define DHCP_LEASE_ACTIVE 13 /** DHCP OPTIONS CODE **/ #define DHO_PAD 0 #define DHO_SUBNET 1 #define DHO_TIME_OFFSET 2 #define DHO_ROUTERS 3 #define DHO_TIME_SERVERS 4 #define DHO_NAME_SERVERS 5 #define DHO_DOMAIN_NAME_SERVERS 6 #define DHO_LOG_SERVER 7 #define DHO_COOKIE_SERVERS 8 #define DHO_LPR_SERVERS 9 #define DHO_IMPRESS_SERVER 10 #define DHO_RESOURCE_LOCATION_SERVERS 11 #define DHO_HOST_NAME 12 #define DHO_BOOT_SIZE 13 #define DHO_MERIT_DUMP 14 #define DHO_DOMAIN_NAME 15 #define DHO_SWAP_SERVER 16 #define DHO_ROOT_PATH 17 #define DHO_EXTENSIONS_PATH 18 #define DHO_IP_FORWARDING 19 #define DHO_NON_LOCAL_SOURCE_ROUTING 20 #define DHO_POLICY_FILTER 21 #define DHO_MAX_DGRAM_REASSEMBLY 22 #define DHO_DEFAULT_IP_TTL 23 #define DHO_PATH_MTU_AGING_TIMEOUT 24 #define DHO_PATH_MTU_PLATEAU_TABLE 25 #define DHO_INTERFACE_MTU 26 #define DHO_ALL_SUBNETS_LOCAL 27 #define DHO_BROADCAST_ADDRESS 28 #define DHO_PERFORM_MASK_DISCOVERY 29 #define DHO_MASK_SUPPLIER 30 #define DHO_ROUTER_DISCOVERY 31 #define DHO_ROUTER_SOLICITATION_ADDRESS 32 #define DHO_STATIC_ROUTES 33 #define DHO_TRAILER_ENCAPSULATION 34 #define DHO_ARP_CACHE_TIMEOUT 35 #define DHO_IEEE802_3_ENCAPSULATION 36 #define DHO_DEFAULT_TCP_TTL 37 #define DHO_TCP_KEEPALIVE_INTERVAL 38 #define DHO_TCP_KEEPALIVE_GARBAGE 39 #define DHO_NIS_SERVERS 41 #define DHO_NTP_SERVERS 42 #define DHO_VENDOR_ENCAPSULATED_OPTIONS 43 #define DHO_NETBIOS_NAME_SERVERS 44 #define DHO_NETBIOS_DD_SERVER 45 #define DHO_NETBIOS_NODE_TYPE 46 #define DHO_NETBIOS_SCOPE 47 #define DHO_FONT_SERVERS 48 #define DHO_X_DISPLAY_MANAGER 49 #define DHO_DHCP_REQUESTED_ADDRESS 50 #define DHO_DHCP_LEASE_TIME 51 #define DHO_DHCP_OPTION_OVERLOAD 52 #define DHO_DHCP_MESSAGE_TYPE 53 #define DHO_DHCP_SERVER_IDENTIFIER 54 #define DHO_DHCP_PARAMETER_REQUEST_LIST 55 #define DHO_DHCP_MESSAGE 56 #define DHO_DHCP_MAX_MESSAGE_SIZE 57 #define DHO_DHCP_RENEWAL_TIME 58 #define DHO_DHCP_REBINDING_TIME 59 #define DHO_VENDOR_CLASS_IDENTIFIER 60 #define DHO_DHCP_CLIENT_IDENTIFIER 61 #define DHO_NWIP_DOMAIN_NAME 62 #define DHO_NWIP_SUBOPTIONS 63 #define DHO_NISPLUS_DOMAIN 64 #define DHO_NISPLUS_SERVER 65 #define DHO_TFTP_SERVER 66 #define DHO_BOOTFILE 67 #define DHO_MOBILE_IP_HOME_AGENT 68 #define DHO_SMTP_SERVER 69 #define DHO_POP3_SERVER 70 #define DHO_NNTP_SERVER 71 #define DHO_WWW_SERVER 72 #define DHO_FINGER_SERVER 73 #define DHO_IRC_SERVER 74 #define DHO_STREETTALK_SERVER 75 #define DHO_STDA_SERVER 76 #define DHO_USER_CLASS 77 #define DHO_FQDN 81 #define DHO_DHCP_AGENT_OPTIONS 82 #define DHO_NDS_SERVERS 85 #define DHO_NDS_TREE_NAME 86 #define DHO_NDS_CONTEXT 87 #define DHO_CLIENT_LAST_TRANSACTION_TIME 91 #define DHO_ASSOCIATED_IP 92 #define DHO_USER_AUTHENTICATION_PROTOCOL 98 #define DHO_AUTO_CONFIGURE 116 #define DHO_NAME_SERVICE_SEARCH 117 #define DHO_SUBNET_SELECTION 118 #define DHO_DOMAIN_SEARCH 119 #define DHO_CLASSLESS_ROUTE 121 #define DHO_END -1 /** DHCP PACKET LENGTH **/ #define BOOTP_ABSOLUTE_MIN_LEN 236 #define DHCP_VEND_SIZE 64 #define DHCP_MAX_MTU 1500 struct dhcp_option { char code; char *value; char length; struct dhcp_option *next; }; struct dhcp_packet { char op; char htype; char hlen; char hops; char xid[4]; char secs[2]; char flags[2]; char ciaddr[4]; char yiaddr[4]; char siaddr[4]; char giaddr[4]; char chaddr[16]; char sname[64]; char file[128]; struct dhcp_option *options; char *padding; }; struct dhcp_packet *marshall(char buffer[], int offset, int length); void free_packet(struct dhcp_packet *packet); int serialize(struct dhcp_packet *packet, char buffer[], int length); #endif
0vishnutsuresh0-a
dhcp_packet.h
C
asf20
5,429
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<errno.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> #include<pthread.h> #include "dhcp_server.h" #include "dhcp_log.h" struct server_config gobal_config = {0}; struct dhcp_packet_handler gobal_packet_handler = { .do_discover = &do_discover, .do_inform = &do_inform, .do_request = &do_request, .do_release = &do_release, .do_decline = &do_decline, }; int ip_asc2bytes(char bytes[], char* ip_address) { INFO("==>ip_asc2bytes, ip_address=%s", ip_address); if(NULL == ip_address || strlen(ip_address) > 15 || strlen(ip_address) < 7) { ERROR("***IP address is invalid, ip_asc2bytes==>***"); return 0; } char buff[4] = {0}; int buff_index = 0; int ret = 0; int i = 0; for(i = 0; '\0' != ip_address[i]; i++) { if('.' == ip_address[i]) { buff[4] = '\0'; bytes[ret++] = atoi(buff); memset(buff, 0, 4); buff_index = 0; } if(ip_address[i] >= '0' && ip_address[i] <= '9') { buff[buff_index++] = ip_address[i]; } } if(buff_index > 0) { buff[4] = '\0'; bytes[ret++] = atoi(buff); } INFO("ip_asc2bytes==>"); return ret; } int start_server(char *config_file) { INFO("==>start_server, config_file=%s", config_file); //parse configuration file FILE *file = fopen(config_file, "r"); if(NULL == file) { FATAL("***Cannot open config_file!***, start_server==>"); return -1; } char buffer[CONFIG_BUFFER_SIZE]; while(!feof(file)) { if(NULL != fgets(buffer, CONFIG_BUFFER_SIZE, file)) { DEBUG("read line from config file: %s", buffer); int index = 0; for(; '\0' != buffer[index] && '=' != buffer[index]; index++); if('\0' == buffer[index]) { continue; } buffer[index] = '\0'; char *value_begin = buffer + index + 1; int value_length = strlen(value_begin); if('\n' == value_begin[value_length - 1]) { value_begin[value_length - 1] = '\0'; } if(0 == strcmp(buffer, CONFIG_SERVER_ADDRESS)) { strncpy(gobal_config.server, value_begin, 16); } else if(0 == strcmp(buffer, CONFIG_LISTEN_PORT)) { char value[6] = {0}; strncpy(value, value_begin, 6); gobal_config.port = atoi(value); } else if(0 == strcmp(buffer, CONFIG_LEASE_TIME)) { char value[11] = {0}; strncpy(value, value_begin , 11); gobal_config.lease = atoi(value); } else if(0 == strcmp(buffer, CONFIG_RENEW_TIME)) { char value[11] = {0} ; strncpy(value, value_begin , 11); gobal_config.renew = atoi(value); } else if(0 == strcmp(buffer, CONFIG_IP_ALLOCATOR_FILE)) { strncpy(gobal_config.ip_allocator_file, value_begin, 256); } } } fclose(file); if(NULL == gobal_config.server || 0 == gobal_config.port || 0 == gobal_config.lease || 0 == gobal_config.renew || NULL == gobal_config.ip_allocator_file) { goto ERROR; } DEBUG("-------DUMP GOBAL_CONFIG----------"); DEBUG("gobal_config.server=%s", gobal_config.server); DEBUG("gobal_config.port=%d", gobal_config.port); DEBUG("gobal_config.lease=%d", gobal_config.lease); DEBUG("gobal_config.renew=%d", gobal_config.renew); DEBUG("-----------------END--------------"); int dhcp_socket = 0; int so_reuseaddr = 1; struct sockaddr_in server_address; if((dhcp_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { FATAL("***Cannot open the socket! %s(%d)***", strerror(errno), errno); goto ERROR; } setsockopt(dhcp_socket, SOL_SOCKET, SO_REUSEADDR, &so_reuseaddr, sizeof(so_reuseaddr)); memset(&server_address, 0, sizeof(server_address)); server_address.sin_family = AF_INET; server_address.sin_port = htons(gobal_config.port); server_address.sin_addr.s_addr = htonl(INADDR_ANY); if(bind(dhcp_socket, (struct sockaddr*)&server_address, sizeof(server_address)) < 0) { FATAL("***Cannot bind the socket with the address! %s(%d)***", strerror(errno), errno); goto ERROR; } socklen_t addr_len = sizeof(struct sockaddr_in); while(1) { struct raw_msg *msg = (struct raw_msg*)malloc(sizeof(struct raw_msg)); if(NULL == msg) { FATAL("***Allocate memory failed! %s(%d)***", strerror(errno), errno); continue; } memset(msg, 0, sizeof(struct raw_msg)); msg->socket_fd = dhcp_socket; msg->length = recvfrom(dhcp_socket, msg->buff, DHCP_MAX_MTU, 0, (struct sockaddr*)&msg->address, &addr_len); DEBUG("%d bytes received", msg->length); if(msg->length < 0) { WARN("***Receive data error! %s(%d)***", strerror(errno), errno); free(msg); continue; } pthread_t thread_id; pthread_create(&thread_id, NULL, &handle_msg, (void *)msg); } ERROR: if(0 != dhcp_socket) { close(dhcp_socket); } WARN("***error!*** marshall==>"); return -1; } void *handle_msg(void *arg) { INFO("==>handle_msg, arg=%d", arg); struct raw_msg *msg = (struct raw_msg*)arg; struct dhcp_packet *request = marshall(msg->buff, 0, msg->length); if(NULL != request) { struct dhcp_packet *response = dispatch(request); if(NULL != response) { int broadcast_socket = 0; int so_broadcast = 1; int so_reuseaddr = 1; struct sockaddr_in server_address; if((broadcast_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { FATAL("***Cannot open the socket! %s(%d)***", strerror(errno), errno); goto ERROR; } setsockopt(broadcast_socket, SOL_SOCKET, SO_BROADCAST, &so_broadcast, sizeof(so_broadcast)); setsockopt(broadcast_socket, SOL_SOCKET, SO_REUSEADDR, &so_reuseaddr, sizeof(so_reuseaddr)); memset(&server_address, 0, sizeof(server_address)); server_address.sin_family = AF_INET; server_address.sin_port = htons(gobal_config.port); server_address.sin_addr.s_addr = inet_addr(gobal_config.server); if(bind(broadcast_socket, (struct sockaddr*)&server_address, sizeof(server_address)) < 0) { FATAL("***Cannot bind the socket with the address! %s(%d)***", strerror(errno), errno); goto ERROR; } char buffer[DHCP_MAX_MTU]; int length = serialize(response, buffer, DHCP_MAX_MTU); struct sockaddr_in broadcast = {0}; broadcast.sin_family = AF_INET; broadcast.sin_port = htons(BOOTP_REPLAY_PORT); broadcast.sin_addr.s_addr = htonl(INADDR_BROADCAST); int send_length = sendto(broadcast_socket, buffer, length, 0, (struct sockaddr*)&broadcast, sizeof(broadcast)); if(send_length < 0) { WARN("***Send data error! %s(%d)***", strerror(errno), errno); } else { DEBUG("Total %d bytes send!", send_length); } ERROR: if(0 != broadcast_socket) { close(broadcast_socket); } free_packet(response); } else { WARN("Response packet is NULL."); } free_packet(request); } else { WARN("Can not marshall request packet from raw bytes."); } free(msg); INFO("handle_msg==>"); return NULL; } struct dhcp_packet *dispatch(struct dhcp_packet *request) { INFO("==>dispatch"); if(NULL == request) { ERROR("***Request packet is NULL***"); goto ERROR; } if(BOOT_REQUEST != request->op) { WARN("***Packet is not send from dhcp client, ignor!***"); goto ERROR; } //get the dhcp packet type char type = '\0'; struct dhcp_option *option = request->options; while(NULL != option) { if(DHO_DHCP_MESSAGE_TYPE == option->code) { type = *option->value; break; } option = option->next; } if('\0' == type) { ERROR("***No dhcp message type found in the packet!***"); goto ERROR; } DEBUG("packet type=%d", type); struct dhcp_packet *response = NULL; switch(type) { case DHCP_DISCOVER: response = gobal_packet_handler.do_discover(request); break; case DHCP_RELEASE: response = gobal_packet_handler.do_release(request); break; case DHCP_INFORM: response = gobal_packet_handler.do_inform(request); break; case DHCP_REQUEST: response = gobal_packet_handler.do_request(request); break; case DHCP_DECLINE: response = gobal_packet_handler.do_decline(request); break; default: break; } INFO("dispatch==>"); return response; ERROR: INFO("***Error***, dispatch==>"); return NULL; } extern ip_allocator ip_allocator_handler; struct dhcp_packet *do_discover(struct dhcp_packet *request) { INFO("==>do_discover"); struct network_config config = {0}; memcpy(config.hardware_address, request->chaddr, 16); if(ip_allocator_handler(&config) < 0) { WARN("Cannot assign IP address! do_discover==>"); return NULL; } struct dhcp_packet *response = (struct dhcp_packet*)malloc(sizeof(struct dhcp_packet)); if(NULL == response) { FATAL("***Allocate memory failed! %s(%d)*** do_discover==>", strerror(errno), errno); return NULL; } memset(response, 0, sizeof(struct dhcp_packet)); response->op = BOOT_REPLY; response->htype = request->htype; response->hlen = request->hlen; response->hops = 1; memcpy(response->xid, request->xid, 4); memcpy(response->yiaddr, config.ip_address, 4); memcpy(response->flags, request->flags, 2); memcpy(response->chaddr, request->chaddr, 16); //options //message type struct dhcp_option *packet_type = (struct dhcp_option*)malloc(sizeof(struct dhcp_option)); if(NULL == packet_type) { free_packet(response); FATAL("***Allocate memory failed! %s(%d)*** do_discover==>", strerror(errno), errno); return NULL; } memset(packet_type, 0, sizeof(struct dhcp_option)); packet_type->code = DHO_DHCP_MESSAGE_TYPE; packet_type->value = (char *)malloc(1); if(NULL == packet_type->value) { free_packet(response); FATAL("***Allocate memory failed! %s(%d)*** do_discover==>", strerror(errno), errno); return NULL; } *packet_type->value = DHCP_OFFER; packet_type->length = 1; response->options = packet_type; //server identifier struct dhcp_option *server_identifier = (struct dhcp_option*)malloc(sizeof(struct dhcp_option)); if(NULL == server_identifier) { free_packet(response); FATAL("***Allocate memory failed! %s(%d)*** do_discover==>", strerror(errno), errno); return NULL; } memset(server_identifier, 0, sizeof(struct dhcp_option)); server_identifier->code = DHO_DHCP_SERVER_IDENTIFIER; server_identifier->value = (char *)malloc(4); if(NULL == server_identifier->value) { free_packet(response); FATAL("***Allocate memory failed! %s(%d)*** do_discover==>", strerror(errno), errno); return NULL; } ip_asc2bytes(server_identifier->value, gobal_config.server); server_identifier->length = 4; packet_type->next = server_identifier; //lease time struct dhcp_option *lease_time = (struct dhcp_option*)malloc(sizeof(struct dhcp_option)); if(NULL == lease_time) { free_packet(response); FATAL("***Allocate memory failed! %s(%d)*** do_discover==>", strerror(errno), errno); return NULL; } memset(lease_time, 0, sizeof(struct dhcp_option)); lease_time->code = DHO_DHCP_LEASE_TIME; lease_time->value = (char *)malloc(4); if(NULL == lease_time->value) { free_packet(response); FATAL("***Allocate memory failed! %s(%d)*** do_discover==>", strerror(errno), errno); return NULL; } memcpy(lease_time->value, &gobal_config.lease, 4); lease_time->length = 4; server_identifier->next = lease_time; //renew time struct dhcp_option *renew_time = (struct dhcp_option*)malloc(sizeof(struct dhcp_option)); if(NULL == renew_time) { free_packet(response); FATAL("***Allocate memory failed! %s(%d)*** do_discover==>", strerror(errno), errno); return NULL; } memset(renew_time, 0, sizeof(struct dhcp_option)); renew_time->code = DHO_DHCP_RENEWAL_TIME; renew_time->value = (char *)malloc(4); if(NULL == renew_time->value) { free_packet(response); FATAL("***Allocate memory failed! %s(%d)*** do_discover==>", strerror(errno), errno); return NULL; } memcpy(renew_time->value, &gobal_config.renew, 4); renew_time->length = 4; lease_time->next = renew_time; //router/gateway struct dhcp_option *router = (struct dhcp_option*)malloc(sizeof(struct dhcp_option)); if(NULL == router) { free_packet(response); FATAL("***Allocate memory failed! %s(%d)*** do_discover==>", strerror(errno), errno); return NULL; } memset(router, 0, sizeof(struct dhcp_option)); router->code = DHO_ROUTERS; router->value = (char *)malloc(4); if(NULL == router->value) { free_packet(response); FATAL("***Allocate memory failed! %s(%d)*** do_discover==>", strerror(errno), errno); return NULL; } memcpy(router->value, config.router, 4); router->length = 4; renew_time->next = router; //netmask struct dhcp_option *subnet_mask = (struct dhcp_option*)malloc(sizeof(struct dhcp_option)); if(NULL == subnet_mask) { free_packet(response); FATAL("***Allocate memory failed! %s(%d)*** do_discover==>", strerror(errno), errno); return NULL; } memset(subnet_mask, 0, sizeof(struct dhcp_option)); subnet_mask->code = DHO_SUBNET; subnet_mask->value = (char *)malloc(4); if(NULL == subnet_mask->value) { free_packet(response); FATAL("***Allocate memory failed! %s(%d)*** do_discover==>", strerror(errno), errno); return NULL; } memcpy(subnet_mask->value, config.netmask, 4); subnet_mask->length = 4; router->next = subnet_mask; //dns struct dhcp_option *dns_server = (struct dhcp_option*)malloc(sizeof(struct dhcp_option)); if(NULL == dns_server) { free_packet(response); FATAL("***Allocate memory failed! %s(%d)*** do_discover==>", strerror(errno), errno); return NULL; } memset(dns_server, 0, sizeof(struct dhcp_option)); dns_server->code = DHO_DOMAIN_NAME_SERVERS; dns_server->value = (char *)malloc(8); if(NULL == dns_server->value) { free_packet(response); FATAL("***Allocate memory failed! %s(%d)*** do_discover==>", strerror(errno), errno); return NULL; } memcpy(dns_server->value, config.dns1, 4); memcpy(dns_server->value + 4, config.dns2, 4); dns_server->length = 8; subnet_mask->next = dns_server; INFO("do_discover==>"); return response; } struct dhcp_packet *do_request(struct dhcp_packet *request) { INFO("==>do_request"); struct network_config config = {0}; memcpy(config.hardware_address, request->chaddr, 16); if(ip_allocator_handler(&config) < 0) { WARN("Cannot assign IP address! do_request==>"); return NULL; } char type = DHCP_ACK; char requested_address[4] = {0}; if(0 != memcmp(requested_address, request->ciaddr, 4)) { INFO("request->ciaddr is not 0, copy it to request_address"); memcpy(requested_address, request->ciaddr, 4); } else { INFO("request->ciaddr is 0, get request_address from dhcp option"); struct dhcp_option *option = request->options; while(NULL != option) { if(DHO_DHCP_REQUESTED_ADDRESS == option->code && option->length >= 4) { memcpy(requested_address, option->value, 4); break; } option = option->next; } } if(0 != memcmp(config.ip_address, requested_address, 4)) { WARN("request_address is not the same as IP assigned, change packet type to NAK"); type = DHCP_NAK; } struct dhcp_packet *response = (struct dhcp_packet*)malloc(sizeof(struct dhcp_packet)); memset(response, 0, sizeof(struct dhcp_packet)); response->op = BOOT_REPLY; response->htype = request->htype; response->hlen = request->hlen; response->hops = 1; memcpy(response->xid, request->xid, 4); memcpy(response->yiaddr, requested_address, 4); memcpy(response->flags, request->flags, 2); memcpy(response->chaddr, request->chaddr, 16); if(DHCP_ACK == type) { //options //message type struct dhcp_option *packet_type = (struct dhcp_option*)malloc(sizeof(struct dhcp_option)); if(NULL == packet_type) { free_packet(response); FATAL("***Allocate memory failed! %s(%d)*** do_discover==>", strerror(errno), errno); return NULL; } memset(packet_type, 0, sizeof(struct dhcp_option)); packet_type->code = DHO_DHCP_MESSAGE_TYPE; packet_type->value = (char *)malloc(1); if(NULL == packet_type->value) { free_packet(response); FATAL("***Allocate memory failed! %s(%d)*** do_discover==>", strerror(errno), errno); return NULL; } *packet_type->value = type; packet_type->length = 1; response->options = packet_type; //server identifier struct dhcp_option *server_identifier = (struct dhcp_option*)malloc(sizeof(struct dhcp_option)); if(NULL == server_identifier) { free_packet(response); FATAL("***Allocate memory failed! %s(%d)*** do_discover==>", strerror(errno), errno); return NULL; } memset(server_identifier, 0, sizeof(struct dhcp_option)); server_identifier->code = DHO_DHCP_SERVER_IDENTIFIER; server_identifier->value = (char *)malloc(4); if(NULL == server_identifier->value) { free_packet(response); FATAL("***Allocate memory failed! %s(%d)*** do_discover==>", strerror(errno), errno); return NULL; } ip_asc2bytes(server_identifier->value, gobal_config.server); server_identifier->length = 4; packet_type->next = server_identifier; //lease time struct dhcp_option *lease_time = (struct dhcp_option*)malloc(sizeof(struct dhcp_option)); if(NULL == lease_time) { free_packet(response); FATAL("***Allocate memory failed! %s(%d)*** do_discover==>", strerror(errno), errno); return NULL; } memset(lease_time, 0, sizeof(struct dhcp_option)); lease_time->code = DHO_DHCP_LEASE_TIME; lease_time->value = (char *)malloc(4); if(NULL == lease_time->value) { free_packet(response); FATAL("***Allocate memory failed! %s(%d)*** do_discover==>", strerror(errno), errno); return NULL; } memcpy(lease_time->value, &gobal_config.lease, 4); lease_time->length = 4; server_identifier->next = lease_time; //renew time struct dhcp_option *renew_time = (struct dhcp_option*)malloc(sizeof(struct dhcp_option)); if(NULL == renew_time) { free_packet(response); FATAL("***Allocate memory failed! %s(%d)*** do_discover==>", strerror(errno), errno); return NULL; } memset(renew_time, 0, sizeof(struct dhcp_option)); renew_time->code = DHO_DHCP_RENEWAL_TIME; renew_time->value = (char *)malloc(4); if(NULL == renew_time->value) { free_packet(response); FATAL("***Allocate memory failed! %s(%d)*** do_discover==>", strerror(errno), errno); return NULL; } memcpy(renew_time->value, &gobal_config.renew, 4); renew_time->length = 4; lease_time->next = renew_time; //router/gateway struct dhcp_option *router = (struct dhcp_option*)malloc(sizeof(struct dhcp_option)); if(NULL == router) { free_packet(response); FATAL("***Allocate memory failed! %s(%d)*** do_discover==>", strerror(errno), errno); return NULL; } memset(router, 0, sizeof(struct dhcp_option)); router->code = DHO_ROUTERS; router->value = (char *)malloc(4); if(NULL == router->value) { free_packet(response); FATAL("***Allocate memory failed! %s(%d)*** do_discover==>", strerror(errno), errno); return NULL; } memcpy(router->value, config.router, 4); router->length = 4; renew_time->next = router; //netmask struct dhcp_option *subnet_mask = (struct dhcp_option*)malloc(sizeof(struct dhcp_option)); if(NULL == subnet_mask) { free_packet(response); FATAL("***Allocate memory failed! %s(%d)*** do_discover==>", strerror(errno), errno); return NULL; } memset(subnet_mask, 0, sizeof(struct dhcp_option)); subnet_mask->code = DHO_SUBNET; subnet_mask->value = (char *)malloc(4); if(NULL == subnet_mask->value) { free_packet(response); FATAL("***Allocate memory failed! %s(%d)*** do_discover==>", strerror(errno), errno); return NULL; } memcpy(subnet_mask->value, config.netmask, 4); subnet_mask->length = 4; router->next = subnet_mask; //dns struct dhcp_option *dns_server = (struct dhcp_option*)malloc(sizeof(struct dhcp_option)); if(NULL == dns_server) { free_packet(response); FATAL("***Allocate memory failed! %s(%d)*** do_discover==>", strerror(errno), errno); return NULL; } memset(dns_server, 0, sizeof(struct dhcp_option)); dns_server->code = DHO_DOMAIN_NAME_SERVERS; dns_server->value = (char *)malloc(8); if(NULL == dns_server->value) { free_packet(response); FATAL("***Allocate memory failed! %s(%d)*** do_discover==>", strerror(errno), errno); return NULL; } memcpy(dns_server->value, config.dns1, 4); memcpy(dns_server->value + 4, config.dns2, 4); dns_server->length = 8; subnet_mask->next = dns_server; } INFO("do_request==>"); return response; } struct dhcp_packet *do_release(struct dhcp_packet *request) { INFO("==>do_release"); return NULL; INFO("do_release==>"); } struct dhcp_packet *do_inform(struct dhcp_packet *request) { INFO("==>do_inform"); struct network_config config = {0}; memcpy(config.hardware_address, request->chaddr, 16); if(ip_allocator_handler(&config) < 0) { WARN("Cannot assign IP address! do_inform==>"); return NULL; } struct dhcp_packet *response = (struct dhcp_packet*)malloc(sizeof(struct dhcp_packet)); memset(response, 0, sizeof(struct dhcp_packet)); response->op = BOOT_REPLY; response->htype = request->htype; response->hlen = request->hlen; response->hops = 1; memcpy(response->xid, request->xid, 4); memcpy(response->yiaddr, config.ip_address, 4); memcpy(response->flags, request->flags, 2); memcpy(response->chaddr, request->chaddr, 16); //options //message type struct dhcp_option *packet_type = (struct dhcp_option*)malloc(sizeof(struct dhcp_option)); if(NULL == packet_type) { free_packet(response); FATAL("***Allocate memory failed! %s(%d)*** do_discover==>", strerror(errno), errno); return NULL; } memset(packet_type, 0, sizeof(struct dhcp_option)); packet_type->code = DHO_DHCP_MESSAGE_TYPE; packet_type->value = (char *)malloc(1); if(NULL == packet_type->value) { free_packet(response); FATAL("***Allocate memory failed! %s(%d)*** do_discover==>", strerror(errno), errno); return NULL; } *packet_type->value = DHCP_ACK; packet_type->length = 1; response->options = packet_type; //server identifier struct dhcp_option *server_identifier = (struct dhcp_option*)malloc(sizeof(struct dhcp_option)); if(NULL == server_identifier) { free_packet(response); FATAL("***Allocate memory failed! %s(%d)*** do_discover==>", strerror(errno), errno); return NULL; } memset(server_identifier, 0, sizeof(struct dhcp_option)); server_identifier->code = DHO_DHCP_SERVER_IDENTIFIER; server_identifier->value = (char *)malloc(4); if(NULL == server_identifier->value) { free_packet(response); FATAL("***Allocate memory failed! %s(%d)*** do_discover==>", strerror(errno), errno); return NULL; } ip_asc2bytes(server_identifier->value, gobal_config.server); server_identifier->length = 4; packet_type->next = server_identifier; //lease time struct dhcp_option *lease_time = (struct dhcp_option*)malloc(sizeof(struct dhcp_option)); if(NULL == lease_time) { free_packet(response); FATAL("***Allocate memory failed! %s(%d)*** do_discover==>", strerror(errno), errno); return NULL; } memset(lease_time, 0, sizeof(struct dhcp_option)); lease_time->code = DHO_DHCP_LEASE_TIME; lease_time->value = (char *)malloc(4); if(NULL == lease_time->value) { free_packet(response); FATAL("***Allocate memory failed! %s(%d)*** do_discover==>", strerror(errno), errno); return NULL; } memcpy(lease_time->value, &gobal_config.lease, 4); lease_time->length = 4; server_identifier->next = lease_time; //renew time struct dhcp_option *renew_time = (struct dhcp_option*)malloc(sizeof(struct dhcp_option)); if(NULL == renew_time) { free_packet(response); FATAL("***Allocate memory failed! %s(%d)*** do_discover==>", strerror(errno), errno); return NULL; } memset(renew_time, 0, sizeof(struct dhcp_option)); renew_time->code = DHO_DHCP_RENEWAL_TIME; renew_time->value = (char *)malloc(4); if(NULL == renew_time->value) { free_packet(response); FATAL("***Allocate memory failed! %s(%d)*** do_discover==>", strerror(errno), errno); return NULL; } memcpy(renew_time->value, &gobal_config.renew, 4); renew_time->length = 4; lease_time->next = renew_time; //router/gateway struct dhcp_option *router = (struct dhcp_option*)malloc(sizeof(struct dhcp_option)); if(NULL == router) { free_packet(response); FATAL("***Allocate memory failed! %s(%d)*** do_discover==>", strerror(errno), errno); return NULL; } memset(router, 0, sizeof(struct dhcp_option)); router->code = DHO_ROUTERS; router->value = (char *)malloc(4); if(NULL == router->value) { free_packet(response); FATAL("***Allocate memory failed! %s(%d)*** do_discover==>", strerror(errno), errno); return NULL; } memcpy(router->value, config.router, 4); router->length = 4; renew_time->next = router; //netmask struct dhcp_option *subnet_mask = (struct dhcp_option*)malloc(sizeof(struct dhcp_option)); if(NULL == subnet_mask) { free_packet(response); FATAL("***Allocate memory failed! %s(%d)*** do_discover==>", strerror(errno), errno); return NULL; } memset(subnet_mask, 0, sizeof(struct dhcp_option)); subnet_mask->code = DHO_SUBNET; subnet_mask->value = (char *)malloc(4); if(NULL == subnet_mask->value) { free_packet(response); FATAL("***Allocate memory failed! %s(%d)*** do_discover==>", strerror(errno), errno); return NULL; } memcpy(subnet_mask->value, config.netmask, 4); subnet_mask->length = 4; router->next = subnet_mask; //dns struct dhcp_option *dns_server = (struct dhcp_option*)malloc(sizeof(struct dhcp_option)); if(NULL == dns_server) { free_packet(response); FATAL("***Allocate memory failed! %s(%d)*** do_discover==>", strerror(errno), errno); return NULL; } memset(dns_server, 0, sizeof(struct dhcp_option)); dns_server->code = DHO_DOMAIN_NAME_SERVERS; dns_server->value = (char *)malloc(8); if(NULL == dns_server->value) { free_packet(response); FATAL("***Allocate memory failed! %s(%d)*** do_discover==>", strerror(errno), errno); return NULL; } memcpy(dns_server->value, config.dns1, 4); memcpy(dns_server->value + 4, config.dns2, 4); dns_server->length = 8; subnet_mask->next = dns_server; INFO("do_inform==>"); return response; } struct dhcp_packet *do_decline(struct dhcp_packet *request) { INFO("==>do_decline"); return NULL; INFO("do_decline==>"); } int main() { log_init("/source/dhcp/dhcp_log.conf"); start_server("/source/dhcp/dhcp_server.conf"); }
0vishnutsuresh0-a
dhcp_server.c
C
asf20
26,619
#ifndef _LOG_H_ #define _LOG_H_ #define LOG_INFO 0 #define LOG_DEBUG 1 #define LOG_WARN 2 #define LOG_ERROR 3 #define LOG_FATAL 4 #define LOG_INFO_STRING "INFO" #define LOG_DEBUG_STRING "DEBUG" #define LOG_WARN_STRING "WARN" #define LOG_ERROR_STRING "ERROR" #define LOG_FATAL_STRING "FATAL" #define CONDIF_LOG_ENABLED "log_enabled" #define CONFIG_LOG_LEVEL "log_level" #define CONFIG_LOG_FILE_DIR "log_file" #define CONFIG_BUFFER_SIZE 1024 #define LOG_BUFFER_SIZE 4096 //4KB #define MAX_FILE_PATH 256 #define LOG_FILE_NAME_PREFIX "dhcp_log" struct log_config { char log_enabled; char log_level; char log_file_dir[MAX_FILE_PATH]; }; int log_init(char *config_file); void dhcp_log(char level, const char *source, const char *func, int line, char *message, ...); char * log_level_string(char log_level); #define INFO(message, ...) dhcp_log(LOG_INFO, __FILE__, __FUNCTION__, __LINE__, message, ##__VA_ARGS__) #define DEBUG(message, ...) dhcp_log(LOG_DEBUG, __FILE__, __FUNCTION__, __LINE__, message, ##__VA_ARGS__) #define WARN(message, ...) dhcp_log(LOG_WARN, __FILE__, __FUNCTION__, __LINE__, message, ##__VA_ARGS__) #define ERROR(message, ...) dhcp_log(LOG_ERROR, __FILE__, __FUNCTION__, __LINE__, message, ##__VA_ARGS__) #define FATAL(message, ...) dhcp_log(LOG_FATAL, __FILE__, __FUNCTION__, __LINE__, message, ##__VA_ARGS__) #endif
0vishnutsuresh0-a
dhcp_log.h
C
asf20
1,379
<?php include("inc/header.php"); ?> <div class="wrapper"> <?php include("inc/logoarea.php"); include("inc/navigation.php"); ?> <div class="content"> <div class="interests"> <h1>Find Friends</h1> <form name="register" action="search_member.php?page=friend&id=<?php echo $uid; ?>" method="post"> <table width="500" border="0" cellspacing="3" cellpadding="3"> <tr> <td>Name:</td> <td><input type="text" name="name" /></td> </tr> <tr height="22"> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td align="right">&nbsp;</td> <td><input type="submit" value="Search Members" /></td> </tr> </table> </form> <div class="search_results"> <?php $name=$_POST['name']; $con=mysql_connect("localhost","root","") or die("Couldnot establish connection with database server"); mysql_select_db("db_discuss",$con); $display_query=mysql_query("select * from tbl_discuss where name='$name'",$con); if(!$row=mysql_fetch_array($display_query)){ echo 'Sorry, Search Result not found.'; mysql_close($con); } else{ do{ echo "<hr><br>"; echo "<strong>Name</strong> = ".$row[name]."<br><strong>Country</strong> = ".$row[country]."<br><strong>Age</strong> = ".$row[age]."<br><strong>Email</strong> = ".$row[email]."<br><strong>Username</strong> = ".$row[username]; echo "<br><br>"; echo "<form method='post' action='addfriend.php?page=friend&id=".$uid."' >"; echo "<input type='hidden' name='userid' value='".$row[uid]."' >"; echo "<input type='submit' value='Add as Friend'></form>"; }while($row=mysql_fetch_array($display_query)); mysql_close($con); } ?> </div> </div> </div> </div> <?php include("inc/footer.php"); ?>
069kb4-discussion-forum
trunk/search_member.php
PHP
mit
1,789
// JavaScript Document $(document).ready(function(){ $("ul.subnav").parent().append("<span></span>"); //Only shows drop down trigger when js is enabled (Adds empty span tag after ul.subnav*) $("ul.topnav li span").hover(function() { //When trigger is clicked... //Following events are applied to the subnav itself (moving subnav up and down) $(this).parent().find("ul.subnav").slideDown('fast').show(); //Drop down the subnav on click $(this).parent().hover(function() { }, function(){ $(this).parent().find("ul.subnav").slideUp('slow'); //When the mouse hovers out of the subnav, move it back up }); //Following events are applied to the trigger (Hover events for the trigger) }).hover(function() { $(this).addClass("subhover"); //On hover over, add class "subhover" }, function(){ //On Hover Out $(this).removeClass("subhover"); //On hover out, remove class "subhover" }); $("#dropped").hover(function() { //When trigger is clicked... //Following events are applied to the subnav itself (moving subnav up and down) $(this).parent().find("ul.subnav").slideDown('fast').show(); //Drop down the subnav on click $(this).parent().hover(function() { }, function(){ $(this).parent().find("ul.subnav").slideUp('slow'); //When the mouse hovers out of the subnav, move it back up }); //Following events are applied to the trigger (Hover events for the trigger) }).hover(function() { $(this).addClass("subhover"); //On hover over, add class "subhover" }, function(){ //On Hover Out $(this).removeClass("subhover"); //On hover out, remove class "subhover" }); $("#dropped2").hover(function() { //When trigger is clicked... //Following events are applied to the subnav itself (moving subnav up and down) $(this).parent().find("ul.subnav").slideDown('fast').show(); //Drop down the subnav on click $(this).parent().hover(function() { }, function(){ $(this).parent().find("ul.subnav").slideUp('slow'); //When the mouse hovers out of the subnav, move it back up }); //Following events are applied to the trigger (Hover events for the trigger) }).hover(function() { $(this).addClass("subhover"); //On hover over, add class "subhover" }, function(){ //On Hover Out $(this).removeClass("subhover"); //On hover out, remove class "subhover" }); });
069kb4-discussion-forum
trunk/scripts/dropmenu.js
JavaScript
mit
2,727
// JavaScript Document function inputfocus(){ document.search.search.value=""; }
069kb4-discussion-forum
trunk/scripts/search_fun.js
JavaScript
mit
91
<?php include("inc/header.php"); ?> <div class="wrapper"> <?php include("inc/logoarea.php"); include("inc/navigation.php"); ?> <div class="content"> <?php $fname=$_POST['fname']; $mname=$_POST['mname']; $lname=$_POST['lname']; $country=$_POST['country']; $phone=$_POST['phone']; $email=$_POST['email']; $password=$_POST['password']; $con=mysql_connect("localhost","root","") or die("Couldnot establish connection with database server"); mysql_select_db("db_discuss",$con); mysql_query("update tbl_discuss set fname='$fname', mname='$mname', lname='$lname', country='$country',phone='$phone', password='$password' where uid='$uid'",$con); $display_query=mysql_query("select * from tbl_discuss where uid='$uid'",$con); ?> <div class="interests"> <h1>My Profile</h1> <p> Edit to change your profile. </p> <?php while($row=mysql_fetch_array($display_query)){ ?> <form onsubmit="return validate();" name="register" action="update_profile.php?page=profile&id=<?php echo $uid; ?>" method="post"> <table width="500" border="0" cellspacing="3" cellpadding="3"> <tr> <th>Username:</th> <td><strong> <?php echo $row['username']; ?> </strong></td> </tr> <tr> <th>First Name:</th> <td><input type="text" name="name" value="<?php echo $row['fname']; ?>" /></td> </tr> <tr> <th>Last name:</th> <td><input type="text" name="age" value="<?php echo $row['lname']; ?>" /></td> </tr> <tr> <th>Country:</th> <td><input type="text" name="country" value="<?php echo $row['country']; ?>" /></td> </tr> <tr> <th>Email:</th> <td><input type="text" name="country" value="<?php echo $row['email']; ?>" /></td> </tr> <tr> <th>Password:</th> <td><strong> <?php echo $row['password']; ?> </strong></td> </tr> <tr height="22"> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td align="right">&nbsp;</td> <td><input type="submit" value="Update" /></td> </tr> </table> </form> <?php } mysql_close($con); ?> </div> </div> </div> <?php include("inc/footer.php"); ?>
069kb4-discussion-forum
trunk/update_profile.php
PHP
mit
2,324
<?php include("includes/header.php"); ?> <div class="wrapper"> <?php include("includes/logoarea.php"); ?> <?php include("includes/navigation.php"); ?> <div class="content"> <?php if($p){ $dir="includes/".$p.".php"; include("$dir"); } else{ include("includes/home.php"); } ?> </div> </div> <?php include("includes/footer.php"); ?>
069kb4-discussion-forum
trunk/index.php
PHP
mit
423
<?php include("inc/header.php"); ?> <div class="wrapper"> <?php include("inc/logoarea.php"); include("inc/navigation.php"); ?> <div class="content"> <div class="interests"> <h1>Friend Requests</h1> <?php $con=mysql_connect("localhost","root","") or die("Couldnot establish connection with database server"); mysql_select_db("db_discuss",$con); foreach( $_POST['accept'] as $from ){ mysql_query("update tbl_friend set accept='y' where req_from='$from' and req_to='$uid'",$con) or die('not accepted'); $display_query=mysql_query("select * from tbl_discuss where uid='$from'",$con); while($row=mysql_fetch_array($display_query)){ echo "<br>You are now friend with <strong>".$row[name]."</strong>"; } } mysql_close($con); ?> </div> </div> </div> <?php include("inc/footer.php"); ?>
069kb4-discussion-forum
trunk/request_friend.php
PHP
mit
942
<?php include("inc/header.php"); ?> <div class="wrapper"> <?php include("inc/logoarea.php"); include("inc/navigation.php"); ?> <div class="content"> <?php $friend=$_POST['friend']; $message=$_POST['message']; $con=mysql_connect("localhost","root","") or die("Couldnot establish connection with database server"); mysql_select_db("db_discuss",$con); $display_query=mysql_query("select * from tbl_discuss where uid='$uid'",$con) or die('name not found'); while($row=mysql_fetch_array($display_query)){ $from=$row[name]; } mysql_query("insert into tbl_mailbox(mail_from,mail_to,messages) values('$from','$friend','$message')",$con) or die("Sorry"); echo "<p class='red'>Message successfully sent.</p>"; ?> </div> </div> <?php include("inc/footer.php"); ?>
069kb4-discussion-forum
trunk/sendmail.php
PHP
mit
848
<?php include("includes/header.php"); ?> <div class="wrapper"> <?php include("includes/logoarea.php"); include("includes/navigation.php"); ?> <div class="content"> <?php $fname=$_POST['fname']; $mname=$_POST['mname']; $lname=$_POST['lname']; $country=$_POST['country']; $phone=$_POST['phone']; $email=$_POST['email']; $username=$_POST['username']; $password=$_POST['password']; $con=mysql_connect("localhost","root",""); mysql_select_db("db_discuss",$con); $display_query=mysql_query("select * from tbl_discuss where username='$username'",$con); if($row=mysql_fetch_array($display_query)){ mysql_close($con); echo '<span class=error>The username is already in use. Please Try different Username.</span>'; echo "<br><a href='index.php?page=register'>Retry</a> | "; } else{ mysql_query("insert into tbl_discuss(fname,mname,lname,country,phone,email,username,password)values('$fname','$mname','$lname','$country','$phone','$email','$username','$password')",$con) or die("Sorry, registration unsuccessful. Please <a href='index.php?page=register'>Try Again</a>"); mysql_close($con); echo '<p>'; echo "Hello <strong>".$fname." !</strong><br><br>"; echo "You have been registered in <strong>'DISCUSSION CENTRE'</strong>. Please <a href='index.php?page=login'>login</a> and start discussing.<br><br>"; echo "</p>"; } ?> <strong> <a href='index.php?page=home'>Return Home</a> </strong> </div> </div> <?php include("includes/footer.php"); ?>
069kb4-discussion-forum
trunk/reg_process.php
PHP
mit
1,527
<h1>About Me</h1> <p> Hello! Thank you for visiting this website. This is a simple discussion center project using php and mysql. If you want the source code for this project, please <a href="contact.php">contact me</a>. </p>
069kb4-discussion-forum
trunk/includes/about.php
Hack
mit
269
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Form validation</title> <script type="text/javascript"> function validateForm() { //Getr the controls var nameControl=document.getElementById("name"); var mailControl=document.getElementById("mail"); var phoneControl=document.getElementById("phone"); //Get the error spans var nameError=document.getElementById("nameError"); var mailError=document.getElementById("mailError"); var phoneError=document.getElementById("phoneError"); //Create Expressions var isNumeric=/^([0-9])+$/; var isLetters=/^([aA-zZ ])+&/; var isEmail=/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/; //check each one if fail, set an appropriate error messphone; //If nmae is empty or inValid if(nameControl.value=="") { nameError.innerHTML="Name required"; return false; } else nameError.innerHTML=""; //Idf email empty or invalid if(mailControl.value=="") { mailError.innerHTML="Email is Empty"; return false; } else if(mailControl.value.search(isEmail)) { mailError.innerHTML="Invalid Email"; return false; } else mailError.innerHTML=""; //If phone is empty or invalid if(phoneControl.value=="") { phoneError.innerHTML="Valid Phone required"; return false; } else if(phoneControl.value.search(isNumeric)) { phoneError.innerHTML="Invalid Phone"; return false; } else phoneError.innerHTML=""; return true; //If any errors occured, return false otherwise true if(nameError.innerHTML==""&& mailError.innerHTML==""&&phoneError.innerHTML=="") return false; else return true; }; </script> <style type="text/css"> .error{ color:#ff0000; font-weight:bold; font-family:Arial, Helvetica, sans-serif; font-size:12px; } </style> </head> <body> <form action="script.php" method="post" name="myForm" onsubmit="return validateForm();"> <table> <tr> <th>Name</th> <td><input type="text" name="name" id="name" /></td> <td><span id="nameError" class="error"></spam></td> </tr> <tr> <th>Email</th> <td><input type="text" name="mail" id="mail" /></td> <td><span id="mailError" class="error"></span></td> </tr> <tr> <th>Phone</th> <td><input type="text" name="phone" id="phone" /></td> <td><span id="phoneError" class="error"></span></td> </tr> <tr> <td></td><td><input value="Send" type="submit" /></td> </tr> </table> </form> </body> </html>
069kb4-discussion-forum
trunk/includes/validate.php
PHP
mit
2,630
<h1>Contact Information</h1> <p> KRIGNAL </p>
069kb4-discussion-forum
trunk/includes/contact.php
Hack
mit
88
// JavaScript Document $(document).ready(function() {//8 $('form#loginform').submit(function() {//7 $('form#loginform .error').remove(); var hasError = false; $('.required').each(function() {//4 if(jQuery.trim($(this).val()) == '') {//1 var labelText = $(this).prev('label').text(); $(this).parent().append('<span class="error">Can not be blank'+labelText+'</span>'); $(this).addClass('inputError'); hasError = true; } else if($(this).hasClass('email')) {//3 var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/; if(!emailReg.test(jQuery.trim($(this).val()))) {//2 var labelText = $(this).prev('label').text(); $(this).parent().append('<span class="error">Invalid Email</span>'); $(this).addClass('inputError'); hasError = true; }//2// }//3// else if($(this).hasClass('ans')) { var name=/^(5)+$/; if(!name.test(jQuery.trim($(this).val()))) { var labettext = $(this).prev('label').text(); $(this).parent().append('<span class="error">Incorrect code<span>'); $(this).addClass('inputError'); hasError = true; } } //phone else if($(this).hasClass('phone')) { var phone=/^([0,9][0-9]{8,9}$)/; if(!phone.test(jQuery.trim($(this).val()))) { var labeltext = $(this).prev('label').text(); $(this).parent().append('<span class="error">Invalid phone number</span>'); $(this).addClass('inputError'); hasError = true; }}//phone // else if($(this).hasClass('code')) { var phone=/^([0][0-9]{2,4}$)/; if(!phone.test(jQuery.trim($(this).val()))) { var labeltext = $(this).prev('label').text(); $(this).parent().append('<span class="error">Invalid ZIP code</span>'); $(this).addClass('inputError'); hasError = true; }}//phone else if($(this).hasClass('name')) { var name=/^([aA-zZ ])+$/; /*/^[^\s]+\s[^\s]+$/*/ if(!name.test(jQuery.trim($(this).val()))) { var labettext = $(this).prev('label').text(); $(this).parent().append('<span class="error">This is not your real name</span>'); $(this).addClass('inputError'); hasError = true; } } }//4// ); if(!hasError) { $('form#loginform input.submit').fadeOut('normal', function() {//6 $(this).parent().append(''); }); var formInput = $(this).serialize(); $.post($(this).attr('action'),formInput, function(data){ $('form#loginform').slideUp("fast", function() {//5 $(this).before('<p class="success"><strong>Done!</strong> Thank you for contacting us. Your message has been sent. Our customer representative will contact you shortly.</span>') }//5// ); }//6// ); }//7// return false; }//8// ); } );
069kb4-discussion-forum
trunk/includes/valid.js
JavaScript
mit
2,648
<html> <head><style type="text/css"> #loginform .radio { width:10px; } .error { color:#ff0000; font-size:12px; font-weight:bold; } #right { float:right; width:350px; margin-top:15px; padding:15px; } </style> <script type="text/javascript"> function validateForm() { //Getr the controls var fnameControl=document.getElementById("fname"); var lnameControl=document.getElementById("lname"); var emailControl=document.getElementById("email"); var phoneControl=document.getElementById("phone"); var usernameControl=document.getElementById("username"); var passwordControl=document.getElementById("password"); //Get the error spans var fnameError=document.getElementById("fnameError"); var lameError=document.getElementById("lameError"); var emailError=document.getElementById("emailError"); var phoneError=document.getElementById("phoneError"); var usernameError=document.getElementById("usernameError"); var passwordError=document.getElementById("passwordError"); //Create Expressions var isNumeric=/^([0-9])+$/; var isLetters=/^([aA-zZ ])+&/; var isEemail=/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/; //check each one if fail, set an appropriate error messphone; //If nmae is empty or inValid if(fnameControl.value=="") { fnameError.innerHTML="First name required"; myForm.fname.focus; return false; } else fnameError.innerHTML=""; //For last name if(lnameControl.value=="") { lnameError.innerHTML="Last name required"; myForm.fname.focus; return false; } else lnameError.innerHTML=""; //Idf eemail empty or invalid if(emailControl.value=="") { emailError.innerHTML="Valid email required"; return false; } else if(emailControl.value.search(isEemail)) { emailError.innerHTML="Invalid Eemail"; return false; } else emailError.innerHTML=""; //If phone is empty or invalid if(phoneControl.value=="") { phoneError.innerHTML="Valid Phone required"; return false; } else if(phoneControl.value.search(isNumeric)) { phoneError.innerHTML="Invalid phone format"; return false; } else if(phoneControl.value.length<10) { phoneError.innerHTML="Phone should be at least 10 characters long"; return false; } else phoneError.innerHTML=""; //For username if(usernameControl.value=="") { usernameError.innerHTML="Username required"; return false; } else if(usernameControl.value.length<4) { usernameError.innerHTML="Username hould be at least 4 characters long" return false; } else usernameError.innerHTML=""; //For password if(passwordControl.value=="") { passwordError.innerHTML="Password required"; return false; } else if(passwordControl.value.length<6) { passwordError.innerHTML="Password should be at least 6 characters long" return false; } else nameError.innerHTML=""; return true; //If any errors occured, return false otherwise true if(nameError.innerHTML==""&& emailError.innerHTML==""&&phoneError.innerHTML=="") return false; else return true; }; </script> </head> <body> <h1>Registration</h1> <p> Please fill in the following form carefully. </p> <form action="reg_process.php?page=register" id="loginform" method="post" name="myForm" onSubmit="return validateForm();"> <table> <tr> <td><label>Name</label></td> <td> <input type="text" placeholder="First" class="short" name="fname" id="fname" /> <input type="text" name="mname" placeholder="Middle" class="short" id="mname" /> <input class="short" type="text" placeholder="Last" name="lname" id="lname" /></td> <td></td> </tr> <tr> <td><label>Country</label></td> <td><input type="text" name="country" id="country" /></td> <td></td> </tr> <tr> <td><label>Email</label></td> <td><input type="text" name="email" id="email" /></td> <td></td> </tr> <tr> <td><label>Phone</label></td> <td><input type="text" name="phone" id="phone" /></td> <td></td> </tr> <tr> <td><label>Username</label></td> <td><input type="text" name="username" id="username" /></td> <td></td> </tr> <tr> <td><label>Password</label></td> <td><input type="password" name="password" id="password" /></td> <td></td> </tr> <tr> <td></td><td><input value="Register" class="button" type="submit" /></td> </tr> </table> </form> <div id="right"> <span id="passwordError" class="error"></span> <span id="usernameError" class="error"></span> <span id="phoneError" class="error"></span> <span id="emailError" class="error"></span> <span id="countryError" class="error"></span> <span id="fnameError" class="error"></span> <span id="lnameError" class="error"></span> </div> </body> </html>
069kb4-discussion-forum
trunk/includes/register.php
Hack
mit
4,743
<div class="footer"> <div class="wrapper"> <p> Designed and developed by: KRIGNAL.com </p> </div> </div> </body> </html>
069kb4-discussion-forum
trunk/includes/footer.php
Hack
mit
158
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Discussion Center::Talk about anything</title> <link href="css/styles.css" type="text/css" rel="stylesheet" /> <script language="javascript" src="scripts/search_fun.js"></script> </head> <body>
069kb4-discussion-forum
trunk/includes/header.php
Hack
mit
451
<h1>Login</h1> <p> One moment please! Login to your account to start discussion. </p> <form action="log_process.php?page=login" id="loginform2" method="post"> <table border="0" > <tr> <td></td><td class="line">Username and Password are case-sensitive</td></tr> <tr> <td><label>Username</label></td> <td><input type="text" name="username" /></td> </tr> <tr> <td><label>Password</label></td> <td><input type="password" name="password" /></td> </tr> <tr height="22"> <td></td><td>Not Registered Yet? <a href="?page=register">Register Now</a></td> </tr> <tr> <td></td> <td><input class="button" type="submit" value="Login" /></td> </tr> </table> </form>
069kb4-discussion-forum
trunk/includes/login.php
Hack
mit
782
<div class="logo"> <a class="guestbook_logo" href="index.php"></a> </div>
069kb4-discussion-forum
trunk/includes/logoarea.php
Hack
mit
87
<?php $page="home"; ?> <style type="text/css"> h1 { padding-bottom:0px; margin:0px; } </style> <div class="interests"> <h1>Welcome</h1> <p> Welcome to DiscussCenter. Leave moments live! DiscussCentre is developed for the discussion for the any topics as your interests. Start discussion and explore the facts beyond your expections. We gather you a number of friends to add and findout new solutions and story. </p> We would love to hear you to improve this discussion centre. To start discussion just click 'Get started' below</p> </div> <center><a class="allbutton" href="index.php?page=login">Get started</a></center>
069kb4-discussion-forum
trunk/includes/home.php
PHP
mit
720
<?php $p=$_GET['page']; ?> <div class="navigation"> <ul> <li><a class="<?php if($p=='home' or $p==''){ echo 'active';} ?>" href="index.php?page=home">Home</a></li> <li><a class="<?php if($p=='login'){ echo 'active';} ?>" href="index.php?page=login">Login</a></li> <li><a class="<?php if($p=='contact'){ echo 'active';} ?>" href="index.php?page=contact">Contact</a></li> <li> <form name="search" action="search_process.php" method="get"> <input class="search" onfocus="inputfocus()" title="Search Members" type="text" placeholder="Search Members" name="search"/> <input type="hidden" value="Search" /><br /> </form> </li> </ul> </div>
069kb4-discussion-forum
trunk/includes/navigation.php
PHP
mit
798
<?php include("inc/header.php"); ?> <div class="wrapper"> <?php include("inc/logoarea.php"); include("inc/navigation.php"); ?> <div class="content"> <p class="red"> <?php $to=$_POST['userid']; $from=$_GET['id']; $con=mysql_connect("localhost","root",""); mysql_select_db("db_discuss",$con); //checks if request already sent. $request_sent=mysql_query("select * from tbl_friend where req_from='$from' and req_to='$to' and accept='n'",$con); //checks if request is sent to yourself. //checks if you are already friend. $already_friend=mysql_query("select * from tbl_friend where (req_from='$from' and req_to='$to' and accept='y') or (req_from='$to' and req_to='from' and accept='y')",$con); if($row=mysql_fetch_array($request_sent)){ mysql_close($con); echo 'The Friend request has already been sent.'; } elseif($to==$from){ mysql_close($con); echo 'You cannot send friend request to yourself.'; } elseif($row=mysql_fetch_array($already_friend)){ mysql_close($con); echo 'You are already friends.'; } else{ mysql_query("insert into tbl_friend(req_from,req_to,accept) values('$from','$to','n')",$con) or die("Friend not added"); mysql_close($con); echo 'Friend request has been sent.'; } ?> </p> <div class="interests"> <h1>Find Friends</h1> <form name="register" action="search_member.php?page=friend&id=<?php echo $uid; ?>" method="post"> <table width="500" border="0" cellspacing="3" cellpadding="3"> <tr> <td>Name:</td> <td><input type="text" name="name" /></td> </tr> <tr height="22"> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td align="right">&nbsp;</td> <td><input type="submit" value="Search Members" /></td> </tr> </table> </form> </div> </div> </div> <?php include("inc/footer.php"); ?>
069kb4-discussion-forum
trunk/addfriend.php
PHP
mit
1,919
<?php include("includes/header.php"); ?> <div class="wrapper"> <?php include("includes/logoarea.php"); ?> <?php include("includes/navigation.php"); ?> <div class="content"> <h1>Search Results</h1> <?php $search=$_GET['search']; $con=mysql_connect("localhost","root","") or die("Couldnot establish connection with database server"); mysql_select_db("db_discuss",$con); $display_query=mysql_query("select * from tbl_discuss where fname='$search' or country='$search' or email='$search' or username='$search'",$con) or die("sorry"); if(!$row=mysql_fetch_array($display_query)){ echo 'Sorry, Search Result not found.'; mysql_close($con); } else{ do{ echo "<hr size=1 color='#dddddd'><br>"; echo "<strong>Name</strong> = ".$row['fname']. "&nbsp;" .$row['mname']. "&nbsp;" .$row['lname']. "<br/> <strong>Email</strong> = ".$row['email']."<br/> <strong>Username</strong> = ".$row['username']."<br/> <strong>Country</strong> = ".$row['country']."<br/>"; }while($row=mysql_fetch_array($display_query)); mysql_close($con); } ?> </div> </div> <?php include("includes/footer.php"); ?>
069kb4-discussion-forum
trunk/search_process.php
PHP
mit
1,176
<?php include("inc/header.php"); ?> <div class="wrapper"> <?php include("inc/logoarea.php"); include("inc/navigation.php"); ?> <div class="content"> <div class="interests"> <h1>Find Friends</h1> <form name="register" action="search_member.php?page=friend&id=<?php echo $uid; ?>" method="post"> <table border="0" cellspacing="3" cellpadding="3"> <tr> <td>Name:</td> <td><input type="text" name="fname" /></td> <td><input class="button" type="submit" value="Search" /></td> </tr> </table> </form> <div class="search_results"> <?php $fname=$_POST['fname']; $con=mysql_connect("localhost","root","") or die("Couldnot establish connection with database server"); mysql_select_db("db_discuss",$con); $display_query=mysql_query("select * from tbl_discuss where fname='$fname'",$con); if(!$row=mysql_fetch_array($display_query)){ echo 'Sorry, Search Result not found.'; mysql_close($con); } else{ do{ echo "<hr><br>"; echo "<strong>Name</strong> = ".$row['fname']."<br><strong>Country</strong> = ".$row['country']."<br><Email</strong> = ".$row['email']."<br><strong>Username</strong> = ".$row['username']; echo "<br><br>"; echo "<form method='post' action='addfriend.php?page=friend&id=".$uid."' >"; echo "<input type='hidden' name='userid' value='".$row['uid']."' >"; echo "<input type='submit' value='Add as Friend'></form>"; }while($row=mysql_fetch_array($display_query)); mysql_close($con); } ?> </div> </div> </div> </div> <?php include("inc/footer.php"); ?>
069kb4-discussion-forum
trunk/discuss/search_member.php
PHP
mit
1,633
<?php include("inc/header.php"); ?> <div class="wrapper"> <?php include("inc/logoarea.php"); include("inc/navigation.php"); ?> <div class="content"> <?php $name=$_POST['name']; $country=$_POST['country']; $age=$_POST['age']; $phone=$_POST['phone']; $intrests=$_POST['interests']; $biography=$_POST['biography']; $con=mysql_connect("localhost","root","") or die("Couldnot establish connection with database server"); mysql_select_db("db_discuss",$con); mysql_query("update tbl_discuss set name='$name',country='$country',age='$age',phone='$phone',intrests='$intrests',biography='$biography' where uid='$uid'",$con); $display_query=mysql_query("select * from tbl_discuss where uid='$uid'",$con); ?> <div class="interests"> <h1>My Profile</h1> <p> Edit to change your profile. </p> <?php while($row=mysql_fetch_array($display_query)){ ?> <form onsubmit="return validate();" name="register" action="update_profile.php?page=profile&id=<?php echo $uid; ?>" method="post"> <table width="500" border="0" cellspacing="3" cellpadding="3"> <tr> <th>Username:</th> <td><strong> <?php echo $row[username]; ?> </strong></td> </tr> <tr> <th>Name:</th> <td><input type="text" name="name" value="<?php echo $row[name]; ?>" /></td> </tr> <tr> <th>Country:</th> <td><input type="text" name="country" value="<?php echo $row[country]; ?>" /></td> </tr> <tr> <th>Age:</th> <td><input type="text" name="age" value="<?php echo $row[age]; ?>" /></td> </tr> <tr> <th>Gender:</th> <td> <strong> <?php if($row[gender]=='m') echo 'male'; else echo 'female'; ?> </strong> </td> </tr> <tr> <th>Phone:</th> <td><input type="text" name="phone" value="<?php echo $row[phone]; ?>" /></td> </tr> <tr> <th>Email:</th> <td><strong> <?php echo $row[email]; ?> </strong></td> </tr> <tr> <th>Interests:</thd> <td><textarea name="interests"><?php echo $row[intrests]; ?> </textarea></td> </tr> <tr> <th>Biography:</th> <td><textarea name="biography"><?php echo $row[biography]; ?> </textarea></td> </tr> <tr height="22"> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td align="right">&nbsp;</td> <td><input type="submit" value="Update" /></td> </tr> </table> </form> <?php } mysql_close($con); ?> </div> </div> </div> <?php include("inc/footer.php"); ?>
069kb4-discussion-forum
trunk/discuss/update_profile.php
PHP
mit
2,672
<?php include("inc/header.php"); ?> <div class="wrapper"> <?php include("inc/logoarea.php"); include("inc/navigation.php"); ?> <div class="content"> <?php $p=$_GET['page']; $n=$_GET['num']; if($p){ $dir="inc/".$p.$n.".php"; include("$dir"); } else{ include("inc/home.php"); } ?> </div> </div> <?php include("inc/footer.php"); ?>
069kb4-discussion-forum
trunk/discuss/index.php
PHP
mit
416
<?php include("inc/header.php"); ?> <div class="wrapper"> <?php include("inc/logoarea.php"); include("inc/navigation.php"); ?> <div class="content"> <div class="interests"> <h1>Friend Requests</h1> <?php $con=mysql_connect("localhost","root","") or die("Couldnot establish connection with database server"); mysql_select_db("db_discuss",$con); foreach( $_POST['accept'] as $from ){ mysql_query("update tbl_friend set accept='y' where req_from='$from' and req_to='$uid'",$con) or die('not accepted'); $display_query=mysql_query("select * from tbl_discuss where uid='$from'",$con); while($row=mysql_fetch_array($display_query)){ echo "<br>You are now friend with <strong>".$row[name]."</strong>"; } } mysql_close($con); ?> </div> </div> </div> <?php include("inc/footer.php"); ?>
069kb4-discussion-forum
trunk/discuss/request_friend.php
PHP
mit
942
<?php include("inc/header.php"); ?> <div class="wrapper"> <?php include("inc/logoarea.php"); include("inc/navigation.php"); ?> <div class="content"> <?php $friend=$_POST['friend']; $message=$_POST['message']; $con=mysql_connect("localhost","root","") or die("Couldnot establish connection with database server"); mysql_select_db("db_discuss",$con); $display_query=mysql_query("select * from tbl_discuss where uid='$uid'",$con) or die('name not found'); while($row=mysql_fetch_array($display_query)){ $from=$row['fname']; } mysql_query("insert into tbl_mailbox(mail_from,mail_to,messages) values('$from','$friend','$message')",$con) or die("Sorry"); echo "<p class='red'>Message successfully sent.</p>"; ?> </div> </div> <?php include("inc/footer.php"); ?>
069kb4-discussion-forum
trunk/discuss/sendmail.php
PHP
mit
851
<?php include("inc/header.php"); ?> <div class="wrapper"> <?php include("inc/logoarea.php"); include("inc/navigation.php"); ?> <div class="content"> <p class="red"> <?php $to=$_POST['userid']; $from=$_GET['id']; $con=mysql_connect("localhost","root",""); mysql_select_db("db_discuss",$con); //checks if request already sent. $request_sent=mysql_query("select * from tbl_friend where req_from='$from' and req_to='$to' and accept='n'",$con); //checks if request is sent to yourself. //checks if you are already friend. $already_friend=mysql_query("select * from tbl_friend where (req_from='$from' and req_to='$to' and accept='y') or (req_from='$to' and req_to='from' and accept='y')",$con); if($row=mysql_fetch_array($request_sent)){ mysql_close($con); echo 'The Friend request has already been sent.'; } else if($to==$from){ mysql_close($con); echo 'You cannot send friend request to yourself.'; } else if($row=mysql_fetch_array($already_friend)){ mysql_close($con); echo 'You are already friends.'; } else{ mysql_query("insert into tbl_friend(req_from,req_to,accept) values('$from','$to','n')",$con) or die("Friend not added"); mysql_close($con); echo 'Friend request has been sent.'; } ?> </p> <div class="interests"> <h1>Find Friends</h1> <form name="register" action="search_member.php?page=friend&id=<?php echo $uid; ?>" method="post"> <table width="500" border="0" cellspacing="3" cellpadding="3"> <tr> <td>Name:</td> <td><input type="text" name="name" /></td> </tr> <tr height="22"> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td align="right">&nbsp;</td> <td><input type="submit" value="Search Members" /></td> </tr> </table> </form> </div> </div> </div> <?php include("inc/footer.php"); ?>
069kb4-discussion-forum
trunk/discuss/addfriend.php
PHP
mit
1,921
<?php $con=mysql_connect("localhost","root","") or die("Couldnot establish connection with database server"); mysql_select_db("db_discuss",$con); $display_query=mysql_query("select * from tbl_mailbox where mail_to='$uid'",$con); ?> <div class="interests"> <h1>Inbox</h1> <table border="1" cellpadding="3" cellspacing="0"> <?php if(!$row=mysql_fetch_array($display_query)){ echo 'Sorry, there are no messages.'; } else{ ?> <tr> <th>From</th> <th>Message</th> </tr> <?php do{ echo "<tr><td>".$row[mail_from]."</td><td>".$row[messages]."</td></tr>"; }while($row=mysql_fetch_array($display_query)); } ?> </table> </div> <?php mysql_close($con); ?>
069kb4-discussion-forum
trunk/discuss/inc/inbox1.php
PHP
mit
998
<div class="interests"> <h1>Find Friends</h1> <form name="register" action="search_member.php?page=friend&id=<?php echo $uid; ?>" method="post"> <table width="500" border="0" cellspacing="3" cellpadding="3"> <tr> <td>Name:</td> <td><input type="text" name="name" /></td> </tr> <tr height="22"> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td align="right">&nbsp;</td> <td><input type="submit" value="Search Members" /></td> </tr> </table> </form> </div>
069kb4-discussion-forum
trunk/discuss/inc/friend1.php
PHP
mit
526
<?php $tid=$_GET['topic']; $category=$_GET['cat']; ?> <h3><a href="index.php?page=home&id=<?php echo $uid; ?>">Discuss Home</a> &gt; <?php echo $category; ?></h3> <ul class="friend_requests"> <?php $reply_message=$_POST['reply']; $con=mysql_connect("localhost","root","") or die("Couldnot establish connection with database server"); mysql_select_db("db_discuss",$con); $qry=mysql_query("select * from tbl_topics where tid='$tid'",$con); $row=mysql_fetch_array($qry); $startedby=$row[startedby]; $topic=$row[topic]; $message=$row[message]; $tid=$row[tid]; $replies=$row[replies]+1; if($reply_message){ $reply_name=mysql_query("select name from tbl_discuss where uid='$uid'",$con); $name_arr=mysql_fetch_array($reply_name); $name_reply=$name_arr[name]; mysql_query("insert into tbl_replies(tid,rep_message,name) values('$tid','$reply_message','$name_reply')",$con); mysql_query("update tbl_topics set replies='$replies' where tid='$tid'",$con); } echo "<li><h3>".$topic."<span class='started'>(Started by - ".$startedby.")</span></h3><div class='dis_message'>".$message."</div></li>"; $msg_reply=mysql_query("select * from tbl_replies where tid='$tid'",$con); while($rec=mysql_fetch_array($msg_reply)){ echo "<li><h4>Reply by: ".$rec[name]."</h4><div class='dis_message'>".$rec[rep_message]."</div></li>"; } ?> </ul> <h1>Reply</h1> <form method='post' action='index.php?page=home&topic=<?php echo $tid."&cat=".$category."&num=5&id=".$uid; ?>' > <p> <textarea name='reply' class='huge'></textarea> </p><p> <input type='submit' value='Post'> </p></form> <?php mysql_close($con); ?>
069kb4-discussion-forum
trunk/discuss/inc/home5.php
PHP
mit
1,645
<div class="interests"> <h1>My Friends</h1> <ul class="friend_requests"> <?php $con=mysql_connect("localhost","root","") or die("Couldnot establish connection with database server"); mysql_select_db("db_discuss",$con); $display_query=mysql_query("select * from tbl_friend where (req_from='$uid' or req_to='$uid') and accept='y'",$con); while($row=mysql_fetch_array($display_query)){ if($row[req_from]==$uid){ $fren=$row[req_to]; } else{ $fren=$row[req_from]; } $display_frn=mysql_query("select * from tbl_discuss where uid='$fren'",$con); while($record=mysql_fetch_array($display_frn)){ echo "<li><a href='index.php?page=profile_frn&friend=".$record[uid]."&id=".$uid."'><strong>".$record[name]."</strong></a></li>"; echo "<br>"; } } ?> </ul> </div>
069kb4-discussion-forum
trunk/discuss/inc/friend2.php
PHP
mit
875
<?php $con=mysql_connect("localhost","root","") or die("Couldnot establish connection with database server"); mysql_select_db("db_discuss",$con); $starter=mysql_query("select * from tbl_discuss where uid=$uid",$con); $row=mysql_fetch_array($starter); $startedby= $row['username']; $category=$_GET['cat']; $topic=$_POST['topic']; $message=$_POST['message']; echo "<h1>$category</h1>"; mysql_query("insert into tbl_topics (startedby,topic,message,replies,category) values('$startedby','$topic','$message','0','$category')",$con) or die("Sorry, Message cannot be posted"); echo "<p class='green'>Message has been Posted</a> <br><br>"; $qry=mysql_query("select * from tbl_topics where startedby='$startedby' and topic='$topic'",$con); $rec=mysql_fetch_array($qry); $topic=$rec['tid']; ?> <h3><a href="index.php?page=home&id=<?php echo $uid; ?>">Discuss Home</a> &gt; <?php echo $category=$_GET['cat']; ?></h3> <a href="index.php?page=home&cat=<?php echo $category.'&topic='.$topic.'&num=4&id='.$uid; ?>" class="view_post">View your post</a> <?php mysql_close($con); ?>
069kb4-discussion-forum
trunk/discuss/inc/home3.php
PHP
mit
1,097
<div class="interests"> <h1>Friend Requests</h1> <?php $con=mysql_connect("localhost","root","") or die("Couldnot establish connection with database server"); mysql_select_db("db_discuss",$con); $display_query=mysql_query("select * from tbl_friend where req_to='$uid' and accept='n'",$con); $requests=mysql_num_rows($display_query); if($requests < 1){ echo "<p class='red'>Sorry, you have no friend requests now.</p>"; } else{ ?> <form method="post" action="request_friend.php?page=friend&id=<?php echo $uid; ?>"> <ul class="friend_requests"> <?php while($row=mysql_fetch_array($display_query)){ $user=$row[req_from]; $dis_qry=mysql_query("select * from tbl_discuss where uid=$user",$con); while($record=mysql_fetch_array($dis_qry)){ echo "<li><a href=''>".$record[name]."</a> has added you as friend. <strong>Accept?</strong> <input type='checkbox' name='accept[]' value='".$user."' /></li>"; } } ?> <li> <input type="submit" value="Done" /> </li> </ul> </form> <?php mysql_close($con); } ?> </div>
069kb4-discussion-forum
trunk/discuss/inc/friend3.php
PHP
mit
1,264
<?php $con=mysql_connect("localhost","root","") or die("Couldnot establish connection with database server"); mysql_select_db("db_discuss",$con); $display_query=mysql_query("select * from tbl_discuss where uid='$uid'",$con); ?> <div class="interests"> <h1>My Profile</h1> <p> Edit to change your profile. </p> <?php while($row=mysql_fetch_array($display_query)){ ?> <form onsubmit="return validate();" name="register" action="update_profile.php?page=profile&id=<?php echo $uid; ?>" method="post"> <table width="500" border="0" cellspacing="3" cellpadding="3"> <tr> <th>Username:</th> <td><strong> <?php echo $row[username]; ?> </strong></td> </tr> <tr> <th>Name:</th> <td><input type="text" name="name" value="<?php echo $row[name]; ?>" /></td> </tr> <tr> <th>Country:</th> <td><input type="text" name="country" value="<?php echo $row[country]; ?>" /></td> </tr> <tr> <th>Age:</th> <td><input type="text" name="age" value="<?php echo $row[age]; ?>" /></td> </tr> <tr> <th>Gender:</th> <td> <strong> <?php if($row[gender]=='m') echo 'male'; else echo 'female'; ?> </strong> </td> </tr> <tr> <th>Phone:</th> <td><input type="text" name="phone" value="<?php echo $row[phone]; ?>" /></td> </tr> <tr> <th>Email:</th> <td><strong> <?php echo $row[email]; ?> </strong></td> </tr> <tr> <th>Interests:</thd> <td><textarea name="interests"><?php echo $row[intrests]; ?> </textarea></td> </tr> <tr> <th>Biography:</th> <td><textarea name="biography"><?php echo $row[biography]; ?> </textarea></td> </tr> <tr height="22"> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td align="right">&nbsp;</td> <td><input type="submit" value="Update" /></td> </tr> </table> </form> <?php } mysql_close($con); ?> </div>
069kb4-discussion-forum
trunk/discuss/inc/profile.php
PHP
mit
2,069
<?php $con=mysql_connect("localhost","root","") or die("Couldnot establish connection with database server"); mysql_select_db("db_discuss",$con); $display_query=mysql_query("select * from tbl_friend where (req_from='$uid' or req_to='$uid') and accept='y'",$con); ?> <div class="interests"> <h1>Compose Mail</h1> <form method="post" action="sendmail.php?page=inbox&id=<?php echo $uid; ?>" > <p> <label>Select your friend:</label> <select name="friend"> <?php while($row=mysql_fetch_array($display_query)){ if($row[req_from]==$uid){ $fren=$row[req_to]; } else{ $fren=$row[req_from]; } $display_frn=mysql_query("select * from tbl_discuss where uid='$fren'",$con); while($record=mysql_fetch_array($display_frn)){ echo "<option value='".$record[uid]."'><br><strong>".$record[name]."</strong><br></option>"; } } ?> </select> </p> <p> <label>Message:</label> <textarea name="message"></textarea> </p> <p> <input type="submit" value="send" /> </p> </form> </div> <?php mysql_close($con); ?>
069kb4-discussion-forum
trunk/discuss/inc/inbox2.php
PHP
mit
1,365
<?php $friend=$_GET['friend']; $con=mysql_connect("localhost","root","") or die("Couldnot establish connection with database server"); mysql_select_db("db_discuss",$con); $display_query=mysql_query("select * from tbl_discuss where uid='$friend'",$con); ?> <div class="interests"> <?php while($row=mysql_fetch_array($display_query)){ ?> <h1><?php echo $row[username]; ?></h1> <table width="500" border="0" cellspacing="3" cellpadding="3"> <tr> <th>Username:</th> <td><strong> <?php echo $row[username]; ?> </strong></td> </tr> <tr> <th>Name:</th> <td><strong><?php echo $row[name]; ?></strong></td> </tr> <tr> <th>Country:</th> <td><strong><?php echo $row[country]; ?></strong></td> </tr> <tr> <th>Age:</th> <td><strong><?php echo $row[age]; ?></strong></td> </tr> <tr> <th>Gender:</th> <td> <strong> <?php if($row[gender]=='m') echo 'male'; else echo 'female'; ?> </strong> </td> </tr> <tr> <th>Phone:</th> <td><strong><?php echo $row[phone]; ?></strong></td> </tr> <tr> <th>Email:</th> <td><strong> <?php echo $row[email]; ?> </strong></td> </tr> <tr> <th>Interests:</thd> <td><strong><?php echo $row[intrests]; ?> </strong></td> </tr> <tr> <th>Biography:</th> <td><strong><?php echo $row[biography]; ?> </strong></td> </tr> <tr height="22"> <td>&nbsp;</td> <td>&nbsp;</td> </tr> </table> <?php } mysql_close($con); ?> </div>
069kb4-discussion-forum
trunk/discuss/inc/profile_frn.php
PHP
mit
1,646
<div class="footer"> <div class="wrapper"> <p> Designed and developed by: KRIGNAL.com </p> </div> </div> </body> </html>
069kb4-discussion-forum
trunk/discuss/inc/footer.php
Hack
mit
160
<?php $uid=$_GET['id']; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Discussion Centre:Talk about anything</title> <link href="../css/styles.css" type="text/css" rel="stylesheet" /> <script language="javascript" src="../scripts/search_fun.js"></script> <script type="text/javascript" src="../scripts/jquery.js"></script> <script type="text/javascript" src="../scripts/dropmenu.js"></script> </head> <body>
069kb4-discussion-forum
trunk/discuss/inc/header.php
PHP
mit
632
<?php $category=$_GET['cat']; ?> <h3><a href="index.php?page=home&id=<?php echo $uid; ?>">Discuss Home</a> &gt; <?php echo $category=$_GET['cat']; ?></h3> <form method="post" action="index.php?page=home&cat=<?php echo $category.'&num=3&id='.$uid; ?>"> <p> <label>Topic:</label><input class="long" type="text" name="topic" > </p> <p> <textarea name="message" class="huge"></textarea> </p> <p> <input type="submit" value="Post"> </p> </form>
069kb4-discussion-forum
trunk/discuss/inc/home2.php
PHP
mit
494
<?php include("includes/header.php"); ?> <div class="wrapper"> <?php include("includes/logoarea.php"); ?> <?php include("includes/navigation.php"); ?> <div class="content"> <h1>Search Results</h1> <?php $search=$_GET['search']; $con=mysql_connect("localhost","root","") or die("Couldnot establish connection with database server"); mysql_select_db("db_discuss",$con); $display_query=mysql_query("select * from tbl_discuss where fname='$search' or country='$search' or email='$search' or username='$search'",$con) or die("sorry"); if(!$row=mysql_fetch_array($display_query)){ echo 'Sorry, Search Result not found.'; mysql_close($con); } else{ do{ echo "<hr size=1 color='#dddddd'><br>"; echo "<strong>Name</strong> = ".$row['fname']. "&nbsp;" .$row['mname']. "&nbsp;" .$row['lname']. "<br/><strong>Email</strong> = ".$row['email']."<br/><strong>Username</strong> = ".$row['username']; echo "<br/>"; }while($row=mysql_fetch_array($display_query)); mysql_close($con); } ?> </div> </div> <?php include("includes/footer.php"); ?>
069kb4-discussion-forum
trunk/discuss/inc/search_process.php
PHP
mit
1,118
<div class="interests"> <span class="breadcum"> <a href="index.php?page=home&id=<?php echo $uid; ?>">Discuss Home</a> &raquo; <?php echo $category=$_GET['cat']; ?> <a class="button" href="index.php?page=home&num=2&cat=<?php echo $category.'&id='.$uid; ?>">Start new topic</a> </span> <div class="discus_topics"> <?php $con=mysql_connect("localhost","root","") or die("Couldnot establish connection with database server"); mysql_select_db("db_discuss",$con); $qry_select=mysql_query("select * from tbl_topics where category='$category'",$con); $qry_select2=mysql_query("select * from tbl_discuss",$con); ?> <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr> <th width="25%">Started by</th> <th width="55%">Topic Title</td> <th width="20%">Replies</th> </tr> <?php while($row=mysql_fetch_array($qry_select)){ ?> <tr> <td width="25%"><?php echo $row['startedby']; ?></td> <td width="55%"><a href="index.php?page=home&cat=<?php echo $category.'&topic='.$row['tid'].'&num=4&id='.$uid; ?>"><strong><?php echo $row['topic']; ?></strong></a></td> <td width="20%"><?php echo $row['replies']; ?></th> </tr> <?php } mysql_close($con); ?> </table> </div> </div>
069kb4-discussion-forum
trunk/discuss/inc/home1.php
PHP
mit
1,396
<div class="logo"> <a class="guestbook_logo" href="index.php?page=home"></a> </div>
069kb4-discussion-forum
trunk/discuss/inc/logoarea.php
Hack
mit
108
<div class="interests"> <h3>Choose your Interest for discussion</h3> <ul> <li><a href="index.php?page=home&cat=Technology&num=1&id=<?php echo $uid; ?>"><img src="../images/interests/computer.png" alt="TECHNOLOGY" /></a></li> <li><a href="index.php?page=home&cat=Education&num=1&id=<?php echo $uid; ?>"><img src="../images/interests/education.png" alt="EDUCATION" /></a></li> <li><a href="index.php?page=home&cat=Music&num=1&id=<?php echo $uid; ?>"><img src="../images/interests/music.png" alt="MUSIC" /></a></li> <li><a href="index.php?page=home&cat=Soccer&num=1&id=<?php echo $uid; ?>"><img src="../images/interests/soccer.png" alt="SPORTS" /></a></li> </ul> </div>
069kb4-discussion-forum
trunk/discuss/inc/home.php
PHP
mit
801
<?php $p=$_GET['page']; ?> <div class="navigation"> <ul class="topnav"> <li><a class="<?php if($p=='home' or $p==''){ echo 'active';} ?>" href="index.php?page=home&id=<?php echo $uid; ?>">Discuss</a></li> <li><a class="<?php if($p=='profile'){ echo 'active';} ?>" href="index.php?page=profile&id=<?php echo $uid; ?>">My Profile</a></li> <li><a id="dropped" class="<?php if($p=='friend'){ echo 'active';} ?>" href="index.php?page=friend&num=2&id=<?php echo $uid; ?>">Friends</a> <ul class="subnav"> <li class="top_drop"></li> <li><a href="index.php?page=friend&num=1&id=<?php echo $uid; ?>">Find Friends</a></li> <li><a href="index.php?page=friend&num=2&id=<?php echo $uid; ?>">My Friends</a></li> <li><a href="index.php?page=friend&num=3&id=<?php echo $uid; ?>">Friend Requests</a></li> <li class="bottom_drop"></li> </ul> </li> <li><a id="dropped2" class="<?php if($p=='inbox'){ echo 'active';} ?>" href="index.php?page=inbox&num=1&id=<?php echo $uid; ?>">Mailbox</a> <ul class="subnav"> <li class="top_drop"></li> <li><a href="index.php?page=inbox&num=1&id=<?php echo $uid; ?>">Inbox</a></li> <li><a href="index.php?page=inbox&num=2&id=<?php echo $uid; ?>">Compose</a></li> <li class="bottom_drop"></li> </ul> </li> <li><a href="../">Logout</a></li> </ul> </div>
069kb4-discussion-forum
trunk/discuss/inc/navigation.php
PHP
mit
1,639
<?php $con=mysql_connect("localhost","root","") or die("Couldnot establish connection with database server"); mysql_select_db("db_discuss",$con); $topic=$_GET['topic']; $category=$_GET['cat']; $message=mysql_query("select * from tbl_topics where tid=$topic",$con); $row=mysql_fetch_array($message); ?> <h3><a href="index.php?page=home&id=<?php echo $uid; ?>">Discuss Home</a> &gt; <?php echo $category=$_GET['cat']; ?></h3> <ul class="friend_requests"> <?php $startedby=$row['startedby']; $topic=$row['topic']; $message=$row['message']; $count=$row['replies']; $tid=$row['tid']; echo "<li><h3>".$topic."<span class='started'>(Started by - ".$startedby.")</span></h3><div class='dis_message'>".$message."</div></li>"; $msg_reply=mysql_query("select * from tbl_replies where tid='$tid'",$con); while($rec=mysql_fetch_array($msg_reply)){ echo "<li><h4>Reply by: ".$rec[name]."</h4><div class='dis_message'>".$rec[rep_message]."</div></li>"; } mysql_close($con); ?> </ul> <h1>Reply</h1> <form method='post' action='index.php?page=home&topic=<?php echo $tid."&cat=".$category."&num=5&id=".$uid; ?>' > <p> <textarea name='reply' class='huge'></textarea> </p><p> <input type='submit' value='Post'> </p></form>
069kb4-discussion-forum
trunk/discuss/inc/home4.php
PHP
mit
1,249
@charset "utf-8"; /* CSS Document */ body,ul,li,h1,h2,h3,h4,h5,ol,a{ margin: 0; padding: 0; outline: none; } body{ font-family: Arial, Helvetica, sans-serif; font-size: 14px; color:#333333333; } a { color:#0471e1; font-weight:bold; text-decoration:none; } a:hover { text-decoration:underline; } h3{ padding: 13px 0; } h3 a:link, h3 a:visited{ text-decoration: none; } h3 a:hover{ color: #F60; } #loginform, #loginform2 { border-top:1px dashed #999999; padding-top:20px; float:left; font-size:13px; } #loginform2 input { width:220px; border:1px solid #cccccc; padding:3px; font-size:13px; height:17px; } .line { font-family:Arial, Helvetica, sans-serif; font-size:11px; color:#333333; } #loginform input { width:320px; border:1px solid #cccccc; padding:3px; color:#333333; font-size:13px; font-weight:bold; } #loginform input:focus, #loginform2 input:focus { border:1px solid #0e8fc3; box-shadow:0px 0px 5px #0e8fc3; } #loginform label { float:right; padding-right:5px; } #loginform .button, #loginform2 .button { background:#0471e1; border-radius:5px; border:1px solid #02a0c1; width:100px; cursor:pointer; font-weight:normal; height:30px; color:#ffffff; background-image: -moz-linear-gradient(top, #02a0c1, #0e8fc3); background-image: -ms-linear-gradient(top, #02a0c1, #0e8fc3); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#02a0c1), to(#0e8fc3)); background-image: -webkit-linear-gradient(top, #02a0c1, #0e8fc3); background-image: -o-linear-gradient(top, #02a0c1, #0e8fc3); background-image: linear-gradient(top, #02a0c1, #0e8fc3); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#02a0c1', endColorstr='#0e8fc3', GradientType=0); background-color:#333333; font-weight:bold; border-radius:4px; padding:5px 15px; font-size:14px; color:#ffffff; } .error { color:#ff0000; font-size:12px; font-weight:bold; } #loginform .button:hover, #loginform2 .button:hover { background:#078aa5; } #loginform .short { width:99px; } textarea.huge{ width: 544px; height: 220px; } .red{ color: red; } .breadcum { font-weight:normal; color:#555555; font-size:13px; } .allbutton { font-size:21px; color:#eeeeee; padding:6px 15px 6px 15px; font-weight:normal; border-radius:4px; background-image:-moz-linear-gradient(top, #0e8fc3, #078aa5); background-image:-ms-linear-gradient(top, #0e8fc3, #078aa5); background-image:-webkit-linear-gradient(top, #0e8fc3, #078aa5); background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#0e8fc3), to(#078aa5)); background-image:-o-linear-gradient(top, #0e8fc3, #078aa5); background-image:linear-gradient(#0e8fc3, #0e8fc3); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#0e8fc3', endColorstr='#078aa5', GradientType=0); background-color:#0e8fc3; } .allbutton:hover { background-image:-moz-linear-gradient(top, #0e8fc3, #0e8fc3); background-image:-ms-linear-gradient(top, #0e8fc3, #0e8fc3); background-image:-webkit-linear-gradient(top, #0e8fc3, #0e8fc3); background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#0e8fc3), to(#0e8fc3)); background-image:-o-linear-gradient(top, #0e8fc3, #0e8fc3); background-image:linear-gradient(#0e8fc3, #0e8fc3); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#0e8fc3', endColorstr='#0e8fc3', GradientType=0); background-color:#0e8fc3; color:#ffffff; text-decoration:none; } .button:hover { color:#efefef; } .wrapper{ margin: 0 auto; width: 823px; } .logo{ margin-top: 40px; width: 100%; float:left; } .logo a.guestbook_logo{ background: url(../images/logo.png) no-repeat; width: 184px; height: 18px; float:left; outline: none; } .search{ width: 150px; height:15px; border:1px solid #ffffff; padding:2px; margin:5px 5px 0 0; position: relative; } .search:focus{ width:200px; border:1px #0s8fc3; box-shadow:0px 0px 7px #0e8fc3; } .search input{ color: #999999; } .search input:active,.search input:focus{ color: #444444; } .search input.button{ color: #333333333; padding: 2px 13px; } .navigation{ width: 100%; float:left; background:#f75c18; height:30px; background:#efefef url(../images/nav.png); margin-top:15px; } .navigation ul{ line-height:30px; float:right; } .navigation ul li{ list-style:none; position: relative; float:left; border-left:1px solid #ffffff; } .navigation ul li a:link,.navigation ul li a:visited{ color: #555555; text-decoration: none; display: block; float:left; padding: 0 31px; font-family: Arial, Helvetica, sans-serif, Geneva, sans-serif; font-size: 13px; font-weight: bold; } .navigation ul li a.active{ color: #000000; } .navigation ul li a:hover{ color: #333333; background:#dddddd; } /*------------------Dropdown starts-----------------------*/ ul.topnav li span.subhover {background-position: center bottom; cursor: pointer;} /*--Hover effect for trigger--*/ ul.topnav li ul.subnav { position: absolute; /*--Important - Keeps subnav from affecting main navigation flow--*/ left: -1px; top: 30px; margin: 0; padding: 0; display: none; float: left; width: 222px; } ul.topnav li ul.subnav li{ background: url(../images/dropnavi_mid.jpg) repeat-y; margin: 0; padding: 0; display: block; } ul.topnav li ul.subnav li.top_drop{ background: url(../images/dropnavi_top.jpg) no-repeat; width: 222px; height: 24px; } ul.topnav li ul.subnav li.bottom_drop{ background: url(../images/dropnavi_bottom.jpg) no-repeat; width: 222px; height: 24px; } html ul.topnav li ul.subnav li a { display: block; padding: 0px; padding-left: 10px; line-height: 31px; height: 31px; font-weight: normal; font-variant: normal; width: 210px; color:#666666; font-weight: bold; border-top: 1px solid #ffffff; border-bottom: 1px solid #ccc; margin: 0 1px; } html ul.topnav li ul.subnav li a:hover{ color: #000000; background:#eeeeee; } /*------------------------------Dropdown ends-----------------------------*/ /*-----------------------Content starts-----------------*/ .content{ width: 100%; height:auto; margin-top: 40px; float:left; } .content h1{ color: #a5aeb9; font-family:Arial, Helvetica, sans-serif; } .messages_contain h2{ color:#2F96CB; text-align: center; padding-bottom: 10px; border-bottom: 4px solid #ccc; } .messages_contain hr{ margin-top: 0; } .adv_search{ width: 100%; float: left; padding-bottom: 22px; margin-bottom: 40px; border-bottom: 2px double #444; } .adv_search input{ color: #999; } .adv_search input:active,.adv_search input:focus{ color: #444; } .adv_search input.button{ color: #333333; padding: 2px 13px; } .search_results{ margin-top: 22px; } .content a.gotoguestbook{ background: url(../images/gotoguestbook.png) no-repeat; display: block; width: 554px; height: 224px; float:left; text-indent: -9999px; } .interests{ width: 100%; float: left; margin-bottom: 22px; } .interests ul{ list-style: none; } .interests ul li{ display: inline; } .interests ul li a:link,.interests ul li a:visited{ height: 154px; width: 202px; margin-top:20px; float: left; } .interests ul li a:hover { opacity:0.8; } .interests h3{ color: #04519e; font-family:Arial, Helvetica, sans-serif; font-size: 19px; font-weight: normal; border-bottom: 1px dashed #333333; } ul.friend_requests{ float: left; width: 100%; margin-top: 22px; } ul.friend_requests li{ padding: 7px 0; border-bottom: 1px dotted #ccc; margin-top: 1px; width: 100%; float:left; list-style: none; } ul.friend_requests li a:link,ul.friend_requests li a:visited{ float: none; } ul.friend_requests li h3{ color: #069; background: #ddd; padding: 3px 0 3px 13px; font-size: 17px; } ul.friend_requests li h4{ color: #09C; background: #ddd; padding: 3px 0 3px 13px; font-size: 13px; } ul.friend_requests li h3 span.started{ font-weight: normal; color: #F60; font-size: 12px; padding-left: 13px; } ul.friend_requests li h5{ font-weight: normal; color: #F60; font-size: 12px; padding-left: 13px; } .dis_message{ padding: 13px; background: #f1f1f1; } /*-----------------------Discussion starts-----------------*/ .discus_topics{ width: 100%; float:left; margin-top: 3px; } .discus_topics th,.discus_topics td{ border: 1px dotted #333333; padding: 5px 13px; } /*-----------------------footer starts-----------------*/ .footer { background:#cccccc; margin-top:100px; float:left;ccccc; width:100%; height:100px; }
069kb4-discussion-forum
trunk/css/styles.css
CSS
mit
8,921
<?php $con=mysql_connect("localhost","root","") or die("Couldnot establish connection with database server"); mysql_select_db("db_discuss",$con); $display_query=mysql_query("select * from tbl_mailbox where mail_to='$uid'",$con); ?> <div class="interests"> <h1>Inbox</h1> <table border="1" cellpadding="3" cellspacing="0"> <?php if(!$row=mysql_fetch_array($display_query)){ echo 'Sorry, there are no messages.'; } else{ ?> <tr> <th>From</th> <th>Message</th> </tr> <?php do{ echo "<tr><td>".$row[mail_from]."</td><td>".$row[messages]."</td></tr>"; }while($row=mysql_fetch_array($display_query)); } ?> </table> </div> <?php mysql_close($con); ?>
069kb4-discussion-forum
trunk/inc/inbox1.php
PHP
mit
998
<div class="interests"> <h1>Find Friends</h1> <form name="register" action="search_member.php?page=friend&id=<?php echo $uid; ?>" method="post"> <table width="500" border="0" cellspacing="3" cellpadding="3"> <tr> <td>Name:</td> <td><input type="text" name="name" /></td> </tr> <tr height="22"> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td align="right">&nbsp;</td> <td><input type="submit" value="Search Members" /></td> </tr> </table> </form> </div>
069kb4-discussion-forum
trunk/inc/friend1.php
PHP
mit
526
<?php $tid=$_GET['topic']; $category=$_GET['cat']; ?> <h3><a href="index.php?page=home&id=<?php echo $uid; ?>">Discuss Home</a> &gt; <?php echo $category; ?></h3> <ul class="friend_requests"> <?php $reply_message=$_POST['reply']; $con=mysql_connect("localhost","root","") or die("Couldnot establish connection with database server"); mysql_select_db("db_discuss",$con); $qry=mysql_query("select * from tbl_topics where tid='$tid'",$con); $row=mysql_fetch_array($qry); $startedby=$row[startedby]; $topic=$row[topic]; $message=$row[message]; $tid=$row[tid]; $replies=$row[replies]+1; if($reply_message){ $reply_name=mysql_query("select name from tbl_discuss where uid='$uid'",$con); $name_arr=mysql_fetch_array($reply_name); $name_reply=$name_arr[name]; mysql_query("insert into tbl_replies(tid,rep_message,name) values('$tid','$reply_message','$name_reply')",$con); mysql_query("update tbl_topics set replies='$replies' where tid='$tid'",$con); } echo "<li><h3>".$topic."<span class='started'>(Started by - ".$startedby.")</span></h3><div class='dis_message'>".$message."</div></li>"; $msg_reply=mysql_query("select * from tbl_replies where tid='$tid'",$con); while($rec=mysql_fetch_array($msg_reply)){ echo "<li><h4>Reply by: ".$rec[name]."</h4><div class='dis_message'>".$rec[rep_message]."</div></li>"; } ?> </ul> <h1>Reply</h1> <form method='post' action='index.php?page=home&topic=<?php echo $tid."&cat=".$category."&num=5&id=".$uid; ?>' > <p> <textarea name='reply' class='huge'></textarea> </p><p> <input type='submit' value='Post'> </p></form> <?php mysql_close($con); ?>
069kb4-discussion-forum
trunk/inc/home5.php
PHP
mit
1,645
<div class="interests"> <h1>My Friends</h1> <ul class="friend_requests"> <?php $con=mysql_connect("localhost","root","") or die("Couldnot establish connection with database server"); mysql_select_db("db_discuss",$con); $display_query=mysql_query("select * from tbl_friend where (req_from='$uid' or req_to='$uid') and accept='y'",$con); while($row=mysql_fetch_array($display_query)){ if($row[req_from]==$uid){ $fren=$row[req_to]; } else{ $fren=$row[req_from]; } $display_frn=mysql_query("select * from tbl_discuss where uid='$fren'",$con); while($record=mysql_fetch_array($display_frn)){ echo "<li><a href='index.php?page=profile_frn&friend=".$record[uid]."&id=".$uid."'><strong>".$record[name]."</strong></a></li>"; echo "<br>"; } } ?> </ul> </div>
069kb4-discussion-forum
trunk/inc/friend2.php
PHP
mit
875
<?php $con=mysql_connect("localhost","root","") or die("Couldnot establish connection with database server"); mysql_select_db("db_discuss",$con); $starter=mysql_query("select * from tbl_discuss where uid=$uid",$con); $row=mysql_fetch_array($starter); $startedby= $row[username]; $category=$_GET['cat']; $topic=$_POST['topic']; $message=$_POST['message']; echo "<h1>$category</h1>"; mysql_query("insert into tbl_topics (startedby,topic,message,replies,category) values('$startedby','$topic','$message','0','$category')",$con) or die("Sorry, Message cannot be posted"); echo "<p class='red'>Message has been Posted</a> <br><br>"; $qry=mysql_query("select * from tbl_topics where startedby='$startedby' and topic='$topic'",$con); $rec=mysql_fetch_array($qry); $topic=$rec[tid]; ?> <h3><a href="index.php?page=home&id=<?php echo $uid; ?>">Discuss Home</a> &gt; <?php echo $category=$_GET['cat']; ?></h3> <a href="index.php?page=home&cat=<?php echo $category.'&topic='.$topic.'&num=4&id='.$uid; ?>" class="view_post">View your post</a> <?php mysql_close($con); ?>
069kb4-discussion-forum
trunk/inc/home3.php
PHP
mit
1,091
<div class="interests"> <h1>Friend Requests</h1> <?php $con=mysql_connect("localhost","root","") or die("Couldnot establish connection with database server"); mysql_select_db("db_discuss",$con); $display_query=mysql_query("select * from tbl_friend where req_to='$uid' and accept='n'",$con); $requests=mysql_num_rows($display_query); if($requests < 1){ echo "<p class='red'>Sorry, you have no friend requests now.</p>"; } else{ ?> <form method="post" action="request_friend.php?page=friend&id=<?php echo $uid; ?>"> <ul class="friend_requests"> <?php while($row=mysql_fetch_array($display_query)){ $user=$row[req_from]; $dis_qry=mysql_query("select * from tbl_discuss where uid=$user",$con); while($record=mysql_fetch_array($dis_qry)){ echo "<li><a href=''>".$record[name]."</a> has added you as friend. <strong>Accept?</strong> <input type='checkbox' name='accept[]' value='".$user."' /></li>"; } } ?> <li> <input type="submit" value="Done" /> </li> </ul> </form> <?php mysql_close($con); } ?> </div>
069kb4-discussion-forum
trunk/inc/friend3.php
PHP
mit
1,264
<?php $con=mysql_connect("localhost","root","") or die("Couldnot establish connection with database server"); mysql_select_db("db_discuss",$con); $display_query=mysql_query("select * from tbl_discuss where uid='$uid'",$con); ?> <div class="interests"> <h1>My Profile</h1> <p> Edit to change your profile. </p> <?php while($row=mysql_fetch_array($display_query)){ ?> <form onsubmit="return validate();" name="register" action="update_profile.php?page=profile&id=<?php echo $uid; ?>" method="post"> <table width="500" border="0" cellspacing="3" cellpadding="3"> <tr> <th>Username:</th> <td><strong> <?php echo $row[username]; ?> </strong></td> </tr> <tr> <th>Name:</th> <td><input type="text" name="name" value="<?php echo $row[name]; ?>" /></td> </tr> <tr> <th>Country:</th> <td><input type="text" name="country" value="<?php echo $row[country]; ?>" /></td> </tr> <tr> <th>Age:</th> <td><input type="text" name="age" value="<?php echo $row[age]; ?>" /></td> </tr> <tr> <th>Gender:</th> <td> <strong> <?php if($row[gender]=='m') echo 'male'; else echo 'female'; ?> </strong> </td> </tr> <tr> <th>Phone:</th> <td><input type="text" name="phone" value="<?php echo $row[phone]; ?>" /></td> </tr> <tr> <th>Email:</th> <td><strong> <?php echo $row[email]; ?> </strong></td> </tr> <tr> <th>Interests:</thd> <td><textarea name="interests"><?php echo $row[intrests]; ?> </textarea></td> </tr> <tr> <th>Biography:</th> <td><textarea name="biography"><?php echo $row[biography]; ?> </textarea></td> </tr> <tr height="22"> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td align="right">&nbsp;</td> <td><input type="submit" value="Update" /></td> </tr> </table> </form> <?php } mysql_close($con); ?> </div>
069kb4-discussion-forum
trunk/inc/profile.php
PHP
mit
2,069
<?php $con=mysql_connect("localhost","root","") or die("Couldnot establish connection with database server"); mysql_select_db("db_discuss",$con); $display_query=mysql_query("select * from tbl_friend where (req_from='$uid' or req_to='$uid') and accept='y'",$con); ?> <div class="interests"> <h1>Compose Mail</h1> <form method="post" action="sendmail.php?page=inbox&id=<?php echo $uid; ?>" > <p> <label>Select your friend:</label> <select name="friend"> <?php while($row=mysql_fetch_array($display_query)){ if($row[req_from]==$uid){ $fren=$row[req_to]; } else{ $fren=$row[req_from]; } $display_frn=mysql_query("select * from tbl_discuss where uid='$fren'",$con); while($record=mysql_fetch_array($display_frn)){ echo "<option value='".$record[uid]."'><br><strong>".$record[name]."</strong><br></option>"; } } ?> </select> </p> <p> <label>Message:</label> <textarea name="message"></textarea> </p> <p> <input type="submit" value="send" /> </p> </form> </div> <?php mysql_close($con); ?>
069kb4-discussion-forum
trunk/inc/inbox2.php
PHP
mit
1,365
<?php $friend=$_GET['friend']; $con=mysql_connect("localhost","root","") or die("Couldnot establish connection with database server"); mysql_select_db("db_discuss",$con); $display_query=mysql_query("select * from tbl_discuss where uid='$friend'",$con); ?> <div class="interests"> <?php while($row=mysql_fetch_array($display_query)){ ?> <h1><?php echo $row[username]; ?></h1> <table width="500" border="0" cellspacing="3" cellpadding="3"> <tr> <th>Username:</th> <td><strong> <?php echo $row[username]; ?> </strong></td> </tr> <tr> <th>Name:</th> <td><strong><?php echo $row[name]; ?></strong></td> </tr> <tr> <th>Country:</th> <td><strong><?php echo $row[country]; ?></strong></td> </tr> <tr> <th>Age:</th> <td><strong><?php echo $row[age]; ?></strong></td> </tr> <tr> <th>Gender:</th> <td> <strong> <?php if($row[gender]=='m') echo 'male'; else echo 'female'; ?> </strong> </td> </tr> <tr> <th>Phone:</th> <td><strong><?php echo $row[phone]; ?></strong></td> </tr> <tr> <th>Email:</th> <td><strong> <?php echo $row[email]; ?> </strong></td> </tr> <tr> <th>Interests:</thd> <td><strong><?php echo $row[intrests]; ?> </strong></td> </tr> <tr> <th>Biography:</th> <td><strong><?php echo $row[biography]; ?> </strong></td> </tr> <tr height="22"> <td>&nbsp;</td> <td>&nbsp;</td> </tr> </table> <?php } mysql_close($con); ?> </div>
069kb4-discussion-forum
trunk/inc/profile_frn.php
PHP
mit
1,646
<div class="footer"> <div class="wrapper"> <p> Designed and developed by: <a target="_blank" href="http://www.krignal.com">KRIGNAL.com</a> </p> </div> </div> </body> </html>
069kb4-discussion-forum
trunk/inc/footer.php
Hack
mit
213
<?php $uid=$_GET['id']; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>MDiscussion Center::Talk about anything</title> <link href="../css/styles.css" type="text/css" rel="stylesheet" /> <script language="javascript" src="../scripts/search_fun.js"></script> <script type="text/javascript" src="../scripts/jquery.js"></script> <script type="text/javascript" src="../scripts/dropmenu.js"></script> </head> <body>
069kb4-discussion-forum
trunk/inc/header.php
PHP
mit
636
<?php $category=$_GET['cat']; ?> <h3><a href="index.php?page=home&id=<?php echo $uid; ?>">Discuss Home</a> &gt; <?php echo $category=$_GET['cat']; ?></h3> <form method="post" action="index.php?page=home&cat=<?php echo $category.'&num=3&id='.$uid; ?>"> <p> <label>Topic:</label><input class="long" type="text" name="topic" > </p> <p> <textarea name="message" class="huge"></textarea> </p> <p> <input type="submit" value="Post"> </p> </form>
069kb4-discussion-forum
trunk/inc/home2.php
PHP
mit
494
<div class="interests"> <h3><a href="index.php?page=home&id=<?php echo $uid; ?>">Discuss Home</a> &gt; <?php echo $category=$_GET['cat']; ?></h3> <p> <strong><a href="index.php?page=home&num=2&cat=<?php echo $category.'&id='.$uid; ?>">Start A New Topic</a></strong> </p> <div class="discus_topics"> <?php $con=mysql_connect("localhost","root","") or die("Couldnot establish connection with database server"); mysql_select_db("db_discuss",$con); $qry_select=mysql_query("select * from tbl_topics where category='$category'",$con); ?> <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr> <th width="25%">Started by</th> <th width="55%">Topic Title</td> <th width="20%">Replies</th> </tr> <?php while($row=mysql_fetch_array($qry_select)){ ?> <tr> <td width="25%"><?php echo $row['startedby']; ?></td> <td width="55%"><a href="index.php?page=home&cat=<?php echo $category.'&topic='.$row['tid'].'&num=4&id='.$uid; ?>"><strong><?php echo $row['topic']; ?></strong></a></td> <td width="20%"><?php echo $row['replies']; ?></th> </tr> <?php } mysql_close($con); ?> </table> </div> </div>
069kb4-discussion-forum
trunk/inc/home1.php
PHP
mit
1,314
<div class="logo"> <a class="guestbook_logo" href="index.php"></a> </div>
069kb4-discussion-forum
trunk/inc/logoarea.php
Hack
mit
87
<div class="interests"> <h3>Choose your Interest for discussion</h3> <ul> <li><a href="index.php?page=login"><img src="images/interests/computer.png" alt="COMPUTER" /></a></li> <li><a href="index.php?page=login"><img src="images/interests/movies.png" alt="MOVIES" /></a></li> <li><a href="index.php?page=login"><img src="images/interests/music.png" alt="MUSIC" /></a></li> <li><a href="index.php?page=login"><img src="images/interests/soccer.png" alt="SPORTS" /></a></li> </ul> </div>
069kb4-discussion-forum
trunk/inc/home.php
Hack
mit
640
<?php $p=$_GET['page']; ?> <div class="navigation"> <ul class="topnav"> <li><img src="../images/navi_sep.png" alt="|" /></li> <li><a class="<?php if($p=='home' or $p==''){ echo 'active';} ?>" href="index.php?page=home&id=<?php echo $uid; ?>">Discuss</a><img src="../images/navi_sep.png" alt="|" /></li> <li><a class="<?php if($p=='profile'){ echo 'active';} ?>" href="index.php?page=profile&id=<?php echo $uid; ?>">My Profile</a><img src="../images/navi_sep.png" alt="|" /></li> <li><a id="dropped" class="<?php if($p=='friend'){ echo 'active';} ?>" href="index.php?page=friend&num=2&id=<?php echo $uid; ?>">Friends</a> <ul class="subnav"> <li class="top_drop"></li> <li><a href="index.php?page=friend&num=1&id=<?php echo $uid; ?>">Find Friends</a></li> <li><a href="index.php?page=friend&num=2&id=<?php echo $uid; ?>">My Friends</a></li> <li><a href="index.php?page=friend&num=3&id=<?php echo $uid; ?>">Friend Requests</a></li> <li class="bottom_drop"></li> </ul> <img src="../images/navi_sep.png" alt="|" /></li> <li><a id="dropped2" class="<?php if($p=='inbox'){ echo 'active';} ?>" href="index.php?page=inbox&num=1&id=<?php echo $uid; ?>">Mailbox</a> <ul class="subnav"> <li class="top_drop"></li> <li><a href="index.php?page=inbox&num=1&id=<?php echo $uid; ?>">Inbox</a></li> <li><a href="index.php?page=inbox&num=2&id=<?php echo $uid; ?>">Compose</a></li> <li class="bottom_drop"></li> </ul> <img src="../images/navi_sep.png" alt="|" /></li> <li><a href="../">Logout</a><img src="../images/navi_sep.png" alt="|" /></li> </ul> </div>
069kb4-discussion-forum
trunk/inc/navigation.php
PHP
mit
1,901
<?php $startedby=$_POST['startedby']; $con=mysql_connect("localhost","root","") or die("Couldnot establish connection with database server"); mysql_select_db("db_discuss",$con); $topic=$_GET['topic']; $category=$_GET['cat']; $message=mysql_query("select * from tbl_topics where tid=$topic",$con); $row=mysql_fetch_array($message); ?> <h3><a href="index.php?page=home&id=<?php echo $uid; ?>">Discuss Home</a> &gt; <?php echo $category=$_GET['cat']; ?></h3> <ul class="friend_requests"> <?php echo "<li><h3>".$topic."<span class='started'>(Started by - ".$startedby.")</span></h3><div class='dis_message'>".$message."</div></li>"; $msg_reply=mysql_query("select * from tbl_replies where tid='$tid'",$con); while($rec=mysql_fetch_array($msg_reply)){ echo "<li><h4>Reply by: ".$rec[name]."</h4><div class='dis_message'>".$rec[rep_message]."</div></li>"; } mysql_close($con); ?> </ul> <h1>Reply</h1> <form method='post' action='index.php?page=home&topic=<?php echo $tid."&cat=".$category."&num=5&id=".$uid; ?>' > <p> <textarea name='reply' class='huge'></textarea> </p><p> <input type='submit' value='Post'> </p></form>
069kb4-discussion-forum
trunk/inc/home4.php
PHP
mit
1,161
<?php $username=$_POST['username']; $password=$_POST['password']; $con=mysql_connect("localhost","root","") or die("Couldnot establish connection with database server"); mysql_select_db("db_discuss",$con); $display_query=mysql_query("select * from tbl_discuss where username='$username' and password='$password'",$con); //if($row=mysql_fetch_array($display_query)){ mysql_close($con); //header("Location:discuss/index.php?page=home&id=$row[uid]"); header("Location:discuss/index.php?page=home&id=1"); //} ?> <style type="text/css"> .error { color:#ff0000; font-weight:bold; } </style> <?php include("includes/header.php"); ?> <div class="wrapper"> <?php include("includes/logoarea.php"); ?> <?php include("includes/navigation.php"); ?> <div class="content"> <?php echo "<span class=error>Sorry, Username or password is incorrect.</span> <a href='index.php?page=login'>Try Again</a> or <a href='index.php?page=register'>Register</a>"; ?> </div> </div> <?php include("includes/footer.php"); ?>
069kb4-discussion-forum
trunk/log_process.php
PHP
mit
1,094
import time def yesno(question): val = raw_input(question + " ") return val.startswith("y") or val.startswith("Y") use_pysqlite2 = yesno("Use pysqlite 2.0?") use_autocommit = yesno("Use autocommit?") use_executemany= yesno("Use executemany?") if use_pysqlite2: from pysqlite2 import dbapi2 as sqlite else: import sqlite def create_db(): con = sqlite.connect(":memory:") if use_autocommit: if use_pysqlite2: con.isolation_level = None else: con.autocommit = True cur = con.cursor() cur.execute(""" create table test(v text, f float, i integer) """) cur.close() return con def test(): row = ("sdfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffasfd", 3.14, 42) l = [] for i in range(1000): l.append(row) con = create_db() cur = con.cursor() if sqlite.version_info > (2, 0): sql = "insert into test(v, f, i) values (?, ?, ?)" else: sql = "insert into test(v, f, i) values (%s, %s, %s)" starttime = time.time() for i in range(50): if use_executemany: cur.executemany(sql, l) else: for r in l: cur.execute(sql, r) endtime = time.time() print "elapsed", endtime - starttime cur.execute("select count(*) from test") print "rows:", cur.fetchone()[0] if __name__ == "__main__": test()
0o2batodd-friendly
benchmarks/insert.py
Python
mit
1,496
import time def yesno(question): val = raw_input(question + " ") return val.startswith("y") or val.startswith("Y") use_pysqlite2 = yesno("Use pysqlite 2.0?") if use_pysqlite2: use_custom_types = yesno("Use custom types?") use_dictcursor = yesno("Use dict cursor?") use_rowcursor = yesno("Use row cursor?") else: use_tuple = yesno("Use rowclass=tuple?") if use_pysqlite2: from pysqlite2 import dbapi2 as sqlite else: import sqlite def dict_factory(cursor, row): d = {} for idx, col in enumerate(cursor.description): d[col[0]] = row[idx] return d if use_pysqlite2: def dict_factory(cursor, row): d = {} for idx, col in enumerate(cursor.description): d[col[0]] = row[idx] return d class DictCursor(sqlite.Cursor): def __init__(self, *args, **kwargs): sqlite.Cursor.__init__(self, *args, **kwargs) self.row_factory = dict_factory class RowCursor(sqlite.Cursor): def __init__(self, *args, **kwargs): sqlite.Cursor.__init__(self, *args, **kwargs) self.row_factory = sqlite.Row def create_db(): if sqlite.version_info > (2, 0): if use_custom_types: con = sqlite.connect(":memory:", detect_types=sqlite.PARSE_DECLTYPES|sqlite.PARSE_COLNAMES) sqlite.register_converter("text", lambda x: "<%s>" % x) else: con = sqlite.connect(":memory:") if use_dictcursor: cur = con.cursor(factory=DictCursor) elif use_rowcursor: cur = con.cursor(factory=RowCursor) else: cur = con.cursor() else: if use_tuple: con = sqlite.connect(":memory:") con.rowclass = tuple cur = con.cursor() else: con = sqlite.connect(":memory:") cur = con.cursor() cur.execute(""" create table test(v text, f float, i integer) """) return (con, cur) def test(): row = ("sdfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffasfd", 3.14, 42) l = [] for i in range(1000): l.append(row) con, cur = create_db() if sqlite.version_info > (2, 0): sql = "insert into test(v, f, i) values (?, ?, ?)" else: sql = "insert into test(v, f, i) values (%s, %s, %s)" for i in range(50): cur.executemany(sql, l) cur.execute("select count(*) as cnt from test") starttime = time.time() for i in range(50): cur.execute("select v, f, i from test") l = cur.fetchall() endtime = time.time() print "elapsed:", endtime - starttime if __name__ == "__main__": test()
0o2batodd-friendly
benchmarks/fetch.py
Python
mit
2,801
#!/usr/bin/env python from pysqlite2.test import test test()
0o2batodd-friendly
scripts/test-pysqlite
Python
mit
61
from pysqlite2 import dbapi2 as sqlite import os, threading def getcon(): #con = sqlite.connect("db", isolation_level=None, timeout=5.0) con = sqlite.connect(":memory:") cur = con.cursor() cur.execute("create table test(i, s)") for i in range(10): cur.execute("insert into test(i, s) values (?, 'asfd')", (i,)) con.commit() cur.close() return con def reader(what): con = getcon() while 1: cur = con.cursor() cur.execute("select i, s from test where i % 1000=?", (what,)) res = cur.fetchall() cur.close() con.close() def appender(): con = getcon() counter = 0 while 1: cur = con.cursor() cur.execute("insert into test(i, s) values (?, ?)", (counter, "foosadfasfasfsfafs")) #cur.execute("insert into test(foo) values (?)", (counter,)) counter += 1 if counter % 100 == 0: #print "appender committing", counter con.commit() cur.close() con.close() def updater(): con = getcon() counter = 0 while 1: cur = con.cursor() counter += 1 if counter % 5 == 0: cur.execute("update test set s='foo' where i % 50=0") #print "updater committing", counter con.commit() cur.close() con.close() def deleter(): con = getcon() counter = 0 while 1: cur = con.cursor() counter += 1 if counter % 5 == 0: #print "deleter committing", counter cur.execute("delete from test where i % 20=0") con.commit() cur.close() con.close() threads = [] for i in range(10): continue threads.append(threading.Thread(target=lambda: reader(i))) for i in range(5): threads.append(threading.Thread(target=appender)) #threads.append(threading.Thread(target=updater)) #threads.append(threading.Thread(target=deleter)) for t in threads: t.start()
0o2batodd-friendly
scripts/stress.py
Python
mit
1,977
# Gerhard Haering <gh@gharing.d> is responsible for the hacked version of this # module. # # This is a modified version of the bdist_wininst distutils command to make it # possible to build installers *with extension modules* on Unix. """distutils.command.bdist_wininst Implements the Distutils 'bdist_wininst' command: create a windows installer exe-program.""" # This module should be kept compatible with Python 2.1. __revision__ = "$Id: bdist_wininst.py 59620 2007-12-31 14:47:07Z christian.heimes $" import sys, os, string from distutils.core import Command from distutils.util import get_platform from distutils.dir_util import create_tree, remove_tree from distutils.errors import * from distutils.sysconfig import get_python_version from distutils import log class bdist_wininst (Command): description = "create an executable installer for MS Windows" user_options = [('bdist-dir=', None, "temporary directory for creating the distribution"), ('keep-temp', 'k', "keep the pseudo-installation tree around after " + "creating the distribution archive"), ('target-version=', None, "require a specific python version" + " on the target system"), ('no-target-compile', 'c', "do not compile .py to .pyc on the target system"), ('no-target-optimize', 'o', "do not compile .py to .pyo (optimized)" "on the target system"), ('dist-dir=', 'd', "directory to put final built distributions in"), ('bitmap=', 'b', "bitmap to use for the installer instead of python-powered logo"), ('title=', 't', "title to display on the installer background instead of default"), ('skip-build', None, "skip rebuilding everything (for testing/debugging)"), ('install-script=', None, "basename of installation script to be run after" "installation or before deinstallation"), ('pre-install-script=', None, "Fully qualified filename of a script to be run before " "any files are installed. This script need not be in the " "distribution"), ] boolean_options = ['keep-temp', 'no-target-compile', 'no-target-optimize', 'skip-build'] def initialize_options (self): self.bdist_dir = None self.keep_temp = 0 self.no_target_compile = 0 self.no_target_optimize = 0 self.target_version = None self.dist_dir = None self.bitmap = None self.title = None self.skip_build = 0 self.install_script = None self.pre_install_script = None # initialize_options() def finalize_options (self): if self.bdist_dir is None: bdist_base = self.get_finalized_command('bdist').bdist_base self.bdist_dir = os.path.join(bdist_base, 'wininst') if not self.target_version: self.target_version = "" if not self.skip_build and self.distribution.has_ext_modules(): short_version = get_python_version() if self.target_version and self.target_version != short_version: raise DistutilsOptionError, \ "target version can only be %s, or the '--skip_build'" \ " option must be specified" % (short_version,) self.target_version = short_version self.set_undefined_options('bdist', ('dist_dir', 'dist_dir')) if self.install_script: for script in self.distribution.scripts: if self.install_script == os.path.basename(script): break else: raise DistutilsOptionError, \ "install_script '%s' not found in scripts" % \ self.install_script # finalize_options() def run (self): # HACK I disabled this check. if 0 and (sys.platform != "win32" and (self.distribution.has_ext_modules() or self.distribution.has_c_libraries())): raise DistutilsPlatformError \ ("distribution contains extensions and/or C libraries; " "must be compiled on a Windows 32 platform") if not self.skip_build: self.run_command('build') install = self.reinitialize_command('install', reinit_subcommands=1) install.root = self.bdist_dir install.skip_build = self.skip_build install.warn_dir = 0 install_lib = self.reinitialize_command('install_lib') # we do not want to include pyc or pyo files install_lib.compile = 0 install_lib.optimize = 0 if self.distribution.has_ext_modules(): # If we are building an installer for a Python version other # than the one we are currently running, then we need to ensure # our build_lib reflects the other Python version rather than ours. # Note that for target_version!=sys.version, we must have skipped the # build step, so there is no issue with enforcing the build of this # version. target_version = self.target_version if not target_version: assert self.skip_build, "Should have already checked this" target_version = sys.version[0:3] plat_specifier = ".%s-%s" % (get_platform(), target_version) build = self.get_finalized_command('build') build.build_lib = os.path.join(build.build_base, 'lib' + plat_specifier) # Use a custom scheme for the zip-file, because we have to decide # at installation time which scheme to use. for key in ('purelib', 'platlib', 'headers', 'scripts', 'data'): value = string.upper(key) if key == 'headers': value = value + '/Include/$dist_name' setattr(install, 'install_' + key, value) log.info("installing to %s", self.bdist_dir) install.ensure_finalized() # avoid warning of 'install_lib' about installing # into a directory not in sys.path sys.path.insert(0, os.path.join(self.bdist_dir, 'PURELIB')) install.run() del sys.path[0] # And make an archive relative to the root of the # pseudo-installation tree. from tempfile import mktemp archive_basename = mktemp() fullname = self.distribution.get_fullname() arcname = self.make_archive(archive_basename, "zip", root_dir=self.bdist_dir) # create an exe containing the zip-file self.create_exe(arcname, fullname, self.bitmap) if self.distribution.has_ext_modules(): pyversion = get_python_version() else: pyversion = 'any' self.distribution.dist_files.append(('bdist_wininst', pyversion, self.get_installer_filename(fullname))) # remove the zip-file again log.debug("removing temporary file '%s'", arcname) os.remove(arcname) if not self.keep_temp: remove_tree(self.bdist_dir, dry_run=self.dry_run) # run() def get_inidata (self): # Return data describing the installation. lines = [] metadata = self.distribution.metadata # Write the [metadata] section. lines.append("[metadata]") # 'info' will be displayed in the installer's dialog box, # describing the items to be installed. info = (metadata.long_description or '') + '\n' # Escape newline characters def escape(s): return string.replace(s, "\n", "\\n") for name in ["author", "author_email", "description", "maintainer", "maintainer_email", "name", "url", "version"]: data = getattr(metadata, name, "") if data: info = info + ("\n %s: %s" % \ (string.capitalize(name), escape(data))) lines.append("%s=%s" % (name, escape(data))) # The [setup] section contains entries controlling # the installer runtime. lines.append("\n[Setup]") if self.install_script: lines.append("install_script=%s" % self.install_script) lines.append("info=%s" % escape(info)) lines.append("target_compile=%d" % (not self.no_target_compile)) lines.append("target_optimize=%d" % (not self.no_target_optimize)) if self.target_version: lines.append("target_version=%s" % self.target_version) title = self.title or self.distribution.get_fullname() lines.append("title=%s" % escape(title)) import time import distutils build_info = "Built %s with distutils-%s" % \ (time.ctime(time.time()), distutils.__version__) lines.append("build_info=%s" % build_info) return string.join(lines, "\n") # get_inidata() def create_exe (self, arcname, fullname, bitmap=None): import struct self.mkpath(self.dist_dir) cfgdata = self.get_inidata() installer_name = self.get_installer_filename(fullname) self.announce("creating %s" % installer_name) if bitmap: bitmapdata = open(bitmap, "rb").read() bitmaplen = len(bitmapdata) else: bitmaplen = 0 file = open(installer_name, "wb") file.write(self.get_exe_bytes()) if bitmap: file.write(bitmapdata) # Convert cfgdata from unicode to ascii, mbcs encoded try: unicode except NameError: pass else: if isinstance(cfgdata, unicode): cfgdata = cfgdata.encode("mbcs") # Append the pre-install script cfgdata = cfgdata + "\0" if self.pre_install_script: script_data = open(self.pre_install_script, "r").read() cfgdata = cfgdata + script_data + "\n\0" else: # empty pre-install script cfgdata = cfgdata + "\0" file.write(cfgdata) # The 'magic number' 0x1234567B is used to make sure that the # binary layout of 'cfgdata' is what the wininst.exe binary # expects. If the layout changes, increment that number, make # the corresponding changes to the wininst.exe sources, and # recompile them. header = struct.pack("<iii", 0x1234567B, # tag len(cfgdata), # length bitmaplen, # number of bytes in bitmap ) file.write(header) file.write(open(arcname, "rb").read()) # create_exe() def get_installer_filename(self, fullname): # Factored out to allow overriding in subclasses if self.target_version: # if we create an installer for a specific python version, # it's better to include this in the name installer_name = os.path.join(self.dist_dir, "%s.win32-py%s.exe" % (fullname, self.target_version)) else: installer_name = os.path.join(self.dist_dir, "%s.win32.exe" % fullname) return installer_name # get_installer_filename() def get_exe_bytes (self): from distutils.msvccompiler import get_build_version # If a target-version other than the current version has been # specified, then using the MSVC version from *this* build is no good. # Without actually finding and executing the target version and parsing # its sys.version, we just hard-code our knowledge of old versions. # NOTE: Possible alternative is to allow "--target-version" to # specify a Python executable rather than a simple version string. # We can then execute this program to obtain any info we need, such # as the real sys.version string for the build. cur_version = get_python_version() if self.target_version and self.target_version != cur_version: if self.target_version < "2.3": raise NotImplementedError elif self.target_version == "2.3": bv = "6" elif self.target_version in ("2.4", "2.5"): bv = "7.1" elif self.target_version in ("2.6", "2.7"): bv = "9.0" else: raise NotImplementedError else: # for current version - use authoritative check. bv = get_build_version() # wininst-x.y.exe is in the same directory as this file directory = os.path.dirname(__file__) # we must use a wininst-x.y.exe built with the same C compiler # used for python. XXX What about mingw, borland, and so on? # The uninstallers need to be available in $PYEXT_CROSS/uninst/*.exe # Use http://oss.itsystementwicklung.de/hg/pyext_cross_linux_to_win32/ # and copy it alongside your pysqlite checkout. filename = os.path.join(directory, os.path.join(os.environ["PYEXT_CROSS"], "uninst", "wininst-%s.exe" % bv)) return open(filename, "rb").read() # class bdist_wininst
0o2batodd-friendly
cross_bdist_wininst.py
Python
mit
13,886
from __future__ import with_statement from pysqlite2 import dbapi2 as sqlite3 from datetime import datetime, timedelta import time def read_modify_write(): # Open connection and create example schema and data. # In reality, open a database file instead of an in-memory database. con = sqlite3.connect(":memory:") cur = con.cursor() cur.executescript(""" create table test(id integer primary key, data); insert into test(data) values ('foo'); insert into test(data) values ('bar'); insert into test(data) values ('baz'); """) # The read part. There are two ways for fetching data using pysqlite. # 1. "Lazy-reading" # cur.execute("select ...") # for row in cur: # ... # # Advantage: Low memory consumption, good for large resultsets, data is # fetched on demand. # Disadvantage: Database locked as long as you iterate over cursor. # # 2. "Eager reading" # cur.fetchone() to fetch one row # cur.fetchall() to fetch all rows # Advantage: Locks cleared ASAP. # Disadvantage: fetchall() may build large lists. cur.execute("select id, data from test where id=?", (2,)) row = cur.fetchone() # Stupid way to modify the data column. lst = list(row) lst[1] = lst[1] + " & more" # This is the suggested recipe to modify data using pysqlite. We use # pysqlite's proprietary API to use the connection object as a context # manager. This is equivalent to the following code: # # try: # cur.execute("...") # except: # con.rollback() # raise # finally: # con.commit() # # This makes sure locks are cleared - either by commiting or rolling back # the transaction. # # If the rollback happens because of concurrency issues, you just have to # try again until it succeeds. Much more likely is that the rollback and # the raised exception happen because of other reasons, though (constraint # violation, etc.) - don't forget to roll back on errors. # # Or use this recipe. It's useful and gets everything done in two lines of # code. with con: cur.execute("update test set data=? where id=?", (lst[1], lst[0])) def delete_older_than(): # Use detect_types if you want to use date/time types in pysqlite. con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_COLNAMES) cur = con.cursor() # With "DEFAULT current_timestamp" we have SQLite fill the timestamp column # automatically. cur.executescript(""" create table test(id integer primary key, data, created timestamp default current_timestamp); """) with con: for i in range(3): cur.execute("insert into test(data) values ('foo')") time.sleep(1) # Delete older than certain interval # SQLite uses UTC time, so we need to create these timestamps in Python, too. with con: delete_before = datetime.utcnow() - timedelta(seconds=2) cur.execute("delete from test where created < ?", (delete_before,)) def modify_insert(): # Use a unique index and the REPLACE command to have the "insert if not # there, but modify if it is there" pattern. Race conditions are taken care # of by transactions. con = sqlite3.connect(":memory:") cur = con.cursor() cur.executescript(""" create table test(id integer primary key, name, age); insert into test(name, age) values ('Adam', 18); insert into test(name, age) values ('Eve', 21); create unique index idx_test_data_unique on test(name); """) with con: # Make Adam age 19 cur.execute("replace into test(name, age) values ('Adam', 19)") # Create new entry cur.execute("replace into test(name, age) values ('Abel', 3)") if __name__ == "__main__": read_modify_write() delete_older_than() modify_insert()
0o2batodd-friendly
misc/patterns.py
Python
mit
3,936
##################################################################### # Makefile originally written by Hans Oesterholt-Dijkema # Adapted and sanitized by Gerhard Haering for use with the pysqlite # project. # # It works with the free MSVC2003 toolkit as well as with MS Visual # Studio 2003. # # Makefile for SQLITE for use with GNU Make (MinGW/MSYS) # and the MSVC2003 free toolkit. Expects the MSVC Free SDK # installed along with the MSVC2003 free toolkit. # # Expects $INCLUDE, $LIB, $PATH set right for use with CL.EXE in # MSYS. NEEDS MSYS for clean: and install:, for making only: # Works also in the Visual C++ Toolkit 2003 Command Prompt, # provided %INCLUDE%, %LIB%, %PATH% are set accordingly. ##################################################################### CL=cl CLFLAGS=-O2 -Og -G7 LINK=link PREFIX=$$VCTOOLKITINSTALLDIR INCINST=$(PREFIX)/include LIBINST=$(PREFIX)/lib BININST=$(PREFIX)/bin SQLITE_OBJ = alter.o analyze.o attach.o auth.o btree.o build.o \ callback.o complete.o date.o \ delete.o expr.o func.o hash.o insert.o \ main.o opcodes.o os.o os_unix.o os_win.o \ pager.o parse.o pragma.o prepare.o printf.o random.o \ select.o table.o tokenize.o trigger.o update.o \ util.o vacuum.o \ vdbe.o vdbeapi.o vdbeaux.o vdbefifo.o vdbemem.o \ where.o utf.o legacy.o loadext.o vtab.o SQLITE_OBJ = alter.o analyze.o attach.o auth.o btmutex.o btree.o build.o callback.o \ complete.o date.o delete.o expr.o func.o hash.o insert.o journal.o \ legacy.o loadext.o main.o malloc.o mem1.o mem2.o mem3.o mutex.o \ mutex_w32.o opcodes.o os.o os_win.o pager.o parse.o pragma.o prepare.o \ printf.o random.o select.o table.o tokenize.o trigger.o update.o utf.o \ util.o vacuum.o vdbeapi.o vdbeaux.o vdbeblob.o vdbe.o vdbefifo.o vdbemem.o \ vtab.o where.o SQLITE_PRG_OBJ=shell.o all: sqlite3.lib @echo "done" clean: rm -f *.dll *.lib *.exp *.exe *.o sqlite3.exe: sqlite3.dll $(SQLITE_PRG_OBJ) $(LINK) -OUT:sqlite3.exe $(SQLITE_PRG_OBJ) sqlite3.lib sqlite3static.lib: $(SQLITE_OBJ) $(LINK) -LIB -OUT:sqlite3static.lib $(SQLITE_OBJ) sqlite3.dll: $(SQLITE_OBJ) $(LINK) -OUT:sqlite3.dll -dll -def:sqlite3.def $(SQLITE_OBJ) %.o: %.c $(CL) -c $(CLFLAGS) -Fo$@ $<
0o2batodd-friendly
misc/Makefile
Makefile
mit
2,369
from pysqlite2 import dbapi2 as sqlite3 Cursor = sqlite3.Cursor class EagerCursor(Cursor): def __init__(self, con): Cursor.__init__(self, con) self.rows = [] self.pos = 0 def execute(self, *args): sqlite3.Cursor.execute(self, *args) self.rows = Cursor.fetchall(self) self.pos = 0 def fetchone(self): try: row = self.rows[self.pos] self.pos += 1 return row except IndexError: return None def fetchmany(self, num=None): if num is None: num = self.arraysize result = self.rows[self.pos:self.pos+num] self.pos += num return result def fetchall(self): result = self.rows[self.pos:] self.pos = len(self.rows) return result def test(): con = sqlite3.connect(":memory:") cur = con.cursor(EagerCursor) cur.execute("create table test(foo)") cur.executemany("insert into test(foo) values (?)", [(3,), (4,), (5,)]) cur.execute("select * from test") print cur.fetchone() print cur.fetchone() print cur.fetchone() print cur.fetchone() print cur.fetchone() if __name__ == "__main__": test()
0o2batodd-friendly
misc/eager.py
Python
mit
1,230
/* microprotocols.c - minimalist and non-validating protocols implementation * * Copyright (C) 2003-2004 Federico Di Gregorio <fog@debian.org> * * This file is part of psycopg and was adapted for pysqlite. Federico Di * Gregorio gave the permission to use it within pysqlite under the following * license: * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #include <Python.h> #include <structmember.h> #include "cursor.h" #include "microprotocols.h" #include "prepare_protocol.h" /** the adapters registry **/ PyObject *psyco_adapters; /* pysqlite_microprotocols_init - initialize the adapters dictionary */ int pysqlite_microprotocols_init(PyObject *dict) { /* create adapters dictionary and put it in module namespace */ if ((psyco_adapters = PyDict_New()) == NULL) { return -1; } return PyDict_SetItemString(dict, "adapters", psyco_adapters); } /* pysqlite_microprotocols_add - add a reverse type-caster to the dictionary */ int pysqlite_microprotocols_add(PyTypeObject *type, PyObject *proto, PyObject *cast) { PyObject* key; int rc; if (proto == NULL) proto = (PyObject*)&pysqlite_PrepareProtocolType; key = Py_BuildValue("(OO)", (PyObject*)type, proto); if (!key) { return -1; } rc = PyDict_SetItem(psyco_adapters, key, cast); Py_DECREF(key); return rc; } /* pysqlite_microprotocols_adapt - adapt an object to the built-in protocol */ PyObject * pysqlite_microprotocols_adapt(PyObject *obj, PyObject *proto, PyObject *alt) { PyObject *adapter, *key; /* we don't check for exact type conformance as specified in PEP 246 because the pysqlite_PrepareProtocolType type is abstract and there is no way to get a quotable object to be its instance */ /* look for an adapter in the registry */ key = Py_BuildValue("(OO)", (PyObject*)obj->ob_type, proto); if (!key) { return NULL; } adapter = PyDict_GetItem(psyco_adapters, key); Py_DECREF(key); if (adapter) { PyObject *adapted = PyObject_CallFunctionObjArgs(adapter, obj, NULL); return adapted; } /* try to have the protocol adapt this object*/ if (PyObject_HasAttrString(proto, "__adapt__")) { PyObject *adapted = PyObject_CallMethod(proto, "__adapt__", "O", obj); if (adapted) { if (adapted != Py_None) { return adapted; } else { Py_DECREF(adapted); } } if (PyErr_Occurred() && !PyErr_ExceptionMatches(PyExc_TypeError)) return NULL; } /* and finally try to have the object adapt itself */ if (PyObject_HasAttrString(obj, "__conform__")) { PyObject *adapted = PyObject_CallMethod(obj, "__conform__","O", proto); if (adapted) { if (adapted != Py_None) { return adapted; } else { Py_DECREF(adapted); } } if (PyErr_Occurred() && !PyErr_ExceptionMatches(PyExc_TypeError)) { return NULL; } } /* else set the right exception and return NULL */ PyErr_SetString(pysqlite_ProgrammingError, "can't adapt"); return NULL; } /** module-level functions **/ PyObject * pysqlite_adapt(pysqlite_Cursor *self, PyObject *args) { PyObject *obj, *alt = NULL; PyObject *proto = (PyObject*)&pysqlite_PrepareProtocolType; if (!PyArg_ParseTuple(args, "O|OO", &obj, &proto, &alt)) return NULL; return pysqlite_microprotocols_adapt(obj, proto, alt); }
0o2batodd-friendly
src/microprotocols.c
C
mit
4,357
/* microprotocols.c - definitions for minimalist and non-validating protocols * * Copyright (C) 2003-2004 Federico Di Gregorio <fog@debian.org> * * This file is part of psycopg and was adapted for pysqlite. Federico Di * Gregorio gave the permission to use it within pysqlite under the following * license: * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #ifndef PSYCOPG_MICROPROTOCOLS_H #define PSYCOPG_MICROPROTOCOLS_H 1 #include <Python.h> /** adapters registry **/ extern PyObject *psyco_adapters; /** the names of the three mandatory methods **/ #define MICROPROTOCOLS_GETQUOTED_NAME "getquoted" #define MICROPROTOCOLS_GETSTRING_NAME "getstring" #define MICROPROTOCOLS_GETBINARY_NAME "getbinary" /** exported functions **/ /* used by module.c to init the microprotocols system */ extern int pysqlite_microprotocols_init(PyObject *dict); extern int pysqlite_microprotocols_add( PyTypeObject *type, PyObject *proto, PyObject *cast); extern PyObject *pysqlite_microprotocols_adapt( PyObject *obj, PyObject *proto, PyObject *alt); extern PyObject * pysqlite_adapt(pysqlite_Cursor* self, PyObject *args); #define pysqlite_adapt_doc \ "adapt(obj, protocol, alternate) -> adapt obj to given protocol. Non-standard." #endif /* !defined(PSYCOPG_MICROPROTOCOLS_H) */
0o2batodd-friendly
src/microprotocols.h
C
mit
2,118
#!/usr/bin/env python # # Cross-compile and build pysqlite installers for win32 on Linux or Mac OS X. # # The way this works is very ugly, but hey, it *works*! And I didn't have to # reinvent the wheel using NSIS. import os import sys import urllib import zipfile from setup import get_amalgamation # Cross-compiler if sys.platform == "darwin": CC = "/usr/local/i386-mingw32-4.3.0/bin/i386-mingw32-gcc" LIBDIR = "lib.macosx-10.6-i386-2.5" STRIP = "/usr/local/i386-mingw32-4.3.0/bin/i386-mingw32-gcc --strip-all" else: CC = "/usr/bin/i586-mingw32msvc-gcc" LIBDIR = "lib.linux-i686-2.5" STRIP = "strip --strip-all" # Optimization settings OPT = "-O2" # pysqlite sources + SQLite amalgamation SRC = "src/module.c src/connection.c src/cursor.c src/cache.c src/microprotocols.c src/prepare_protocol.c src/statement.c src/util.c src/row.c amalgamation/sqlite3.c" # You will need to fetch these from # https://pyext-cross.pysqlite.googlecode.com/hg/ CROSS_TOOLS = "../pysqlite-pyext-cross" def execute(cmd): print cmd return os.system(cmd) def compile_module(pyver): VER = pyver.replace(".", "") INC = "%s/python%s/include" % (CROSS_TOOLS, VER) vars = locals() vars.update(globals()) cmd = '%(CC)s -mno-cygwin %(OPT)s -mdll -DMODULE_NAME=\\"pysqlite2._sqlite\\" -DSQLITE_ENABLE_RTREE=1 -DSQLITE_ENABLE_FTS3=1 -I amalgamation -I %(INC)s -I . %(SRC)s -L %(CROSS_TOOLS)s/python%(VER)s/libs -lpython%(VER)s -o build/%(LIBDIR)s/pysqlite2/_sqlite.pyd' % vars execute(cmd) execute("%(STRIP)s build/%(LIBDIR)s/pysqlite2/_sqlite.pyd" % vars) def main(): vars = locals() vars.update(globals()) get_amalgamation() for ver in ["2.5", "2.6", "2.7"]: execute("rm -rf build") # First, compile the host version. This is just to get the .py files in place. execute("python2.5 setup.py build") # Yes, now delete the host extension module. What a waste of time. os.unlink("build/%(LIBDIR)s/pysqlite2/_sqlite.so" % vars) # Cross-compile win32 extension module. compile_module(ver) # Prepare for target Python version. libdir_ver = LIBDIR[:-3] + ver os.rename("build/%(LIBDIR)s" % vars, "build/" + libdir_ver) # And create the installer! os.putenv("PYEXT_CROSS", CROSS_TOOLS) execute("python2.5 setup.py cross_bdist_wininst --skip-build --target-version=" + ver) if __name__ == "__main__": main()
0o2batodd-friendly
mkwin32.py
Python
mit
2,464
/* :Author: David Goodger :Contact: goodger@users.sourceforge.net :Date: $Date: 2005-04-25 22:24:49 +0200 (Mon, 25 Apr 2005) $ :Version: $Revision: 3256 $ :Copyright: This stylesheet has been placed in the public domain. Default cascading style sheet for the HTML output of Docutils. */ /* "! important" is used here to override other ``margin-top`` and ``margin-bottom`` styles that are later in the stylesheet or more specific. See http://www.w3.org/TR/CSS1#the-cascade */ .first { margin-top: 0 ! important } .last { margin-bottom: 0 ! important } .hidden { display: none } a.toc-backref { text-decoration: none ; color: black } blockquote.epigraph { margin: 2em 5em ; } dl.docutils dd { margin-bottom: 0.5em } /* Uncomment (and remove this text!) to get bold-faced definition list terms dl.docutils dt { font-weight: bold } */ div.abstract { margin: 2em 5em } div.abstract p.topic-title { font-weight: bold ; text-align: center } div.admonition, div.attention, div.caution, div.danger, div.error, div.hint, div.important, div.note, div.tip, div.warning { margin: 2em ; border: medium outset ; padding: 1em } div.admonition p.admonition-title, div.hint p.admonition-title, div.important p.admonition-title, div.note p.admonition-title, div.tip p.admonition-title { font-weight: bold ; font-family: sans-serif } div.attention p.admonition-title, div.caution p.admonition-title, div.danger p.admonition-title, div.error p.admonition-title, div.warning p.admonition-title { color: red ; font-weight: bold ; font-family: sans-serif } /* Uncomment (and remove this text!) to get reduced vertical space in compound paragraphs. div.compound .compound-first, div.compound .compound-middle { margin-bottom: 0.5em } div.compound .compound-last, div.compound .compound-middle { margin-top: 0.5em } */ div.dedication { margin: 2em 5em ; text-align: center ; font-style: italic } div.dedication p.topic-title { font-weight: bold ; font-style: normal } div.figure { margin-left: 2em } div.footer, div.header { font-size: smaller } div.line-block { display: block ; margin-top: 1em ; margin-bottom: 1em } div.line-block div.line-block { margin-top: 0 ; margin-bottom: 0 ; margin-left: 1.5em } div.sidebar { margin-left: 1em ; border: medium outset ; padding: 1em ; background-color: #ffffee ; width: 40% ; float: right ; clear: right } div.sidebar p.rubric { font-family: sans-serif ; font-size: medium } div.system-messages { margin: 5em } div.system-messages h1 { color: red } div.system-message { border: medium outset ; padding: 1em } div.system-message p.system-message-title { color: red ; font-weight: bold } div.topic { margin: 2em } h1.title { text-align: center } h2.subtitle { text-align: center } hr.docutils { width: 75% } ol.simple, ul.simple { margin-bottom: 1em } ol.arabic { list-style: decimal } ol.loweralpha { list-style: lower-alpha } ol.upperalpha { list-style: upper-alpha } ol.lowerroman { list-style: lower-roman } ol.upperroman { list-style: upper-roman } p.attribution { text-align: right ; margin-left: 50% } p.caption { font-style: italic } p.credits { font-style: italic ; font-size: smaller } p.label { white-space: nowrap } p.rubric { font-weight: bold ; font-size: larger ; color: maroon ; text-align: center } p.sidebar-title { font-family: sans-serif ; font-weight: bold ; font-size: larger } p.sidebar-subtitle { font-family: sans-serif ; font-weight: bold } p.topic-title { font-weight: bold } pre.address { margin-bottom: 0 ; margin-top: 0 ; font-family: serif ; font-size: 100% } pre.line-block { font-family: serif ; font-size: 100% } pre.literal-block, pre.doctest-block { margin-left: 2em ; margin-right: 2em ; background-color: #eeeeee } span.classifier { font-family: sans-serif ; font-style: oblique } span.classifier-delimiter { font-family: sans-serif ; font-weight: bold } span.interpreted { font-family: sans-serif } span.option { white-space: nowrap } span.pre { white-space: pre } span.problematic { color: red } table.citation { border-left: solid thin gray } table.docinfo { margin: 2em 4em } table.docutils { margin-top: 0.5em ; margin-bottom: 0.5em } table.footnote { border-left: solid thin black } table.docutils td, table.docutils th, table.docinfo td, table.docinfo th { padding-left: 0.5em ; padding-right: 0.5em ; vertical-align: top } table.docutils th.field-name, table.docinfo th.docinfo-name { font-weight: bold ; text-align: left ; white-space: nowrap ; padding-left: 0 } h1 tt.docutils, h2 tt.docutils, h3 tt.docutils, h4 tt.docutils, h5 tt.docutils, h6 tt.docutils { font-size: 100% } tt.docutils { background-color: #eeeeee } ul.auto-toc { list-style-type: none } body { background-color: #eeeeff; font-family: Verdana, Arial, Helvetica, sans-serif; }
0o2batodd-friendly
doc/docutils.css
CSS
mit
5,000