function runGeoLookup() { global $GEOIP_REGION_NAME; $geoip = Net_GeoIP::getInstance(BT_ROOT . "/bt-config/GeoLiteCity.dat"); $location = null; try { $location = $geoip->lookupLocation($_SERVER['REMOTE_ADDR']); } catch (Exception $e) { //ignore it, seriously dude, friggin ignore it. } if ($location) { $country = DB::quote($location->countryCode); $country_full = DB::quote($location->countryName); $state = DB::quote($location->region); $state_full = @DB::quote($GEOIP_REGION_NAME[strtoupper($location->countryCode)][strtoupper($location->region)]); $city = DB::quote($location->city); $timezone = @DB::quote(get_time_zone($location->countryCode, $location->region)); $postalcode = DB::quote($location->postalCode); } else { return 0; } $sql = "select location_id from bt_g_geo_locations where country='{$country}' and state='{$state}' and city='{$city}'"; $id = DB::getVar($sql); if (!$id) { $sql = "insert into bt_g_geo_locations values ('','{$country}','{$country_full}','{$state}','{$state_full}','{$city}','{$timezone}','{$postalcode}')"; DB::query($sql); $id = DB::insertId(); } return $id; }
function test_3_more_inserts() { DB::insert('`accounts`', array('username' => 'Bart', 'password' => 'hello', 'age' => 15, 'height' => 10.371)); $dbname = DB::$dbName; DB::insert("`{$dbname}`.`accounts`", array('username' => 'Charlie\'s Friend', 'password' => 'goodbye', 'age' => 30, 'height' => 155.23, 'favorite_word' => null)); $this->assert(DB::insertId() === 3); $counter = DB::queryFirstField("SELECT COUNT(*) FROM accounts"); $this->assert($counter === strval(3)); DB::insert('`accounts`', array('username' => 'Deer', 'password' => '', 'age' => 15, 'height' => 10.371)); $username = DB::queryFirstField("SELECT username FROM accounts WHERE password=%s0", null); $this->assert($username === 'Deer'); $password = DB::queryFirstField("SELECT password FROM accounts WHERE favorite_word IS NULL"); $this->assert($password === 'goodbye'); DB::$usenull = false; DB::insertUpdate('accounts', array('id' => 3, 'favorite_word' => null)); $password = DB::queryFirstField("SELECT password FROM accounts WHERE favorite_word=%s AND favorite_word=%s", null, ''); $this->assert($password === 'goodbye'); DB::$usenull = true; DB::insertUpdate('accounts', array('id' => 3, 'favorite_word' => null)); DB::$param_char = '###'; $bart = DB::queryFirstRow("SELECT * FROM accounts WHERE age IN ###li AND height IN ###ld AND username IN ###ls", array(15, 25), array(10.371, 150.123), array('Bart', 'Barts')); $this->assert($bart['username'] === 'Bart'); DB::insert('accounts', array('username' => 'f_u')); DB::query("DELETE FROM accounts WHERE username=###s", 'f_u'); DB::$param_char = '%'; $charlie_password = DB::queryFirstField("SELECT password FROM accounts WHERE username IN %ls AND username = %s", array('Charlie', 'Charlie\'s Friend'), 'Charlie\'s Friend'); $this->assert($charlie_password === 'goodbye'); $charlie_password = DB::queryOneField('password', "SELECT * FROM accounts WHERE username IN %ls AND username = %s", array('Charlie', 'Charlie\'s Friend'), 'Charlie\'s Friend'); $this->assert($charlie_password === 'goodbye'); $passwords = DB::queryFirstColumn("SELECT password FROM accounts WHERE username=%s", 'Bart'); $this->assert(count($passwords) === 1); $this->assert($passwords[0] === 'hello'); $username = $password = $age = null; list($age, $username, $password) = DB::queryOneList("SELECT age,username,password FROM accounts WHERE username=%s", 'Bart'); $this->assert($username === 'Bart'); $this->assert($password === 'hello'); $this->assert($age == 15); $mysqli_result = DB::queryRaw("SELECT * FROM accounts WHERE favorite_word IS NULL"); $this->assert($mysqli_result instanceof MySQLi_Result); $row = $mysqli_result->fetch_assoc(); $this->assert($row['password'] === 'goodbye'); $this->assert($mysqli_result->fetch_assoc() === null); }
public function duplicate($id) { DB::startTransaction(); if (!DB::query("insert into " . $this->tableName() . " (name, user_id, url) select concat(name,' copy') as name, user_id, url from " . $this->tableName() . " where cloaker_id='" . DB::quote($id) . "'")) { DB::rollback(); return false; } $new_id = DB::insertId(); if (!$new_id) { DB::rollback(); return false; } if (!CloakerOptionModel::model()->duplicate($id, $new_id)) { DB::rollback(); return false; } if (!CloakerHostnameModel::model()->duplicate($id, $new_id)) { DB::rollback(); return false; } if (!CloakerIpModel::model()->duplicate($id, $new_id)) { DB::rollback(); return false; } if (!CloakerRefererModel::model()->duplicate($id, $new_id)) { DB::rollback(); return false; } if (!CloakerUaModel::model()->duplicate($id, $new_id)) { DB::rollback(); return false; } DB::commit(); return $new_id; }
/** * Добавляет новость в базу данных. * * @param array $array массив с данными о новости. * @return bool|int в случае успеха возвращает id добавленной новости. */ public function addNews($array) { unset($array['id']); $result = array(); $array['url'] = empty($array['url']) ? MG::translitIt($array['title']) : $array['url']; if (strlen($array['url']) > 60) { $array['url'] = substr($array['url'], 0, 60); } // Исключает дублирование. $dublicatUrl = false; $tempArray = $this->getNewsByUrl($array['url']); if (!empty($tempArray)) { $dublicatUrl = true; } if (DB::buildQuery('INSERT INTO `mpl_news` SET add_date=now(), ', $array)) { $id = DB::insertId(); // Если url дублируется, то дописываем к нему id новости. if ($dublicatUrl) { $this->updateNews(array('id' => $id, 'url' => $array['url'] . '_' . $id)); } $array['id'] = $id; $result = $array; } return $result; }
/** * 创建一条记录 * @param array $tableInfo 待插入的数据 * @param boolean $isAutoIncrement 操作成功时,如果该值为true,返回最后插入的id;否则返回true * @return boolean | int */ private function _create(array $tableInfo, $isAutoIncrement = true, $action = self::PARAM_CREATE_ACTION_INSERT) { if (empty($tableInfo)) { return false; } switch ($action) { case self::PARAM_CREATE_ACTION_INSERT: case self::PARAM_CREATE_ACTION_INSERT_IGNORE: case self::PARAM_CREATE_ACTION_REPLACE: break; default: throw new Exception('error insert action'); } $sql = "{$action} {$this->tableName}\n SET\n "; $sqlSets = ''; $tableInfo = $this->quote($tableInfo); foreach ($tableInfo as $key => $val) { if ($sqlSets != '') { $sqlSets .= ' ,'; } $sqlSets .= "\n `{$key}` = {$val}\n "; } $sql .= $sqlSets; if ($this->mdb->query($sql)) { if ($isAutoIncrement) { $id = $this->mdb->insertId(); return $id > 0 ? $id : true; } else { return true; } } return false; }
/** * Сохраняет и обновляет параметры записи. * @return type */ public function saveEntity() { $this->messageSucces = $this->lang['ENTITY_SAVE']; $this->messageError = $this->lang['ENTITY_SAVE_NOT']; unset($_POST['pluginHandler']); if (!empty($_POST['id'])) { // если передан ID, то обновляем if (DB::query(' UPDATE `' . PREFIX . $this->pluginName . '` SET ' . DB::buildPartQuery($_POST) . ' WHERE id = ' . DB::quote($_POST['id']))) { $this->data['row'] = $_POST; $this->data['slider'] = SliderAction::sliderAction(); } else { return false; } } else { // если не передан ID, то создаем if (DB::buildQuery('INSERT INTO `' . PREFIX . $this->pluginName . '` SET ', $_POST)) { $_POST['id'] = DB::insertId(); DB::query(' UPDATE `' . PREFIX . $this->pluginName . '` SET `sort` = `id` WHERE `id` = ' . DB::quote($_POST['id'])); $this->data['row'] = $_POST; $this->data['slider'] = SliderAction::sliderAction(); } else { return false; } } return true; }
function update_coa($account_code, $account_group, $account_desc_short, $account_desc_long, $parent_account_id, $account_status) { //Define $now ??? where is it comming from $edit = DB::UPDATE(DB_PREFIX . $_SESSION['co_prefix'] . 'coa', array('account_code' => $account_code, 'account_group' => $account_group, 'account_desc_short' => $account_desc_short, 'account_desc_long' => $account_desc_long, 'parent_account_id' => $parent_account_id, 'last_modified_by' => $user_name, 'last_modified_on' => $now, 'account_status' => $account_status), "account_id =%s", $coa_id); $coa_id = DB::insertId(); return $coa_id; }
function expense_voucher_detail($voucher_id, $voucher_paid_from_account, $expense_type, $expense_detail, $expense_ammount, $expense_attachment) { $now = getDateTime(0, 'mySQL'); $insert = DB::Insert(DB_PREFIX . $_SESSION['co_prefix'] . 'voucher_expense_detail', array('voucher_id' => $voucher_id, 'expense_account_id' => $voucher_paid_from_account, 'expense_type' => $expense_type, 'expense_description' => $expense_detail, 'expense_amount' => $expense_ammount, 'has_attachment' => $expense_attachment, 'created_by' => $_SESSION['user_name'], 'created_on' => $now, 'voucher_detail_status' => 'Draft')); $voucher_detail_id = DB::insertId(); if ($voucher_detail_id) { return $voucher_detail_id; return $voucher_id; } else { return 0; } }
function saveTrackingVariables($campaign) { $mysql = array(); $v1 = DB::quote(getArrayVar($_GET, $campaign->option('var_v1')->value)); $v2 = DB::quote(getArrayVar($_GET, $campaign->option('var_v2')->value)); $v3 = DB::quote(getArrayVar($_GET, $campaign->option('var_v3')->value)); $v4 = DB::quote(getArrayVar($_GET, $campaign->option('var_v4')->value)); if (!$v1) { $v1 = DB::quote(getArrayVar($_GET, 'subid1')); } if (!$v2) { $v2 = DB::quote(getArrayVar($_GET, 'subid2')); } if (!$v3) { $v3 = DB::quote(getArrayVar($_GET, 'subid3')); } if (!$v4) { $v4 = DB::quote(getArrayVar($_GET, 'subid4')); } $v1 = strtolower($v1); $v2 = strtolower($v2); $v3 = strtolower($v3); $v4 = strtolower($v4); $row = DB::getRows("select var_id,LOWER(var_value) as var_value from bt_s_variables where var_value IN ('{$v1}','{$v2}','{$v3}','{$v4}')", 'var_value'); if (!isset($row[$v1])) { DB::query("insert into bt_s_variables set var_value='{$v1}'"); $row[$v1] = array('var_id' => DB::insertId(), 'var_value' => $v1); } if (!isset($row[$v2])) { DB::query("insert into bt_s_variables set var_value='{$v2}'"); $row[$v2] = array('var_id' => DB::insertId(), 'var_value' => $v2); } if (!isset($row[$v3])) { DB::query("insert into bt_s_variables set var_value='{$v3}'"); $row[$v3] = array('var_id' => DB::insertId(), 'var_value' => $v3); } if (!isset($row[$v4])) { DB::query("insert into bt_s_variables set var_value='{$v4}'"); $row[$v4] = array('var_id' => DB::insertId(), 'var_value' => $v4); } $mysql['v1'] = $row[$v1]['var_value']; $mysql['v1_id'] = $row[$v1]['var_id']; $mysql['v2'] = $row[$v2]['var_value']; $mysql['v2_id'] = $row[$v2]['var_id']; $mysql['v3'] = $row[$v3]['var_value']; $mysql['v3_id'] = $row[$v3]['var_id']; $mysql['v4'] = $row[$v4]['var_value']; $mysql['v4_id'] = $row[$v4]['var_id']; return $mysql; }
public function add_product($amount, $currency, $name, $description) { // Add to DB DB::insert('products', array('amount' => $amount, 'currency' => $currency, 'display_name' => $name, 'description' => $description)); $this->product_id = DB::insertId(); // Add image, if needed if (isset($_FILES['product_image']) && isset($_FILES['product_image']['tmp_name']) && is_uploaded_file($_FILES['product_image']['tmp_name'])) { $contents = base64_encode(file_get_contents($_FILES['product_image']['tmp_name'])); DB::insert('products_images', array('id' => $this->product_id, 'mime_type' => $_FILES['product_image']['type'], 'filename' => $_FILES['product_image']['name'], 'contents' => $contents)); @unlinK($_FILES['product_image']['tmp_name']); } // Return return $this->product_id; }
public static function get_keyword_id($keyword) { //only grab the first 255 charactesr of keyword $keyword = substr($keyword, 0, 255); $mysql['keyword'] = DB::quote($keyword); $keyword_sql = "SELECT keyword_id FROM bt_s_keywords WHERE keyword='" . $mysql['keyword'] . "'"; $keyword_row = DB::getRow($keyword_sql); if ($keyword_row) { //if this already exists, return the id for it $keyword_id = $keyword_row['keyword_id']; return $keyword_id; } else { //else if this ip doesn't exist, insert the row and grab the id for it $keyword_sql = "INSERT INTO bt_s_keywords SET keyword='" . $mysql['keyword'] . "'"; $keyword_result = DB::query($keyword_sql); //($keyword_sql); $keyword_id = DB::insertId(); return $keyword_id; } }
/** * Добавляет новую учетную запись пользователя в базу сайта. * @param $userInfo - массив значений для вставки в БД [Поле => Значение]. * @return bool */ public static function add($userInfo) { $result = false; // Если пользователя с таким емайлом еще нет. if (!self::getUserInfoByEmail($userInfo['email'])) { $userInfo['pass'] = crypt($userInfo['pass']); foreach ($array as $k => $v) { if ($k !== 'pass') { $array[$k] = htmlspecialchars_decode($v); $array[$k] = htmlspecialchars($v); } } if (DB::buildQuery('INSERT INTO `' . PREFIX . 'user` SET ', $userInfo)) { $id = DB::insertId(); $result = $id; } } else { $result = false; } $args = func_get_args(); return MG::createHook(__CLASS__ . "_" . __FUNCTION__, $result, $args); }
function runOrganizationLookup() { $orgip = Net_GeoIP::getInstance(BT_ROOT . "/bt-config/GeoIPOrg.dat"); $org = ''; try { $org = $orgip->lookupOrg($_SERVER['REMOTE_ADDR']); } catch (Exception $e) { return 0; } if (!$org) { return 0; } $org = DB::quote($org); $sql = "select org_id from bt_g_organizations where name='{$org}'"; $id = DB::getVar($sql); if (!$id) { $sql = "insert into bt_g_organizations values ('','{$org}')"; DB::query($sql); $id = DB::insertId(); } return $id; }
/** * Создает новую страницу. * * @param array $array массив с данными о страницах. * @return bool|int в случае успеха возвращает id добавленной страницы. */ public function addPage($array) { unset($array['id']); $result = array(); if (!empty($array['url'])) { $array['url'] = URL::prepareUrl($array['url']); } $maskField = array('title', 'meta_title', 'meta_keywords', 'meta_desc', 'image_title', 'image_alt'); foreach ($array as $k => $v) { if (in_array($k, $maskField)) { $v = htmlspecialchars_decode($v); $array[$k] = htmlspecialchars($v); } } // Исключает дублирование. $dublicatUrl = false; $tempArray = $this->getPageByUrl($array['url'], $array['parent_url']); if (!empty($tempArray)) { $dublicatUrl = true; } $array['sort'] = $array['id']; if (DB::buildQuery('INSERT INTO `' . PREFIX . 'page` SET ', $array)) { $id = DB::insertId(); // Если url дублируется, то дописываем к нему id продукта. if ($dublicatUrl) { $arr = array('id' => $id, 'sort' => $id, 'url' => $array['url'] . '_' . $id); } else { $arr = array('id' => $id, 'sort' => $id, 'url' => $array['url']); } $this->updatePage($arr); $array['id'] = $id; $result = $array; } $args = func_get_args(); return MG::createHook(__CLASS__ . "_" . __FUNCTION__, $result, $args); }
public function create($group_id = 2) { // Initialize global $template, $config; // Validate profile $this->validate_profile(); if ($template->has_errors == 1) { return 0; } // Set variables $reg_ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '127.0.0.1'; $full_name = isset($_POST['full_name']) ? $_POST['full_name'] : ''; // Get custom fields $custom_fields = array(); $rows = DB::query("SELECT * FROM users_custom_fields ORDER BY id"); foreach ($rows as $row) { $var = 'custom' . $row['id']; if (!isset($_POST[$var])) { continue; } $custom_fields[$var] = $_POST[$var]; } // Add to DB DB::insert('users', array('username' => $_POST['username'], 'full_name' => $full_name, 'email' => $_POST['email'], 'password' => '*', 'group_id' => $group_id, 'reg_ip' => $reg_ip, 'custom_fields' => serialize($custom_fields))); $this->userid = DB::insertId(); // Update password $client = new encrypt(); $password = $client->get_password_hash($_POST['password'], $this->userid); DB::update('users', array('password' => $password), "id = %d", $this->userid); // Add alerts add_alert('new_user', $this->userid); // Execute hooks execute_hooks('new_user', $this->userid); // Return return $this->userid; }
exit; } //Check to see if the username already exists $result = DB::query("SELECT * FROM users WHERE username=%s", $username); if (!$result) { $canRegister = true; // $_SESSION['username'] = $_POST['username']; } else { $canRegister = false; } if ($canRegister && $password == $password2) { try { DB::insert('users', array('username' => $username, 'password' => $hashed_password, 'email' => $email, 'name' => $name)); $_SESSION['username'] = $username; // $_SESSION is a cookie that is around as long as the browser is open. $_SESSION['uid'] = DB::insertId(); // This will get the last auto-incremented id that was inserted into the database. header('Location: index.php'); exit; } catch (MeekroDBException $e) { header('Location: /register.php?error=yes'); exit; } } else { header('Location: /register.php?error=usernameexists'); exit; } if ($password != $password2) { header('Location: /register.php?error=nomatch'); exit; }
/** * Создает свойства продукта * @param type $key = Название характеристики * @param type $value = Значание * @param type $categoryId = Категория * @param type $productId = Продукт * @return type */ function createProperty($key, $value, $categoryId, $productId) { if (empty($key)) { return false; } // 0. Очистим продукт от всех ранее имеющихся свойств $propertyId = ''; // 1. Проверяем, существует такая характеристика у данной категории? $res = DB::query('SELECT * FROM `' . PREFIX . 'property` LEFT JOIN `' . PREFIX . 'category_user_property` as `cup` ON `cup`.`property_id`=`' . PREFIX . 'property`.`id` WHERE `name` = ' . DB::quote($key)); $row = DB::fetchAssoc($res); if (empty($row)) { // если нет характеристики до создадим ее DB::query(' INSERT INTO `' . PREFIX . 'property` (`name`, `type`, `activity`) VALUES (' . DB::quote($key) . ',"string",1)'); $propertyId = DB::insertId(); // установка сортировки DB::query('UPDATE `' . PREFIX . 'property` SET `sort` = ' . DB::quote($propertyId) . ' WHERE `id` = ' . DB::quote($propertyId)); } else { // если найдена уже характеристика, получаем ее id $propertyId = $row['id']; // добавляем привязку, если ее небыло раньше, для действующей категории $res = DB::query(' SELECT * FROM `' . PREFIX . 'category_user_property` WHERE `property_id` = ' . DB::quote($propertyId) . ' AND `category_id` = ' . DB::quote($categoryId)); $rowCup = DB::fetchAssoc($res); if (empty($rowCup)) { DB::query(' INSERT INTO `' . PREFIX . 'category_user_property` (`category_id`, `property_id`) VALUES (' . DB::quote($categoryId) . ',' . DB::quote($propertyId) . ')'); } } // 2. Привязываем к продукту $res = DB::query(' SELECT * FROM `' . PREFIX . 'product_user_property` WHERE `property_id` = ' . DB::quote($propertyId) . ' AND `product_id` = ' . DB::quote($productId)); $row = DB::fetchAssoc($res); if (empty($row)) { DB::query(' INSERT INTO `' . PREFIX . 'product_user_property` (`product_id`, `property_id`, `value`) VALUES (' . DB::quote($productId) . ',' . DB::quote($propertyId) . ',' . DB::quote($value) . ')'); } else { DB::query(' UPDATE `' . PREFIX . 'product_user_property` SET `value` = ' . DB::quote($value) . ' WHERE `product_id` = ' . DB::quote($productId) . ' AND `property_id` = ' . DB::quote($propertyId)); } // 3. Привязываем к категории $res = DB::query(' SELECT * FROM `' . PREFIX . 'category_user_property` WHERE `property_id` = ' . DB::quote($propertyId)); $row = DB::fetchAssoc($res); if (empty($row)) { // если нет характеристики до создадим ее DB::query(' INSERT INTO `' . PREFIX . 'category_user_property` (`category_id`, `property_id`) VALUES (' . DB::quote($categoryId) . ',' . DB::quote($propertyId) . ')'); } }
switch ($_POST['type']) { case "addNewCategory": // store key DB::insert($pre . 'categories', array('parent_id' => 0, 'title' => $_POST['title'], 'level' => 0, 'order' => 1)); echo '[{"error" : "", "id" : "' . DB::insertId() . '"}]'; break; case "deleteCategory": DB::delete($pre . "categories", "id = %i", $_POST['id']); DB::delete($pre . "categories_folders", "category_id = %i", $_POST['id']); echo '[{"error" : ""}]'; break; case "addNewField": // store key if (!empty($_POST['title']) && !empty($_POST['id'])) { DB::insert($pre . 'categories', array('parent_id' => $_POST['id'], 'title' => $_POST['title'], 'level' => 1, 'type' => 'text', 'order' => 1)); echo '[{"error" : "", "id" : "' . DB::insertId() . '"}]'; } break; case "renameItem": // update key if (!empty($_POST['data']) && !empty($_POST['id'])) { DB::update($pre . 'categories', array('title' => $_POST['data']), "id=%i", $_POST['id']); echo '[{"error" : "", "id" : "' . $_POST['id'] . '"}]'; } break; case "moveItem": // update key if (!empty($_POST['data']) && !empty($_POST['id'])) { DB::update($pre . 'categories', array('parent_id' => $_POST['data'], 'order' => 99), "id=%i", $_POST['id']); echo '[{"error" : "", "id" : "' . $_POST['id'] . '"}]'; }
if (count($foldersArray) == 0 || empty($item[KP_PATH])) { $folderId = $_POST['destination']; } else { $folderId = $foldersArray[$item[KP_PATH]]['id']; } $data = DB::queryFirstRow("SELECT title FROM " . prefix_table("nested_tree") . " WHERE id = %i", intval($folderId)); $results .= " - Inserting\n"; // prepare PW if ($import_perso == true) { $encrypt = cryption($pw, $_SESSION['my_sk'], "", "encrypt"); } else { $encrypt = cryption($pw, SALT, "", "encrypt"); } //ADD item DB::insert(prefix_table("items"), array('label' => stripslashes($item[KP_TITLE]), 'description' => stripslashes(str_replace($lineEndSeparator, '<br />', $item[KP_NOTES])), 'pw' => $encrypt['string'], 'pw_iv' => $encrypt['iv'], 'url' => stripslashes($item[KP_URL]), 'id_tree' => $folderId, 'login' => stripslashes($item[KP_USERNAME]), 'anyone_can_modify' => $_POST['import_kps_anyone_can_modify'] == "true" ? 1 : 0)); $newId = DB::insertId(); //if asked, anyone in role can modify if (isset($_POST['import_kps_anyone_can_modify_in_role']) && $_POST['import_kps_anyone_can_modify_in_role'] == "true") { foreach ($_SESSION['arr_roles'] as $role) { DB::insert(prefix_table("restriction_to_roles"), array('role_id' => $role['id'], 'item_id' => $newId)); } } //Add log DB::insert(prefix_table("log_items"), array('id_item' => $newId, 'date' => time(), 'id_user' => $_SESSION['user_id'], 'action' => 'at_creation', 'raison' => 'at_import')); //Add entry to cache table DB::insert(prefix_table("cache"), array('id' => $newId, 'label' => stripslashes($item[KP_TITLE]), 'description' => stripslashes(str_replace($lineEndSeparator, '<br />', $item[KP_NOTES])), 'id_tree' => $folderId, 'perso' => $personalFolder == 0 ? 0 : 1, 'login' => stripslashes($item[KP_USERNAME]), 'folder' => $data['title'], 'author' => $_SESSION['user_id'])); //show //$text .= '- '.addslashes($item[2]).'<br />'; //increment number of imported items $nbItemsImported++; } else {
/** * Сохранение способа доставки */ public function saveDeliveryMethod() { $this->messageSucces = $this->lang['ACT_SUCCESS']; $this->messageError = $this->lang['ACT_ERROR']; $status = $_POST['status']; $deliveryName = htmlspecialchars($_POST['deliveryName']); $deliveryCost = (double) $_POST['deliveryCost']; $deliveryId = (int) $_POST['deliveryId']; $free = (double) $_POST['free']; $paymentMethod = $_POST['paymentMethod']; $paymentArray = json_decode($paymentMethod, true); $deliveryDescription = htmlspecialchars($_POST['deliveryDescription']); $deliveryActivity = $_POST['deliveryActivity']; $deliveryDate = $_POST['deliveryDate']; $deliveryYmarket = $_POST['deliveryYmarket']; switch ($status) { case 'createDelivery': $sql = "\n INSERT INTO `" . PREFIX . "delivery` (`name`,`cost`, `description`, `activity`,`free`, `date`, `ymarket` )\n VALUES (\n " . DB::quote($deliveryName) . ", " . DB::quote($deliveryCost) . ", " . DB::quote($deliveryDescription) . ", " . DB::quote($deliveryActivity) . ", " . DB::quote($free) . ", " . DB::quote($deliveryDate) . ", " . DB::quote($deliveryYmarket) . " \n );\n "; $result = DB::query($sql); if ($deliveryId = DB::insertId()) { DB::query(" UPDATE `" . PREFIX . "delivery` SET `sort`=`id` WHERE `id` = " . DB::quote($deliveryId)); $status = 'success'; $msg = $this->lang['ACT_SUCCESS']; } else { $status = 'error'; $msg = $this->lang['ACT_ERROR']; } foreach ($paymentArray as $paymentId => $compare) { $sql = "\n INSERT INTO `" . PREFIX . "delivery_payment_compare`\n (`compare`,`payment_id`, `delivery_id`)\n VALUES (\n " . DB::quote($compare) . ", " . DB::quote($paymentId) . ", " . DB::quote($deliveryId) . "\n );\n "; $result = DB::query($sql); } break; case 'editDelivery': $sql = "\n UPDATE `" . PREFIX . "delivery`\n SET `name` = " . DB::quote($deliveryName) . ",\n `cost` = " . DB::quote($deliveryCost) . ",\n `description` = " . DB::quote($deliveryDescription) . ",\n `activity` = " . DB::quote($deliveryActivity) . ",\n `free` = " . DB::quote($free) . ",\n `date` = " . DB::quote($deliveryDate) . ",\n `ymarket` = " . DB::quote($deliveryYmarket) . "\n WHERE id = " . DB::quote($deliveryId); $result = DB::query($sql); foreach ($paymentArray as $paymentId => $compare) { $result = DB::query("\n SELECT * \n FROM `" . PREFIX . "delivery_payment_compare` \n WHERE `payment_id` = " . DB::quote($paymentId) . "\n AND `delivery_id` = " . DB::quote($deliveryId)); if (!DB::numRows($object)) { $sql = "\n INSERT INTO `" . PREFIX . "delivery_payment_compare`\n (`compare`,`payment_id`, `delivery_id`)\n VALUES (\n " . DB::quote($compare) . ", " . DB::quote($paymentId) . ", " . DB::quote($deliveryId) . "\n );\n "; $result = DB::query($sql); } else { $sql = "\n UPDATE `" . PREFIX . "delivery_payment_compare`\n SET `compare` = " . DB::quote($compare) . "\n WHERE `payment_id` = " . DB::quote($paymentId) . "\n AND `delivery_id` = " . DB::quote($deliveryId); $result = DB::query($sql); } } if ($result) { $status = 'success'; $msg = $this->lang['ACT_SUCCESS']; } else { $status = 'error'; $msg = $this->lang['ACT_ERROR']; } } if ($deliveryYmarket == 1) { DB::query(" UPDATE `" . PREFIX . "delivery` SET `ymarket`=0 WHERE `id` != " . DB::quote($deliveryId)); } $response = array('data' => array('id' => $deliveryId), 'status' => $status, 'msg' => $msg); echo json_encode($response); }
$total_sigs = $_POST['address_type'] == 'standard' ? 1 : $_POST['multisig_sig_total']; // Validate public keys if ($_POST['autogen_keys'] == 0) { for ($x = 1; $x <= $total_sigs; $x++) { if (!($import = $b32->import($_POST['bip32_key' . $x]))) { $template->add_message("The #{$x} BIP32 key you specified is an invalid BIP32 key.", 'error'); } elseif ($import['type'] != 'public') { $template->add_message("The #{$x} BIP32 key you specified is an invalid BIP32 key.", 'error'); } } } // Create wallet, if no errors if ($template->has_errors != 1) { // Add to DB DB::insert('coin_wallets', array('address_type' => $_POST['address_type'], 'sigs_required' => $required_sigs, 'sigs_total' => $total_sigs, 'display_name' => $_POST['wallet_name'])); $wallet_id = DB::insertId(); // Gather BIP32 keys $keys = array(); for ($x = 1; $x <= $total_sigs; $x++) { // Auto-generate, if needed if ($_POST['autogen_keys'] == 1) { $private_key = $b32->generate_master_key(); $public_key = $b32->extended_private_to_public($private_key); array_push($keys, array('num' => $x, 'private_key' => $private_key, 'public_key' => $public_key)); } else { $public_key = $_POST['bip32_key' . $x]; } // Add key to db DB::insert('coin_wallets_keys', array('wallet_id' => $wallet_id, 'public_key' => $enc_client->encrypt($public_key))); } // User message
$counter = DB::count(); if ($counter == 0) { DB::insert(prefix_table("kb_categories"), array('category' => $category)); $cat_id = DB::insertId(); } else { //get the ID of this existing category $cat_id = DB::queryfirstrow("SELECT id FROM " . prefix_table("kb_categories") . " WHERE category = %s", $category); $cat_id = $cat_id['id']; } if (isset($id) && !empty($id)) { //update KB DB::update(prefix_table("kb"), array('label' => $label, 'description' => $description, 'author_id' => $_SESSION['user_id'], 'category_id' => $cat_id, 'anyone_can_modify' => $anyone_can_modify), "id=%i", $id); } else { //add new KB DB::insert(prefix_table("kb"), array('label' => $label, 'description' => $description, 'author_id' => $_SESSION['user_id'], 'category_id' => $cat_id, 'anyone_can_modify' => $anyone_can_modify)); $id = DB::insertId(); } //delete all associated items to this KB DB::delete(prefix_table("kb_items"), "kb_id = %i", $id); //add all items associated to this KB foreach (explode(',', $kb_associated_to) as $item_id) { DB::insert(prefix_table("kb_items"), array('kb_id' => $id, 'item_id' => $item_id)); } echo '[ { "status" : "done" } ]'; } else { echo '[ { "status" : "none" } ]'; } break; /** * Open KB */
$link = mysqli_connect($server, $user, $pass, $database, $port); $link->set_charset($encoding); //Build tree $tree = new SplClassLoader('Tree\\NestedTree', $_SESSION['settings']['cpassman_dir'] . '/includes/libraries'); $tree->register(); $tree = new Tree\NestedTree\NestedTree($pre . 'nested_tree', 'id', 'parent_id', 'title'); if (!empty($_POST['type'])) { switch ($_POST['type']) { #CASE adding a new role case "add_new_role": //Check if role already exist : No similar roles $tmp = DB::query("SELECT * FROM " . prefix_table("roles_title") . " WHERE title = %s", stripslashes($_POST['name'])); $counter = DB::count(); if ($counter == 0) { DB::insert(prefix_table("roles_title"), array('title' => stripslashes($_POST['name']), 'complexity' => $_POST['complexity'], 'creator_id' => $_SESSION['user_id'])); $role_id = DB::insertId(); if ($role_id != 0) { //Actualize the variable $_SESSION['nb_roles']++; echo '[ { "error" : "no" } ]'; } else { echo '[ { "error" : "yes" , "message" : "Database error. Contact your administrator!" } ]'; } } else { echo '[ { "error" : "yes" , "message" : "' . $LANG['error_role_exist'] . '" } ]'; } break; //------------------------------------------- #CASE delete a role //------------------------------------------- #CASE delete a role
$new_user_id = DB::insertId(); // Create personnal folder if ($dataReceived['personal_folder'] == "true") { DB::insert(prefix_table("nested_tree"), array('parent_id' => '0', 'title' => $new_user_id, 'bloquer_creation' => '0', 'bloquer_modification' => '0', 'personal_folder' => '1')); $tree->rebuild(); } // Create folder and role for domain if ($dataReceived['new_folder_role_domain'] == "true") { // create folder DB::insert(prefix_table("nested_tree"), array('parent_id' => 0, 'title' => mysqli_escape_string($link, stripslashes($dataReceived['domain'])), 'personal_folder' => 0, 'renewal_period' => 0, 'bloquer_creation' => '0', 'bloquer_modification' => '0')); $new_folder_id = DB::insertId(); // Add complexity DB::insert(prefix_table("misc"), array('type' => 'complex', 'intitule' => $new_folder_id, 'valeur' => 50)); // Create role DB::insert(prefix_table("roles_title"), array('title' => mysqli_escape_string($link, stripslashes($dataReceived['domain'])))); $new_role_id = DB::insertId(); // Associate new role to new folder DB::insert(prefix_table("roles_values"), array('folder_id' => $new_folder_id, 'role_id' => $new_role_id)); // Add the new user to this role DB::update(prefix_table("users"), array('fonction_id' => is_int($new_role_id)), "id=%i", $new_user_id); // rebuild tree $tree->rebuild(); } // get links url if (empty($_SESSION['settings']['email_server_url'])) { $_SESSION['settings']['email_server_url'] = $_SESSION['settings']['cpassman_url']; } // Send email to new user @sendEmail($LANG['email_subject_new_user'], str_replace(array('#tp_login#', '#tp_pw#', '#tp_link#'), array(" " . addslashes($login), addslashes($pw), $_SESSION['settings']['email_server_url']), $LANG['email_new_user_mail']), $dataReceived['email']); // update LOG logEvents('user_mngt', 'at_user_added', $_SESSION['user_id'], $_SESSION['login'], $new_user_id);
$updStatus = DB::update(prefix_table("items"), array('description' => !empty($suggestion['description']) ? $existing_item_id['id'] . "<br />----<br />" . $suggestion['description'] : $existing_item_id['id'], 'pw' => $suggestion['pw'], 'pw_iv' => $suggestion['pw_iv']), "id=%i", $existing_item_id['id']); if ($updStatus) { // update LOG DB::insert(prefix_table("log_items"), array('id_item' => $existing_item_id['id'], 'date' => time(), 'id_user' => $_SESSION['user_id'], 'action' => 'at_modification', 'raison' => 'at_suggestion')); // update cache table updateCacheTable("update_value", $existing_item_id['id']); // delete suggestion DB::delete(prefix_table("suggestion"), "id = %i", $_POST['id']); echo '[ { "status" : "done" } ]'; } else { echo '[ { "status" : "error_when_updating" } ]'; } } else { // add as Item DB::insert(prefix_table("items"), array('label' => $suggestion['label'], 'description' => $suggestion['description'], 'pw' => $suggestion['pw'], 'id_tree' => $suggestion['folder_id'], 'inactif' => '0', 'perso' => '0', 'anyone_can_modify' => '0', 'pw_iv' => $suggestion['pw_iv'])); $newID = DB::insertId(); if (is_numeric($newID)) { // update log DB::insert(prefix_table("log_items"), array('id_item' => $newID, 'date' => time(), 'id_user' => $suggestion['author_id'], 'action' => 'at_creation')); // update cache table updateCacheTable("add_value", $newID); // delete suggestion DB::delete(prefix_table("suggestion"), "id = %i", $_POST['id']); echo '[ { "status" : "done" } ]'; } else { echo '[ { "status" : "error_when_creating" } ]'; } } break; case "get_complexity_level": // Check KEY
/** * Добавляет товар в базу данных. * @param array $array массив с данными о товаре. * @return bool|int в случае успеха возвращает id добавленного товара. */ public function addProduct($array, $clone = false) { if (empty($array['title'])) { return false; } $userProperty = $array['userProperty']; $variants = !empty($array['variants']) ? $array['variants'] : array(); // варианты товара unset($array['userProperty']); unset($array['variants']); unset($array['id']); $result = array(); $array['url'] = empty($array['url']) ? MG::translitIt($array['title']) : $array['url']; $maskField = array('title', 'meta_title', 'meta_keywords', 'meta_desc', 'image_title', 'image_alt'); foreach ($array as $k => $v) { if (in_array($k, $maskField)) { $v = htmlspecialchars_decode($v); $array[$k] = htmlspecialchars($v); } } if (!empty($array['url'])) { $array['url'] = URL::prepareUrl($array['url']); } // Исключает дублирование. $dublicatUrl = false; $tempArray = $this->getProductByUrl($array['url']); if (!empty($tempArray)) { $dublicatUrl = true; } if (DB::buildQuery('INSERT INTO `' . PREFIX . 'product` SET ', $array)) { $id = DB::insertId(); // Если url дублируется, то дописываем к нему id продукта. if ($dublicatUrl) { $this->updateProduct(array('id' => $id, 'url' => $array['url'] . '_' . $id, 'sort' => $id)); } else { $this->updateProduct(array('id' => $id, 'url' => $array['url'], 'sort' => $id)); } $array['id'] = $id; $array['userProperty'] = $userProperty; $userProp = array(); if ($clone) { if (!empty($userProperty)) { foreach ($userProperty as $property) { $userProp[$property['property_id']] = $property['value']; if (!empty($property['product_margin'])) { $userProp["margin_" . $property['property_id']] = $property['product_margin']; } } $userProperty = $userProp; } } if (!empty($userProperty)) { $this->saveUserProperty($userProperty, $id); } // Обновляем и добавляем варианты продукта. $this->saveVariants($variants, $id); $variants = $this->getVariants($id); foreach ($variants as $variant) { $array['variants'][] = $variant; } $tempProd = $this->getProduct($id); $array['category_url'] = $tempProd['category_url']; $array['product_url'] = $tempProd['product_url']; $result = $array; } $this->updatePriceCourse($currencyShopIso, array($result['id'])); $args = func_get_args(); return MG::createHook(__CLASS__ . "_" . __FUNCTION__, $result, $args); }
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&group=' . $data['id_tree'] . '&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'] = "."; } }
/** * Создает дубль заказа * @return $id - номер копируемого заказа */ public function cloneOrder($id) { // учет остатков товаров в заказе $res = DB::query('SELECT `order_content` FROM `' . PREFIX . 'order` WHERE `id`= ' . DB::quote($id)); if ($row = DB::fetchArray($res)) { $content = unserialize(stripslashes($row['order_content'])); } $allAvailable = true; foreach ($content as $item) { if ($this->notSetGoods($item['id']) == false) { return false; } $res = DB::query('SELECT p.`count`, pv.`count` AS `var_count`, pv.`code` FROM `' . PREFIX . 'product` p LEFT JOIN `' . PREFIX . 'product_variant` pv ON p.id = pv.product_id WHERE p.id=' . DB::quote($item['id'])); while ($row = DB::fetchArray($res)) { if (!empty($row['code']) && $row['code'] == $item['code']) { $count = $row['var_count']; } elseif (empty($row['code'])) { $count = $row['count']; } } if ($count >= 0 && $count < $item['count']) { $allAvailable = false; } } if ($allAvailable == false) { return false; } $product = new Models_Product(); foreach ($content as $item) { $product->decreaseCountProduct($item['id'], $item['code'], $item['count']); } $sql = " INSERT INTO \r\n `" . PREFIX . "order`\r\n ( \r\n `updata_date`, \r\n `add_date`, \r\n `close_date`, \r\n `user_email`, \r\n `phone`, \r\n `address`, \r\n `summ`, \r\n `order_content`, \r\n `delivery_id`, \r\n `delivery_cost`, \r\n `payment_id`, \r\n `paided`, \r\n `status_id`, \r\n `comment`, \r\n `confirmation`, \r\n `yur_info`, \r\n `name_buyer`\r\n ) \r\n SELECT \r\n `updata_date`, \r\n now() as `add_date`,\r\n `close_date`, \r\n `user_email`, \r\n `phone`, \r\n `address`, \r\n `summ`,\r\n `order_content`,\r\n `delivery_id`,\r\n `delivery_cost`,\r\n `payment_id`,\r\n `paided`,\r\n `status_id`,\r\n `comment`,\r\n `confirmation`,\r\n `yur_info`,\r\n `name_buyer`\r\n FROM " . PREFIX . "order\r\n WHERE `id`= " . DB::quote($id); $res = DB::query($sql); $id = DB::insertId(); $orderNumber = $this->getOrderNumber($id); DB::query("UPDATE `" . PREFIX . "order` SET `number`= " . DB::quote($orderNumber) . " WHERE `id`=" . DB::quote($id) . ""); return true; }
public function addSlide() { $this->messageError = $this->lang['ENTITY_SAVE_ERROR']; $this->messageSucces = $this->lang['ENTITY_SAVE_SUCCESS']; unset($_POST['pluginHandler']); if (!empty($_POST['id'])) { $this->updateSlide($_POST); } else { unset($_POST['id']); if (isset($_POST['type'])) { $_POST['sort'] = $this->getCountSlide(); if ($_POST['type'] == 'img') { $this->data['row']['type'] = $_POST['type']; unset($_POST['type']); if (DB::buildQuery('INSERT INTO `' . PREFIX . $this->pluginName . '` SET ', $_POST)) { $this->data['row']['id'] = DB::insertId(); $this->data['row']['sort'] = $_POST['sort']; $this->data['row']['img'] = SITE . '/' . PLUGIN_DIR . $this->pluginName . '/img/slides/' . $_POST['img']; return true; } } else { if ($_POST['type'] == 'desc') { $this->data['row']['type'] = $_POST['type']; unset($_POST['type']); if (DB::buildQuery('INSERT INTO `' . PREFIX . $this->pluginName . '` SET ', $_POST)) { $this->data['row']['id'] = DB::insertId(); $this->data['row']['name_link'] = $_POST['name_link']; $this->data['row']['url_link'] = $_POST['url_link']; $this->data['row']['desc'] = $_POST['desc']; $this->data['row']['sort'] = $_POST['sort']; $this->data['row']['img'] = SITE . '/' . PLUGIN_DIR . $this->pluginName . '/img/slides/' . $_POST['img']; return true; } } } } } }
function process_form() { // INITIAL DATA FETCHING global $name, $email, $cell, $yog, $mailings; // so that the show_form function can use these values later $name = htmlentities(ucwords(trim(strtolower($_POST['name']), ' \\-\''))); foreach (array('-', '\'') as $delimiter) { if (strpos($name, $delimiter) !== false) { $name = implode($delimiter, array_map('ucfirst', explode($delimiter, $name))); } } // forces characters after spaces, hyphens and apostrophes to be capitalized $name = preg_replace('/[\\s\']*\\-+[\\s\']*/', '-', $name); // removes hyphens not between two characters $name = preg_replace('/[\\s\\-]*\'+[\\s\\-]*/', '\'', $name); // removes apostrophes not between two characters $name = preg_replace('/\\s+/', ' ', $name); // removes multiple consecutive spaces $name = preg_replace('/\\-+/', '-', $name); // removes multiple consecutive hyphens $name = preg_replace('/\'+/', '\'', $name); // removes multiple consecutive apostrophes $email = htmlentities(strtolower($_POST['email'])); $cell = htmlentities($_POST['cell']); $yog = $_POST['yog']; $pass = $_POST['pass1']; $mailings = '0'; if ($_POST['mailings'] == 'Yes') { $mailings = '1'; } // CHECK THAT THE NAME IS VALID if (($name = sanitize_username($name)) === false) { alert('Your name must have only letters, hyphens, apostrophes, and spaces, and be between 3 and 30 characters long', -1); show_form(); return; } if (strpos($name, ' ') == false) { alert('Please enter both your first <span class="i">and</span> last name', -1); show_form(); return; } // CHECK THAT THE EMAIL ADDRESS IS VALID if (!val('e', $email)) { alert('That\'s not a valid email address', -1); show_form(); return; } // CHECK AND FORMAT CELL PHONE NUMBER if ($cell != '' && ($cell = format_phone_number($cell)) === false) { //Validate the format of the cell phone number (if it's not left blank) alert('That\'s not a valid cell phone number', -1); show_form(); return; } // CHECK THAT THE YOG IS VALID $grade = intval(getGradeFromYOG($yog)); if ($grade < 9 || $grade > 12) { alert('That is not a valid YOG (' . $grade . 'you have to be in high school)', -1); show_form(); return; } // CHECK THAT THE PASSWORDS MATCH, MEET MINIMUM LENGTH if ($pass != $_POST['pass2']) { alert('The passwords that you entered do not match', -1); show_form(); return; } if (strlen($pass) < 6) { alert('Please choose a password that has at least 6 characters', -1); show_form(); return; } // CHECK THAT THEY ENTERED THE RECAPTCHA CORRECTLY // CURRENTLY BROKEN: NEED TO UPDATE RECAPTCHA /* $recaptcha_msg = validate_recaptcha(); if ($recaptcha_msg !== true) { alert($recaptcha_msg, -1); show_form(); return; } */ // CHECK THAT AN ACCOUNT WITH THAT EMAIL DOES NOT ALREADY EXIST // this is done *after* checking the reCaptcha to prevent bots from harvesting our email // addresses via a brute-force attack. if (DBExt::queryCount('users', 'LOWER(email)=LOWER(%s)', $email) != 0) { alert('An account with that email address already exists', -1); show_form(); return; } // CHECK THAT AN ACCOUNT WITH THE SAME NAME IN THE SAME GRADE DOES NOT EXIST // - with the exception that if it's permissions = 'E', they probably mistyped their email and are redoing it. if (DBExt::queryCount('users', 'LOWER(name)=%s AND yog=%i AND permissions!="E"', strtolower($name), $yog) != 0) { alert('An account in your grade with that name already exists', -1); show_form(); return; } // ** All information has been validated at this point ** $verification_code = generate_code(5); // for verifying ownership of the email address // Check if email address has been pre-approved if (isset($_SESSION['PREAPPROVED']) && $email === $_SESSION['PREAPPROVED']) { $approved = '1'; // skip Captain approval $verification_code = '1'; // skip email verification (already done) } else { $approved = '0'; } // Create database entry $passhash = hash_pass($email, $pass); if ($cell == '') { $cell = 'None'; } else { $cell = preg_replace('#[^\\d]#', '', $_POST['cell']); } // remove non-numbers from cell phone # again DB::insert('users', array('name' => $name, 'email' => $email, 'passhash' => $passhash, 'cell' => $cell, 'yog' => $yog, 'mailings' => $mailings, 'approved' => $approved, 'email_verification' => $verification_code, 'registration_ip' => htmlentities(strtolower($_SERVER['REMOTE_ADDR'])))); set_login_data(DB::insertId()); // LOG THEM IN // For pre-approved members: if ($approved == '1') { global $WEBMASTER_EMAIL; $to = array($email => $name); $subject = 'Account Created'; $body = <<<HEREDOC Welcome to the LHS Math Club website, {$name}! Your account has been created. If you have any questions about the site, please email the webmaster at {$WEBMASTER_EMAIL} HEREDOC; send_email($to, $subject, $body, $WEBMASTER_EMAIL); $_SESSION['HOME_welcome'] = 'Welcome to the LHS Math Club website, ' . $name . '!'; header('Location: Home'); } $_SESSION['ACCOUNT_do_send_verification_email'] = true; header('Location: Verify_Email'); }