Example #1
0
 /**
  * Devolver los datos de definiciones de campos personalizados
  *
  * @param int        $customFieldId El id del campo personalizado
  * @param bool|false $returnRawData Devolver los datos de la consulta sin formatear
  * @return array|bool
  */
 public static function getCustomFields($customFieldId = null, $returnRawData = false)
 {
     $query = 'SELECT customfielddef_id, customfielddef_module, customfielddef_field FROM customFieldsDef';
     if (!is_null($customFieldId)) {
         $query .= ' WHERE customfielddef_id = :id LIMIT 1';
         $data['id'] = $customFieldId;
     } else {
         $query .= ' ORDER BY customfielddef_module';
     }
     if (!$returnRawData) {
         DB::setReturnArray();
     }
     $queryRes = DB::getResults($query, __FUNCTION__, $data);
     if ($queryRes === false) {
         return array();
     }
     if (!$returnRawData) {
         $customFields = array();
         foreach ($queryRes as $customField) {
             /**
              * @var CustomFieldDef
              */
             $field = unserialize($customField->customfielddef_field);
             $attribs = new \stdClass();
             $attribs->id = $customField->customfielddef_id;
             $attribs->module = self::getFieldsModules($customField->customfielddef_module);
             $attribs->name = $field->getName();
             $attribs->typeName = self::getFieldsTypes($field->getType(), true);
             $attribs->type = $field->getType();
             $customFields[] = $attribs;
         }
         return $customFields;
     }
     return $queryRes;
 }
Example #2
0
 /**
  *
  * @param string $order
  * @param int $limit Default is 10
  * @return object|null
  */
 public function getTags($order, $limit = 10)
 {
     if (!Config::get('home' . ucfirst($order), 'tags')) {
         return NULL;
     }
     if ($order == 'latest') {
         DB::select('tag');
         DB::from('tag');
         DB::orderBy('id', 'desc');
     } else {
         if ($order == 'random') {
             $range = $this->_tagsRandomRange();
             DB::select('tag');
             DB::from('tag');
             DB::whereGreaterEqual('id', $range['start']);
             DB::whereLessEqual('id', $range['end']);
             DB::orderBy('id', 'rand');
         }
     }
     $configLimit = Config::get('home' . ucfirst($order) . 'Limit', 'tags');
     if ($configLimit) {
         $limit = $configLimit;
     }
     DB::limit($limit);
     DB::run();
     return DB::getResults();
 }
 /**
  * Comprobar el hash de recuperación de clave.
  *
  * @param string $hash con el hash de recuperación
  * @return int con el Id del usuario
  */
 public static function checkHashPassRecover($hash)
 {
     $query = 'SELECT userpassr_userId FROM usrPassRecover ' . 'WHERE userpassr_hash = :hash ' . 'AND userpassr_used = 0 ' . 'AND userpassr_date >= :date ' . 'ORDER BY userpassr_date DESC LIMIT 1';
     $data['hash'] = $hash;
     $data['date'] = time() - self::MAX_PASS_RECOVER_TIME;
     $queryRes = DB::getResults($query, __FUNCTION__, $data);
     if ($queryRes === false) {
         return false;
     }
     return $queryRes->userpassr_userId;
 }
Example #4
0
 public function login($username = null, $password = null)
 {
     // testa token do formulário
     if (!check_token($_POST['token'])) {
         return false;
     }
     // verificar se username existe
     $user = $this->findByUsername($username);
     if (is_numeric($user->id)) {
         // verificar senha digitada
         if (!$password) {
             return false;
         }
         $this->db->query("SELECT password FROM users WHERE id = :id", array(array('name' => 'id', 'value' => $user->id)));
         $res = $this->db->getResults();
         if ($this->db->isOk() && password_verify($password, $res->password)) {
             $_SESSION["user"] = $user->id;
             return true;
         }
     }
     return false;
 }
Example #5
0
 /**
  * Migrar el grupo de los usuarios a la nueva tabla
  */
 public static function migrateUsersGroup()
 {
     $query = 'SELECT user_id, user_groupId FROM usrData';
     $queryRes = DB::getResults($query, __FUNCTION__, $data);
     if ($queryRes === false) {
         return false;
     }
     foreach ($queryRes as $user) {
         if (!Groups::addUsersForGroup(array($user->user_groupId), $user->user_id)) {
             Log::writeNewLog(_('Migrar Grupos'), sprintf('%s (%s)'), _('Error al migrar grupo del usuario'), $user->user_id);
         }
     }
     return true;
 }
Example #6
0
 /**
  * Obtener los eventos guardados.
  *
  * @param int $start con el número de registro desde el que empezar
  * @return false|array con el resultado de la consulta
  */
 public static function getEvents($start)
 {
     $query = 'SELECT ' . 'log_id,' . 'FROM_UNIXTIME(log_date) as log_date,' . 'log_action,' . 'log_login,' . 'log_ipAddress,' . 'log_description ' . 'FROM log ' . 'ORDER BY log_id DESC ' . 'LIMIT :start, 50';
     $data['start'] = $start;
     // Obtenemos el número total de registros
     DB::setFullRowCount();
     // Devolver un array siempre
     DB::setReturnArray();
     $queryRes = DB::getResults($query, __FUNCTION__, $data);
     if ($queryRes === false) {
         return false;
     }
     self::$numRows = DB::$lastNumRows;
     return $queryRes;
 }
Example #7
0
 /**
  * Desencriptar la clave maestra del usuario para la sesión.
  *
  * @param bool $showPass opcional, para devolver la clave desencriptada
  * @return false|string Devuelve bool se hay error o string si se devuelve la clave
  */
 public function getUserMPass($showPass = false)
 {
     $query = 'SELECT user_mPass, user_mIV FROM usrData WHERE user_id = :id LIMIT 1';
     $data['id'] = $this->_userId;
     $queryRes = DB::getResults($query, __FUNCTION__, $data);
     if ($queryRes === false) {
         return false;
     }
     if ($queryRes->user_mPass && $queryRes->user_mIV) {
         $clearMasterPass = Crypt::getDecrypt($queryRes->user_mPass, $queryRes->user_mIV, $this->getCypherPass());
         if (!$clearMasterPass) {
             return false;
         }
         return $showPass === true ? $clearMasterPass : SessionUtil::saveSessionMPass($clearMasterPass);
     }
     return false;
 }
Example #8
0
 /**
  * Obtiene el listado de categorías.
  *
  * @param int  $id            con el Id de la categoría
  * @param bool $retAssocArray para devolver un array asociativo
  * @return array con el id de categoria como clave y en nombre como valor
  */
 public static function getCategories($id = null, $retAssocArray = false)
 {
     $query = 'SELECT category_id, category_name,category_description FROM categories ';
     $data = null;
     if (!is_null($id)) {
         $query .= "WHERE category_id = :id LIMIT 1";
         $data['id'] = $id;
     } else {
         $query .= "ORDER BY category_name";
     }
     DB::setReturnArray();
     $queryRes = DB::getResults($query, __FUNCTION__, $data);
     if ($queryRes === false) {
         return array();
     }
     if ($retAssocArray) {
         $resCategories = array();
         foreach ($queryRes as $category) {
             $resCategories[$category->category_id] = $category->category_name;
         }
         return $resCategories;
     }
     return $queryRes;
 }
Example #9
0
<?php

require_once 'DB.php';
$db = new DB('host', 'username', 'password', 'database');
if (isset($_GET['code'])) {
    $taintedCode = $_GET['code'];
    header('Content-Type: application/json');
    if (preg_match('/^\\d{4}$/', $taintedCode) && strlen($taintedCode) == 4) {
        $rawIntCode = intval($taintedCode);
        $strCode = '';
        if (filter_var($rawIntCode, FILTER_VALIDATE_INT)) {
            $strCode = $rawIntCode;
            $query = "SELECT product_name, product_price FROM products WHERE product_code = '{$strCode}'";
            $results = $db->getResults($query);
            $output = array();
            foreach ($results as $result) {
                $output['name'] = $result['product_name'];
                $output['price'] = $result['product_price'];
            }
            echo json_encode($output);
        }
    }
}
Example #10
0
<?php

require_once 'DB.php';
$db = new DB('host', 'username', 'password', 'database');
$productCodes = $db->getResults("SELECT product_code FROM products");
?>
<!DOCTYPE html>
<html>
<head>
  <title>jQuery: AJAX autocomplete for e-commerce products</title>
  <meta charset="utf-8" />
  <link rel="stylesheet" href="css/style.css" type="text/css" media="screen" />
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
  <script type="text/javascript" src="js/autoproducts.js"></script>
</head>
<body>
<form action="" method="post" id="cart">
	<div>
		<input type="text" name="code" id="code" placeholder="Product Code" />
		<div id="name"></div>
		<div id="price"></div>
		<input type="submit" value="Add to cart" />
	</div>
	<h3>Available product codes</h3>
	<ul id="codes">
	<?php 
$html = '';
foreach ($productCodes as $productCode) {
    $code = $productCode['product_code'];
    $html .= sprintf('<li>%s</li>', $code);
}
Example #11
0
<?php

require_once 'DB.php';
header('Content-Type: application/json');
$db = new DB('host', 'username', 'password', 'database');
$images = $db->getResults("SELECT * FROM images");
$total = $db->numResults;
$url = 'images/';
$results = array();
$results['total'] = $total;
$results['images'] = array();
foreach ($images as $image => $row) {
    $image_url = $url . $row['filename'];
    $caption = $row['title'];
    $width = $row['width'];
    $height = $row['height'];
    $results['images'][] = array('url' => $image_url, 'caption' => $caption, 'width' => $width, 'height' => $height);
}
$json = json_encode($results);
echo $json;
exit;
Example #12
0
 /**
  * Comprobar si un usuario autentifica mediante LDAP
  * .
  *
  * @param string $userLogin con el login del usuario
  * @return bool
  */
 public static function checkUserIsLDAP($userLogin)
 {
     $query = 'SELECT BIN(user_isLdap) AS user_isLdap FROM usrData WHERE user_login = :login LIMIT 1';
     $data['login'] = $userLogin;
     $queryRes = DB::getResults($query, __FUNCTION__, $data);
     return $queryRes !== false && intval($queryRes->user_isLdap) === 1;
 }
Example #13
0
 /**
  * Obtener los datos de todas las cuentas
  *
  * @return array
  * @throws SPException
  */
 public static function getAccountsData()
 {
     $query = 'SELECT account_id,' . 'account_name,' . 'account_categoryId,' . 'account_customerId,' . 'account_login,' . 'account_url,' . 'account_pass,' . 'account_IV,' . 'account_notes ' . 'FROM accounts';
     DB::setReturnArray();
     $queryRes = DB::getResults($query, __FUNCTION__, $data);
     if ($queryRes === false) {
         throw new SPException(SPException::SP_CRITICAL, _('No se pudieron obtener los datos de las cuentas'));
     }
     return $queryRes;
 }
Example #14
0
 /**
  * Obtiene un valor desde la configuración en la BBDD.
  *
  * @param string $param con el parámetro de configuración
  * @param string $default El valor por defecto
  * @return false|string con el valor
  */
 public static function getValue($param, $default = null)
 {
     $query = 'SELECT config_value FROM config WHERE config_parameter = :parameter LIMIT 1';
     $data['parameter'] = $param;
     $queryRes = DB::getResults($query, __FUNCTION__, $data);
     if ($queryRes === false) {
         return false;
     }
     return $queryRes->config_value ? $queryRes->config_value : $default;
 }
Example #15
0
 /**
  * Obtener el nombre de un perfil por a partir del Id.
  *
  * @param int $id con el Id del perfil
  * @return false|string con el nombre del perfil
  */
 public static function getProfileNameById($id)
 {
     $query = 'SELECT userprofile_name FROM usrProfiles WHERE userprofile_id = :id LIMIT 1';
     $data['id'] = $id;
     $queryRes = DB::getResults($query, __FUNCTION__, $data);
     if ($queryRes === false) {
         return false;
     }
     return $queryRes->userprofile_name;
 }
Example #16
0
 /**
  * Obtener las preferencas de un usuario
  *
  * @param $id int El id del usuario
  * @return bool|UserPreferences
  * @throws SPException
  */
 public static function getPreferences($id)
 {
     $query = 'SELECT user_preferences FROM usrData WHERE user_id = :id LIMIT 1';
     $data['id'] = $id;
     $queryRes = DB::getResults($query, __FUNCTION__, $data);
     if ($queryRes === false) {
         return new UserPreferences();
         //            throw new SPException(SPException::SP_WARNING, _('Datos de preferencias incorrectos'));
     }
     $preferences = unserialize($queryRes->user_preferences);
     if (!$preferences instanceof UserPreferences) {
         return new UserPreferences();
     }
     return $preferences;
 }
Example #17
0
 /**
  * Obtiene el listado con el nombre de los usuarios de una cuenta.
  *
  * @param int $accountId con el id de la cuenta
  * @return false|array con los nombres de los usuarios ordenados
  */
 public static function getUsersNameForAccount($accountId)
 {
     $query = 'SELECT user_id,' . 'user_login ' . 'FROM accUsers ' . 'JOIN usrData ON user_Id = accuser_userId ' . 'WHERE accuser_accountId = :id';
     $data['id'] = $accountId;
     DB::setReturnArray();
     $queryRes = DB::getResults($query, __FUNCTION__, $data);
     if ($queryRes === false) {
         return false;
     }
     foreach ($queryRes as $users) {
         $usersName[$users->user_id] = $users->user_login;
     }
     asort($usersName, SORT_STRING);
     return $usersName;
 }
Example #18
0
 /**
  * Obtener el listado de archivos de una cuenta.
  *
  * @param int $accountId con el Id de la cuenta
  * @return false|array con los archivos de la cuenta.
  */
 public static function getFileList($accountId)
 {
     $query = "SELECT accfile_id," . "accfile_name," . "accfile_size, " . "accfile_thumb, " . "accfile_type " . "FROM accFiles " . "WHERE accfile_accountId = :id";
     $data['id'] = $accountId;
     DB::setReturnArray();
     $queryRes = DB::getResults($query, __FUNCTION__, $data);
     if ($queryRes === false) {
         return false;
     }
     $files = array();
     foreach ($queryRes as $file) {
         $files[] = array('id' => $file->accfile_id, 'name' => $file->accfile_name, 'size' => round($file->accfile_size / 1000, 2), 'thumb' => $file->accfile_thumb, 'type' => $file->accfile_type);
     }
     return $files;
 }
Example #19
0
 /**
  * Obtener el listado de clientes.
  *
  * @param int  $customerId    con el Id del cliente
  * @param bool $retAssocArray para devolver un array asociativo
  * @return array con el id de cliente como clave y el nombre como valor
  */
 public static function getCustomers($customerId = null, $retAssocArray = false)
 {
     $query = 'SELECT customer_id, customer_name, customer_description FROM customers ';
     $data = null;
     if (!is_null($customerId)) {
         $query .= "WHERE customer_id = :id LIMIT 1";
         $data['id'] = $customerId;
     } else {
         $query .= "ORDER BY customer_name";
     }
     DB::setReturnArray();
     $queryRes = DB::getResults($query, __FUNCTION__, $data);
     if ($queryRes === false) {
         return array();
     }
     if ($retAssocArray) {
         $resCustomers = array();
         foreach ($queryRes as $customer) {
             $resCustomers[$customer->customer_id] = $customer->customer_name;
         }
         return $resCustomers;
     }
     return $queryRes;
 }
Example #20
0
 /**
  * Comprobar si un usuario/email existen en la BBDD.
  *
  * @return false|int Devuelve bool si error y int si existe el usuario/email
  */
 public function checkUserExist()
 {
     $userLogin = strtoupper($this->_userLogin);
     $userEmail = strtoupper($this->_userEmail);
     $query = 'SELECT user_login, user_email ' . 'FROM usrData ' . 'WHERE (UPPER(user_login) = :login ' . 'OR UPPER(user_email) = :email) ' . 'AND user_id != :id';
     $data['login'] = $userLogin;
     $data['email'] = $userEmail;
     $data['id'] = $this->_userId;
     DB::setReturnArray();
     $queryRes = DB::getResults($query, __FUNCTION__, $data);
     if ($queryRes === false) {
         return false;
     }
     foreach ($queryRes as $userData) {
         $resULogin = strtoupper($userData->user_login);
         $resUEmail = strtoupper($userData->user_email);
         if ($resULogin == $userLogin) {
             return UserUtil::USER_LOGIN_EXIST;
         } elseif ($resUEmail == $userEmail) {
             return UserUtil::USER_MAIL_EXIST;
         }
     }
 }
Example #21
0
 /**
  * Obtiene el listado de grupos de una cuenta.
  *
  * @param int $accountId con el Id de la cuenta
  * @return false|array con el Id de grupo
  */
 public static function getGroupsForAccount($accountId)
 {
     $query = 'SELECT accgroup_groupId FROM accGroups WHERE accgroup_accountId = :id';
     $data['id'] = $accountId;
     DB::setReturnArray();
     $queryRes = DB::getResults($query, __FUNCTION__, $data);
     if ($queryRes === false) {
         return array();
     }
     foreach ($queryRes as $group) {
         $groups[] = (int) $group->accgroup_groupId;
     }
     return $groups;
 }
Example #22
0
 /**
  * Obtener los perfiles disponibles
  *
  * @return array|bool
  */
 public static function getProfiles()
 {
     if (Util::demoIsEnabled()) {
         $query = 'SELECT userprofile_id, userprofile_name FROM usrProfiles WHERE userprofile_name <> "Admin" AND userprofile_name <> "Demo" ORDER BY userprofile_name';
     } else {
         $query = 'SELECT userprofile_id, userprofile_name FROM usrProfiles ORDER BY userprofile_name';
     }
     DB::setReturnArray();
     return DB::getResults($query, __FUNCTION__);
 }
Example #23
0
			$.get( "ajax.php", { s: page }, function( html ) {
				$( "#content" ).html( html );

			});
		});

	});

})( jQuery );
  </script>
</head>
<body>
	<div id="content">
		<?php 
$db = new DB('host', 'username', 'password', 'database');
$posts = $db->getResults("SELECT * FROM posts WHERE post_type = 'post' AND post_status = 'publish' ORDER BY ID DESC LIMIT 3");
$allPosts = $db->getResults("SELECT * FROM posts WHERE post_type = 'post' AND post_status = 'publish' ORDER BY ID");
$total = $db->numResults;
$pages = $total / 3;
$html = '';
foreach ($posts as $post => $content) {
    $postContent = $content['post_excerpt'];
    $postTitle = $content['post_title'];
    $date = strtotime($content['post_date']);
    $postDate = strftime('%d-%m-%Y', $date);
    $html .= sprintf('<h3>%s</h3><small>%s</small><p>%s</p>', $postTitle, $postDate, $postContent);
}
echo $html;
?>
	</div>
	<div id="pagination">
Example #24
0
 /**
  * Obtener el Id padre de una cuenta en el histórico.
  *
  * @param $historyId int El id de la cuenta en el histórico
  * @return int El id de la cuenta padre
  * @throws SPException
  */
 public static function getAccountIdFromId($historyId)
 {
     $query = 'SELECT acchistory_accountId FROM accHistory WHERE acchistory_id = :id LIMIT 1';
     $data['id'] = $historyId;
     $queryRes = DB::getResults($query, __FUNCTION__, $data);
     if ($queryRes === false) {
         throw new SPException(SPException::SP_CRITICAL, _('No se pudieron obtener los datos de la cuenta'), 0);
     }
     return $queryRes->acchistory_accountId;
 }
Example #25
0
 /**
  * Actualizar los datos encriptados con una nueva clave
  *
  * @param string $currentMasterPass La clave maestra actual
  * @param string $newMasterPassword La nueva clave maestra
  * @return bool
  * @throws SPException
  */
 public static function updateCustomFieldsCrypt($currentMasterPass, $newMasterPassword)
 {
     $Log = new Log();
     $Log->setAction(_('Campos Personalizados'));
     $query = 'SELECT customfielddata_id, customfielddata_data, customfielddata_iv FROM customFieldsData';
     DB::setReturnArray();
     $queryRes = DB::getResults($query, __FUNCTION__);
     if ($queryRes === false) {
         $Log->addDescription(_('Fin'));
         $Log->writeLog();
         return true;
     }
     $Log->addDescription(_('Actualizando datos encriptados'));
     $Log->writeLog(true);
     $errors = array();
     $success = array();
     foreach ($queryRes as $customField) {
         $fieldData = Crypt::getDecrypt($customField->customfielddata_data, $customField->customfielddata_iv, $currentMasterPass);
         $fieldCryptData = Crypt::encryptData($fieldData, $newMasterPassword);
         $query = 'UPDATE customFieldsData SET ' . 'customfielddata_data = :data, ' . 'customfielddata_iv = :iv ' . 'WHERE customfielddata_id = :id ';
         $data['id'] = $customField->customfielddata_id;
         $data['data'] = $fieldCryptData['data'];
         $data['iv'] = $fieldCryptData['iv'];
         if (DB::getQuery($query, __FUNCTION__, $data) === false) {
             $errors[] = $customField->customfielddata_id;
         } else {
             $success[] = $customField->customfielddata_id;
         }
     }
     if (count($errors) > 0) {
         $Log->addDescription(_('Registros no actualizados') . ': ' . implode(',', $errors));
         $Log->writeLog(true);
     }
     if (count($success) > 0) {
         $Log->addDescription(_('Registros actualizados') . ': ' . implode(',', $success));
         $Log->writeLog(true);
     }
     $Log->addDescription(_('Fin'));
     $Log->writeLog();
     return count($errors) === 0;
 }
Example #26
0
 /**
  * Obtener el IV del usuario a partir del Id.
  *
  * @param int $id El id del usuario
  * @return string El hash
  */
 public static function getUserIVById($id)
 {
     $query = 'SELECT user_mIV FROM usrData WHERE user_id = :id LIMIT 1';
     $data['id'] = $id;
     $queryRes = DB::getResults($query, __FUNCTION__, $data);
     if ($queryRes === false) {
         return false;
     }
     return $queryRes->user_mIV;
 }
Example #27
0
 /**
  * Autentificación de usuarios con MySQL.
  *
  * Esta función comprueba la clave del usuario. Si el usuario necesita ser migrado desde phpPMS,
  * se ejecuta el proceso para actualizar la clave.
  *
  * @param string $userLogin con el login del usuario
  * @param string $userPass  con la clave del usuario
  * @return bool
  */
 public static function authUserMySQL($userLogin, $userPass)
 {
     if (UserMigrate::checkUserIsMigrate($userLogin)) {
         if (!UserMigrate::migrateUser($userLogin, $userPass)) {
             return false;
         }
     }
     $query = 'SELECT user_login, user_pass, user_hashSalt ' . 'FROM usrData ' . 'WHERE user_login = :login AND user_isMigrate = 0 LIMIT 1';
     $data['login'] = $userLogin;
     $queryRes = DB::getResults($query, __FUNCTION__, $data);
     return $queryRes !== false && $queryRes->user_pass == crypt($userPass, $queryRes->user_hashSalt);
 }
Example #28
0
 /**
  * Backup de las tablas de la BBDD.
  * Utilizar '*' para toda la BBDD o 'table1 table2 table3...'
  *
  * @param string $tables
  * @param string $backupFile
  * @throws SPException
  * @return bool
  */
 private static function backupTables($tables = '*', $backupFile)
 {
     $dbname = Config::getValue("dbname");
     try {
         $handle = fopen($backupFile, 'w');
         if ($tables == '*') {
             $resTables = DB::getResults('SHOW TABLES', __FUNCTION__);
         } else {
             $resTables = is_array($tables) ? $tables : explode(',', $tables);
         }
         $sqlOut = '--' . PHP_EOL;
         $sqlOut .= '-- sysPass DB dump generated on ' . time() . ' (START)' . PHP_EOL;
         $sqlOut .= '--' . PHP_EOL;
         $sqlOut .= '-- Please, do not alter this file, it could break your DB' . PHP_EOL;
         $sqlOut .= '--' . PHP_EOL . PHP_EOL;
         $sqlOut .= 'CREATE DATABASE IF NOT EXISTS `' . $dbname . '`;' . PHP_EOL . PHP_EOL;
         $sqlOut .= 'USE `' . $dbname . '`;' . PHP_EOL . PHP_EOL;
         fwrite($handle, $sqlOut);
         // Recorrer las tablas y almacenar los datos
         foreach ($resTables as $table) {
             $tableName = $table->{'Tables_in_' . $dbname};
             $sqlOut = '-- ' . PHP_EOL;
             $sqlOut .= '-- Table ' . strtoupper($tableName) . PHP_EOL;
             $sqlOut .= '-- ' . PHP_EOL;
             // Consulta para crear la tabla
             $sqlOut .= 'DROP TABLE IF EXISTS `' . $tableName . '`;' . PHP_EOL . PHP_EOL;
             $txtCreate = DB::getResults('SHOW CREATE TABLE ' . $tableName, __FUNCTION__);
             $sqlOut .= $txtCreate->{'Create Table'} . ';' . PHP_EOL . PHP_EOL;
             fwrite($handle, $sqlOut);
             DB::setReturnRawData();
             // Consulta para obtener los registros de la tabla
             $queryRes = DB::getResults('SELECT * FROM ' . $tableName, __FUNCTION__);
             $numColumns = $queryRes->columnCount();
             while ($row = $queryRes->fetch(\PDO::FETCH_NUM)) {
                 fwrite($handle, 'INSERT INTO `' . $tableName . '` VALUES(');
                 $field = 1;
                 foreach ($row as $value) {
                     if (is_numeric($value)) {
                         fwrite($handle, $value);
                     } else {
                         fwrite($handle, DB::escape($value));
                     }
                     if ($field < $numColumns) {
                         fwrite($handle, ',');
                     }
                     $field++;
                 }
                 fwrite($handle, ');' . PHP_EOL);
             }
             fwrite($handle, PHP_EOL . PHP_EOL);
             DB::setReturnRawData(false);
         }
         $sqlOut = '--' . PHP_EOL;
         $sqlOut .= '-- sysPass DB dump generated on ' . time() . ' (END)' . PHP_EOL;
         $sqlOut .= '--' . PHP_EOL;
         $sqlOut .= '-- Please, do not alter this file, it could break your DB' . PHP_EOL;
         $sqlOut .= '--' . PHP_EOL . PHP_EOL;
         fwrite($handle, $sqlOut);
         fclose($handle);
     } catch (\Exception $e) {
         throw new SPException(SPException::SP_CRITICAL, $e->getMessage());
     }
     return true;
 }
Example #29
0
 /**
  * Obtiene el número de cuentas que un usuario puede ver.
  *
  * @return false|int con el número de registros
  */
 public function getAccountMax()
 {
     $data = null;
     if (!Session::getUserIsAdminApp() && !Session::getUserIsAdminAcc()) {
         $query = 'SELECT COUNT(DISTINCT account_id) as numacc ' . 'FROM accounts ' . 'LEFT JOIN accGroups ON account_id = accgroup_accountId ' . 'WHERE account_userGroupId = :userGroupId ' . 'OR account_userId = :userId ' . 'OR accgroup_groupId = :groupId';
         $data['userGroupId'] = Session::getUserGroupId();
         $data['groupId'] = Session::getUserGroupId();
         $data['userId'] = Session::getUserId();
     } else {
         $query = "SELECT COUNT(*) as numacc FROM accounts";
     }
     $queryRes = DB::getResults($query, __FUNCTION__, $data);
     if ($queryRes === false) {
         return false;
     }
     return $queryRes->numacc;
 }
Example #30
0
<?php

require_once 'DB.php';
header('Content-Type: text/html');
$start = 0;
$end = 3;
$value = 0;
if (isset($_GET['s'])) {
    $taintedStart = $_GET['s'];
    if (strlen($taintedStart) <= 2) {
        $s = intval($taintedStart);
        if (filter_var($s, FILTER_VALIDATE_INT)) {
            if ($s > $start) {
                $start = $s;
            }
        }
    }
}
$value = $start * $end - $end;
$db = new DB('host', 'username', 'password', 'database');
$posts = $db->getResults("SELECT * FROM posts WHERE post_type = 'post' AND post_status = 'publish' ORDER BY ID DESC LIMIT {$value},{$end}");
$html = '';
foreach ($posts as $post => $content) {
    $postContent = $content['post_excerpt'];
    $postTitle = $content['post_title'];
    $date = strtotime($content['post_date']);
    $postDate = strftime('%d-%m-%Y', $date);
    $html .= sprintf('<h3>%s</h3><small>%s</small><p>%s</p>', $postTitle, $postDate, $postContent);
}
echo $html;