/** * @param array $params Parameters for creating an account * username, password, email are required * language, first_name, last_name are optional * @return array */ public function create($params) { $params = $this->filter_parameters($params, array('username', 'password', 'first_name', 'last_name', 'email', 'language')); $v = new \Valitron\Validator($params); $v->rules(['required' => [['username'], ['password'], ['email'], ['language']]]); $used_values = null; $return_errors = null; if ($v->validate()) { if ($this->get_user_id($params['username']) !== false) { $used_values[] = 'username'; } if ($this->email_used($params['email'])) { $used_values[] = 'email'; } if ($used_values === null) { $v->rule('email', 'email'); if ($v->validate()) { $v->rules(['lengthMax' => [['username', 20]]]); if ($v->validate()) { $params['password'] = create_hash($params['password']); $sql = "INSERT INTO user ("; foreach ($params as $key => $value) { $sql .= $key . ","; } $sql = substr($sql, 0, -1); $sql .= ") VALUES ("; foreach ($params as $key => $value) { $sql .= " :" . $key . ","; $params[':' . $key] = $value; } $sql = substr($sql, 0, -1); $sql .= ")"; $query = $this->db->prepare($sql); $query->execute($params); $user_id = $this->get_user_id($params['username']); $auth = new Token($this->db); require_once 'core/Mail.php'; $mail = new Mail(); $mail->addAddress($params['email'], $params['username']); $mail->isHTML(true); $mail->Subject = "Welcome to buckbrowser"; $mail->Body = str_replace(['%username%', '%bb-link%'], [$params['username'], 'http://buckbrowser.langstra.nl'], file_get_contents(TEMPLATE_PATH . 'mail/signup.html')); $mail->send(); return array('token' => $auth->create_token($user_id)); } else { $return_errors['incorrect_fields'] = 'username'; } } else { $return_errors['incorrect_fields'] = 'email'; } } else { $return_errors['already_exists'] = $used_values; } } else { $return_errors['empty_fields'] = array_keys($v->errors()); } return $this->create_error($return_errors); }
/** * Update User Configuration * * @param string $username * @param string $password0 * @param string $password1 * @param string $email * @param string $language * @param optional string $firstname * @param optional string $lastname * * @author Nikita Rousseau */ public function updateUserConfig($username, $password0, $password1, $email, $language, $firstname = '', $lastname = '') { $form = array('username' => $username, 'password0' => $password0, 'password1' => $password1, 'email' => $email, 'language' => $language); $errors = array(); // array to hold validation errors $data = array(); // array to pass back data $dbh = Core_DBH::getDBH(); // Get Database Handle // Get languages $languages = parse_ini_file(CONF_LANG_INI); $languages = array_flip(array_values($languages)); // validate the variables ====================================================== $v = new Valitron\Validator($form); $rules = ['required' => [['username'], ['password0'], ['password1'], ['email'], ['language']], 'alphaNum' => [['username']], 'lengthMin' => [['username', 4], ['password0', 8]], 'equals' => [['password0', 'password1']], 'email' => [['email']], 'in' => [['language', $languages]]]; $labels = array('username' => 'Username', 'password0' => 'Password', 'password1' => 'Confirmation Password', 'email' => 'Email', 'language' => 'Language'); $v->rules($rules); $v->labels($labels); $v->validate(); $errors = $v->errors(); // Apply the form ============================================================== if (empty($errors)) { // Database update $db_data['username'] = $form['username']; $db_data['password'] = Core_AuthService::getHash($form['password0']); $db_data['email'] = $form['email']; $db_data['lang'] = $form['language']; if (!empty($firstname)) { $db_data['firstname'] = $firstname; } if (!empty($lastname)) { $db_data['lastname'] = $lastname; } $authService = Core_AuthService::getAuthService(); $uid = Core_AuthService::getSessionInfo('ID'); foreach ($db_data as $key => $value) { $sth = $dbh->prepare("\tUPDATE " . DB_PREFIX . "user\n\t\t\t\t\t\t\t\t\t\tSET " . $key . " = :" . $key . "\n\t\t\t\t\t\t\t\t\t\tWHERE user_id = '" . $uid . "';"); $sth->bindParam(':' . $key, $value); $sth->execute(); } // Reload Session $authService->rmSessionInfo(); $authService->setSessionInfo($uid, $db_data['username'], $db_data['firstname'], $db_data['lastname'], $db_data['lang'], BGP_USER_TEMPLATE); $authService->setSessionPerms(); $this->rmCookie('LANG'); } // return a response =========================================================== // response if there are errors if (!empty($errors)) { // if there are items in our errors array, return those errors $data['success'] = false; $data['errors'] = $errors; $data['msgType'] = 'warning'; $data['msg'] = T_('Bad Settings!'); } else { $data['success'] = true; } // return all our data to an AJAX call return $data; }
protected function validate($queryParams) { $v = new \Valitron\Validator($queryParams); $v->rules($this->rules); if (!$v->validate()) { throw new ValidationFailed($v->errors()); } }
function validate($array, $rules) { require_once $_SERVER['DOCUMENT_ROOT'] . '/vendor/autoload.php'; $v = new Valitron\Validator($array); // Input array from $_POST/$_GET/Custom array $v->rules($rules); $v->labels(array('fname' => 'First Name', 'lname' => 'Last Name', 'phone' => 'Phone Number', 'email' => 'Email address', 'dob' => 'Date of Birth', 'streetAddress' => 'Street Address')); if (!$v->validate()) { foreach ($v->errors() as $field => $messages) { echo implode(', ', $messages) . ". "; } die; } }
/** * @param array $params Parameters for creating a contact * token, company, first_name, last_name, email, street_name, house_number, zipcode, place_name are required * id_country, default_payment_term, default_auto_reminder are optional * @return array */ public function create($params) { $params = $this->filter_parameters($params, array('token', 'company', 'first_name', 'last_name', 'email', 'street_name', 'house_number', 'zipcode', 'place_name', 'id_country', 'default_payment_term', 'default_auto_reminder')); $v = new \Valitron\Validator($params); $v->rules(['required' => [['token'], ['company'], ['first_name'], ['last_name'], ['email'], ['street_name'], ['house_number'], ['zipcode'], ['place_name']]]); $return_errors = null; if ($v->validate()) { if (($token = $this->token->validate($params['token'])) !== false) { $v->rule('email', 'email'); if ($v->validate()) { unset($params['token']); $sql = "INSERT INTO contact ("; foreach ($params as $key => $value) { $sql .= $key . ","; } $sql .= "id_company"; $sql .= ") VALUES ("; foreach ($params as $key => $value) { $sql .= " :" . $key . ","; $params[':' . $key] = $value; } $sql .= ":id_company"; $sql .= ")"; $params[":id_company"] = $token['id_company']; $query = $this->db->prepare($sql); $this->db->beginTransaction(); if (!$query->execute($params)) { $this->db->rollBack(); return $this->what_error(); } else { $id = $this->db->lastInsertId(); $this->db->commit(); return ['id' => $id]; } } else { $return_errors['incorrect_fields'] = 'email'; } } else { return $this->auth_error(); } } else { $return_errors['empty_fields'] = array_keys($v->errors()); } return $this->create_error($return_errors); }
/** * @param array $params Parameters for creating a template * token, name, content * @return array */ public function create($params) { $params = $this->filter_parameters($params, array('token', 'name', 'content')); $v = new \Valitron\Validator($params); $v->rules(['required' => [['token'], ['name'], ['content']]]); $return_errors = null; if ($v->validate()) { if (($token = $this->token->validate($params['token'])) !== false) { if ($v->validate()) { unset($params['token']); $sql = "INSERT INTO template ("; foreach ($params as $key => $value) { $sql .= $key . ","; } $sql .= "id_company"; $sql .= ") VALUES ("; foreach ($params as $key => $value) { $sql .= " :" . $key . ","; $params[':' . $key] = $value; } $sql .= ":id_company"; $sql .= ")"; $params[":id_company"] = $token['id_company']; $query = $this->db->prepare($sql); $this->db->beginTransaction(); if (!$query->execute($params)) { $this->db->rollBack(); return $this->what_error(); } else { $id = $this->db->lastInsertId(); $this->db->commit(); return ['id' => $id]; } } else { $return_errors['incorrect_fields'] = 'email'; } } else { return $this->auth_error(); } } else { $return_errors['empty_fields'] = array_keys($v->errors()); } return $this->create_error($return_errors); }
$param2 = '?' . $param2 . '&'; } else { $param2 = '?'; } $conf_id = (int) getgpcvar("conf_id", "G"); $back_page = "system_config.php"; $cur_page = cur_page(); ///////////////////////////////////////////////////////////////// if (isset($_POST['title'])) { $conf_id = (int) getgpcvar("conf_id", "P"); ##/ Validate Fields include_once '../../includes/form_validator.php'; $form_v = new Valitron\Validator($_POST); $rules = ['required' => [['title'], ['c_value']], 'lengthMax' => [['title', 100], ['c_value', 50]]]; $form_v->labels(array('title' => 'Title', 'c_value' => 'Value')); $form_v->rules($rules); $form_v->validate(); $fv_errors = $form_v->errors(); //var_dump("<pre>", $_POST, $fv_errors); die(); #- if (!is_array($fv_errors) || empty($fv_errors) || count($fv_errors) <= 0) { if ($conf_id > 0) { ###/ Updating Database #/ system_config $sql_tb1 = "UPDATE system_config SET title='{$_POST['title']}', c_value='{$_POST['c_value']}'\n WHERE id='{$conf_id}'"; mysql_exec($sql_tb1, 'save'); #- $_SESSION["CUSA_ADMIN_MSG_GLOBAL"] = array(true, 'The Site data has been successfully Updated'); redirect_me("{$consts['DOC_ROOT_ADMIN']}{$cur_page}{$param2}&conf_id={$conf_id}", true); ////////////////------- } else {
</tr> <?php } ?> </table> </div> <?php } } if (!($row = $db->query("SELECT * FROM personalDetails WHERE personID = '" . $_SESSION['logon_id'] . "'")->fetch_assoc())) { require 'logout.php'; } require_once $_SERVER['DOCUMENT_ROOT'] . '/vendor/autoload.php'; // Validate library $v = new Valitron\Validator($row); $v->rules(['required' => [['email'], ['firstName'], ['lastName'], ['DOB'], ['phone'], ['streetAddress'], ['suburb'], ['city'], ['postCode'], ['NZQA']]]); $v->labels(array('fname' => 'First Name', 'lname' => 'Last Name', 'phone' => 'Phone Number', 'email' => 'Email address', 'dob' => 'Date of Birth', 'streetAddress' => 'Street Address')); if (!$v->validate()) { echo " <h3><img src='images/warn.png' style='width:25px;height:25px;vertical-align:middle'/> Before you enrol, you'll need to complete the following information:<br>"; foreach ($v->errors() as $key => $val) { echo $key . "<br>"; } echo "<br>\n\t\t\t Please visit the <a href='portal.php?page=personal'>Personal Details</a> page to fill this in</h3>"; die; } $db->close(); ?> <!-- Check if filled in all information before this point --> <div style="text-align:left;margin:0 auto;"> <h2>Apply to enrol</h2> <form id="enrolqualForm" action="#" method="post" onsubmit="return false" style="width:100%; max-width:300px;min-width:200px;margin:0 auto; ">
<?php require_once "src/Valitron/Validator.php"; $rules = ['required' => 'foo', 'accepted' => 'bar', 'integer' => 'bar']; $v = new Valitron\Validator(array(), array('foo', 'bar')); $v->rules($rules); $v->rule('min', 'bar', 10); $v->rule('lengthBetween', 'foo', 10, 20); $v->rule('lengthBetween', 'foo', 8, 15); $v->rule('lengthMax', 'foo', 12); $v->rule('equals', 'bar', 'foo'); $v->rule('different', 'fizz', 'buzz'); $v->rule('date', 'fizz'); $v->rule('in', 'buzz', array("spam", "eggs", "parrots")); $v->rule('dateAfter', 'fizz'); $v->rule('alphaNum', 'fizz'); $v->validate(); $result = $v->exportRules("bootstrapvalidator", array("prettyPrint" => true, "exportType" => "json")); echo "<pre>"; print_r($result); echo "</pre>"; $result = $v->exportRules("bootstrapvalidator", array("prettyPrint" => true, "exportType" => "data")); echo "<pre>"; print_r($result); echo "</pre>";
/** * User Password Renewal * * @param string $username * @param string $email * @param optional bool $captcha_validation * * @author Nikita Rousseau */ public function sendNewPassword($username, $email, $captcha_validation = TRUE) { $form = array('username' => $username, 'email' => $email); $errors = array(); // array to hold validation errors $data = array(); // array to pass back data $dbh = Core_DBH::getDBH(); // Get Database Handle // validate the variables ====================================================== $v = new Valitron\Validator($form); $rules = ['required' => [['username'], ['email']], 'alphaNum' => [['username']], 'email' => [['email']]]; $v->rules($rules); $v->validate(); $errors = $v->errors(); // Verify the form ============================================================= if (empty($errors)) { $username = $form['username']; $email = $form['email']; try { $sth = $dbh->prepare("\n\t\t\t\t\tSELECT user_id, email\n\t\t\t\t\tFROM " . DB_PREFIX . "user\n\t\t\t\t\tWHERE\n\t\t\t\t\t\tusername = :username AND\n\t\t\t\t\t\temail \t = :email AND\n\t\t\t\t\t\tstatus = 'active'\n\t\t\t\t\t;"); $sth->bindParam(':username', $username); $sth->bindParam(':email', $email); $sth->execute(); $result = $sth->fetchAll(); } catch (PDOException $e) { echo $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine(); die; } if (!empty($result) && $captcha_validation == TRUE) { $authService = Core_AuthService::getAuthService(); // Reset Login Attempts $authService->rsSecCount(); // Reset User Passwd $plainTextPasswd = bgp_create_random_password(13); $digestPasswd = Core_AuthService::getHash($plainTextPasswd); try { // Update User Passwd $sth = $dbh->prepare("\n\t\t\t\t\t\tUPDATE " . DB_PREFIX . "user\n\t\t\t\t\t\tSET\n\t\t\t\t\t\t\tpassword \t= :password\n\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\tuser_id\t\t= :user_id\n\t\t\t\t\t\t;"); $sth->bindParam(':password', $digestPasswd); $sth->bindParam(':user_id', $result[0]['user_id']); $sth->execute(); } catch (PDOException $e) { echo $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine(); die; } // Send Email $to = htmlentities($result[0]['email'], ENT_QUOTES); $subject = T_('Reset Password'); $message = T_('Your password has been reset to:'); $message .= "<br /><br />" . $plainTextPasswd . "<br /><br />"; $message .= T_('With IP') . ': '; $message .= $_SERVER['REMOTE_ADDR']; $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; $headers .= 'From: Bright Game Panel System <root@' . $_SERVER['SERVER_NAME'] . '>' . "\r\n"; $headers .= 'X-Mailer: PHP/' . phpversion(); $mail = mail($to, $subject, $message, $headers); // Log Event $logger = self::getLogger(); $logger->info('Password reset.'); } else { // Call security component $authService = Core_AuthService::getAuthService(); $authService->incrementSecCount(); // Log Event $logger = self::getLogger(); $logger->info('Bad password reset.'); // Messages if (empty($result)) { $errors['username'] = T_('Wrong information.'); $errors['email'] = T_('Wrong information.'); } if ($captcha_validation == FALSE) { $errors['captcha'] = T_('Wrong CAPTCHA Code.'); } } } // return a response =========================================================== // response if there are errors if (!empty($errors)) { // if there are items in our errors array, return those errors $data['success'] = false; $data['errors'] = $errors; // notification $authService = Core_AuthService::getAuthService(); if ($authService->isBanned()) { $data['msgType'] = 'warning'; $data['msg'] = T_('You have been banned') . ' ' . CONF_SEC_BAN_DURATION . ' ' . T_('seconds!'); } else { $data['msgType'] = 'warning'; $data['msg'] = T_('Invalid information provided!'); } } else { if (!$mail) { // mail delivery error $data['success'] = false; // notification $data['msgType'] = 'danger'; $data['msg'] = T_('An error has occured while sending the email. Contact your system administrator.'); } else { $data['success'] = true; } } // return all our data to an AJAX call return $data; }
function bulutfon_output($vars) { require_once "init.php"; $repository = new Repository(); $request = Request::createFromGlobals(); $provider = new Bulutfon($repository->getKeys()); $tokens = $repository->getTokens(); $smarty = bulutfon_smarty(); if ($tokens) { $token = new AccessToken(Helper::decamelize($tokens)); } else { Helper::outputIfAjax("<a href='{$provider->getAuthorizationUrl()}' class='button'>Yetkilendir.</a>"); Helper::redirect($provider->getAuthorizationUrl()); } switch ($request->get('tab', 'default')) { case 'delete': $phone = (int) $request->get('number', false); if ($repository->deleteNumber($phone)) { Helper::json('deleted'); } Helper::json('failed'); break; case 'addtouser': $smarty->assign('number', $request->get('number')); if ($request->get('clientid')) { $validator = new Valitron\Validator($_POST); $rules = array('required' => array(array('telefon-numarasi'), array('clientid'), array('value')), 'integer' => array(array('telefon-numarasi'), array('clientid')), 'lengthMin' => array(array('telefon-numarasi', 10)), 'lengthMax' => array(array('telefon-numarasi', 20))); $validator->rules($rules); function show_errors($array, $value, $smarty) { $errors = "<div style='color: #a94442;background-color: #f2dede;border:1px solid #ebccd1;padding:5px'><ul style='padding:0'>"; if (isset($array)) { foreach ($array as $e) { $errors .= "<li>{$e}</li>"; } $smarty->assign($value, "{$errors}</ul></div>"); } } if ($validator->validate()) { $add = $repository->addNumber($request->get('clientid'), $request->get('telefon-numarasi')); if ($add) { $smarty->assign('success', 'Kayıt başarıyla eklenmiştir.'); } else { $errors = array(); $errors['telefon-numarasi'] = array('Bu telefon numarası zaten kayıtlı.'); show_errors($errors['telefon-numarasi'], 'telefon', $smarty); $smarty->assign('number', $request->get('telefon-numarasi')); } } else { // really hate smarty and i am a bit lazy. $errors = $validator->errors(); // it must be handled by smarty but i cant figure out show_errors($errors['telefon-numarasi'], 'telefon', $smarty); show_errors($errors['clientid'], 'user', $smarty); show_errors($errors['value'], 'user', $smarty); } } $smarty->display('adduser.tpl'); break; default: $page = $request->get('page', 1); $userid = $request->get('userid'); // 100 results a bit overkill setted to 10. $filters = array('limit' => (int) $request->get('limit', 10)); $fields = true; if ($userid) { $smarty->assign('userid', $userid); $numbers = $repository->getUserNumbers($userid); if (!$numbers) { Helper::json("<p>Kayıtlı telefon numarası bulunamadı.</p>"); } $smarty->assign('userNumbers', $numbers); foreach ($numbers as $number) { if (strlen($number) > 9 && strlen($number) < 12) { array_push($numbers, '90' . ltrim($number, '0')); } } $numbers = Helper::imp($numbers); $filters['caller_or_callee'] = $numbers; } $smarty->assign('cdrs', $provider->getCdrs($token, $filters, $page)->cdrs); $smarty->assign('fields', $fields); $smarty->assign('page', $page); $smarty->assign('limit', (int) $request->get('limit', 10)); Helper::outputIfAjax($smarty->fetch('cdr.tpl')); $smarty->display('cdr.tpl'); break; } }
/** * Add a New Box To The Collection * * @http_method POST * @resource box/ * * @param string $name query * @param string $os query * @param string $ip query * @param string $port query * @param string $login query * @param string $password query * @param optional string $userPath * @param optional string $steamPath * @param optional string $notes * * @return application/json * * @author Nikita Rousseau */ function postBox($name, $os, $ip, $port, $login, $password, $userPath = '', $steamPath = '', $notes = '') { $args = array('name' => $name, 'os' => $os, 'ip' => $ip, 'port' => $port, 'login' => $login, 'password' => $password, 'userPath' => $userPath, 'steamPath' => $steamPath, 'notes' => $notes); $errors = array(); // array to hold validation errors $data = array(); // array to pass back data $dbh = Core_DBH::getDBH(); // Get Database Handle // validate the variables ====================================================== $v = new Valitron\Validator($args); $rules = ['required' => [['name'], ['os'], ['ip'], ['port'], ['login'], ['password']], 'regex' => [['name', "/^([-a-z0-9_ -])+\$/i"]], 'integer' => [['os'], ['port']], 'ip' => [['ip']], 'alphaNum' => [['login']]]; $labels = array('name' => T_('Remote Machine Name'), 'os' => T_('Operating System'), 'ip' => T_('IP Address'), 'port' => T_('Port'), 'login' => T_('Login'), 'password' => T_('Password')); $v->rules($rules); $v->labels($labels); $v->validate(); $errors = $v->errors(); // validate the variables phase 2 ============================================== if (empty($errors)) { // Verify OS ID try { $sth = $dbh->prepare("\n\t\t\t\t\tSELECT operating_system\n\t\t\t\t\tFROM " . DB_PREFIX . "os\n\t\t\t\t\tWHERE\n\t\t\t\t\t\tos_id = :os_id\n\t\t\t\t\t;"); $sth->bindParam(':os_id', $args['os']); $sth->execute(); $result = $sth->fetchAll(PDO::FETCH_ASSOC); } catch (PDOException $e) { echo $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine(); die; } if (empty($result[0])) { $errors['os'] = 'Bad Identifier'; } // Verify Communication $socket = @fsockopen($args['ip'], $args['port'], $errno, $errstr, 3); if ($socket === FALSE) { $errors['com'] = "Unable to connect to " . $args['ip'] . " on port " . $args['port'] . ". " . utf8_encode($errstr) . " ( {$errno} )"; unset($socket); } else { unset($socket); $ssh = new Net_SSH2($args['ip'], $args['port']); if (!$ssh->login($args['login'], $args['password'])) { $errors['com'] = 'Login failed'; } else { // Verify Remote Paths if (!empty($args['userPath'])) { if (boolval(trim($ssh->exec('test -d ' . escapeshellcmd($args['userPath']) . " && echo '1' || echo '0'"))) === FALSE) { $errors['remoteUserHome'] = 'Invalid path. Must be an absolute or full path'; } } if (!empty($args['steamPath'])) { if (boolval(trim($ssh->exec('test -f ' . escapeshellcmd($args['steamPath']) . " && echo '1' || echo '0'"))) === FALSE) { $errors['steamcmd'] = 'SteamCMD not found. Must be an absolute or full path'; } } } $ssh->disconnect(); } } // Apply ======================================================================= if (empty($errors)) { // // Database update // // Vars Init if (empty($args['userPath'])) { $home = "~"; $args['userPath'] = $home; } else { $home = escapeshellcmd(normalizePath($args['userPath'])); $args['userPath'] = $home; } $config = parse_ini_file(CONF_SECRET_INI); // BOX try { $sth = $dbh->prepare("\n\t\t\t\t\tINSERT INTO " . DB_PREFIX . "box\n\t\t\t\t\tSET\n\t\t\t\t\t\tos_id \t\t\t= :os,\n\t\t\t\t\t\tname \t\t\t= :name,\n\t\t\t\t\t\tsteam_lib_path \t= :steamcmd,\n\t\t\t\t\t\tnotes \t\t\t= :notes\n\t\t\t\t\t;"); $sth->bindParam(':os', $args['os']); $sth->bindParam(':name', $args['name']); $sth->bindParam(':steamcmd', $args['steamPath']); $sth->bindParam(':notes', $args['notes']); $sth->execute(); $box_id = $dbh->lastInsertId(); } catch (PDOException $e) { echo $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine(); die; } // IP try { $sth = $dbh->prepare("\n\t\t\t\t\tINSERT INTO " . DB_PREFIX . "box_ip\n\t\t\t\t\tSET\n\t\t\t\t\t\tbox_id = :box_id,\n\t\t\t\t\t\tip = :ip,\n\t\t\t\t\t\tis_default = 1\n\t\t\t\t\t;"); $sth->bindParam(':box_id', $box_id); $sth->bindParam(':ip', $args['ip']); $sth->execute(); } catch (PDOException $e) { echo $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine(); die; } // CREDENTIALS // Phase 1 // Connect to the remote host // Try to append our public key to authorized_keys $ssh = new Net_SSH2($args['ip'], $args['port']); $ssh->login($args['login'], $args['password']); $remote_keys = $ssh->exec('cat ' . $home . '/.ssh/authorized_keys'); // Check if the public key already exists if (strpos($remote_keys, file_get_contents(RSA_PUBLIC_KEY_FILE)) === FALSE) { // Otherwise, append it $ssh->exec("echo '" . file_get_contents(RSA_PUBLIC_KEY_FILE) . "' >> " . $home . "/.ssh/authorized_keys"); } // Phase 2 // Verify that the public key is allowed on the remote host $isUsingSSHPubKey = TRUE; // By default, we use the SSH authentication keys method $remote_keys = $ssh->exec('cat ' . $home . '/.ssh/authorized_keys'); $ssh->disconnect(); if (strpos($remote_keys, file_get_contents(RSA_PUBLIC_KEY_FILE)) === FALSE) { // authorized_keys is not writable // Use compatibility mode // Store the password in DB $isUsingSSHPubKey = FALSE; } else { // Phase 3 // Try to connect with our private key on the remote host $ssh = new Net_SSH2($args['ip'], $args['port']); $key = new Crypt_RSA(); $key->loadKey(file_get_contents(RSA_PRIVATE_KEY_FILE)); if (!$ssh->login($args['login'], $key)) { // Authentication failed // Use compatibility mode // Store the password in DB $isUsingSSHPubKey = FALSE; } $ssh->disconnect(); } // SSH CREDENTIALS $cipher = new Crypt_AES(CRYPT_AES_MODE_ECB); $cipher->setKeyLength(256); $cipher->setKey($config['APP_SSH_KEY']); if ($isUsingSSHPubKey) { try { $sth = $dbh->prepare("\n\t\t\t\t\t\tINSERT INTO " . DB_PREFIX . "box_credential\n\t\t\t\t\t\tSET\n\t\t\t\t\t\t\tlogin = :login,\n\t\t\t\t\t\t\tremote_user_home = :home,\n\t\t\t\t\t\t\tcom_protocol = 'ssh2',\n\t\t\t\t\t\t\tcom_port = :com_port\n\t\t\t\t\t\t;"); $login = $cipher->encrypt($args['login']); $sth->bindParam(':login', $login); $sth->bindParam(':home', $args['userPath']); $sth->bindParam(':com_port', $args['port']); $sth->execute(); $credential_id = $dbh->lastInsertId(); } catch (PDOException $e) { echo $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine(); die; } } else { try { $sth = $dbh->prepare("\n\t\t\t\t\t\tINSERT INTO " . DB_PREFIX . "box_credential\n\t\t\t\t\t\tSET\n\t\t\t\t\t\t\tlogin = :login,\n\t\t\t\t\t\t\tpassword = :password,\n\t\t\t\t\t\t\tremote_user_home = :home,\n\t\t\t\t\t\t\tcom_protocol = 'ssh2',\n\t\t\t\t\t\t\tcom_port = :port\n\t\t\t\t\t\t;"); $login = $cipher->encrypt($args['login']); $password = $cipher->encrypt($args['password']); $sth->bindParam(':login', $login); $sth->bindParam(':password', $password); $sth->bindParam(':home', $args['userPath']); $sth->bindParam(':com_port', $args['port']); $sth->execute(); $credential_id = $dbh->lastInsertId(); } catch (PDOException $e) { echo $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine(); die; } } // UPDATE BOX try { $sth = $dbh->prepare("\n\t\t\t\t\tUPDATE " . DB_PREFIX . "box\n\t\t\t\t\tSET\n\t\t\t\t\t\tbox_credential_id = :box_credential_id\n\t\t\t\t\tWHERE box_id = :box_id\n\t\t\t\t\t;"); $sth->bindParam(':box_credential_id', $credential_id); $sth->bindParam(':box_id', $box_id); $sth->execute(); } catch (PDOException $e) { echo $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine(); die; } } // return a response and log =================================================== $logger = self::getLogger(); $data['errors'] = $errors; if (!empty($data['errors'])) { $data['success'] = false; $logger->info('Failed to add box.'); } else { $data['success'] = true; $logger->info('Box added.'); } return array('response' => 'application/json', 'data' => json_encode($data)); }