Exemple #1
0
function payment_config($id)
{
    global $tpl, $template, $twig, $mysql, $SYSTEM_FLAGS, $config, $userROW, $lang, $CurrentHandler;
    $row = $mysql->record('SELECT * FROM ' . prefix . '_eshop_payment WHERE name = ' . db_squote($id) . ' LIMIT 1');
    if (isset($_REQUEST['submit'])) {
        $PARAMS['name'] = $id;
        $PARAMS['merchantid'] = $_REQUEST['merchantid'];
        $PARAMS['merchantpass'] = $_REQUEST['merchantpass'];
        $SQL['name'] = $id;
        $SQL['options'] = json_encode($PARAMS);
        if (empty($error_text)) {
            $vnames = array();
            foreach ($SQL as $k => $v) {
                $vnames[] = $k . ' = ' . db_squote($v);
            }
            $mysql->query("REPLACE INTO " . prefix . "_eshop_payment SET " . implode(', ', $vnames) . " ");
            redirect_eshop('?mod=extra-config&plugin=eshop&action=list_payment');
        }
    }
    /*
    foreach ($row as $k => $v) { 
        $tEntry[$k] = $v;
    }
    */
    $tEntry = array();
    $tEntry['name'] = $row['name'];
    $tEntry['options'] = json_decode($row['options'], true);
    $payment_config_tpl = dirname(__FILE__) . '/tpl/config.tpl';
    $xt = $twig->loadTemplate($payment_config_tpl);
    $tVars = array('entries' => isset($tEntry) ? $tEntry : '');
    $tpath = locatePluginTemplates(array('config/main'), 'eshop', 1);
    $xg = $twig->loadTemplate($tpath['config/main'] . 'config/' . 'main.tpl');
    $tVars = array('entries' => $xt->render($tVars), 'php_self' => $PHP_SELF, 'plugin_url' => admin_url . '/admin.php?mod=extra-config&plugin=eshop', 'skins_url' => skins_url, 'admin_url' => admin_url, 'home' => home, 'current_title' => '—истемы оплаты [' . $id . ']');
    print $xg->render($tVars);
}
Exemple #2
0
function payment_eshop()
{
    global $mysql, $twig, $userROW, $template, $ip, $SYSTEM_FLAGS, $lang;
    $filter = array();
    $SQL = array();
    $payment_name = "";
    $payment_options = array();
    $SQL['payment_id'] = filter_var($_REQUEST['payment_id'], FILTER_SANITIZE_STRING);
    if (empty($SQL['payment_id'])) {
        $error_text[] = 'ID платежной системы не задано';
    } else {
        $filter[] = '(name = ' . db_squote($SQL['payment_id']) . ')';
        $sqlQ = "SELECT * FROM " . prefix . "_eshop_payment " . (count($filter) ? "WHERE " . implode(" AND ", $filter) : '') . " LIMIT 1";
        $row = $mysql->record($sqlQ);
        if (empty($row)) {
            $error_text[] = 'Платежной системы с таким ID не существует или не заданы настройки';
        } else {
            $payment_name = $row['name'];
            $payment_options = json_decode($row['options'], true);
        }
    }
    if (empty($error_text)) {
        $payment_filename = dirname(__FILE__) . '/payment/' . $payment_name . '/payment.php';
        if (file_exists($payment_filename)) {
            include_once $payment_filename;
            payment_action($payment_name, $payment_options, $_REQUEST);
        } else {
            $error_text[] = "Файл {$payment_filename} не существует";
        }
    }
    if (!empty($error_text)) {
        foreach ($error_text as $error) {
            //$error_input .= msg(array("type" => "error", "text" => $error));
            $error_input .= "<p>" . $error . "</p>";
        }
    } else {
        $error_input = '';
    }
    $tVars = array('errors' => $error_text, 'errors_text' => $error_input);
    $tpath = locatePluginTemplates(array('payment_eshop'), 'eshop', pluginGetVariable('eshop', 'localsource'));
    $xt = $twig->loadTemplate($tpath['payment_eshop'] . 'payment_eshop.tpl');
    $template['vars']['mainblock'] = $xt->render($tVars);
    $SYSTEM_FLAGS['info']['title']['others'] = "";
    $SYSTEM_FLAGS['info']['title']['group'] = $lang['eshop']['name_payment'];
    $SYSTEM_FLAGS['meta']['description'] = "";
    $SYSTEM_FLAGS['meta']['keywords'] = "";
}
Exemple #3
0
function edit_currency($params)
{
    global $tpl, $template, $config, $mysql, $lang, $twig;
    $tpath = locatePluginTemplates(array('config/main', 'config/add_currencies'), 'eshop', 1);
    $id = intval($_REQUEST['id']);
    $row = $mysql->record('SELECT * FROM ' . prefix . '_eshop_currencies WHERE id = ' . db_squote($id) . ' LIMIT 1');
    if (isset($_REQUEST['submit'])) {
        $SQL['name'] = input_filter_com(convert($_REQUEST['name']));
        if (empty($SQL['name'])) {
            $error_text[] = 'Название валюты не задано';
        }
        $SQL['sign'] = input_filter_com(convert($_REQUEST['sign']));
        if (empty($SQL['sign'])) {
            $error_text[] = 'Знак валюты не задан';
        }
        $SQL['code'] = input_filter_com(convert($_REQUEST['code']));
        if (empty($SQL['code'])) {
            $error_text[] = 'Код валюты не задан';
        }
        $SQL['rate_from'] = input_filter_com(convert($_REQUEST['rate_from']));
        if (empty($SQL['rate_from'])) {
            $error_text[] = 'Конверсия не задана';
        }
        $SQL['rate_to'] = 1;
        $SQL['cents'] = 1;
        $SQL['position'] = input_filter_com(convert($_REQUEST['position']));
        if ($SQL['position'] == "") {
            $SQL['position'] = 0;
        }
        $SQL['enabled'] = input_filter_com(convert($_REQUEST['enabled']));
        if (empty($error_text)) {
            $vnames = array();
            foreach ($SQL as $k => $v) {
                $vnames[] = $k . ' = ' . db_squote($v);
            }
            $mysql->query('UPDATE ' . prefix . '_eshop_currencies SET ' . implode(', ', $vnames) . ' WHERE id = \'' . intval($id) . '\' ');
            generate_currency_cache(true);
            redirect_eshop('?mod=extra-config&plugin=eshop&action=list_currencies');
        }
    }
    if (!empty($error_text)) {
        foreach ($error_text as $error) {
            $error_input .= msg(array("type" => "error", "text" => $error));
        }
    } else {
        $error_input = '';
    }
    foreach ($row as $k => $v) {
        $tEntry[$k] = $v;
    }
    $tEntry['error'] = $error_input;
    $tEntry['mode'] = "edit";
    $xt = $twig->loadTemplate($tpath['config/add_currencies'] . 'config/' . 'add_currencies.tpl');
    $tVars = array('entries' => isset($tEntry) ? $tEntry : '');
    $xg = $twig->loadTemplate($tpath['config/main'] . 'config/' . 'main.tpl');
    $tVars = array('entries' => $xt->render($tVars), 'php_self' => $PHP_SELF, 'plugin_url' => admin_url . '/admin.php?mod=extra-config&plugin=eshop', 'skins_url' => skins_url, 'admin_url' => admin_url, 'home' => home, 'current_title' => 'Валюты: Редактирование валюты');
    print $xg->render($tVars);
}
        $filename = root . 'skins/default/lang/english/skin.ini';
        $content = parse_ini_file($filename, true);
    }
    if (!is_array($lang_askin)) {
        $lang_askin = array();
    }
    if ($area) {
        $lang_askin[$area] = $content;
    } else {
        $lang_askin = array_merge($lang_askin, $content);
    }
    return $lang_askin;
}
$lang = array_merge(LoadLang('index', 'admin'), LoadLang_askin());
if (is_array($userROW)) {
    $newpm = $mysql->result("SELECT count(pmid) FROM " . prefix . "_users_pm WHERE to_id = " . db_squote($userROW['id']) . " AND viewed = '0'");
    $newpm = $newpm != "0" ? '<span class="count-label">' . $newpm . '</span>' : '';
    // Calculate number of un-approved news
    $unapproved = '';
    if ($userROW['status'] == 1 || $userROW['status'] == 2) {
        $unapp1 = $mysql->result("SELECT count(id) FROM " . prefix . "_news WHERE approve = '-1'");
        $unapp2 = $mysql->result("SELECT count(id) FROM " . prefix . "_news WHERE approve = '0'");
        if ($unapp1) {
            $unapproved1 = '<a class="navbar-brand fr" href="' . $PHP_SELF . '?mod=news&status=1" title="Черновики"><i class="fa fa-pencil-square-o"></i> <span class="count-label">' . $unapp1 . '</span></a>';
        }
        if ($unapp2) {
            $unapproved2 = '<a class="navbar-brand fr" href="' . $PHP_SELF . '?mod=news&status=2" title="На модерации"><i class="fa fa-minus-circle"></i> <span class="count-label">' . $unapp2 . '</span></a>';
        }
    }
}
$skins_url = skins_url;
Exemple #5
0
 function editProfileForm($userID, $SQLrow, &$tvars)
 {
     global $mysql, $twig, $userROW, $template;
     $conditions = array();
     if ($userID) {
         array_push($conditions, "author_id = " . db_squote($userID));
     }
     $fSort = " ORDER BY id DESC";
     $sqlQPart = "FROM " . prefix . "_eshop_orders " . (count($conditions) ? "WHERE " . implode(" AND ", $conditions) : '') . $fSort;
     $sqlQ = "SELECT * " . $sqlQPart;
     foreach ($mysql->select($sqlQ) as $row) {
         $order_link = checkLinkAvailable('eshop', 'order') ? generateLink('eshop', 'order', array(), array('id' => $row['id'], 'uniqid' => $row['uniqid'])) : generateLink('core', 'plugin', array('plugin' => 'eshop', 'handler' => 'order'), array(), array('id' => $row['id'], 'uniqid' => $row['uniqid']));
         $row['order_link'] = $order_link;
         $tEntry[] = $row;
     }
     $tvars['eshop']['orders'] = $tEntry;
 }
Exemple #6
0
function payment_action($payment_name, $payment_options, $rData)
{
    global $tpl, $template, $config, $mysql, $lang, $twig, $SUPRESS_TEMPLATE_SHOW, $SYSTEM_FLAGS;
    $SUPRESS_TEMPLATE_SHOW = 1;
    $SUPRESS_MAINBLOCK_SHOW = 1;
    $current_time = time() + $config['date_adjust'] * 60;
    $result = intval($rData['result']);
    if (!empty($result)) {
        switch ($result) {
            case '1':
                // fail_url
                redirect_eshop(link_eshop());
                break;
            case '2':
                $rData['sign'] = str_replace(' ', '+', $rData['sign']);
                $rData['xml'] = str_replace(' ', '+', $rData['xml']);
                // result_url
                if (!empty($rData['xml']) and !empty($rData['sign'])) {
                    // Инициализация переменной для хранения сообщения об ошибке
                    $error = '';
                    // Декодируем входные параметры
                    $xml_encoded = str_replace(' ', '+', $rData['xml']);
                    $xml = base64_decode($xml_encoded);
                    // преобразуем входной xml в удобный для использования формат
                    $xml_vars = simplexml_load_string($xml);
                    //$file = '/home/s/stdex/air.tw1.ru/public_html/engine/plugins/eshop/eeeeee.txt';
                    //file_put_contents($file, strval($xml_vars), FILE_APPEND | LOCK_EX);
                    if ($xml_vars->order_id) {
                        $hidden_key = $payment_options['hidden_key'];
                        $sign = md5($hidden_key . $xml . $hidden_key);
                        $sign_encode = base64_encode($sign);
                        $a_or_id = explode("_", $xml_vars->order_id);
                        $zid = $a_or_id[1];
                        $merchant_id = (string) $xml_vars->merchant_id;
                        $order_id = (string) $xml_vars->order_id;
                        $amount = (string) $xml_vars->amount;
                        $currency = (string) $xml_vars->currency;
                        $description = (string) $xml_vars->description;
                        $description = iconv("utf-8", "windows-1251", $description);
                        $paymode = (string) $xml_vars->paymode;
                        $trans_id = (string) $xml_vars->trans_id;
                        $status = (string) $xml_vars->status;
                        $error_msg = (string) $xml_vars->error_msg;
                        $test_mode = (string) $xml_vars->test_mode;
                        $info = array('payment_name' => $payment_name, 'merchant_id' => $merchant_id, 'amount' => $amount, 'currency' => $currency, 'description' => $description, 'paymode' => $paymode, 'trans_id' => $trans_id, 'status' => $status, 'error_msg' => $error_msg, 'test_mode' => $test_mode);
                        if ($sign_encode == $rData['sign']) {
                            if ($status == 'success') {
                                $mysql->query('INSERT INTO ' . prefix . '_eshop_purchases (dt, order_id, info)
                                    VALUES
                                    (' . db_squote($current_time) . ',
                                        ' . db_squote($zid) . ',
                                        ' . db_squote(json_encode($info)) . '
                                    )
                                ');
                                $mysql->query('UPDATE ' . prefix . '_eshop_orders SET
                                    paid = 1
                                    WHERE id = ' . $zid . '
                                ');
                            }
                        } else {
                            $error = 'Incorrect sign';
                            //redirect_eshop(link_eshop());
                        }
                    } else {
                        $error = 'Unknown order_id';
                        //redirect_eshop(link_eshop());
                    }
                    // Отвечаем серверу Pay2Pay
                    if ($error == '') {
                        $ret = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n                        <result>\n                        <status>yes</status>\n                        <err_msg></err_msg>\n                        </result>";
                    } else {
                        $ret = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n                        <result>\n                        <status>no</status>\n                        <err_msg>{$error}</err_msg>\n                        </result>";
                    }
                    die($ret);
                }
                break;
            case '3':
                // success_url
                redirect_eshop(link_eshop());
                break;
            default:
                break;
        }
    } else {
        $filter = array();
        $SQL = array();
        $order_id = filter_var($rData['order_id'], FILTER_SANITIZE_STRING);
        $uniqid = filter_var($rData['order_uniqid'], FILTER_SANITIZE_STRING);
        if (empty($order_id) || empty($uniqid)) {
            redirect_eshop(link_eshop());
        } else {
            $filter[] = '(id = ' . db_squote($order_id) . ')';
            $filter[] = '(uniqid = ' . db_squote($uniqid) . ')';
            $sqlQ = "SELECT * FROM " . prefix . "_eshop_orders " . (count($filter) ? "WHERE " . implode(" AND ", $filter) : '') . " LIMIT 1";
            $row = $mysql->record($sqlQ);
            if ($row['paid'] == 1) {
                redirect_eshop(link_eshop());
            } elseif (!empty($row)) {
                $merchant_id = $payment_options['merchant_id'];
                // Идентификатор магазина в Pay2Pay
                $secret_key = $payment_options['secret_key'];
                // Секретный ключ
                $hash_order_id = $current_time . "_" . $order_id;
                // Номер заказа
                $amount = $row['total_price'];
                // Сумма заказа
                $currency = $SYSTEM_FLAGS['eshop']['currency'][0]['code'];
                // Валюта заказа
                $desc = 'Оплата по заказу ID: ' . $order_id;
                // Описание заказа
                $desc = iconv("windows-1251", "utf-8", $desc);
                $test_mode = $payment_options['test_mode'];
                // Тестовый режим
                // Формируем xml
                $xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n                 <request>\n                 <version>1.2</version>\n                 <merchant_id>{$merchant_id}</merchant_id>\n                 <language>ru</language>\n                 <order_id>{$hash_order_id}</order_id>\n                 <amount>{$amount}</amount>\n                 <currency>{$currency}</currency>\n                 <description>{$desc}</description>\n                 <test_mode>{$test_mode}</test_mode>\n                 <other><![CDATA[{$order_id}]]></other>\n                 </request>";
                // Вычисляем подпись
                $sign = md5($secret_key . $xml . $secret_key);
                // Кодируем данные в BASE64
                $xml_encode = base64_encode($xml);
                $sign_encode = base64_encode($sign);
                echo '
                <!DOCTYPE html><html><body>
                    <form id="b-site" action="https://merchant.pay2pay.com/?page=init" method="post">
                        <input type="hidden" name="xml" value="' . $xml_encode . '">
                        <input type="hidden" name="sign" value="' . $sign_encode . '">
                    </form>
                    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
                    <script>$("document").ready(function() {$("#b-site").submit();});</script>
                </body></html>';
                exit;
            } else {
                redirect_eshop(link_eshop());
            }
        }
    }
}
Exemple #7
0
function update_currency()
{
    global $tpl, $mysql, $twig, $parse, $SYSTEM_FLAGS;
    $rates_array = array();
    foreach ($SYSTEM_FLAGS['eshop']['currency'] as $currency) {
        if ($currency['code'] != "USD") {
            $code = $currency['code'];
            $q = $code . "_USD";
            $q_url = "http://free.currencyconverterapi.com/api/v3/convert?q=" . $q . "&compact=ultra";
            $get_rate = (array) json_decode(file_get_contents($q_url));
            $mysql->query('UPDATE ' . prefix . '_eshop_currencies SET rate_from = ' . db_squote($get_rate[$q]) . ' WHERE code =' . db_squote($code) . ' ');
            $rates_array[$q] = $get_rate[$q];
        }
    }
    generate_currency_cache(true);
    $rates_str = "";
    foreach ($rates_array as $k => $v) {
        $rates_str .= $k . ' = ' . $v . "<br/><br/>";
    }
    return $rates_str;
}
Exemple #8
0
function automation()
{
    global $tpl, $mysql, $twig;
    $tpath = locatePluginTemplates(array('config/main', 'config/automation'), 'eshop', 1);
    if (isset($_REQUEST['yml_url']) && !empty($_REQUEST['yml_url']) && isset($_REQUEST['import'])) {
        import_yml($_REQUEST['yml_url']);
        //$import_str = implode('<br/>',$_SESSION['import_yml']);
        //$info = "Импорт YML успешно завершен<br/><br/>".$import_str;
        $info = "Импорт YML успешно завершен";
        msg(array("type" => "info", "info" => $info));
    }
    if (isset($_REQUEST['currency'])) {
        $rates_str = update_currency();
        $info = "Валюты обновлены<br/><br/>" . $rates_str;
        msg(array("type" => "info", "info" => $info));
    }
    if (isset($_REQUEST['change_price'])) {
        $change_price_type = intval($_REQUEST['change_price_type']);
        $change_price_qnt = intval($_REQUEST['change_price_qnt']);
        update_prices($change_price_type, $change_price_qnt);
        $info = "Цены обновлены<br/>";
        msg(array("type" => "info", "info" => $info));
    }
    if (isset($_REQUEST['export_csv'])) {
        $SUPRESS_TEMPLATE_SHOW = 1;
        $SUPRESS_MAINBLOCK_SHOW = 1;
        require_once dirname(__FILE__) . '/csv_lib/CsvImportInterface.php';
        require_once dirname(__FILE__) . '/csv_lib/CsvImport.php';
        require_once dirname(__FILE__) . '/csv_lib/CsvExportInterface.php';
        require_once dirname(__FILE__) . '/csv_lib/CsvExport.php';
        $export = new CsvExport();
        $cat_array = array();
        foreach ($mysql->select('SELECT * FROM ' . prefix . '_eshop_categories ORDER BY position ASC') as $cat_row) {
            $catlink = checkLinkAvailable('eshop', '') ? generateLink('eshop', '', array('cat' => $cat_row['id'])) : generateLink('core', 'plugin', array('plugin' => 'eshop'), array('cat' => $cat_row['id']));
            $cat_array[] = array('id' => $cat_row['id'], 'url' => $cat_row['url'], 'image' => $cat_row['image'], 'name' => $cat_row['name'], 'description' => $cat_row['description'], 'parent_id' => $cat_row['parent_id'], 'position' => $cat_row['position'], 'meta_title' => $cat_row['meta_title'], 'meta_keywords' => $cat_row['meta_keywords'], 'meta_description' => $cat_row['meta_description'], 'link' => $catlink);
        }
        $conditions = array();
        array_push($conditions, "p.active = 1");
        //$limitCount = "10000";
        $fSort = " GROUP BY p.id ORDER BY p.id DESC ";
        $sqlQPart = "FROM " . prefix . "_eshop_products p LEFT JOIN " . prefix . "_eshop_products_categories pc ON p.id = pc.product_id LEFT JOIN " . prefix . "_eshop_categories c ON pc.category_id = c.id " . (count($conditions) ? "WHERE " . implode(" AND ", $conditions) : '') . $fSort;
        $sqlQ = "SELECT p.id AS id, p.url AS url, p.code AS code, p.name AS name, p.annotation AS annotation, p.body AS body, p.active AS active, p.featured AS featured, p.stocked AS stocked, p.position AS position, p.meta_title AS meta_title, p.meta_keywords AS meta_keywords, p.meta_description AS meta_description, p.date AS date, p.editdate AS editdate, p.views AS views, c.id AS cid, c.name AS category " . $sqlQPart;
        $entries = array();
        foreach ($mysql->select($sqlQ) as $row) {
            $entriesImg = array();
            foreach ($mysql->select('SELECT * FROM ' . prefix . '_eshop_images i WHERE i.product_id = ' . $row['id'] . ' ') as $row2) {
                $entriesImg[] = $row2['filepath'];
            }
            $entriesVariants = array();
            foreach ($mysql->select('SELECT * FROM ' . prefix . '_eshop_variants v WHERE v.product_id = ' . $row['id'] . ' ') as $vrow) {
                $entriesVariants[] = $vrow;
            }
            $options_array = array();
            foreach ($mysql->select("SELECT * FROM " . prefix . "_eshop_options LEFT JOIN " . prefix . "_eshop_features ON " . prefix . "_eshop_features.id=" . prefix . "_eshop_options.feature_id WHERE " . prefix . "_eshop_options.product_id = " . $row['id'] . " ORDER BY position, id") as $orow) {
                $options_array[$orow['id']] = $orow['value'];
            }
            $xf_name_id = array();
            $features_array = array();
            foreach ($mysql->select("SELECT * FROM " . prefix . "_eshop_features ORDER BY position, id") as $frow) {
                $frow['value'] = $options_array[$frow['id']];
                $frow['foptions'] = json_decode($frow['foptions'], true);
                foreach ($frow['foptions'] as $key => $value) {
                    $frow['foptions'][$key] = iconv("utf-8", "windows-1251", $value);
                }
                $features_array["xfields_" . $frow['name']] = $frow['value'];
                $xf_name_id[$frow['name']] = $frow['id'];
            }
            $images_comma_separated = implode(",", $entriesImg);
            $entry = array();
            $entry = array('id' => $row['id'], 'code' => $row['code'], 'url' => $row['url'], 'name' => $row['name'], 'variants' => $entriesVariants, 'annotation' => $row['annotation'], 'body' => $row['body'], 'active' => $row['active'], 'featured' => $row['featured'], 'stocked' => $row['stocked'], 'meta_title' => $row['meta_title'], 'meta_keywords' => $row['meta_keywords'], 'meta_description' => $row['meta_description'], 'date' => empty($row['date']) ? '' : $row['date'], 'editdate' => empty($row['editdate']) ? '' : $row['editdate'], 'cat_name' => $row['category'], 'cid' => $row['cid'], 'images' => $images_comma_separated);
            foreach ($features_array as $fk => $fv) {
                $entry[$fk] = $fv;
            }
            $entries[] = $entry;
        }
        $count = 0;
        foreach ($entries as $entry) {
            foreach ($entry['variants'] as $variant) {
                $entry_row = array();
                $entry_row = $entry;
                unset($entry_row['variants']);
                $entry_row['v_id'] = $variant['id'];
                $entry_row['v_sku'] = $variant['sku'];
                $entry_row['v_name'] = $variant['name'];
                $entry_row['v_price'] = $variant['price'];
                $entry_row['v_compare_price'] = $variant['compare_price'];
                $entry_row['v_stock'] = $variant['stock'];
                $entry_row['v_amount'] = $variant['amount'];
                if ($count == 0) {
                    $export->setHeader(array_keys($entry_row));
                }
                $count += 1;
                $export->append(array($entry_row));
                unset($entry_row);
            }
        }
        $export->export('products.csv', ';');
        die;
    }
    if (isset($_REQUEST['import_csv'])) {
        $SUPRESS_TEMPLATE_SHOW = 1;
        $SUPRESS_MAINBLOCK_SHOW = 1;
        if (is_uploaded_file($_FILES["filename"]["tmp_name"])) {
            require_once dirname(__FILE__) . '/csv_lib/CsvImportInterface.php';
            require_once dirname(__FILE__) . '/csv_lib/CsvImport.php';
            require_once dirname(__FILE__) . '/csv_lib/CsvExportInterface.php';
            require_once dirname(__FILE__) . '/csv_lib/CsvExport.php';
            $import = new CsvImport();
            $filepath = dirname(__FILE__) . "/import/" . $_FILES["filename"]["name"];
            move_uploaded_file($_FILES["filename"]["tmp_name"], $filepath);
            $import->setFile($filepath, 10000, ";");
            $items = $import->getRows();
            $xf_name_id = array();
            foreach ($mysql->select("SELECT * FROM " . prefix . "_eshop_features ORDER BY position, id") as $frow) {
                $xf_name_id[$frow['name']] = $frow['id'];
            }
            foreach ($items as $iv) {
                $current_time = time();
                $id = $iv['id'];
                $code = empty($iv['code']) ? "" : $iv['code'];
                $url = empty($iv['url']) ? "" : $iv['url'];
                $name = empty($iv['name']) ? "" : $iv['name'];
                $v_id = empty($iv['v_id']) ? "" : $iv['v_id'];
                $v_sku = empty($iv['v_sku']) ? "" : $iv['v_sku'];
                $v_name = empty($iv['v_name']) ? "" : $iv['v_name'];
                $v_price = empty($iv['v_price']) ? "" : $iv['v_price'];
                $v_compare_price = empty($iv['v_compare_price']) ? "" : $iv['v_compare_price'];
                $v_stock = empty($iv['v_stock']) ? "" : $iv['v_stock'];
                $v_amount = empty($iv['v_amount']) ? "" : $iv['v_amount'];
                if ($v_amount == '') {
                    $v_amount = 'NULL';
                }
                $annotation = empty($iv['annotation']) ? "" : $iv['annotation'];
                $body = empty($iv['body']) ? "" : $iv['body'];
                $active = empty($iv['active']) ? "1" : $iv['active'];
                $featured = empty($iv['featured']) ? "0" : $iv['featured'];
                $stocked = empty($iv['stocked']) ? "0" : $iv['stocked'];
                $meta_title = empty($iv['meta_title']) ? "" : $iv['meta_title'];
                $meta_keywords = empty($iv['meta_keywords']) ? "" : $iv['meta_keywords'];
                $meta_description = empty($iv['meta_description']) ? "" : $iv['meta_description'];
                $date = empty($iv['date']) ? $current_time : $iv['date'];
                $editdate = empty($iv['editdate']) ? $current_time : $iv['editdate'];
                $cat_name = empty($iv['cat_name']) ? "" : $iv['cat_name'];
                $cid = empty($iv['cid']) ? "0" : $iv['cid'];
                //$images = explode(',',$iv['images']);
                $xfields_items = array();
                foreach ($iv as $xfk => $xfv) {
                    preg_match("/xfields_/", $xfk, $find_xf);
                    if (isset($find_xf[0])) {
                        $xf_name = str_replace('xfields_', '', $xfk);
                        $xf_id = $xf_name_id[$xf_name];
                        $xfields_items[$xf_id] = $xfv;
                    }
                }
                if ($iv['id'] != "") {
                    $product_row = $mysql->record("SELECT * FROM " . prefix . "_eshop_products WHERE id=" . db_squote($iv['id']) . " ");
                    if (empty($product_row)) {
                        if ($url != "") {
                            if (!is_array($mysql->record("select id from " . prefix . "_eshop_products where url = " . db_squote($product_row["url"]) . " limit 1"))) {
                                $mysql->query("INSERT INTO " . prefix . "_eshop_products (`id`, `code`, `url`, `name`, `annotation`, `body`, `active`, `featured`, `stocked`, `meta_title`, `meta_keywords`, `meta_description`, `date`, `editdate`) VALUES ('{$id}','{$code}','{$url}','{$name}','{$annotation}','{$body}','{$active}','{$featured}','{$stocked}','{$meta_title}','{$meta_keywords}','{$meta_description}','{$date}','{$editdate}')");
                                $qid = $mysql->lastid('eshop_products');
                                import_upload_images($qid);
                                if (!empty($xfields_items)) {
                                    foreach ($xfields_items as $f_key => $f_value) {
                                        if ($f_value != '') {
                                            $mysql->query("INSERT INTO " . prefix . "_eshop_options (`product_id`, `feature_id`, `value`) VALUES ('{$qid}','{$f_key}','{$f_value}')");
                                        }
                                    }
                                }
                                $category_id = intval($cid);
                                if ($category_id != 0) {
                                    $mysql->query("INSERT INTO " . prefix . "_eshop_products_categories (`product_id`, `category_id`) VALUES ('{$qid}','{$category_id}')");
                                }
                                $mysql->query("INSERT INTO " . prefix . "_eshop_variants (`product_id`, `sku`, `name`, `price`, `compare_price`, `stock`, `amount`) VALUES ('{$qid}', '{$v_sku}', '{$v_name}', '{$v_price}', '{$v_compare_price}', '{$v_stock}', '{$v_amount}')");
                            }
                        }
                    } else {
                        if ($product_row["url"]) {
                            if (is_array($mysql->record("select id from " . prefix . "_eshop_products where url = " . db_squote($url) . " limit 1"))) {
                                $mysql->query("REPLACE INTO " . prefix . "_eshop_products (`id`, `code`, `url`, `name`, `annotation`, `body`, `active`, `featured`, `stocked`, `meta_title`, `meta_keywords`, `meta_description`, `date`, `editdate`) VALUES ('{$id}','{$code}','{$url}','{$name}','{$annotation}','{$body}','{$active}','{$featured}','{$stocked}','{$meta_title}','{$meta_keywords}','{$meta_description}','{$date}','{$editdate}')");
                                $qid = $product_row["id"];
                                import_upload_images($qid);
                                if (!empty($xfields_items)) {
                                    //$mysql->query("DELETE FROM ".prefix."_eshop_options WHERE product_id='$qid'");
                                    foreach ($xfields_items as $f_key => $f_value) {
                                        if ($f_value != '') {
                                            $mysql->query("REPLACE INTO " . prefix . "_eshop_options (`product_id`, `feature_id`, `value`) VALUES ('{$qid}','{$f_key}','{$f_value}')");
                                        }
                                    }
                                }
                                $category_id = intval($cid);
                                if ($category_id != 0) {
                                    //$mysql->query("DELETE FROM ".prefix."_eshop_products_categories WHERE product_id='$qid'");
                                    $mysql->query("REPLACE INTO " . prefix . "_eshop_products_categories (`product_id`, `category_id`) VALUES ('{$qid}','{$category_id}')");
                                } else {
                                    $mysql->query("DELETE FROM " . prefix . "_eshop_products_categories WHERE product_id='{$qid}'");
                                }
                                $SQLv = array();
                                $SQLv['product_id'] = $qid;
                                $SQLv['sku'] = $v_sku;
                                $SQLv['name'] = $v_name;
                                $SQLv['price'] = $v_price;
                                $SQLv['compare_price'] = $v_compare_price;
                                $SQLv['stock'] = $v_stock;
                                $SQLv['amount'] = $v_amount;
                                foreach ($SQLv as $k => $v) {
                                    $vnames[] = $k . ' = ' . db_squote($v);
                                }
                                if ($v_id != "") {
                                    $mysql->query('UPDATE ' . prefix . '_eshop_variants SET ' . implode(', ', $vnames) . ' WHERE id = \'' . intval($v_id) . '\'  ');
                                } else {
                                    $mysql->query("INSERT INTO " . prefix . "_eshop_variants (`product_id`, `sku`, `name`, `price`, `compare_price`, `stock`, `amount`) VALUES ('{$qid}', '{$v_sku}', '{$v_name}', '{$v_price}', '{$v_compare_price}', '{$v_stock}', '{$v_amount}')");
                                }
                                //$mysql->query("DELETE FROM ".prefix."_eshop_variants WHERE product_id='$qid'");
                                //$mysql->query("INSERT INTO ".prefix."_eshop_variants (`product_id`, `price`, `compare_price`, `stock`) VALUES ('$qid', '$price', '$compare_price', '$stock')");
                            }
                        }
                    }
                } else {
                    $mysql->query("INSERT INTO " . prefix . "_eshop_products (`code`, `url`, `name`, `annotation`, `body`, `active`, `featured`, `stocked`, `meta_title`, `meta_keywords`, `meta_description`, `date`, `editdate`) VALUES ('{$code}','{$url}','{$name}','{$annotation}','{$body}','{$active}','{$featured}','{$stocked}','{$meta_title}','{$meta_keywords}','{$meta_description}','{$date}','{$editdate}')");
                    $qid = $mysql->lastid('eshop_products');
                    import_upload_images($qid);
                    if (!empty($xfields_items)) {
                        foreach ($xfields_items as $f_key => $f_value) {
                            if ($f_value != '') {
                                $mysql->query("INSERT INTO " . prefix . "_eshop_options (`product_id`, `feature_id`, `value`) VALUES ('{$qid}','{$f_key}','{$f_value}')");
                            }
                        }
                    }
                    $category_id = intval($cid);
                    if ($category_id != 0) {
                        $mysql->query("INSERT INTO " . prefix . "_eshop_products_categories (`product_id`, `category_id`) VALUES ('{$qid}','{$category_id}')");
                    }
                    $mysql->query("INSERT INTO " . prefix . "_eshop_variants (`product_id`, `sku`, `name`, `price`, `compare_price`, `stock`, `amount`) VALUES ('{$qid}', '{$v_sku}', '{$v_name}', '{$v_price}', '{$v_compare_price}', '{$v_stock}', '{$v_amount}')");
                }
            }
            unlink($filepath);
            $info = "Импорт CSV завершен<br/>";
            msg(array("type" => "info", "info" => $info));
            die;
        } else {
            $info = "Ошибка загрузки файла<br/>";
            msg(array("type" => "info", "info" => $info));
            die;
        }
    }
    if (isset($_REQUEST['multiple_upload_images'])) {
        $images = $_REQUEST['data']['images'];
        if ($images != NULL) {
            foreach ($images as $inx_img => $img) {
                $img_parts = explode(".", $img);
                $img_s = explode("_", $img_parts[0]);
                $qid = $img_s[0];
                if ($qid != "") {
                    $prd_row = $mysql->record("select * from " . prefix . "_eshop_products where id = " . db_squote($qid) . " limit 1");
                    if (!is_array($prd_row)) {
                        break;
                    }
                    $positions_img = array();
                    foreach ($mysql->select("SELECT * FROM " . prefix . "_eshop_images WHERE product_id = '{$qid}' ORDER BY position, id") as $irow) {
                        $positions_img[] = $irow['position'];
                    }
                    if (!empty($positions_img)) {
                        $max_img_pos = max($positions_img) + 1;
                    } else {
                        $max_img_pos = 0;
                    }
                    $inx_img = $max_img_pos;
                    @mkdir($_SERVER['DOCUMENT_ROOT'] . '/uploads/eshop/products/' . $qid . '/', 0777);
                    @mkdir($_SERVER['DOCUMENT_ROOT'] . '/uploads/eshop/products/' . $qid . '/thumb', 0777);
                    $timestamp = time();
                    $iname = $timestamp . "-" . $img;
                    $temp_name = $_SERVER['DOCUMENT_ROOT'] . '/uploads/eshop/products/temp/' . $img;
                    $current_name = $_SERVER['DOCUMENT_ROOT'] . '/uploads/eshop/products/' . $qid . '/' . $iname;
                    rename($temp_name, $current_name);
                    $temp_name = $_SERVER['DOCUMENT_ROOT'] . '/uploads/eshop/products/temp/thumb/' . $img;
                    $current_name = $_SERVER['DOCUMENT_ROOT'] . '/uploads/eshop/products/' . $qid . '/thumb/' . $iname;
                    rename($temp_name, $current_name);
                    $mysql->query("INSERT INTO " . prefix . "_eshop_images (`filepath`, `product_id`, `position`) VALUES ('{$iname}','{$qid}','{$inx_img}')");
                }
            }
        }
        $info = "Изображения загружены<br/>";
        msg(array("type" => "info", "info" => $info));
    }
    $xt = $twig->loadTemplate($tpath['config/automation'] . 'config/' . 'automation.tpl');
    $yml_export_link = checkLinkAvailable('eshop', 'yml_export') ? generateLink('eshop', 'yml_export', array()) : generateLink('core', 'plugin', array('plugin' => 'eshop', 'handler' => 'yml_export'), array());
    $tVars = array('yml_export_link' => $yml_export_link, 'info' => '');
    $xg = $twig->loadTemplate($tpath['config/main'] . 'config/' . 'main.tpl');
    $tVars = array('entries' => $xt->render($tVars), 'php_self' => $PHP_SELF, 'plugin_url' => admin_url . '/admin.php?mod=extra-config&plugin=eshop', 'skins_url' => skins_url, 'admin_url' => admin_url, 'home' => home, 'current_title' => 'Автоматизация');
    print $xg->render($tVars);
}
Exemple #9
0
 /**
  * Добавляем элемент
  * @param $offer
  * @return bool
  */
 function Add($offer, $name, $url)
 {
     global $tpl, $mysql, $twig, $parse, $SYSTEM_FLAGS, $config;
     $description = iconv('utf-8', 'windows-1251', (string) $offer->description);
     $PROP = array();
     $PROP['id'] = (int) $offer->attributes()->id;
     $PROP['name'] = $name;
     $PROP['url'] = $url;
     $PROP['meta_title'] = $name;
     $PROP['annotation'] = str_replace('&nbsp;', ' ', $description);
     $PROP['date'] = time() + $config['date_adjust'] * 60;
     $PROP['editdate'] = $PROP['date'];
     $vnames = array();
     foreach ($PROP as $k => $v) {
         $vnames[] = $k . ' = ' . db_squote($v);
     }
     $result = $mysql->query('INSERT INTO ' . prefix . '_eshop_products SET ' . implode(', ', $vnames) . ' ');
     if ($result) {
         $qid = $mysql->lastid('eshop_products');
         if (count($offer->picture) > 0) {
             $pictures = $this->xml2array($offer->picture);
             $inx_img = 0;
             foreach ($pictures as $picture) {
                 try {
                     $rootpath = $_SERVER['DOCUMENT_ROOT'];
                     $url = substr($picture, 0, strpos($picture, '?') ? strpos($picture, '?') : strlen($picture));
                     $name = basename($url);
                     $file_path = $rootpath . "/uploads/eshop/products/temp/{$name}";
                     file_put_contents($file_path, file_get_contents($url));
                     $fileParts = pathinfo($file_path);
                     $extension = $fileParts['extension'];
                     $extensions = array_map('trim', explode(',', pluginGetVariable('eshop', 'ext_image')));
                     $pre_quality = pluginGetVariable('eshop', 'pre_quality');
                     if (!in_array($extension, $extensions)) {
                         return "0";
                     }
                     // CREATE THUMBNAIL
                     if ($extension == "jpg" || $extension == "jpeg") {
                         $src = imagecreatefromjpeg($file_path);
                     } else {
                         if ($extension == "png") {
                             $src = imagecreatefrompng($file_path);
                         } else {
                             $src = imagecreatefromgif($file_path);
                         }
                     }
                     list($width, $height) = getimagesize($file_path);
                     $newwidth = pluginGetVariable('eshop', 'width_thumb');
                     if ($width > $newwidth) {
                         $newheight = $height / $width * $newwidth;
                         $tmp = imagecreatetruecolor($newwidth, $newheight);
                         imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
                         $thumbname = $rootpath . "/uploads/eshop/products/temp/thumb/{$name}";
                         if (file_exists($thumbname)) {
                             unlink($thumbname);
                         }
                         imagejpeg($tmp, $thumbname, $pre_quality >= 10 && $pre_quality <= 100 ? $pre_quality : 100);
                         imagedestroy($src);
                         imagedestroy($tmp);
                     } else {
                         if ($extension == "jpg" || $extension == "jpeg") {
                             $src = imagecreatefromjpeg($file_path);
                         } else {
                             if ($extension == "png") {
                                 $src = imagecreatefrompng($file_path);
                             } else {
                                 $src = imagecreatefromgif($file_path);
                             }
                         }
                         imagejpeg($src, $file_path, $pre_quality >= 10 && $pre_quality <= 100 ? $pre_quality : 100);
                         $thumbname = $rootpath . "/uploads/eshop/products/temp/thumb/{$name}";
                         copy($file_path, $thumbname);
                         imagedestroy($src);
                     }
                     $newwidth = pluginGetVariable('eshop', 'pre_width');
                     if (isset($newwidth) && $newwidth != '0') {
                         if ($extension == "jpg" || $extension == "jpeg") {
                             $src = imagecreatefromjpeg($file_path);
                         } else {
                             if ($extension == "png") {
                                 $src = imagecreatefrompng($file_path);
                             } else {
                                 $src = imagecreatefromgif($file_path);
                             }
                         }
                         list($width, $height) = getimagesize($file_path);
                         $newheight = $height / $width * $newwidth;
                         $tmp = imagecreatetruecolor($newwidth, $newheight);
                         imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
                         $thumbname = $file_path;
                         imagejpeg($tmp, $thumbname, $pre_quality >= 10 && $pre_quality <= 100 ? $pre_quality : 100);
                         imagedestroy($src);
                         imagedestroy($tmp);
                     }
                     $img = $name;
                     $timestamp = time();
                     $iname = $timestamp . "-" . $img;
                     @mkdir($_SERVER['DOCUMENT_ROOT'] . '/uploads/eshop/products/' . $qid . '/', 0777);
                     @mkdir($_SERVER['DOCUMENT_ROOT'] . '/uploads/eshop/products/' . $qid . '/thumb', 0777);
                     $temp_name = $_SERVER['DOCUMENT_ROOT'] . '/uploads/eshop/products/temp/' . $img;
                     $current_name = $_SERVER['DOCUMENT_ROOT'] . '/uploads/eshop/products/' . $qid . '/' . $iname;
                     rename($temp_name, $current_name);
                     $temp_name = $_SERVER['DOCUMENT_ROOT'] . '/uploads/eshop/products/temp/thumb/' . $img;
                     $current_name = $_SERVER['DOCUMENT_ROOT'] . '/uploads/eshop/products/' . $qid . '/thumb/' . $iname;
                     rename($temp_name, $current_name);
                     $mysql->query("INSERT INTO " . prefix . "_eshop_images (`filepath`, `product_id`, `position`) VALUES ('{$iname}','{$qid}','{$inx_img}')");
                     $inx_img += 1;
                 } catch (Exception $ex) {
                     $this->eco('Ошибка: ' . $ex . '<br>');
                     return "0";
                 }
             }
         }
         $category_id = (int) $offer->categoryId;
         if ($category_id != 0) {
             $mysql->query("INSERT INTO " . prefix . "_eshop_products_categories (`product_id`, `category_id`) VALUES ('{$qid}','{$category_id}')");
         }
         $price = (string) $offer->price;
         $currencyId = (string) $offer->currencyId;
         $stock = "5";
         if (isset($price)) {
             foreach ($SYSTEM_FLAGS['eshop']['currency'] as $currency) {
                 if ($currencyId == "RUR") {
                     $currencyId = "RUB";
                 }
                 if ($currency['code'] == $currencyId) {
                     $price = $price / $SYSTEM_FLAGS['eshop']['currency'][0]['rate_from'] * $currency['rate_from'];
                 }
             }
             $mysql->query("DELETE FROM " . prefix . "_eshop_variants WHERE product_id='{$qid}'");
             $mysql->query("INSERT INTO " . prefix . "_eshop_variants (`product_id`, `price`, `stock`) VALUES ('{$qid}', '{$price}', '{$stock}')");
         }
         $returnArr = array();
         $returnArr[] = array_merge(['value' => $PROP['id']], array('name' => 'source_id'));
         foreach ($offer->children() as $element) {
             if (mb_strtolower($element->getName()) == 'param') {
                 $returnArr[] = array_merge(['value' => (string) $element], $this->getElementAttributes($element));
             }
             if (mb_strtolower($element->getName()) == 'url') {
                 $returnArr[] = array_merge(['value' => (string) $element], array('name' => 'source_url'));
             }
         }
         foreach ($returnArr as $el) {
             $f_name = iconv('utf-8', 'windows-1251', $el['name']);
             $feature_row = $mysql->record("select * from " . prefix . "_eshop_features where name = " . db_squote($f_name) . " limit 1");
             if (!is_array($feature_row)) {
                 $mysql->query('INSERT INTO ' . prefix . '_eshop_features (name) VALUES (' . db_squote($f_name) . ')');
                 $rowID = $mysql->lastid('eshop_features');
                 $f_key = $rowID;
             } else {
                 $f_key = $feature_row['id'];
             }
             $f_value = iconv('utf-8', 'windows-1251', $el['value']);
             if ($f_value != "") {
                 $mysql->query("INSERT INTO " . prefix . "_eshop_options (`product_id`, `feature_id`, `value`) VALUES ('{$qid}','{$f_key}','{$f_value}')");
             }
         }
     }
 }
Exemple #10
0
function payment_action($payment_name, $payment_options, $rData)
{
    global $tpl, $template, $config, $mysql, $lang, $twig, $SUPRESS_TEMPLATE_SHOW, $SYSTEM_FLAGS;
    $SUPRESS_TEMPLATE_SHOW = 1;
    $SUPRESS_MAINBLOCK_SHOW = 1;
    $current_time = time() + $config['date_adjust'] * 60;
    $result = intval($rData['result']);
    if (!empty($result)) {
        switch ($result) {
            case '1':
                // fail_url
                redirect_eshop(link_eshop());
                break;
            case '2':
                // result_url
                $method = $rData['method'];
                $params = $rData['params'];
                $secretKey = $payment_options['secretKey'];
                if ($method == 'check') {
                    $message = 'CHECK is successful';
                    return json_encode(array("jsonrpc" => "2.0", "result" => array("message" => $message)));
                } elseif ($method == 'pay') {
                    if ($params['sign'] == getMd5Sign($params, $secretKey)) {
                        $merchant_purse = $params;
                        $amount = $rData['OutSum'];
                        $order_id = intval($rData['InvId']);
                        $info = array('payment_name' => $payment_name, 'merchant_purse' => $merchant_purse, 'amount' => $amount, 'order_id' => $order_id);
                        $mysql->query('INSERT INTO ' . prefix . '_eshop_purchases (dt, order_id, info)
                            VALUES
                            (' . db_squote($current_time) . ',
                                ' . db_squote($order_id) . ',
                                ' . db_squote(json_encode($info)) . '
                            )
                        ');
                        $mysql->query('UPDATE ' . prefix . '_eshop_orders SET
                            paid = 1
                            WHERE id = ' . $order_id . '
                        ');
                        $message = 'PAY is successful';
                        return json_encode(array("jsonrpc" => "2.0", "result" => array("message" => $message)));
                    } else {
                        $message = 'Incorrect digital signature';
                        return json_encode(array("jsonrpc" => "2.0", "error" => array("code" => -32000, "message" => $message)));
                    }
                } else {
                    $message = $method . ' not supported';
                    return json_encode(array("jsonrpc" => "2.0", "error" => array("code" => -32000, "message" => $message)));
                }
                break;
            case '3':
                // success_url
                redirect_eshop(link_eshop());
                break;
            default:
                break;
        }
    } else {
        $filter = array();
        $SQL = array();
        $order_id = filter_var($rData['order_id'], FILTER_SANITIZE_STRING);
        $uniqid = filter_var($rData['order_uniqid'], FILTER_SANITIZE_STRING);
        if (empty($order_id) || empty($uniqid)) {
            redirect_eshop(link_eshop());
        } else {
            $filter[] = '(id = ' . db_squote($order_id) . ')';
            $filter[] = '(uniqid = ' . db_squote($uniqid) . ')';
            $sqlQ = "SELECT * FROM " . prefix . "_eshop_orders " . (count($filter) ? "WHERE " . implode(" AND ", $filter) : '') . " LIMIT 1";
            $row = $mysql->record($sqlQ);
            if ($row['paid'] == 1) {
                redirect_eshop(link_eshop());
            } elseif (!empty($row)) {
                if (!empty($_SERVER['REMOTE_ADDR'])) {
                    $ip = $_SERVER['REMOTE_ADDR'];
                } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
                } elseif (!empty($_SERVER['HTTP_CLIENT_IP'])) {
                    $ip = $_SERVER['HTTP_CLIENT_IP'];
                }
                $paymentType = "card";
                $sum = $row['total_price'];
                $account = $order_id;
                $projectId = $payment_options['projectId'];
                $secretKey = $payment_options['secretKey'];
                $desc = 'Оплата по заказу ID: ' . $order_id;
                $account = $order_id;
                $fail_url = home . '/eshop/payment/?result=1&payment_id=unitpay';
                $result_url = home . '/eshop/payment/?result=2&payment_id=unitpay';
                $success_url = home . '/eshop/payment/?result=3&payment_id=unitpay';
                $currency = $SYSTEM_FLAGS['eshop']['currency'][0]['code'];
                // build URL
                $url = "https://unitpay.ru/api?method=initPayment&" . "params[paymentType]={$paymentType}&params[sum]={$sum}&params[account]={$account}&params[projectId]={$projectId}&params[secretKey]={$secretKey}&params[ip]={$ip}&params[resultUrl]={$success_url}&params[currency]={$currency}";
                header('Location: ' . $url . '');
                exit;
            } else {
                redirect_eshop(link_eshop());
            }
        }
    }
}
Exemple #11
0
function edit_message($mid)
{
    global $tpl, $mysql, $lang, $twig, $config;
    $tpath = locatePluginTemplates(array('config/main', 'config/messages_edit'), 'guestbook', 1);
    if (!empty($mid) || isset($_REQUEST['id'])) {
        $id = isset($mid) ? intval($mid) : intval($_REQUEST['id']);
    }
    // get fields
    $fdata = $mysql->select("SELECT * FROM " . prefix . "_guestbook_fields");
    if (!empty($id)) {
        $row = $mysql->record('SELECT * FROM ' . prefix . '_guestbook WHERE id = ' . db_squote($id) . ' LIMIT 1');
        if (isset($_REQUEST['submit'])) {
            $errors = array();
            $author = $_REQUEST['author'];
            $status = $_REQUEST['status'];
            $message = str_replace(array("\r\n", "\r"), "\n", convert($_REQUEST['message']));
            $answer = str_replace(array("\r\n", "\r"), "\n", convert($_REQUEST['answer']));
            if (empty($author) || empty($message)) {
                $errors[] = $lang['gbconfig']['msge_field_required'];
            }
            $upd_rec = array('message' => db_squote($message), 'answer' => db_squote($answer), 'author' => db_squote($author), 'status' => db_squote($status));
            if (preg_match('#^(\\d+)\\.(\\d+)\\.(\\d+) +(\\d+)\\:(\\d+)$#', $_REQUEST['cdate'], $m)) {
                $upd_rec['postdate'] = mktime($m[4], $m[5], 0, $m[2], $m[1], $m[3]) + $config['date_adjust'] * 60;
            }
            foreach ($fdata as $fnum => $frow) {
                if (!empty($_REQUEST[$frow['id']])) {
                    $upd_rec[$frow['id']] = db_squote($_REQUEST[$frow['id']]);
                } elseif (intval($frow['required']) === 1) {
                    $errors[] = $lang['gbconfig']['msge_field_required'];
                } else {
                    $upd_rec[$frow['id']] = "''";
                }
            }
            // prepare query
            $upd_str = '';
            $count = 0;
            foreach ($upd_rec as $k => $v) {
                $upd_str .= $k . '=' . $v;
                $count++;
                if ($count < count($upd_rec)) {
                    $upd_str .= ', ';
                }
            }
            if (!count($errors)) {
                $mysql->query('UPDATE ' . prefix . '_guestbook SET ' . $upd_str . ' WHERE id = \'' . intval($id) . '\' ');
                msg(array("text" => $lang['gbconfig']['msgo_edit_success']));
                return TRUE;
            } else {
                msg(array("type" => "error", "text" => implode($errors)));
            }
        }
        // output social data
        $social = unserialize($row['social']);
        $profiles = array();
        foreach ($social as $name => $sid) {
            $img = $mysql->record("SELECT name, description FROM " . prefix . "_images WHERE id = {$sid}");
            $profiles[$name] = array('photo' => $config['images_url'] . '/' . $img['name'], 'link' => $img['description']);
        }
        // output fields data
        $tFields = array();
        foreach ($fdata as $fnum => $frow) {
            $tField = array('id' => $frow['id'], 'name' => $frow['name'], 'placeholder' => $frow['placeholder'], 'default_value' => $frow['default_value'], 'required' => intval($frow['required']), 'value' => $row[$frow['id']]);
            $tFields[] = $tField;
        }
    } else {
        msg(array("type" => "error", "text" => "Не передан id"));
    }
    $xt = $twig->loadTemplate($tpath['config/messages_edit'] . 'config/messages_edit.tpl');
    $tVars = array('skins_url' => skins_url, 'home' => home, 'tpl_home' => admin_url, 'id' => $id, 'message' => $row['message'], 'answer' => $row['answer'], 'author' => $row['author'], 'status' => $row['status'], 'ip' => $row['ip'], 'postdate' => $row['postdate'], 'fields' => $tFields, 'social' => $profiles);
    $xg = $twig->loadTemplate($tpath['config/main'] . 'config/main.tpl');
    $tVars = array('entries' => $xt->render($tVars));
    print $xg->render($tVars);
}
Exemple #12
0
function ebasket_rpc_manage($params)
{
    global $userROW, $DSlist, $mysql, $twig;
    LoadPluginLibrary('xfields', 'common');
    if (!is_array($params) || !isset($params['action'])) {
        return array('status' => 0, 'errorCode' => 1, 'errorText' => iconv("windows-1251", "utf-8", 'Параметр действия не задан'));
    }
    $params = arrayCharsetConvert(1, $params);
    switch ($params['action']) {
        // **** ADD NEW ITEM INTO ebasket ****
        case 'add':
            $linked_ds = intval($params['ds']);
            $linked_id = intval($params['id']);
            $count = intval($params['count']);
            $variant_id = intval($params['variant_id']);
            // Check available DataSources
            if (!in_array($linked_ds, array($DSlist['news']))) {
                return array('status' => 0, 'errorCode' => 2, 'errorText' => iconv("windows-1251", "utf-8", 'Плагин поддерживает работу только с элементами продукции'));
            }
            // Check available DataSources
            if ($count < 1) {
                return array('status' => 0, 'errorCode' => 3, 'errorText' => iconv("windows-1251", "utf-8", 'Количество продукции должно быть положительным'));
            }
            // Check if linked item is available
            switch ($linked_ds) {
                case $DSlist['news']:
                    $conditions = array();
                    if ($linked_id) {
                        array_push($conditions, "p.id = " . db_squote($linked_id));
                    }
                    if ($variant_id != 0) {
                        array_push($conditions, "v.id = " . db_squote($variant_id));
                    }
                    $fSort = " GROUP BY p.id ORDER BY p.id DESC";
                    $sqlQPart = "FROM " . prefix . "_eshop_products p LEFT JOIN " . prefix . "_eshop_products_categories pc ON p.id = pc.product_id LEFT JOIN " . prefix . "_eshop_categories c ON pc.category_id = c.id LEFT JOIN (SELECT * FROM " . prefix . "_eshop_images ORDER BY position, id) i ON i.product_id = p.id LEFT JOIN " . prefix . "_eshop_variants v ON p.id = v.product_id " . (count($conditions) ? "WHERE " . implode(" AND ", $conditions) : '') . $fSort;
                    $sqlQ = "SELECT p.id AS id, p.url as url, p.code AS code, p.name AS name, p.active AS active, p.featured AS featured, p.position AS position, c.url as curl, c.name AS category, i.filepath AS image_filepath, v.id AS v_id, v.sku AS v_sku, v.name AS v_name, v.amount AS v_amount, v.price AS price, v.compare_price AS compare_price, v.stock AS stock " . $sqlQPart;
                    // Retrieve news record
                    $rec = $mysql->record($sqlQ);
                    if (!is_array($rec)) {
                        return array('status' => 0, 'errorCode' => 4, 'errorText' => iconv("windows-1251", "utf-8", 'Продукт с ID (' . $linked_id . ') не найден'));
                    }
                    if ($rec['v_amount'] != NULL) {
                        if ($count > $rec['v_amount']) {
                            return array('status' => 0, 'errorCode' => 5, 'errorText' => iconv("windows-1251", "utf-8", 'Нет требуемого количества продукта с ID (' . $linked_id . '). Можно заказать только ' . $rec['v_amount'] . ''));
                        }
                    }
                    $btitle = $rec['name'];
                    $price = $rec['price'];
                    $view_link = checkLinkAvailable('eshop', 'show') ? generateLink('eshop', 'show', array('alt' => $rec['url'])) : generateLink('core', 'plugin', array('plugin' => 'eshop', 'handler' => 'show'), array('alt' => $rec['url']));
                    $rec['view_link'] = $view_link;
                    // Add data into basked
                    return ebasket_add_item($linked_ds, $linked_id, $btitle, $price, $count, array('item' => $rec));
                    break;
            }
            break;
        case 'update':
            return basket_update();
            break;
        case 'update_count':
            $id = intval($params['id']);
            $linked_ds = intval($params['linked_ds']);
            $linked_id = intval($params['linked_id']);
            $count = intval($params['count']);
            return basket_update_item_count($id, $linked_ds, $linked_id, $count);
            break;
        case 'delete':
            $id = intval($params['id']);
            $linked_ds = intval($params['linked_ds']);
            $linked_id = intval($params['linked_id']);
            return basket_delete_item($id, $linked_ds, $linked_id);
            break;
        case 'add_fast':
            $linked_ds = intval($params['ds']);
            $linked_id = intval($params['id']);
            $count = intval($params['count']);
            $variant_id = intval($params['variant_id']);
            $type = intval($params['type']);
            $order['name'] = filter_var($params['name'], FILTER_SANITIZE_STRING);
            if (empty($order['name'])) {
                return array('status' => 0, 'errorCode' => 6, 'errorText' => iconv("windows-1251", "utf-8", 'Не заполнено поле имя'));
            }
            $order['email'] = "";
            $order['phone'] = filter_var($params['phone'], FILTER_SANITIZE_STRING);
            if (empty($order['phone'])) {
                return array('status' => 0, 'errorCode' => 7, 'errorText' => iconv("windows-1251", "utf-8", 'Не заполнено поле телефон'));
            }
            $order['address'] = filter_var($params['address'], FILTER_SANITIZE_STRING);
            if (empty($order['address'])) {
                return array('status' => 0, 'errorCode' => 8, 'errorText' => iconv("windows-1251", "utf-8", 'Не заполнено поле адрес'));
            }
            // Check available DataSources
            if (!in_array($linked_ds, array($DSlist['news']))) {
                return array('status' => 0, 'errorCode' => 2, 'errorText' => iconv("windows-1251", "utf-8", 'Плагин поддерживает работу только с элементами продукции'));
            }
            // Check available DataSources
            if ($count < 1) {
                $count = 1;
            }
            $conditions = array();
            if ($linked_id) {
                array_push($conditions, "p.id = " . db_squote($linked_id));
            }
            if ($variant_id != 0) {
                array_push($conditions, "v.id = " . db_squote($variant_id));
            }
            $fSort = " GROUP BY p.id ORDER BY p.id DESC";
            $sqlQPart = "FROM " . prefix . "_eshop_products p LEFT JOIN " . prefix . "_eshop_products_categories pc ON p.id = pc.product_id LEFT JOIN " . prefix . "_eshop_categories c ON pc.category_id = c.id LEFT JOIN (SELECT * FROM " . prefix . "_eshop_images ORDER BY position, id) i ON i.product_id = p.id LEFT JOIN " . prefix . "_eshop_variants v ON p.id = v.product_id " . (count($conditions) ? "WHERE " . implode(" AND ", $conditions) : '') . $fSort;
            $sqlQ = "SELECT p.id AS id, p.url as url, p.code AS code, p.name AS name, p.active AS active, p.featured AS featured, p.position AS position, c.url as curl, c.name AS category, i.filepath AS image_filepath, v.id AS v_id, v.sku AS v_sku, v.name AS v_name, v.amount AS v_amount, v.price AS price, v.compare_price AS compare_price, v.stock AS stock " . $sqlQPart;
            // Retrieve news record
            $rec = $mysql->record($sqlQ);
            if (!is_array($rec)) {
                return array('status' => 0, 'errorCode' => 4, 'errorText' => iconv("windows-1251", "utf-8", 'Продукт с ID (' . $linked_id . ') не найден'));
            }
            if ($rec['v_amount'] != NULL) {
                if ($count > $rec['v_amount']) {
                    return array('status' => 0, 'errorCode' => 5, 'errorText' => iconv("windows-1251", "utf-8", 'Нет требуемого количества продукта с ID (' . $linked_id . '). Можно заказать только ' . $rec['v_amount'] . ''));
                }
            }
            $btitle = $rec['name'];
            $price = $rec['price'];
            $view_link = checkLinkAvailable('eshop', 'show') ? generateLink('eshop', 'show', array('alt' => $rec['url'])) : generateLink('core', 'plugin', array('plugin' => 'eshop', 'handler' => 'show'), array('alt' => $rec['url']));
            $rec['view_link'] = $view_link;
            // Add data into basked
            return ebasket_add_fast_order($linked_ds, $linked_id, $btitle, $price, $count, $type, $order, array('item' => $rec));
            break;
    }
    return array('status' => 1, 'errorCode' => 0, 'data' => iconv("windows-1251", "utf-8", 'OK, ' . var_export($params, true)));
}
Exemple #13
0
function payment_action($payment_name, $payment_options, $rData)
{
    global $tpl, $template, $config, $mysql, $lang, $twig, $SUPRESS_TEMPLATE_SHOW, $SYSTEM_FLAGS;
    $SUPRESS_TEMPLATE_SHOW = 1;
    $SUPRESS_MAINBLOCK_SHOW = 1;
    $current_time = time() + $config['date_adjust'] * 60;
    $result = intval($rData['result']);
    if (!empty($result)) {
        switch ($result) {
            case '1':
                // fail_url
                redirect_eshop(link_eshop());
                break;
            case '2':
                // result_url
                // Кошелек продавца, на который покупатель совершил платеж. Формат - буква и 12 цифр.
                $merchant_purse = $rData['LMI_PAYEE_PURSE'];
                // Сумма, которую заплатил покупатель. Дробная часть отделяется точкой.
                $amount = $rData['OutSum'];
                // Внутренний номер покупки продавца
                // В этом поле передается id заказа в нашем магазине.
                $order_id = intval($rData['InvId']);
                // Контрольная подпись
                $crc = strtoupper($rData['SignatureValue']);
                $mrh_pass2 = $payment_options['mrh_pass2'];
                // Проверяем контрольную подпись
                $my_crc = strtoupper(md5("{$amount}:{$order_id}:{$mrh_pass2}"));
                if ($my_crc !== $crc) {
                    die("bad sign\n");
                }
                $info = array('payment_name' => $payment_name, 'merchant_purse' => $merchant_purse, 'amount' => $amount, 'order_id' => $order_id);
                $mysql->query('INSERT INTO ' . prefix . '_eshop_purchases (dt, order_id, info)
                    VALUES
                    (' . db_squote($current_time) . ',
                        ' . db_squote($order_id) . ',
                        ' . db_squote(json_encode($info)) . '
                    )
                ');
                $mysql->query('UPDATE ' . prefix . '_eshop_orders SET
                    paid = 1
                    WHERE id = ' . $order_id . '
                ');
                die("OK" . $order_id . "\n");
                break;
            case '3':
                // success_url
                redirect_eshop(link_eshop());
                break;
            default:
                break;
        }
    } else {
        $filter = array();
        $SQL = array();
        $order_id = filter_var($rData['order_id'], FILTER_SANITIZE_STRING);
        $uniqid = filter_var($rData['order_uniqid'], FILTER_SANITIZE_STRING);
        if (empty($order_id) || empty($uniqid)) {
            redirect_eshop(link_eshop());
        } else {
            $filter[] = '(id = ' . db_squote($order_id) . ')';
            $filter[] = '(uniqid = ' . db_squote($uniqid) . ')';
            $sqlQ = "SELECT * FROM " . prefix . "_eshop_orders " . (count($filter) ? "WHERE " . implode(" AND ", $filter) : '') . " LIMIT 1";
            $row = $mysql->record($sqlQ);
            if ($row['paid'] == 1) {
                redirect_eshop(link_eshop());
            } elseif (!empty($row)) {
                $mrh_login = $payment_options['mrh_login'];
                $mrh_pass1 = $payment_options['mrh_pass1'];
                $test_mode = $payment_options['test_mode'];
                $inv_id = $order_id;
                $inv_desc = 'Оплата по заказу ID: ' . $order_id;
                $out_summ = $row['total_price'];
                $OutSumCurrency = $SYSTEM_FLAGS['eshop']['currency'][0]['code'];
                $shp_item = 1;
                $in_curr = "";
                $culture = "ru";
                $IsTest = $test_mode;
                $crc = md5("{$mrh_login}:{$out_summ}:{$inv_id}:{$OutSumCurrency}:{$mrh_pass1}:Shp_item={$shp_item}");
                // build URL
                $url = "https://auth.robokassa.ru/Merchant/Index.aspx?MrchLogin={$mrh_login}&" . "OutSum={$out_summ}&InvId={$inv_id}&Desc={$inv_desc}&OutSumCurrency={$OutSumCurrency}&SignatureValue={$crc}&IsTest={$IsTest}";
                header('Location: ' . $url . '');
                exit;
            } else {
                redirect_eshop(link_eshop());
            }
        }
    }
}
Exemple #14
0
function ebasket_rpc_manage($params)
{
    global $userROW, $DSlist, $mysql, $twig;
    LoadPluginLibrary('xfields', 'common');
    if (!is_array($params) || !isset($params['action'])) {
        return array('status' => 0, 'errorCode' => 1, 'errorText' => 'Activity mode is not set');
    }
    $params = arrayCharsetConvert(1, $params);
    switch ($params['action']) {
        // **** ADD NEW ITEM INTO ebasket ****
        case 'add':
            $linked_ds = intval($params['ds']);
            $linked_id = intval($params['id']);
            $count = intval($params['count']);
            // Check available DataSources
            if (!in_array($linked_ds, array($DSlist['news']))) {
                return array('status' => 0, 'errorCode' => 2, 'errorText' => 'ebasket can be used only for NEWS');
            }
            // Check available DataSources
            if ($count < 1) {
                return array('status' => 0, 'errorCode' => 2, 'errorText' => 'Count should be positive');
            }
            // Check if linked item is available
            switch ($linked_ds) {
                case $DSlist['news']:
                    $conditions = array();
                    if ($linked_id) {
                        array_push($conditions, "p.id = " . db_squote($linked_id));
                    }
                    $fSort = " GROUP BY p.id ORDER BY p.id DESC";
                    $sqlQPart = "FROM " . prefix . "_eshop_products p LEFT JOIN " . prefix . "_eshop_products_categories pc ON p.id = pc.product_id LEFT JOIN " . prefix . "_eshop_categories c ON pc.category_id = c.id LEFT JOIN (SELECT * FROM " . prefix . "_eshop_images ORDER BY position, id) i ON i.product_id = p.id LEFT JOIN " . prefix . "_eshop_variants v ON p.id = v.product_id " . (count($conditions) ? "WHERE " . implode(" AND ", $conditions) : '') . $fSort;
                    $sqlQ = "SELECT p.id AS id, p.url as url, p.code AS code, p.name AS name, p.active AS active, p.featured AS featured, p.position AS position, c.url as curl, c.name AS category, i.filepath AS image_filepath, v.price AS price, v.compare_price AS compare_price, v.stock AS stock " . $sqlQPart;
                    // Retrieve news record
                    $rec = $mysql->record($sqlQ);
                    if (!is_array($rec)) {
                        return array('status' => 0, 'errorCode' => 3, 'errorText' => 'Item [news] with ID (' . $linked_id . ') is not found');
                    }
                    $btitle = $rec['name'];
                    $price = $rec['price'];
                    $view_link = checkLinkAvailable('eshop', 'show') ? generateLink('eshop', 'show', array('alt' => $rec['url'])) : generateLink('core', 'plugin', array('plugin' => 'eshop', 'handler' => 'show'), array('alt' => $rec['url']));
                    $rec['view_link'] = $view_link;
                    // Add data into basked
                    return ebasket_add_item($linked_ds, $linked_id, $btitle, $price, $count, array('item' => $rec));
                    break;
            }
            break;
        case 'update_count':
            $id = intval($params['id']);
            $linked_ds = intval($params['linked_ds']);
            $linked_id = intval($params['linked_id']);
            $count = intval($params['count']);
            return basket_update_item_count($id, $linked_ds, $linked_id, $count);
            break;
        case 'delete':
            $id = intval($params['id']);
            $linked_ds = intval($params['linked_ds']);
            $linked_id = intval($params['linked_id']);
            return basket_delete_item($id, $linked_ds, $linked_id);
            break;
        case 'add_fast':
            $linked_ds = intval($params['ds']);
            $linked_id = intval($params['id']);
            $count = intval($params['count']);
            $type = intval($params['type']);
            $order['name'] = filter_var($params['name'], FILTER_SANITIZE_STRING);
            if (empty($order['name'])) {
                return array('status' => 0, 'errorCode' => 3, 'errorText' => 'Item [news] with ID (' . $linked_id . ') is not found');
            }
            $order['email'] = "";
            $order['phone'] = filter_var($params['phone'], FILTER_SANITIZE_STRING);
            if (empty($order['phone'])) {
                return array('status' => 0, 'errorCode' => 3, 'errorText' => 'Item [news] with ID (' . $linked_id . ') is not found');
            }
            $order['address'] = filter_var($params['address'], FILTER_SANITIZE_STRING);
            if (empty($order['address'])) {
                return array('status' => 0, 'errorCode' => 3, 'errorText' => 'Item [news] with ID (' . $linked_id . ') is not found');
            }
            // Check available DataSources
            if (!in_array($linked_ds, array($DSlist['news']))) {
                return array('status' => 0, 'errorCode' => 2, 'errorText' => 'ebasket can be used only for NEWS');
            }
            // Check available DataSources
            if ($count < 1) {
                $count = 1;
            }
            $conditions = array();
            if ($linked_id) {
                array_push($conditions, "p.id = " . db_squote($linked_id));
            }
            $fSort = " GROUP BY p.id ORDER BY p.id DESC";
            $sqlQPart = "FROM " . prefix . "_eshop_products p LEFT JOIN " . prefix . "_eshop_products_categories pc ON p.id = pc.product_id LEFT JOIN " . prefix . "_eshop_categories c ON pc.category_id = c.id LEFT JOIN (SELECT * FROM " . prefix . "_eshop_images ORDER BY position, id) i ON i.product_id = p.id LEFT JOIN " . prefix . "_eshop_variants v ON p.id = v.product_id " . (count($conditions) ? "WHERE " . implode(" AND ", $conditions) : '') . $fSort;
            $sqlQ = "SELECT p.id AS id, p.url as url, p.code AS code, p.name AS name, p.active AS active, p.featured AS featured, p.position AS position, c.url as curl, c.name AS category, i.filepath AS image_filepath, v.price AS price, v.compare_price AS compare_price, v.stock AS stock " . $sqlQPart;
            // Retrieve news record
            $rec = $mysql->record($sqlQ);
            if (!is_array($rec)) {
                return array('status' => 0, 'errorCode' => 3, 'errorText' => 'Item [news] with ID (' . $linked_id . ') is not found');
            }
            $btitle = $rec['name'];
            $price = $rec['price'];
            $view_link = checkLinkAvailable('eshop', 'show') ? generateLink('eshop', 'show', array('alt' => $row['url'])) : generateLink('core', 'plugin', array('plugin' => 'eshop', 'handler' => 'show'), array('alt' => $row['url']));
            $rec['view_link'] = $view_link;
            // Add data into basked
            return ebasket_add_fast_order($linked_ds, $linked_id, $btitle, $price, $count, $type, $order, array('item' => $rec));
            break;
    }
    return array('status' => 1, 'errorCode' => 0, 'data' => 'OK, ' . var_export($params, true));
}
function guestbook_social()
{
    global $config, $template, $tpl, $mysql;
    session_start();
    $providers = array('Vkontakte', 'Facebook', 'Google', 'Instagram');
    $auth_config = array("base_url" => home . "/engine/plugins/guestbook/lib/hybridauth/", "providers" => array("Vkontakte" => array("enabled" => true, "keys" => array("id" => pluginGetVariable('guestbook', 'vk_client_id'), "secret" => pluginGetVariable('guestbook', 'vk_client_secret'))), "Facebook" => array("enabled" => true, "keys" => array("id" => pluginGetVariable('guestbook', 'facebook_client_id'), "secret" => pluginGetVariable('guestbook', 'facebook_client_secret')), "scope" => "email", "display" => "popup", "auth_type" => "reauthenticate"), "Google" => array("enabled" => true, "keys" => array("id" => pluginGetVariable('guestbook', 'google_client_id'), "secret" => pluginGetVariable('guestbook', 'google_client_secret')), "scope" => "https://www.googleapis.com/auth/userinfo.profile", "display" => "popup", "approval_prompt" => "force"), "Instagram" => array("enabled" => true, "keys" => array("id" => pluginGetVariable('guestbook', 'instagram_client_id'), "secret" => pluginGetVariable('guestbook', 'instagram_client_secret')))));
    if (isset($_GET['provider']) && in_array($_GET['provider'], $providers)) {
        $provider = $_GET['provider'];
        require_once $_SERVER['DOCUMENT_ROOT'] . '/engine/plugins/guestbook/lib/hybridauth/Hybrid/Auth.php';
        try {
            $hybridauth = new Hybrid_Auth($auth_config);
            $adapter = $hybridauth->authenticate($provider);
        } catch (Exception $e) {
            echo "<script>self.close();</script>\n";
        }
        $user_profile = $adapter->getUserProfile();
        // print_r($user_profile);
        // exit;
        $profile = $provider == 'Instagram' ? 'https://www.instagram.com/' . $user_profile->username : $user_profile->profileURL;
        $photo = $user_profile->photoURL;
        if (!empty($photo)) {
            // Prevent duplicate uploads
            $exist = $mysql->record("SELECT id FROM " . prefix . "_images WHERE description = " . db_squote($profile) . " LIMIT 1");
            if (!empty($exist['id'])) {
                $rowID = $exist;
            } else {
                addToFiles('newavatar', $photo);
                @(include_once root . 'includes/classes/upload.class.php');
                // UPLOAD AVATAR
                if ($_FILES['newavatar']['name']) {
                    $imanage = new image_managment();
                    $fname = $provider . '_' . time() . '_' . strtolower($_FILES['newavatar']['name']);
                    if (!strpos($fname, '.jpg')) {
                        $fname .= '.jpg';
                    }
                    $ftmp = $_FILES['newavatar']['tmp_name'];
                    $mysql->query("INSERT INTO " . prefix . "_images (name, orig_name, description, folder, date, owner_id, category) VALUES (" . db_squote($fname) . ", " . db_squote($fname) . ", " . db_squote($profile) . ", '', unix_timestamp(now()), '1', '0')");
                    $rowID = $mysql->record("select LAST_INSERT_ID() as id");
                    if (copy($ftmp, $config['images_dir'] . $fname)) {
                        $sz = $imanage->get_size($config['images_dir'] . $fname);
                        $mysql->query("update " . prefix . "_images set width=" . db_squote($sz['1']) . ", height=" . db_squote($sz['2']) . " where id = " . db_squote($rowID['id']) . " ");
                    }
                }
            }
            $adapter->logout();
            echo "<script>window.opener.document.getElementById('" . $provider . "_li').className += 'active'; " . "window.opener.document.getElementById('" . $provider . "_id').value = " . $rowID['id'] . "; self.close();</script>\n";
        }
    }
}