count() public static method

public static count ( )
Example #1
0
 function draw()
 {
     global $display;
     $cat_newss = array();
     $display->add('is_admin', User::have_permit(ADMIN_NEWS));
     $display->add('url_home', WEB_DIR);
     $display->add('time_now', News::displayTime());
     $display->add('cat_name', $this->news_cat['name']);
     $display->add('cat_url', URL::build('news_list', array('news_catid' => $this->news_cat['id'], 'azname' => AZLib::safe_title($this->news_cat['name']))));
     $condition = ' status=1 ';
     $total = DB::count("news", $condition);
     $limit = '';
     //$pagging	= AZPagging::paging_list($limit,20,'page_no');
     $pagging = AZPagging::paging_list($limit, $total, 20);
     $re = DB::query('SELECT * FROM news WHERE ' . $condition . ' ORDER BY id DESC' . $limit);
     if ($re) {
         while ($news = mysql_fetch_assoc($re)) {
             $news['title'] = stripslashes($news['title']);
             $news['brief'] = stripslashes($news['brief']);
             $news['url'] = Url::build('news_detail', array('news_catid' => $news['news_catid'], 'news_id' => $news['id'], 'azname' => AZLib::safe_title($news['title'])));
             if ($news['image']) {
                 $news['image'] = AZLib::getImageThumb($news['image'], 150, 0, 0, $news['img_server']);
             }
             $news['news_h'] = date('H:i', $news['time_created']);
             $news['news_d'] = date('d-m-Y', $news['time_created']);
             $news['admin_link'] = News::admin_link($news);
             $cat_newss[$news['id']] = $news;
         }
     }
     $display->add('pagging', $pagging);
     $display->add('cat_newss', $cat_newss);
     $display->output("NewsPage");
 }
Example #2
0
 function draw()
 {
     global $display;
     $cats = array();
     $display->add('url_add', Url::build_current(array('cmd' => 'add')));
     /*
     $display->add('url_edit',Url::build_current(array('cmd'=>'edit','id'=>$category['id'])));
     $display->add('url_del',Url::build_current(array('cmd'=>'delete','id'=>$category['id'])));
     $display->add('url_sort_up',Url::build_current(array('cmd'=>'move_home','dir'=>'move_home','id'=>$category['id'])));
     $display->add('url_sort_low',Url::build_current(array('cmd'=>'move_home','dir'=>'move_end','id'=>$category['id'])));
     */
     $posMin = 1;
     $posMax = DB::count("news_categories");
     $re = DB::query('SELECT * FROM news_categories ORDER BY position, id');
     if ($re) {
         $index = 0;
         $column = 1;
         while ($row = mysql_fetch_assoc($re)) {
             $row['url'] = URL::build('news_list', array('news_catid' => $row['id'], 'azname' => AZLib::safe_title($row['name'])));
             $row['edit'] = Url::build_current(array('cmd' => 'edit', 'id' => $row['id']));
             $row['delete'] = Url::build_current(array('cmd' => 'delete', 'id' => $row['id']));
             $row['move_home'] = '<a title="Chuyển lên trên cùng" href="' . Url::build_current(array('cmd' => 'move_home', 'id' => $row['id'])) . '">Move HOME</a>';
             $row['move_end'] = '<a title="Chuyển xuống dưới cùng" href="' . Url::build_current(array('cmd' => 'move_end', 'id' => $row['id'])) . '">Move END</a>';
             if ($row['position'] > $posMin) {
                 $row['move_up'] = '<a title="Chuyển lên" href="' . Url::build_current(array('cmd' => 'move_up', 'id' => $row['id'])) . '"><img src="style/img/admin/move_up.gif"></a>';
             }
             if ($row['position'] < $posMax) {
                 $row['move_down'] = '<a title="Chuyển xuống" href="' . Url::build_current(array('cmd' => 'move_down', 'id' => $row['id'])) . '"><img src="style/img/admin/move_down.gif"></a>';
             }
             $cats[$row['id']] = $row;
         }
     }
     $display->add('cats', $cats);
     $display->output("NewsAdminCats");
 }
Example #3
0
 public function Scores($userid)
 {
     \DB::$user = '******';
     \DB::$password = '******';
     \DB::$dbName = 'Euro2016';
     $adminscore = \DB::query("select * from Scores where UserID = 4");
     $NoOfMatches = \DB::count();
     $userscore = \DB::query("select * from Scores where UserID = %i", $userid);
     $totalscore = 0;
     foreach ($adminscore as $ascore) {
         foreach ($userscore as $uscore) {
             if ($uscore['MatchID'] == $ascore['MatchID']) {
                 if ($uscore['CountryHome'] == $ascore['CountryHome'] && $uscore['CountryAway'] == $ascore['CountryAway']) {
                     $totalscore += 3;
                 } else {
                     if ($uscore['CountryHome'] > $uscore['CountryAway'] && $ascore['CountryHome'] > $ascore['CountryAway']) {
                         $totalscore += 1;
                     } else {
                         if ($uscore['CountryHome'] < $uscore['CountryAway'] && $ascore['CountryHome'] < $ascore['CountryAway']) {
                             $totalscore += 1;
                         } else {
                             if ($uscore['CountryHome'] == $uscore['CountryAway'] && $ascore['CountryHome'] == $ascore['CountryAway']) {
                                 $totalscore += 1;
                             }
                         }
                     }
                 }
             }
         }
     }
     return $totalscore;
 }
Example #4
0
 public function listAction()
 {
     $data = array();
     if (empty($this->_params['page'])) {
         $this->_params['page'] = 1;
     }
     if (empty($this->_params['perpage'])) {
         $this->_params['perpage'] = 20;
     }
     if (empty($this->_params['sortby'])) {
         $this->_params['sortby'] = 'depositor no.';
     }
     if (empty($this->_params['sortorder'])) {
         $this->_params['sortorder'] = 'DESC';
     }
     if (isset($this->_params['search'])) {
         #TODO
     } else {
         $from = $this->_params['page'] * $this->_params['perpage'] - $this->_params['perpage'];
         $query = 'SELECT * FROM depositors ORDER BY `' . $this->_params['sortby'] . '` ' . $this->_params['sortorder'] . ' LIMIT ' . $from . ', ' . $this->_params['perpage'];
         $data['pages'] = DB::count('depositors') / $this->_params['perpage'];
         $data['page'] = $this->_params['page'];
         if ($result = DB::exec($query)) {
             $data['success'] = true;
             $data['result'] = $result;
             return $data;
         } else {
             $data['success'] = false;
             $data['errormsg'] = 'DB fault';
             return $data;
         }
     }
 }
Example #5
0
 function test_Delete()
 {
     DB::insert('page', array('id' => 1, 'created' => time(), 'a' => 123, 'b' => 456));
     $item = new StoredItem('Page', 1);
     $this->assertTrue($item->Delete());
     $this->assertEqual(0, DB::count('page', "id='1'"));
 }
Example #6
0
 function draw()
 {
     global $display;
     $display->add('msg', $this->showFormErrorMessages(1));
     $display->add("url_admin", Url::build_current());
     $status_select = Url::get('status_select', 6);
     //1:Chưa cập nhật; 2: Đã gửi đơn hàng ; 3: Đã TT; 4: Hủy đơn hàng; 5: Đã duyệt
     $status_arr = array(6 => "--Tất cả--", 2 => "Đã gửi đơn hàng", 1 => "Chưa cập nhật", 3 => "Đã Thanh toán", 5 => "Đã duyệt", 4 => "Đã hủy");
     $display->add("status_option", AZLib::getOption($status_arr, $status_select));
     $date_begin = Url::get('date_begin');
     $date_end = Url::get('date_end');
     $display->add("date_begin", $date_begin);
     $display->add("date_end", $date_end);
     $created_time_from = 0;
     $created_time_to = 0;
     if ($date_begin) {
         $date_arr = explode("-", $date_begin);
         if (isset($date_arr[0]) && isset($date_arr[1]) && isset($date_arr[2])) {
             $created_time_from = mktime(0, 0, 0, (int) $date_arr[1], (int) $date_arr[0], (int) $date_arr[2]);
         }
     }
     if ($date_end) {
         $date_arr = explode("-", $date_end);
         if (isset($date_arr[0]) && isset($date_arr[1]) && isset($date_arr[2])) {
             $created_time_to = mktime(23, 59, 59, (int) $date_arr[1], (int) $date_arr[0], (int) $date_arr[2]);
         }
     }
     $condition = "";
     if ($status_select != 6) {
         $condition .= "status=" . $status_select;
     }
     if ($created_time_from) {
         $condition .= ($condition != '' ? ' AND ' : '') . ' time_create >=' . $created_time_from;
     }
     if ($date_end) {
         $condition .= ($condition != '' ? ' AND ' : '') . " time_create <={$created_time_to}";
     }
     $total = DB::count("cart", $condition);
     $limit = '';
     $display->add('paging', AZPagging::paging_list($limit, $total, 40, 10, 'page_no', '', true, 'Đơn hàng'));
     $all_carts = array();
     $re = DB::query("SELECT * FROM cart " . ($condition != '' ? 'WHERE ' : '') . $condition . " ORDER BY id DESC {$limit}");
     if ($re) {
         while ($Cart = mysql_fetch_assoc($re)) {
             $Cart["time_create"] = date('d/m/Y H:i:s', $Cart['time_create']);
             $Cart["time_change"] = date('d/m/Y H:i:s', $Cart['time_change']);
             $Cart["url"] = Url::build_current(array('cmd' => 'edit', 'id' => $Cart['id']));
             $Cart["status"] = $status_arr[$Cart['status']];
             $Cart["delete"] = Url::build_current(array('cmd' => 'delete', 'id' => $Cart['id']));
             $Cart["price"] = number_format($Cart['price'], null, null, '.');
             $all_carts[$Cart['id']] = $Cart;
         }
     }
     $display->add('all_carts', $all_carts);
     $display->add('is_admin', User::is_admin());
     $this->beginForm();
     $display->output('CartAdmin');
     $this->endForm();
 }
Example #7
0
 function draw()
 {
     global $display;
     $display->add('skin_path', IMAGE_PATH);
     $txt = '';
     $option1 = '';
     $sql = "SELECT * FROM `public_survey` WHERE ";
     $search = Url::get('search');
     if ($search != '') {
         $condition = "title LIKE '%{$search}%' OR question LIKE '%{$search}%'";
     } else {
         $condition = " 1";
     }
     $totalRows = DB::count("public_survey", $condition);
     $limit = '';
     $display->add('pagging', AZPagging::paging_list($limit, $totalRows, 40));
     $sql .= $condition . $limit;
     $block_id = (int) Url::get('block_id', 0);
     $href = str_replace(WEB_DIR, '', urldecode(Url::get('href')));
     $surveys = DB::fetch_all($sql);
     if ($surveys) {
         foreach ($surveys as &$survey) {
             if ($block_id) {
                 $survey["add_to_block"] = $href . ($href != '' ? '&' : '?') . "cmd=add_poll_to_block&poll_id={$survey['id']}&block_id={$block_id}";
             }
             if ($survey['view'] == 1) {
                 $survey["url_view"] = Url::build_current(array("cmd" => "unpublish", "id" => $survey['id']));
                 $survey["view"] = '<img src="style/images/unexam.gif" title="Ẩn"/>';
                 $survey["view_str"] = "Hiển thị";
             } else {
                 $survey["url_view"] = Url::build_current(array("cmd" => "publish", "id" => $survey['id']));
                 $survey["view_str"] = "Đang ẩn";
                 $survey["view"] = '<img src="style/images/exam.gif" title="Cho hiển thị"/>';
             }
             $survey["url_view_survey"] = Url::build('view_survey', array('id' => $survey['id']));
             $survey["url_option"] = Url::build('admin_option', array('id_survey' => $survey['id']));
             $question = $survey['question'] . '<br><br>';
             $total_cout = DB::fetch('SELECT SUM(`count`) AS total_cout FROM `public_survey_opinion` WHERE id_survey=' . $survey['id'], 'total_cout', 0);
             $options = DB::fetch_all('SELECT * FROM `public_survey_opinion` WHERE id_survey=' . $survey['id']);
             foreach ($options as $option) {
                 $question .= "+ [ID:{$option['id']}] <b>{$option['option']}</b> <font color=red>({$option['count']}/{$total_cout} lượt chọn)</font><br>";
             }
             $survey["question"] = $question;
             if ($survey['type'] == 0) {
                 $type_send = "Nhiều lựa chọn";
             } else {
                 $type_send = "Một lựa chọn";
             }
             $survey["type_send"] = $type_send;
             $survey["time"] = date("d/m/Y H:i", $survey["time"]);
             $survey["time_m"] = date("d/m/Y H:i", $survey["time_m"]);
             $survey["edit"] = Url::build_current(array('id_survey' => $survey['id'], 'cmd' => 'edit'));
             $survey["delete"] = Url::build_current(array('id_survey' => $survey['id'], 'cmd' => 'delete'));
         }
     }
     $display->add('surveys', $surveys);
     $display->add('url_addnew', Url::build('admin_survey', array('cmd' => 'add')));
     $display->output('ListSurvey');
 }
Example #8
0
 /**
  * Home Page
  *
  * @return Template
  * @author Dan Cox
  */
 public function home()
 {
     /** 
      * Get all available schedules to send here.
      */
     $schedules = DB::count('Schedule');
     return Template::make('pages/home', ['schedules' => $schedules]);
 }
Example #9
0
 static function isNotice($user_id, $type, $id)
 {
     if ($user_id && $id) {
         $condition = 'user_id = ' . (int) $user_id . ' AND type = ' . (int) $type . ' AND id_item = ' . (int) $id;
         return DB::count('bad_content', $condition);
     }
     return 0;
 }
Example #10
0
 function update_last_commented_at()
 {
     # return if self.do_not_bump_post
     $comment_count = DB::count("comments WHERE post_id = ?", $this->post_id);
     if ($comment_count <= CONFIG::comment_threshold) {
         DB::update("posts SET last_commented_at = (SELECT created_at FROM comments WHERE post_id = :post_id ORDER BY created_at DESC LIMIT 1) WHERE posts.id = :post_id", array('post_id' => $this->post_id));
     }
 }
Example #11
0
 public function isAdmin()
 {
     \DB::$user = '******';
     \DB::$password = '******';
     \DB::$dbName = 'Euro2016';
     $row = \DB::queryFirstRow("select * from userroles where userid = %i;", Auth::user()->id);
     if (\DB::count() > 0) {
         return true;
     } else {
         return false;
     }
 }
 function username_exists()
 {
     $db = new DB();
     $db->connect();
     $sql = "select * from registered_users where Username='******'";
     $db->query($sql);
     $count = $db->count();
     if ($count == 0) {
         return 0;
     } else {
         return 1;
     }
 }
Example #13
0
 function check_login()
 {
     $db = new DB();
     $db->connect();
     $sql = "select * from registered_users where Username='******' and Password='******'";
     $db->query($sql);
     $count = $db->count();
     if ($count == 1) {
         return 1;
     } else {
         return 0;
     }
 }
Example #14
0
 function draw()
 {
     global $display;
     $this->beginForm();
     $display->add('name', Url::get('name', ''));
     $max_pos = DB::count("news_categories") + 1;
     $display->add('position_option', AZLib::getOptionNum(1, $max_pos, Url::get('position', $max_pos)));
     $display->add('public', (int) Url::get('public', 1));
     $display->add('keywords', Url::get('keywords', ''));
     $display->add('description', Url::get('description', ''));
     $display->add('msg', $this->showFormErrorMessages(1));
     $display->output("NewsAdminCatsAdd");
     $this->endForm();
 }
Example #15
0
 function test_open()
 {
     // test a bad connection
     $this->assertFalse(DB::open($this->bad_conf));
     $this->assertEquals('could not find driver', DB::error());
     $this->assertEquals(0, DB::count());
     // test a master connection
     $this->assertTrue(DB::open($this->conf));
     $this->assertEquals(1, DB::count());
     // test a second connection
     $this->assertTrue(DB::open($this->conf2));
     $this->assertEquals(2, DB::count());
     unset(DB::$connections['slave_1']);
 }
Example #16
0
 function draw()
 {
     global $display;
     $this->beginForm();
     $display->add('url_add', Url::build_current(array('cmd' => 'add')));
     $current_path = "<a href='" . URL::build('news_list', array('news_catid' => $this->row['id'], 'azname' => AZLib::safe_title($this->row['name']))) . "'>" . $this->row['name'] . "</a>";
     $display->add('current_cat', $current_path);
     $display->add('name', Url::get('name', $this->row['name']));
     $display->add('position_option', AZLib::getOptionNum(1, DB::count("news_categories"), Url::get('position', $this->row['position'])));
     $display->add('public', Url::get('public', $this->row['public'] ? 1 : 2));
     $display->add('keywords', Url::get('keywords', $this->row['keywords']));
     $display->add('description', Url::get('description', $this->row['description']));
     $display->add('msg', $this->showFormErrorMessages(1));
     $display->output("NewsAdminCatsEdit");
     $this->endForm();
 }
function updateSettings($setting, $val, $type = '')
{
    global $server, $user, $pass, $database, $pre, $port, $encoding;
    if (empty($type)) {
        $type = 'admin';
    }
    require_once $_SESSION['settings']['cpassman_dir'] . '/sources/main.functions.php';
    require_once $_SESSION['settings']['cpassman_dir'] . '/sources/SplClassLoader.php';
    // Connect to database
    require_once $_SESSION['settings']['cpassman_dir'] . '/includes/libraries/Database/Meekrodb/db.class.php';
    DB::$host = $server;
    DB::$user = $user;
    DB::$password = $pass;
    DB::$dbName = $database;
    DB::$port = $port;
    DB::$encoding = $encoding;
    DB::$error_handler = 'db_error_handler';
    $link = mysqli_connect($server, $user, $pass, $database, $port);
    $link->set_charset($encoding);
    // Check if setting is already in DB. If NO then insert, if YES then update.
    $data = DB::query("SELECT * FROM " . prefix_table("misc") . "\n        WHERE type = %s AND intitule = %s", $type, $setting);
    $counter = DB::count();
    if ($counter == 0) {
        DB::insert(prefix_table("misc"), array('valeur' => $val, 'type' => $type, 'intitule' => $setting));
        // in case of stats enabled, add the actual time
        if ($setting == 'send_stats') {
            DB::insert(prefix_table("misc"), array('valeur' => time(), 'type' => $type, 'intitule' => $setting . '_time'));
        }
    } else {
        DB::update(prefix_table("misc"), array('valeur' => $val), "type = %s AND intitule = %s", $type, $setting);
        // in case of stats enabled, update the actual time
        if ($setting == 'send_stats') {
            // Check if previous time exists, if not them insert this value in DB
            $data_time = DB::query("SELECT * FROM " . prefix_table("misc") . "\n                WHERE type = %s AND intitule = %s", $type, $setting . '_time');
            $counter = DB::count();
            if ($counter == 0) {
                DB::insert(prefix_table("misc"), array('valeur' => 0, 'type' => $type, 'intitule' => $setting . '_time'));
            } else {
                DB::update(prefix_table("misc"), array('valeur' => 0), "type = %s AND intitule = %s", $type, $setting);
            }
        }
    }
    $_SESSION['settings'][$setting] = $val;
}
Example #18
0
 public static function get_categories($page, $page_size = 10, $order)
 {
     $ret = [];
     $db = new DB([]);
     $db->connect();
     $total = $db->count('msf_article');
     $total_page = 0;
     $total_page = ceil($total / $page_size);
     $start = ($page - 1) * $page_size;
     $limit = $page_size;
     //$page * $page_size - 1;
     $order_tag = explode('~', $order);
     $sql = "select * from msf_article order by `{$order_tag[0]}` {$order_tag[1]} limit {$start}, {$limit}";
     $articles = $db->get_results($sql);
     $sql = "select id, name, alias from msf_category";
     $cates = $db->get_results($sql);
     $cate = [];
     foreach ($cates as $idx => $data) {
         $cate[$data['id']] = [$data['name'], $data['alias']];
     }
     $sql = "select id, name from msf_user";
     $users = $db->get_results($sql);
     $user = [];
     foreach ($users as $idx => $data) {
         $user[$data['id']] = $data['name'];
     }
     foreach ($articles as $key => $article) {
         if (array_key_exists($article['category_id'], $cate)) {
             $articles[$key]['category_name'] = $cate[$article['category_id']][0];
             $articles[$key]['category_alias'] = $cate[$article['category_id']][1];
         }
     }
     foreach ($articles as $key => $value) {
         if (array_key_exists($value['create_user'], $user)) {
             $articles[$key]['create_user'] = $user[$value['create_user']];
         }
     }
     $ret = ['page_info' => ['total_page' => $total_page, 'cur_page' => $page, 'page_size' => $page_size], 'articles' => $articles];
     return $ret;
 }
Example #19
0
 public static function create_article()
 {
     $title = Request::post('title');
     $alias = Request::post('alias');
     $content = Request::post('content');
     $tags = Request::post('tags');
     $cate_id = Request::post('cate_id');
     //数据有效性检验
     if ($title == '' || $content == '') {
         return "文章标题和内容不能为空。";
     }
     $db = new DB([]);
     $db->connect();
     if ($alias !== '') {
         $cnt = $db->count('msf_article', "alias='{$alias}'");
         if ($cnt >= 1) {
             return "已经存在同名的文章别名。";
         }
     }
     $sql = "insert into msf_article (title, alias, content, tags, category_id, created_at, updated_at)\n                values ('{$title}','{$alias}', '{$content}', '{$tags}', {$cate_id}, NOW(), NOW())";
     $db->query($sql);
     return $db->insert_id();
 }
Example #20
0
 function draw()
 {
     global $display;
     $keyword = Url::get('keyword');
     $display->add('keyword', $keyword);
     $display->add('export_link', Url::build_current(array('cmd' => 'export')));
     $where = '1';
     if ($keyword != '') {
         $where .= ' AND email LIKE "%' . $keyword . '%"';
     }
     $total_item = DB::count('news_letter_email', $where);
     $limit = '';
     $item_per_page = 40;
     $page_no = (int) Url::get('page_no');
     $pagging = AZPagging::paging_list($limit, $total_item, $item_per_page, 10);
     $re = DB::query('SELECT * FROM news_letter_email WHERE ' . $where . ' ORDER BY id ' . $limit);
     $news_letter_emails = array();
     $i = 0;
     if ($page_no <= 0) {
         $page_no = 1;
     }
     if ($re) {
         while ($item = mysql_fetch_assoc($re)) {
             $item['time_add'] = date('H:i', $item['time_add']) . ' ngày ' . date('d/m/Y', $item['time_add']) . '<br />Cách đây ' . AZLib::duration_time($item['time_add']);
             $item['delete'] = AZLib::buttonDel(Url::build_current(array('cmd' => 'delete', 'id' => $item['id'])), 'style/images/admin/delete.gif', 'Loại bỏ Email này khỏi danh sách!');
             $i++;
             $item['i'] = $i + ($page_no - 1) * $item_per_page;
             $news_letter_emails[$item['id']] = $item;
         }
     }
     $display->add('pagging', $pagging);
     $display->add('news_letter_emails', $news_letter_emails);
     $display->add('count', $total_item);
     $this->beginForm();
     $display->output("NewsLetterAdmin");
     $this->endForm();
 }
Example #21
0
 public function __add_to_cart($item_id, $sides)
 {
     $item = DB::queryOneRow("SELECT * FROM menu_items WHERE id=%s", $item_id);
     $existing_uid = DB::queryOneRow("SELECT uid FROM carts WHERE user_id=%s AND cart_type=%s AND active=%d", $this->data["uid"], $item["service_id"], 1);
     if (DB::count() != 0) {
         $uid = $existing_uid["uid"];
     } else {
         $uid = GUID();
     }
     DB::query("UPDATE carts SET quantity=quantity+1 WHERE item_id=%s AND user_id=%s AND cart_type=%s AND active=%d", $item_id, $this->data["uid"], $item["service_id"], 1);
     if (DB::affectedRows() == 0) {
         DB::insert("carts", array("uid" => $uid, "cart_type" => $item["service_id"], "item_id" => $item_id, "user_id" => $this->data["uid"]));
     }
     if (count($sides) > 0) {
         foreach ($sides as $sk => $sv) {
             DB::query("UPDATE cart_sides SET quantity=quantity+1 WHERE cart_entry_uid=%s AND side_id=%s", $uid, $sv);
             if (DB::affectedRows() == 0) {
                 DB::insert("cart_sides", array("cart_entry_uid" => $uid, "side_id" => $sv));
             }
         }
     }
     return $this->get_cart($item["category_id"]);
     //        DB::sqleval("NOW()")
 }
 $texte .= '</tr></thead><tbody>';
 //Display each folder with associated rights by role
 $i = 0;
 foreach ($tree as $node) {
     if (in_array($node->id, $_SESSION['groupes_visibles']) && !in_array($node->id, $_SESSION['personal_visible_groups'])) {
         $ident = "";
         for ($a = 1; $a < $node->nlevel; $a++) {
             $ident .= "&#8212;";
         }
         //display 1st cell of the line
         $texte .= '<tr><td style=\'font-size:10px; font-family:arial;\' title=\'ID=' . $node->id . '\'>' . $ident . " " . $node->title . '</td>';
         foreach ($arrRoles as $role) {
             //check if this role has access or not
             // if not then color is red; if yes then color is green
             $role_detail = DB::queryfirstrow("SELECT * FROM " . prefix_table("roles_values") . " WHERE folder_id = %i AND role_id = %i", $node->id, $role);
             if (DB::count() > 0) {
                 if ($role_detail['type'] == "W") {
                     $couleur = '#008000';
                     $allowed = "W";
                     $title = $LANG['write'];
                     $label = '<i class="fa fa-indent"></i>&nbsp;<i class="fa fa-edit"></i>&nbsp;<i class="fa fa-eraser"></i>';
                 } elseif ($role_detail['type'] == "ND") {
                     $couleur = '#4E45F7';
                     $allowed = "ND";
                     $title = $LANG['no_delete'];
                     $label = '<i class="fa fa-indent"></i>&nbsp;<i class="fa fa-edit"></i>';
                 } elseif ($role_detail['type'] == "NE") {
                     $couleur = '#4E45F7';
                     $allowed = "NE";
                     $title = $LANG['no_edit'];
                     $label = '<i class="fa fa-indent"></i>&nbsp;<i class="fa fa-eraser"></i>';
} elseif (isset($_GET['action']) && $_GET['action'] == "failed_auth") {
    //Columns name
    $aColumns = array('l.date', 'l.label', 'l.qui');
    // Filtering
    $sWhere = " WHERE l.type = 'failed_auth'";
    if ($_GET['sSearch'] != "") {
        $sWhere .= " AND (";
        for ($i = 0; $i < count($aColumns); $i++) {
            $sWhere .= $aColumns[$i] . " LIKE %ss_" . $i . " OR ";
        }
        $sWhere = substr_replace($sWhere, "", -3) . ") ";
    }
    DB::query("SELECT l.date as auth_date, l.label as label, l.qui as who\n        FROM " . $pre . "log_system as l" . $sWhere, array('0' => filter_var($_GET['sSearch'], FILTER_SANITIZE_STRING), '1' => filter_var($_GET['sSearch'], FILTER_SANITIZE_STRING), '2' => filter_var($_GET['sSearch'], FILTER_SANITIZE_STRING)));
    $iTotal = DB::count();
    $rows = DB::query("SELECT l.date as auth_date, l.label as label, l.qui as who\n        FROM " . $pre . "log_system as l\n        {$sWhere}\n        {$sOrder}\n        {$sLimit}", array('0' => filter_var($_GET['sSearch'], FILTER_SANITIZE_STRING), '1' => filter_var($_GET['sSearch'], FILTER_SANITIZE_STRING), '2' => filter_var($_GET['sSearch'], FILTER_SANITIZE_STRING)));
    $iFilteredTotal = DB::count();
    // Output
    if ($iTotal == "") {
        $iTotal = 0;
    }
    $sOutput = '{';
    $sOutput .= '"sEcho": ' . intval($_GET['sEcho']) . ', ';
    $sOutput .= '"iTotalRecords": ' . $iTotal . ', ';
    $sOutput .= '"iTotalDisplayRecords": ' . $iTotal . ', ';
    $sOutput .= '"aaData": ';
    if ($iFilteredTotal > 0) {
        $sOutput .= '[';
    }
    foreach ($rows as $record) {
        $sOutput .= "[";
        //col1
Example #24
0
<?php

include "DB.php";
# json.php
$db = new DB("root", "110992", "localhost", "todo");
$rows = [];
$result = [];
$num_rows = 0;
if (isset($_GET['id'])) {
    $result = $db->find('tasks', ['id' => $_GET['id']]);
    $num_rows = $db->count();
} else {
    $result = $db->findAll('tasks');
    $num_rows = $db->count();
}
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json; charset=utf-8');
//$db->pretty();
echo $db->toJson();
Example #25
0
                       }*/
                     // store
                     DB::insert(prefix_table("export"), array('id' => $record['id'], 'description' => addslashes($record['description']), 'label' => addslashes($record['label']), 'pw' => stripslashes($pw), 'login' => $record['login'], 'path' => $path));
                 }
             }
             $id_managed = $record['id'];
             $folder_title = $record['folder_title'];
         }
     }
     //}
     echo '[{}]';
     break;
 case "finalize_export_pdf":
     // query
     $rows = DB::query("SELECT * FROM " . prefix_table("export"));
     $counter = DB::count();
     if ($counter > 0) {
         // print
         //Some variables
         $table_full_width = 190;
         $table_col_width = array(45, 40, 45, 60);
         $table = array('label', 'login', 'pw', 'description');
         $prev_path = "";
         //Prepare the PDF file
         include $_SESSION['settings']['cpassman_dir'] . '/includes/libraries/Pdf/Tfpdf/fpdf.php';
         $pdf = new FPDF_Protection();
         $pdf->SetProtection(array('print'), $_POST['pdf_password']);
         //Add font for regular text
         $pdf->AddFont('DejaVu', '', 'DejaVuSansCondensed.ttf', true);
         //Add monospace font for passwords
         $pdf->AddFont('LiberationMono', '');
Example #26
0
function identifyUser($sentData)
{
    global $debugLdap, $debugDuo, $k;
    include $_SESSION['settings']['cpassman_dir'] . '/includes/settings.php';
    header("Content-type: text/html; charset=utf-8");
    error_reporting(E_ERROR);
    require_once $_SESSION['settings']['cpassman_dir'] . '/sources/main.functions.php';
    require_once $_SESSION['settings']['cpassman_dir'] . '/sources/SplClassLoader.php';
    if ($debugDuo == 1) {
        $dbgDuo = fopen($_SESSION['settings']['path_to_files_folder'] . "/duo.debug.txt", "a");
    }
    /*
    if (empty($sentData) && isset($_COOKIE['TeamPassC'])) {
    	$sentData = prepareExchangedData($_COOKIE['TeamPassC'], "encode");
    	setcookie('TeamPassC', "", time()-3600);
    }
    */
    if ($debugDuo == 1) {
        fputs($dbgDuo, "Content of data sent '" . $sentData . "'\n");
    }
    // connect to the server
    require_once $_SESSION['settings']['cpassman_dir'] . '/includes/libraries/Database/Meekrodb/db.class.php';
    DB::$host = $server;
    DB::$user = $user;
    DB::$password = $pass;
    DB::$dbName = $database;
    DB::$port = $port;
    DB::$encoding = $encoding;
    DB::$error_handler = 'db_error_handler';
    $link = mysqli_connect($server, $user, $pass, $database, $port);
    $link->set_charset($encoding);
    //Load AES
    $aes = new SplClassLoader('Encryption\\Crypt', '../includes/libraries');
    $aes->register();
    // load passwordLib library
    $pwdlib = new SplClassLoader('PasswordLib', '../includes/libraries');
    $pwdlib->register();
    $pwdlib = new PasswordLib\PasswordLib();
    // User's language loading
    $k['langage'] = @$_SESSION['user_language'];
    require_once $_SESSION['settings']['cpassman_dir'] . '/includes/language/' . $_SESSION['user_language'] . '.php';
    // decrypt and retreive data in JSON format
    $dataReceived = prepareExchangedData($sentData, "decode");
    // Prepare variables
    $passwordClear = htmlspecialchars_decode($dataReceived['pw']);
    $passwordOldEncryption = encryptOld(htmlspecialchars_decode($dataReceived['pw']));
    $username = htmlspecialchars_decode($dataReceived['login']);
    $logError = "";
    if ($debugDuo == 1) {
        fputs($dbgDuo, "Starting authentication of '" . $username . "'\n");
    }
    // GET SALT KEY LENGTH
    if (strlen(SALT) > 32) {
        $_SESSION['error']['salt'] = true;
    }
    $_SESSION['user_language'] = $k['langage'];
    $ldapConnection = false;
    /* LDAP connection */
    if ($debugLdap == 1) {
        // create temp file
        $dbgLdap = fopen($_SESSION['settings']['path_to_files_folder'] . "/ldap.debug.txt", "w");
        fputs($dbgLdap, "Get all LDAP params : \n" . 'mode : ' . $_SESSION['settings']['ldap_mode'] . "\n" . 'type : ' . $_SESSION['settings']['ldap_type'] . "\n" . 'base_dn : ' . $_SESSION['settings']['ldap_domain_dn'] . "\n" . 'search_base : ' . $_SESSION['settings']['ldap_search_base'] . "\n" . 'bind_dn : ' . $_SESSION['settings']['ldap_bind_dn'] . "\n" . 'bind_passwd : ' . $_SESSION['settings']['ldap_bind_passwd'] . "\n" . 'user_attribute : ' . $_SESSION['settings']['ldap_user_attribute'] . "\n" . 'account_suffix : ' . $_SESSION['settings']['ldap_suffix'] . "\n" . 'domain_controllers : ' . $_SESSION['settings']['ldap_domain_controler'] . "\n" . 'use_ssl : ' . $_SESSION['settings']['ldap_ssl'] . "\n" . 'use_tls : ' . $_SESSION['settings']['ldap_tls'] . "\n*********\n\n");
    }
    if ($debugDuo == 1) {
        fputs($dbgDuo, "LDAP status: " . $_SESSION['settings']['ldap_mode'] . "\n");
    }
    if (isset($_SESSION['settings']['ldap_mode']) && $_SESSION['settings']['ldap_mode'] == 1 && $username != "admin") {
        //Multiple Domain Names
        if (strpos(html_entity_decode($username), '\\') == true) {
            $ldap_suffix = "@" . substr(html_entity_decode($username), 0, strpos(html_entity_decode($username), '\\'));
            $username = substr(html_entity_decode($username), strpos(html_entity_decode($username), '\\') + 1);
        }
        if ($_SESSION['settings']['ldap_type'] == 'posix-search') {
            $ldapconn = ldap_connect($_SESSION['settings']['ldap_domain_controler']);
            if ($debugLdap == 1) {
                fputs($dbgLdap, "LDAP connection : " . ($ldapconn ? "Connected" : "Failed") . "\n");
            }
            ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
            if ($ldapconn) {
                $ldapbind = ldap_bind($ldapconn, $_SESSION['settings']['ldap_bind_dn'], $_SESSION['settings']['ldap_bind_passwd']);
                if ($debugLdap == 1) {
                    fputs($dbgLdap, "LDAP bind : " . ($ldapbind ? "Bound" : "Failed") . "\n");
                }
                if ($ldapbind) {
                    $filter = "(&(" . $_SESSION['settings']['ldap_user_attribute'] . "={$username})(objectClass=posixAccount))";
                    $result = ldap_search($ldapconn, $_SESSION['settings']['ldap_search_base'], $filter, array('dn'));
                    if ($debugLdap == 1) {
                        fputs($dbgLdap, 'Search filter : ' . $filter . "\n" . 'Results : ' . print_r(ldap_get_entries($ldapconn, $result), true) . "\n");
                    }
                    if (ldap_count_entries($ldapconn, $result)) {
                        // try auth
                        $result = ldap_get_entries($ldapconn, $result);
                        $user_dn = $result[0]['dn'];
                        $ldapbind = ldap_bind($ldapconn, $user_dn, $passwordClear);
                        if ($ldapbind) {
                            $ldapConnection = true;
                        } else {
                            $ldapConnection = false;
                        }
                    }
                } else {
                    $ldapConnection = false;
                }
            } else {
                $ldapConnection = false;
            }
        } else {
            if ($debugLdap == 1) {
                fputs($dbgLdap, "Get all ldap params : \n" . 'base_dn : ' . $_SESSION['settings']['ldap_domain_dn'] . "\n" . 'account_suffix : ' . $_SESSION['settings']['ldap_suffix'] . "\n" . 'domain_controllers : ' . $_SESSION['settings']['ldap_domain_controler'] . "\n" . 'use_ssl : ' . $_SESSION['settings']['ldap_ssl'] . "\n" . 'use_tls : ' . $_SESSION['settings']['ldap_tls'] . "\n*********\n\n");
            }
            $adldap = new SplClassLoader('LDAP\\adLDAP', '../includes/libraries');
            $adldap->register();
            // Posix style LDAP handles user searches a bit differently
            if ($_SESSION['settings']['ldap_type'] == 'posix') {
                $ldap_suffix = ',' . $_SESSION['settings']['ldap_suffix'] . ',' . $_SESSION['settings']['ldap_domain_dn'];
            } elseif ($_SESSION['settings']['ldap_type'] == 'windows' and $ldap_suffix == '') {
                //Multiple Domain Names
                $ldap_suffix = $_SESSION['settings']['ldap_suffix'];
            }
            $adldap = new LDAP\adLDAP\adLDAP(array('base_dn' => $_SESSION['settings']['ldap_domain_dn'], 'account_suffix' => $ldap_suffix, 'domain_controllers' => explode(",", $_SESSION['settings']['ldap_domain_controler']), 'use_ssl' => $_SESSION['settings']['ldap_ssl'], 'use_tls' => $_SESSION['settings']['ldap_tls']));
            if ($debugLdap == 1) {
                fputs($dbgLdap, "Create new adldap object : " . $adldap->get_last_error() . "\n\n\n");
                //Debug
            }
            // openLDAP expects an attribute=value pair
            if ($_SESSION['settings']['ldap_type'] == 'posix') {
                $auth_username = $_SESSION['settings']['ldap_user_attribute'] . '=' . $username;
            } else {
                $auth_username = $username;
            }
            // authenticate the user
            if ($adldap->authenticate($auth_username, html_entity_decode($passwordClear))) {
                $ldapConnection = true;
                //update user's password
                $data['pw'] = $pwdlib->createPasswordHash($passwordClear);
                DB::update(prefix_table('users'), array('pw' => $data['pw']), "login=%s", $username);
            } else {
                $ldapConnection = false;
            }
            if ($debugLdap == 1) {
                fputs($dbgLdap, "After authenticate : " . $adldap->get_last_error() . "\n\n\n" . "ldap status : " . $ldapConnection . "\n\n\n");
                //Debug
            }
        }
    } else {
        if (isset($_SESSION['settings']['ldap_mode']) && $_SESSION['settings']['ldap_mode'] == 2) {
            // nothing
        }
    }
    // Check if user exists
    $data = DB::queryFirstRow("SELECT * FROM " . prefix_table("users") . " WHERE login=%s_login", array('login' => $username));
    $counter = DB::count();
    if ($debugDuo == 1) {
        fputs($dbgDuo, "USer exists: " . $counter . "\n");
    }
    // Check PSK
    if (isset($_SESSION['settings']['psk_authentication']) && $_SESSION['settings']['psk_authentication'] == 1 && $data['admin'] != 1) {
        $psk = htmlspecialchars_decode($dataReceived['psk']);
        $pskConfirm = htmlspecialchars_decode($dataReceived['psk_confirm']);
        if (empty($psk)) {
            echo '[{"value" : "psk_required"}]';
            exit;
        } elseif (empty($data['psk'])) {
            if (empty($pskConfirm)) {
                echo '[{"value" : "bad_psk_confirmation"}]';
                exit;
            } else {
                $_SESSION['my_sk'] = $psk;
            }
        } elseif ($pwdlib->verifyPasswordHash($psk, $data['psk']) === true) {
            echo '[{"value" : "bad_psk"}]';
            exit;
        }
    }
    $proceedIdentification = false;
    if ($counter > 0) {
        $proceedIdentification = true;
    } elseif ($counter == 0 && $ldapConnection == true && isset($_SESSION['settings']['ldap_elusers']) && $_SESSION['settings']['ldap_elusers'] == 0) {
        // If LDAP enabled, create user in CPM if doesn't exist
        $data['pw'] = $pwdlib->createPasswordHash($passwordClear);
        // create passwordhash
        DB::insert(prefix_table('users'), array('login' => $username, 'pw' => $data['pw'], 'email' => "", 'admin' => '0', 'gestionnaire' => '0', 'personal_folder' => $_SESSION['settings']['enable_pf_feature'] == "1" ? '1' : '0', 'fonction_id' => '0', 'groupes_interdits' => '0', 'groupes_visibles' => '0', 'last_pw_change' => time(), 'user_language' => $_SESSION['settings']['default_language']));
        $newUserId = DB::insertId();
        // Create personnal folder
        if ($_SESSION['settings']['enable_pf_feature'] == "1") {
            DB::insert(prefix_table("nested_tree"), array('parent_id' => '0', 'title' => $newUserId, 'bloquer_creation' => '0', 'bloquer_modification' => '0', 'personal_folder' => '1'));
        }
        // Get info for user
        //$sql = "SELECT * FROM ".prefix_table("users")." WHERE login = '******'";
        //$row = $db->query($sql);
        $proceedIdentification = true;
    }
    // Check if user exists (and has been created in case of new LDAP user)
    $data = DB::queryFirstRow("SELECT * FROM " . prefix_table("users") . " WHERE login=%s_login", array('login' => $username));
    $counter = DB::count();
    if ($counter == 0) {
        echo '[{"value" : "user_not_exists", "text":""}]';
        exit;
    }
    if ($debugDuo == 1) {
        fputs($dbgDuo, "USer exists (confirm): " . $counter . "\n");
    }
    // check GA code
    if (isset($_SESSION['settings']['2factors_authentication']) && $_SESSION['settings']['2factors_authentication'] == 1 && $username != "admin") {
        if (isset($dataReceived['GACode']) && !empty($dataReceived['GACode'])) {
            include_once $_SESSION['settings']['cpassman_dir'] . "/includes/libraries/Authentication/GoogleAuthenticator/FixedBitNotation.php";
            include_once $_SESSION['settings']['cpassman_dir'] . "/includes/libraries/Authentication/GoogleAuthenticator/GoogleAuthenticator.php";
            $g = new Authentication\GoogleAuthenticator\GoogleAuthenticator();
            if ($g->checkCode($data['ga'], $dataReceived['GACode'])) {
                $proceedIdentification = true;
            } else {
                $proceedIdentification = false;
                $logError = "ga_code_wrong";
            }
        } else {
            $proceedIdentification = false;
            $logError = "ga_code_wrong";
        }
    }
    if ($debugDuo == 1) {
        fputs($dbgDuo, "Proceed with Ident: " . $proceedIdentification . "\n");
    }
    if ($proceedIdentification === true) {
        // User exists in the DB
        //$data = $db->fetchArray($row);
        //v2.1.17 -> change encryption for users password
        if ($passwordOldEncryption == $data['pw'] && !empty($data['pw'])) {
            //update user's password
            $data['pw'] = bCrypt($passwordClear, COST);
            DB::update(prefix_table('users'), array('pw' => $data['pw']), "id=%i", $data['id']);
        }
        if (crypt($passwordClear, $data['pw']) == $data['pw'] && !empty($data['pw'])) {
            //update user's password
            $data['pw'] = $pwdlib->createPasswordHash($passwordClear);
            DB::update(prefix_table('users'), array('pw' => $data['pw']), "id=%i", $data['id']);
        }
        // check the given password
        if ($pwdlib->verifyPasswordHash($passwordClear, $data['pw']) === true) {
            $userPasswordVerified = true;
        } else {
            $userPasswordVerified = false;
        }
        if ($debugDuo == 1) {
            fputs($dbgDuo, "User's password verified: " . $userPasswordVerified . "\n");
        }
        // Can connect if
        // 1- no LDAP mode + user enabled + pw ok
        // 2- LDAP mode + user enabled + ldap connection ok + user is not admin
        // 3-  LDAP mode + user enabled + pw ok + usre is admin
        // This in order to allow admin by default to connect even if LDAP is activated
        if (isset($_SESSION['settings']['ldap_mode']) && $_SESSION['settings']['ldap_mode'] == 0 && $userPasswordVerified == true && $data['disabled'] == 0 || isset($_SESSION['settings']['ldap_mode']) && $_SESSION['settings']['ldap_mode'] == 1 && $ldapConnection == true && $data['disabled'] == 0 && $username != "admin" || isset($_SESSION['settings']['ldap_mode']) && $_SESSION['settings']['ldap_mode'] == 2 && $ldapConnection == true && $data['disabled'] == 0 && $username != "admin" || isset($_SESSION['settings']['ldap_mode']) && $_SESSION['settings']['ldap_mode'] == 1 && $username == "admin" && $userPasswordVerified == true && $data['disabled'] == 0) {
            $_SESSION['autoriser'] = true;
            // Generate a ramdom ID
            $key = $pwdlib->getRandomToken(50);
            if ($debugDuo == 1) {
                fputs($dbgDuo, "User's token: " . $key . "\n");
            }
            // Log into DB the user's connection
            if (isset($_SESSION['settings']['log_connections']) && $_SESSION['settings']['log_connections'] == 1) {
                logEvents('user_connection', 'connection', $data['id']);
            }
            // Save account in SESSION
            $_SESSION['login'] = stripslashes($username);
            $_SESSION['name'] = stripslashes($data['name']);
            $_SESSION['lastname'] = stripslashes($data['lastname']);
            $_SESSION['user_id'] = $data['id'];
            $_SESSION['user_admin'] = $data['admin'];
            $_SESSION['user_manager'] = $data['gestionnaire'];
            $_SESSION['user_read_only'] = $data['read_only'];
            $_SESSION['last_pw_change'] = $data['last_pw_change'];
            $_SESSION['last_pw'] = $data['last_pw'];
            $_SESSION['can_create_root_folder'] = $data['can_create_root_folder'];
            $_SESSION['key'] = $key;
            $_SESSION['personal_folder'] = $data['personal_folder'];
            $_SESSION['user_language'] = $data['user_language'];
            $_SESSION['user_email'] = $data['email'];
            $_SESSION['user_ga'] = $data['ga'];
            $_SESSION['user_avatar'] = $data['avatar'];
            $_SESSION['user_avatar_thumb'] = $data['avatar_thumb'];
            $_SESSION['user_upgrade_needed'] = $data['upgrade_needed'];
            // manage session expiration
            $serverTime = time();
            if ($dataReceived['TimezoneOffset'] > 0) {
                $userTime = $serverTime + $dataReceived['TimezoneOffset'];
            } else {
                $userTime = $serverTime;
            }
            $_SESSION['fin_session'] = $userTime + $dataReceived['duree_session'] * 60;
            /* If this option is set user password MD5 is used as personal SALTKey */
            if (isset($_SESSION['settings']['use_md5_password_as_salt']) && $_SESSION['settings']['use_md5_password_as_salt'] == 1) {
                $_SESSION['my_sk'] = md5($passwordClear);
                setcookie("TeamPass_PFSK_" . md5($_SESSION['user_id']), encrypt($_SESSION['my_sk'], ""), time() + 60 * 60 * 24 * $_SESSION['settings']['personal_saltkey_cookie_duration'], '/');
            }
            @syslog(LOG_WARNING, "User logged in - " . $_SESSION['user_id'] . " - " . date("Y/m/d H:i:s") . " {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']})");
            if (empty($data['last_connexion'])) {
                $_SESSION['derniere_connexion'] = time();
            } else {
                $_SESSION['derniere_connexion'] = $data['last_connexion'];
            }
            if (!empty($data['latest_items'])) {
                $_SESSION['latest_items'] = explode(';', $data['latest_items']);
            } else {
                $_SESSION['latest_items'] = array();
            }
            if (!empty($data['favourites'])) {
                $_SESSION['favourites'] = explode(';', $data['favourites']);
            } else {
                $_SESSION['favourites'] = array();
            }
            if (!empty($data['groupes_visibles'])) {
                $_SESSION['groupes_visibles'] = @implode(';', $data['groupes_visibles']);
            } else {
                $_SESSION['groupes_visibles'] = array();
            }
            if (!empty($data['groupes_interdits'])) {
                $_SESSION['groupes_interdits'] = @implode(';', $data['groupes_interdits']);
            } else {
                $_SESSION['groupes_interdits'] = array();
            }
            // User's roles
            $_SESSION['fonction_id'] = $data['fonction_id'];
            $_SESSION['user_roles'] = explode(";", $data['fonction_id']);
            // build array of roles
            $_SESSION['user_pw_complexity'] = 0;
            $_SESSION['arr_roles'] = array();
            foreach (array_filter(explode(';', $_SESSION['fonction_id'])) as $role) {
                $resRoles = DB::queryFirstRow("SELECT title, complexity FROM " . prefix_table("roles_title") . " WHERE id=%i", $role);
                $_SESSION['arr_roles'][$role] = array('id' => $role, 'title' => $resRoles['title']);
                // get highest complexity
                if ($_SESSION['user_pw_complexity'] < $resRoles['complexity']) {
                    $_SESSION['user_pw_complexity'] = $resRoles['complexity'];
                }
            }
            // build complete array of roles
            $_SESSION['arr_roles_full'] = array();
            $rows = DB::query("SELECT id, title FROM " . prefix_table("roles_title") . " ORDER BY title ASC");
            foreach ($rows as $record) {
                $_SESSION['arr_roles_full'][$record['id']] = array('id' => $record['id'], 'title' => $record['title']);
            }
            // Set some settings
            $_SESSION['user']['find_cookie'] = false;
            $_SESSION['settings']['update_needed'] = "";
            // Update table
            DB::update(prefix_table('users'), array('key_tempo' => $_SESSION['key'], 'last_connexion' => time(), 'timestamp' => time(), 'disabled' => 0, 'no_bad_attempts' => 0, 'session_end' => $_SESSION['fin_session'], 'psk' => $pwdlib->createPasswordHash(htmlspecialchars_decode($psk))), "id=%i", $data['id']);
            if ($debugDuo == 1) {
                fputs($dbgDuo, "Preparing to identify the user rights\n");
            }
            // Get user's rights
            identifyUserRights($data['groupes_visibles'], $_SESSION['groupes_interdits'], $data['admin'], $data['fonction_id'], false);
            // Get some more elements
            $_SESSION['screenHeight'] = $dataReceived['screenHeight'];
            // Get last seen items
            $_SESSION['latest_items_tab'][] = "";
            foreach ($_SESSION['latest_items'] as $item) {
                if (!empty($item)) {
                    $data = DB::queryFirstRow("SELECT id,label,id_tree FROM " . prefix_table("items") . " WHERE id=%i", $item);
                    $_SESSION['latest_items_tab'][$item] = array('id' => $item, 'label' => $data['label'], 'url' => 'index.php?page=items&amp;group=' . $data['id_tree'] . '&amp;id=' . $item);
                }
            }
            // send back the random key
            $return = $dataReceived['randomstring'];
            // Send email
            if (isset($_SESSION['settings']['enable_send_email_on_user_login']) && $_SESSION['settings']['enable_send_email_on_user_login'] == 1 && $_SESSION['user_admin'] != 1) {
                // get all Admin users
                $receivers = "";
                $rows = DB::query("SELECT email FROM " . prefix_table("users") . " WHERE admin = %i", 1);
                foreach ($rows as $record) {
                    if (empty($receivers)) {
                        $receivers = $record['email'];
                    } else {
                        $receivers = "," . $record['email'];
                    }
                }
                // Add email to table
                DB::insert(prefix_table("emails"), array('timestamp' => time(), 'subject' => $LANG['email_subject_on_user_login'], 'body' => str_replace(array('#tp_user#', '#tp_date#', '#tp_time#'), array(" " . $_SESSION['login'], date($_SESSION['settings']['date_format'], $_SESSION['derniere_connexion']), date($_SESSION['settings']['time_format'], $_SESSION['derniere_connexion'])), $LANG['email_body_on_user_login']), 'receivers' => $receivers, 'status' => "not sent"));
            }
        } elseif ($data['disabled'] == 1) {
            // User and password is okay but account is locked
            $return = "user_is_locked";
        } else {
            // User exists in the DB but Password is false
            // check if user is locked
            $userIsLocked = 0;
            $nbAttempts = intval($data['no_bad_attempts'] + 1);
            if ($_SESSION['settings']['nb_bad_authentication'] > 0 && intval($_SESSION['settings']['nb_bad_authentication']) < $nbAttempts) {
                $userIsLocked = 1;
                // log it
                if (isset($_SESSION['settings']['log_connections']) && $_SESSION['settings']['log_connections'] == 1) {
                    logEvents('user_locked', 'connection', $data['id']);
                }
            }
            DB::update(prefix_table('users'), array('key_tempo' => $_SESSION['key'], 'last_connexion' => time(), 'disabled' => $userIsLocked, 'no_bad_attempts' => $nbAttempts), "id=%i", $data['id']);
            // What return shoulb we do
            if ($userIsLocked == 1) {
                $return = "user_is_locked";
            } elseif ($_SESSION['settings']['nb_bad_authentication'] == 0) {
                $return = "false";
            } else {
                $return = $nbAttempts;
            }
        }
    } else {
        $return = "false";
    }
    if ($debugDuo == 1) {
        fputs($dbgDuo, "\n\n----\n" . "Identified : " . $return . "\n");
    }
    echo '[{"value" : "' . $return . '", "user_admin":"', isset($_SESSION['user_admin']) ? $_SESSION['user_admin'] : "", '", "initial_url" : "' . @$_SESSION['initial_url'] . '",
            "error" : "' . $logError . '"}]';
    $_SESSION['initial_url'] = "";
    if ($_SESSION['settings']['cpassman_dir'] == "..") {
        $_SESSION['settings']['cpassman_dir'] = ".";
    }
}
Example #27
0
							<thead>
								<tr>
									<th>Status</th>
									<th>Version</th>
									<th>IP Address</th>
									<th>Target Name</th>
									<th width='110'>Callback Period</th>
									<th>Last Callback</th>
									<th width='180'>Actions</th>
								</tr>
							</thead>

	<?php 
    foreach ($result as $row) {
        $result2 = DB::query("SELECT * FROM tasks WHERE id = %s AND status != %s", $row['id'], 2);
        $count = DB::count();
        //HIGHLIGHT THE ROW/IMPLANT IF TASKS ARE QUEUED UP
        if ($count != 0) {
            if ($result2[0]['status'] == 0) {
                print "<tr data-target='" . $row['id'] . "' class='bgrow'>";
            } else {
                print "<tr data-target='" . $row['id'] . "' style='background-color: #F18A7E'>";
            }
        } else {
            print "<tr data-target='" . $row['id'] . "'>";
        }
        ?>
								<td>
								<?php 
        //PRINT ICON FOR SYSTEM OR NOT
        if ($row['privileges'] == 1) {
Example #28
0
 function remove_save_img()
 {
     if (!User::is_login()) {
         echo "not_login";
         exit;
     }
     $id = (int) Url::get('id', 0);
     //check ton tai
     if (DB::count('img_save', ' img_id = ' . $id . ' AND user_id = ' . User::id())) {
         DB::delete('img_save', ' img_id = ' . $id . ' AND user_id = ' . User::id());
         if (isset($_SESSION['wish_item'])) {
             $_SESSION['wish_item']--;
             if ($_SESSION['wish_item'] < 0) {
                 $_SESSION['wish_item'] = 0;
             }
         } else {
             $_SESSION['wish_item'] = DB::count("img_save", "user_id = " . User::id());
         }
         echo 'success';
         if (isset($_COOKIE['user_save_img_list_items'])) {
             $arr_img_ids_temp = explode(',', $_COOKIE['user_save_img_list_items']);
             $tempArr = array();
             foreach ($arr_img_ids_temp as $value) {
                 if ($value != $id) {
                     $tempArr[] = $value;
                 }
             }
             $ids = implode(',', $tempArr);
             EClassApi::my_setcookie('user_save_img_list_items', $ids);
             $_SESSION['load_wish_list'] = true;
         }
     } else {
         echo 'unsuccess';
     }
     exit;
 }
Example #29
0
DB::$host = $server;
DB::$user = $user;
DB::$password = $pass;
DB::$dbName = $database;
DB::$port = $port;
DB::$encoding = $encoding;
DB::$error_handler = 'db_error_handler';
$link = mysqli_connect($server, $user, $pass, $database, $port);
$link->set_charset($encoding);
// get some numbers
DB::query("SELECT id FROM " . $pre . "items");
$counter_items = DB::count();
DB::query("SELECT id FROM " . $pre . "users");
$counter_users = DB::count();
DB::query("SELECT id FROM " . $pre . "nested_tree");
$counter_folders = DB::count();
?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
        <title>Teampass - Tools</title>
        <?php 
echo '
        <link rel="stylesheet" href="../includes/js/jquery-ui/jquery-ui.min.css" type="text/css" />
        <script type="text/javascript" src="../includes/js/functions.js"></script>
        <script type="text/javascript" src="../includes/js/jquery-ui/external/jquery/jquery.js"></script>
        <script type="text/javascript" src="../includes/js/jquery-ui/jquery-ui.min.js"></script>
        <script type="text/javascript" src="../includes/js/jcenter/jquery.center.js"></script>';
?>
        <script type="application/javascript">
            function launchTool(number)
Example #30
0
function rest_get()
{
    $_SESSION['user_id'] = "'api'";
    if (!@count($GLOBALS['request']) == 0) {
        $request_uri = $GLOBALS['_SERVER']['REQUEST_URI'];
        preg_match('/\\/api(\\/index.php|)\\/(.*)\\?apikey=(.*)/', $request_uri, $matches);
        if (count($matches) == 0) {
            rest_error('REQUEST_SENT_NOT_UNDERSTANDABLE');
        }
        $GLOBALS['request'] = explode('/', $matches[2]);
    }
    if (apikey_checker($GLOBALS['apikey'])) {
        global $server, $user, $pass, $database, $pre, $link;
        teampass_connect();
        $rand_key = teampass_get_randkey();
        $category_query = "";
        if ($GLOBALS['request'][0] == "read") {
            if ($GLOBALS['request'][1] == "category") {
                // get ids
                if (strpos($GLOBALS['request'][2], ",") > 0) {
                    $condition = "id_tree IN %ls";
                    $condition_value = explode(',', $GLOBALS['request'][2]);
                } else {
                    $condition = "id_tree = %s";
                    $condition_value = $GLOBALS['request'][2];
                }
                DB::debugMode(false);
                /* load folders */
                $response = DB::query("SELECT id,parent_id,title,nleft,nright,nlevel FROM " . prefix_table("nested_tree") . " WHERE parent_id=%i ORDER BY `title` ASC", $GLOBALS['request'][2]);
                $rows = array();
                $i = 0;
                foreach ($response as $row) {
                    /*$json['folders'][$i]['id'] = $row['id'];
                      $json['folders'][$i]['parent_id'] = $row['parent_id'];
                      $json['folders'][$i]['title'] = $row['title'];
                      $json['folders'][$i]['nleft'] = $row['nleft'];
                      $json['folders'][$i]['nright'] = $row['nright'];
                      $json['folders'][$i]['nlevel'] = $row['nlevel'];*/
                    $i++;
                    $response = DB::query("SELECT id,label,login,pw FROM " . prefix_table("items") . " WHERE id_tree=%i", $row['id']);
                    foreach ($response as $data) {
                        // get ITEM random key
                        $data_tmp = DB::queryFirstRow("SELECT rand_key FROM " . prefix_table("keys") . " WHERE id = %i", $data['id']);
                        // prepare output
                        $id = $data['id'];
                        $json[$id]['label'] = utf8_encode($data['label']);
                        $json[$id]['login'] = utf8_encode($data['login']);
                        $json[$id]['pw'] = teampass_decrypt_pw($data['pw'], SALT, $data_tmp['rand_key']);
                    }
                }
            } elseif ($GLOBALS['request'][1] == "items") {
                // only accepts numeric
                $array_items = explode(',', $GLOBALS['request'][2]);
                $items_list = "";
                foreach ($array_items as $item) {
                    if (!is_numeric($item)) {
                        rest_error('ITEM_MALFORMED');
                    }
                }
                if (count($array_items) > 1 && count($array_items) < 5) {
                    foreach ($array_items as $item) {
                        if (empty($items_list)) {
                            $items_list = $item;
                        } else {
                            $items_list .= "," . $item;
                        }
                    }
                } elseif (count($array_items) == 1) {
                    $items_list = $item;
                } else {
                    rest_error('NO_ITEM');
                }
                $response = DB::query("select id,label,login,pw,id_tree from " . prefix_table("items") . " where id IN %ls", $items_list);
                foreach ($response as $data) {
                    // get ITEM random key
                    $data_tmp = DB::queryFirstRow("SELECT rand_key FROM " . prefix_table("keys") . " WHERE id = %i", $data['id']);
                    // prepare output
                    $id = $data['id'];
                    $json[$id]['label'] = utf8_encode($data['label']);
                    $json[$id]['login'] = utf8_encode($data['login']);
                    $json[$id]['pw'] = teampass_decrypt_pw($data['pw'], SALT, $data_tmp['rand_key']);
                }
            }
            if (isset($json) && $json) {
                echo json_encode($json);
            } else {
                rest_error('EMPTY');
            }
        } elseif ($GLOBALS['request'][0] == "find") {
            if ($GLOBALS['request'][1] == "item") {
                $array_category = explode(';', $GLOBALS['request'][2]);
                $item = $GLOBALS['request'][3];
                foreach ($array_category as $category) {
                    if (!preg_match_all("/^([\\w\\:\\'\\-\\sàáâãäåçèéêëìíîïðòóôõöùúûüýÿ]+)\$/i", $category, $result)) {
                        rest_error('CATEGORY_MALFORMED');
                    }
                }
                if (!preg_match_all("/^([\\w\\:\\'\\-\\sàáâãäåçèéêëìíîïðòóôõöùúûüýÿ]+)\$/i", $item, $result)) {
                    rest_error('ITEM_MALFORMED');
                } elseif (empty($item) || count($array_category) == 0) {
                    rest_error('MALFORMED');
                }
                if (count($array_category) > 1 && count($array_category) < 5) {
                    for ($i = count($array_category); $i > 0; $i--) {
                        $slot = $i - 1;
                        if (!$slot) {
                            $category_query .= "select id from " . prefix_table("nested_tree") . " where title LIKE '" . $array_category[$slot] . "' AND parent_id = 0";
                        } else {
                            $category_query .= "select id from " . prefix_table("nested_tree") . " where title LIKE '" . $array_category[$slot] . "' AND parent_id = (";
                        }
                    }
                    for ($i = 1; $i < count($array_category); $i++) {
                        $category_query .= ")";
                    }
                } elseif (count($array_category) == 1) {
                    $category_query = "select id from " . prefix_table("nested_tree") . " where title LIKE '" . $array_category[0] . "' AND parent_id = 0";
                } else {
                    rest_error('NO_CATEGORY');
                }
                DB::debugMode(false);
                $response = DB::query("select id,label,login,pw,id_tree\n                    from " . prefix_table("items") . "\n                    where id_tree = (%s)\n                    and label LIKE %ss", $category_query, $item);
                foreach ($response as $data) {
                    // get ITEM random key
                    $data_tmp = DB::queryFirstRow("SELECT rand_key FROM " . prefix_table("keys") . " WHERE id = %i", $data['id']);
                    // prepare output
                    $json['id'] = utf8_encode($data['id']);
                    $json['label'] = utf8_encode($data['label']);
                    $json['login'] = utf8_encode($data['login']);
                    $json['pw'] = teampass_decrypt_pw($data['pw'], SALT, $data_tmp['rand_key']);
                    $json['folder_id'] = $data['id_tree'];
                    $json['status'] = utf8_encode("OK");
                }
                if (isset($json) && $json) {
                    echo json_encode($json);
                } else {
                    rest_error('EMPTY');
                }
            }
        } elseif ($GLOBALS['request'][0] == "add") {
            if ($GLOBALS['request'][1] == "item") {
                // get item definition
                $array_item = explode(';', $GLOBALS['request'][2]);
                if (count($array_item) != 9) {
                    rest_error('BADDEFINITION');
                }
                $item_label = $array_item[0];
                $item_pwd = $array_item[1];
                $item_desc = $array_item[2];
                $item_folder_id = $array_item[3];
                $item_login = $array_item[4];
                $item_email = $array_item[5];
                $item_url = $array_item[6];
                $item_tags = $array_item[7];
                $item_anyonecanmodify = $array_item[8];
                // added so one can sent data including the http or https !
                // anyway we have to urlencode this data
                $item_url = urldecode($item_url);
                // same for the email
                $item_email = urldecode($item_email);
                // do some checks
                if (!empty($item_label) && !empty($item_pwd) && !empty($item_folder_id)) {
                    // Check length
                    if (strlen($item_pwd) > 50) {
                        rest_error('BADDEFINITION');
                    }
                    // Check Folder ID
                    DB::query("SELECT * FROM " . prefix_table("nested_tree") . " WHERE id = %i", $item_folder_id);
                    $counter = DB::count();
                    if ($counter == 0) {
                        rest_error('BADDEFINITION');
                    }
                    // check if element doesn't already exist
                    DB::query("SELECT * FROM " . prefix_table("items") . " WHERE label = %s AND inactif = %i", addslashes($item_label), "0");
                    $counter = DB::count();
                    if ($counter != 0) {
                        $itemExists = 1;
                        // prevent the error if the label already exists
                        // so lets just add the time() as a random factor
                        $item_label .= " (" . time() . ")";
                    } else {
                        $itemExists = 0;
                    }
                    if ($itemExists == 0) {
                        // prepare password and generate random key
                        $randomKey = substr(md5(rand() . rand()), 0, 15);
                        $item_pwd = $randomKey . $item_pwd;
                        $item_pwd = encrypt($item_pwd);
                        if (empty($item_pwd)) {
                            rest_error('BADDEFINITION');
                        }
                        // ADD item
                        try {
                            DB::insert(prefix_table("items"), array("label" => $item_label, "description" => $item_desc, "pw" => $item_pwd, "email" => $item_email, "url" => $item_url, "id_tree" => intval($item_folder_id), "login" => $item_login, "inactif" => 0, "restricted_to" => "", "perso" => 0, "anyone_can_modify" => intval($item_anyonecanmodify)));
                            $newID = DB::InsertId();
                            // Store generated key
                            DB::insert(prefix_table("keys"), array("sql_table" => "items", "id" => $newID, "rand_key" => $randomKey));
                            // log
                            DB::insert(prefix_table("log_items"), array("id_item" => $newID, "date" => time(), "id_user" => "9999999", "action" => "at_creation"));
                            // Add tags
                            $tags = explode(' ', $item_tags);
                            foreach ((array) $tags as $tag) {
                                if (!empty($tag)) {
                                    DB::insert(prefix_table("tags"), array("item_id" => $newID, "tag" => strtolower($tag)));
                                }
                            }
                            // Update CACHE table
                            DB::insert(prefix_table("cache"), array("id" => $newID, "label" => $item_label, "description" => $item_desc, "tags" => $item_tags, "id_tree" => $item_folder_id, "perso" => "0", "restricted_to" => "", "login" => $item_login, "folder" => "", "author" => "9999999"));
                            echo '{"status":"item added"}';
                        } catch (PDOException $ex) {
                            echo '<br />' . $ex->getMessage();
                        }
                    } else {
                        rest_error('BADDEFINITION');
                    }
                } else {
                    rest_error('BADDEFINITION');
                }
            }
        } elseif ($GLOBALS['request'][0] == "auth") {
            /*
             ** FOR SECURITY PURPOSE, it is mandatory to use SSL to connect your teampass instance. The user password is not encrypted!
             **
             **
             ** Expected call format: .../api/index.php/auth/<PROTOCOL>/<URL>/<login>/<password>?apikey=<VALID API KEY>
             ** Example: https://127.0.0.1/teampass/api/index.php/auth/http/www.zadig-tge.adp.com/U1/test/76?apikey=chahthait5Aidood6johh6Avufieb6ohpaixain
             ** RESTRICTIONS:
             **              - <PROTOCOL>        ==> http|https|ftp|...
             **              - <URL>             ==> encode URL without protocol (example: http://www.teampass.net becomes www.teampass.net)
             **              - <login>           ==> user's login
             **              - <password>        ==> currently clear password
             **
             ** RETURNED ANSWER:
             **              - format sent back is JSON
             **              - Example: {"<item_id>":{"label":"<pass#1>","login":"******","pw":"<pwd#1>"},"<item_id>":{"label":"<pass#2>","login":"******","pw":"<pwd#2>"}}
             **
             */
            // get user credentials
            if (isset($GLOBALS['request'][3]) && isset($GLOBALS['request'][4])) {
                // get url
                if (isset($GLOBALS['request'][1]) && isset($GLOBALS['request'][2])) {
                    // is user granted?
                    $user = DB::queryFirstRow("SELECT `id`, `pw`, `groupes_interdits`, `groupes_visibles`, `fonction_id` FROM " . $pre . "users WHERE login = %s", $GLOBALS['request'][3]);
                    if (crypt($GLOBALS['request'][4], $user['pw']) == $user['pw']) {
                        // define the restriction of "id_tree" of this user
                        $userDef = DB::queryOneColumn('folder_id', "SELECT DISTINCT folder_id \n                            FROM " . prefix_table("roles_values") . "\n                            WHERE type IN ('R', 'W') ", empty($user['groupes_interdits']) ? "" : "\n                            AND folder_id NOT IN (" . str_replace(";", ",", $user['groupes_interdits']) . ")", " \n                            AND role_id IN %ls \n                            GROUP BY folder_id", explode(";", $user['groupes_interdits']));
                        // complete with "groupes_visibles"
                        foreach (explode(";", $user['groupes_visibles']) as $v) {
                            array_push($userDef, $v);
                        }
                        // find the item associated to the url
                        $response = DB::query("SELECT id, label, login, pw, id_tree, restricted_to\n                            FROM " . prefix_table("items") . " \n                            WHERE url LIKE %s\n                            AND id_tree IN (" . implode(",", $userDef) . ")\n                            ORDER BY id DESC", $GLOBALS['request'][1] . "://" . urldecode($GLOBALS['request'][2] . '%'));
                        $counter = DB::count();
                        if ($counter > 0) {
                            $json = "";
                            foreach ($response as $data) {
                                // check if item visible
                                if (empty($data['restricted_to']) || $data['restricted_to'] != "" && in_array($user['id'], explode(";", $data['restricted_to']))) {
                                    // get ITEM random key
                                    $data_tmp = DB::queryFirstRow("SELECT rand_key FROM " . prefix_table("keys") . " WHERE id = %i", $data['id']);
                                    // prepare export
                                    $json[$data['id']]['label'] = utf8_encode($data['label']);
                                    $json[$data['id']]['login'] = utf8_encode($data['login']);
                                    $json[$data['id']]['pw'] = teampass_decrypt_pw($data['pw'], SALT, $data_tmp['rand_key']);
                                }
                            }
                            // prepare answer. If no access then inform
                            if (empty($json)) {
                                rest_error('AUTH_NO_DATA');
                            } else {
                                echo json_encode($json);
                            }
                        } else {
                            rest_error('AUTH_NO_DATA');
                        }
                    } else {
                        rest_error('AUTH_NOT_GRANTED');
                    }
                } else {
                    rest_error('AUTH_NO_URL');
                }
            } else {
                rest_error('AUTH_NO_IDENTIFIER');
            }
        } else {
            rest_error('METHOD');
        }
    }
}