<?php namespace PHPMaker2020\recetarios_2021; ?>
<?php

/**
 * Table class for usuarios
 */
class usuarios extends DbTable
{
	protected $SqlFrom = "";
	protected $SqlSelect = "";
	protected $SqlSelectList = "";
	protected $SqlWhere = "";
	protected $SqlGroupBy = "";
	protected $SqlHaving = "";
	protected $SqlOrderBy = "";
	public $UseSessionForListSql = TRUE;

	// Column CSS classes
	public $LeftColumnClass = "col-sm-2 col-form-label ew-label";
	public $RightColumnClass = "col-sm-10";
	public $OffsetColumnClass = "col-sm-10 offset-sm-2";
	public $TableLeftColumnClass = "w-col-2";

	// Export
	public $ExportDoc;

	// Fields
	public $id;
	public $Apellido;
	public $Nombre;
	public $Usuario;
	public $Contrasena;
	public $ReportarA;
	public $UsuarioNivel;
	public $Activado;
	public $Fecha_Nacimiento;
	public $Direccion;
	public $Localidad;
	public $Provincia;
	public $CodigoPostal;
	public $Telefono;
	public $Extension;
	public $_Email;
	public $Foto;
	public $Notas;
	public $Perfil;

	// Constructor
	public function __construct()
	{
		global $Language, $CurrentLanguage;
		parent::__construct();

		// Language object
		if (!isset($Language))
			$Language = new Language();
		$this->TableVar = 'usuarios';
		$this->TableName = 'usuarios';
		$this->TableType = 'TABLE';

		// Update Table
		$this->UpdateTable = "`usuarios`";
		$this->Dbid = 'DB';
		$this->ExportAll = TRUE;
		$this->ExportPageBreakCount = 0; // Page break per every n record (PDF only)
		$this->ExportPageOrientation = "portrait"; // Page orientation (PDF only)
		$this->ExportPageSize = "a4"; // Page size (PDF only)
		$this->ExportExcelPageOrientation = ""; // Page orientation (PhpSpreadsheet only)
		$this->ExportExcelPageSize = ""; // Page size (PhpSpreadsheet only)
		$this->ExportWordPageOrientation = "portrait"; // Page orientation (PHPWord only)
		$this->ExportWordColumnWidth = NULL; // Cell width (PHPWord only)
		$this->DetailAdd = FALSE; // Allow detail add
		$this->DetailEdit = FALSE; // Allow detail edit
		$this->DetailView = FALSE; // Allow detail view
		$this->ShowMultipleDetails = FALSE; // Show multiple details
		$this->GridAddRowCount = 5;
		$this->AllowAddDeleteRow = TRUE; // Allow add/delete row
		$this->BasicSearch = new BasicSearch($this->TableVar);

		// id
		$this->id = new DbField('usuarios', 'usuarios', 'x_id', 'id', '`id`', '`id`', 3, 11, -1, FALSE, '`id`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'NO');
		$this->id->IsAutoIncrement = TRUE; // Autoincrement field
		$this->id->IsPrimaryKey = TRUE; // Primary key field
		$this->id->Sortable = TRUE; // Allow sort
		$this->id->DefaultErrorMessage = $Language->phrase("IncorrectInteger");
		$this->fields['id'] = &$this->id;

		// Apellido
		$this->Apellido = new DbField('usuarios', 'usuarios', 'x_Apellido', 'Apellido', '`Apellido`', '`Apellido`', 200, 20, -1, FALSE, '`Apellido`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->Apellido->Nullable = FALSE; // NOT NULL field
		$this->Apellido->Required = TRUE; // Required field
		$this->Apellido->Sortable = TRUE; // Allow sort
		$this->fields['Apellido'] = &$this->Apellido;

		// Nombre
		$this->Nombre = new DbField('usuarios', 'usuarios', 'x_Nombre', 'Nombre', '`Nombre`', '`Nombre`', 200, 10, -1, FALSE, '`Nombre`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->Nombre->Nullable = FALSE; // NOT NULL field
		$this->Nombre->Required = TRUE; // Required field
		$this->Nombre->Sortable = TRUE; // Allow sort
		$this->fields['Nombre'] = &$this->Nombre;

		// Usuario
		$this->Usuario = new DbField('usuarios', 'usuarios', 'x_Usuario', 'Usuario', '`Usuario`', '`Usuario`', 200, 20, -1, FALSE, '`Usuario`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->Usuario->Nullable = FALSE; // NOT NULL field
		$this->Usuario->Required = TRUE; // Required field
		$this->Usuario->Sortable = TRUE; // Allow sort
		$this->fields['Usuario'] = &$this->Usuario;

		// Contrasena
		$this->Contrasena = new DbField('usuarios', 'usuarios', 'x_Contrasena', 'Contrasena', '`Contrasena`', '`Contrasena`', 200, 250, -1, FALSE, '`Contrasena`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'PASSWORD');
		$this->Contrasena->Nullable = FALSE; // NOT NULL field
		$this->Contrasena->Required = TRUE; // Required field
		$this->Contrasena->Sortable = TRUE; // Allow sort
		$this->fields['Contrasena'] = &$this->Contrasena;

		// ReportarA
		$this->ReportarA = new DbField('usuarios', 'usuarios', 'x_ReportarA', 'ReportarA', '`ReportarA`', '`ReportarA`', 3, 11, -1, FALSE, '`ReportarA`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->ReportarA->Sortable = TRUE; // Allow sort
		$this->ReportarA->DefaultErrorMessage = $Language->phrase("IncorrectInteger");
		$this->fields['ReportarA'] = &$this->ReportarA;

		// UsuarioNivel
		$this->UsuarioNivel = new DbField('usuarios', 'usuarios', 'x_UsuarioNivel', 'UsuarioNivel', '`UsuarioNivel`', '`UsuarioNivel`', 3, 11, -1, FALSE, '`UsuarioNivel`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'SELECT');
		$this->UsuarioNivel->Sortable = TRUE; // Allow sort
		$this->UsuarioNivel->UsePleaseSelect = TRUE; // Use PleaseSelect by default
		$this->UsuarioNivel->PleaseSelectText = $Language->phrase("PleaseSelect"); // "PleaseSelect" text
		$this->UsuarioNivel->Lookup = new Lookup('UsuarioNivel', 'userlevels', FALSE, 'userlevelid', ["userlevelname","","",""], [], [], [], [], [], [], '', '');
		$this->UsuarioNivel->DefaultErrorMessage = $Language->phrase("IncorrectInteger");
		$this->fields['UsuarioNivel'] = &$this->UsuarioNivel;

		// Activado
		$this->Activado = new DbField('usuarios', 'usuarios', 'x_Activado', 'Activado', '`Activado`', '`Activado`', 202, 1, -1, FALSE, '`Activado`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'CHECKBOX');
		$this->Activado->Nullable = FALSE; // NOT NULL field
		$this->Activado->Sortable = TRUE; // Allow sort
		$this->Activado->DataType = DATATYPE_BOOLEAN;
		$this->Activado->TrueValue = "Y";
		$this->Activado->FalseValue = "N";
		$this->Activado->Lookup = new Lookup('Activado', 'usuarios', FALSE, '', ["","","",""], [], [], [], [], [], [], '', '');
		$this->Activado->OptionCount = 2;
		$this->fields['Activado'] = &$this->Activado;

		// Fecha_Nacimiento
		$this->Fecha_Nacimiento = new DbField('usuarios', 'usuarios', 'x_Fecha_Nacimiento', 'Fecha_Nacimiento', '`Fecha_Nacimiento`', CastDateFieldForLike("`Fecha_Nacimiento`", 0, "DB"), 135, 19, 0, FALSE, '`Fecha_Nacimiento`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->Fecha_Nacimiento->Sortable = TRUE; // Allow sort
		$this->Fecha_Nacimiento->DefaultErrorMessage = str_replace("%s", $GLOBALS["DATE_FORMAT"], $Language->phrase("IncorrectDate"));
		$this->fields['Fecha_Nacimiento'] = &$this->Fecha_Nacimiento;

		// Direccion
		$this->Direccion = new DbField('usuarios', 'usuarios', 'x_Direccion', 'Direccion', '`Direccion`', '`Direccion`', 200, 60, -1, FALSE, '`Direccion`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->Direccion->Sortable = TRUE; // Allow sort
		$this->fields['Direccion'] = &$this->Direccion;

		// Localidad
		$this->Localidad = new DbField('usuarios', 'usuarios', 'x_Localidad', 'Localidad', '`Localidad`', '`Localidad`', 200, 15, -1, FALSE, '`Localidad`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->Localidad->Sortable = TRUE; // Allow sort
		$this->fields['Localidad'] = &$this->Localidad;

		// Provincia
		$this->Provincia = new DbField('usuarios', 'usuarios', 'x_Provincia', 'Provincia', '`Provincia`', '`Provincia`', 200, 15, -1, FALSE, '`Provincia`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->Provincia->Sortable = TRUE; // Allow sort
		$this->fields['Provincia'] = &$this->Provincia;

		// CodigoPostal
		$this->CodigoPostal = new DbField('usuarios', 'usuarios', 'x_CodigoPostal', 'CodigoPostal', '`CodigoPostal`', '`CodigoPostal`', 200, 10, -1, FALSE, '`CodigoPostal`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->CodigoPostal->Sortable = TRUE; // Allow sort
		$this->fields['CodigoPostal'] = &$this->CodigoPostal;

		// Telefono
		$this->Telefono = new DbField('usuarios', 'usuarios', 'x_Telefono', 'Telefono', '`Telefono`', '`Telefono`', 200, 24, -1, FALSE, '`Telefono`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->Telefono->Sortable = TRUE; // Allow sort
		$this->fields['Telefono'] = &$this->Telefono;

		// Extension
		$this->Extension = new DbField('usuarios', 'usuarios', 'x_Extension', 'Extension', '`Extension`', '`Extension`', 200, 4, -1, FALSE, '`Extension`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->Extension->Sortable = TRUE; // Allow sort
		$this->fields['Extension'] = &$this->Extension;

		// Email
		$this->_Email = new DbField('usuarios', 'usuarios', 'x__Email', 'Email', '`Email`', '`Email`', 200, 30, -1, FALSE, '`Email`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->_Email->Sortable = TRUE; // Allow sort
		$this->fields['Email'] = &$this->_Email;

		// Foto
		$this->Foto = new DbField('usuarios', 'usuarios', 'x_Foto', 'Foto', '`Foto`', '`Foto`', 200, 255, -1, FALSE, '`Foto`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->Foto->Sortable = TRUE; // Allow sort
		$this->fields['Foto'] = &$this->Foto;

		// Notas
		$this->Notas = new DbField('usuarios', 'usuarios', 'x_Notas', 'Notas', '`Notas`', '`Notas`', 201, -1, -1, FALSE, '`Notas`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXTAREA');
		$this->Notas->Sortable = TRUE; // Allow sort
		$this->fields['Notas'] = &$this->Notas;

		// Perfil
		$this->Perfil = new DbField('usuarios', 'usuarios', 'x_Perfil', 'Perfil', '`Perfil`', '`Perfil`', 201, -1, -1, FALSE, '`Perfil`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXTAREA');
		$this->Perfil->Sortable = TRUE; // Allow sort
		$this->fields['Perfil'] = &$this->Perfil;
	}

	// Field Visibility
	public function getFieldVisibility($fldParm)
	{
		global $Security;
		return $this->$fldParm->Visible; // Returns original value
	}

	// Set left column class (must be predefined col-*-* classes of Bootstrap grid system)
	function setLeftColumnClass($class)
	{
		if (preg_match('/^col\-(\w+)\-(\d+)$/', $class, $match)) {
			$this->LeftColumnClass = $class . " col-form-label ew-label";
			$this->RightColumnClass = "col-" . $match[1] . "-" . strval(12 - (int)$match[2]);
			$this->OffsetColumnClass = $this->RightColumnClass . " " . str_replace("col-", "offset-", $class);
			$this->TableLeftColumnClass = preg_replace('/^col-\w+-(\d+)$/', "w-col-$1", $class); // Change to w-col-*
		}
	}

	// Single column sort
	public function updateSort(&$fld)
	{
		if ($this->CurrentOrder == $fld->Name) {
			$sortField = $fld->Expression;
			$lastSort = $fld->getSort();
			if ($this->CurrentOrderType == "ASC" || $this->CurrentOrderType == "DESC") {
				$thisSort = $this->CurrentOrderType;
			} else {
				$thisSort = ($lastSort == "ASC") ? "DESC" : "ASC";
			}
			$fld->setSort($thisSort);
			$this->setSessionOrderBy($sortField . " " . $thisSort); // Save to Session
		} else {
			$fld->setSort("");
		}
	}

	// Table level SQL
	public function getSqlFrom() // From
	{
		return ($this->SqlFrom != "") ? $this->SqlFrom : "`usuarios`";
	}
	public function sqlFrom() // For backward compatibility
	{
		return $this->getSqlFrom();
	}
	public function setSqlFrom($v)
	{
		$this->SqlFrom = $v;
	}
	public function getSqlSelect() // Select
	{
		return ($this->SqlSelect != "") ? $this->SqlSelect : "SELECT * FROM " . $this->getSqlFrom();
	}
	public function sqlSelect() // For backward compatibility
	{
		return $this->getSqlSelect();
	}
	public function setSqlSelect($v)
	{
		$this->SqlSelect = $v;
	}
	public function getSqlWhere() // Where
	{
		$where = ($this->SqlWhere != "") ? $this->SqlWhere : "";
		$this->TableFilter = "";
		AddFilter($where, $this->TableFilter);
		return $where;
	}
	public function sqlWhere() // For backward compatibility
	{
		return $this->getSqlWhere();
	}
	public function setSqlWhere($v)
	{
		$this->SqlWhere = $v;
	}
	public function getSqlGroupBy() // Group By
	{
		return ($this->SqlGroupBy != "") ? $this->SqlGroupBy : "";
	}
	public function sqlGroupBy() // For backward compatibility
	{
		return $this->getSqlGroupBy();
	}
	public function setSqlGroupBy($v)
	{
		$this->SqlGroupBy = $v;
	}
	public function getSqlHaving() // Having
	{
		return ($this->SqlHaving != "") ? $this->SqlHaving : "";
	}
	public function sqlHaving() // For backward compatibility
	{
		return $this->getSqlHaving();
	}
	public function setSqlHaving($v)
	{
		$this->SqlHaving = $v;
	}
	public function getSqlOrderBy() // Order By
	{
		return ($this->SqlOrderBy != "") ? $this->SqlOrderBy : "";
	}
	public function sqlOrderBy() // For backward compatibility
	{
		return $this->getSqlOrderBy();
	}
	public function setSqlOrderBy($v)
	{
		$this->SqlOrderBy = $v;
	}

	// Apply User ID filters
	public function applyUserIDFilters($filter, $id = "")
	{
		global $Security;

		// Add User ID filter
		if ($Security->currentUserID() != "" && !$Security->isAdmin()) { // Non system admin
			$filter = $this->addUserIDFilter($filter, $id);
		}
		return $filter;
	}

	// Check if User ID security allows view all
	public function userIDAllow($id = "")
	{
		$allow = $this->UserIDAllowSecurity;
		switch ($id) {
			case "add":
			case "copy":
			case "gridadd":
			case "register":
			case "addopt":
				return (($allow & 1) == 1);
			case "edit":
			case "gridedit":
			case "update":
			case "changepwd":
			case "forgotpwd":
				return (($allow & 4) == 4);
			case "delete":
				return (($allow & 2) == 2);
			case "view":
				return (($allow & 32) == 32);
			case "search":
				return (($allow & 64) == 64);
			case "lookup":
				return (($allow & 256) == 256);
			default:
				return (($allow & 8) == 8);
		}
	}

	// Get recordset
	public function getRecordset($sql, $rowcnt = -1, $offset = -1)
	{
		$conn = $this->getConnection();
		$conn->raiseErrorFn = Config("ERROR_FUNC");
		$rs = $conn->selectLimit($sql, $rowcnt, $offset);
		$conn->raiseErrorFn = "";
		return $rs;
	}

	// Get record count
	public function getRecordCount($sql, $c = NULL)
	{
		$cnt = -1;
		$rs = NULL;
		$sql = preg_replace('/\/\*BeginOrderBy\*\/[\s\S]+\/\*EndOrderBy\*\//', "", $sql); // Remove ORDER BY clause (MSSQL)
		$pattern = '/^SELECT\s([\s\S]+)\sFROM\s/i';

		// Skip Custom View / SubQuery / SELECT DISTINCT / ORDER BY
		if (($this->TableType == 'TABLE' || $this->TableType == 'VIEW' || $this->TableType == 'LINKTABLE') &&
			preg_match($pattern, $sql) && !preg_match('/\(\s*(SELECT[^)]+)\)/i', $sql) &&
			!preg_match('/^\s*select\s+distinct\s+/i', $sql) && !preg_match('/\s+order\s+by\s+/i', $sql)) {
			$sqlwrk = "SELECT COUNT(*) FROM " . preg_replace($pattern, "", $sql);
		} else {
			$sqlwrk = "SELECT COUNT(*) FROM (" . $sql . ") COUNT_TABLE";
		}
		$conn = $c ?: $this->getConnection();
		if ($rs = $conn->execute($sqlwrk)) {
			if (!$rs->EOF && $rs->FieldCount() > 0) {
				$cnt = $rs->fields[0];
				$rs->close();
			}
			return (int)$cnt;
		}

		// Unable to get count, get record count directly
		if ($rs = $conn->execute($sql)) {
			$cnt = $rs->RecordCount();
			$rs->close();
			return (int)$cnt;
		}
		return $cnt;
	}

	// Get SQL
	public function getSql($where, $orderBy = "")
	{
		return BuildSelectSql($this->getSqlSelect(), $this->getSqlWhere(),
			$this->getSqlGroupBy(), $this->getSqlHaving(), $this->getSqlOrderBy(),
			$where, $orderBy);
	}

	// Table SQL
	public function getCurrentSql()
	{
		$filter = $this->CurrentFilter;
		$filter = $this->applyUserIDFilters($filter);
		$sort = $this->getSessionOrderBy();
		return $this->getSql($filter, $sort);
	}

	// Table SQL with List page filter
	public function getListSql()
	{
		$filter = $this->UseSessionForListSql ? $this->getSessionWhere() : "";
		AddFilter($filter, $this->CurrentFilter);
		$filter = $this->applyUserIDFilters($filter);
		$this->Recordset_Selecting($filter);
		$select = $this->getSqlSelect();
		$sort = $this->UseSessionForListSql ? $this->getSessionOrderBy() : "";
		return BuildSelectSql($select, $this->getSqlWhere(), $this->getSqlGroupBy(),
			$this->getSqlHaving(), $this->getSqlOrderBy(), $filter, $sort);
	}

	// Get ORDER BY clause
	public function getOrderBy()
	{
		$sort = $this->getSessionOrderBy();
		return BuildSelectSql("", "", "", "", $this->getSqlOrderBy(), "", $sort);
	}

	// Get record count based on filter (for detail record count in master table pages)
	public function loadRecordCount($filter)
	{
		$origFilter = $this->CurrentFilter;
		$this->CurrentFilter = $filter;
		$this->Recordset_Selecting($this->CurrentFilter);
		$select = $this->TableType == 'CUSTOMVIEW' ? $this->getSqlSelect() : "SELECT * FROM " . $this->getSqlFrom();
		$groupBy = $this->TableType == 'CUSTOMVIEW' ? $this->getSqlGroupBy() : "";
		$having = $this->TableType == 'CUSTOMVIEW' ? $this->getSqlHaving() : "";
		$sql = BuildSelectSql($select, $this->getSqlWhere(), $groupBy, $having, "", $this->CurrentFilter, "");
		$cnt = $this->getRecordCount($sql);
		$this->CurrentFilter = $origFilter;
		return $cnt;
	}

	// Get record count (for current List page)
	public function listRecordCount()
	{
		$filter = $this->getSessionWhere();
		AddFilter($filter, $this->CurrentFilter);
		$filter = $this->applyUserIDFilters($filter);
		$this->Recordset_Selecting($filter);
		$select = $this->TableType == 'CUSTOMVIEW' ? $this->getSqlSelect() : "SELECT * FROM " . $this->getSqlFrom();
		$groupBy = $this->TableType == 'CUSTOMVIEW' ? $this->getSqlGroupBy() : "";
		$having = $this->TableType == 'CUSTOMVIEW' ? $this->getSqlHaving() : "";
		$sql = BuildSelectSql($select, $this->getSqlWhere(), $groupBy, $having, "", $filter, "");
		$cnt = $this->getRecordCount($sql);
		return $cnt;
	}

	// INSERT statement
	protected function insertSql(&$rs)
	{
		$names = "";
		$values = "";
		foreach ($rs as $name => $value) {
			if (!isset($this->fields[$name]) || $this->fields[$name]->IsCustom)
				continue;
			if (Config("ENCRYPTED_PASSWORD") && $name == Config("LOGIN_PASSWORD_FIELD_NAME"))
				$value = Config("CASE_SENSITIVE_PASSWORD") ? EncryptPassword($value) : EncryptPassword(strtolower($value));
			$names .= $this->fields[$name]->Expression . ",";
			$values .= QuotedValue($value, $this->fields[$name]->DataType, $this->Dbid) . ",";
		}
		$names = preg_replace('/,+$/', "", $names);
		$values = preg_replace('/,+$/', "", $values);
		return "INSERT INTO " . $this->UpdateTable . " (" . $names . ") VALUES (" . $values . ")";
	}

	// Insert
	public function insert(&$rs)
	{
		$conn = $this->getConnection();
		$success = $conn->execute($this->insertSql($rs));
		if ($success) {

			// Get insert id if necessary
			$this->id->setDbValue($conn->insert_ID());
			$rs['id'] = $this->id->DbValue;
		}
		return $success;
	}

	// UPDATE statement
	protected function updateSql(&$rs, $where = "", $curfilter = TRUE)
	{
		$sql = "UPDATE " . $this->UpdateTable . " SET ";
		foreach ($rs as $name => $value) {
			if (!isset($this->fields[$name]) || $this->fields[$name]->IsCustom || $this->fields[$name]->IsAutoIncrement)
				continue;
			if (Config("ENCRYPTED_PASSWORD") && $name == Config("LOGIN_PASSWORD_FIELD_NAME")) {
				if ($value == $this->fields[$name]->OldValue) // No need to update hashed password if not changed
					continue;
				$value = Config("CASE_SENSITIVE_PASSWORD") ? EncryptPassword($value) : EncryptPassword(strtolower($value));
			}
			$sql .= $this->fields[$name]->Expression . "=";
			$sql .= QuotedValue($value, $this->fields[$name]->DataType, $this->Dbid) . ",";
		}
		$sql = preg_replace('/,+$/', "", $sql);
		$filter = ($curfilter) ? $this->CurrentFilter : "";
		if (is_array($where))
			$where = $this->arrayToFilter($where);
		AddFilter($filter, $where);
		if ($filter != "")
			$sql .= " WHERE " . $filter;
		return $sql;
	}

	// Update
	public function update(&$rs, $where = "", $rsold = NULL, $curfilter = TRUE)
	{
		$conn = $this->getConnection();
		$success = $conn->execute($this->updateSql($rs, $where, $curfilter));
		return $success;
	}

	// DELETE statement
	protected function deleteSql(&$rs, $where = "", $curfilter = TRUE)
	{
		$sql = "DELETE FROM " . $this->UpdateTable . " WHERE ";
		if (is_array($where))
			$where = $this->arrayToFilter($where);
		if ($rs) {
			if (array_key_exists('id', $rs))
				AddFilter($where, QuotedName('id', $this->Dbid) . '=' . QuotedValue($rs['id'], $this->id->DataType, $this->Dbid));
		}
		$filter = ($curfilter) ? $this->CurrentFilter : "";
		AddFilter($filter, $where);
		if ($filter != "")
			$sql .= $filter;
		else
			$sql .= "0=1"; // Avoid delete
		return $sql;
	}

	// Delete
	public function delete(&$rs, $where = "", $curfilter = FALSE)
	{
		$success = TRUE;
		$conn = $this->getConnection();
		if ($success)
			$success = $conn->execute($this->deleteSql($rs, $where, $curfilter));
		return $success;
	}

	// Load DbValue from recordset or array
	protected function loadDbValues(&$rs)
	{
		if (!$rs || !is_array($rs) && $rs->EOF)
			return;
		$row = is_array($rs) ? $rs : $rs->fields;
		$this->id->DbValue = $row['id'];
		$this->Apellido->DbValue = $row['Apellido'];
		$this->Nombre->DbValue = $row['Nombre'];
		$this->Usuario->DbValue = $row['Usuario'];
		$this->Contrasena->DbValue = $row['Contrasena'];
		$this->ReportarA->DbValue = $row['ReportarA'];
		$this->UsuarioNivel->DbValue = $row['UsuarioNivel'];
		$this->Activado->DbValue = $row['Activado'];
		$this->Fecha_Nacimiento->DbValue = $row['Fecha_Nacimiento'];
		$this->Direccion->DbValue = $row['Direccion'];
		$this->Localidad->DbValue = $row['Localidad'];
		$this->Provincia->DbValue = $row['Provincia'];
		$this->CodigoPostal->DbValue = $row['CodigoPostal'];
		$this->Telefono->DbValue = $row['Telefono'];
		$this->Extension->DbValue = $row['Extension'];
		$this->_Email->DbValue = $row['Email'];
		$this->Foto->DbValue = $row['Foto'];
		$this->Notas->DbValue = $row['Notas'];
		$this->Perfil->DbValue = $row['Perfil'];
	}

	// Delete uploaded files
	public function deleteUploadedFiles($row)
	{
		$this->loadDbValues($row);
	}

	// Record filter WHERE clause
	protected function sqlKeyFilter()
	{
		return "`id` = @id@";
	}

	// Get record filter
	public function getRecordFilter($row = NULL)
	{
		$keyFilter = $this->sqlKeyFilter();
		if (is_array($row))
			$val = array_key_exists('id', $row) ? $row['id'] : NULL;
		else
			$val = $this->id->OldValue !== NULL ? $this->id->OldValue : $this->id->CurrentValue;
		if (!is_numeric($val))
			return "0=1"; // Invalid key
		if ($val == NULL)
			return "0=1"; // Invalid key
		else
			$keyFilter = str_replace("@id@", AdjustSql($val, $this->Dbid), $keyFilter); // Replace key value
		return $keyFilter;
	}

	// Return page URL
	public function getReturnUrl()
	{
		$name = PROJECT_NAME . "_" . $this->TableVar . "_" . Config("TABLE_RETURN_URL");

		// Get referer URL automatically
		if (ServerVar("HTTP_REFERER") != "" && ReferPageName() != CurrentPageName() && ReferPageName() != "login.php") // Referer not same page or login page
			$_SESSION[$name] = ServerVar("HTTP_REFERER"); // Save to Session
		if (@$_SESSION[$name] != "") {
			return $_SESSION[$name];
		} else {
			return "usuarioslist.php";
		}
	}
	public function setReturnUrl($v)
	{
		$_SESSION[PROJECT_NAME . "_" . $this->TableVar . "_" . Config("TABLE_RETURN_URL")] = $v;
	}

	// Get modal caption
	public function getModalCaption($pageName)
	{
		global $Language;
		if ($pageName == "usuariosview.php")
			return $Language->phrase("View");
		elseif ($pageName == "usuariosedit.php")
			return $Language->phrase("Edit");
		elseif ($pageName == "usuariosadd.php")
			return $Language->phrase("Add");
		else
			return "";
	}

	// List URL
	public function getListUrl()
	{
		return "usuarioslist.php";
	}

	// View URL
	public function getViewUrl($parm = "")
	{
		if ($parm != "")
			$url = $this->keyUrl("usuariosview.php", $this->getUrlParm($parm));
		else
			$url = $this->keyUrl("usuariosview.php", $this->getUrlParm(Config("TABLE_SHOW_DETAIL") . "="));
		return $this->addMasterUrl($url);
	}

	// Add URL
	public function getAddUrl($parm = "")
	{
		if ($parm != "")
			$url = "usuariosadd.php?" . $this->getUrlParm($parm);
		else
			$url = "usuariosadd.php";
		return $this->addMasterUrl($url);
	}

	// Edit URL
	public function getEditUrl($parm = "")
	{
		$url = $this->keyUrl("usuariosedit.php", $this->getUrlParm($parm));
		return $this->addMasterUrl($url);
	}

	// Inline edit URL
	public function getInlineEditUrl()
	{
		$url = $this->keyUrl(CurrentPageName(), $this->getUrlParm("action=edit"));
		return $this->addMasterUrl($url);
	}

	// Copy URL
	public function getCopyUrl($parm = "")
	{
		$url = $this->keyUrl("usuariosadd.php", $this->getUrlParm($parm));
		return $this->addMasterUrl($url);
	}

	// Inline copy URL
	public function getInlineCopyUrl()
	{
		$url = $this->keyUrl(CurrentPageName(), $this->getUrlParm("action=copy"));
		return $this->addMasterUrl($url);
	}

	// Delete URL
	public function getDeleteUrl()
	{
		return $this->keyUrl("usuariosdelete.php", $this->getUrlParm());
	}

	// Add master url
	public function addMasterUrl($url)
	{
		return $url;
	}
	public function keyToJson($htmlEncode = FALSE)
	{
		$json = "";
		$json .= "id:" . JsonEncode($this->id->CurrentValue, "number");
		$json = "{" . $json . "}";
		if ($htmlEncode)
			$json = HtmlEncode($json);
		return $json;
	}

	// Add key value to URL
	public function keyUrl($url, $parm = "")
	{
		$url = $url . "?";
		if ($parm != "")
			$url .= $parm . "&";
		if ($this->id->CurrentValue != NULL) {
			$url .= "id=" . urlencode($this->id->CurrentValue);
		} else {
			return "javascript:ew.alert(ew.language.phrase('InvalidRecord'));";
		}
		return $url;
	}

	// Sort URL
	public function sortUrl(&$fld)
	{
		if ($this->CurrentAction || $this->isExport() ||
			in_array($fld->Type, [128, 204, 205])) { // Unsortable data type
				return "";
		} elseif ($fld->Sortable) {
			$urlParm = $this->getUrlParm("order=" . urlencode($fld->Name) . "&amp;ordertype=" . $fld->reverseSort());
			return $this->addMasterUrl(CurrentPageName() . "?" . $urlParm);
		} else {
			return "";
		}
	}

	// Get record keys from Post/Get/Session
	public function getRecordKeys()
	{
		$arKeys = [];
		$arKey = [];
		if (Param("key_m") !== NULL) {
			$arKeys = Param("key_m");
			$cnt = count($arKeys);
		} else {
			if (Param("id") !== NULL)
				$arKeys[] = Param("id");
			elseif (IsApi() && Key(0) !== NULL)
				$arKeys[] = Key(0);
			elseif (IsApi() && Route(2) !== NULL)
				$arKeys[] = Route(2);
			else
				$arKeys = NULL; // Do not setup

			//return $arKeys; // Do not return yet, so the values will also be checked by the following code
		}

		// Check keys
		$ar = [];
		if (is_array($arKeys)) {
			foreach ($arKeys as $key) {
				if (!is_numeric($key))
					continue;
				$ar[] = $key;
			}
		}
		return $ar;
	}

	// Get filter from record keys
	public function getFilterFromRecordKeys($setCurrent = TRUE)
	{
		$arKeys = $this->getRecordKeys();
		$keyFilter = "";
		foreach ($arKeys as $key) {
			if ($keyFilter != "") $keyFilter .= " OR ";
			if ($setCurrent)
				$this->id->CurrentValue = $key;
			else
				$this->id->OldValue = $key;
			$keyFilter .= "(" . $this->getRecordFilter() . ")";
		}
		return $keyFilter;
	}

	// Load rows based on filter
	public function &loadRs($filter)
	{

		// Set up filter (WHERE Clause)
		$sql = $this->getSql($filter);
		$conn = $this->getConnection();
		$rs = $conn->execute($sql);
		return $rs;
	}

	// Load row values from recordset
	public function loadListRowValues(&$rs)
	{
		$this->id->setDbValue($rs->fields('id'));
		$this->Apellido->setDbValue($rs->fields('Apellido'));
		$this->Nombre->setDbValue($rs->fields('Nombre'));
		$this->Usuario->setDbValue($rs->fields('Usuario'));
		$this->Contrasena->setDbValue($rs->fields('Contrasena'));
		$this->ReportarA->setDbValue($rs->fields('ReportarA'));
		$this->UsuarioNivel->setDbValue($rs->fields('UsuarioNivel'));
		$this->Activado->setDbValue($rs->fields('Activado'));
		$this->Fecha_Nacimiento->setDbValue($rs->fields('Fecha_Nacimiento'));
		$this->Direccion->setDbValue($rs->fields('Direccion'));
		$this->Localidad->setDbValue($rs->fields('Localidad'));
		$this->Provincia->setDbValue($rs->fields('Provincia'));
		$this->CodigoPostal->setDbValue($rs->fields('CodigoPostal'));
		$this->Telefono->setDbValue($rs->fields('Telefono'));
		$this->Extension->setDbValue($rs->fields('Extension'));
		$this->_Email->setDbValue($rs->fields('Email'));
		$this->Foto->setDbValue($rs->fields('Foto'));
		$this->Notas->setDbValue($rs->fields('Notas'));
		$this->Perfil->setDbValue($rs->fields('Perfil'));
	}

	// Render list row values
	public function renderListRow()
	{
		global $Security, $CurrentLanguage, $Language;

		// Call Row Rendering event
		$this->Row_Rendering();

		// Common render codes
		// id
		// Apellido
		// Nombre
		// Usuario
		// Contrasena
		// ReportarA
		// UsuarioNivel
		// Activado
		// Fecha_Nacimiento
		// Direccion
		// Localidad
		// Provincia
		// CodigoPostal
		// Telefono
		// Extension
		// Email
		// Foto
		// Notas
		// Perfil
		// id

		$this->id->ViewValue = $this->id->CurrentValue;
		$this->id->ViewCustomAttributes = "";

		// Apellido
		$this->Apellido->ViewValue = $this->Apellido->CurrentValue;
		$this->Apellido->ViewCustomAttributes = "";

		// Nombre
		$this->Nombre->ViewValue = $this->Nombre->CurrentValue;
		$this->Nombre->ViewCustomAttributes = "";

		// Usuario
		$this->Usuario->ViewValue = $this->Usuario->CurrentValue;
		$this->Usuario->ViewCustomAttributes = "";

		// Contrasena
		$this->Contrasena->ViewValue = $Language->phrase("PasswordMask");
		$this->Contrasena->ViewCustomAttributes = "";

		// ReportarA
		$this->ReportarA->ViewValue = $this->ReportarA->CurrentValue;
		$this->ReportarA->ViewValue = FormatNumber($this->ReportarA->ViewValue, 0, -2, -2, -2);
		$this->ReportarA->ViewCustomAttributes = "";

		// UsuarioNivel
		if ($Security->canAdmin()) { // System admin
			$curVal = strval($this->UsuarioNivel->CurrentValue);
			if ($curVal != "") {
				$this->UsuarioNivel->ViewValue = $this->UsuarioNivel->lookupCacheOption($curVal);
				if ($this->UsuarioNivel->ViewValue === NULL) { // Lookup from database
					$filterWrk = "`userlevelid`" . SearchString("=", $curVal, DATATYPE_NUMBER, "");
					$sqlWrk = $this->UsuarioNivel->Lookup->getSql(FALSE, $filterWrk, '', $this);
					$rswrk = Conn()->execute($sqlWrk);
					if ($rswrk && !$rswrk->EOF) { // Lookup values found
						$arwrk = [];
						$arwrk[1] = $rswrk->fields('df');
						$this->UsuarioNivel->ViewValue = $this->UsuarioNivel->displayValue($arwrk);
						$rswrk->Close();
					} else {
						$this->UsuarioNivel->ViewValue = $this->UsuarioNivel->CurrentValue;
					}
				}
			} else {
				$this->UsuarioNivel->ViewValue = NULL;
			}
		} else {
			$this->UsuarioNivel->ViewValue = $Language->phrase("PasswordMask");
		}
		$this->UsuarioNivel->ViewCustomAttributes = "";

		// Activado
		if (ConvertToBool($this->Activado->CurrentValue)) {
			$this->Activado->ViewValue = $this->Activado->tagCaption(1) != "" ? $this->Activado->tagCaption(1) : "Y";
		} else {
			$this->Activado->ViewValue = $this->Activado->tagCaption(2) != "" ? $this->Activado->tagCaption(2) : "N";
		}
		$this->Activado->ViewCustomAttributes = "";

		// Fecha_Nacimiento
		$this->Fecha_Nacimiento->ViewValue = $this->Fecha_Nacimiento->CurrentValue;
		$this->Fecha_Nacimiento->ViewValue = FormatDateTime($this->Fecha_Nacimiento->ViewValue, 0);
		$this->Fecha_Nacimiento->ViewCustomAttributes = "";

		// Direccion
		$this->Direccion->ViewValue = $this->Direccion->CurrentValue;
		$this->Direccion->ViewCustomAttributes = "";

		// Localidad
		$this->Localidad->ViewValue = $this->Localidad->CurrentValue;
		$this->Localidad->ViewCustomAttributes = "";

		// Provincia
		$this->Provincia->ViewValue = $this->Provincia->CurrentValue;
		$this->Provincia->ViewCustomAttributes = "";

		// CodigoPostal
		$this->CodigoPostal->ViewValue = $this->CodigoPostal->CurrentValue;
		$this->CodigoPostal->ViewCustomAttributes = "";

		// Telefono
		$this->Telefono->ViewValue = $this->Telefono->CurrentValue;
		$this->Telefono->ViewCustomAttributes = "";

		// Extension
		$this->Extension->ViewValue = $this->Extension->CurrentValue;
		$this->Extension->ViewCustomAttributes = "";

		// Email
		$this->_Email->ViewValue = $this->_Email->CurrentValue;
		$this->_Email->ViewCustomAttributes = "";

		// Foto
		$this->Foto->ViewValue = $this->Foto->CurrentValue;
		$this->Foto->ViewCustomAttributes = "";

		// Notas
		$this->Notas->ViewValue = $this->Notas->CurrentValue;
		$this->Notas->ViewCustomAttributes = "";

		// Perfil
		$this->Perfil->ViewValue = $this->Perfil->CurrentValue;
		$this->Perfil->ViewCustomAttributes = "";

		// id
		$this->id->LinkCustomAttributes = "";
		$this->id->HrefValue = "";
		$this->id->TooltipValue = "";

		// Apellido
		$this->Apellido->LinkCustomAttributes = "";
		$this->Apellido->HrefValue = "";
		$this->Apellido->TooltipValue = "";

		// Nombre
		$this->Nombre->LinkCustomAttributes = "";
		$this->Nombre->HrefValue = "";
		$this->Nombre->TooltipValue = "";

		// Usuario
		$this->Usuario->LinkCustomAttributes = "";
		$this->Usuario->HrefValue = "";
		$this->Usuario->TooltipValue = "";

		// Contrasena
		$this->Contrasena->LinkCustomAttributes = "";
		$this->Contrasena->HrefValue = "";
		$this->Contrasena->TooltipValue = "";

		// ReportarA
		$this->ReportarA->LinkCustomAttributes = "";
		$this->ReportarA->HrefValue = "";
		$this->ReportarA->TooltipValue = "";

		// UsuarioNivel
		$this->UsuarioNivel->LinkCustomAttributes = "";
		$this->UsuarioNivel->HrefValue = "";
		$this->UsuarioNivel->TooltipValue = "";

		// Activado
		$this->Activado->LinkCustomAttributes = "";
		$this->Activado->HrefValue = "";
		$this->Activado->TooltipValue = "";

		// Fecha_Nacimiento
		$this->Fecha_Nacimiento->LinkCustomAttributes = "";
		$this->Fecha_Nacimiento->HrefValue = "";
		$this->Fecha_Nacimiento->TooltipValue = "";

		// Direccion
		$this->Direccion->LinkCustomAttributes = "";
		$this->Direccion->HrefValue = "";
		$this->Direccion->TooltipValue = "";

		// Localidad
		$this->Localidad->LinkCustomAttributes = "";
		$this->Localidad->HrefValue = "";
		$this->Localidad->TooltipValue = "";

		// Provincia
		$this->Provincia->LinkCustomAttributes = "";
		$this->Provincia->HrefValue = "";
		$this->Provincia->TooltipValue = "";

		// CodigoPostal
		$this->CodigoPostal->LinkCustomAttributes = "";
		$this->CodigoPostal->HrefValue = "";
		$this->CodigoPostal->TooltipValue = "";

		// Telefono
		$this->Telefono->LinkCustomAttributes = "";
		$this->Telefono->HrefValue = "";
		$this->Telefono->TooltipValue = "";

		// Extension
		$this->Extension->LinkCustomAttributes = "";
		$this->Extension->HrefValue = "";
		$this->Extension->TooltipValue = "";

		// Email
		$this->_Email->LinkCustomAttributes = "";
		$this->_Email->HrefValue = "";
		$this->_Email->TooltipValue = "";

		// Foto
		$this->Foto->LinkCustomAttributes = "";
		$this->Foto->HrefValue = "";
		$this->Foto->TooltipValue = "";

		// Notas
		$this->Notas->LinkCustomAttributes = "";
		$this->Notas->HrefValue = "";
		$this->Notas->TooltipValue = "";

		// Perfil
		$this->Perfil->LinkCustomAttributes = "";
		$this->Perfil->HrefValue = "";
		$this->Perfil->TooltipValue = "";

		// Call Row Rendered event
		$this->Row_Rendered();

		// Save data for Custom Template
		$this->Rows[] = $this->customTemplateFieldValues();
	}

	// Render edit row values
	public function renderEditRow()
	{
		global $Security, $CurrentLanguage, $Language;

		// Call Row Rendering event
		$this->Row_Rendering();

		// id
		$this->id->EditAttrs["class"] = "form-control";
		$this->id->EditCustomAttributes = "";
		$this->id->EditValue = $this->id->CurrentValue;
		$this->id->ViewCustomAttributes = "";

		// Apellido
		$this->Apellido->EditAttrs["class"] = "form-control";
		$this->Apellido->EditCustomAttributes = "";
		if (!$this->Apellido->Raw)
			$this->Apellido->CurrentValue = HtmlDecode($this->Apellido->CurrentValue);
		$this->Apellido->EditValue = $this->Apellido->CurrentValue;
		$this->Apellido->PlaceHolder = RemoveHtml($this->Apellido->caption());

		// Nombre
		$this->Nombre->EditAttrs["class"] = "form-control";
		$this->Nombre->EditCustomAttributes = "";
		if (!$this->Nombre->Raw)
			$this->Nombre->CurrentValue = HtmlDecode($this->Nombre->CurrentValue);
		$this->Nombre->EditValue = $this->Nombre->CurrentValue;
		$this->Nombre->PlaceHolder = RemoveHtml($this->Nombre->caption());

		// Usuario
		$this->Usuario->EditAttrs["class"] = "form-control";
		$this->Usuario->EditCustomAttributes = "";
		if (!$this->Usuario->Raw)
			$this->Usuario->CurrentValue = HtmlDecode($this->Usuario->CurrentValue);
		$this->Usuario->EditValue = $this->Usuario->CurrentValue;
		$this->Usuario->PlaceHolder = RemoveHtml($this->Usuario->caption());

		// Contrasena
		$this->Contrasena->EditAttrs["class"] = "form-control";
		$this->Contrasena->EditCustomAttributes = "";
		$this->Contrasena->EditValue = $this->Contrasena->CurrentValue;
		$this->Contrasena->PlaceHolder = RemoveHtml($this->Contrasena->caption());

		// ReportarA
		$this->ReportarA->EditAttrs["class"] = "form-control";
		$this->ReportarA->EditCustomAttributes = "";
		if (!$Security->isAdmin() && $Security->isLoggedIn()) { // Non system admin
			if (SameString($this->id->CurrentValue, CurrentUserID())) {
				$this->ReportarA->EditValue = $this->ReportarA->CurrentValue;
				$this->ReportarA->EditValue = FormatNumber($this->ReportarA->EditValue, 0, -2, -2, -2);
				$this->ReportarA->ViewCustomAttributes = "";
			} else {
			}
		} else {
			$this->ReportarA->EditValue = $this->ReportarA->CurrentValue;
			$this->ReportarA->PlaceHolder = RemoveHtml($this->ReportarA->caption());
		}

		// UsuarioNivel
		$this->UsuarioNivel->EditAttrs["class"] = "form-control";
		$this->UsuarioNivel->EditCustomAttributes = "";
		if (!$Security->canAdmin()) { // System admin
			$this->UsuarioNivel->EditValue = $Language->phrase("PasswordMask");
		} else {
		}

		// Activado
		$this->Activado->EditCustomAttributes = "";
		$this->Activado->EditValue = $this->Activado->options(FALSE);

		// Fecha_Nacimiento
		$this->Fecha_Nacimiento->EditAttrs["class"] = "form-control";
		$this->Fecha_Nacimiento->EditCustomAttributes = "";
		$this->Fecha_Nacimiento->EditValue = FormatDateTime($this->Fecha_Nacimiento->CurrentValue, 8);
		$this->Fecha_Nacimiento->PlaceHolder = RemoveHtml($this->Fecha_Nacimiento->caption());

		// Direccion
		$this->Direccion->EditAttrs["class"] = "form-control";
		$this->Direccion->EditCustomAttributes = "";
		if (!$this->Direccion->Raw)
			$this->Direccion->CurrentValue = HtmlDecode($this->Direccion->CurrentValue);
		$this->Direccion->EditValue = $this->Direccion->CurrentValue;
		$this->Direccion->PlaceHolder = RemoveHtml($this->Direccion->caption());

		// Localidad
		$this->Localidad->EditAttrs["class"] = "form-control";
		$this->Localidad->EditCustomAttributes = "";
		if (!$this->Localidad->Raw)
			$this->Localidad->CurrentValue = HtmlDecode($this->Localidad->CurrentValue);
		$this->Localidad->EditValue = $this->Localidad->CurrentValue;
		$this->Localidad->PlaceHolder = RemoveHtml($this->Localidad->caption());

		// Provincia
		$this->Provincia->EditAttrs["class"] = "form-control";
		$this->Provincia->EditCustomAttributes = "";
		if (!$this->Provincia->Raw)
			$this->Provincia->CurrentValue = HtmlDecode($this->Provincia->CurrentValue);
		$this->Provincia->EditValue = $this->Provincia->CurrentValue;
		$this->Provincia->PlaceHolder = RemoveHtml($this->Provincia->caption());

		// CodigoPostal
		$this->CodigoPostal->EditAttrs["class"] = "form-control";
		$this->CodigoPostal->EditCustomAttributes = "";
		if (!$this->CodigoPostal->Raw)
			$this->CodigoPostal->CurrentValue = HtmlDecode($this->CodigoPostal->CurrentValue);
		$this->CodigoPostal->EditValue = $this->CodigoPostal->CurrentValue;
		$this->CodigoPostal->PlaceHolder = RemoveHtml($this->CodigoPostal->caption());

		// Telefono
		$this->Telefono->EditAttrs["class"] = "form-control";
		$this->Telefono->EditCustomAttributes = "";
		if (!$this->Telefono->Raw)
			$this->Telefono->CurrentValue = HtmlDecode($this->Telefono->CurrentValue);
		$this->Telefono->EditValue = $this->Telefono->CurrentValue;
		$this->Telefono->PlaceHolder = RemoveHtml($this->Telefono->caption());

		// Extension
		$this->Extension->EditAttrs["class"] = "form-control";
		$this->Extension->EditCustomAttributes = "";
		if (!$this->Extension->Raw)
			$this->Extension->CurrentValue = HtmlDecode($this->Extension->CurrentValue);
		$this->Extension->EditValue = $this->Extension->CurrentValue;
		$this->Extension->PlaceHolder = RemoveHtml($this->Extension->caption());

		// Email
		$this->_Email->EditAttrs["class"] = "form-control";
		$this->_Email->EditCustomAttributes = "";
		if (!$this->_Email->Raw)
			$this->_Email->CurrentValue = HtmlDecode($this->_Email->CurrentValue);
		$this->_Email->EditValue = $this->_Email->CurrentValue;
		$this->_Email->PlaceHolder = RemoveHtml($this->_Email->caption());

		// Foto
		$this->Foto->EditAttrs["class"] = "form-control";
		$this->Foto->EditCustomAttributes = "";
		if (!$this->Foto->Raw)
			$this->Foto->CurrentValue = HtmlDecode($this->Foto->CurrentValue);
		$this->Foto->EditValue = $this->Foto->CurrentValue;
		$this->Foto->PlaceHolder = RemoveHtml($this->Foto->caption());

		// Notas
		$this->Notas->EditAttrs["class"] = "form-control";
		$this->Notas->EditCustomAttributes = "";
		$this->Notas->EditValue = $this->Notas->CurrentValue;
		$this->Notas->PlaceHolder = RemoveHtml($this->Notas->caption());

		// Perfil
		$this->Perfil->EditAttrs["class"] = "form-control";
		$this->Perfil->EditCustomAttributes = "";
		$this->Perfil->EditValue = $this->Perfil->CurrentValue;
		$this->Perfil->PlaceHolder = RemoveHtml($this->Perfil->caption());

		// Call Row Rendered event
		$this->Row_Rendered();
	}

	// Aggregate list row values
	public function aggregateListRowValues()
	{
	}

	// Aggregate list row (for rendering)
	public function aggregateListRow()
	{

		// Call Row Rendered event
		$this->Row_Rendered();
	}

	// Export data in HTML/CSV/Word/Excel/Email/PDF format
	public function exportDocument($doc, $recordset, $startRec = 1, $stopRec = 1, $exportPageType = "")
	{
		if (!$recordset || !$doc)
			return;
		if (!$doc->ExportCustom) {

			// Write header
			$doc->exportTableHeader();
			if ($doc->Horizontal) { // Horizontal format, write header
				$doc->beginExportRow();
				if ($exportPageType == "view") {
					$doc->exportCaption($this->id);
					$doc->exportCaption($this->Apellido);
					$doc->exportCaption($this->Nombre);
					$doc->exportCaption($this->Usuario);
					$doc->exportCaption($this->Contrasena);
					$doc->exportCaption($this->ReportarA);
					$doc->exportCaption($this->UsuarioNivel);
					$doc->exportCaption($this->Activado);
					$doc->exportCaption($this->Fecha_Nacimiento);
					$doc->exportCaption($this->Direccion);
					$doc->exportCaption($this->Localidad);
					$doc->exportCaption($this->Provincia);
					$doc->exportCaption($this->CodigoPostal);
					$doc->exportCaption($this->Telefono);
					$doc->exportCaption($this->Extension);
					$doc->exportCaption($this->_Email);
					$doc->exportCaption($this->Foto);
					$doc->exportCaption($this->Notas);
					$doc->exportCaption($this->Perfil);
				} else {
					$doc->exportCaption($this->id);
					$doc->exportCaption($this->Apellido);
					$doc->exportCaption($this->Nombre);
					$doc->exportCaption($this->Usuario);
					$doc->exportCaption($this->ReportarA);
					$doc->exportCaption($this->UsuarioNivel);
					$doc->exportCaption($this->Activado);
					$doc->exportCaption($this->Fecha_Nacimiento);
					$doc->exportCaption($this->Direccion);
					$doc->exportCaption($this->Localidad);
					$doc->exportCaption($this->Provincia);
					$doc->exportCaption($this->CodigoPostal);
					$doc->exportCaption($this->Telefono);
					$doc->exportCaption($this->Extension);
					$doc->exportCaption($this->_Email);
					$doc->exportCaption($this->Foto);
				}
				$doc->endExportRow();
			}
		}

		// Move to first record
		$recCnt = $startRec - 1;
		if (!$recordset->EOF) {
			$recordset->moveFirst();
			if ($startRec > 1)
				$recordset->move($startRec - 1);
		}
		while (!$recordset->EOF && $recCnt < $stopRec) {
			$recCnt++;
			if ($recCnt >= $startRec) {
				$rowCnt = $recCnt - $startRec + 1;

				// Page break
				if ($this->ExportPageBreakCount > 0) {
					if ($rowCnt > 1 && ($rowCnt - 1) % $this->ExportPageBreakCount == 0)
						$doc->exportPageBreak();
				}
				$this->loadListRowValues($recordset);

				// Render row
				$this->RowType = ROWTYPE_VIEW; // Render view
				$this->resetAttributes();
				$this->renderListRow();
				if (!$doc->ExportCustom) {
					$doc->beginExportRow($rowCnt); // Allow CSS styles if enabled
					if ($exportPageType == "view") {
						$doc->exportField($this->id);
						$doc->exportField($this->Apellido);
						$doc->exportField($this->Nombre);
						$doc->exportField($this->Usuario);
						$doc->exportField($this->Contrasena);
						$doc->exportField($this->ReportarA);
						$doc->exportField($this->UsuarioNivel);
						$doc->exportField($this->Activado);
						$doc->exportField($this->Fecha_Nacimiento);
						$doc->exportField($this->Direccion);
						$doc->exportField($this->Localidad);
						$doc->exportField($this->Provincia);
						$doc->exportField($this->CodigoPostal);
						$doc->exportField($this->Telefono);
						$doc->exportField($this->Extension);
						$doc->exportField($this->_Email);
						$doc->exportField($this->Foto);
						$doc->exportField($this->Notas);
						$doc->exportField($this->Perfil);
					} else {
						$doc->exportField($this->id);
						$doc->exportField($this->Apellido);
						$doc->exportField($this->Nombre);
						$doc->exportField($this->Usuario);
						$doc->exportField($this->ReportarA);
						$doc->exportField($this->UsuarioNivel);
						$doc->exportField($this->Activado);
						$doc->exportField($this->Fecha_Nacimiento);
						$doc->exportField($this->Direccion);
						$doc->exportField($this->Localidad);
						$doc->exportField($this->Provincia);
						$doc->exportField($this->CodigoPostal);
						$doc->exportField($this->Telefono);
						$doc->exportField($this->Extension);
						$doc->exportField($this->_Email);
						$doc->exportField($this->Foto);
					}
					$doc->endExportRow($rowCnt);
				}
			}

			// Call Row Export server event
			if ($doc->ExportCustom)
				$this->Row_Export($recordset->fields);
			$recordset->moveNext();
		}
		if (!$doc->ExportCustom) {
			$doc->exportTableFooter();
		}
	}

	// User ID filter
	public function getUserIDFilter($userId)
	{
		$userIdFilter = '`id` = ' . QuotedValue($userId, DATATYPE_NUMBER, Config("USER_TABLE_DBID"));
		$parentUserIdFilter = '`id` IN (SELECT `id` FROM ' . "`usuarios`" . ' WHERE `ReportarA` = ' . QuotedValue($userId, DATATYPE_NUMBER, Config("USER_TABLE_DBID")) . ')';
		$userIdFilter = "($userIdFilter) OR ($parentUserIdFilter)";
		return $userIdFilter;
	}

	// Add User ID filter
	public function addUserIDFilter($filter = "", $id = "")
	{
		global $Security;
		$filterWrk = "";
		if ($id == "")
			$id = (CurrentPageID() == "list") ? $this->CurrentAction : CurrentPageID();
		if (!$this->userIDAllow($id) && !$Security->isAdmin()) {
			$filterWrk = $Security->userIdList();
			if ($filterWrk != "")
				$filterWrk = '`id` IN (' . $filterWrk . ')';
		}

		// Call User ID Filtering event
		$this->UserID_Filtering($filterWrk);
		AddFilter($filter, $filterWrk);
		return $filter;
	}

	// Add Parent User ID filter
	public function addParentUserIDFilter($userId)
	{
		global $Security;
		if (!$Security->isAdmin()) {
			$result = $Security->parentUserIDList($userId);
			if ($result != "")
				$result = '`id` IN (' . $result . ')';
			return $result;
		}
		return "";
	}

	// User ID subquery
	public function getUserIDSubquery(&$fld, &$masterfld)
	{
		global $UserTable;
		$wrk = "";
		$sql = "SELECT " . $masterfld->Expression . " FROM `usuarios`";
		$filter = $this->addUserIDFilter("");
		if ($filter != "")
			$sql .= " WHERE " . $filter;

		// Use subquery
		if (Config("USE_SUBQUERY_FOR_MASTER_USER_ID")) {
			$wrk = $sql;
		} else {

			// List all values
			if ($rs = Conn($UserTable->Dbid)->execute($sql)) {
				while (!$rs->EOF) {
					if ($wrk != "")
						$wrk .= ",";
					$wrk .= QuotedValue($rs->fields[0], $masterfld->DataType, Config("USER_TABLE_DBID"));
					$rs->moveNext();
				}
				$rs->close();
			}
		}
		if ($wrk != "")
			$wrk = $fld->Expression . " IN (" . $wrk . ")";
		return $wrk;
	}

	// Get file data
	public function getFileData($fldparm, $key, $resize, $width = 0, $height = 0)
	{

		// No binary fields
		return FALSE;
	}

	// Table level events
	// Recordset Selecting event
	function Recordset_Selecting(&$filter) {

		// Enter your code here
	}

	// Recordset Selected event
	function Recordset_Selected(&$rs) {

		//echo "Recordset Selected";
	}

	// Recordset Search Validated event
	function Recordset_SearchValidated() {

		// Example:
		//$this->MyField1->AdvancedSearch->SearchValue = "your search criteria"; // Search value

	}

	// Recordset Searching event
	function Recordset_Searching(&$filter) {

		// Enter your code here
	}

	// Row_Selecting event
	function Row_Selecting(&$filter) {

		// Enter your code here
	}

	// Row Selected event
	function Row_Selected(&$rs) {

		//echo "Row Selected";
	}

	// Row Inserting event
	function Row_Inserting($rsold, &$rsnew) {

		// Enter your code here
		// To cancel, set return value to FALSE

		return TRUE;
	}

	// Row Inserted event
	function Row_Inserted($rsold, &$rsnew) {

		//echo "Row Inserted"
	}

	// Row Updating event
	function Row_Updating($rsold, &$rsnew) {

		// Enter your code here
		// To cancel, set return value to FALSE

		return TRUE;
	}

	// Row Updated event
	function Row_Updated($rsold, &$rsnew) {

		//echo "Row Updated";
	}

	// Row Update Conflict event
	function Row_UpdateConflict($rsold, &$rsnew) {

		// Enter your code here
		// To ignore conflict, set return value to FALSE

		return TRUE;
	}

	// Grid Inserting event
	function Grid_Inserting() {

		// Enter your code here
		// To reject grid insert, set return value to FALSE

		return TRUE;
	}

	// Grid Inserted event
	function Grid_Inserted($rsnew) {

		//echo "Grid Inserted";
	}

	// Grid Updating event
	function Grid_Updating($rsold) {

		// Enter your code here
		// To reject grid update, set return value to FALSE

		return TRUE;
	}

	// Grid Updated event
	function Grid_Updated($rsold, $rsnew) {

		//echo "Grid Updated";
	}

	// Row Deleting event
	function Row_Deleting(&$rs) {

		// Enter your code here
		// To cancel, set return value to False

		return TRUE;
	}

	// Row Deleted event
	function Row_Deleted(&$rs) {

		//echo "Row Deleted";
	}

	// Email Sending event
	function Email_Sending($email, &$args) {

		//var_dump($email); var_dump($args); exit();
		return TRUE;
	}

	// Lookup Selecting event
	function Lookup_Selecting($fld, &$filter) {

		//var_dump($fld->Name, $fld->Lookup, $filter); // Uncomment to view the filter
		// Enter your code here

	}

	// Row Rendering event
	function Row_Rendering() {

		// Enter your code here
	}

	// Row Rendered event
	function Row_Rendered() {

		// To view properties of field class, use:
		//var_dump($this-><FieldName>);

	}

	// User ID Filtering event
	function UserID_Filtering(&$filter) {

		// Enter your code here
	}
}
?>