/**
  * POST | This handles the registration with validation.
  *
  * @return mixed
  */
 public function storeRegistrationForm()
 {
     $inputs = request()->get();
     $validator = new RegistrationValidator();
     $validation = $validator->validate($inputs);
     if (count($validation)) {
         session()->set('input', $inputs);
         return redirect()->to(url()->previous())->withError(RegistrationValidator::toHtml($validation));
     }
     $token = bin2hex(random_bytes(100));
     $connection = db()->connection();
     try {
         $connection->begin();
         $user = new User();
         $success = $user->create(['email' => $inputs['email'], 'password' => security()->hash($inputs['password']), 'token' => $token]);
         if ($success === false) {
             throw new Exception('It seems we can\'t create an account, ' . 'please check your access credentials!');
         }
         queue(\Components\Queue\Email::class, ['function' => 'registeredSender', 'template' => 'emails.registered-inlined', 'to' => $inputs['email'], 'url' => route('activateUser', ['token' => $token]), 'subject' => 'You are now registered, activation is required.']);
         $connection->commit();
     } catch (TransactionFailed $e) {
         $connection->rollback();
         throw $e;
     } catch (Exception $e) {
         $connection->rollback();
         throw $e;
     }
     return redirect()->to(route('showLoginForm'))->withSuccess(lang()->get('responses/register.creation_success'));
 }
 public function pub_run($o)
 {
     $this->stomp = new Stomp('tcp://network.home.micoli.org:61613');
     $this->stomp->connect('guest', 'guest');
     try {
         $this->imapProxy->setAccount($o['account']);
         $this->imapProxy->open('INBOX');
         if (!$this->imapProxy->isConnected()) {
             return $res;
         }
         $this->getLatestMails($o);
         $running = true;
         do {
             db(date('H:i:s ') . "IN IDLE ");
             $response = $this->imapProxy->idle(5 * 60);
             if ($response) {
                 db(date('H:i:s -------------') . $response);
                 $this->getLatestMails($o);
             } else {
                 db(date('H:i:s ') . 'TIMEOUT OCCURED');
             }
         } while ($running);
         db(__CLASS__ . " " . __LINE__);
     } catch (Horde_Imap_Client_Exception $e) {
         db($e);
     } catch (InvalidArgumentException $e) {
         db($e);
     }
 }
 /**
  * Order step
  */
 function _order_step_start($FORCE_DISPLAY_FORM = false)
 {
     module('shop')->_basket_save();
     $basket_contents = module('shop')->_basket_api()->get_all();
     $products_ids = [];
     foreach ((array) $basket_contents as $_item_id => $_info) {
         if ($_info["product_id"]) {
             $products_ids[$_info["product_id"]] = $_info["product_id"];
         }
     }
     if (!empty($products_ids)) {
         $products_infos = db()->query_fetch_all("SELECT * FROM " . db('shop_products') . " WHERE id IN(" . implode(",", $products_ids) . ") AND active='1'");
         $products_atts = module('shop')->_products_get_attributes($products_ids);
         $group_prices = module('shop')->_get_group_prices($products_ids);
     }
     $total_price = 0;
     foreach ((array) $products_infos as $_info) {
         $_product_id = $_info["id"];
         $_info["_group_price"] = $group_prices[$_product_id][module('shop')->USER_GROUP];
         $quantity = $basket_contents[$_info["id"]]["quantity"];
         $price = module('shop')->_product_get_price($_info);
         $dynamic_atts = [];
         foreach ((array) $products_atts[$_product_id] as $_attr_id => $_attr_info) {
             if ($basket_contents[$_product_id]["atts"][$_attr_info["name"]] == $_attr_info["value"]) {
                 $dynamic_atts[$_attr_id] = "- " . $_attr_info["name"] . " " . $_attr_info["value"];
                 $price += $_attr_info["price"];
             }
         }
         $URL_PRODUCT_ID = module('shop')->_product_id_url($_info);
         $products[$_info["id"]] = ["name" => _prepare_html($_info["name"]), "price" => module('shop')->_format_price($price), "currency" => _prepare_html(module('shop')->CURRENCY), "quantity" => intval($quantity), "details_link" => process_url("./?object=shop&action=product_details&id=" . $URL_PRODUCT_ID), "dynamic_atts" => !empty($dynamic_atts) ? implode("\n<br />", $dynamic_atts) : "", "cat_name" => _prepare_html(module('shop')->_shop_cats[$_info["cat_id"]]), "cat_url" => process_url("./?object=shop&action=products_show&id=" . module('shop')->_shop_cats_all[$_info["cat_id"]]['url'])];
         $total_price += $price * $quantity;
     }
     $replace = ["products" => $products, "total_price" => module('shop')->_format_price($total_price), "currency" => _prepare_html(module('shop')->CURRENCY), "back_link" => "./?object=shop&action=basket", "next_link" => "./?object=shop&action=order&id=delivery", "cats_block" => module('shop')->_categories_show()];
     return tpl()->parse("shop/order_start", $replace);
 }
Beispiel #4
0
/**
 * Get a summary of how many accounts, graphs, pages etc the current user has.
 * Does not include disabled accounts towards the limit (#217).
 * May be cached per user.
 */
function user_limits_summary($user_id)
{
    global $global_user_limits_summary;
    if (!isset($global_user_limits_summary[$user_id])) {
        $accounts = array();
        foreach (account_data_grouped() as $group) {
            foreach ($group as $key => $data) {
                if (!isset($data['group'])) {
                    continue;
                }
                $q = db()->prepare("SELECT COUNT(*) AS c FROM " . $data['table'] . " WHERE user_id=?" . ($data['failure'] ? " AND is_disabled=0" : "") . (isset($data['query']) ? $data['query'] : ""));
                $q->execute(array($user_id));
                $accounts[$key] = $q->fetch();
                $accounts[$key] = $accounts[$key]['c'];
                if (!isset($accounts['total_' . $data['group']])) {
                    $accounts['total_' . $data['group']] = 0;
                }
                $accounts['total_' . $data['group']] += $accounts[$key];
                if (!isset($data['wizard'])) {
                    continue;
                }
                if (!isset($accounts['wizard_' . $data['wizard']])) {
                    $accounts['wizard_' . $data['wizard']] = 0;
                }
                $accounts['wizard_' . $data['wizard']] += $accounts[$key];
            }
        }
        $global_user_limits_summary[$user_id] = $accounts;
    }
    return $global_user_limits_summary[$user_id];
}
Beispiel #5
0
 function basket_add()
 {
     $product = db()->query_fetch("SELECT id FROM " . db('shop_products') . " WHERE active = '1' AND " . (is_numeric($_GET["id"]) ? "id=" . intval($_GET["id"]) : "url='" . _es($_GET['id']) . "'"));
     if (!empty($product)) {
         $_GET['id'] = $product['id'];
     }
     $atts = module('shop')->_products_get_attributes($product["id"]);
     if ($_GET["id"]) {
         $_GET["id"] = intval($_GET["id"]);
         $_POST["quantity"][$_GET["id"]] = 1;
     }
     if (!empty($atts) && empty($_POST["atts"])) {
         module('shop')->_basket_is_processed = true;
         return js_redirect("./?object=shop&action=product_details&id=" . $_GET["id"]);
     }
     if (!empty($_POST["quantity"]) && !module('shop')->_basket_is_processed) {
         foreach ((array) $_POST["quantity"] as $_product_id => $_quantity) {
             $_product_id = intval($_product_id);
             $_old_quantity = (int) module('shop')->_basket_api()->get($_product_id, 'quantity');
             $_quantity = intval($_quantity) + intval($_old_quantity);
             if ($_product_id && $_quantity) {
                 module('shop')->_basket_api()->set($_product_id, ["product_id" => $_product_id, "quantity" => $_quantity, "atts" => $_POST["atts"][$_product_id]]);
             }
         }
         // Prevent double processing
         module('shop')->_basket_is_processed = true;
     }
     return js_redirect("./?object=shop");
 }
Beispiel #6
0
 /**
  */
 function show()
 {
     $filter_name = $_GET['object'] . '__' . $_GET['action'];
     $default_filter = ['order_by' => 'date', 'order_direction' => 'desc'];
     $sql = 'SELECT * FROM ' . db('log_auth');
     return table($sql, ['filter' => (array) $_SESSION[$filter_name] + $default_filter, 'filter_params' => ['name' => 'like']])->user('user_id')->text('login')->link('group', './?object=user_groups&action=edit&id=%d', main()->get_data('user_groups'))->link('ip', './?object=' . $_GET['object'] . '&action=show_for_ip&id=%d')->date('date', ['format' => 'full', 'nowrap' => 1])->text('user_agent')->text('referer');
 }
function top_match()
{
    global $db, $allowHover, $llwars, $picformat, $sql_prefix;
    $qry = db("SELECT s1.datum,s1.cid,s1.id,s1.bericht,s1.xonx,s1.punkte,s1.gpunkte,s1.squad_id,s2.icon,s2.name FROM " . $db['cw'] . " AS s1\n             LEFT JOIN " . $db['squads'] . " AS s2 ON s1.squad_id = s2.id\n             WHERE `top` = '1'\n             ORDER BY RAND()");
    if ($get = _fetch($qry)) {
        //Clans Mod
        $clandetailssql = db("SELECT clantag, gegner FROM " . $sql_prefix . "clans WHERE id LIKE " . $get['cid']);
        $clans = _fetch($clandetailssql);
        $squad = '_defaultlogo.jpg';
        $gegner = '_defaultlogo.jpg';
        foreach ($picformat as $end) {
            if (file_exists(basePath . '/inc/images/clanwars/' . $get['cid'] . '_logo.' . $end)) {
                $gegner = $get['cid'] . '_logo.' . $end;
            }
            if (file_exists(basePath . '/inc/images/squads/' . $get['squad_id'] . '_logo.' . $end)) {
                $squad = $get['squad_id'] . '_logo.' . $end;
            }
        }
        if ($allowHover == 1 || $allowHover == 2) {
            $hover = 'onmouseover="DZCP.showInfo(\'<tr><td colspan=2 align=center padding=3 class=infoTop>' . jsconvert(re($get['name'])) . '<br/>vs.<br/> ' . jsconvert(re($clans['gegner'])) . '</td></tr><tr><td><b>' . _played_at . ':</b></td><td>' . date("d.m.Y H:i", $get['datum']) . _uhr . '</td></tr><tr><td><b>' . _cw_xonx . ':</b></td><td>' . jsconvert(re($get['xonx'])) . '</td></tr><tr><td><b>' . _result . ':</b></td><td>' . cw_result_nopic_raw($get['punkte'], $get['gpunkte']) . '</td></tr><tr><td><b>' . _comments_head . ':</b></td><td>' . cnt($db['cw_comments'], "WHERE cw = '" . $get['id'] . "'") . '</td></tr>\')" onmouseout="DZCP.hideInfo()"';
        }
        $topmatch .= show("menu/top_match", array("id" => $get['id'], "clantag" => re(cut($clans['clantag'], $llwars)), "team" => re(cut($get['name'], $llwars)), "game" => substr(strtoupper(str_replace('.' . $icon, '', re($get['icon']))), 0, 5), "id" => $get['id'], "gegner" => $gegner, "squad" => $squad, "hover" => $hover, "info" => $get['datum'] > time() ? date("d.m.Y", $get['datum']) : cw_result_nopic($get['punkte'], $get['gpunkte'])));
    }
    return empty($topmatch) ? '<center style="margin:3px 0">' . _no_top_match . '</center>' : '<table class="navContent" cellspacing="0">' . $topmatch . '</table>';
}
Beispiel #8
0
 /**
  * Track user error message
  *
  * @param	string
  * @return	void
  */
 function _track_error($error_message = "")
 {
     if (empty($error_message)) {
         return false;
     }
     // Try to get user error message source
     $backtrace = debug_backtrace();
     $cur_trace = $backtrace[1];
     $next_trace = $backtrace[2];
     // Prepare log text
     $text = "## LOG STARTS AT " . date("Y-m-d H:i:s") . "; QUERY_STRING: " . $_SERVER["QUERY_STRING"] . "; REFERER: " . $_SERVER["HTTP_REFERER"] . "; USER_ID: " . main()->USER_ID . "; USER_GROUP: " . main()->USER_GROUP . "; SITE_ID: " . SITE_ID . "; USER_AGENT: " . $_SERVER["HTTP_USER_AGENT"] . " ##\r\n";
     $text .= "URL: http://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"] . "\r\n";
     $text .= "SOURCE FILE: \"" . $cur_trace["file"] . "\" at LINE " . $cur_trace["line"] . "; " . (!empty($next_trace["class"]) ? "METHOD: " . $next_trace["class"] . "->" . $next_trace["function"] : "FUNCTION: " . $next_trace["function"]) . ";\r\n";
     $text .= "MESSAGE: " . $error_message . "\r\n";
     $text .= "## LOG ENDS ##\r\n";
     // Do add current error info to the log file
     $h = fopen(INCLUDE_PATH . $this->LOG_USER_ERRORS_FILE_NAME, "a");
     fwrite($h, $text);
     fclose($h);
     // Do store message into database (also check if that possible)
     if ($this->LOG_INTO_DB && is_object(db())) {
         $error_type = 0;
         db()->insert_safe('log_user_errors', ['error_level' => intval($error_type), 'error_text' => $error_message, 'source_file' => $cur_trace['file'], 'source_line' => intval($cur_trace['line']), 'date' => time(), 'site_id' => (int) conf('SITE_ID'), 'user_id' => intval($_SESSION[MAIN_TYPE_ADMIN ? 'admin_id' : 'user_id']), 'user_group' => intval($_SESSION[MAIN_TYPE_ADMIN ? 'admin_group' : 'user_group']), 'is_admin' => MAIN_TYPE_ADMIN ? 1 : 0, 'ip' => common()->get_ip(), 'query_string' => WEB_PATH . '?' . $_SERVER['QUERY_STRING'], 'user_agent' => $_SERVER['HTTP_USER_AGENT'], 'referer' => $_SERVER['HTTP_REFERER'], 'request_uri' => $_SERVER['REQUEST_URI'], 'env_data' => $this->DB_LOG_ENV ? $this->_prepare_env() : '', 'object' => $_GET['object'], 'action' => $_GET['action']]);
     }
 }
function InsertSalesType($SalesTypeDetails, $user, $password)
{
    $Errors = array();
    $db = db($user, $password);
    if (gettype($db) == 'integer') {
        $Errors[0] = NoAuthorisation;
        return $Errors;
    }
    $FieldNames = '';
    $FieldValues = '';
    foreach ($SalesTypeDetails as $key => $value) {
        $FieldNames .= $key . ', ';
        $FieldValues .= '"' . $value . '", ';
    }
    $sql = 'INSERT INTO salestypes (' . substr($FieldNames, 0, -2) . ') ' . 'VALUES (' . substr($FieldValues, 0, -2) . ') ';
    if (sizeof($Errors) == 0) {
        $result = DB_Query($sql, $db);
        if (DB_error_no($db) != 0) {
            $Errors[0] = DatabaseUpdateFailed;
        } else {
            $Errors[0] = 0;
        }
    }
    return $Errors;
}
Beispiel #10
0
function motm()
{
    global $db, $allowHover;
    $userpics = get_files(basePath . '/inc/images/uploads/userpics/');
    $qry = db("SELECT * FROM " . $db['users'] . " WHERE level >= 2");
    while ($rs = _fetch($qry)) {
        foreach ($userpics as $userpic) {
            $tmpId = intval($userpic);
            if ($tmpId == $rs['id']) {
                $temparr[] = $rs['id'];
                $a++;
                break;
            }
        }
    }
    $arrayID = rand(0, count($temparr) - 1);
    $uid = $temparr[$arrayID];
    $get = _fetch(db("SELECT * FROM " . $db['users'] . " WHERE id = '" . $uid . "'"));
    if (!empty($get) && !empty($temparr)) {
        $status = $get['status'] == 1 || $get['level'] == 1 ? _aktiv : _inaktiv;
        if ($allowHover == 1) {
            $info = 'onmouseover="DZCP.showInfo(\'<tr><td colspan=2 align=center padding=3 class=infoTop>' . rawautor($get['id']) . '</td></tr><tr><td width=80px><b>' . _posi . ':</b></td><td>' . getrank($get['id']) . '</td></tr><tr><td><b>' . _status . ':</b></td><td>' . $status . '</td></tr><tr><td><b>' . _age . ':</b></td><td>' . getAge($get['bday']) . '</td></tr><tr><td colspan=2 align=center>' . jsconvert(userpic($get['id'])) . '</td></tr>\')" onmouseout="DZCP.hideInfo()"';
        }
        $member = show("menu/motm", array("uid" => $get['id'], "upic" => userpic($get['id'], 130, 161), "info" => $info));
    } else {
        $member = '';
    }
    return empty($member) ? '' : '<table class="navContent" cellspacing="0">' . $member . '</table>';
}
Beispiel #11
0
 public function action(\Baguette\Application $app, \Teto\Routing\Action $action)
 {
     if ($app->session->get('user_id', ['default' => false])) {
         return new Response\RedirectResponse('/');
     }
     if (!$app->isTokenVerified) {
         return new Response\RedirectResponse('/');
     }
     // systemは特殊なユーザーなのでログインできない
     if (isset($_REQUEST['user'], $_REQUEST['password']) && $_REQUEST['user'] != 'system') {
         $user = trim($_REQUEST['user']);
         $pass = $_REQUEST['password'];
         $query = 'SELECT * FROM `users` WHERE `slug` = ?';
         $stmt = db()->prepare($query);
         $stmt->execute([$user]);
         if ($login = $stmt->fetch(\PDO::FETCH_ASSOC)) {
             $query = 'SELECT `password` FROM `user_passwords` WHERE `user_id` = ?';
             $stmt = db()->prepare($query);
             $stmt->execute([$login['id']]);
             $res = $stmt->fetch(\PDO::FETCH_ASSOC);
             if ($res && password($pass, $res['password']) === true) {
                 $app->refreshSession();
                 $app->session->set('user_id', $login['id']);
                 $app->session->set('user_slug', $login['slug']);
                 $app->session->set('user_name', $login['name']);
                 return new Response\RedirectResponse('/');
             }
         }
     }
     return new Response\TemplateResponse('login.tpl.html', ['user' => isset($_REQUEST['user']) ? $_REQUEST['user'] : null]);
 }
Beispiel #12
0
function is_installed()
{
    if (!db()) {
        return false;
    }
    return my_sql("SHOW COLUMNS FROM `user`");
}
Beispiel #13
0
 /**
  * Get geo info by IP from db
  */
 function _get_geo_data_from_db($cur_ip = "")
 {
     $cur_ip = trim(array_pop(explode(",", preg_replace("/[^0-9\\.,]/i", "", $cur_ip))));
     if (empty($cur_ip)) {
         return false;
     }
     if ($this->_is_ip_to_skip($cur_ip)) {
         return false;
     }
     $STORE_UNKNOWN_IPS = true;
     // Also check if IP is not recognized by our system and skip it
     if ($STORE_UNKNOWN_IPS && db()->query_num_rows("SELECT * FROM " . db('geo_skip_ip') . " WHERE ip = INET_ATON('" . _es($cur_ip) . "')")) {
         return false;
     }
     // Prepare query
     $sql = "SELECT * \n\t\t\tFROM " . db('geo_city_location') . " \n\t\t\tWHERE loc_id = ( \n\t\t\t\tSELECT loc_id FROM " . db('geo_city_blocks') . "\n\t\t\t\tWHERE start_ip <= INET_ATON('" . _es($cur_ip) . "') \n\t\t\t\t\tAND end_ip >= INET_ATON('" . _es($cur_ip) . "') \n\t\t\t\tLIMIT 1 \n\t\t\t)";
     $A = db()->query_fetch($sql);
     if (empty($A)) {
         if ($STORE_UNKNOWN_IPS) {
             db()->query("INSERT INTO " . db('geo_skip_ip') . " (\n\t\t\t\t\t\tip, hits\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\tINET_ATON('" . _es($cur_ip) . "'), 1\n\t\t\t\t\t) ON DUPLICATE KEY UPDATE hits = hits + 1");
         }
         return false;
     }
     $geo_data = ["country_code" => $A["country"], "country_name" => _country_name($A["country"]), "region_code" => $A["region"], "city_name" => $A["city"], "dma_code" => $A["dma_code"], "area_code" => $A["area_code"], "longitude" => $A["longitude"], "latitude" => $A["latitude"]];
     return $geo_data;
 }
Beispiel #14
0
function InsertGLAccountGroup($AccountGroupDetails, $user, $password)
{
    $Errors = array();
    $db = db($user, $password);
    if (gettype($db) == 'integer') {
        $Errors[0] = NoAuthorisation;
        return $Errors;
    }
    foreach ($AccountGroupDetails as $key => $value) {
        $AccountGroupDetails[$key] = DB_escape_string($value);
    }
    $Errors = VerifyAccountGroup($AccountGroupDetails['groupname'], sizeof($Errors), $Errors, $db);
    $Errors = VerifyAccountSectionExists($AccountGroupDetails['sectioninaccounts'], sizeof($Errors), $Errors, $db);
    if (isset($AccountGroupDetails['pandl'])) {
        $Errors = VerifyPandL($AccountGroupDetails['pandl'], sizeof($Errors), $Errors);
    }
    $Errors = VerifyParentGroupExists($AccountGroupDetails['parentgroupname'], sizeof($Errors), $Errors, $db);
    $FieldNames = '';
    $FieldValues = '';
    foreach ($AccountGroupDetails as $key => $value) {
        $FieldNames .= $key . ', ';
        $FieldValues .= '"' . $value . '", ';
    }
    if (sizeof($Errors) == 0) {
        $sql = 'INSERT INTO accountgroups (' . substr($FieldNames, 0, -2) . ') ' . 'VALUES (' . substr($FieldValues, 0, -2) . ') ';
        $result = DB_Query($sql, $db);
        if (DB_error_no($db) != 0) {
            $Errors[0] = DatabaseUpdateFailed;
        } else {
            $Errors[0] = 0;
        }
    }
    return $Errors;
}
 public function pertimeAction()
 {
     return;
     db()->exec("SELECT store_stats_graph('app', '2010-01-01', NOW()::date::text)");
     //		$stats = new Default_Model_AppStats($this->appType);
     //		$this->view->entries = $stats->perVO();
 }
Beispiel #16
0
function InsertGLAccountSection($AccountSectionDetails, $user, $password)
{
    $Errors = array();
    $db = db($user, $password);
    if (gettype($db) == 'integer') {
        $Errors[0] = NoAuthorisation;
        return $Errors;
    }
    foreach ($AccountSectionDetails as $key => $value) {
        $AccountSectionDetails[$key] = DB_escape_string($value);
    }
    $Errors = VerifyAccountSection($AccountSectionDetails['sectionname'], sizeof($Errors), $Errors, $db);
    if (isset($AccountSectionDetails['accountname'])) {
        $Errors = VerifySectionName($AccountSectionDetails['sectionname'], sizeof($Errors), $Errors);
    }
    $FieldNames = '';
    $FieldValues = '';
    foreach ($AccountSectionDetails as $key => $value) {
        $FieldNames .= $key . ', ';
        $FieldValues .= '"' . $value . '", ';
    }
    if (sizeof($Errors) == 0) {
        $sql = "INSERT INTO accountsection ('" . mb_substr($FieldNames, 0, -2) . "')\n\t\t\t\t\tVALUES ('" . mb_substr($FieldValues, 0, -2) . "')";
        $result = DB_Query($sql, $db);
        if (DB_error_no($db) != 0) {
            $Errors[0] = DatabaseUpdateFailed;
        } else {
            $Errors[0] = 0;
        }
    }
    return $Errors;
}
Beispiel #17
0
 public function getDBInstance() : \PDO
 {
     if ($this->pdo == null) {
         $this->pdo = db()->getInstance();
     }
     return $this->pdo;
 }
 function _site_map_items($sm_obj)
 {
     if (!is_object($sm_obj)) {
         return false;
     }
     $shop_cats = _class('cats')->_get_items_array('shop_cats');
     foreach ((array) $shop_cats as $cid => $c) {
         if (!$c['parent_id']) {
             $top_level[$cid] = $cid;
         }
     }
     foreach ((array) $top_level as $cid) {
         $c =& $shop_cats[$cid];
         if (!$c['active']) {
             unset($shop_cats[$cid]);
             continue;
         }
         $sm_obj->_store_item(['url' => url('/shop/products/' . $cid)]);
     }
     $q = db()->query('SELECT id FROM ' . db('shop_products') . ' WHERE active="1" AND image="1"');
     while ($a = db()->fetch_assoc($q)) {
         $sm_obj->_store_item(['url' => url('/shop/product/' . $a['id'])]);
     }
     return true;
 }
Beispiel #19
0
 static function getAdvs($position_id, $limit = 10)
 {
     $condition = " WHERE `position_id` = '" . $position_id . "' AND `status` = '" . self::ST_ON . "' ";
     $condition .= " AND `end_date` > '" . date('Y-m-d') . "' ";
     $result = db()->exec("SELECT `id`, `title`, `status`, `pic`, `uri`, `background`, `summary` FROM `" . self::fmTbl() . "` " . $condition . "  ORDER BY rand() LIMIT " . $limit);
     return 1 === $limit && !empty($result) ? $result[0] : $result;
 }
Beispiel #20
0
 function orders()
 {
     if (!main()->USER_ID) {
         if (main()->is_post()) {
             module('shop')->order_validate_data();
             // Display next form if we have no errors
             if (!common()->_error_exists()) {
                 return module('shop')->order_view(true);
             }
         }
         $items[] = ["order_id" => $_POST["order_id"], "email" => $_POST["email"], "form_action" => "./?object=shop&action=orders", "back_link" => "./?object=shop"];
     } else {
         $sql = "SELECT * FROM " . db('shop_orders') . " WHERE user_id=" . intval(main()->USER_ID);
         //$filter_sql = $this->PARENT_OBJ->USE_FILTER ? $this->PARENT_OBJ->_create_filter_sql() : "";
         $sql .= strlen($filter_sql) ? " WHERE 1=1 " . $filter_sql : " ORDER BY date DESC ";
         list($add_sql, $pages, $total) = common()->divide_pages($sql);
         $orders_info = db()->query_fetch_all($sql . $add_sql);
         if (!empty($orders_info)) {
             foreach ((array) $orders_info as $v) {
                 $user_ids[] = $v["user_id"];
             }
             $user_infos = user($user_ids);
         }
         foreach ((array) $orders_info as $v) {
             if ($v["status"] == "pending" or $v["status"] == "pending payment") {
                 $del = "./?object=shop&action=order_delete&id=" . $v["id"];
             } else {
                 $del = "";
             }
             $items[] = ["order_id" => $v["id"], "date" => _format_date($v["date"], "long"), "sum" => module('shop')->_format_price($v["total_sum"]), "user_link" => _profile_link($v["user_id"]), "user_name" => _display_name($user_infos[$v["user_id"]]), "status" => $v["status"], "delete_url" => $del, "view_url" => "./?object=shop&action=order_view&id=" . $v["id"]];
         }
     }
     $replace = ["error_message" => _e(), "items" => (array) $items, "pages" => $pages, "total" => intval($total), "filter" => module('shop')->USE_FILTER ? module('shop')->_show_filter() : ""];
     return tpl()->parse("shop/order_show", $replace);
 }
Beispiel #21
0
 public function table_settings()
 {
     $table = z(t(v('table')));
     $tables = get_table_list(db());
     if (!in_array($table, $tables)) {
         return info_page('<a href="javascript:history.back(1);">table不存在,点击返回</a>');
     }
     $data['fields'] = get_fields_info($table);
     $data['actions'] = array('list' => 'List', 'insert' => 'Insert', 'update' => 'Update', 'remove' => 'Remove');
     $data['table'] = $table;
     $data['my_actions'] = get_data("SELECT * FROM `__meta_code` WHERE `table` = '" . s($table) . "' ORDER BY `id` DESC");
     //print_r( $fields );
     $data['title'] = $data['top_title'] = 'API设置';
     $data['js'][] = 'codemirror.js';
     $data['js'][] = 'util/runmode.js';
     $data['js'][] = 'mode/php/php.js';
     $data['js'][] = 'mode/htmlmixed/htmlmixed.js';
     $data['js'][] = 'mode/css/css.js';
     $data['js'][] = 'mode/javascript/javascript.js';
     $data['js'][] = 'mode/xml/xml.js';
     $data['js'][] = 'mode/clike/clike.js';
     $data['css'][] = 'codemirror.css';
     $data['css'][] = 'theme/night.css';
     render($data);
 }
Beispiel #22
0
function insertElement()
{
    if (isset($_POST['ClassificationID'])) {
        $ClassificationID = json_decode(sanitize($_POST['ClassificationID']));
    }
    if (isset($_POST['Element'])) {
        $Element = json_decode(sanitize($_POST['Element']));
    }
    if (isset($_POST['AtomicMass'])) {
        $AtomicMass = json_decode(sanitize($_POST['AtomicMass']));
    }
    $dbConn = mysqli_connect(server(), username(), password(), db("Elements"));
    if ($dbConn->connect_error) {
        die("Connection failed: " . $dbConn->connect_error);
    }
    $query = "INSERT INTO Elements ( ClassificationID, Element, AtomicMass ) " . "VALUES ( " . "" . $ClassificationID . ", " . "'" . $Element . "', " . "" . $AtomicMass . " );";
    $result = $dbConn->query($query);
    $return = new stdClass();
    $return->querystring = (string) $query;
    if ($result) {
        $return->success = true;
    } else {
        $return->success = false;
    }
    return json_encode($return);
}
Beispiel #23
0
 public function oauth($tokenid)
 {
     $successURL = isset($_GET['returnurl']) ? $_GET['returnurl'] : new URL('auth', 'invalidReturn');
     $failureURL = isset($_GET['cancelurl']) ? $_GET['cancelurl'] : $successURL;
     $grant = isset($_GET['grant']) ? (int) $_GET['grant'] === 1 : null;
     $session = Session::getInstance();
     $token = db()->table('token')->get('token', $tokenid)->fetch();
     #No token, no access
     if (!$token) {
         throw new PublicException('No token', 404);
     }
     $this->view->set('token', $token);
     $this->view->set('cancelURL', $failureURL);
     $this->view->set('continue', (string) new URL('auth', 'oauth', $tokenid, array_merge($_GET->getRaw(), array('grant' => 1))));
     if (!$session->getUser()) {
         return $this->response->getHeaders()->redirect(new URL('user', 'login', array('returnto' => (string) URL::current())));
     }
     if ($grant === false) {
         return $this->response->getHeaders()->redirect($failureURL);
     }
     if ($grant === true) {
         $token->user = $this->user;
         $token->store();
         return $this->response->getHeaders()->redirect($successURL);
     }
 }
 function products_similar_by_basket($id)
 {
     $sql_order_id = "SELECT order_id FROM " . db('shop_order_items') . " WHERE product_id =  " . $id;
     $orders = db()->query($sql_order_id);
     while ($A = db()->fetch_assoc($orders)) {
         $order_id .= $A["order_id"] . ",";
     }
     $order_id = rtrim($order_id, ",");
     if (!empty($order_id)) {
         $sql_product_id = "SELECT product_id FROM " . db('shop_order_items') . " WHERE  order_id IN (  " . $order_id . ") AND product_id != " . $id;
         $products = db()->query($sql_product_id);
         while ($A = db()->fetch_assoc($products)) {
             $product_id .= $A["product_id"] . ",";
         }
         $product_id = rtrim($product_id, ",");
     }
     if (!empty($product_id)) {
         $sql = "SELECT * FROM " . db('shop_products') . " WHERE  id in ( " . $product_id . ")";
         $product = db()->query_fetch_all($sql);
         foreach ((array) $product as $k => $product_info) {
             $thumb_path = $product_info["url"] . "_" . $product_info["id"] . "_1" . module("shop")->THUMB_SUFFIX . ".jpg";
             $URL_PRODUCT_ID = module("shop")->_product_id_url($product_info);
             $items[$product_info["id"]] = ["name" => _prepare_html($product_info["name"]), "price" => module("shop")->_format_price(module("shop")->_product_get_price($product_info)), "currency" => _prepare_html(module("shop")->CURRENCY), "image" => file_exists(module("shop")->products_img_dir . $thumb_path) ? module("shop")->products_img_webdir . $thumb_path : "", "link" => $product_info["external_url"] ? $product_info["external_url"] : process_url("./?object=shop&action=product_details&id=" . $URL_PRODUCT_ID), "special" => ""];
         }
     }
     $replace = ["items" => $items, "title" => "Those who purchased this product also buy"];
     return tpl()->parse("shop/products_similar_by_price", $replace);
 }
Beispiel #25
0
 public static function import($datafile)
 {
     db('import')->echoOn();
     db('import')->beginTransaction();
     $data = Yaml::read($datafile);
     $schema = $data['schema'];
     $tables = $data['data'];
     $automap = array();
     foreach ($tables as $tableName => $rows) {
         foreach ($rows as $row) {
             $values = array();
             foreach ($row as $fieldName => $fieldValue) {
                 if (!isset($schema[$tableName]['auto']) || !in_array($fieldName, $schema[$tableName]['auto'])) {
                     $values[$fieldName] = $fieldValue;
                 }
             }
             if (isset($schema[$tableName]['refs'])) {
                 foreach ($schema[$tableName]['refs'] as $fieldName => $referee) {
                     $values[$fieldName] = $automap[$referee[0]][$referee[1]][$row[$fieldName]];
                 }
             }
             $id = db('import')->insertArray($tableName, $values);
             if (isset($row['id'])) {
                 $automap[$tableName]['id'][$row['id']] = $id;
             }
         }
     }
     db('import')->rollbackTransaction();
 }
Beispiel #26
0
 /**
  * Prepare DB for application settings
  * @return mixed
  */
 public function prepare()
 {
     db()->execute("\n                CREATE TABLE IF NOT EXISTS `email_distribution` (\n                  `distribution_id` int(11) NOT NULL AUTO_INCREMENT,\n                  `template_id` int(11) NOT NULL,\n                  `status` int(11) DEFAULT '0',\n                  `recipient_count` int(11) DEFAULT '0',\n                  `bounce_count` int(11) DEFAULT '0',\n                  `open_count` int(11) DEFAULT '0',\n                  `click_count` int(11) DEFAULT '0',\n                  `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,\n                  `finished` datetime NOT NULL,\n                  `active` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`distribution_id`)\n                ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;\n            ");
     db()->execute("\n                CREATE TABLE IF NOT EXISTS `email_letter` (\n                  `letter_id` int(11) NOT NULL AUTO_INCREMENT,\n                  `distribution_id` int(11) NOT NULL,\n                  `template_id` int(11) NOT NULL,\n                  `recipient` varchar(50) NOT NULL,\n                  `status` int(11) DEFAULT '0',\n                  `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,\n                  PRIMARY KEY (`letter_id`)\n                ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;\n            ");
     db()->execute("\n                CREATE TABLE IF NOT EXISTS `email_template` (\n                  `template_id` int(11) NOT NULL AUTO_INCREMENT,\n                  `content` text NOT NULL,\n                  `locale` varchar(5) NOT NULL DEFAULT 'en',\n                  `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,\n                  PRIMARY KEY (`template_id`)\n                ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;\n            ");
     return parent::prepare();
 }
Beispiel #27
0
function var_set($name, $value, $exp = 0)
{
    $db = db();
    $value = json_encode($value);
    $db->dquery('SELECT id FROM variable WHERE name = ":name"');
    $db->arg(':name', $name);
    $db->execute();
    $res = $db->fetch_single();
    if ($exp) {
        $exp = time() + $exp * 3600;
    }
    if (empty($res)) {
        $db->dquery('INSERT INTO variable (name, value, expires) VALUES (":name", ":value", :exp)');
        $db->arg(':name', $name);
        $db->arg(':value', $value);
        $db->arg(':exp', $exp);
        $db->execute();
    } else {
        $db->dquery('UPDATE variable SET name = ":name", value = ":value", expires = :exp WHERE id = :id;');
        $db->arg(':name', $name);
        $db->arg(':value', $value);
        $db->arg(':exp', $exp);
        $db->arg(':id', $res['id']);
        $db->execute();
    }
}
Beispiel #28
0
 public function startAttempt($quiz, $studentId = null)
 {
     db()->beginTransaction();
     if (empty($studentId)) {
         $studentId = studentId();
     }
     if (!empty($quiz['maxAttemptNum'])) {
         $numAttemptsUsed = field_sql('SELECT COUNT(quizAttemptId) FROM quiz_attempt WHERE quizId=:quizId AND studentId=:studentId', array('quizId' => $quiz['quizId'], 'studentId' => $studentId));
         if ($numAttemptsUsed >= $quiz['maxAttemptNum']) {
             throw new Exception('Attempt limit consumed', 403);
         }
     }
     $numAttemptsInproc = field_sql('SELECT COUNT(quizAttemptId) FROM quiz_attempt WHERE quizId=:quizId AND studentId=:studentId AND status=:status', array('quizId' => $quiz['quizId'], 'studentId' => $studentId, 'status' => STATUS_INPROC));
     if ($numAttemptsInproc > 0) {
         throw new Exception('Already started', 403);
     }
     entry_change('quiz_attempt', array('quizId' => $quiz['quizId'], 'studentId' => $studentId, 'status' => STATUS_INPROC, 'timeStart' => date('Y-m-d H:i:s')));
     $attemptId = db()->lastInsertId();
     $questions = entries_sql('SELECT questionId FROM question WHERE questionBaseId=:questionBaseId', array('questionBaseId' => $quiz['questionBaseId']));
     if (empty($questions)) {
         throw new Exception('Questions not found', 404);
     }
     shuffle($questions);
     $num = 1;
     foreach ($questions as $q) {
         if (!empty($quiz['numQuestion']) && $num > $quiz['numQuestion']) {
             break;
         }
         entry_change('question_session', array('num' => $num++, 'quizAttemptId' => $attemptId, 'questionId' => $q['questionId'], 'status' => STATUS_NEW));
     }
     db()->commit();
     return $attemptId;
 }
 public function removeava()
 {
     if (isset($_GET['avi_id']) && isset($_GET['cli_id'])) {
         $idAvis = $_GET['avi_id'];
         $idUser = $_GET['cli_id'];
         $st = db()->prepare("DELETE FROM T_J_AVISABUSIF_AVA WHERE avi_id=:avi and cli_id=:cli");
         $st->bindParam(':avi', $idAvis);
         $st->bindParam(':cli', $idUser);
         $st->execute();
         $m = new message();
         $m->setFlash("L'avis abusif a été ignoré", "success");
         header("Refresh:0; url=../Sprint/?r=src");
         //            $id = $_GET['avi_id'];
         //            $avis = new T_E_AVIS_AVI($id);
         //            if($avis->avi_id == null){
         //                $m = new message();
         //                $m->setFlash("Cet avis n'existe pas");
         //                header("Refresh:0; url=../Sprint/?r=src");
         //            } else {
         //                $avis->deleteAllAva();
         //                $m = new message();
         //                $m->setFlash("l'avis a bien été supprimé","success");
         //                header("Refresh:0; url=../Sprint/?r=src");
         //
         //            }
     }
 }
 public function search()
 {
     //quelque soit le mot il est mis en minuscule
     $motclef = strtolower($_POST["mot_clef"]);
     $srchConsole = $_POST["choiceconsole"];
     $srchRayon = $_POST["choicerayon"];
     $class = get_called_class();
     $table = strtolower($class);
     if ($srchConsole == "console") {
         if ($srchRayon == "rayon") {
             //console - et rayon -
             $st = db()->prepare("select * from t_e_jeuvideo_jeu j where (lower(jeu_nom) like '%" . $motclef . "%') or (jeu_id in (select w.jeu_id from t_e_motcle_mot w where lower(w.mot_mot) like '%" . $motclef . "%'))");
         } else {
             //console - et rayon +
             $st = db()->prepare("select * from t_e_jeuvideo_jeu j join t_r_console_con c on c.con_id = j.con_id join t_j_jeurayon_jer v on v.jeu_id = j.jeu_id join t_r_rayon_ray r on r.ray_id=v.ray_id where (lower(jeu_nom) like '%" . $motclef . "%' or j.jeu_id in (select w.jeu_id from t_e_motcle_mot w where lower(w.mot_mot) like '%" . $motclef . "%')) and  ray_nom like '%" . $srchRayon . "%'");
         }
     } else {
         if ($srchRayon == "rayon") {
             //console + et rayon -
             $st = db()->prepare("select * from t_e_jeuvideo_jeu j join t_r_console_con c on c.con_id = j.con_id where (lower(jeu_nom) like '%" . $motclef . "%' or j.jeu_id in (select w.jeu_id from t_e_motcle_mot w where lower(w.mot_mot) like '%" . $motclef . "%')) and con_nom like '%" . $srchConsole . "%'");
         } else {
             //console + et rayon +
             $st = db()->prepare("select * from t_e_jeuvideo_jeu j join t_r_console_con c on c.con_id = j.con_id join t_j_jeurayon_jer v on v.jeu_id = j.jeu_id join t_r_rayon_ray r on r.ray_id=v.ray_id where (lower(jeu_nom) like '%" . $motclef . "%' or j.jeu_id in (select w.jeu_id from t_e_motcle_mot w where lower(w.mot_mot) like '%" . $motclef . "%')) and  ray_nom like '%" . $srchRayon . "%' and con_nom like '%" . $srchConsole . "%'");
         }
         //join t_e_motcle_mot w on w.jeu_id=j.jeu_id     "lower(mot_mot) like '".$motclef."'"
     }
     $st->execute();
     $list = array();
     while ($row = $st->fetch(PDO::FETCH_ASSOC)) {
         $list[] = new T_e_jeuvideo_jeu($this->_jeu_id = $row["jeu_id"]);
     }
     $this->render("search", $list);
 }