예제 #1
1
파일: yay_parse.php 프로젝트: lastguest/yay
function yay_parse(string $source, Directives $directives = null, BlueContext $blueContext = null) : string
{
    if ($gc = gc_enabled()) {
        gc_disable();
    }
    // important optimization!
    static $globalDirectives = null;
    if (null === $globalDirectives) {
        $globalDirectives = new ArrayObject();
    }
    $directives = $directives ?: new Directives();
    $blueContext = $blueContext ?: new BlueContext();
    $cg = (object) ['ts' => TokenStream::fromSource($source), 'directives' => $directives, 'cycle' => new Cycle($source), 'globalDirectives' => $globalDirectives, 'blueContext' => $blueContext];
    foreach ($cg->globalDirectives as $d) {
        $cg->directives->add($d);
    }
    traverse(midrule(function (TokenStream $ts) use($directives, $blueContext) {
        $token = $ts->current();
        tail_call:
        if (null === $token) {
            return;
        }
        // skip when something looks like a new macro to be parsed
        if ('macro' === (string) $token) {
            return;
        }
        // here we do the 'magic' to match and expand userland macros
        $directives->apply($ts, $token, $blueContext);
        $token = $ts->next();
        goto tail_call;
    }), consume(chain(token(T_STRING, 'macro')->as('declaration'), optional(repeat(rtoken('/^·\\w+$/')))->as('tags'), lookahead(token('{')), commit(chain(braces()->as('pattern'), operator('>>'), braces()->as('expansion')))->as('body'), optional(token(';'))), CONSUME_DO_TRIM)->onCommit(function (Ast $macroAst) use($cg) {
        $scope = Map::fromEmpty();
        $tags = Map::fromValues(array_map('strval', $macroAst->{'tags'}));
        $pattern = new Pattern($macroAst->{'declaration'}->line(), $macroAst->{'body pattern'}, $tags, $scope);
        $expansion = new Expansion($macroAst->{'body expansion'}, $tags, $scope);
        $macro = new Macro($tags, $pattern, $expansion, $cg->cycle);
        $cg->directives->add($macro);
        // allocate the userland macro
        // allocate the userland macro globally if it's declared as global
        if ($macro->tags()->contains('·global')) {
            $cg->globalDirectives[] = $macro;
        }
    }))->parse($cg->ts);
    $expansion = (string) $cg->ts;
    if ($gc) {
        gc_enable();
    }
    return $expansion;
}
예제 #2
0
파일: Pattern.php 프로젝트: lastguest/yay
 private function layer(string $start, string $end, Parser $parser, $cg) : Parser
 {
     return chain(token($start), rtoken('/^···(\\w+)$/')->as('label'), commit(token($end)))->onCommit(function (Ast $result) use($parser, $cg) {
         $id = $this->lookupCapture($result->label);
         $cg->parsers[] = (clone $parser)->as($id);
     });
 }
예제 #3
0
function transaction_started()
{
    global $db;
    try {
        if ($db->beginTransaction()) {
            return true;
        }
        $db - commit();
        return false;
    } catch (PDOException $e) {
        return true;
    }
}
예제 #4
0
 public function postLunbo()
 {
     $options = $this->request()->only(['lb_image1', 'lb_url1', 'lb_title1', 'lb_image2', 'lb_url2', 'lb_title2', 'lb_image3', 'lb_url3', 'lb_title3']);
     try {
         transaction();
         foreach ($options as $key => $option) {
             Option::where('key', $key)->update(['value' => $option]);
         }
         commit();
         return $this->success('保存成功');
     } catch (\Exception $exception) {
         rollback();
     }
     return $this->error('修改失败,请稍后再试');
 }
function UpdatePlanetBatimentQueueList($planetid)
{
    $RetValue = false;
    $now = time();
    begin_transaction();
    $CurrentPlanet = doquery("SELECT * FROM {{table}} WHERE `id` = '" . $planetid . "' FOR UPDATE", 'planets', true);
    if (!$CurrentPlanet || $CurrentPlanet['b_building'] == 0 || $CurrentPlanet['b_building'] > $now) {
        rollback();
        return false;
    }
    $CurrentUser = doquery("SELECT * FROM {{table}} WHERE `id` = '" . $CurrentPlanet['id_owner'] . "' LOCK IN SHARE MODE", 'users', true);
    if (!$CurrentUser) {
        return false;
    }
    PlanetResourceUpdate($CurrentUser, $CurrentPlanet, $CurrentPlanet['b_building'], false);
    CheckPlanetBuildingQueue($CurrentPlanet, $CurrentUser);
    commit();
}
예제 #6
0
 function transferir($idOrigem, $cadastroOrigem, $valor, $idDestino, $cadastroDestino)
 {
     if ($this->isPessoaJuridica($cadastroDestino)) {
         try {
             beginTransaction();
             $ps = $this->executar('SELECT * FROM conta WHERE id_conta = ?', array($idOrigem));
             $p = $ps->fetchObject();
             if ($p->saldo < $valor) {
                 rollBack();
                 throw new TransferenciaException('Saldo da conta de origem insuficiente');
             }
             $ps = $this->executar('UPDATE conta SET saldo = saldo - ? WHERE id_conta = ?', array($valor, $idOrigem));
             $valorDoisPorCento = $valor * 0.02;
             $valorNovo = $valor - $valor * 0.02;
             $ps = $this->executar('UPDATE conta SET saldo = saldo + ? WHERE id_conta = ?', array($valorDoisPorCento, 0));
             $ps = $this->executar('UPDATE conta SET saldo = saldo + ? WHERE id_conta = ?', array($valorNovo, $idDestino));
             commit();
         } catch (Exception $e) {
             rollBack();
             throw new TransferenciaException('Erro ao realizar transferencia');
         }
     } else {
         try {
             beginTransaction();
             $ps = $this->executar('SELECT * FROM conta WHERE id_conta = ?', array($idOrigem));
             $p = $ps->fetchObject();
             if ($p->saldo < $valor) {
                 rollBack();
                 throw new TransferenciaException('Saldo da conta de origem insuficiente');
             }
             $ps = $this->executar('UPDATE conta SET saldo = saldo - ? WHERE id_conta = ?', array($valor, $idOrigem));
             $ps = $this->executar('UPDATE conta SET saldo = saldo + ? WHERE id_conta = ?', array($valor, $idDestino));
             commit();
         } catch (Exception $e) {
             rollBack();
             throw new TransferenciaException('Erro ao realizar transferencia');
         }
     }
 }
예제 #7
0
function insert_sql_data( $db_conn, $p_campaigns, $p_headers, $p_details )
// insert the header and detail data into the file
// with appropriate safeguards to ensure full 
// completion or rollback of the transaction.
{
GLOBAL $msg_log;

	$success = TRUE;
// Wrap all this in a transaction
// First, turn off autocommit
	$qry = "set autocommit=0";
//pre_echo( $qry );
	$success = mysql_query( $qry, $db_conn );

// Second, take care of all ALTER TABLE queries.  Due to a (documented)
// glitch in MySQL, these commands force a transaction to commit, 
// which sucks.

	if ($success) 
	{ // Create the temp_header table
		$qry = "CREATE TEMPORARY TABLE temp_header LIKE contract_header";
//pre_echo( $qry );
		$success = mysql_query( $qry, $db_conn );
		if (!$success) 
		{
			message_log_append( $msg_log, mysql_error( $db_conn ), MSG_LOG_ERROR );
		}
	}

	if ($success) 
	{ // Create the temp_detail table
		$qry = "CREATE TEMPORARY TABLE temp_detail LIKE contract_detail";
//pre_echo( $qry );
		$success = mysql_query( $qry, $db_conn );
		if (!$success)
		{
			message_log_append( $msg_log, mysql_error( $db_conn ), MSG_LOG_ERROR );
		}
	}

	if ($success) 
	{ // Delete the Seq field from table temp_header
		$qry = "ALTER TABLE temp_header DROP COLUMN Seq";
//pre_echo( $qry );
		$success = mysql_query( $qry, $db_conn );
		if (!$success)
		{
			message_log_append( $msg_log, mysql_error( $db_conn ), MSG_LOG_ERROR );
		}
	}

    if ($success) 
	{ // Delete the Line column from table temp_detail
		$qry = "ALTER TABLE temp_detail DROP COLUMN Line";
//pre_echo( $qry );
		$success = mysql_query( $qry, $db_conn );
		if (!$success)
		{
			message_log_append( $msg_log, mysql_error( $db_conn ), MSG_LOG_ERROR );
		}
	}

// loop through the campaigns, headers, and details to insert the
// data into the SQL database.  Keep solid track of all error
// results so that we can ROLLBACK on any error.
	if ($success) 
	{
//echo "<pre>";
//var_dump( $p_campaigns );  echo "</pre><br>";
		$success = begin( $db_conn );
		if (!$success)
		{
			message_log_append( $msg_log, "Error in START TRANSACTION: " . mysql_error( $db_conn ), MSG_LOG_ERROR );
		}
	}

// do the work here, and keep track of $success
// If we need to create a new agency record, do that here.
	$new_agency = FALSE;
	if ($success && is_null( $p_campaigns[0][ 'Agency Record' ])) 
	{
		$agent_name = $p_campaigns[0][ 'Agency Name' ];
		$rate = DEFAULT_AGENCY_RATE / 10;
		if ($success = agency_insert( $db_conn, $agent_name, $rate, $aindex )) 
		{
			$p_campaigns[0][ 'Agency Record' ] = agency_record( $agent_name, OPERATOR_NAME );
			$success = !is_null( $p_campaigns[0][ 'Agency Record' ]);
		} // if agency_insert
		if ($success) 
		{
			$new_agency = TRUE;
			message_log_append( $msg_log, "Agency created: " .
			"Seq = $aindex, Name = '$agent_name'", MSG_LOG_WARNING );
		} 
		else 
		{
			message_log_append( $msg_log, "Error while creating " . "Agency '$agent_name': " . mysql_error( $db_conn ), MSG_LOG_ERROR );
		}
	} // if null agency record

// If we need to create a new customer record, do that here.

	$new_customer = FALSE;
	if ($success && is_null( $p_campaigns[0][ 'Customer Record' ])) 
	{
		$cust_name = $p_campaigns[0][ 'Customer Name' ];
		$rate = DEFAULT_CUST_DISCOUNT;
		if ($success = customer_insert( $db_conn, $cust_name, $rate, $cindex )) 
		{
			$p_campaigns[0][ 'Customer Record' ] = cust_record( $cust_name, OPERATOR_NAME );
			$success = !is_null( $p_campaigns[0][ 'Customer Record' ]);
		} // if customer_insert
		if ($success) 
		{
			$new_customer = TRUE;
			message_log_append( $msg_log, "Customer created: " . "Seq = $cindex, Name = '$cust_name'", MSG_LOG_WARNING );
		} 
		else 
		{
			message_log_append( $msg_log, "Error while creating " . "Customer '$cust_name' " . mysql_error( $db_conn ), MSG_LOG_ERROR );
		}
	} // if null customer record

	if ($success) 
	{
// build the list of header fields, in order with 'quote required' flag
//  [n][0] is field name, [n][1] is boolean T=quote required, F=not
		$hdr_flds = build_header_field_array();
// A SQL INSERT statement lead-in
		$hdr_sql  = "INSERT INTO temp_header ( ";
		$hdr_sql .= fld_list( $hdr_flds ) . ") VALUES\n";

// build the list of detail fields, in order with 'quote required' flag
//  [n][0] is field name, [n][1] is boolean T=quote required, F=not

		$det_flds = build_detail_field_array();

// A SQL INSERT statement lead-in
		$det_sql  = "INSERT INTO temp_detail ( ";
		$det_sql .= fld_list( $det_flds ) . ") VALUES ";

// Here we go.  We'll loop through each contract header record,
// and its accompanying detail records.

		$n_inserted = 0;

		while ($success && (list( $key ) = each( $p_headers ))) 
		{
		    if (count( $p_details[ $key ] ) > 0) 
			{
//	If we created a new agency or customer above, update 
//	the respective header fields.
				if ($new_customer) 
				{
					$p_headers[ $key ][ 'CIndex' ] = $cindex;
					$p_headers[ $key ][ 'Discount' ] = $p_campaigns[0][ 'Customer Record' ][ 'Discount' ];
				}
				if ($new_agency) 
				{
					$p_headers[ $key ][ 'AIndex' ] = $aindex;
					$p_headers[ $key ][ 'AgencyComm' ] = $p_campaigns[0][ 'Agency Record' ][ 'Rate' ];
				}
				$row = data_values( $hdr_flds, $p_headers[ $key ] );
				$sql_header  = $hdr_sql;	// INSERT INTO ... VALUES
				$sql_header .= "(" . $row . ");";

				$rows = "";
				foreach ($p_details[ $key ] as $line)
				{
					$rows .= ",\n( " . data_values( $det_flds, $line ) . " )";
				}
				$rows = substr( $rows, 1 );	// remove comma-newline
				$sql_detail  = $det_sql;	// INSERT INTO ... VALUES
				$sql_detail .= $rows;

				if ($success = do_insert( $db_conn, $sql_header, $sql_detail ))
				{
					$n_inserted++;
				}
			} // if detail count > 0
		} // while success and each key
	} // if success

	if ($success) 
	{
		$success = commit( $db_conn );
		if ($success)
		{
			message_log_append( $msg_log, "$n_inserted contract" . ($n_inserted == 1 ? '' : 's') . " imported" );
		}
		else 
		{
			message_log_append( $msg_log, "Error in COMMIT TRANSACTION: " . mysql_error( $db_conn ), MSG_LOG_ERROR );
			if (!rollback( $db_conn ))
			{
				message_log_append( $msg_log, "Error in ROLLBACK TRANSACTION: " . mysql_error( $db_conn ), MSG_LOG_ERROR );
			}
		}
	} 
	else 
	{
		if (!rollback( $db_conn ))
		{
			message_log_append( $msg_log, "Error in ROLLBACK TRANSACTION: " . mysql_error( $db_conn ), MSG_LOG_ERROR );
		}
	} // if success
	return( $success );
} // insert_sql_data
예제 #8
0
 function save($oData)
 {
     if (!$oData["id_orden_compra"]) {
         begin();
         $detalle = array();
         $cabecera = array();
         $cabecera = explode("@@", $oData["cabecera"]);
         $detalle = explode("||", $oData["detalle"]);
         $sql = "INSERT INTO  ordenes_compra (id_proveedor, fecha_orden_compra, nro_orden_compra, generada)\r\n\t\t\t\t\tVALUES (" . $cabecera[0] . ", '" . dateToMySQL($cabecera[1]) . "', " . $cabecera[2] . ", 1)";
         if (!mysql_query($sql)) {
             die('Error: ' . mysql_error());
             rollback();
             return false;
         } else {
             $id = mysql_insert_id();
             foreach ($detalle as $detail) {
                 $values = explode("@@", $detail);
                 $sql = "INSERT INTO detalle_ordenes_compra (id_orden_compra, id_producto, cantidad_detalle_orden_compra) VALUES  (" . $id . ", " . $values[0] . ", " . $values[1] . ")";
                 if (!mysql_query($sql)) {
                     die('Error: ' . mysql_error());
                     rollback();
                     break;
                 }
             }
             if ($cabecera[2]) {
                 $nroVta = $cabecera[2] + 1;
             }
             $sql = "UPDATE parametros SET valor_parametro = " . $nroVta . " WHERE nombre_parametro='nro_orden_compra'";
             if (!mysql_query($sql)) {
                 die('Error: ' . mysql_error());
                 rollback();
                 break;
             } else {
                 commit();
                 return true;
             }
             return false;
         }
     } else {
         $sql = "delete from detalle_ordenes_compra where id_orden_compra=" . $oData["id_orden_compra"];
         getRS($sql);
         $sql = "delete from ordenes_compra where id_orden_compra=" . $oData["id_orden_compra"];
         getRS($sql);
         begin();
         $detalle = array();
         $cabecera = array();
         $cabecera = explode("@@", $oData["cabecera"]);
         $detalle = explode("||", $oData["detalle"]);
         $sql = "INSERT INTO  ordenes_compra (id_proveedor, fecha_orden_compra, nro_orden_compra, generada)\r\n\t\t\t\t\tVALUES (" . $cabecera[0] . ", '" . dateToMySQL($cabecera[1]) . "', " . $cabecera[2] . ", 1)";
         if (!mysql_query($sql)) {
             die('Error: ' . mysql_error());
             rollback();
             return false;
         } else {
             $id = mysql_insert_id();
             foreach ($detalle as $detail) {
                 $values = explode("@@", $detail);
                 $sql = "INSERT INTO detalle_ordenes_compra (id_orden_compra, id_producto, cantidad_detalle_orden_compra) VALUES  (" . $id . ", " . $values[0] . ", " . $values[1] . ")";
                 if (!mysql_query($sql)) {
                     die('Error: ' . mysql_error());
                     rollback();
                     break;
                 }
             }
             if ($cabecera[2]) {
                 $nroVta = $cabecera[2] + 1;
             }
             $sql = "UPDATE parametros SET valor_parametro = " . $nroVta . " WHERE nombre_parametro='nro_orden_compra'";
             if (!mysql_query($sql)) {
                 die('Error: ' . mysql_error());
                 rollback();
                 break;
             } else {
                 commit();
                 return true;
             }
             return false;
         }
     }
 }
예제 #9
0
 public function commit()
 {
     return commit($this->conn);
 }
예제 #10
0
// Get the comments about the user
$commentsResult = mysql_query("SELECT * FROM comments WHERE comments.to_user_id={$userId}", $link) or die("ERROR: Query failed for the list of comments.");
if (mysql_num_rows($commentsResult) == 0) {
    print "<h2>There is no comment for this user.</h2><br>\n";
} else {
    print "<DL>\n";
    while ($commentsRow = mysql_fetch_array($commentsResult)) {
        $authorId = $commentsRow["from_user_id"];
        $authorResult = mysql_query("SELECT nickname FROM users WHERE users.id={$authorId}", $link) or die("ERROR: Query failed for the comment author.");
        if (mysql_num_rows($authorResult) == 0) {
            die("ERROR: This author does not exist.<br>\n");
        } else {
            $authorRow = mysql_fetch_array($authorResult);
            $authorName = $authorRow["nickname"];
        }
        $date = $commentsRow["date"];
        $comment = $commentsRow["comment"];
        print "<DT><b><BIG><a href=\"/PHP/ViewUserInfo.php?userId=" . $authorId . "\">{$authorName}</a></BIG></b>" . " wrote the " . $date . "<DD><i>" . $comment . "</i><p>\n";
        mysql_free_result($authorResult);
    }
    print "</DL>\n";
}
commit($link);
mysql_free_result($userResult);
mysql_free_result($commentsResult);
mysql_close($link);
printHTMLfooter($scriptName, $startTime);
?>
  </body>
</html>
예제 #11
0
    $c->writeln(_("Found directories:"));
    $c->writeln(implode("\n", $dirs));
}
$apps = strip_horde($dirs);
$apps[0] = 'horde';
$c->writeln(wordwrap(sprintf(_("Found applications: %s"), implode(', ', $apps))));
$c->writeln();
switch ($cmd) {
    case 'cleanup':
    case 'commit':
    case 'compendium':
    case 'merge':
        $cmd();
        break;
    case 'commit-help':
        commit(true);
        break;
    case 'extract':
        xtract();
        break;
    case 'init':
        init();
        $c->writeln();
        merge();
        break;
    case 'make':
        cleanup(true);
        $c->writeln();
        make();
        break;
    case 'make-help':
function HandleTechnologieBuild(&$CurrentPlanet, &$CurrentUser)
{
    global $resource;
    if ($CurrentUser['b_tech_planet'] != 0) {
        // Y a une technologie en cours sur une de mes colonies
        if ($CurrentUser['b_tech_planet'] != $CurrentPlanet['id']) {
            // Et ce n'est pas sur celle ci !!
            $WorkingPlanet = doquery("SELECT * FROM {{table}} WHERE `id` = '" . $CurrentUser['b_tech_planet'] . "';", 'planets', true);
        }
        if (isset($WorkingPlanet) && $WorkingPlanet) {
            $ThePlanet = $WorkingPlanet;
        } else {
            $ThePlanet = $CurrentPlanet;
        }
        $now = time();
        if ($ThePlanet['b_tech'] <= $now && $ThePlanet['b_tech_id'] != 0) {
            begin_transaction();
            $Me = doquery("SELECT * FROM {{table}} WHERE `id` = '" . $CurrentUser['id'] . "' FOR UPDATE", 'users', true);
            if ($Me['b_tech_planet'] == $CurrentUser['b_tech_planet']) {
                $Result['WorkOn'] = "";
                $Result['OnWork'] = false;
                return $Result;
            }
            $ThePlanet = doquery("SELECT * FROM {{table}} WHERE `id` = '" . $ThePlanet['id'] . "' FOR UPDATE", 'planets', true);
            if ($ThePlanet['b_tech'] > $now || $ThePlanet['b_tech_id'] == 0) {
                $Result['WorkOn'] = $ThePlanet;
                $Result['OnWork'] = true;
                return $Result;
            }
            // La recherche en cours est terminée ...
            $CurrentUser[$resource[$ThePlanet['b_tech_id']]]++;
            // Mise a jour de la planete sur laquelle la technologie a été recherchée
            $QryUpdatePlanet = "UPDATE {{table}} SET ";
            $QryUpdatePlanet .= "`b_tech` = '0', ";
            $QryUpdatePlanet .= "`b_tech_id` = '0' ";
            $QryUpdatePlanet .= "WHERE ";
            $QryUpdatePlanet .= "`id` = '" . $ThePlanet['id'] . "';";
            doquery($QryUpdatePlanet, 'planets');
            // Mes a jour de la techno sur l'enregistrement Utilisateur
            // Et tant qu'a faire des stats points
            $QryUpdateUser = "******";
            $QryUpdateUser .= "`" . $resource[$ThePlanet['b_tech_id']] . "` = '" . $CurrentUser[$resource[$ThePlanet['b_tech_id']]] . "', ";
            $QryUpdateUser .= "`b_tech_planet` = '0' ";
            $QryUpdateUser .= "WHERE ";
            $QryUpdateUser .= "`id` = '" . $CurrentUser['id'] . "';";
            doquery($QryUpdateUser, 'users');
            $ThePlanet["b_tech_id"] = 0;
            if (isset($WorkingPlanet)) {
                $WorkingPlanet = $ThePlanet;
            } else {
                $CurrentPlanet = $ThePlanet;
            }
            $Result['WorkOn'] = "";
            $Result['OnWork'] = false;
            commit();
        } elseif ($ThePlanet["b_tech_id"] == 0) {
            assert(false);
            // Il n'y a rien a l'ouest ...
            // Pas de Technologie en cours devait y avoir un bug lors de la derniere connexion
            // On met l'enregistrement informant d'une techno en cours de recherche a jours
            doquery("UPDATE {{table}} SET `b_tech_planet` = '0'  WHERE `id` = '" . $CurrentUser['id'] . "';", 'users');
            $Result['WorkOn'] = "";
            $Result['OnWork'] = false;
        } else {
            // Bin on bosse toujours ici ... Alors ne nous derangez pas !!!
            $Result['WorkOn'] = $ThePlanet;
            $Result['OnWork'] = true;
        }
    } else {
        $Result['WorkOn'] = "";
        $Result['OnWork'] = false;
    }
    return $Result;
}
예제 #13
0
 public function postAdd(Register $register)
 {
     //验证表单
     $this->validate($this->request(), ['mobile' => 'required|digits:11', 'birthday' => 'required|date', 'sex' => 'required|in:' . array_keys_impload(UserEnum::$sexForm), 'password' => 'required|min:5|max:20', 'password_confirm' => 'required|required_with:password|same:password', 'marital_status' => 'in:' . array_keys_impload(UserEnum::$maritalForm), 'height' => 'digits:3|between:130,210', 'education' => 'in:' . array_keys_impload(UserEnum::$educationForm), 'salary' => 'in:' . array_keys_impload(UserEnum::$salaryForm), 'user_name' => 'required|min:2|max:15|unique:users', 'email' => 'required|email|unique:users']);
     $form = $this->request()->only(['user_name', 'email', 'mobile', 'birthday', 'password', 'marital_status', 'height', 'education', 'salary', 'province', 'city', 'area']);
     try {
         transaction();
         $user = User::create($form);
         $register->delete();
         commit();
         return $this->success('添加成功', $user);
     } catch (\Exception $exp) {
         rollback();
         return $this->error('抱歉,添加失败');
     }
 }
예제 #14
0
		die ('No se encuentra la base de datos seleccionada : ' . mysql_error());
	}
	
	$lNumber = $_POST['leaseNum'];
	$sDate = $_POST['sDate'];
	$eDate = $_POST['eDate'];
	$duration = $_POST['duration'];
	$studentID = $_POST['student'];
	$placeNum = $_POST['room'];
	

	$contrato = "INSERT INTO Lease VALUES ('$lNumber', '$sDate', '$eDate', '$duration', '$studentID', '$placeNum')";
	begin(); // Empieza la transaccion
	$result = mysql_query($contrato);
	
	if(!$result) {
		
		rollback(); // Si hubo un error se le da rollback
		echo 'Hubo un error';
		exit;
	}
	
	else {
		commit(); //Si fue exitosa se lleva a cabo
		echo 'Operación realizada con éxito';
	}
	
	
	header("Location: confirmacion.php");
?>
예제 #15
0
/**
 * @post update
 */
function update_post_controller($id)
{
    __is_guest();
    if (!empty($_POST)) {
        if (checked_token($_POST['_token'])) {
            __session_start();
            $_SESSION['old'] = [];
            $_SESSION['errors'] = [];
            $rules = ['title' => FILTER_SANITIZE_STRING, 'content' => FILTER_SANITIZE_STRING, 'status' => ['filter' => FILTER_CALLBACK, 'options' => function ($s) {
                if (in_array($s, ['published', 'unpublished'])) {
                    return $s;
                } else {
                    return 'unpublished';
                }
            }], 'published_at' => ['filter' => FILTER_CALLBACK, 'options' => function ($checkbox) {
                if ($checkbox == 'yes') {
                    return new DateTime('now');
                }
            }]];
            $sanitize = filter_input_array(INPUT_POST, $rules);
            $id = (int) $id;
            // test if errors
            if (empty($_POST['title'])) {
                $_SESSION['errors']['title'] = 'title is required';
            }
            if (!empty($_SESSION['errors'])) {
                $_SESSION['old'] = $sanitize;
                redirect('post/create');
                // exit
            }
            if (!empty($_FILES['file']) && is_uploaded_file($_FILES['file']['tmp_name'])) {
                try {
                    $dateFile = upload($_FILES['file']);
                    beginTransaction();
                    update_post_model($id, $sanitize);
                    create_media_model(['filename' => $dateFile['filename'], 'post_id' => $id, 'size' => $dateFile['size']]);
                    commit();
                    setFlashMessage("success stored");
                    redirect('dashboard');
                } catch (Exception $e) {
                    if ($e instanceof RuntimeException) {
                        $_SESSION['old'] = $sanitize;
                        $_SESSION['errors']['upload'] = $e->getMessage();
                        redirect('post/create');
                    }
                    rollback();
                    $_SESSION['old'] = $sanitize;
                    $_SESSION['errors']['file'] = $e->getMessage();
                    redirect('post/create');
                }
            } else {
                try {
                    beginTransaction();
                    update_post_model($id, $sanitize);
                    $media_id = (int) $_POST['m_id'];
                    if (!empty($_POST['m_id']) && !empty($_POST['delete_filename'])) {
                        $media = find_model($media_id, 'medias');
                        $m = $media->fetch();
                        destroy_model($media_id, 'medias');
                    }
                    commit();
                    if (!empty($m)) {
                        unlink(getEnv('UPLOAD_DIRECTORY') . '/' . htmlentities($m['m_filename']));
                    }
                    setFlashMessage(trans('success_updated_post', $sanitize['title']));
                    redirect('dashboard');
                } catch (Exception $e) {
                    rollback();
                    $_SESSION['old'] = $sanitize;
                    $_SESSION['errors']['file'] = $e->getMessage();
                    redirect('post/create');
                }
                throw new RuntimeException('418');
            }
        }
    }
}
예제 #16
0
/**
 * BatimentBuildingPage.php
 *
 * @version 1.1
 * @copyright 2008 by Chlorel for XNova
 */
function BatimentBuildingPage(&$CurrentPlanet, $CurrentUser)
{
    global $lang, $resource, $reslist, $phpEx, $dpath, $game_config, $_GET;
    // Tables of buildings by type of possible planet
    $Allowed['1'] = array(1, 2, 3, 4, 12, 14, 15, 21, 22, 23, 24, 31, 33, 34, 44);
    $Allowed['3'] = array(12, 14, 21, 22, 23, 24, 34, 41, 42, 43);
    // Boucle d'interpretation des eventuelles commandes
    if (isset($_GET['cmd'])) {
        // On passe une commande
        $bThisIsCheated = false;
        $bDoItNow = false;
        $TheCommand = $_GET['cmd'];
        //$ListID       = $_GET['listid'];
        if (isset($_GET['building'])) {
            $Element = $_GET['building'];
            if (!strchr($Element, " ")) {
                if (!strchr($Element, ",")) {
                    if (in_array(trim($Element), $Allowed[$CurrentPlanet['planet_type']])) {
                        $bDoItNow = true;
                    } else {
                        $bThisIsCheated = true;
                    }
                } else {
                    $bThisIsCheated = true;
                }
            } else {
                $bThisIsCheated = true;
            }
        } elseif (isset($_GET['listid'])) {
            $bDoItNow = true;
        }
        if ($bDoItNow == true) {
            begin_transaction();
            $CurrentPlanet = doquery("SELECT * FROM {{table}} WHERE `id` = '" . $CurrentPlanet['id'] . "' FOR UPDATE;", 'planets', true);
            switch ($TheCommand) {
                case 'cancel':
                    // Interrompre le premier batiment de la queue
                    CancelBuildingFromQueue($CurrentPlanet, $CurrentUser);
                    break;
                case 'remove':
                    // Supprimer un element de la queue (mais pas le premier)
                    // $RemID -> element de la liste a supprimer
                    RemoveBuildingFromQueue($CurrentPlanet, $CurrentUser, $_GET['listid']);
                    break;
                case 'insert':
                    // Insere un element dans la queue
                    AddBuildingToQueue($CurrentPlanet, $CurrentUser, $Element, true);
                    break;
                case 'destroy':
                    // Detruit un batiment deja construit sur la planete !
                    AddBuildingToQueue($CurrentPlanet, $CurrentUser, $Element, false);
                    break;
                default:
                    break;
            }
            // switch
            PlanetResourceUpdate($CurrentUser, $CurrentPlanet, time());
            SetNextQueueElementOnTop($CurrentPlanet, $CurrentUser);
            BuildingSavePlanetRecord($CurrentPlanet);
            commit();
        } elseif ($bThisIsCheated == true) {
            ResetThisFuckingCheater($CurrentUser['id']);
        }
    }
    CheckPlanetUsedFields($CurrentPlanet);
    PlanetResourceUpdate($CurrentUser, $CurrentPlanet, time());
    $Queue = ShowBuildingQueue($CurrentPlanet, $CurrentUser);
    // Record what has changed in planet!
    // BuildingSavePlanetRecord ( $CurrentPlanet );
    // Record what has been any changes in users
    // BuildingSaveUserRecord ( $CurrentUser );
    if ($Queue['lenght'] < MAX_BUILDING_QUEUE_SIZE) {
        $CanBuildElement = true;
    } else {
        $CanBuildElement = false;
    }
    $SubTemplate = gettemplate('buildings_builds_row');
    $BuildingPage = "";
    foreach ($lang['tech'] as $Element => $ElementName) {
        if (in_array($Element, $Allowed[$CurrentPlanet['planet_type']])) {
            $CurrentMaxFields = CalculateMaxPlanetFields($CurrentPlanet);
            if ($CurrentPlanet["field_current"] < $CurrentMaxFields - $Queue['lenght']) {
                $RoomIsOk = true;
            } else {
                $RoomIsOk = false;
            }
            if (IsTechnologieAccessible($CurrentUser, $CurrentPlanet, $Element)) {
                $HaveRessources = IsElementBuyable($CurrentUser, $CurrentPlanet, $Element, true, false);
                $parse = array();
                $parse['dpath'] = $dpath;
                $parse['i'] = $Element;
                $BuildingLevel = $CurrentPlanet[$resource[$Element]];
                $parse['nivel'] = $BuildingLevel == 0 ? "" : " (" . $lang['level'] . " " . $BuildingLevel . ")";
                $parse['n'] = $ElementName;
                $parse['descriptions'] = $lang['res']['descriptions'][$Element];
                $ElementBuildTime = GetBuildingTime($CurrentUser, $CurrentPlanet, $Element);
                $parse['time'] = ShowBuildTime($ElementBuildTime);
                $parse['price'] = GetElementPrice($CurrentUser, $CurrentPlanet, $Element);
                $parse['rest_price'] = GetRestPrice($CurrentUser, $CurrentPlanet, $Element);
                $parse['click'] = '';
                $NextBuildLevel = $CurrentPlanet[$resource[$Element]] + 1;
                if ($Element == 31) {
                    // Sp�cial Laboratoire
                    if ($CurrentUser["b_tech_planet"] != 0 && $game_config['BuildLabWhileRun'] != 1) {
                        // Variable qui contient le parametre
                        // On verifie si on a le droit d'evoluer pendant les recherches (Setting dans config)
                        $parse['click'] = "<font color=#FF0000>" . $lang['in_working'] . "</font>";
                    }
                }
                if ($parse['click'] != '') {
                    // Bin on ne fait rien, vu que l'on l'a deja fait au dessus !!
                } elseif ($RoomIsOk && $CanBuildElement) {
                    if ($Queue['lenght'] == 0) {
                        if ($NextBuildLevel == 1) {
                            if ($HaveRessources == true) {
                                $parse['click'] = "<a href=\"?cmd=insert&building=" . $Element . "\"><font color=#00FF00>" . $lang['BuildFirstLevel'] . "</font></a>";
                            } else {
                                $parse['click'] = "<font color=#FF0000>" . $lang['BuildFirstLevel'] . "</font>";
                            }
                        } else {
                            if ($HaveRessources == true) {
                                $parse['click'] = "<a href=\"?cmd=insert&building=" . $Element . "\"><font color=#00FF00>" . $lang['BuildNextLevel'] . " " . $NextBuildLevel . "</font></a>";
                            } else {
                                $parse['click'] = "<font color=#FF0000>" . $lang['BuildNextLevel'] . " " . $NextBuildLevel . "</font>";
                            }
                        }
                    } else {
                        $parse['click'] = "<a href=\"?cmd=insert&building=" . $Element . "\"><font color=#00FF00>" . $lang['InBuildQueue'] . "</font></a>";
                    }
                } elseif ($RoomIsOk && !$CanBuildElement) {
                    if ($NextBuildLevel == 1) {
                        $parse['click'] = "<font color=#FF0000>" . $lang['BuildFirstLevel'] . "</font>";
                    } else {
                        $parse['click'] = "<font color=#FF0000>" . $lang['BuildNextLevel'] . " " . $NextBuildLevel . "</font>";
                    }
                } else {
                    $parse['click'] = "<font color=#FF0000>" . $lang['NoMoreSpace'] . "</font>";
                }
                $BuildingPage .= parsetemplate($SubTemplate, $parse);
            }
        }
    }
    $parse = $lang;
    // Faut il afficher la liste de construction ??
    if ($Queue['lenght'] > 0) {
        $parse['BuildListScript'] = InsertBuildListScript("buildings");
        $parse['BuildList'] = $Queue['buildlist'];
    } else {
        $parse['BuildListScript'] = "";
        $parse['BuildList'] = "";
    }
    $parse['planet_field_current'] = $CurrentPlanet["field_current"];
    $parse['planet_field_max'] = $CurrentPlanet['field_max'] + $CurrentPlanet[$resource[33]] * 5;
    $parse['field_libre'] = $parse['planet_field_max'] - $CurrentPlanet['field_current'];
    $parse['BuildingsList'] = $BuildingPage;
    $page = parsetemplate(gettemplate('buildings_builds'), $parse);
    display($page, '');
}
예제 #17
0
 public static function insertRtt()
 {
     $db = self::__instance();
     $id = $db->insert(self::getTableName(), $function_data);
     self::clearSession();
     return $id;
     //�������ַ�ʽ����Է���sample��DB
     $db = self::__instance();
     //$db=self::__instance(SAMPLE_DB_ID);
     $sql = "insert into splunk_mroom_rtt (REP_DATE,CLIENT_REGION,SEND_HOST,AVG_RTT) \n    values(to_date('2015-01-01','YYYY-MM-DD'),'aa','115.231.160.100','0.03554113')";
     insert_data($dbconn, $sql);
     commit($dbconn);
     $sql = "select " . self::$columns . " from " . self::getTableName() . " order by REP_DATE desc";
     $list = $db->query()->insert();
     if ($list) {
         return $list;
     }
     return array();
 }
예제 #18
0
 function crearItemsDeCarga($id)
 {
     begin();
     if ($this->cargaExists($id)) {
         if (!$this->eliminarItemsDeCarga($id)) {
             rollback();
         }
     }
     $sql = "INSERT INTO cargas (id_reparto, id_producto, cantidad, fecha_update)\n                SELECT  t1.id_reparto, \n                        t4.id_producto,\n                        SUM(t3.cantidad_detalle_venta) cantidad,\n                        NOW()\n                FROM repartos t1\n                INNER JOIN ventas t2 ON t1.id_reparto=t2.id_reparto\n                INNER JOIN detalle_ventas t3 ON t2.id_venta=t3.id_venta\n                INNER JOIN productos t4 ON t3.id_producto=t4.id_producto\n                WHERE t1.id_reparto != 1 AND t1.id_reparto = {$id}\n                GROUP BY t4.id_producto\n                ORDER BY detalle_producto";
     if (!mysql_query($sql)) {
         die('Error: ' . mysql_error());
         rollback();
         return false;
     } else {
         commit();
         return true;
     }
 }
예제 #19
0
        // Create a set of SQL IN lists (e.g. "('seq1', 'seq2',...).  You
        // need a set because there can be limits of 255 IN list members.
        // print "Splitting lists into array of 255\n";
        $lists = array_chunk($message_data['child_seqs'], $max_sql_in_list_count);
        foreach ($lists as $list) {
            $in_list = create_sql_in_list($list);
            $query = "DELETE FROM " . DEFAULTLOGTABLE . " WHERE seq IN {$in_list}";
            // print "Processing in list\n";
            if (!perform_query($query, $dbLink)) {
                rollback($dbLink);
                die("Error: Delete failed.");
            }
        }
    }
}
commit($dbLink);
$dbsecs = get_microtime() - $db_time_start;
print "Debug: Log table modifications complete in {$dbsecs} seconds...\n";
//------------------------------------------------------------------------
// Gather and spit out some stats
//------------------------------------------------------------------------
$query = 'SELECT count(*) AS "count" from ' . DEFAULTLOGTABLE;
$result = perform_query($query, $dbLink);
$row = fetch_array($result);
$num_rows_after = $row['count'];
$savings = $num_rows - $num_rows_after;
$savings_p = round($savings / $num_rows * 100, 0);
echo "\nStarting Row Count = {$num_rows}\n";
echo "Ending Row Count = {$num_rows_after}\n";
echo "Cleaned {$savings} records saving {$savings_p} percent\n";
$time_end = get_microtime();
예제 #20
0
 public function postRegister()
 {
     $this->validate($this->request(), array('realname' => 'required', 'mobile' => 'required|size:11|unique:users,mobile', 'sex' => 'required:in:' . array_keys_impload(\App\Enum\User::$sexLang), 'birthday' => 'required|date', 'marriage' => 'required|in:' . array_keys_impload(\App\Enum\User::$marriageLang), 'like' => 'exists:users,user_id'), array('realname.required' => '请填写真实姓名', 'mobile.required' => '请填写手机号', 'mobile.size' => '手机号格式不正确', 'mobile.unique' => '手机号已被注册', 'sex.required' => '请选择您的性别', 'sex.in' => '您填写的性别有误', 'birthday.required' => '请填写您的生日', 'birthday.date' => '您填写的生日格式不正确', 'marriage.required' => '您填写您的婚姻状态', 'marriage.in' => '婚姻状态不正确', 'like.exist' => '您报名的对象不存在'));
     $form = $this->request()->only('realname', 'mobile', 'sex', 'birthday', 'marriage');
     try {
         transaction();
         //创建用户
         $user = User::create($form);
         if ($this->request()->has('like')) {
             //创建喜欢的人
             $user->like()->create(array('like_user_id' => $this->request()->get('like')));
         }
         //创建用户信息
         $user->info()->create(array());
         //创建择偶条件
         $user->object()->create(array('sex' => $user->sex == \App\Enum\User::SEX_FEMALE ? \App\Enum\User::SEX_MALE : \App\Enum\User::SEX_FEMALE));
         commit();
         return $this->rest()->success($user, '报名成功,管理员审核通过后即可登录');
     } catch (\Exception $ex) {
         rollback();
         dd($ex->getMessage());
         return $this->rest()->error('抱歉,报名失败,请稍后再试');
     }
 }
예제 #21
0
                            if ($datato == 'citas') {
                                $amot = 'Pac: ' . $_POST["PACIENTE_CIT"] . ' - Esp: ' . $_POST["BAREMO_CIT"] . ' - Med: ' . $_POST["PROVEEDOR_CIT"];
                            }
                            audit($datato, 'I', $res, $amot);
                        }
                    } elseif (isset($_POST[$_GET["saveidcampo" . $ix]])) {
                        $response .= $_POST[$_GET["saveidcampo" . $ix]] . "|||";
                    } elseif (isset($adds[$_GET["saveidcampo" . $ix]])) {
                        $response .= $adds[$_GET["saveidcampo" . $ix]] . "|||";
                    }
                }
            }
        }
    } else {
        $data = "<span style='color:green'><br>Ya existe este codigo<b/><br/>Ya sido cargado en el formulario</span>|||" . $_POST[$saveidcampo];
        rollback();
    }
    $txt = "agregados";
}
if ($data) {
    echo $data;
} else {
    if ($result) {
        echo "<b>Datos {$txt} con exito...</b>|||" . $response;
    } else {
        //putxt(mssql_get_last_message());
        echo "<span style='color:#999'>No se completo la operaci&oacute;n...</span>|||" . $response;
    }
}
commit();
예제 #22
0
파일: release.php 프로젝트: rjsmelo/tiki
/**
 * @param $msg
 * @param bool $increment_step
 * @param bool $commit_msg
 * @return bool
 */
function important_step($msg, $increment_step = true, $commit_msg = false)
{
    global $options;
    static $step = 0;
    // Auto-Skip the step if this is a commit step and if there is nothing to commit
    if ($commit_msg && !has_uncommited_changes('.')) {
        return false;
    }
    // Increment step number if needed
    if ($increment_step) {
        $step++;
    }
    if ($commit_msg && $options['no-commit']) {
        print "Skipping actual commit ('{$commit_msg}') because no-commit = true\n";
        return;
    }
    $do_step = false;
    if ($options['force-yes']) {
        important("\n{$step}) {$msg}...");
        $do_step = true;
    } else {
        important("\n{$step}) {$msg}?");
        $prompt = '[Y/n/q/?] ';
        if (function_exists('readline')) {
            // readline function requires php readline extension...
            $c = readline($prompt);
        } else {
            echo $prompt;
            $c = rtrim(fgets(STDIN), "\n");
        }
        switch (strtolower($c)) {
            case 'y':
            case '':
                $do_step = true;
                break;
            case 'n':
                info(">> Skipping step {$step}.");
                $do_step = false;
                break;
            case 'q':
                die;
                break;
            default:
                if ($c != '?') {
                    info(color(">> Unknown answer '{$c}'.", 'red'));
                }
                info(">> You have to type 'y' (Yes), 'n' (No) or 'q' (Quit) and press Enter.");
                return important_step($msg, false);
        }
    }
    if ($commit_msg && $do_step && ($revision = commit($commit_msg))) {
        info(">> Commited revision {$revision}.");
    }
    return $do_step;
}
예제 #23
0
select_data($c1);
// Both inserts have been rolled back
select_data($c2);
insert_data($c2);
// Insert a row using c2
commit($c2);
// Commit using c2
select_data($c1);
// Result of c2 insert is returned
delete_data($c1);
// Delete all rows in table using c1
select_data($c1);
// No rows returned
select_data($c2);
// No rows returned
commit($c1);
// Commit using c1
select_data($c1);
// No rows returned
select_data($c2);
// No rows returned
drop_table($c1);
$db = "";
$c1 = oci_connect("scott", "tiger", $db);
$c2 = oci_connect("scott", "tiger", $db);
echo "</pre>";
function create_table($conn)
{
    $stmt = oci_parse($conn, "create table scott.hallo (test varchar2(64))");
    oci_execute($stmt);
    echo $conn . " created table\n\n";
예제 #24
0
 function saveIndiceEstacional($oData)
 {
     begin();
     $sql = "SELECT * FROM indices_estacionales WHERE id_producto = " . $oData["id_producto"];
     $result = getRS($sql);
     if (!getNrosRows($result)) {
         $dur_periodo = $this->getDuracionPeriodo();
         $cant_dias_anio = date("z", mktime(0, 0, 0, 12, 31, date("Y"))) + 1;
         $periodo_x_anio = number_format($cant_dias_anio / $dur_periodo);
         for ($i = 0; $i < $periodo_x_anio; $i++) {
             if ($i + 1 == $oData["nro_estacion"]) {
                 $sql = "INSERT INTO indices_estacionales (id_producto, orden, valor) VALUES (" . $oData["id_producto"] . "," . ($i + 1) . ", " . $oData["indice_estacional"] . ")";
             } else {
                 $sql = "INSERT INTO indices_estacionales (id_producto, orden) VALUES (" . $oData["id_producto"] . "," . ($i + 1) . ")";
             }
             $rs = getRS($sql);
             if (!$rs) {
                 die('Error: ' . mysql_error());
                 rollback();
             } else {
                 commit();
             }
         }
     } else {
         $sql = "SELECT * FROM indices_estacionales WHERE id_producto = " . $oData["id_producto"] . " and orden = " . $oData["nro_estacion"];
         $result = getRS($sql);
         if (!getNrosRows($result)) {
             $sql = "INSERT INTO indices_estacionales (id_producto, orden, valor) VALUES (" . $oData["id_producto"] . "," . $oData["nro_estacion"] . ", " . $oData["indice_estacional"] . ")";
             $rs = getRS($sql);
             if (!$rs) {
                 die('Error: ' . mysql_error());
                 rollback();
             }
         } else {
             $sql = "UPDATE indices_estacionales SET valor = " . $oData["indice_estacional"] . " WHERE id_producto = " . $oData["id_producto"] . " AND orden = " . $oData["nro_estacion"];
             $rs = getRS($sql);
             if (!$rs) {
                 die('Error: ' . mysql_error());
                 rollback();
             }
         }
     }
 }
예제 #25
0
 public function getSeedMaleAvatar()
 {
     $FILE = new \Illuminate\Filesystem\Filesystem();
     $files = $FILE->files('/Users/vicens/www/meigui/public/uploads/avatar');
     try {
         transaction();
         foreach ($files as $path) {
             $file = $FILE->name($path) . '.jpg';
             $user = User::where('sex', UserEnum::SEX_MALE)->whereNull('avatar')->first();
             if ($user && !$user->getOriginal('avatar')) {
                 $user->update(array('avatar' => $file));
             }
         }
         commit();
         return '添加成功';
     } catch (\Exception $e) {
         rollback();
         return $e->getMessage();
     }
 }
 function executePolitica_SR()
 {
     $sql = "SELECT *\r\n\t\t\t\tFROM productos p\r\n\t\t\t\t  INNER JOIN agotamientos_permitidos ap\r\n\t\t\t\t\tON ap.id_agotamiento = p.id_agotamiento\r\n\t\t\t\tWHERE id_politica = 2";
     $rs = getRS($sql);
     if (getNrosRows($rs)) {
         $flag = false;
         while ($row = getRow($rs)) {
             $sql = "SELECT *\r\n\t\t\t\t\t\tFROM ordenes_compra oc\r\n\t\t\t\t\t\t  INNER JOIN detalle_ordenes_compra doc\r\n\t\t\t\t\t\t\tON doc.id_orden_compra = oc.id_orden_compra\r\n\t\t\t\t\t\t\t  AND id_producto = " . $row["id_producto"] . "\r\n\t\t\t\t\t\tORDER BY fecha_orden_compra DESC LIMIT 1";
             $rsOC = getRS($sql);
             $rowOC = getRow($rsOC);
             $fechaOC = $rowOC["fecha_orden_compra"];
             $fechaActual = date("Y-m-d");
             $diferencia = getDiferenciaEntreFechas($fechaOC, $fechaActual);
             $R = $row["tpo_de_reaprovisionamiento_producto"];
             if ($diferencia >= $R) {
                 $R = $R / 7;
                 // lo convierto a semanas
                 $A = $row["costo_de_emision_producto"];
                 $oData = array();
                 $oData["id_producto"] = $row["id_producto"];
                 $D = $this->getDemandaAnual($oData);
                 $H = $row["tasa_de_almacenamiento_producto"] * $row["precio_unitario_producto"];
                 $Q = number_format(sqrt(2 * $A * $D / $H));
                 $agotamiento = $row["agotamientos_perm_x_anio"];
                 $N = number_format($D / $Q);
                 $nivel_de_serv = 1 - $agotamiento / $N;
                 $k = $this->getFactorDeSeguridad($nivel_de_serv);
                 $data = $this->getMinTpoDeEntregaAndProv($oData);
                 $te = $data["tpo_de_entrega"];
                 $te_sobre_durEnSem = $te / $this->getDuracionPeriodoEnSemanas();
                 $days = number_format($te * 7 + $R);
                 $desv_std = $this->getDesvStd($oData, $days) * $te_sobre_durEnSem;
                 $SS = $k * $desv_std;
                 $mu_e = $this->getDemanda($oData, $days) * $te_sobre_durEnSem;
                 $S = number_format($mu_e + $SS);
                 if ($row["stock_actual_producto"] < $S) {
                     begin();
                     $sql = "UPDATE productos SET nivel_s_producto={$S}, stock_seguridad_producto={$SS} WHERE id_producto=" . $oData["id_producto"];
                     if (!getRS($sql)) {
                         rollback();
                         return false;
                     } else {
                         $exp = new ExpertoOrdenes();
                         $nro_orden = $exp->getNroOrdenCompra();
                         $sql = "INSERT INTO  ordenes_compra (fecha_orden_compra, nro_orden_compra, generada, id_proveedor)\r\n\t\t\t\t\t\t\t\t\tVALUES ('" . date("Y-m-d") . "', " . $nro_orden . ", 0, " . $data["id_proveedor"] . ")";
                         if (!getRS($sql)) {
                             rollback();
                             return false;
                         } else {
                             $id = mysql_insert_id();
                             $cant = $S - $row["stock_actual_producto"];
                             $sql = "INSERT INTO detalle_ordenes_compra (id_orden_compra, id_producto, cantidad_detalle_orden_compra) VALUES  (" . $id . ", " . $oData["id_producto"] . ", " . $cant . ")";
                             if (!getRS($sql)) {
                                 rollback();
                                 return false;
                             } else {
                                 $nro_orden += 1;
                                 $sql = "UPDATE parametros SET valor_parametro = " . $nro_orden . " WHERE nombre_parametro='nro_orden_compra'";
                                 if (!mysql_query($sql)) {
                                     die('Error: ' . mysql_error());
                                     rollback();
                                     return false;
                                 } else {
                                     commit();
                                     $flag = true;
                                 }
                             }
                         }
                     }
                 }
             }
         }
         return $flag;
     }
     return false;
 }