blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
116
path
stringlengths
2
241
src_encoding
stringclasses
31 values
length_bytes
int64
14
3.6M
score
float64
2.52
5.13
int_score
int64
3
5
detected_licenses
listlengths
0
41
license_type
stringclasses
2 values
text
stringlengths
14
3.57M
download_success
bool
1 class
e47f0aef8aac8bab736cae771708ee1ee791f7b2
PHP
eduardofpu/LojaVirtualPHP
/loja/model/Clientes.class.php
UTF-8
19,952
2.890625
3
[]
no_license
<?php /** * Description of Clientes * * @author Eduardo */ class Clientes extends Conexao { private $cli_nome, $cli_sobrenome, $cli_data_nasc, $cli_rg, $cli_cpf, $cli_ddd, $cli_fone, $cli_celular, $cli_endereco, $cli_numero, $cli_bairro, $cli_cidade, $cli_uf, $cli_cep, $cli_email, $cli_data_cad, $cli_hora_cad, $cli_senha; /** * classe pai de conexão */ function __construct() { parent::__construct(); } function GetClientes(){ $query = "SELECT * FROM ".$this->prefix."clientes"; $this->ExecuteSQL($query); $this->GetLista(); } /** * * @param type $id cliente */ function GetClientesID($id){ $query = "SELECT * FROM ".$this->prefix."clientes WHERE cli_id = :id"; $params = array(':id' =>(int)$id); $this->ExecuteSQL($query, $params); $this->GetLista(); } private function GetLista(){ $i=1; while($lista = $this->ListarDados() ): $this->itens[$i] = array( 'cli_id'=>$lista['cli_id'], 'cli_nome'=>$lista['cli_nome'], 'cli_sobrenome'=>$lista['cli_sobrenome'], 'cli_endereco'=>$lista['cli_endereco'], 'cli_numero'=>$lista['cli_numero'], 'cli_bairro'=>$lista['cli_bairro'], 'cli_cidade'=>$lista['cli_cidade'], 'cli_uf'=>$lista['cli_uf'], 'cli_cpf'=>$lista['cli_cpf'], 'cli_cep'=>$lista['cli_cep'], 'cli_rg'=>$lista['cli_rg'], 'cli_ddd'=>$lista['cli_ddd'], 'cli_fone'=>$lista['cli_fone'], 'cli_email'=>$lista['cli_email'], 'cli_celular'=>$lista['cli_celular'], 'cli_pass'=>$lista['cli_pass'], 'cli_data_nasc'=>$lista['cli_data_nasc'], 'cli_hora_cad'=> $lista['cli_hora_cad'], 'cli_data_cad'=>Sistema::Fdata($lista['cli_data_cad']), ); $i++; endwhile; } /** * prepara os campos para inserir e atualizar */ function Preparar($cli_nome, $cli_sobrenome, $cli_data_nasc, $cli_rg, $cli_cpf, $cli_ddd, $cli_fone, $cli_celular, $cli_endereco, $cli_numero, $cli_bairro, $cli_cidade, $cli_uf, $cli_cep, $cli_email, $cli_data_cad, $cli_hora_cad, $cli_senha) { $this->setCli_nome($cli_nome); $this->setCli_sobrenome($cli_sobrenome); $this->setCli_data_nasc($cli_data_nasc); $this->setCli_rg($cli_rg); $this->setCli_cpf($cli_cpf); $this->setCli_ddd($cli_ddd); $this->setCli_fone($cli_fone); $this->setCli_celular($cli_celular); $this->setCli_celular($cli_celular); $this->setCli_endereco($cli_endereco); $this->setCli_numero($cli_numero); $this->setCli_bairro($cli_bairro); $this->setCli_cidade($cli_cidade); $this->setCli_uf($cli_uf); $this->setCli_cep($cli_cep); $this->setCli_email($cli_email); $this->setCli_data_cad($cli_data_cad); $this->setCli_hora_cad($cli_hora_cad); $this->setCli_senha($cli_senha); } function Inserir() { //se for maior que zero significa que exite algum cpf igual------------------------- if($this->GetClienteCPF($this->getCli_cpf())>0): echo '<div class="alert alert-danger" id="erro_mostra">Este CPF já esta cadastrado '; Sistema::VoltarPagina(); echo '</div>'; exit(); endif; //se for maior que zero significa que exite algum email igual---------------------- if($this->GetClienteEmail($this->getCli_email())>0): echo '<div class="alert alert-danger" id="erro_mostra">Este Email já esta cadastrado '; Sistema::VoltarPagina(); echo '</div>'; exit(); endif; //Caso passou na verificação os dados serão gravados no banco------------------------- $query = "INSERT INTO ".$this->prefix."clientes (cli_nome, cli_sobrenome, cli_data_nasc, cli_rg, cli_cpf, cli_ddd, cli_fone, cli_celular, cli_endereco, cli_numero, cli_bairro, cli_cidade, cli_uf, cli_cep, cli_email, cli_data_cad, cli_hora_cad, cli_pass) VALUES (:cli_nome, :cli_sobrenome, :cli_data_nasc, :cli_rg, :cli_cpf, :cli_ddd, :cli_fone, :cli_celular, :cli_endereco, :cli_numero, :cli_bairro, :cli_cidade, :cli_uf, :cli_cep, :cli_email, :cli_data_cad, :cli_hora_cad, :cli_senha)"; $params = array( ':cli_nome'=> $this->getCli_nome(), ':cli_sobrenome'=> $this->getCli_sobrenome(), ':cli_data_nasc'=> $this->getCli_data_nasc(), ':cli_rg'=> $this->getCli_rg(), ':cli_cpf'=> $this->getCli_cpf(), ':cli_ddd'=> $this->getCli_ddd(), ':cli_fone'=> $this->getCli_fone(), ':cli_celular'=> $this->getCli_celular(), ':cli_endereco'=> $this->getCli_endereco(), ':cli_numero'=> $this->getCli_numero(), ':cli_bairro'=> $this->getCli_bairro(), ':cli_cidade'=> $this->getCli_cidade(), ':cli_uf'=> $this->getCli_uf(), ':cli_cep'=> $this->getCli_cep(), ':cli_email'=> $this->getCli_email(), ':cli_data_cad'=> $this->getCli_data_cad(), ':cli_hora_cad'=> $this->getCli_hora_cad(), ':cli_senha'=> $this->getCli_senha(), ); //echo $query; $this->ExecuteSQL($query, $params); } function Alterar($id) { //se o cpf for diferente da sessao------------------------- if($this->GetClienteCPF($this->getCli_cpf())>0 && $this->getCli_cpf() <> $_SESSION['CLI']['cli_cpf']): echo '<div class="alert alert-danger" id="erro_mostra">Este CPF já esta cadastrado '; Sistema::VoltarPagina(); echo '</div>'; exit(); endif; //se o email for diferente da sessao---------------------- if($this->GetClienteEmail($this->getCli_email())>0 && $this->getCli_email() <> $_SESSION['CLI']['cli_email']): echo '<div class="alert alert-danger" id="erro_mostra">Este Email já esta cadastrado '; Sistema::VoltarPagina(); echo '</div>'; exit(); endif; //Caso passou na verificação os dados serão gravados no banco------------------------- $query = "UPDATE ".$this->prefix."clientes SET cli_nome=:cli_nome, cli_sobrenome=:cli_sobrenome, cli_data_nasc=:cli_data_nasc, cli_rg=:cli_rg, cli_cpf=:cli_cpf, cli_ddd=:cli_ddd, cli_fone=:cli_fone, cli_celular=:cli_celular, cli_endereco=:cli_endereco, cli_numero=:cli_numero, cli_bairro=:cli_bairro, cli_cidade=:cli_cidade, cli_uf=:cli_uf, cli_cep=:cli_cep, cli_email=:cli_email, cli_data_cad=:cli_data_cad, cli_hora_cad=:cli_hora_cad, cli_pass=:cli_senha WHERE cli_id =:cli_id"; $params = array( ':cli_nome'=> $this->getCli_nome(), ':cli_sobrenome'=> $this->getCli_sobrenome(), ':cli_data_nasc'=> $this->getCli_data_nasc(), ':cli_rg'=> $this->getCli_rg(), ':cli_cpf'=> $this->getCli_cpf(), ':cli_ddd'=> $this->getCli_ddd(), ':cli_fone'=> $this->getCli_fone(), ':cli_celular'=> $this->getCli_celular(), ':cli_endereco'=> $this->getCli_endereco(), ':cli_numero'=> $this->getCli_numero(), ':cli_bairro'=> $this->getCli_bairro(), ':cli_cidade'=> $this->getCli_cidade(), ':cli_uf'=> $this->getCli_uf(), ':cli_cep'=> $this->getCli_cep(), ':cli_email'=> $this->getCli_email(), ':cli_data_cad'=> $this->getCli_data_cad(), ':cli_hora_cad'=> $this->getCli_hora_cad(), ':cli_senha'=> $this->getCli_senha(), ':cli_id' => (int)$id ); //echo $query; if($this->ExecuteSQL($query, $params)): return true; else: return false; endif; } function AlterarADM($id) { //se o cpf for diferente da sessao------------------------- // if($this->GetClienteCPF($this->getCli_cpf())>0 && $this->getCli_cpf() != $_REQUEST['CLI']['cli_cpf']): // echo '<div class="alert alert-danger" id="erro_mostra">Este CPF já esta cadastrado '; // Sistema::VoltarPagina(); // echo '</div>'; // exit(); // endif; //se o email for diferente da sessao---------------------- // if($this->GetClienteEmail($this->getCli_email())>0 && $this->getCli_email() != $_REQUEST['CLI']['cli_email']): // echo '<div class="alert alert-danger" id="erro_mostra">Este Email já esta cadastrado '; // Sistema::VoltarPagina(); // echo '</div>'; // exit(); // endif; //Caso passou na verificação os dados serão gravados no banco------------------------- $query = "UPDATE ".$this->prefix."clientes SET cli_nome=:cli_nome, cli_sobrenome=:cli_sobrenome, cli_data_nasc=:cli_data_nasc, cli_rg=:cli_rg, cli_cpf=:cli_cpf, cli_ddd=:cli_ddd, cli_fone=:cli_fone, cli_celular=:cli_celular, cli_endereco=:cli_endereco, cli_numero=:cli_numero, cli_bairro=:cli_bairro, cli_cidade=:cli_cidade, cli_uf=:cli_uf, cli_cep=:cli_cep, cli_email=:cli_email WHERE cli_id =:cli_id"; $params = array( ':cli_nome'=> $this->getCli_nome(), ':cli_sobrenome'=> $this->getCli_sobrenome(), ':cli_data_nasc'=> $this->getCli_data_nasc(), ':cli_rg'=> $this->getCli_rg(), ':cli_cpf'=> $this->getCli_cpf(), ':cli_ddd'=> $this->getCli_ddd(), ':cli_fone'=> $this->getCli_fone(), ':cli_celular'=> $this->getCli_celular(), ':cli_endereco'=> $this->getCli_endereco(), ':cli_numero'=> $this->getCli_numero(), ':cli_bairro'=> $this->getCli_bairro(), ':cli_cidade'=> $this->getCli_cidade(), ':cli_uf'=> $this->getCli_uf(), ':cli_cep'=> $this->getCli_cep(), ':cli_email'=> $this->getCli_email(), ':cli_id' => (int)$id ); //echo $query; if($this->ExecuteSQL($query, $params)): return true; else: return false; endif; } /** * * @param string verifica se o cpf exite ou não no banco * @return int total de dados */ function GetClienteCPF($cpf){ $query = "SELECT * FROM ".$this->prefix."clientes WHERE cli_cpf = :cpf "; $params = array(':cpf'=> $cpf); $this->ExecuteSQL($query, $params); return $this->TotalDados(); } /** * * @param string verifica se o email exite ou não no banco * @return int total de dados */ function GetClienteEmail($email){ $query = "SELECT * FROM ".$this->prefix."clientes WHERE cli_email = :email "; $params = array(':email'=> $email); $this->ExecuteSQL($query, $params); return $this->TotalDados(); } function SenhaUpdate($senha,$email){ $query = "UPDATE ".$this->prefix."clientes SET cli_pass = :senha WHERE cli_email = :email "; $this->setCli_senha($senha); $this->setCli_email($email); $params = array(':senha'=> $this->getCli_senha(), ':email'=> $this->getCli_email()); //grava no banco o update $this->ExecuteSQL($query, $params); } /** * * @return metodo get retorna os dados dos clientes */ function getCli_nome() { return $this->cli_nome; } function getCli_sobrenome() { return $this->cli_sobrenome; } function getCli_data_nasc() { return $this->cli_data_nasc; } function getCli_rg() { return $this->cli_rg; } function getCli_cpf() { return $this->cli_cpf; } function getCli_ddd() { return $this->cli_ddd; } function getCli_fone() { return $this->cli_fone; } function getCli_celular() { return $this->cli_celular; } function getCli_endereco() { return $this->cli_endereco; } function getCli_numero() { return $this->cli_numero; } function getCli_bairro() { return $this->cli_bairro; } function getCli_cidade() { return $this->cli_cidade; } function getCli_uf() { return $this->cli_uf; } function getCli_cep() { return $this->cli_cep; } function getCli_email() { return $this->cli_email; } function getCli_data_cad() { return $this->cli_data_cad; } function getCli_hora_cad() { return $this->cli_hora_cad; } function getCli_senha() { return $this->cli_senha; } /** * * @param metodos set Verificar e tratar os valores */ function setCli_nome($cli_nome) { //validando campo nome--------------------------------------------------------- //$nome = filter_var($cli_nome, FILTER_SANITIZE_STRING);// remove caractere e retorna string realiza limpeza if(strlen($cli_nome)<3): echo '<div class="alert alert-danger" id="erro_mostra">Digite seu nome '; Sistema::VoltarPagina(); echo '</div>'; exit(); else: $this->cli_nome = $cli_nome; endif; } function setCli_sobrenome($cli_sobrenome) { //validando campo Sobre nome--------------------------------------------------------- //$sobrenome = filter_var($cli_sobrenome, FILTER_SANITIZE_STRING);// remove caractere e retorna string realiza limpeza if(strlen($cli_sobrenome)<3): echo '<div class="alert alert-danger" id="erro_mostra">Digite seu Sobre nome '; Sistema::VoltarPagina(); echo '</div>'; exit(); else: $this->cli_sobrenome = $cli_sobrenome; endif; } function setCli_data_nasc($cli_data_nasc) { $this->cli_data_nasc = $cli_data_nasc; } function setCli_rg($cli_rg) { $this->cli_rg = $cli_rg; } //Validando CPF-------------------------------------------------------------------------- function setCli_cpf($cli_cpf) { //Validar CPF: CPF PARA TESTE: 21368854303------senha gravada para s97n71tz usuario Eduardo email eduardo27_minotauro@hotmail.com-------- if(!Sistema::ValidarCPF($cli_cpf)): echo '<div class="alert alert-danger" id="erro_mostra">CPF incorreto '; Sistema::VoltarPagina(); echo '</div>'; exit(); else: $this->cli_cpf = $cli_cpf; endif; } //validando ddd------------------------------------------------------------------- function setCli_ddd($cli_ddd) { // faz filtragem pegando somente numeros------------------------------------- $ddd = filter_var($cli_ddd, FILTER_SANITIZE_NUMBER_INT); if(strlen($ddd) !=2): echo '<div class="alert alert-danger" id="erro_mostra">DDD incorreto'; Sistema::VoltarPagina(); echo '</div>'; exit(); else: $this->cli_ddd = $cli_ddd; endif; } function setCli_fone($cli_fone) { $this->cli_fone = $cli_fone; } function setCli_celular($cli_celular) { $this->cli_celular = $cli_celular; } function setCli_endereco($cli_endereco) { $this->cli_endereco = $cli_endereco; } function setCli_numero($cli_numero) { $this->cli_numero = $cli_numero; } function setCli_bairro($cli_bairro) { $this->cli_bairro = $cli_bairro; } function setCli_cidade($cli_cidade) { $this->cli_cidade = $cli_cidade; } //validando Estado------------------------------------------------------------- function setCli_uf($cli_uf) { // faz filtragem pegando somente numeros------------------------------------- $uf = filter_var($cli_uf, FILTER_SANITIZE_STRING);// remove caractere e retorna string realiza limpeza if(strlen($uf) !=2): echo '<div class="alert alert-danger" id="erro_mostra">UF incorreto'; Sistema::VoltarPagina(); echo '</div>'; exit(); else: $this->cli_uf = $cli_uf; endif; } //validando campo cep-------------------------------------------------------------- function setCli_cep($cli_cep) { // faz filtragem pegando somente numeros------------------------------------- $cep = filter_var($cli_cep, FILTER_SANITIZE_NUMBER_INT); if(strlen($cep) !=8): echo '<div class="alert alert-danger" id="erro_mostra">CEP incorreto'; Sistema::VoltarPagina(); echo '</div>'; exit(); else: $this->cli_cep = $cli_cep; endif; } //Verificação de email caso a validação do java script falhe-------------------------------- function setCli_email($cli_email) { if(!filter_var($cli_email, FILTER_VALIDATE_EMAIL)):// retorna um false ou true não realiza limpeza echo '<div class="alert alert-danger" id="erro_mostra">Email incorreto '; Sistema::VoltarPagina(); echo '</div>'; exit(); else: $this->cli_email = $cli_email; endif; } function setCli_data_cad($cli_data_cad) { $this->cli_data_cad = $cli_data_cad; } function setCli_hora_cad($cli_hora_cad) { $this->cli_hora_cad = $cli_hora_cad; } //Se precisar mudar o tipo de criptografia sera necessario mexer somente aqui.... function setCli_senha($cli_senha) { //O md5 vai criptografar a senha //$this->cli_senha = md5($cli_senha); //$this->cli_senha = hash('SHA512', $cli_senha);// SHA512 e uma senha com 128 digitos $this->cli_senha = Sistema::Criptografia($cli_senha); } }
true
1719fd82675939ee91c039f8c67a8d8cd495b2dc
PHP
novalrialan/playlist_lagu
/app/Http/Middleware/PlaylistSongMiddleware.php
UTF-8
939
2.84375
3
[ "MIT" ]
permissive
<?php namespace App\Http\Middleware; use App\Exceptions\PlaylistSongNotAuthenticatedException; use Closure; use App\Model\User; class PlaylistSongMiddleware { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if (empty($request->header('api_token'))) { # kondisi ketika api_token tidak dikirim melalui header throw new PlaylistSongNotAuthenticatedException(); } # kondisi token tidak kosong $token = request()->header('api_token'); $user = User::where('api_token','=',$token)->first(); if($user === null){ throw new PlaylistSongNotAuthenticatedException(); } # kondisi ketika api_tokennya ada $request->fullname = $user; return $next($request); } }
true
6bc00c298b20a82fd9a25cdd2881ce0651618927
PHP
vano20/udemy_oop
/static_modifier.php
UTF-8
276
2.984375
3
[]
no_license
<?php /**Class Mobil * */ class Mobil { static $wheel_count = 4; static $door_count = 4; //static property //methods static function detil_mobil(){ echo Mobil::$wheel_count; echo Mobil::$door_count; } } // echo Mobil::$door_count; Mobil::detil_mobil(); ?>
true
b53af66c1446e68ea0e85bbd983a3e3aa25e1772
PHP
mikhail-leonov/Recipe
/src/Recipe/Interfaces/DestinationFactoryInterface.php
UTF-8
683
2.9375
3
[]
no_license
<?php /** * Recipe - A recipe manager * * @author Mikhail Leonov <mikecommon@gmail.com> * @copyright (c) Mikhail Leonov * @link https://github.com/mikhail-leonov/recipe * @license MIT */ namespace Recipe\Interfaces; /** * This is the "DestinationFactory interface". */ interface DestinationFactoryInterface { /** * Method to build an Destination object of $name type IDestination * * @var string $name Destination name to create * * @throws Exception if the provided name does not match existing php Destination file * * @return IDestination Destination we have created */ public static function build(string $name) : IDestination; }
true
9a7c76e97af769c6adceb8432a4f07327adc599b
PHP
abcde090/php-task
/user_upload.php
UTF-8
5,603
2.984375
3
[ "MIT" ]
permissive
<?php // MySQL connection details $host = "127.0.0.1"; $username = "root"; $password = ""; $dbname = "myDatabase"; $table = "users"; $conn = new mysqli($host, $username, $password); echo "Script starting now.\n"; commandControl($host, $username, $password, $conn, $dbname, $table); // Open a connection to mySQL server and display connection status function connection($conn) { if ($conn->connect_error) { die('Error (' . $conn->connect_error . ') '); } else echo "Successfully connected to MySQL server.\n"; } // Handle all command inputs function commandControl($host, $username, $password, $conn, $dbname, $table) { $shortOptions = "uph"; $longOptions = array( "file:", "create_table", "dry_run", "help", ); $options = getopt($shortOptions, $longOptions); $command = FALSE; if (array_key_exists('file', $options) and !array_key_exists('dry_run', $options)) { $file = $options["file"]; $info = pathinfo($file); if ($info["extension"] === "csv") { table_creation($conn, $dbname, $table); loadData($file, TRUE, $conn, $dbname, $table); } else { echo "Unsupported file format. Please try again with a csv file.\n"; } $command = TRUE; } if (array_key_exists('create_table', $options)) { table_creation($conn, $dbname, $table); $command = TRUE; } if (array_key_exists('dry_run', $options) and array_key_exists('file', $options)) { echo "Dry run mode: no data will be added to the database.\n"; $file = $options["file"]; $info = pathinfo($file); if ($info["extension"] === "csv") { table_creation($conn, $dbname, $table); loadData($file, FALSE, $conn, $dbname, $table); } else { echo "Unsupported file format. Please try again.\n"; } $command = TRUE; } if (array_key_exists('u', $options)) { echo "MySQL username: " . $username . "\n"; $command = TRUE; } if (array_key_exists('p', $options)) { echo "MySQL password: " . $password . "\n"; $command = TRUE; } if (array_key_exists('h', $options)) { echo "MySQL host: " . $host . "\n"; $command = TRUE; } if (array_key_exists('help', $options)) { help_messages(); $command = TRUE; } if (!$command) { echo "Invalid command. Please enter a valid command(enter --help for full commands list).\n"; } } // Display help messages function help_messages() { echo " --file [csv file name] – this is the name of the CSV to be parsed.\n --create_table – this will cause the MySQL users table to be built (and no further action will be taken).\n --dry_run – this will be used with the --file directive in the instance that we want to run the script but not insert into the DB. All other functions will be executed, but the database won't be altered.\n -u – MySQL username.\n -p – MySQL password.\n -h – MySQL host.\n"; } // Create the database and table if not exists function table_creation($conn, $dbname, $table) { connection($conn); $query = "CREATE DATABASE IF NOT EXISTS $dbname"; if (mysqli_query($conn, $query)) { echo "Success creating database $dbname.\n"; } else { echo "Failure creating database $dbname.\n"; } $db_selected = mysqli_select_db($conn, $dbname); if (!$db_selected) { die('Cannot use the selected database'); } $sql = "CREATE TABLE IF NOT EXISTS $table ( name VARCHAR(30) NOT NULL, surname VARCHAR(30) NOT NULL, email VARCHAR(50) NOT NULL, UNIQUE (email) )"; if (mysqli_query($conn, $sql)) { echo "Table $table created successfully.\n"; } else { echo "Error: " . mysqli_error($conn) . "\n"; } } // loadData from csv file, insert data into the database when $insert is true, otherwise dry_run function loadData($filename, $insert, $conn, $dbname, $table) { table_creation($conn, $dbname, $table); $file = fopen($filename, "r"); $count = 0; while (!feof($file)) { $array = fgetcsv($file, 1000, ","); $name = string_filter($array[0]); $surname = string_filter($array[1]); if (email_filter($array[2], $count)) { echo "Row $count is valid.\n"; if ($insert === TRUE) { $email = trim(strtolower($array[2])); $sql = "INSERT INTO $table (name, surname, email) VALUES ('$name', '$surname', '$email')"; global $conn; if ($conn->query($sql)) { echo "Row $count has been inserted into the database successfully.\n"; } else { echo "Error: $conn->error\n"; } } } $count++; } fclose($file); } // Capitalize the first word and remove numbers and special characters of the name function string_filter($string) { $string = preg_replace("/[^A-Za-z']/", "", $string); $string = trim(ucfirst(strtolower($string))); $string = str_replace("'", "\'", $string); return $string; } //Checks whether email is valid. function email_filter($email, $count) { $email = filter_var($email, FILTER_SANITIZE_EMAIL); $email = str_replace("'", "\'", $email); if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { echo ("Row $count contains an invalid email address.\n"); return FALSE; } return TRUE; }
true
42e585cb5f786f904e9471b8ec28af3a5396252d
PHP
liuyu1518/Qyhrpc
/src/Qyhrpc/RPC/Plugins/Forward.php
UTF-8
1,295
2.609375
3
[ "MIT" ]
permissive
<?php namespace Qyhrpc\RPC\Plugins; use Qyhrpc\RPC\Client; use Qyhrpc\RPC\Core\ClientContext; use Qyhrpc\RPC\Core\Context; class Forward { public $client; public $timeout = null; public function __construct(?array $urilist = null) { $this->client = new Client($urilist); } public function ioHandler(string $request, Context $context, callable $next): string { $clientContext = new ClientContext(); $clientContext->timeout = $this->timeout; $clientContext->init($this->client); return $this->client->request($request, $clientContext); } public function invokeHandler(string $name, array &$args, Context $context, callable $next) { $clientContext = new ClientContext(); $clientContext->timeout = $this->timeout; $clientContext->requestHeaders = $context->requestHeaders; $result = $this->client->invoke($fullname, $args, $clientContext); $context->responseHeaders = $clientContext->responseHeaders; return $result; } public function use (callable ...$handlers): self { $this->client->use(...$handlers); return $this; } public function unuse(callable ...$handlers): self { $this->client->unuse(...$handlers); return $this; } }
true
5f996c2eefe81e15e4f5935b54b74c1d8165e2ca
PHP
Meyjan/Engi-s-Cinema
/src/php/ReviewPage.php
UTF-8
962
2.578125
3
[]
no_license
<?php require "SqlConnection.php"; require "SqlUtility.php"; // Check browser's cookie $cookie = "-999"; if (isset($_COOKIE["login_cookie"])) { $cookie = $_COOKIE["login_cookie"]; } else { echo -500; return; } // Check the cookie in the database $conn = openConnection(); $sql = "SELECT id FROM user_table WHERE token = \"" . $cookie . "\""; $user_result = executeSql($conn, $sql)[0]; $rating = filter_input(INPUT_POST, "rating", FILTER_SANITIZE_NUMBER_INT); $review = filter_input(INPUT_POST, "review", FILTER_SANITIZE_STRING); $reviewAct = filter_input(INPUT_POST, "reAction", FILTER_SANITIZE_STRING); $scheduleId = filter_input(INPUT_POST, "scheduleId", FILTER_SANITIZE_NUMBER_INT); $sql = "UPDATE movie_user_table SET rating = " . $rating . ", review = \"" . $review . "\" WHERE user_id = " . $user_result . " AND schedule_id = " . $scheduleId; if ($conn -> query($sql) !== true) { echo 500; return; } else { echo 200; } ?>
true
1a47eb5bddabfca3804b2f00ec31ee5e9d6bd408
PHP
enumag/phpstan-oneline
/src/OneLineErrorFormatter.php
UTF-8
1,320
2.625
3
[]
no_license
<?php declare(strict_types = 1); namespace Grifart\PhpstanOneLine; use PHPStan\Command\AnalysisResult; use PHPStan\Command\ErrorFormatter\ErrorFormatter; use PHPStan\File\RelativePathHelper; use Symfony\Component\Console\Style\OutputStyle; class OneLineErrorFormatter implements ErrorFormatter { /** @var RelativePathHelper */ private $relativePathHelper; public function __construct( RelativePathHelper $relativePathHelper ) { $this->relativePathHelper = $relativePathHelper; } public function formatErrors( AnalysisResult $analysisResult, OutputStyle $style ): int { if (!$analysisResult->hasErrors()) { $style->success('No errors'); return 0; } foreach ($analysisResult->getNotFileSpecificErrors() as $notFileSpecificError) { $style->writeln(sprintf('<unknown location> %s', $notFileSpecificError)); } foreach ($analysisResult->getFileSpecificErrors() as $fileSpecificError) { $style->writeln( sprintf( '%s:%d %s', $this->relativePathHelper->getRelativePath($fileSpecificError->getFile()), $fileSpecificError->getLine() ?? '?', $fileSpecificError->getMessage() ) ); } $style->error(sprintf($analysisResult->getTotalErrorsCount() === 1 ? 'Found %d error' : 'Found %d errors', $analysisResult->getTotalErrorsCount())); return 1; } }
true
4f788121a6147e3270fa70f3f7cec21664fb55c5
PHP
bcGiR/roommates
/create-exec.php
UTF-8
1,079
2.671875
3
[]
no_license
<?php require('dbadapter.php'); require('validate.php'); if (isset($_POST['house_name'])) { $error = validateCreateHouse(); if (!$error) { // validation successful $house_name = $_POST['house_name']; $rent = $_POST['rent']; $house_password = password_hash($_POST['house_password'], PASSWORD_DEFAULT); $result = createHouse($house_name, $house_password, $rent); setUserHouse($username, $result); // sets the users house to the newly created one if ($result) { // house created successfully $message = "House $house_name created successfully!"; echo "<script type='text/javascript'>alert('$message'); window.location.href = 'http://localhost/mates/home.php';</script>"; } else { // house creation falied $message = "Sorry, there was an unexpected error.\nPlease try again."; echo "<script type='text/javascript'>alert('$message');</script>"; } } else { // form invalid echo "<script type='text/javascript'>alert('$error');</script>"; } } ?>
true
30082177d2dcf21cc2994b1fe1cfc3a67533cf23
PHP
udistrital/migracion
/academicopro/bloque/admin_biblioteca/funcion.class.php
UTF-8
2,673
2.609375
3
[]
no_license
<?php /** * Funcion adminConsultarInscripcionGrupoCoordinador * * Esta clase se encarga de crear la logica y mostrar la interfaz de usuario * * @package nombrePaquete * @subpackage nombreSubpaquete * @author Luis Fernando Torres * @version 0.0.0.1 * Fecha: 23/06/2011 */ /** * Verifica si la variable global existe para poder navegar en el sistema * * @global boolean Permite navegar en el sistema */ if(!isset($GLOBALS["autorizado"])) { include("../index.php"); exit; } /** * Incluye la clase abstracta funcionGeneral.class.php * * Esta clase contiene funciones que se utilizan durante el desarrollo del aplicativo. */ include_once($configuracion["raiz_documento"].$configuracion["clases"]."/funcionGeneral.class.php"); /** * Incluye la clase sesion.class.php * Esta clase se encarga de crear, modificar y borrar sesiones */ include_once($configuracion["raiz_documento"].$configuracion["clases"]."/ezproxyTicket.class.php"); /** * Clase funcion_adminConsultarInscripcionGrupoCoordinador * * Clase que contiene los métodos que ejecutan tareas y crean los formularios de la pagina del bloque. * @package InscripcionCoordinadorPorGrupo * @subpackage Consulta */ class funcion_adminBiblioteca extends funcionGeneral { public $configuracion; /** * Método constructor que crea el objeto sql de la clase funcion_adminConsultarInscripcionGrupoCoordinador * * @param array $configuracion Arreglo que contiene todas las variables de configuracion que se encuentre en la tabla de configuracion del framework */ function __construct($configuracion) { $this->configuracion=$configuracion; /** * Incluye la clase encriptar.class.php * * Esta clase incluye funciones de encriptacion para las URL */ include_once($configuracion["raiz_documento"].$configuracion["clases"]."/encriptar.class.php"); $this->cripto=new encriptar(); $this->sql=new sql_adminBiblioteca($configuracion); } /** * */ function CrearTicketEzproxy() { /* $ezproxy = new EZproxyTicket("http://bdigital.udistrital.edu.co", "ticketcondorezproxy",'usuario');*/ ?> <div style='width:100%; height: 700px'> <iframe src="http://bdigital.udistrital.edu.co/index.php/recursos-electronicos-suscritos" style="width: 100%; height: 100%"></iframe> </div> <?exit; } } ?>
true
10a4d6f214a777e78e37c20087ceec9c64629cb7
PHP
shima-rahman/lina
/php/day9/convert_asccii.php
UTF-8
187
3.078125
3
[]
no_license
<html> <?php $string= "fahmida"; $length=strlen($string); for($i=0;$i<$length;$i++) { $message=ord($string{$i})-ord($string)+ord("FAHMIDA"); echo chr($message); } ?>
true
7b92f22071ca235cf85ebe189334a8f9531d17f5
PHP
tonycool7/working_experience
/listen_to_log.php
UTF-8
892
2.609375
3
[]
no_license
<?php //function follow($file) //{ // $size = 0; // while (true) { // clearstatcache(); // $currentSize = filesize($file); // if ($size == $currentSize) { // usleep(100); // continue; // } // $fh = fopen($file, "r"); // fseek($fh, $size); // // while ($d = fgets($fh)) { // echo $d; // $pos = strpos($d,"Accepted"); // if($pos !== false) { // echo "Found\n"; // } // } // fclose($fh); // $size = $currentSize; // } //} // //follow("/var/log/auth.log"); $handle = popen("tail -f /var/log/auth.log 2>&1", 'r'); while(!feof($handle)) { $buffer = fgets($handle); echo "$buffer\n"; $pos = strpos($buffer,"Accepted"); if($pos !== false) { echo "ssh connection found!\n"; } flush(); } pclose($handle); ?>
true
de79c18e74dcd36809ed74400042137aa75fc770
PHP
tanxu1993/smart_vote
/table/table_smart_token.php
UTF-8
997
2.53125
3
[]
no_license
<?php /** * [smart_token] 2015 * table_smart_token.php */ if(!defined('IN_DISCUZ')) { exit('Access Denied'); } class table_smart_token extends discuz_table { public function __construct() { $this->_table = 'smart_token'; $this->_pk = 'id'; parent::__construct(); } public function fetch_by_id($id) { return DB::fetch_first('SELECT * FROM %t WHERE id=%d', array($this->_table, $id)); } public function count_all() { return (int) DB::result_first("SELECT count(*) FROM %t", array($this->_table)); } public function fetch_all($start, $limit,$order='id') { return DB::fetch_all('SELECT * FROM %t ORDER BY '.$order.' desc ' . DB::limit($start, $limit), array($this->_table), $this->_pk); } public function update_by_id($data,$where) { return DB::update($this->_table,$data, $where); } public function insert($data) { return DB::insert($this->_table,$data); } }
true
5bb086d6b6acc0bb2514c8b6538be3a1580a8edb
PHP
camilledejoye/ddd
/src/Identity/Exception/InvalidUuidStringException.php
UTF-8
522
2.96875
3
[]
no_license
<?php declare(strict_types=1); namespace ddd\Identity\Exception; /** * Thrown when trying to use a string as an UUID when it is not. * * @see \DomainException * @final */ final class InvalidUuidStringException extends \DomainException { /** * {@inheritdoc} * * @param string $invalidUuidString */ public function __construct(string $invalidUuidString) { parent::__construct( sprintf('The string "%s" is not a valid UUID.', $invalidUuidString) ); } }
true
3df3a3e1bb60434acdd4401aa92e28ab90aaabf3
PHP
brm-viracachac/brm-estelar-bmw-arpc
/publication/class/ciudades.php
UTF-8
850
2.625
3
[ "MIT" ]
permissive
<?php class Ciudades { function getCiudadDepartamento($depto){ $CiudadVerDBO = DB_DataObject::Factory('Ciudad'); $CiudadVerDBO->whereAdd("idDepto = '$depto'"); //$CiudadVerDBO->get('2'); $Ciudades = array(); $contador = 0; $CiudadVerDBO->find(); while($CiudadVerDBO->fetch()){ $Ciudades[$contador]->idCiudad = $CiudadVerDBO->idCiudad; $Ciudades[$contador]->nombre = utf8_encode($CiudadVerDBO->nombre); $contador++; } $CiudadVerDBO->fetch(); //printVar($Ciudades); return($Ciudades); } function getCiudadCodigo($id){ $CiudadVerDBO = DB_DataObject::Factory('Ciudad'); $CiudadVerDBO->selectAdd('nombre'); $CiudadVerDBO->idCiudad = $id; //$ingredienteDBO->orderBy("id ASC"); $CiudadVerDBO->find(); while($CiudadVerDBO->fetch()){ $nombre = $CiudadVerDBO->nombre; } return($nombre); } } ?>
true
a5ce37ed7367a941d03d5304f7019183019f70e6
PHP
piotrpasich/linkbot
/symfony/src/AppBundle/Entity/Link.php
UTF-8
4,507
2.890625
3
[ "0BSD", "BSD-3-Clause" ]
permissive
<?php namespace AppBundle\Entity; use XTeam\HighFiveSlackBundle\Entity\Channel; use XTeam\HighFiveSlackBundle\Entity\User; /** * Link */ class Link { /** * @var int */ private $id; /** * @var \stdClass */ private $user; /** * @var string */ private $message; /** * @var string */ private $link; /** * @var \DateTime */ private $createdAt; private $channel; private $slackId; private $sent = false; /** * @var Slack TimeStamp */ private $slackTS; /** * @var int */ private $reactionsCount = 0; private $linkInfo; private $type; private $status = SELF::STATUS_NEW; CONST STATUS_NEW = 'new'; CONST STATUS_READY = 'ready'; CONST STATUS_BROKEN = 'broken'; /** * Get id * * @return int */ public function getId() { return $this->id; } /** * Set user * * @param \stdClass $user * * @return Link */ public function setUser($user) { $this->user = $user; return $this; } /** * Get user * * @return User */ public function getUser() { return $this->user; } /** * Set message * * @param string $message * * @return Link */ public function setMessage($message) { $this->message = $message; return $this; } /** * Get message * * @return string */ public function getMessage() { return $this->message; } /** * Set link * * @param string $link * * @return Link */ public function setLink($link) { $this->link = $link; return $this; } /** * Get link * * @return string */ public function getLink() { return $this->link; } /** * Set createdAt * * @param \DateTime $createdAt * * @return Link */ public function setCreatedAt($createdAt) { $this->createdAt = $createdAt; return $this; } /** * Get createdAt * * @return \DateTime */ public function getCreatedAt() { return $this->createdAt; } /** * @return Channel */ public function getChannel() { return $this->channel; } /** * @param mixed $channel */ public function setChannel($channel) { $this->channel = $channel; } /** * @return mixed */ public function getSlackId() { return $this->slackId; } public function setCreatedAtFromTimestamp($timestamp) { $date = new \DateTime(); $date->setTimestamp($timestamp); $this->createdAt = $date; } /** * @param mixed $slackId */ public function setSlackId($slackId) { $this->slackId = $slackId; } /** * @return Slack */ public function getSlackTS() { return $this->slackTS; } /** * @param Slack $slackTS */ public function setSlackTS($slackTS) { $this->slackTS = $slackTS; } /** * @return int */ public function getReactionsCount() { return $this->reactionsCount; } /** * @param int $reactionsCount */ public function setReactionsCount($reactionsCount) { $this->reactionsCount = $reactionsCount; } /** * @return boolean */ public function isSent() { return $this->sent; } /** * @param boolean $sent */ public function setSent($sent) { $this->sent = $sent; } /** * @return mixed */ public function getLinkInfo() { return $this->linkInfo; } /** * @param mixed $linkInfo */ public function setLinkInfo($linkInfo) { $this->linkInfo = $linkInfo; } /** * @return mixed */ public function getType() { return $this->type; } /** * @param mixed $type */ public function setType($type) { $this->type = $type; } /** * @return string */ public function getStatus() { return $this->status; } /** * @param string $status */ public function setStatus($status) { $this->status = $status; } }
true
542df97ae17081fe8544abbe9db1f202c27022c3
PHP
exgull/wezomapp
/lib/ParentObject.php
UTF-8
3,132
2.921875
3
[]
no_license
<?php require_once 'DataBase.php'; /** * Created by PhpStorm. * User: gull * Date: 07.10.16 * Time: 20:34 */ class ParentObject { public function save($array = []) { return isset($this->id) ? $this->update($array) : $this->create(); } protected function create() { $sql = "INSERT INTO ".static::$table_name." ("; $sql .= implode(", ", static::$data).") VALUES ("; for ($i=0; $i < count(static::$data); $i++) { if ($this->{static::$data[$i]} === null) { $sql .= "null, "; } else { $sql .= "'".$this->{static::$data[$i]}."', "; } } $sql = substr($sql, 0, count($sql)-3).")"; if (static::query($sql)) { $this->id = static::insertId(); return true; } else { return false; } } protected function update($update = []) { $sql = "UPDATE ".static::$table_name." SET "; for ($i=0; $i < count(static::$data); $i++) { isset($update[static::$data[$i]]) ? $this->{static::$data[$i]} = $update[static::$data[$i]] : false; $sql .= static::$data[$i].(($this->{static::$data[$i]}===null)? "=null" :"='".$this->{static::$data[$i]}."'").", "; } $sql = substr($sql, 0, count($sql)-3); $sql .= " WHERE id=".$this->id; return static::query($sql) ? true : false; } public function delete() { $sql = "DELETE FROM ".static::$table_name; $sql .= " WHERE id=".$this->id; $sql .= " LIMIT 1"; return static::query($sql) ? true : false; } static public function query($sql="") { global $connect; if (isset($connect) && $result = $connect->query($sql)) { return $result; } else { return false; } } static public function insertId() { global $connect; return isset($connect) ? $connect->insertId() : false; } static public function getById($id) { return static::get('id', $id, true); } static public function get($field=null, $value='', $limit = false, $andfield=null, $andvalue='') { $sql = "SELECT * FROM ".static::$table_name." "; if ($field && ($field=='id' || in_array($field, static::$data))) { $sql .= "WHERE {$field} = '{$value}'"; } if ($andfield && $andfield!==$field && ($andfield=='id' || in_array($andfield, static::$data))) { $sql .= " AND {$andfield} = '{$andvalue}'"; } if ($limit) { $sql .= " LIMIT 1"; $response = static::query($sql); if (is_object($response) && $response->num_rows > 0) { $obj = mysqli_fetch_array($response, MYSQLI_ASSOC); return new static($obj); } else { return false; } } else { $result = static::query($sql); $objs = []; while ($row = mysqli_fetch_assoc($result)) { $obj = new static($row); array_push($objs, $obj); } return $objs; } } }
true
b0db57e2d194bc83cee36fc976e13d8448b73dfb
PHP
EmericLevasseur/methode-agile
/login.php
UTF-8
1,455
2.859375
3
[]
no_license
<?php session_start(); include("conf/db.php"); ?> <form method="post" action="log_in.php"> <label for="log-in-email">Email</label> <input type="email" name="email" id="log-in-email" placeholder="Votre e-mail"> <label for="log-in-password">Mot de passe</label> <input type="password" name="password" id="log-in-password" placeholder="Votre mot de passe"> <button type="submit">Se connecter</button> </form> <?php if (array_key_exists('errors', $_SESSION)) : ?> <p><?= implode('<br>', $_SESSION['errors']);?></p> <?php unset($_SESSION['errors']); endif; ?> <?php if (array_key_exists('success', $_SESSION)) : ?> <p>Vous êtes connecté(e).</p> <?php unset($_SESSION['success']); endif; ?> <p>Liste des membres :</p> <?php $request = $db->prepare("SELECT members.id, email, is_admin, password, inscription_date FROM members"); $request->execute ( array ( ) ); while ($data = $request->fetch()) { ?> <table> <tr> <th><h4>ID : </h4></th> <th><h4>E-mail : </h4></th> <th><h4>Mot de passe : </h4></th> </tr> <tr> <th><?php echo $data["id"]; ?></th> <th><?php echo $data["email"]; ?></th> <th><?php echo $data["password"]; ?></th> </tr> </table> <?php } ?> <style> th { width : 30vw; } </style>
true
23a4e9a897b6936142cec4d9d969e6a4f1efe537
PHP
honeybee/honeybee-agavi-cmf-vendor
/app/lib/Ui/Navigation/NavigationItem.php
UTF-8
414
2.65625
3
[ "MIT" ]
permissive
<?php namespace Honeygavi\Ui\Navigation; use Honeygavi\Ui\Activity\ActivityInterface; use Trellis\Common\BaseObject; class NavigationItem extends BaseObject implements NavigationItemInterface { protected $activity; public function __construct(ActivityInterface $activity) { $this->activity = $activity; } public function getActivity() { return $this->activity; } }
true
c93c20bb690f04e452a50f97dc99f706445170a8
PHP
rubydiao/php
/lecture/14for.php
UTF-8
103
2.890625
3
[]
no_license
<?php //http://localhost/php/14for.php for ($i=1; $i<=10; $i++){ echo $i; echo "<br>"; } ?>
true
c824488772392916daaf9509b0276023f4491d56
PHP
atorpos/model-server
/include/LT/Runtime.php
UTF-8
1,936
2.9375
3
[]
no_license
<?php namespace LT; /** * @property string $scriptDirectory */ class Runtime implements \ArrayAccess { protected $_vars = array(); /** * * @staticvar \LT\Runtime $o * @return \static */ public static function current() { static $o = NULL; if (is_null($o)) { $o = new static; } return $o; } /** * * @param string $name * @return bool */ public function __isset($name) { return isset($this->_vars[$name]); } /** * * @param string $name * @return mixed */ public function __get($name) { if (isset($this->_vars[$name])) { return $this->_vars[$name]; } return NULL; } /** * * @param string $name * @param mixed $value */ public function __set($name, $value) { $this->_vars[$name] = $value; } /** * * @param string $name */ public function __unset($name) { if (!isset($this->_vars[$name])) { return; } unset($this->_vars[$name]); } /** * * @param string $offset * @return bool */ public function offsetExists($offset) { return isset($this->_vars[$offset]); } /** * * @param string $offset * @return mixed */ public function offsetGet($offset) { if (isset($this->_vars[$offset])) { return $this->_vars[$offset]; } return NULL; } /** * * @param string $offset * @param mixed $value */ public function offsetSet($offset, $value) { $this->_vars[$offset] = $value; } /** * * @param string $offset */ public function offsetUnset($offset) { if (!isset($this->_vars[$offset])) { return; } unset($this->_vars[$offset]); } }
true
63e509ef769fb602b0436b776e493d69f8e04831
PHP
danielzielka/cli-rss-to-csv
/tests/CSVCommandTest.php
UTF-8
968
2.578125
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); namespace DanielZielkaRekrutacjaHRtec\tests\CSVCommandTest; use PHPUnit\Framework\TestCase; use DanielZielkaRekrutacjaHRtec\commands\CSVCommand; use DanielZielkaRekrutacjaHRtec\services\FeedResolver; use DanielZielkaRekrutacjaHRtec\services\CSVCreator; use Symfony\Component\Console\Output\ConsoleOutput; use InvalidArgumentException; class CSVCommandTest extends TestCase { public function testSimpleCommandArguments() { $command = new CSVCommand(new FeedResolver(), new CSVCreator()); $this->expectException(InvalidArgumentException::class); $command->simple('http://feeds.bbci.co.uk/news/world/rss.xml', null, new ConsoleOutput()); $this->expectException(InvalidArgumentException::class); $command->simple(null, 'tests/file', new ConsoleOutput()); $this->expectException(InvalidArgumentException::class); $command->simple(null, null, new ConsoleOutput()); } }
true
c1996547378a2be8a7a91a924a427ac69df0ec20
PHP
minhnguyen-balance/oro_platform
/vendor/oro/platform/src/Oro/Bundle/BatchBundle/Step/StepInterface.php
UTF-8
1,405
2.640625
3
[ "MIT" ]
permissive
<?php namespace Oro\Bundle\BatchBundle\Step; use Oro\Bundle\BatchBundle\Entity\StepExecution; /** * Batch domain interface representing the configuration of a step. As with the * Job, a Step is meant to explicitly represent the configuration of a step by * a developer, but also the ability to execute the step. * * Inspired by Spring Batch org.springframework.batch.core.Step; * */ interface StepInterface { /** * @return The name of this step */ public function getName(); /** * Process the step and assign progress and status meta information to the * StepExecution provided. The Step is responsible for setting the meta * information and also saving it if required by the implementation. * * @param StepExecution $stepExecution an entity representing the step to be executed * * @throws JobInterruptedException if the step is interrupted externally */ public function execute(StepExecution $stepExecution); /** * Provide the configuration of the step * * @return array */ public function getConfiguration(); /** * Set the configuration for the step * * @param array $config */ public function setConfiguration(array $config); /** * Get the configurable step elements * * @return array */ public function getConfigurableStepElements(); }
true
b63ebb02977a1fe6da6a687e06b24d0bf37a3fba
PHP
VadyaOleniuk/example
/src/Clear/SecurityBundle/Security/Securable.php
UTF-8
768
2.578125
3
[]
no_license
<?php namespace Clear\SecurityBundle\Security; use Doctrine\ORM\EntityManager; class Securable { protected $manager; public function __construct(EntityManager $manager) { $this->manager = $manager; } public function hasAccess($actionId, $roles) { if (is_string($roles)) { return true; } foreach ($roles as $role) { $actions = $this->manager->getRepository('ClearUserBundle:Disallowed')->findBy(['actionId' => $actionId]); foreach ($actions as $action) { if ($action->getActionId() == $actionId && $action->getRoleUser()->getName() == $role) { return false; } } } return true; } }
true
8905bcf5cdd88560cf42d77fdb90fee91579786a
PHP
MadMikeyB/Meetings
/app/NextStep.php
UTF-8
1,631
2.609375
3
[]
no_license
<?php namespace App; ; class NextStep extends UuidModel { protected $fillable = [ 'user_id', 'meeting_id', 'description', 'completed_by_date', ]; protected $casts = [ 'completed_by_date' => 'datetime', ]; public function meeting() { return $this->belongsTo(Meeting::class); } public function user() { return $this->belongsTo(User::class); } public static function get_for_page($params, $user) { $next_steps = array( 'Incomplete Next Steps' => NextStep::where([ 'is_complete' => false, ]), 'Complete Next Steps' => NextStep::where([ 'is_complete' => true, ]), 'All Next Steps' => NextStep::whereIn( 'is_complete', [true, false] ), ); if(isset($params['next_step']['sort'])) { $sort_by = explode("_", $params['next_step']['sort']); } else { $sort_by = ['description', 'asc']; } foreach($next_steps as $tab => $set) { $next_steps[$tab] = $set->orderBy($sort_by[0], $sort_by[1]); } if(isset($params['next_step']['filter'])) { foreach($params['next_step']['filter'] as $key => $value) { foreach($next_steps as $tab => $set) { $next_steps[$tab] = $set->where($key, 'LIKE', '%'.$value.'%'); } } } if(isset($params['q_limit'])) { foreach($next_steps as $tab => $set) { $next_steps[$tab] = $set->take($params['q_limit']); } } foreach($next_steps as $tab => $set) { $next_steps[$tab] = $set->where([ 'user_id' => $user->id ])->get(); } return $next_steps; } }
true
53c44c89c01b61c86453685769da4b5433689154
PHP
jkiss/Chuanbang
/protected/components/utils/DbUtils.php
UTF-8
451
2.78125
3
[]
no_license
<?php class DbUtils { public static function execute($sql, $params=array()) { return Yii::app()->db->createCommand($sql)->execute($params); } public static function query($sql, $params=array()) { $result = array(); $dataReader = Yii::app()->db->createCommand($sql)->query($params); while(($row=$dataReader->read())!==false) { array_push($result, $row); } return $result; } }
true
54860f3941a49924348cf365da596d3674c2907e
PHP
gfortino/iwp-w2018
/Projects/Team1/online_shopping/online_shopping/application/models/functions.php
UTF-8
1,864
2.78125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<?php function add($a,$b){ $c=$a+$b; return $c; } /** * * 获取图片名称列表 * * @param str $dir 图片路径 * @return array $photo 图片名称列表 */ function get_photo_list($dir) { if (file_exists($dir)) { //获取某目录下所有文件、目录名(不包括子目录下文件、目录名) $handler = opendir($dir); $files=array(); while (($filename = readdir($handler))) {//务必使用!==,防止目录下出现类似文件名“0”等情况 if ($filename != "." && $filename != "..") { $files[] = $filename; } } closedir($handler); //去掉不是照片的文件的文件名,得到只有照片名字的文件名 $photo是照片文件名 $photo=array(); $i=0; if($files!=null) { foreach ($files as $un_file) { if ($un_file != "thumbs" && $un_file != ".DS_Store") { $photo[$i] = $un_file; $i = $i + 1; } } } return $photo; } } //显示图片 function show_product_photos($rowid,$height=null){ if($height==null){ $height=20; } $dir="documents/product/".$rowid; $photo_list=get_photo_list($dir); if($photo_list==null){ echo '<img src="'.base_url().'assets/img/nophoto.png'.'" height="'.$height.'" class="img-rounded">'; return; } foreach ($photo_list as $value){ echo '<img src="'.base_url().$dir."/".$value.'" height="'.$height.'" class="img-rounded">'; } //print_r(get_photo_list($dir)); } //压缩图片
true
d78a440ac48f1e3878ae04a71db6bd8dbb858547
PHP
jbaldwin/project_euler
/p049/p49.php
UTF-8
1,523
3.671875
4
[ "MIT" ]
permissive
<?php /** Prime permutations The arithemetic sequence, 1487, 4817, 8147, in which each of the terms increases by 3330, is unusual in two ways: (i) each of the three terms are prime, and, (ii) each of the 4-digit numbers are permutations of one another. There are no arithemtic sequences made up of 1-, 2-, or 3-digit primes, exhibiting this property, but there is one other 4-digit increasing sequence. What 12-digit number do you form by concatenating the three terms in this sequence? **/ require_once "../lib/prime.php"; require_once "../lib/permutations.php"; $primes = prime_sieve(10000); $magic = 3330; $problem_defined = 1487; $answer = -1; for($i = 0; $i < count($primes); $i++) { $sval = $primes[$i]; if($sval < 1000) continue; if($sval > 4000) break; $permutations = array_unique(permutate(strval($sval))); foreach($permutations as $k => $p) { if($p[0] == '0' || !is_prime($p)) { unset($permutations[$k]); } } if(count($permutations) < 3) continue; sort($permutations, SORT_NUMERIC); array_values($permutations); for($j = 0; $j < count($permutations); $j++) { $check1 = $permutations[$j] + $magic; $check2 = $check1 + $magic; if( in_array($check1, $permutations) && in_array($check2, $permutations) && $permutations[$j] != $problem_defined ) { $answer = $permutations[$j]; // break both for loops $i = count($primes); break; } } } print $answer . ($answer + $magic) . ($answer + 2 * $magic); ?>
true
5d5019e00eea43ca5d9f933b53de2e5471a0bc4e
PHP
neokimu/phprecipe
/02/function.php
UTF-8
786
4.03125
4
[ "MIT" ]
permissive
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>関数を定義したい</title> </head> <body> <?php // ユーザー定義関数 function check($subject, $point) { echo $subject . 'の結果'; if ($point > 75) { echo '合格です'; } else { echo '不合格です'; } echo'(点数:' . $point . ')<br>'; } // 変数に数値を代入します。 $test1 = 84; $test2 = 62; $test3 = 78; // ユーザー定義関数を実行します。 check('社会', $test1); check('英語', $test2); check('数学', $test3); ?> </body> </html>
true
fb6b5a78fa463449538c6b4431c913c440d03924
PHP
ghostegend/practicaProyect
/Shipper.php
UTF-8
3,121
2.984375
3
[]
no_license
<?php class Shipper { private $ID; private $ShipperID; private $CompanyName; private $Phone; public function __construct() { $this->ID=0; $this->CompanyName=""; $this->Phone=""; } public function getID() { return $this->ID; } public function setID($pID) { $this->ID= $pID; } public function getCompanyName() { return $this->CompanyName; } public function setCompanyName($pcompanyName) { $this->CompanyName= $pcompanyName; } public function getPhone() { return $this->Phone; } public function setPhone($pphone) { $this->Phone= $pphone; } public function SelectAll() { $conn= new mysqli("localhost","root","","northwind"); if($conn->connect_error){ die("Error al conectarse a la BD".$conn->connect_error); } $sql="SELECT ShipperID,CompanyName,Phone FROM shippers "; $result=$conn->query($sql); $conn->close(); return $result; } public function Insert() { $conn= new mysqli("localhost","root","","northwind"); if($conn->connect_error){ die("Error al conectarse a la BD".$conn->connect_error); } $sql="INSERT INTO shippers(CompanyName,Phone )VALUES('$this->CompanyName','$this->Phone');"; $result=$conn->query($sql); if($result){ $conn->close(); return "Los valores han sido agregados";} else { $conn->close(); return "Error al ingresar los datos"; } } public function SelectOne() { $conn= new mysqli("localhost","root","","northwind"); if($conn->connect_error){ die("Error al conectarse a la BD".$conn->connect_error); } $sql="SELECT ShipperID,CompanyName,Phone FROM shippers WHERE ShipperID=".$this->ID.";"; $result=$conn->query($sql); $conn->close(); return $result; } public function Update() { $conn= new mysqli("localhost","root","","northwind"); if($conn->connect_error){ die("Error al conectarse a la BD".$conn->connect_error); } $sql="UPDATE shippers SET CompanyName='".$this->CompanyName."',Phone='".$this->Phone."' WHERE ShipperID=".$this->ID.";"; $result=$conn->query($sql); if($result){ $conn->close(); return "usuario modificado";} else { $conn->close(); return "usuario no modificado";} } public function DELETE() { $conn= new mysqli("localhost","root","","northwind"); if($conn->connect_error){ die("Error al conectarse a la BD".$conn->connect_error); } $sql="DELETE FROM shippers WHERE ShipperID=".$this->ID.";"; $result=$conn->query($sql); if($result){ $conn->close(); return "Transportista Borrado"; }else{ $conn->close(); return "Transportista No Borrado"; } } } ?>
true
80860202021210a97692947d39fb1dc2479d66aa
PHP
drublic/TYPO3.extensionmanager
/Classes/Domain/Model/Mirrors.php
UTF-8
3,313
2.765625
3
[]
no_license
<?php namespace TYPO3\CMS\Extensionmanager\Domain\Model; /*************************************************************** * Copyright notice * * (c) 2010 Marcus Krause <marcus#exp2010@t3sec.info> * Steffen Kamper <info@sk-typo3.de> * All rights reserved * * This script is part of the TYPO3 project. The TYPO3 project is * free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * The GNU General Public License can be found at * http://www.gnu.org/copyleft/gpl.html. * * This script is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * This copyright notice MUST APPEAR in all copies of the script! ***************************************************************/ /** * Repository mirrors object for extension manager. * * @author Marcus Krause <marcus#exp2010@t3sec.info> * @author Steffen Kamper <info@sk-typo3.de> * @since 2010-02-11 * @package Extension Manager * @subpackage Model */ class Mirrors extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity { /** * Keeps mirrors. * * @var array */ protected $mirrors = array(); /** * Keeps currently select mirror. * * Is array index. * * @var integer */ protected $currentMirror; /** * Keeps information if a mirror should * be randomly selected. * * @var boolean */ protected $isRandomSelection = TRUE; /** * Method selects one specific mirror to be used. * * @param integer $mirrorId number (>=1) of mirror or NULL for random selection * @return void * @see $currentMirror */ public function setSelect($mirrorId = NULL) { if (is_null($mirrorId)) { $this->isRandomSelection = TRUE; } else { if (is_int($mirrorId) && $mirrorId >= 1 && $mirrorId <= count($this->mirrors)) { $this->currentMirror = $mirrorId - 1; } } } /** * Method returns one mirror for use. * * Mirror has previously been selected or is chosen * randomly. * * @access public * @return array array of a mirror's properties or NULL in case of errors */ public function getMirror() { $sumMirrors = count($this->mirrors); if ($sumMirrors > 0) { if (!is_int($this->currentMirror)) { $this->currentMirror = rand(0, $sumMirrors - 1); } return $this->mirrors[$this->currentMirror]; } return NULL; } /** * Gets the mirror url from selected mirror * * @return string */ public function getMirrorUrl() { $mirror = $this->getMirror(); $mirrorUrl = $mirror['host'] . $mirror['path']; return 'http://' . $mirrorUrl; } /** * Method returns all available mirrors. * * @access public * @return array multidimensional array with mirrors and their properties * @see $mirrors, setMirrors() */ public function getMirrors() { return $this->mirrors; } /** * Method sets available mirrors. * * @param array $mirrors multidimensional array with mirrors and their properties * @return void * @see $mirrors, getMirrors() */ public function setMirrors(array $mirrors) { if (count($mirrors) >= 1) { $this->mirrors = $mirrors; } } } ?>
true
484c811e675f0bface20d8c16b1ff458bc7a8ae9
PHP
bariton3/php-pivotal-tracker-api
/lib/PivotalTracker/Api/Label.php
UTF-8
3,022
2.875
3
[ "MIT" ]
permissive
<?php namespace PivotalTracker\Api; use PivotalTracker\Exception\MissingArgumentException; /** * Listing, editing and delete your project's labels. * * @link https://www.pivotaltracker.com/help/api/rest/v5#Labels * */ class Label extends AbstractApi { /** * List of the project's labels. * * @link https://www.pivotaltracker.com/help/api/rest/v5#projects_project_id_labels_get * * @param string $project_id the id project * @param array $params the additional parameters like name * * @return array list of stories found */ public function all($project_id, array $params = array()) { return $this->get('/projects/'.rawurlencode($project_id).'/labels', $params); } /** * Get extended information about a project's label. * * @link https://www.pivotaltracker.com/help/api/rest/v5#projects_project_id_labels_label_id_get * * @param string $project_id the ID of the project. * @param string $id the label's id * * @return array information about the label */ public function show($project_id, $id) { return $this->get('/projects/'.rawurlencode($project_id).'/labels/'.rawurlencode($id)); } /** * Creates a label on the project. * * @link https://www.pivotaltracker.com/help/api/rest/v5#projects_project_id_labels_post * * @param string $project_id the ID of the project. * @param array $params the new story data * * @throws MissingArgumentException * * @return array information about the labels */ public function create($project_id, array $params) { if (!isset($params['name'])) { throw new MissingArgumentException(array('name')); } return $this->post('/projects/'.rawurlencode($project_id).'/labels', $params); } /** * Updates a project's label. * * @link https://www.pivotaltracker.com/help/api/rest/v5#projects_project_id_labels_label_id_put * * @param string $project_id the id of the project * @param string $id the label's id * @param array $params key=>value user attributes to update. * key can be name * * @return array information about the label */ public function update($project_id, $id, array $params) { return $this->put('/projects/'.rawurlencode($project_id).'/labels/'.rawurlencode($id), $params); } /** * Delete a project's label. * * @link https://www.pivotaltracker.com/help/api/rest/v5#projects_project_id_stories_story_id_delete * * @param string $project_id the id of the project * @param string $id the story id * * @return mixed null on success, array on error with 'error' */ public function remove($project_id, $id) { return $this->delete('/projects/'.rawurlencode($project_id).'/srories/'.rawurlencode($id)); } }
true
1b6250f1230372f13cfe9cd69458a9895ba46599
PHP
Enrise/Glitch_Lib
/lib/Glitch/Image/Adapter/Gd/Action/DrawEllipse.php
UTF-8
2,019
2.75
3
[]
no_license
<?php // require_once 'Zend/Image/Color.php'; // require_once 'Zend/Image/Adapter/Gd/Action/ActionAbstract.php'; class Glitch_Image_Adapter_Gd_Action_DrawEllipse extends Glitch_Image_Adapter_Gd_Action_ActionAbstract { /** * Draws an ellipse on the handle * * @param GD-object $handle The handle on which the ellipse is drawn * @param Glitch_Image_Action_DrawEllipse $ellipseObject The object that with all info */ public function perform($handle, Glitch_Image_Action_DrawEllipse $ellipseObject) { // As of ZF2.0 / PHP5.3, this can be made static. if($ellipseObject->filled()){ $color = $ellipseObject->getFillColor()->getRgb(); $alpha = $ellipseObject->getFillAlpha(); }else{ $color = $ellipseObject->getStrokeColor()->getRgb(); $alpha = $ellipseObject->getStrokeAlpha(); } $colorAlphaAlloc = imagecolorallocatealpha($handle->getHandle(), $color['red'], $color['green'], $color['blue'], 127 - $alpha * 1.27); if($ellipseObject->filled()) { imagefilledellipse($handle->getHandle(), $ellipseObject->getLocation()->getX(), $ellipseObject->getLocation()->getY(), $ellipseObject->getWidth(), $ellipseObject->getHeight(), $colorAlphaAlloc); } else { imageellipse($handle->getHandle(), $ellipseObject->getLocation()->getX(), $ellipseObject->getLocation()->getY(), $ellipseObject->getWidth(), $ellipseObject->getHeight(), $colorAlphaAlloc); } } }
true
de48fc3c3fd9c3d2f63f0a9632946cffe02dc1f1
PHP
Arendach/shar
/app/Http/Middleware/AuthCheck.php
UTF-8
1,791
2.578125
3
[]
no_license
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Support\Facades\DB; class AuthCheck { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if (isset($_COOKIE['session'])) { if ($this->check_cookie()) return $next($request); else $this->display_login($request); } else { $this->display_login($request); } } /** * @param \Illuminate\Http\Request $request */ public function display_login($request) { if ($request->getMethod() == 'POST') { res(401, 'Для продолжения авторизируйтесь!'); } else { echo view('pages.login'); } exit; } /** * @return bool */ public function check_cookie() { $result = DB::table('users_session') ->where('session', '=', $_COOKIE['session']) ->first(); if ($result != null) { $this->load_user($result); $_SESSION['is_auth'] = true; return true; } else { $_SESSION['is_auth'] = false; return false; } } /** * @param $result */ public function load_user($result) { $user = DB::table('users') ->where('id', $result->user_id) ->first(); if ($user->access != -1){ $access = DB::table('users_access')->where('id', $user->access)->first(); $user->access = get_array(json_decode($access->array)); } $_SESSION['user'] = $user; } }
true
6560430856c3ae1fb79216b54146e083845c5472
PHP
snickers54/dblink
/library/dblink_objects/user.php
UTF-8
3,007
2.734375
3
[]
no_license
<?php class user { private $class = array(); private $extensions = array(); private $planet; private $alliance; private $json; public static $var_json = array("config", "attack", "achievements", "spy", "mission", "planetes_images", 'stats'); private $structure = array('user_id', 'login', 'password', 'email', 'avatar', 'access', 'alliance_id', 'argent', 'date_register', 'last_date', 'ip_register', 'last_ip', 'active', 'spy', 'attack', 'planetes_images', 'parrain_id', 'achievements', 'mission', 'config', 'race'); public function __get($key) { return (isset($this->class[$key])) ? $this->class[$key] : ((isset($this->extensions[$key])) ? $this->extensions[$key] : NULL); } public function __construct($string, $planet, $alliance) { $this->json = $string; $this->planet = $planet; $this->alliance = $alliance; $array = json_decode($string, true); foreach ($array AS $key => $value) if (in_array($key, $this->structure)) { if (in_array($key, self::$var_json)) $value = json_decode($value, true); $this->class[$key] = $value; } else $this->extensions[$key] = $value; $this->avatar = users::checkAvatar($this->avatar); if (!isset($this->extensions['nb_success'])) $this->extensions['nb_success'] = self::countSuccess(); if (!isset($this->extensions['nb_missions'])) $this->extensions['nb_missions'] = self::countMissions(); $this->extensions['ressources_time'] = (!isset($_COOKIE['ressources_time'])) ? 10000 : $_COOKIE['ressources_time']; } public function countMissions() {return count($this->mission);} public function countSuccess() {return count($this->achievements);} public function isFriend($user_id) { if (count($this->friends)) foreach ($this->friends AS $friend_id) if ($friend_id['user_id'] == $user_id) return true; return false; } public function __set($key, $val) { if (isset($this->class[$key])) $this->class[$key] = $val; else $this->extensions[$key] = $val; } public function getDatas() { return array_merge_recursive($this->extensions, $this->class); } public function getClass() { return $this->class; } public function getPlanet() { return $this->planet; } public function setPlanet($planet) { $this->planet = $planet; } public function getRessources() {return $this->planet->getRessources();} public function setRessources($ressources) {$this->planet->setRessources($ressources);} public function getAlliance() {return $this->alliance;} public function setAlliance($alliance) {$this->alliance = $alliance;} public function getJSON() {return $this->json;} } ?>
true
bbac5d2e65944aebffbd6424d2bda11e770bb678
PHP
JCdotpe/cenpesco
/capacitacion/editar_notas.php
ISO-8859-1
9,443
2.5625
3
[]
no_license
<?php include ("seguridad.php"); ini_set('max_execution_time', 300); if($_SESSION["tipo"]==1) { ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <?php include("conexion.php"); date_default_timezone_set('Etc/GMT+5'); error_reporting(E_ALL ^ E_NOTICE); $titulo=$_POST['titulo']; $tipo=$_POST['tipo']; $id=$_POST['id']; $fecha=$_POST['fecha']; $tipo=$_POST['tipo']; $bandera=$_POST['bandera']; $cantidad=$_POST['cantidad']; $peso=$_POST['peso']; $tipo=$_POST['tipo']; $id_examen=$_GET['id_examen']; $id_examen1=$_POST['id_examen']; //guardar notas if($bandera==1 and $id_examen1!=NULL and $cantidad!=NULL) { //funcion guardar function insertar($dni,$id_examen1,$nota,$peso,$id) { $sql="UPDATE cap_calificacion SET nota='$nota' WHERE id='".$id."' AND id_examen='".$id_examen1."'"; mysql_query($sql); } for($i=1; $i<=$cantidad; $i++) { insertar($_POST['dni'][$i],$id_examen1,$_POST['nota'][$i],$peso,$_POST['id'][$i]); } } ///--------comprobar alumnos asignado $bnd=0; $result = mysql_query("SELECT * FROM cap_asignacion_alu"); while ($row = mysql_fetch_row($result)) { $bnd=1; } //---roles include("roles.php"); //------------------ $aleatorio = rand (1,1000000); //funcin da function diasem($fecha) { $anio=date("Y",strtotime($fecha)); $mes=date("m",strtotime($fecha)); $dia=date("d",strtotime($fecha)); if (($anio%4 == 0 and $anio%100 != 0) or $anio%400 == 0 ) { $bisiesto=1; } else { $bisiesto=0; } if($mes=='01') { $b=0; $m='Enero'; } if($mes=='02') { $b=31; $m='Febrero'; } if($mes=='03') { $b=59; $m='Marzo'; } if($mes=='04') { $b=90; $m='Abril'; } if($mes=='05') { $b=120; $m='Mayo'; } if($mes=='06') { $b=151; $m='Junio'; } if($mes=='07') { $b=181; $m='Julio'; } if($mes=='08') { $b=212; $m='Agosto'; } if($mes=='09') { $b=243; $m='Septiembre'; } if($mes=='10') { $b=273; $m='Octubre'; } if($mes=='11') { $b=304; $m='Noviembre'; } if($mes=='12') { $b=334; $m='Diciembre'; } if($bisiesto==1 and $mes!='01' and $mes!='02') { $b=intval($dia)+$b+$bisiesto; } else { $b=intval($dia)+$b; } $a=$anio-1; $c=floor($a/4); $d=floor($a/100); $e=floor($a/400); $f=$a+$b+$c+$e-$d; $g=($f%7); if($g==0) { $ds="Domingo"; } if($g==1) { $ds="Lunes"; } if($g==2) { $ds="Martes"; } if($g==3) { $ds="Miercoles"; } if($g==4) { $ds="Jueves"; } if($g==5) { $ds="Viernes"; } if($g==6) { $ds="Sbado"; } return $ds.' '.$dia.' de '.$m.' de '.$anio; //return $ds.' '.$dia.' de '.$m; } //Comprobamos Calificacin $flag=0; $men="Ingrese notas para este examen"; $result = mysql_query("SELECT * FROM cap_calificacion WHERE id_examen='".$id_examen."'"); while ($row = mysql_fetch_row($result)) { $flag=1; $men="Ya existen notas registradas para este examen"; } ////// $result = mysql_query("SELECT * FROM cap_examen WHERE id_examen='".$id_examen."'"); while($row = mysql_fetch_row($result)) { $exam=$row[1]; } ?> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <script src="src/js/jscal2.js"></script> <script src="src/js/lang/en.js"></script> <link rel="stylesheet" type="text/css" href="src/css/jscal2.css" /> <link rel="stylesheet" type="text/css" href="src/css/border-radius.css" /> <link rel="stylesheet" type="text/css" href="src/css/steel/steel.css" /> <title>Aula Virtual de Capacitaci&oacute;n</title> <style type="text/css"> @import url("css/estilo.css"); @import url("css/letras1.css"); </style> <script language="JavaScript"> function pregunta() { if (confirm('Realmente desea eliminar este registro')){ document.form2.submit() } else { return (false); } } //--------- function validar() { if (document.form1.id_modulo.selectedIndex == 0) { alert('Por favor, seleccione un mdulo'); document.form1.id_modulo.focus(); return false; } else if (document.form1.titulo.value == 0) { alert('Por favor, escriba un ttulo'); document.form1.titulo.focus(); return false; } else if (document.form1.fecha.value == 0) { alert('Por favor, seleccione una fecha'); document.form1.fecha.focus(); return false; } else { return true; } } </script> </head> <body> <?php if($_SESSION["sexo"]=='F') { $saludo='Bienvenida'; } if($_SESSION["sexo"]=='M') { $saludo='Bienvenido'; } $cad=''; $result = mysql_query("SELECT * FROM cap_modulo WHERE estado='1'"); while ($row = mysql_fetch_row($result)) { $cad=$cad.' | <a href="principal.php?id_modulo='.$row[0].'">'.$row[1].'</a>'; } ?> <div class="cuerpo"> <div class="cabecera"><br /><span class="titulo"> <?php echo $saludo.', '.($_SESSION["nombres"]); ?></span> <span class="titulo"><br> <strong>AULA VIRTUAL DEL PROYECTO DE CENSO DE PESCA CONTINENTAL DEL PER&Uacute;</strong></span><br> <table width="660" border="0" align="center" cellpadding="2" cellspacing="2"> <tr> <td width="164" height="40"><p class="inicio"><a href="principal.php" ></a></p></td> <td width="164" height="40"><p class="perfiles"><a href="<?php echo $companeros; ?>" ></a></p></td> <td width="164" height="40"><p class="calificaciones"><a href="<?php echo $calificaciones; ?>" ></a></p></td> <td width="164" height="40"><p class="salir"><a href="salir.php" ></a></p></td> </tr> </table> <br> </div> <div id="menuv"> <ul> <li > <span class="subtitulo" ><center><br> <strong class="title">SECCIONES DEL AULA VIRTUAL</strong><br> <br></center></span> </li> <li> </li> </ul> <div class="navegador"> <p class="cuenta"><a href="cuenta.php"></a></p> <p class="examen"><a href="<?php echo $examen; ?>"></a></p> <p class="archivo"><a href="<?php echo $file; ?>"></a></p> <p class="recurso"><a href="<?php echo $recurso; ?>"></a></p> <p class="ayuda"><a href="<?php echo $ayuda; ?>"></a></p> </div> </div> <div class=panel> <p>&nbsp;</p> <p><span class="titulo2"> Editar notas de <?php echo $exam; ?> | <a href="agregar_notas.php" class="titulo2">Regresar</a></span><br /> </p> <hr /> <table width="800" border="0" cellpadding="1" cellspacing="1"> <tr> <td><form id="form1" name="form1" method="post" action="editar_notas.php"> <!-- full-name input--> <table width="700" border="0" cellpadding="1" cellspacing="0"> <tr> <td align="left" valign="top"><label class="aviso"> <strong></strong></label></td> </tr> <tr> <td height="20" align="left" valign="top" class="texto1"><table width="637" border="0" cellpadding="1" cellspacing="0" style="border:thin;border: 1px solid #99FFCC"> <tr> <td width="418" align="left" class="title">APELLIDOS Y NOMBRES</td> <td width="100" align="left" class="title">DNI</td> <td width="111" align="center" class="title">NOTA</td> </tr> <?php //echo $id_examen; if($id_examen!=0) { $result = mysql_query("SELECT * FROM cap_examen WHERE id_examen='".$id_examen."'"); if ($row = mysql_fetch_row($result)) { $peso=$row[6]; $tipo=$row[5]; } $c=0; $sql="SELECT c.nota, c.id_examen, r.id, r.ap_paterno, r.ap_materno, r.nombre1, r.nombre2, r.dni FROM cap_calificacion AS c INNER JOIN regs AS r on(c.id=r.id) WHERE c.id_examen='".$id_examen."' AND c.id_modulo='".$_SESSION["seccion"]."' GROUP BY dni ORDER BY r.ap_paterno ASC"; $result = mysql_query($sql); while ($row = mysql_fetch_row($result)) { $c=$c+1; if($c%2==0) { $color="#99FFCC"; } else { $color="#FFFFFF"; } ?> <tr bgcolor="<?php echo $color; ?>"> <td align="left" class="texto1"><?php echo $c.'. '.utf8_encode(strtoupper($row[3].' '.$row[4].' '.$row[5].' '.$row[6])); ?> <input name="id[<?php echo $c; ?>]" type="hidden" id="id<?php echo $c; ?>" value="<?php echo $row[2]; ?>" /> </td> <td align="left" class="texto1"> <?php echo $row[7]; ?> <input name="dni[<?php echo $c; ?>]" type="hidden" id="dni<?php echo $c; ?>" value="<?php echo $row[7]; ?>" /></td> <td align="center"><label> <input name="bandera" type="hidden" id="bandera" value="1" /> <input name="nota[<?php echo $c; ?>]" type="text" id="nota<?php echo $c; ?>" value="<?php echo $row[0]; ?>" size="5" maxlength="5" /> </label></td> </tr> <?php } } ?> </table> </td> </tr> <tr> <td height="38" align="center" valign="middle" class="texto1"> <input name="id_examen" type="hidden" id="id_examen" value="<?php echo $id_examen; ?>" /> <input name="cantidad" type="hidden" id="cantidad" value="<?php echo $c; ?>" /> <label> <input name="button" type="submit" class="subtitu" id="button" value=" CAMBIAR" /> </label></td> </tr> <tr> <td height="38" align="left" valign="middle" class="title">&nbsp;</td> </tr> </table> <table width="700" border="0" cellpadding="1" cellspacing="0"> <tr> </tr> </table> <p>&nbsp;</p> </form></td> </tr> </table> </div > </div> </body> </html> <?php } ?>
true
41089f0bea89d19109a0dda8a8f51efa1ec9b09f
PHP
cgerling/anitop
/server/src/entity/Anime.php
UTF-8
493
3
3
[]
no_license
<?php namespace anitop\entity; class Anime extends Entity { public $name; public $description; public $studio; public $publisher; public $image; public function __construct(string $name = '', string $description = '', string $studio = '', string $publisher = '', string $image = '') { $this->name = $name; $this->description = $description; $this->studio = $studio; $this->publisher = $publisher; $this->image = $image; } }
true
6c7341394bc2962e48ded9bbb1526b9ad40f32ae
PHP
Ndu-Systems/mr-concrete-api
/models/Address.php
UTF-8
3,403
2.953125
3
[]
no_license
<?php class Address { //DB Stuff private $conn; public function __construct($db) { $this->conn = $db; } public function getAddressByOtherId($OtherId) { $query = "SELECT * FROM address WHERE OtherId =?"; $stmt = $this->conn->prepare($query); $stmt->execute(array($OtherId)); if ($stmt->rowCount()) { return $stmt->fetchAll(PDO::FETCH_ASSOC); } } public function getAddressIdById($AddressId) { $query = "SELECT * FROM address WHERE AddressId =?"; $stmt = $this->conn->prepare($query); $stmt->execute(array($AddressId)); if ($stmt->rowCount()) { return $stmt->fetch(PDO::FETCH_ASSOC); } } public function AddAddress( $AddressId, $UserId, $AddressType, $AddressLine1, $AddressLine2, $AddressLine3, $City, $Province, $PostalCode, $CrateUserId, $ModifyUserId, $StatusId ) { $query = "INSERT INTO address( AddressId, UserId, AddressType, AddressLine1, AddressLine2, AddressLine3, City, Province, PostalCode, CrateUserId, ModifyUserId, StatusId ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)"; try { $stmt = $this->conn->prepare($query); if ($stmt->execute(array( $AddressId, $UserId, $AddressType, $AddressLine1, $AddressLine2, $AddressLine3, $City, $Province, $PostalCode, $CrateUserId, $ModifyUserId, $StatusId ))) { return $this->getAddressIdById($AddressId); } } catch (Exception $e) { return array("ERROR", $e); } } public function UpdateAddress( $AddressId, $UserId, $AddressType, $AddressLine1, $AddressLine2, $AddressLine3, $City, $Province, $PostalCode, $CrateUserId, $ModifyUserId, $StatusId ) { $query = "UPDATE address SET UserId = ?, AddressType = ?, AddressLine1 = ?, AddressLine2 = ?, AddressLine3 = ?, City = ?, Province = ?, PostalCode = ?, CrateUserId = ?, ModifyDate = now(), ModifyUserId = ?, StatusId = ? WHERE AddressId = ? "; try { $stmt = $this->conn->prepare($query); if ($stmt->execute(array( $UserId, $AddressType, $AddressLine1, $AddressLine2, $AddressLine3, $City, $Province, $PostalCode, $CrateUserId, $ModifyUserId, $StatusId, $AddressId ))) { return $this->getAddressIdById($AddressId); } } catch (Exception $e) { return array("ERROR", $e); } } }
true
7b479293ac90cbc355b011de983f0cbc86805116
PHP
inhere/php-console
/src/IO/Output/StreamOutput.php
UTF-8
2,291
3.015625
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); /** * The file is part of inhere/console * * @author https://github.com/inhere * @homepage https://github.com/inhere/php-console * @license https://github.com/inhere/php-console/blob/master/LICENSE */ namespace Inhere\Console\IO\Output; use Inhere\Console\Concern\AbstractOutput; use InvalidArgumentException; use Toolkit\FsUtil\File; use Toolkit\Stdlib\Helper\DataHelper; use Toolkit\Stdlib\OS; use function sprintf; use function stream_get_meta_data; use const PHP_EOL; use const STDOUT; /** * Class StreamOutput * @package Inhere\Console\IO\Output */ class StreamOutput extends AbstractOutput { /** * Normal output stream. Default is STDOUT * * @var resource */ protected $stream = STDOUT; /** * @param string $content * * @return int */ public function write(string $content): int { return File::streamWrite($this->stream, $content); } /** * @param string $format * @param mixed ...$args * * @return int */ public function writef(string $format, ...$args): int { $content = sprintf($format, ...$args); return File::streamWrite($this->stream, $content); } /** * @param string $content * @param bool $quit * @param array $opts * * @return int */ public function writeln($content, bool $quit = false, array $opts = []): int { $content = DataHelper::toString($content); return File::streamWrite($this->stream, $content . PHP_EOL); } /** * @return resource */ public function getStream() { return $this->stream; } /** * @param resource $stream */ public function setStream($stream): void { File::assertStream($stream); $meta = stream_get_meta_data($stream); if (!str_contains($meta['mode'], 'w') && !str_contains($meta['mode'], '+')) { throw new InvalidArgumentException('Expected a writeable stream'); } $this->stream = $stream; } /** * Whether the stream is an interactive terminal * * @return bool */ public function isInteractive(): bool { return OS::isInteractive($this->stream); } }
true
3e6a05665f11d8f95da642987d3c71f1f9a1ca35
PHP
juanvilu/siteGESBlue
/newsletter/num008/variables/index.php
UTF-8
10,318
2.546875
3
[]
no_license
<head> <title>Uso de variables en el reporteador</title> <link href="news_general.css" rel="stylesheet" type="text/css" /> </head> <body> <div class="texto"> <h3>Uso de variables en el editor de formatos.</h3> <p align="right" class="autor"><em>Autor: Roberto Antonio Romero N&aacute;jera</em></p> <p align="justify"> <strong>Control Escolar GES</strong> cuenta con una herramienta muy poderosa que es su editor de formatos; con el, los usuarios pueden obtener desde documentos muy sencillos que solo muestren etiquetas y campos simples, hasta aquellos documentos que son capaces de realizar diversas operaciones aritm&eacute;ticas o manejo de datos.</p> <p align="justify">En los documentos complejos, muchas veces se hace necesario el uso de un recurso de manejo de informaci&oacute;n llamado uso de variables.<br> </p> <h4 align="justify"><strong>&iquest;Qu&eacute; es una variable?</strong></h4> <p>Una variable se define como todo dato que puede cambiar en el transcurso de la ejecuci&oacute;n de un programa (en este caso de un documento). En Control Escolar GES, Usted tiene la posibilidad de usar dos tipos de variables: las <strong>num&eacute;ricas</strong> que podr&aacute;n contener solo valores num&eacute;ricos y las <strong>alfanum&eacute;ricas</strong> que pueden contener combinaci&oacute;n de n&uacute;meros, letras y s&iacute;mbolos.</h4> <p align="justify"><strong>a) Num&eacute;ricas.</strong> Una variable num&eacute;rica se manejar&aacute; con la funci&oacute;n VarNum y la sintaxis es la siguiente:<br> <br> <div class="texto"><strong>VARNUM( &lt;&iacute;ndice&gt;, [acci&oacute;n], [valor_num&eacute;rico_para_almacenar] )</strong><br> <ul> <li>Indice. Las variables se identifican con un n&uacute;mero que puede ser desde 1 hasta 100.<br> </li> <li>Acci&oacute;n = 0 (cero) para consultar el valor previamente almacenado, 1 (uno) para almacenar un nuevo valor y 3 (tres) para incrementar el valor. Por default es 0 (cero). <br> </li> <li>Valor_num&eacute;rico_para_almacenar = Es el n&uacute;mero que ser&aacute; almacenado o incrementado en la variable. Solo deber&aacute; indicarse cuando acci&oacute;n es 1 (uno) &oacute; 3 (tres).<br> </li> </ul> </div> <p align="justify"><strong>b) AlfaNum&eacute;ricas.</strong> Por otra parte las variables num&eacute;ricas se controlan con la funci&oacute;n VarAlfa y la sintaxis es la siguiente:<br> <br> <div class="texto"><strong>VARALFA( &lt;&iacute;ndice&gt;, [acci&oacute;n], [valor_textual_para_almacenar] )</strong><br> <ul> <li>Indice. N&uacute;mero de la variable (desde 1 hasta 100).<br> </li> <li>Acci&oacute;n = 0 (cero) para consultar un valor previamente almacenado, 1 (uno) para almacenar un nuevo dato y 3 (tres) para concatenar el valor. Por default es 0 (cero). <br> </li> <li>Valor_textual_para_almacenar = S&oacute;lo cuando acci&oacute;n es 1 (uno) &oacute; 3 (tres), es el valor textual que ser&aacute; almacenado en la variable. </li> </ul> </div> <p> Para las variables num&eacute;ricas solo deber&aacute; proporcionar datos tipo num&eacute;rico (enteros o de punto flotante -monetarios-) y las alfanum&eacute;ricas datos tipo alfanum&eacute;rico.</p> <h4><strong>&iquest;C&oacute;mo saber el tipo de dato que contiene un campo?</strong></h4> <p>En el editor Usted tendr&aacute; disponibles diversos campos al momento de dise&ntilde;ar un formato y es muy importante saber el tipo de dato de un campo si queremos almacenarlo en una variable. La forma de saber el tipo de dato de un campo es usando la funci&oacute;n TYPEOF(), la cual indicar&aacute; que tipo de dato es. </p> <p>Ejemplo:<br> TYPEOF( CAMPOXYZ ) = Float / Integer / String o Date = (flotante, entero, texto o fecha).</p> <p align="justify">Esta es una forma pr&aacute;ctica y r&aacute;pida de saber el tipo de dato de un campo, no incluya la expresi&oacute;n en el dise&ntilde;o final del reporte.<br> <br> Se puede usar la opci&oacute;n [<strong>Validar Expresi&oacute;n</strong>] de la ventana de insertar expresiones, para saber de una forma r&aacute;pida el tipo de dato:</p> <p align="justify"><img src="<?php echo $url;?>comprobacion.jpg" width="474" height="92"><br> </p> <h4 align="justify"><strong>Conversi&oacute;n de tipo de dato</strong></h4> <p align="justify"> Si Usted desea almacenar el contenido de un campo de tipo alfanum&eacute;rico en una variable num&eacute;rica, deber&aacute; convertirlo a tipo num&eacute;rico (float o integer). Para ello se usa la funci&oacute;n NUM(). </p> <p align="justify">Ejemplo:<br> VARNUM(1,1,NUM(CALIF_BIM1))<br> <br> De forma similar ocurre con las variables alfanum&eacute;ricas, si deseamos almacenar en ellas valores num&eacute;ricos primero deberemos convertirlas a tipo texto usando la funci&oacute;n STR(). </p> <p align="justify">Ejemplo: <br> VARALFA(1,1,STR(ADEUDO))</p> <h4 align="justify"><strong>Usando una expresi&oacute;n compleja para almacenar datos en una variable</strong></h4> <p align="justify">Se puede almacenar datos derivados de campos o constantes directas, pero tambi&eacute;n es posible usar expresiones complejas para almacenar datos. </p> <p align="justify">En el siguiente ejemplo, almacenaremos en una variable alfanum&eacute;rica la etiqueta <strong>Hombre</strong> o <strong>Mujer</strong>, de acuerdo al contenido del campo SEXO (que contiene F o M para el g&eacute;nero de una persona). </p> <p align="center"> VARALFA(1,1,IF(SEXO='F','Mujer','Hombre')) <br></p> <h4><strong>Ejemplo b&aacute;sico para comprender el uso de variables</strong></h4> <p>Se tiene como objetivo numerar una lista de alumnos, para lo cual, en el dise&ntilde;o del reporte dentro de la secci&oacute;n encabezado de p&aacute;gina agregamos la expresi&oacute;n: VARNUM(1,1,0), asignando a la variable num&eacute;rica 1 (uno) el valor cero. Esto se llama &quot;inicializaci&oacute;n&quot; y nos permite tener la certeza de que la variable que llevar&aacute; el conteo de alumnos siempre iniciar&aacute; en CERO.</p> <p align="justify"><img src="<?php echo $url;?>varencabezado.jpg" width="606" height="184"><br> <br> Dentro del mismo formato, iremos a la secci&oacute;n detalle donde colocaremos la expresi&oacute;n VARNUM(1,3,1), que incrementar&aacute; por uno el valor de la variable por cada registro procesado. </p> <p align="justify">Ah&iacute; mismo podremos colocar la expresi&oacute;n VARNUM(1) que nos permitir&aacute; consultar el dato de la variable.</p> <p align="justify"><img src="<?php echo $url;?>vardetalle.jpg" width="606" height="167"></p> <p align="justify">En reportes complejos, con muchas variables, modificaciones y consultas es importante verificar el orden de las expresiones, ya que las instrucciones se ejecutar&aacute;n en secuencia (una tras otra) en el orden que fueron insertadas sin importar la posici&oacute;n en la que est&eacute;n colocadas en el formato. </p> <p align="justify">Para poder verificar el orden de las expresiones se debe hacer &quot;clic&quot; derecho en la parte inferior de la ventana de cualquier secci&oacute;n y seleccionar la opci&oacute;n [<strong>Modificar Orden de Expresiones...</strong>].</p> <p align="justify"><img src="<?php echo $url;?>ordenexp.jpg" width="415" height="91"></p> <p align="justify">Si el orden de las expresiones estuviera incorrecto, se puede utilizar los botones de ordenamiento hasta que logremos el orden deseado.</p> <p align="justify"><img src="<?php echo $url;?>ventana_orden.jpg" width="305" height="204"></p> <p align="justify">Un orden inadecuado puede dar lugar a datos imprecisos.</p> <p align="justify">Ejemplo del reporte con el orden de sus expresiones correcto:</p> <p align="justify"><img src="<?php echo $url;?>rep_orden_ok.jpg" width="593" height="226"></p> <p align="justify">Ejemplo del mismo reporte pero con el orden incorrecto:<br> <br> <img src="<?php echo $url;?>rep_orden_bad.jpg" width="593" height="228"> </p> <p align="justify">Cuando se manejan muchas expresiones usando variables, es de suma importancia cuidar este aspecto. Como se aprecia en la siguiente imagen:</p> <p align="justify"><img src="<?php echo $url;?>avanzado.jpg" width="656" height="307"></p> <p align="justify">A continuaci&oacute;n se propone un ejemplo de c&oacute;mo contar la poblaci&oacute;n de mujeres y hombres existente en un grupo de alumnos.</p> <p align="justify">1) En el encabezado se inicializan dos variables num&eacute;ricas, una para contar a los hombres y otra a las mujeres; se les asigna el valor cero.<br> <br> VARNUM(2,1,0) y VARNUM(3,1,0).</p> <p align="justify">2) En la secci&oacute;n detalle se colocan las expresiones:</p> <p align="justify">VARNUM(2,3,IF(SEXO='F',1,0)) Para contar a las mujeres. <br> VARNUM(3,3,IF(SEXO='M',1,0)) Para contar a los hombres.</p> <p align="justify">3) Finalmente, en el pie de p&aacute;gina o en el sumario se consultan las variables y se suman para saber el total de alumnos:</p> <p align="justify"><img src="<?php echo $url;?>sumario.jpg" width="667" height="202"></p> <p align="justify">Y el reporte mostrar&iacute;a el siguiente resultado:</p> <p align="justify"><img class="noborder" src="<?php echo $url;?>reporte_alumnos.jpg" width="725" height="344"></p> <p align="justify">Este es una aproximaci&oacute;n b&aacute;sica al uso de variables, pero Control Escolar GES tiene la solidez necesaria para dar soporte a dise&ntilde;os m&aacute;s complejos. </p> <div class="valoracion"> <p><a href="http://www.grupoges.com.mx">Consulta las caracter&iacute;sticas de Control Escolar GES en su versi&oacute;n 4</a>. </p> </div> </div> </body>
true
3e213e16a2c88499e4c353f6ab55d9a0f5ce1605
PHP
dwiaji22/tugas-pemweb
/Pemweb Tugas 6/baca.php
UTF-8
640
3.03125
3
[]
no_license
<?php $file = "data.txt"; $data = file_get_contents($file); $baris = explode("[R]", $data); echo "<table border=1>"; echo "<tr>"; echo " <td>Nama</td><td>Email</td>"; echo " <td>Phone</td><td>Umur</td><td>Action</td>"; echo "</tr>"; for($i =0; $i<count($baris)-1; $i++) { $col = explode("|F|", $baris[$i]); echo "<tr>"; echo " <td>" . $col[0] . "</td>"; echo " <td>" . $col[1] . "</td>"; echo " <td>" . $col[2] . "</td>"; echo " <td>" . $col[3] . "</td>"; echo ' <td> <a href="delete.php?row='.$i.'">DELETE</a> <a href="edit.php?row='.$i.'">EDIT</a> </td>'; echo "</tr>"; } echo "</table>";
true
927ac8ba2eb007304198c62133ac8bf31bb76134
PHP
astapov-m/laravel-package-wb
/src/Library/Incomes/IncomeRepository.php
UTF-8
1,047
2.640625
3
[]
no_license
<?php namespace Astapovm\Wb\Library\Incomes; use Astapovm\Wb\Library\Interfaces\RepositoryInterface; use Astapovm\Wb\Library\Traits\RepositoryTrait; use App\Models\Fbo\WbIncome; class IncomeRepository implements RepositoryInterface { use RepositoryTrait; private static function checkingAvailability($incomeId,$nmId) : bool { $order = WbIncome::where('incomeId',$incomeId)->where('nmId',$nmId)->get(); return $order->isEmpty(); } public static function store($item): void { if(static::checkingAvailability($item['incomeId'],$item['nmId'])){ WbIncome::create($item); } } public static function update($item): void { WbIncome::where('incomeId', $item['incomeId'])->update($item); } public static function storeOrUpdate($item): void { WbIncome::updateOrCreate(['incomeId'=> $item['incomeId']],$item); } public static function delete($item): void { WbIncome::where('incomeId', $item['incomeId'])->delete(); } }
true
9942b985f67a57676e906bc876df9b841f8ce894
PHP
Amoldreamer/mars
/app/Models/WorkshopBalance.php
UTF-8
2,021
2.578125
3
[ "MIT" ]
permissive
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\DB; use App\Models\Semester; use App\Models\Workshop; class WorkshopBalance extends Model { public $timestamps = false; protected $fillable = [ 'semester_id', 'workshop_id', 'allocated_balance', 'used_balance', ]; public function workshop() { return $this->belongsTo('App\Models\Workshop'); } public function semester() { return $this->belongsTo('App\Models\Semester'); } public function membersPayedKKTNetreg() { return $this->payedKKTNetregInSemester(Semester::current()); } public function membersPayedKKTNetregInSemester(Semester $semester) { return $this->workshop->users->filter(function ($user, $key) use ($semester) { return $user->isActiveIn($semester) && (! $user->hasToPayKKTNetregInSemester($semester)); }); } /** * Generates all the workshops' allocated balance in the current semester. * For all active members in a workshop who payed kkt: * kkt * (isResident ? 0.6 : 0.45) / member's workshops' count */ public static function generateBalances() { foreach(Workshop::all() as $workshop) { $balance = 0; foreach ($workshop->users as $member) { if ($member->isActive() && !$member->hasToPayKKTNetreg()) { $balance += config('custom.kkt') * ($member->isResident() ? config('custom.workshop_balance_resident') : config('custom.workshop_balance_extern') ) / $member->workshops->count(); } } DB::table('workshop_balances') ->updateOrInsert( ['semester_id' => Semester::current()->id, 'workshop_id' => $workshop->id], ['allocated_balance' => $balance] ); } } }
true
b97a119de132196881501afc126c94310bf9e83e
PHP
VANSEBROUCK/Arbre_Raphael_VANSEBROUCK
/src/vendor/symfony/src/Symfony/Bundle/DoctrineMongoDBBundle/Validator/Constraints/DoctrineMongoDBUniqueValidator.php
UTF-8
4,356
2.65625
3
[ "MIT" ]
permissive
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien.potencier@symfony-project.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Bundle\DoctrineMongoDBBundle\Validator\Constraints; use Doctrine\ODM\MongoDB\DocumentManager; use Doctrine\ODM\MongoDB\Proxy\Proxy; use Doctrine\ODM\MongoDB\Mapping\ClassMetadata; use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\ConstraintValidator; /** * Doctrine MongoDB ODM unique value validator. * * @author Bulat Shakirzyanov <bulat@theopenskyproject.com> */ class DoctrineMongoDBUniqueValidator extends ConstraintValidator { protected $dm; public function __construct(DocumentManager $dm) { $this->dm = $dm; } /** * @param Doctrine\ODM\MongoDB\Document $value * @param Constraint $constraint * @return Boolean */ public function isValid($document, Constraint $constraint) { $class = get_class($document); $metadata = $this->dm->getClassMetadata($class); if ($metadata->isEmbeddedDocument) { throw new \InvalidArgumentException(sprintf("Document '%s' is an embedded document, and cannot be validated", $class)); } $query = $this->getQueryArray($metadata, $document, $constraint->path); // check if document exists in mongodb if (null === ($doc = $this->dm->getRepository($class)->findOneBy($query))) { return true; } // check if document in mongodb is the same document as the checked one if ($doc === $document) { return true; } // check if returned document is proxy and initialize the minimum identifier if needed if ($doc instanceof Proxy) { $metadata->setIdentifierValue($doc, $doc->__identifier); } // check if document has the same identifier as the current one if ($metadata->getIdentifierValue($doc) === $metadata->getIdentifierValue($document)) { return true; } $this->context->setPropertyPath($this->context->getPropertyPath() . '.' . $constraint->path); $this->setMessage($constraint->message, array( '{{ property }}' => $constraint->path, )); return false; } protected function getQueryArray(ClassMetadata $metadata, $document, $path) { $class = $metadata->name; $field = $this->getFieldNameFromPropertyPath($path); if (!isset($metadata->fieldMappings[$field])) { throw new \LogicException('Mapping for \'' . $path . '\' doesn\'t exist for ' . $class); } $mapping = $metadata->fieldMappings[$field]; if (isset($mapping['reference']) && $mapping['reference']) { throw new \LogicException('Cannot determine uniqueness of referenced document values'); } switch ($mapping['type']) { case 'one': // TODO: implement support for embed one documents case 'many': // TODO: implement support for embed many documents throw new \RuntimeException('Not Implemented.'); case 'hash': $value = $metadata->getFieldValue($document, $mapping['fieldName']); return array($path => $this->getFieldValueRecursively($path, $value)); case 'collection': return array($mapping['fieldName'] => array('$in' => $metadata->getFieldValue($document, $mapping['fieldName']))); default: return array($mapping['fieldName'] => $metadata->getFieldValue($document, $mapping['fieldName'])); } } /** * Returns the actual document field value * * E.g. document.someVal -> document * user.emails -> user * username -> username * * @param string $field * @return string */ protected function getFieldNameFromPropertyPath($field) { $pieces = explode('.', $field); return $pieces[0]; } protected function getFieldValueRecursively($fieldName, $value) { $pieces = explode('.', $fieldName); unset($pieces[0]); foreach ($pieces as $piece) { $value = $value[$piece]; } return $value; } }
true
ea7d899832cf50eaca9884d984d783df129ede98
PHP
wikipalco/yetishare
/plugins/wikipal/pluginWikipal.class.php
UTF-8
2,345
2.65625
3
[]
no_license
<?php class pluginWikipal extends Plugin { public $config = null; public function __construct() { // get the plugin config include(DOC_ROOT.'/plugins/wikipal/_plugin_config.inc.php'); // load config into the object $this->config = $pluginConfig; } public function getPluginDetails() { return $this->config; } public function install() { // setup database $db = Database::getDatabase(); // copy over WikiPal details from core if they exist $pre_wikipal_webgate_id = $db->getValue('SELECT config_value FROM site_config WHERE config_key="wikipal_payments_merchant" LIMIT 1'); $pre_wikipal_method = $db->getValue('SELECT config_value FROM site_config WHERE config_key="wikipal_payments_server" LIMIT 1'); if( $pre_wikipal_webgate_id && $pre_wikipal_method ) { // get plugin details $pluginDetails = $this->getPluginDetails(); // update settings $db = Database::getDatabase(); $db->query('UPDATE plugin SET plugin_settings = :plugin_settings WHERE folder_name = :folder_name', array(' plugin_settings'=>'{ "wikipal_webgate_id":"'.$pre_wikipal_webgate_id.'", "wikipal_method":"'.$pre_wikipal_method.'" }', 'folder_name' => $pluginDetails['folder_name'] ) ); // delete old config value $db->query('DELETE FROM site_config WHERE config_key="wikipal_payments_merchant" LIMIT 1'); $db->query('DELETE FROM site_config WHERE config_key="wikipal_payments_server" LIMIT 1'); } return parent::install(); } public function uninstall() { // setup database $db = Database::getDatabase(); $db->query('DELETE FROM site_config WHERE config_key="wikipal_payments_merchant" LIMIT 1'); $db->query('DELETE FROM site_config WHERE config_key="wikipal_payments_server" LIMIT 1'); //this section deletes all wikipal setting from database after uninstall ... you can remove it if you dont want this action.... $pluginDetails = $this->getPluginDetails(); $db->query('DELETE FROM plugin WHERE plugin_name="'.$pluginDetails["plugin_name"].'" LIMIT 1'); // return parent::uninstall(); } }
true
29b6f30efd4f838bb660bd05c2328abecf297e94
PHP
avallete/PHPool
/d06/ex01/Vertex.class.php
UTF-8
1,889
3.390625
3
[]
no_license
<?php require_once('Color.class.php'); Class Vertex { static $verbose = FALSE; private $_x = 0.0; private $_y = 0.0; private $_z = 0.0; private $_w = 1.0; private $_color = NULL; function __get($var){ print "You can't get ".$var.", sorry :'(.\n"; } function __set($value, $var){ print "We can't assign".$var." at ".$value."sorry.\n"; } public function getX(){return $this->_x;} public function getY(){return $this->_y;} public function getZ(){return $this->_z;} public function getW(){return $this->_w;} public function getColor(){return $this->_color;} public function setX($value){$this->_x = floatval($value);} public function setY($value){$this->_y = floatval($value);} public function setZ($value){$this->_z = floatval($value);} public function setW($value){$this->_w = floatval($value);} public function setColor($value){ if ($value instanceof Color) $this->_color = $value;} public static function doc(){ if (file_exists('Vertex.doc.txt')) return (file_get_contents('Vertex.doc.txt').PHP_EOL); } function __construct(array $kwargs) { $this->setX($kwargs["x"]); $this->setY($kwargs["y"]); $this->setZ($kwargs["z"]); $this->getColor(); if (array_key_exists('w', $kwargs)) $this->setW($kwargs['w']); if (array_key_exists('color', $kwargs)) $this->setColor($kwargs['color']); else $this->_color = new Color(['rgb' => 0xFFFFFF]); if (self::$verbose === TRUE) print $this.' constructed'.PHP_EOL; } function __destruct(){ self::$verbose === TRUE ? print $this.' destructed'.PHP_EOL : 0;} function __tostring(){ $str = sprintf("Vertex( x: %.2f, y: %.2f, z:%.2f, w:%.2f", $this->getX(), $this->getY(), $this->getZ(), $this->getW()); if (self::$verbose === TRUE) $str = $str.', '.$this->getColor(); $str = $str.' )'; return ($str); } } ?>
true
474fa617a0e2303947d2c4de719899ea80e5627b
PHP
avisota/contao-subscription-recipient
/src/Controller/ButtonController.php
UTF-8
2,923
2.640625
3
[]
no_license
<?php /** * Avisota newsletter and mailing system * Copyright © 2016 Sven Baumann * * PHP version 5 * * @copyright way.vision 2016 * @author Sven Baumann <baumann.sv@gmail.com> * @package avisota/contao-subscription-recipient * @license LGPL-3.0+ * @filesource */ namespace Avisota\Contao\SubscriptionRecipient\Controller; use ContaoCommunityAlliance\DcGeneral\Contao\View\Contao2BackendView\Event\GetEditModeButtonsEvent; use Symfony\Component\EventDispatcher\EventSubscriberInterface; /** * Class ButtonController * * @package Avisota\Contao\SubscriptionRecipient\Controller */ class ButtonController implements EventSubscriberInterface { /** * Returns an array of event names this subscriber wants to listen to. * * The array keys are event names and the value can be: * * * The method name to call (priority defaults to 0) * * An array composed of the method name to call and the priority * * An array of arrays composed of the method names to call and respective * priorities, or 0 if unset * * For instance: * * * array('eventName' => 'methodName') * * array('eventName' => array('methodName', $priority)) * * array('eventName' => array(array('methodName1', $priority), array('methodName2')) * * @return array The event names to listen to */ public static function getSubscribedEvents() { return array( GetEditModeButtonsEvent::NAME => array( array('getExportButtons'), array('getMigrateButtons'), ), ); } /** * @param GetEditModeButtonsEvent $event */ public function getExportButtons(GetEditModeButtonsEvent $event) { if ($event->getEnvironment()->getDataDefinition()->getName() != 'mem_avisota_recipient_export') { return; } $translator = $event->getEnvironment()->getTranslator(); $buttons = array( 'export' => sprintf( '<input type="submit" name="save" id="save" class="tl_submit" accesskey="s" value="%s" />', $translator->translate('submit', 'mem_avisota_recipient_export') ) ); $event->setButtons($buttons); } /** * @param GetEditModeButtonsEvent $event */ public function getMigrateButtons(GetEditModeButtonsEvent $event) { if ($event->getEnvironment()->getDataDefinition()->getName() != 'mem_avisota_recipient_migrate') { return; } $translator = $event->getEnvironment()->getTranslator(); $buttons = array( 'migrate' => sprintf( '<input type="submit" name="save" id="save" class="tl_submit" accesskey="s" value="%s" />', $translator->translate('submit', 'mem_avisota_recipient_migrate') ) ); $event->setButtons($buttons); } }
true
53e21df58c4eb4731dafa4559c48b43c4195435b
PHP
DaniloAlmeidaSantos/WinnChay-1
/includes/Historic.php
UTF-8
1,731
2.875
3
[]
no_license
<?php class Historic { public function __construct() { require_once 'config/DbConnect.php'; // Chamando o método connect da classe Database e inicializando um link de conexão $this->conn = connect(); } public function viewHistory(){ $stmt = $this->conn->prepare('SELECT * FROM HISTORIC WHERE PLAYER1 = ? OR PLAYER2 = ?'); $stmt->bindParam(1, $_COOKIE['id'], PDO::PARAM_INT); $stmt->bindParam(2, $_COOKIE['id'], PDO::PARAM_INT); $stmt->execute(); if ($stmt->rowCount() > 0): while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { } else: echo "<strong style='color: black;'><h3>Participe de campeonatos para que apareça as suas partidas em seu historico</h1></strong>"; endif; } public function myChamp(){ $validate = $this->conn->prepare('SELECT NAME, IDPICTURE FROM CHAMPIONSHIPS'); $validate->execute(); while ($row = $validate->fetch(PDO::FETCH_ASSOC)) { $realName = $row['REAL_NAME']; $name = $row['NAME']; $idPic = $row['IDPICTURE']; $stmt = $this->conn->prepare("SELECT * FROM $name INNER JOIN PICTURES WHERE IDPLAYER = ? AND PICTURE.IDPICTURE = ?"); $stmt->bindValue(1, $_COOKIE['id'], PDO::PARAM_INT); $stmt->bindValue(2, $idPic, PDO::PARAM_INT); $stmt->execute(); while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { echo "<div class='elementTorn_tornWrap'> <div class='elementTorn_tornImg'> <img src='{$row["PICTURE"]}' alt=''> </div> <div class='elementTorn_tornName'> <h1>$realName</h1> </div> </div>"; } } } } ?>
true
3247affb35edd8d83175c2c4866e66f1a59c55b1
PHP
antwebstudio/yii2-core
/tests/unit/validators/SerializableDataValidatorCest.php
UTF-8
3,223
2.546875
3
[ "MIT" ]
permissive
<?php use ant\validators\SerializableDataValidator; class SerializableDataValidatorCest { public function _before(UnitTester $I) { } public function _after(UnitTester $I) { } // tests public function testValidateAttributeWhenHasError(UnitTester $I) { $model = new SerializableDataValidatorCestModel; $model->data = [ //'firstname' => null, ]; $validator = new SerializableDataValidator; $validator->rules = [ [['firstname'], 'required'], ]; $validator->validateAttribute($model, 'data'); $I->assertTrue($model->hasErrors()); } public function testValidateAttributeWhenNoError(UnitTester $I) { $model = new SerializableDataValidatorCestModel; $model->data = [ 'firstname' => 'firstname', ]; $validator = new SerializableDataValidator; $validator->rules = [ [['firstname'], 'required'], ]; $validator->validateAttribute($model, 'data'); $I->assertFalse($model->hasErrors()); } public function testValidateNestedData(UnitTester $I) { $model = new SerializableDataValidatorCestModel; $model->data = [ //'fullname' => 'fullname', ]; $validator = new SerializableDataValidator; $validator->rules = [ [['fullname'], 'required'], [['nested'], SerializableDataValidator::className(), 'rules' => [ [['firstname', 'lastname'], 'required'], ]], ]; $validator->validateAttribute($model, 'data'); //throw new \Exception(print_r($model->errors,1).print_r($model->errors,1)); $I->assertTrue($model->hasErrors()); $I->assertEquals([ 'data.fullname' => ['Fullname cannot be blank.'], // TODO: return error should be 'data.nested.firstname' => ['Firstname cannot be blank.'], 'data.data.firstname' => ['Firstname cannot be blank.'], 'data.data.lastname' => ['Lastname cannot be blank.'], ], $model->errors); } public function testValidateNestedData2(UnitTester $I) { $model = new SerializableDataValidatorCestModelWithRules; $model->data = [ //'fullname' => 'fullname', ]; $I->assertFalse($model->validate()); //throw new \Exception(print_r($model->errors,1).print_r($model->errors,1)); $I->assertTrue($model->hasErrors()); $I->assertEquals([ 'data.fullname' => ['Fullname cannot be blank.'], // TODO: return error should be 'data.nested.firstname' => ['Firstname cannot be blank.'], 'data.data.firstname' => ['Firstname cannot be blank.'], 'data.data.lastname' => ['Lastname cannot be blank.'], ], $model->errors); } } class SerializableDataValidatorCestModel extends \yii\base\Model { public $data; } class SerializableDataValidatorCestModelWithRules extends \yii\base\Model { public $data; public function rules() { return [ [['data'], SerializableDataValidator::className(), 'rules' => [ [['fullname'], 'required'], [['nested'], SerializableDataValidator::className(), 'rules' => [ [['firstname', 'lastname'], '\ant\validators\MultipleChoiceRequiredValidator'], ]], ]], ]; } }
true
9b380ccdff5bb706abc099282f9dfa421a7b5ac4
PHP
antarus/mystra-pve
/module/Backend/src/Backend/Controller/EvenementsPersonnageController.php
UTF-8
6,222
2.625
3
[]
no_license
<?php namespace Backend\Controller; use Zend\View\Model\ViewModel; /** * Controller pour la vue. * * @author Antarus * @project Raid-TracKer */ class EvenementsPersonnageController extends \Zend\Mvc\Controller\AbstractActionController { public $_servTranslator = null; public $_table = null; /** * Retourne le service de traduction en mode lazy. * * @return */ public function _getServTranslator() { if (!$this->_servTranslator) { $this->_servTranslator = $this->getServiceLocator()->get('translator'); } return $this->_servTranslator; } /** * Returne une instance de la table en lazy. * * @return */ public function getTable() { if (!$this->_table) { $this->_table = $this->getServiceLocator()->get('\Commun\Table\EvenementsPersonnageTable'); } return $this->_table; } /** * Retourne l'ecran de liste. * Affiche uniquement la page. Les données sont chargées via ajax plus tard. * * @return le template de la page liste. */ public function listAction() { // Pour optimiser le rendu $oViewModel = new ViewModel(); $oViewModel->setTemplate('backend/evenements-personnage/list'); return $oViewModel; } /** * Action pour le listing via AJAX. * * @return reponse au format Ztable */ public function ajaxListAction() { $oTable = new \Commun\Grid\EvenementsPersonnageGrid($this->getServiceLocator(),$this->getPluginManager()); $oTable->setAdapter($this->getAdapter()) ->setSource($this->getTable()->getBaseQuery()) ->setParamAdapter($this->getRequest()->getPost()); return $this->htmlResponse($oTable->render()); } /** * Action pour la création. * * @return array */ public function createAction() { $oForm = new \Commun\Form\EvenementsPersonnageForm();//new \Commun\Form\EvenementsPersonnageForm($this->getServiceLocator()); $oRequest = $this->getRequest(); $oFiltre = new \Commun\Filter\EvenementsPersonnageFilter(); $oForm->setInputFilter($oFiltre->getInputFilter()); if ($oRequest->isPost()) { $oEntite = new \Commun\Model\EvenementsPersonnage(); $oForm->setData($oRequest->getPost()); if ($oForm->isValid()) { $oEntite->exchangeArray($oForm->getData()); $this->getTable()->insert($oEntite); $this->flashMessenger()->addMessage($this->_getServTranslator()->translate("La evenements-personnage a été créé avec succès."), 'success'); return $this->redirect()->toRoute('backend-evenements-personnage-list'); } } // Pour optimiser le rendu $oViewModel = new ViewModel(); $oViewModel->setTemplate('backend/evenements-personnage/create'); return $oViewModel->setVariables(array('form' => $oForm)); } /** * Action pour la mise à jour. * * @return array */ public function updateAction() { $id = (int) $this->params()->fromRoute('id', 0); try { $oEntite = $this->getTable()->findRow($id); if (!$oEntite) { $this->flashMessenger()->addMessage($this->_getServTranslator()->translate("Identifiant de evenements-personnage inconnu."), 'error'); return $this->redirect()->toRoute('backend-evenements-personnage-list'); } } catch (\Exception $ex) { $this->flashMessenger()->addMessage($this->_getServTranslator()->translate("Une erreur est survenue lors de la récupération de la evenements-personnage."), 'error'); return $this->redirect()->toRoute('backend-evenements-personnage-list'); } $oForm = new \Commun\Form\EvenementsPersonnageForm();//new \Commun\Form\EvenementsPersonnageForm($this->getServiceLocator()); $oFiltre = new \Commun\Filter\EvenementsPersonnageFilter(); $oEntite->setInputFilter($oFiltre->getInputFilter()); $oForm->bind($oEntite); $oRequest = $this->getRequest(); if ($oRequest->isPost()) { $oForm->setInputFilter($oFiltre->getInputFilter()); $oForm->setData($oRequest->getPost()); if ($oForm->isValid()) { $this->getTable()->update($oEntite); $this->flashMessenger()->addMessage($this->_getServTranslator()->translate("La evenements-personnage a été modifié avec succès."), 'success'); return $this->redirect()->toRoute('backend-evenements-personnage-list'); } } // Pour optimiser le rendu $oViewModel = new ViewModel(); $oViewModel->setTemplate('backend/evenements-personnage/update'); return $oViewModel->setVariables(array('id' => $id, 'form' => $oForm)); } /** * Action pour la suppression. * * @return redirection vers la liste */ public function deleteAction() { $id = (int) $this->params()->fromRoute('id', 0); if (!$id) { return $this->redirect()->toRoute('backend-evenements-personnage-list'); } $oTable = $this->getTable(); $oEntite = $oTable->findRow($id); $oTable->delete($oEntite); $this->flashMessenger()->addMessage($this->_getServTranslator()->translate("La evenements-personnage a été supprimé avec succès."), 'success'); return $this->redirect()->toRoute('backend-evenements-personnage-list'); } /** * Retourne l'adapter associé a ce modèle. * * @return \Zend\Db\Adapter\Adapter */ public function getAdapter() { return $this->getServiceLocator()->get('\Zend\Db\Adapter\Adapter'); } /** * Retourne une response en tant que html. * * @return page html */ public function htmlResponse($html) { $response = $this->getResponse() ->setStatusCode(200) ->setContent($html); return $response; } }
true
79c6a5bb2a28f53432f7607ec92348c84b442533
PHP
Jalle19/vagrant-registry-generator
/src/Registry/Manifest/Version.php
UTF-8
814
2.875
3
[ "MIT" ]
permissive
<?php namespace Jalle19\VagrantRegistryGenerator\Registry\Manifest; /** * Class Version * @package Jalle19\VagrantRegistryGenerator\Registry\Manifest */ class Version { /** * @var string */ private $version; /** * @var Provider[] */ private $providers; /** * Version constructor. * * @param string $version * @param Provider[] $providers */ public function __construct($version, array $providers) { $this->version = $version; $this->providers = $providers; } /** * @return string */ public function getVersion() { return $this->version; } /** * @return Provider[] */ public function getProviders() { return $this->providers; } }
true
d2f860343c062ede6c5b551f434b5506334c7b9c
PHP
arasmussen/WebHost
/root/index.php
UTF-8
1,020
2.734375
3
[]
no_license
<?php $root = realpath($_SERVER['DOCUMENT_ROOT']); require_once("$root/../lib/template/PublicPage.php"); class Homepage extends PublicPage { public function getPageContent() { return '<div id="register">' . '<form method="post" action="javascript:void(0)">' . '<div id="registerUsername">' . '<label>Username</label>' . '<input type="text" name="username" />' . '</div>' . '<div id="registerEmail">' . '<label>Email</label>' . '<input type="text" name="email" />' . '</div>' . '<div id="registerPassword">' . '<label>Password</label>' . '<input type="password" name="password" />' . '</div>' . '<div id="registerButton">' . '<input type="submit" value="Register" />' . '</div>' . '</form>' . '</div>'; } public function getPageTitle() { return 'Web Hoster'; } } $page = new Homepage; $page->render(); ?>
true
f169de0532c7963218d2ddf69b75f42a9f259e9e
PHP
raphaborralho/learningvector
/blocks/lvs/biblioteca/view/.svn/text-base/AdapterView.php.svn-base
UTF-8
788
2.65625
3
[]
no_license
<?php namespace uab\ifce\lvs\view; /** * Adapter para exibição das páginas geradas pelos LVs em qualquer AVA * * @category LVs * @package uab\ifce\lvs\view * @author Ricky Persivo (rickypaz@gmail.com) * @version 1.0 */ interface AdapterView { /** * Adiciona um arquivo css * * @param string $arquivo caminho do arquivo .css * @access public */ function css($arquivo); /** * Renderiza a página gerada * * @access publib */ function exibirPagina(); /** * Recupera a foto armazenada pelo usuário, caso exista * * @param int $usuario * @access public */ function fotoUsuario($usuario); /** * Adiciona um arquivo javascript * * @param string $arquivo caminho do arquivo .js * @access public */ function js($arquivo); } ?>
true
5cf43d59b104c81b73d240fd2e4b4de54c8f9bfc
PHP
avengers5531/db_powon
/src/Dao/RelationshipDAO.php
UTF-8
1,859
2.953125
3
[]
no_license
<?php namespace Powon\Dao; use Powon\Entity\FriendRequest; use Powon\Entity\Member; interface RelationshipDAO{ /** * @param member_from Member: the requesting member * @param member_to Member: the requested member * @param rel_type string (single character): the relationship type ('F', 'I', 'E', 'C') */ public function requestRelationship(Member $member_from, Member $member_to, $rel_type); /** * @param member_from Member: the requesting member * @param member_to Member: the requested member */ public function confirmRelationship(Member $member_from, Member $member_to); /** * Get pending relationship requests for a specific member * @param mid int: member id of the requested party * @return array of members with the requested relationship type */ public function getPendingRelRequests(Member $member); /** * @param member1 Member, the id of the first member * @param member2 Member, the second member (order is irrelevant) * @return string relationship if exists, else null */ public function checkRelationship(Member $member1, Member $member2); /** * @param member1 member, the first member * @param member2 member, the second member (order of members is irrelevant) * @param rel_type string (single character): the relationship type ('F', 'I', 'E', 'C') */ public function updateRelationship(Member $member1, Member $member2, $rel_type); /** * @param member1 Member * @param member2 Member */ public function deleteRelationship(Member $member1, Member $member2); /** * @param member Member: the member to search for friends * @param rel_type String: either F, I, E, or C * @return list of FriendRequest objects */ public function getRelatedMembers(Member $member, $rel_type); }
true
fe965c6d84a70d8eb7bb5ae757eafd662277c43c
PHP
johncorrelli/planning-center-spotify
/app/Models/Spotify/SpotifyAuthorizationApi.php
UTF-8
689
2.828125
3
[]
no_license
<?php namespace App\Models\Spotify; use App\Models\Api; class SpotifyAuthorizationApi extends Api { /** * @param string $clientId your spotify app's client id * @param string $clientSecret your spotify app's client secret * @param ...$attrs */ public function __construct(string $clientId, string $clientSecret, ...$attrs) { parent::__construct(...$attrs); $this->setBaseUrl('https://accounts.spotify.com/api'); $this->setPostBodyFormat('application/x-www-form-urlencoded'); $authorization = base64_encode("{$clientId}:{$clientSecret}"); $this->setAuthorization("Authorization: Basic {$authorization}"); } }
true
8016582cb339c5738135b18fc79073cbc9f38ba0
PHP
lijianzwm/Mantra
/Application/Common/Service/MysqlService.class.php
UTF-8
11,579
2.625
3
[]
no_license
<?php /** * Created by PhpStorm. * User: lijian * Date: 2016/4/17 * Time: 11:42 */ namespace Common\Service; class MysqlService{ /** * 获取当日排行榜,如果没有,返回array(0) {} * @return mixed */ public static function getMysqlTodayRanklist(){ $todayDate = DateService::getStrDate(); return self::generateMysqlSomeDayRanklist($todayDate); } /** * 获取某天的排行榜,如果这个排行榜不存在,就生成一个,存到month_ranklist表中,如果排行榜为空,返回array(0) {} * @param $date * @return mixed */ public static function getMysqlSomedayRanklist($date){ $rankItem = M("day_ranklist")->where("date='$date'")->find(); if( $rankItem ){ return json_decode($rankItem['ranklist'], true); }else{ $ranklist = self::generateMysqlSomeDayRanklist($date); $rankItem['total'] = CountinService::getRanklistTotalNum($ranklist); $rankItem['ranklist'] = json_encode($ranklist); $rankItem['date'] = $date; M("day_ranklist")->add($rankItem); return $ranklist; } } /** * 获取总排行,如果没有,返回array(0) {} * @return mixed */ public static function getMysqlTotalRanklist(){ return M("user")->field("id as userid, showname as name, total as num")->where("total > 0")->order("total desc")->select(); } /** * 更新某日排行榜 * @param $date */ public static function refreshMysqlSomeDayRanklist($date){ M("day_ranklist")->where("date='$date'")->delete(); self::generateMysqlSomeDayRanklist($date); } /** * 生成某日排行榜,若生成的排行榜为空,返回array(0) {} * @param $date * @return mixed */ public static function generateMysqlSomeDayRanklist($date){ $userTable = C("DB_PREFIX")."user"; $dayCountTable = C("DB_PREFIX")."day_count"; $ranklist = M()->table("$userTable user, $dayCountTable count")-> where("user.id = count.userid and count.num > '0' and count.today_date='$date'")-> field('user.id as userid, user.showname as name, count.num as num')-> order('count.num desc' )->select(); return $ranklist; } /** * 获取当月排行榜 * @return mixed */ public static function getMysqlCurMonthRanklist(){ $yearMonth = DateService::getCurrentYearMonth(); $ranklist = self::generateMysqlMonthRanklist($yearMonth); return $ranklist; } /** * 获取某月排行榜 * @return mixed */ public static function getMysqlMonthRanklist($yearMonth){ $rankItem = M("month_ranklist")->where("yearmonth='$yearMonth'")->find(); if( $rankItem ){ return json_decode($rankItem['ranklist'],true); }else{ $ranklist = self::generateMysqlMonthRanklist($yearMonth); $rankItem['total'] = CountinService::getRanklistTotalNum($ranklist); $rankItem['yearmonth'] = $yearMonth; $rankItem['ranklist'] = json_encode($ranklist); M("month_ranklist")->add($rankItem); return $ranklist; } } /** * 生成月排行榜,传入“2016-04”格式的年月字符串,返回排行榜,若排行榜为空,则返回array(0) {} * @param $yearMonth * @return mixed */ public static function generateMysqlMonthRanklist($yearMonth){ $begDate = $yearMonth."-01"; $endDate = $yearMonth."-31"; DebugService::displayLog("generateMysqlMonthRanklist: begDate=$begDate, endDate=$endDate"); $userTable = C("DB_PREFIX")."user"; $dayCountTable = C("DB_PREFIX")."day_count"; $sql = "SELECT USER .id AS userid, USER .showname AS NAME, count.num AS num FROM $userTable USER, ( SELECT userid, sum(num) AS num FROM $dayCountTable WHERE today_date >= '$begDate' AND today_date <= '$endDate' GROUP BY userid ) count WHERE USER .id = count.userid AND count.num > '0' ORDER BY count.num DESC"; DebugService::displayLog($sql); return M()->query($sql); } public static function refreshMysqlMonthRanklist( $yearMonth ){ M("month_ranklist")->where("yearmonth=$yearMonth")->delete(); return self::generateMysqlMonthRanklist($yearMonth); } /** * 获取用户所有数目,如果用户不存在,返回null * @param $userid * @return null */ public static function getMysqlTotalNumById($userid){ $user = M("user")->where("id='$userid'")->find(); if( $user ){ return $user['total']; }else{ return null; } } /** * 获取mysql中用户当日数目,如果用户不存在或当日没有进行报数,返回null * @param $userid * @return null */ public static function getMysqlTodayNumById($userid){ $todayDate = DateService::getStrDate(); $count = M("day_count")->where("userid='$userid' and today_date='$todayDate'")->find(); DebugService::displayLog($count); if( $count ){ return $count['num']; }else{ return null; } } public static function addMysqlTodayNum( $userid, $num ){ $todayDate = DateService::getStrDate(); return self::addMysqlDayNum($userid, $num, $todayDate); } /** * @param $userid * @param $num * @param $date * @param null $currentTime * @return bool */ public static function addMysqlDayNum( $userid, $num, $date ){ $dao = M(); $table = C("DB_PREFIX")."day_count"; $currentTime = DateService::getCurrentTime(); if( $dao->execute("update $table set num=num+$num, update_time='$currentTime' where userid='$userid' AND today_date='$date'") ){ return true; }else{ return false; } } /** * 添加补报数目功能 * @param $userid * @param $num * @param $date * @return bool */ public static function addSupplementMysqlDayNum( $userid, $num, $date ){ $dao = M(); $table = C("DB_PREFIX")."day_count"; if( $dao->execute("update $table set num=num+$num where userid='$userid' AND today_date='$date'") ){ return true; }else{ return false; } } public static function isUserExist($userid){ if( M("user")->where("id=$userid")->find() ){ return true; }else{ return false; } } public static function initMysqlUserTodayNum($userid){ self::insertMysqlTodayNum($userid, 0); } public static function insertMysqlTodayNum( $userid, $num ){ $todayDate = DateService::getStrDate(); return self::insertMysqlDayNum($userid, $num, $todayDate ); } public static function insertSupplementMysqlDayNum( $userid, $num, $date ){ $insertDateTime = $date." 00:00:00"; return self::insertMysqlDayNum($userid,$num,$date,$insertDateTime); } public static function insertMysqlDayNum( $userid, $num, $date, $currentTime=null ){ $count['userid'] = $userid; $count['num'] = $num; $count['today_date'] = $date; if( $currentTime == null ){ $currentTime = DateService::getCurrentTime(); } $count['update_time'] = $currentTime; if( M("day_count")->add($count) ){ return true; }else{ return false; } } public static function addMysqlUserTotalNum($userid, $num ){ $dao = M(); $table = C("DB_PREFIX")."user"; if( $dao->execute("update $table set total=total+$num where id='$userid'") ){ return true; }else{ return false; } } public static function generateMysqlDayTotalNum($date){ $num = M("day_count")->field("sum(num) as num")->where("today_date='$date'")->select(); if( $num ){ DebugService::displayLog("generateMysqlDayTotalNum:num = $num[0]['num']"); return $num[0]['num']; }else{ DebugService::displayLog("generateMysqlDayTotalNum:num = not data"); return 0; } } public static function generateMysqlMonthTotalNum($yearMonth){ $begDate = $yearMonth."-01"; $endDate = $yearMonth."-31"; $num = M("day_count")->field("sum(num) as num")->where("today_date>='$begDate' and today_date <= '$endDate'")->select(); if( $num ){ return $num[0]['num']; }else{ DebugService::displayLog("generateMysqlMonthTotalNum : num = not data"); return 0; } } /** * 获取某一天(如果是今天的话,查询不到,返回-1)的共修总数,若数据库中没有,返回-1 * @param $date * @return int */ public static function getMysqlDayTotalNum($date){ $rankItem = M("day_ranklist")->where("date=$date")->find(); if( $rankItem ){ return $rankItem['total']; }else{ return -1; } } /** * 获取month_ranklist中存的总数,如果不存在,返回-1 * @param $date * @return int */ public static function getMysqlMonthTotalNum($yearMonth){ $rankItem = M("month_ranklist")->where("yearmonth='$yearMonth'")->find(); if( $rankItem ){ return $rankItem['total']; }else{ return -1; } } public static function generateMysqlTotalNum(){ $totalNum = 0; $result = M("month_ranklist")->field("sum(total) as num")->select(); if( $result ){ $totalNum += $result[0]['num']; } $curYearMonth = DateService::getCurrentYearMonth(); $totalNum += self::generateMysqlMonthTotalNum($curYearMonth); return $totalNum; } public static function generateStageGXCompletionNum($stageGX){ $totalNum = 0; $begDate = $stageGX['beg_date']; $endDate = $stageGX['end_date']; $result = M("day_count")->where("today_date >= '$begDate' and today_date <= '$endDate'")->field("sum(num) as num")->select(); if( $result ){ $totalNum = $result[0]['num']; if( $totalNum == null ){ $totalNum = 0; } } return $totalNum; } public static function getCurStageGXCompletionNum(){ $stageGX = StageGXService::getCurStageGX(); return $stageGX['completion_num']; } public static function refreshUserTableTotal($userid){ $result = M("day_count")->where("userid='$userid'")->field("sum(num) as total")->find(); if( $result ){ $total = $result['total']; }else{ $total = 0; } $user = M("user")->where("id='$userid'")->find(); $user['total'] = $total; M("user")->save($user); } }
true
db1ee42b7cbf0a52d10ea03d20bff0635aa1cd51
PHP
Falldanger/NetPeak
/rules/BlackListSymbolsInterface.php
UTF-8
188
2.625
3
[]
no_license
<?php namespace rules; interface BlackListSymbolsInterface { const BLACK_LIST = ['<', '</', '>', '=', '+', '[', ']', '{', '}', '^', '%', '$', '#', '^', '*', '(', ')', '\'', "\""]; }
true
b539441d83dccc17a9f48631179355888b742d41
PHP
fayzo/commerce
/RealEstate-master/php/test/login.php
UTF-8
1,098
2.546875
3
[ "MIT" ]
permissive
<?php $username = $_POST['username']; $password = $_POST['password']; if ($username == "" || $password == ""){ if ($username == "" && $password != ""){ echo "Escriba el nombre de usuario."; } else if ($username != "" && $password == "") { echo "Escriba la contraseña."; } else { echo "Escriba sus credenciales."; } } else { include ("../../Desktop/connect_server/connect_server.php"); $Query = "SELECT * FROM user_admin WHERE username='".$username."';"; $Result = $Conexion->query($Query); if ($Result->num_rows == 1){ $ObjR = $Result->fetch_array(MYSQLI_ASSOC); if (password_verify($password, $ObjR['password'])){ $QEmail = $Conexion->query("SELECT email FROM admin_info WHERE username='".$username."';")->fetch_array(MYSQLI_ASSOC); @session_start(); @$_SESSION['login'] = 1; @$_SESSION['username'] = $username; @$_SESSION['user_email'] = $QEmail['email']; echo "OK"; } else { echo "Contraseña incorrecta!."; } } else if ($Result->num_rows == 0) { echo "Usuario no encontrado, corrija sus credenciales."; } } ?>
true
3ad98da96a80401f94955b297ff697d98516119d
PHP
jasny/Q
/tests/DB/MySQL/SQLSplitterTest.php
UTF-8
78,742
2.734375
3
[]
no_license
<?php use Q\DB, Q\DB_SQLStatement, Q\DB_MySQL_SQLSplitter; set_include_path('../library' . PATH_SEPARATOR . get_include_path()); require_once 'PHPUnit/Framework/TestCase.php'; require_once 'Q/DB/MySQL/SQLSplitter.php'; require_once 'Q/DB/SQLStatement.php'; /** * Test for DB_MySQL_SQLSplitter and modifing DB_SQLStatement objects. */ class DB_MySQL_SQLSplitterTest extends PHPUnit_Framework_TestCase { /** * Query splitter * @var DB_MySQL_SQLSplitter */ public $qs; /** * Init test */ public function setUp() { $this->qs = new DB_MySQL_SQLSplitter(); } /** * End test */ public function tearDown() { $this->qs = null; } /** * Create a query statement objects * * @param string $statment * @return DB_SQLStatement */ public function statement($statement) { $s = new DB_SQLStatement($statement); $s->sqlSplitter = $this->qs; return $s; } /** * Helper function to remove spaces from a query. */ static function cleanQuery($sql) { return trim(preg_replace('/(?:\s+(\s|\)|\,)|(\()\s+)/', '\1\2', $sql)); } //-------- public function testQuote_Null() { $this->assertEquals('NULL', $this->qs->quote(null)); } public function testQuote_NullDefault() { $this->assertEquals('DEFAULT', $this->qs->quote(null, 'DEFAULT')); } public function testQuote_Int() { $this->assertEquals('1', $this->qs->quote(1)); } public function testQuote_Float() { $this->assertEquals('1.3', $this->qs->quote(1.3)); } public function testQuote_True() { $this->assertEquals('TRUE', $this->qs->quote(true)); } public function testQuote_False() { $this->assertEquals('FALSE', $this->qs->quote(false)); } public function testQuote_String() { $this->assertEquals('"test"', $this->qs->quote('test')); } public function testQuote_StringQuotes() { $this->assertEquals('"test \"abc\" test"', $this->qs->quote('test "abc" test')); } public function testQuote_StringMultiline() { $this->assertEquals('"line1\nline2\nline3"', $this->qs->quote("line1\nline2\nline3")); } public function testQuote_Array() { $this->assertEquals('1, TRUE, "abc", DEFAULT', $this->qs->quote(array(1, true, "abc", null), 'DEFAULT')); } public function testQuoteIdentifier_Simple() { $this->assertEquals('`test`', $this->qs->quoteIdentifier("test")); } public function testQuoteIdentifier_Quoted() { $this->assertEquals('`test`', $this->qs->quoteIdentifier("`test`")); } public function testQuoteIdentifier_TableColumn() { $this->assertEquals('`abc`.`test`', $this->qs->quoteIdentifier("abc.test")); } public function testQuoteIdentifier_TableColumn_Quoted() { $this->assertEquals('`abc`.`test`', $this->qs->quoteIdentifier("`abc`.`test`")); } public function testQuoteIdentifier_WithAlias() { $this->assertEquals('`abc`.`test` AS `def`', $this->qs->quoteIdentifier("abc.test AS def")); } public function testQuoteIdentifier_Function() { $this->assertEquals('count(`abc`.`test`) AS `count`', $this->qs->quoteIdentifier("count(abc.test) AS count")); } public function testQuoteIdentifier_Cast() { $this->assertEquals('`qqq`, cast(`abc`.`test` AS DATETIME)', $this->qs->quoteIdentifier("qqq, cast(`abc`.test AS DATETIME)")); } public function testQuoteIdentifier_Cast_Confuse() { $this->assertEquals('`qqq`, cast(myfn(`abc`.`test` as `myarg`) AS DATETIME) AS `date`', $this->qs->quoteIdentifier("qqq, cast(myfn(`abc`.test as myarg) AS DATETIME) AS date")); } public function testQuoteIdentifier_Expression() { $this->assertEquals('`abc`.`test` - `def`.`total`*10 AS `grandtotal`', $this->qs->quoteIdentifier("abc.test - def.total*10 AS grandtotal")); } public function testQuoteIdentifier_Strict() { $this->assertEquals('`abd-def*10`', $this->qs->quoteIdentifier("abd-def*10", DB::QUOTE_STRICT)); } public function testQuoteIdentifier_Strict_TableColumn() { $this->assertEquals('`abc`.`test-10`', $this->qs->quoteIdentifier("`abc`.test-10", DB::QUOTE_STRICT)); } public function testQuoteIdentifier_Strict_Fail() { $this->setExpectedException('Q\SecurityException', "Unable to quote '`abc`.`test`-10' safely"); $this->qs->quoteIdentifier("`abc`.`test`-10", DB::QUOTE_STRICT); } public function testValidIdentifier_Simple() { $this->assertTrue($this->qs->validIdentifier('test')); } public function testValidIdentifier_Quoted() { $this->assertTrue($this->qs->validIdentifier('`test`')); } public function testValidIdentifier_TableColumn() { $this->assertTrue($this->qs->validIdentifier('abc.test')); } public function testValidIdentifier_TableColumn_Quoted() { $this->assertTrue($this->qs->validIdentifier('`abc`.`test`')); } public function testValidIdentifier_Strange() { $this->assertFalse($this->qs->validIdentifier('ta-$38.934#34@dhy')); } public function testValidIdentifier_Strange_Quoted() { $this->assertTrue($this->qs->validIdentifier('`ta-$38.934#34@dhy`')); } public function testValidIdentifier_NoGroup_Simple() { $this->assertTrue($this->qs->validIdentifier('test', DB::FIELDNAME_COLUMN)); } public function testValidIdentifier_NoGroup_Quoted() { $this->assertTrue($this->qs->validIdentifier('`test`', DB::FIELDNAME_COLUMN)); } public function testValidIdentifier_NoGroup_TableColumn() { $this->assertFalse($this->qs->validIdentifier('abc.test', DB::FIELDNAME_COLUMN)); } public function testValidIdentifier_NoGroup_TableColumn_Quoted() { $this->assertFalse($this->qs->validIdentifier('`abc`.`test`', DB::FIELDNAME_COLUMN)); } public function testValidIdentifier_NoGroup_Strange() { $this->assertFalse($this->qs->validIdentifier('ta-$38.934#34@dhy', DB::FIELDNAME_COLUMN)); } public function testValidIdentifier_NoGroup_Strange_Quoted() { $this->assertTrue($this->qs->validIdentifier('`ta-$38.934#34@dhy`', DB::FIELDNAME_COLUMN)); } public function testValidIdentifier_WithGroup_Simple() { $this->assertFalse($this->qs->validIdentifier('test', DB::FIELDNAME_FULL)); } public function testValidIdentifier_WithGroup_Quoted() { $this->assertFalse($this->qs->validIdentifier('`test`', DB::FIELDNAME_FULL)); } public function testValidIdentifier_WithGroup_TableColumn() { $this->assertTrue($this->qs->validIdentifier('abc.test', DB::FIELDNAME_FULL)); } public function testValidIdentifier_WithGroup_TableColumn_Quoted() { $this->assertTrue($this->qs->validIdentifier('`abc`.`test`', DB::FIELDNAME_FULL)); } public function testValidIdentifier_WithGroup_Strange() { $this->assertFalse($this->qs->validIdentifier('ta-$38.934#34@dhy', DB::FIELDNAME_FULL)); } public function testValidIdentifier_WithGroup_Strange_Quoted() { $this->assertFalse($this->qs->validIdentifier('`ta-$38.934#34@dhy`', DB::FIELDNAME_FULL)); } public function testValidIdentifier_WithoutAlias_AsAlias() { $this->assertFalse($this->qs->validIdentifier('`test` AS def')); } public function testValidIdentifier_WithoutAlias_SpaceAlias() { $this->assertFalse($this->qs->validIdentifier('`test` def')); } public function testValidIdentifier_WithoutAlias_Full() { $this->assertFalse($this->qs->validIdentifier('`abc`.`test` AS def')); } public function testValidIdentifier_WithAlias_AsAlias() { $this->assertTrue($this->qs->validIdentifier('`test` AS def', DB::WITH_ALIAS)); } public function testValidIdentifier_WithAlias_SpaceAlias() { $this->assertTrue($this->qs->validIdentifier('`test` def', DB::WITH_ALIAS)); } public function testValidIdentifier_WithAlias_Full() { $this->assertTrue($this->qs->validIdentifier('`abc`.`test` AS def', DB::WITH_ALIAS)); } public function testValidIdentifier_WithGroupWithAlias_AsAlias() { $this->assertFalse($this->qs->validIdentifier('`test` AS def', DB::FIELDNAME_FULL | DB::WITH_ALIAS)); } public function testValidIdentifier_WithGroupWithAlias_Full() { $this->assertTrue($this->qs->validIdentifier('`abc`.`test` AS def', DB::FIELDNAME_FULL | DB::WITH_ALIAS)); } public function testSplitIdentifier_Column() { $this->assertEquals(array(null, 'test', null), $this->qs->splitIdentifier("test")); } public function testSplitIdentifier_Column_Quoted() { $this->assertEquals(array(null, 'test', null), $this->qs->splitIdentifier("`test`")); } public function testSplitIdentifier_TableColumn() { $this->assertEquals(array('abc', 'test', null), $this->qs->splitIdentifier("abc.test")); } public function testSplitIdentifier_TableColumn_Quoted() { $this->assertEquals(array('abc', 'test', null), $this->qs->splitIdentifier("`abc`.`test`")); } public function testSplitIdentifier_SchemaTableColumn() { $this->assertEquals(array('mydb.abc', 'test', null), $this->qs->splitIdentifier("mydb.abc.test")); } public function testSplitIdentifier_SchemaTableColumn_Quoted() { $this->assertEquals(array('mydb.abc', 'test', null), $this->qs->splitIdentifier("`mydb`.`abc`.`test`")); } public function testSplitIdentifier_QuotedDot() { $this->assertEquals(array(null, 'abc.test', null), $this->qs->splitIdentifier("`abc.test`")); } public function testSplitIdentifier_Column_AsAlias() { $this->assertEquals(array(null, 'test', 'def'), $this->qs->splitIdentifier("test AS def")); } public function testSplitIdentifier_Column_SpaceAlias() { $this->assertEquals(array(null, 'test', 'def'), $this->qs->splitIdentifier("test def")); } public function testSplitIdentifier_TableColumn_AsAlias() { $this->assertEquals(array('abc', 'test', 'def'), $this->qs->splitIdentifier("`abc`.`test` AS `def`")); } public function testSplitIdentifier_TableColumn_SpaceAlias() { $this->assertEquals(array('abc', 'test', 'def'), $this->qs->splitIdentifier("`abc`.`test` `def`")); } public function testMakeIdentifier_Column() { $this->assertEquals('`test`', $this->qs->makeIdentifier(null, 'test')); } public function testMakeIdentifier_TableColumn() { $this->assertEquals('`abc`.`test`', $this->qs->makeIdentifier('abc', 'test')); } public function testMakeIdentifier_TableColumnAlias() { $this->assertEquals('`abc`.`test` AS `def`', $this->qs->makeIdentifier('abc', 'test', 'def')); } public function testMakeIdentifier_SchemaTableColumn() { $this->assertEquals('`mydb`.`abc`.`test`', $this->qs->makeIdentifier('mydb.abc', 'test')); } public function testMakeIdentifier_NoQuote() { $this->assertEquals('abc.test AS def', $this->qs->makeIdentifier('abc', 'test', 'def', DB::QUOTE_NONE)); } public function testMakeIdentifier_Expression() { $this->assertEquals('`test`-`qqq` AS `grandtotal`', $this->qs->makeIdentifier('abc', "test-qqq", 'grandtotal')); } public function testMakeIdentifier_Expression_Strict() { $this->assertEquals('`abc`.`test-qqq` AS `grandtotal`', $this->qs->makeIdentifier('abc', "test-qqq", 'grandtotal', DB::QUOTE_STRICT)); } public function testMakeIdentifier_Expression_NoQuote() { $this->assertEquals('test-qqq AS grandtotal', $this->qs->makeIdentifier('abc', "test-qqq", 'grandtotal', DB::QUOTE_NONE)); } public function testMakeIdentifier_Quoted() { $this->assertEquals('`abc`.`test-qqq` AS `grandtotal`', $this->qs->makeIdentifier('abc', "`test-qqq`", 'grandtotal')); } public function testMakeIdentifier_Quoted_NoQuote() { $this->assertEquals('abc.`test-qqq` AS grandtotal', $this->qs->makeIdentifier('abc', "`test-qqq`", 'grandtotal', DB::QUOTE_NONE)); } //-------- public function testParse_Null() { $this->assertEquals('UPDATE phpunit_test SET description=NULL', $this->qs->parse('UPDATE phpunit_test SET description=?', array(null))); } public function testParse_Integer() { $this->assertEquals('SELECT * FROM phpunit_test WHERE status=10', $this->qs->parse("SELECT * FROM phpunit_test WHERE status=?", array(10))); } public function testParse_Float() { $this->assertEquals('SELECT * FROM phpunit_test WHERE status=33.7', $this->qs->parse("SELECT * FROM phpunit_test WHERE status=?", array(33.7))); } public function testParse_Boolean() { $this->assertEquals('SELECT * FROM phpunit_test WHERE status=TRUE AND disabled=FALSE', $this->qs->parse("SELECT * FROM phpunit_test WHERE status=? AND disabled=?", array(true, false))); } public function testParse_String() { $this->assertEquals('SELECT id, "test" AS `desc` FROM phpunit_test WHERE status="ACTIVE"', $this->qs->parse('SELECT id, ? AS `desc` FROM phpunit_test WHERE status=?', array('test', 'ACTIVE'))); } public function testParse_String_Confuse() { $this->assertEquals('SELECT id, "?" AS `desc ?`, \'?\' AS x FROM phpunit_test WHERE status="ACTIVE"', $this->qs->parse('SELECT id, "?" AS `desc ?`, \'?\' AS x FROM phpunit_test WHERE status=?', array('ACTIVE', 'not me', 'not me', 'not me'))); } public function testParse_String_Quote() { $this->assertEquals('SELECT * FROM phpunit_test WHERE description="This is a \\"test\\""', $this->qs->parse('SELECT * FROM phpunit_test WHERE description=?', array('This is a "test"'))); } public function testParse_String_Multiline() { $this->assertEquals('SELECT * FROM phpunit_test WHERE description="This is a \\"test\\"\\nWith another line"', $this->qs->parse('SELECT * FROM phpunit_test WHERE description=?', array('This is a "test"' . "\n" . 'With another line'))); } public function testParse_Array() { $this->assertEquals('SELECT * FROM phpunit_test WHERE description IN ("test", 10, FALSE, "another test")', $this->qs->parse('SELECT * FROM phpunit_test WHERE description IN (?)', array(array("test", 10, FALSE, "another test")))); } public function testParse_NoQuote() { $this->assertEquals('SELECT id, test AS `desc` FROM phpunit_test WHERE status="ACTIVE"', $this->qs->parse('SELECT id, ?! AS `desc` FROM phpunit_test WHERE status=?', array('test', 'ACTIVE'))); } public function testParse_AllNulls() { $this->assertEquals('SELECT id, (NULL) AS `desc` FROM phpunit_test WHERE status=(NULL)', $this->qs->parse('SELECT id, ?! AS `desc` FROM phpunit_test WHERE status=?', null)); } public function testParse_Named() { $this->assertEquals('SELECT id, "test" AS `desc` FROM phpunit_test WHERE status="ACTIVE"', $this->qs->parse('SELECT id, :desc AS `desc` FROM phpunit_test WHERE status=?', array('desc'=>'test', 'ACTIVE'))); } public function testParse_Named_NoQuote() { $this->assertEquals('SELECT id, test AS `desc` FROM phpunit_test WHERE status="ACTIVE"', $this->qs->parse('SELECT id, :!desc AS `desc` FROM phpunit_test WHERE status=?', array('desc'=>'test', 'ACTIVE'))); } public function testParse_Named_AllNulls() { $this->assertEquals('SELECT id, (NULL) AS `desc` FROM phpunit_test WHERE status=(NULL)', $this->qs->parse('SELECT id, :desc AS `desc` FROM phpunit_test WHERE status=?', null)); } public function testCountPlaceholders() { $this->assertEquals(2, $this->qs->countPlaceholders('SELECT id, ? AS `desc`, :named AS `named` FROM phpunit_test WHERE status=?')); } public function testCountPlaceholders_Confuse() { $this->assertEquals(1, $this->qs->countPlaceholders('SELECT id, "?" AS `desc ?`, \'?\' AS x FROM phpunit_test WHERE status=?')); } //-------- public function testGetQueryType_Select() { $this->assertEquals('SELECT', $this->qs->getQueryType("SELECT id, description FROM `test`")); } public function testGetQueryType_Select_Word() { $this->assertEquals('SELECT', $this->qs->getQueryType("SELECT")); } public function testGetQueryType_Select_LowerCase() { $this->assertEquals('SELECT', $this->qs->getQueryType("select id, description from `test`")); } public function testGetQueryType_Select_Spaces() { $this->assertEquals('SELECT', $this->qs->getQueryType("\n\t\n SELECT id, description FROM `test`")); } public function testGetQueryType_Insert() { $this->assertEquals('INSERT', $this->qs->getQueryType("INSERT INTO `test` SELECT 10")); } public function testGetQueryType_Replace() { $this->assertEquals('REPLACE', $this->qs->getQueryType("REPLACE INTO `test` VALUES (10, 'UPDATE')")); } public function testGetQueryType_Delete() { $this->assertEquals('DELETE', $this->qs->getQueryType("DELETE FROM `test` WHERE `select`=10")); } public function testGetQueryType_Truncate() { $this->assertEquals('TRUNCATE', $this->qs->getQueryType("TRUNCATE `test`")); } public function testGetQueryType_AlterTable() { $this->assertEquals('ALTER TABLE', $this->qs->getQueryType("ALTER TABLE `test`")); } public function testGetQueryType_AlterView_Spaces() { $this->assertEquals('ALTER VIEW', $this->qs->getQueryType("ALTER\n\t\tVIEW `test`")); } public function testGetQueryType_AlterUnknown() { $this->assertNull($this->qs->getQueryType("ALTER test set abc")); } public function testGetQueryType_Set() { $this->assertEquals('SET', $this->qs->getQueryType("SET @select=10")); } public function testGetQueryType_Begin() { $this->assertEquals('START TRANSACTION', $this->qs->getQueryType("BEGIN")); } public function testGetQueryType_LoadDataInfile() { $this->assertEquals('LOAD DATA INFILE', $this->qs->getQueryType("LOAD DATA INFILE")); } public function testGetQueryType_Comment() { $this->assertNull($this->qs->getQueryType("-- SELECT `test`")); } public function testGetQueryType_Unknown() { $this->assertNull($this->qs->getQueryType("something")); } public function testSplit_Select_Simple() { $parts = $this->qs->split("SELECT id, description FROM `test`"); $this->assertEquals(array(0=>'SELECT', 'columns'=>'id, description', 'from'=>'`test`', 'where'=>'', 'group by'=>'', 'having'=>'', 'order by'=>'', 'limit'=>'', 100=>''), array_map('trim', $parts)); } public function testSplit_Select_Advanced() { $parts = $this->qs->split("SELECT DISTINCTROW id, description, CONCAT(name, ' from ', city) AS `tman`, ` ORDER BY` as `order`, \"\" AS nothing FROM `test` INNER JOIN abc ON test.id = abc.id WHERE test.x = 'SELECT A FROM B WHERE C ORDER BY D GROUP BY E HAVING X PROCEDURE Y LOCK IN SHARE MODE' GROUP BY my_dd HAVING COUNT(1+3+xyz) < 100 LIMIT 15, 30 FOR UPDATE"); $this->assertEquals(array(0=>'SELECT DISTINCTROW', 'columns'=>"id, description, CONCAT(name, ' from ', city) AS `tman`, ` ORDER BY` as `order`, \"\" AS nothing", 'from'=>"`test` INNER JOIN abc ON test.id = abc.id", 'where'=>"test.x = 'SELECT A FROM B WHERE C ORDER BY D GROUP BY E HAVING X PROCEDURE Y LOCK IN SHARE MODE'", 'group by'=>"my_dd", 'having'=>"COUNT(1+3+xyz) < 100", 'order by'=>'', 'limit'=>"15, 30", 100=>"FOR UPDATE"), array_map('trim', $parts)); } public function testSplit_Select_Subquery() { $parts = $this->qs->split("SELECT id, description, VALUES(SELECT id, desc FROM subt WHERE status='1' CASCADE ON PARENT id = relatie_id) AS subs FROM `test` INNER JOIN (SELECT * FROM abc WHERE i = 1 GROUP BY x) AS abc WHERE abc.x IN (1,2,3,6,7) AND qq!='(SELECT)' ORDER BY abx.dd"); $this->assertEquals(array(0=>'SELECT', 'columns'=>"id, description, VALUES(SELECT id, desc FROM subt WHERE status='1' CASCADE ON PARENT id = relatie_id) AS subs", 'from'=>"`test` INNER JOIN (SELECT * FROM abc WHERE i = 1 GROUP BY x) AS abc", 'where'=>"abc.x IN (1,2,3,6,7) AND qq!='(SELECT)'", 'group by'=>'', 'having'=>'', 'order by'=>'abx.dd', 'limit'=>'', 100=>''), array_map('trim', $parts)); } public function testSplit_Select_SubqueryMadness() { $parts = $this->qs->split("SELECT id, description, VALUES(SELECT id, desc FROM subt1 INNER JOIN (SELECT id, p_id, desc FROM subt2 INNER JOIN (SELECT id, p_id, myfunct(a, b, c) FROM subt3 WHERE x = 10) AS subt3 ON subt2.id = subt3.p_id) AS subt2 ON subt1.id = subt2.p_id WHERE status='1' CASCADE ON PARENT id = relatie_id) AS subs FROM `test` INNER JOIN (SELECT * FROM abc INNER JOIN (SELECT id, p_id, desc FROM subt2 INNER JOIN (SELECT id, p_id, myfunct(a, b, c) FROM subt3 WHERE x = 10) AS subt3 ON subt2.id = subt3.p_id) AS subt2 ON abc.id = subt2.p_id WHERE i = 1 GROUP BY x) AS abc WHERE abc.x IN (1,2,3,6,7) AND qq!='(SELECT)' AND x_id IN (SELECT id FROM x) ORDER BY abx.dd LIMIT 10"); $this->assertEquals(array(0=>'SELECT', 'columns'=>"id, description, VALUES(SELECT id, desc FROM subt1 INNER JOIN (SELECT id, p_id, desc FROM subt2 INNER JOIN (SELECT id, p_id, myfunct(a, b, c) FROM subt3 WHERE x = 10) AS subt3 ON subt2.id = subt3.p_id) AS subt2 ON subt1.id = subt2.p_id WHERE status='1' CASCADE ON PARENT id = relatie_id) AS subs", 'from'=>"`test` INNER JOIN (SELECT * FROM abc INNER JOIN (SELECT id, p_id, desc FROM subt2 INNER JOIN (SELECT id, p_id, myfunct(a, b, c) FROM subt3 WHERE x = 10) AS subt3 ON subt2.id = subt3.p_id) AS subt2 ON abc.id = subt2.p_id WHERE i = 1 GROUP BY x) AS abc", 'where'=>"abc.x IN (1,2,3,6,7) AND qq!='(SELECT)' AND x_id IN (SELECT id FROM x)", 'group by'=>'', 'having'=>'', 'order by'=>'abx.dd', 'limit'=>'10', 100=>''), array_map('trim', $parts)); } public function testSplit_Select_Semicolon() { $parts = $this->qs->split("SELECT id, description FROM `test`; Please ignore this"); $this->assertEquals(array(0=>'SELECT', 'columns'=>'id, description', 'from'=>'`test`', 'where'=>'', 'group by'=>'', 'having'=>'', 'order by'=>'', 'limit'=>'', 100=>''), array_map('trim', $parts)); } public function testJoinSelect_Simple() { $sql = $this->qs->join(array(0=>'SELECT', 'columns'=>'id, description', 'from'=>'`test`', 'where'=>'', 'group by'=>'', 'having'=>'', 'order by'=>'', 'limit'=>'', 100=>'')); $this->assertEquals("SELECT id, description FROM `test`", $sql); } public function testJoinSelect_Advanced() { $sql = $this->qs->join(array(0=>'SELECT DISTINCTROW', 'columns'=>"id, description, CONCAT(name, ' from ', city) AS `tman`, ` ORDER BY` as `order`, \"\" AS nothing", 'from'=>"`test` INNER JOIN abc ON test.id = abc.id", 'where'=>"test.x = 'SELECT A FROM B WHERE C ORDER BY D GROUP BY E HAVING X PROCEDURE Y LOCK IN SHARE MODE'", 'group by'=>"my_dd", 'having'=>"COUNT(1+3+xyz) < 100", 'order by'=>'', 'limit'=>"15, 30", 100=>"FOR UPDATE")); $this->assertEquals("SELECT DISTINCTROW id, description, CONCAT(name, ' from ', city) AS `tman`, ` ORDER BY` as `order`, \"\" AS nothing FROM `test` INNER JOIN abc ON test.id = abc.id WHERE test.x = 'SELECT A FROM B WHERE C ORDER BY D GROUP BY E HAVING X PROCEDURE Y LOCK IN SHARE MODE' GROUP BY my_dd HAVING COUNT(1+3+xyz) < 100 LIMIT 15, 30 FOR UPDATE", $sql); } public function testJoinSelect_Subquery() { $sql = $this->qs->join(array(0=>'SELECT', 'columns'=>"id, description", 'from'=>"`test` INNER JOIN (SELECT * FROM abc WHERE i = 1 GROUP BY x) AS abc", 'where'=>"abc.x IN (1,2,3,6,7) AND qq!='(SELECT)'", 'group by'=>'', 'having'=>'', 'order by'=>'abx.dd', 'limit'=>'', 100=>'')); $this->assertEquals("SELECT id, description FROM `test` INNER JOIN (SELECT * FROM abc WHERE i = 1 GROUP BY x) AS abc WHERE abc.x IN (1,2,3,6,7) AND qq!='(SELECT)' ORDER BY abx.dd", $sql); } //-------- public function testSplit_InsertValuesSimple() { $parts = $this->qs->split("INSERT INTO `test` VALUES (NULL, 'abc')"); $this->assertEquals(array(0=>'INSERT', 'into'=>'`test`', 'columns'=>'', 'values'=>"(NULL, 'abc')", 'on duplicate key update'=>''), array_map('trim', $parts)); } public function testSplit_ReplaceValuesSimple() { $parts = $this->qs->split("REPLACE INTO `test` VALUES (NULL, 'abc')"); $this->assertEquals(array(0=>'REPLACE', 'into'=>'`test`', 'columns'=>'', 'values'=>"(NULL, 'abc')", 'on duplicate key update'=>''), array_map('trim', $parts)); } public function testSplit_InsertValuesColumns() { $parts = $this->qs->split("INSERT INTO `test` (`id`, description, `values`) VALUES (NULL, 'abc', 10)"); $this->assertEquals(array(0=>'INSERT', 'into'=>'`test`', 'columns'=>"(`id`, description, `values`)", 'values'=>"(NULL, 'abc', 10)", 'on duplicate key update'=>''), array_map('trim', $parts)); } public function testSplit_InsertValuesMultiple() { $parts = $this->qs->split("INSERT INTO `test` (`id`, description, `values`) VALUES (NULL, 'abc', 10), (NULL, 'bb', 20), (NULL, 'cde', 30)"); $this->assertEquals(array(0=>'INSERT', 'into'=>'`test`', 'columns'=>"(`id`, description, `values`)", 'values'=>"(NULL, 'abc', 10), (NULL, 'bb', 20), (NULL, 'cde', 30)", 'on duplicate key update'=>''), array_map('trim', $parts)); } public function testSplit_InsertSetSimple() { $parts = $this->qs->split("INSERT INTO `test` SET `id`=NULL, description = 'abc'"); $this->assertEquals(array(0=>'INSERT', 'into'=>'`test`', 'set'=>"`id`=NULL, description = 'abc'", 'on duplicate key update'=>''), array_map('trim', $parts)); } public function testSplit_InsertSelectSimple() { $parts = $this->qs->split("INSERT INTO `test` SELECT NULL, name FROM xyz"); $this->assertEquals(array(0=>'INSERT', 'into'=>'`test`', 'columns'=>'', 'query'=>"SELECT NULL, name FROM xyz", 'on duplicate key update'=>''), array_map('trim', $parts)); } public function testSplit_InsertSelectSubquery() { $parts = $this->qs->split("INSERT INTO `test` SELECT NULL, name FROM xyz WHERE type IN (SELECT type FROM tt GROUP BY type HAVING SUM(qn) > 10)"); $this->assertEquals(array(0=>'INSERT', 'into'=>'`test`', 'columns'=>'', 'query'=>"SELECT NULL, name FROM xyz WHERE type IN (SELECT type FROM tt GROUP BY type HAVING SUM(qn) > 10)", 'on duplicate key update'=>''), array_map('trim', $parts)); } public function testJoinInsertValuesSimple() { $sql = $this->qs->join(array(0=>'INSERT', 'into'=>'`test`', 'columns'=>'', 'values'=>"(NULL, 'abc')", 'on duplicate key update'=>'')); $this->assertEquals("INSERT INTO `test` VALUES (NULL, 'abc')", $sql); } public function testJoinReplaceValuesSimple() { $sql = $this->qs->join(array(0=>'REPLACE', 'into'=>'`test`', 'columns'=>'', 'values'=>"(NULL, 'abc')", 'on duplicate key update'=>'')); $this->assertEquals("REPLACE INTO `test` VALUES (NULL, 'abc')", $sql); } public function testJoinInsertValuesColumns() { $sql = $this->qs->join(array(0=>'INSERT', 'into'=>'`test`', 'columns'=>"(`id`, description, `values`)", 'values'=>"(NULL, 'abc', 10)", 'on duplicate key update'=>'')); $this->assertEquals("INSERT INTO `test` (`id`, description, `values`) VALUES (NULL, 'abc', 10)", $sql); } public function testJoinInsertValuesMultiple() { $sql = $this->qs->join(array(0=>'INSERT', 'into'=>'`test`', 'columns'=>"(`id`, description, `values`)", 'values'=>"(NULL, 'abc', 10), (NULL, 'bb', 20), (NULL, 'cde', 30)", 'on duplicate key update'=>'')); $this->assertEquals("INSERT INTO `test` (`id`, description, `values`) VALUES (NULL, 'abc', 10), (NULL, 'bb', 20), (NULL, 'cde', 30)", $sql); } public function testJoinInsertSelectSimple() { $sql = $this->qs->join(array(0=>'INSERT', 'into'=>'`test`', 'columns'=>'', 'query'=>"SELECT NULL, name FROM xyz", 'on duplicate key update'=>'')); $this->assertEquals("INSERT INTO `test` SELECT NULL, name FROM xyz", $sql); } public function testJoinInsertSelectSubquery() { $sql = $this->qs->join(array(0=>'INSERT', 'into'=>'`test`', 'columns'=>'', 'query'=>"SELECT NULL, name FROM xyz WHERE type IN (SELECT type FROM tt GROUP BY type HAVING SUM(qn) > 10)", 'on duplicate key update'=>'')); $this->assertEquals("INSERT INTO `test` SELECT NULL, name FROM xyz WHERE type IN (SELECT type FROM tt GROUP BY type HAVING SUM(qn) > 10)", $sql); } //-------- public function testSplit_UpdateSimple() { $parts = $this->qs->split("UPDATE `test` SET status='ACTIVE' WHERE id=10"); $this->assertEquals(array(0=>'UPDATE', 'tables'=>'`test`', 'set'=>"status='ACTIVE'", 'where'=>'id=10', 'limit'=>''), array_map('trim', $parts)); } public function testSplit_UpdateAdvanced() { $parts = $this->qs->split("UPDATE `test` LEFT JOIN atst ON `test`.id = atst.idTest SET fld1=DEFAULT, afld = CONCAT(a, f, ' (SELECT TRANSPORT)'), status='ACTIVE' WHERE id = 10 LIMIT 20 OFFSET 10"); $this->assertEquals(array(0=>'UPDATE', 'tables'=>'`test` LEFT JOIN atst ON `test`.id = atst.idTest', 'set'=>"fld1=DEFAULT, afld = CONCAT(a, f, ' (SELECT TRANSPORT)'), status='ACTIVE'", 'where'=>'id = 10', 'limit'=>'20 OFFSET 10'), array_map('trim', $parts)); } public function testSplit_UpdateSubquery() { $parts = $this->qs->split("UPDATE `test` LEFT JOIN (SELECT idTest, a, f, count(*) AS cnt FROM atst) AS atst ON `test`.id = atst.idTest SET fld1=DEFAULT, afld = CONCAT(a, f, ' (SELECT TRANSPORT)'), status='ACTIVE' WHERE id IN (SELECT id FROM whatever LIMIT 100)"); $this->assertEquals(array(0=>'UPDATE', 'tables'=>'`test` LEFT JOIN (SELECT idTest, a, f, count(*) AS cnt FROM atst) AS atst ON `test`.id = atst.idTest', 'set'=>"fld1=DEFAULT, afld = CONCAT(a, f, ' (SELECT TRANSPORT)'), status='ACTIVE'", 'where'=>'id IN (SELECT id FROM whatever LIMIT 100)', 'limit'=>''), array_map('trim', $parts)); } public function testJoin_UpdateSimple() { $sql = $this->qs->join(array(0=>'UPDATE', 'tables'=>'`test`', 'set'=>"status='ACTIVE'", 'where'=>'id=10', 'limit'=>'')); $this->assertEquals("UPDATE `test` SET status='ACTIVE' WHERE id=10", $sql); } public function testJoin_UpdateAdvanced() { $sql = $this->qs->join(array(0=>'UPDATE', 'tables'=>'`test` LEFT JOIN atst ON `test`.id = atst.idTest', 'set'=>"fld1=DEFAULT, afld = CONCAT(a, f, ' (SELECT TRANSPORT)'), status='ACTIVE'", 'where'=>'id = 10', 'limit'=>'20 OFFSET 10')); $this->assertEquals("UPDATE `test` LEFT JOIN atst ON `test`.id = atst.idTest SET fld1=DEFAULT, afld = CONCAT(a, f, ' (SELECT TRANSPORT)'), status='ACTIVE' WHERE id = 10 LIMIT 20 OFFSET 10", $sql); } //-------- public function testSplit_DeleteSimple() { $parts = $this->qs->split("DELETE FROM `test` WHERE id=10"); $this->assertEquals(array(0=>'DELETE', 'columns'=>'', 'from'=>'`test`', 'where'=>'id=10', 'order by'=>'', 'limit'=>''), array_map('trim', $parts)); } public function testSplit_DeleteAdvanced() { $parts = $this->qs->split("DELETE `test`.* FROM `test` INNER JOIN `dude where is my car`.`import` AS dude_import ON `test`.ref = dude_import.ref WHERE dude_import.sql NOT LIKE '% on duplicate key update' AND status = 10 ORDER BY xyz LIMIT 1"); $this->assertEquals(array(0=>'DELETE', 'columns'=>'`test`.*', 'from'=>'`test` INNER JOIN `dude where is my car`.`import` AS dude_import ON `test`.ref = dude_import.ref', 'where'=>"dude_import.sql NOT LIKE '% on duplicate key update' AND status = 10", 'order by'=>'xyz', 'limit'=>'1'), array_map('trim', $parts)); } public function testSplit_DeleteSubquery() { $parts = $this->qs->split("DELETE `test`.* FROM `test` INNER JOIN (SELECT * FROM dude_import GROUP BY x_id WHERE status = 'OK' HAVING COUNT(*) > 1) AS dude_import ON `test`.ref = dude_import.ref WHERE status = 10"); $this->assertEquals(array(0=>'DELETE', 'columns'=>'`test`.*', 'from'=>"`test` INNER JOIN (SELECT * FROM dude_import GROUP BY x_id WHERE status = 'OK' HAVING COUNT(*) > 1) AS dude_import ON `test`.ref = dude_import.ref", 'where'=>"status = 10", 'order by'=>'', 'limit'=>''), array_map('trim', $parts)); } public function testJoin_DeleteSimple() { $sql = $this->qs->join(array(0=>'DELETE', 'columns'=>'', 'from'=>'`test`', 'where'=>'id=10', 'order by'=>'', 'limit'=>'')); $this->assertEquals("DELETE FROM `test` WHERE id=10", $sql); } public function testJoin_DeleteAdvanced() { $sql = $this->qs->join(array(0=>'DELETE', 'columns'=>'`test`.*', 'from'=>'`test` INNER JOIN `dude where is my car`.`import` AS dude_import ON `test`.ref = dude_import.ref', 'where'=>"dude_import.sql NOT LIKE '% on duplicate key update' AND status = 10", 'order by'=>'xyz', 'limit'=>'1')); $this->assertEquals("DELETE `test`.* FROM `test` INNER JOIN `dude where is my car`.`import` AS dude_import ON `test`.ref = dude_import.ref WHERE dude_import.sql NOT LIKE '% on duplicate key update' AND status = 10 ORDER BY xyz LIMIT 1", $sql); } //-------- public function testSplit_Set() { $parts = $this->qs->split("SET abc=10, @def='test'"); $this->assertEquals(array('set'=>"abc=10, @def='test'"), array_map('trim', $parts)); } public function testJoin_Set() { $sql = $this->qs->join(array('set'=>"abc=10, @def='test'")); $this->assertEquals("SET abc=10, @def='test'", $sql); } //-------- public function testSplitColumns_Simple() { $columns = $this->qs->splitColumns("abc, xyz, test"); $this->assertEquals(array("abc", "xyz", "test"), array_map('trim', $columns)); } public function testSplitColumns_Advanced() { $columns = $this->qs->splitColumns("abc, CONCAT('abc', 'der', 10+22, IFNULL(`qq`, 'Q')), test, 10+3 AS `bb`, 'Ho, Hi' AS HoHi, 22"); $this->assertEquals(array("abc", "CONCAT('abc', 'der', 10+22, IFNULL(`qq`, 'Q'))", "test", "10+3 AS `bb`", "'Ho, Hi' AS HoHi", "22"), array_map('trim', $columns)); } public function testSplitColumns_SplitFieldname() { $columns = $this->qs->splitColumns("abc AS qqq, xyz, CONCAT('abc', 'der', 10+22, MYFUNC(x AS y, bla)) AS tst, mytable.`field1`, mytable.`field2` AS ad, `mytable`.field3 + 10", DB::SPLIT_IDENTIFIER); $this->assertEquals(array(array("", "abc", "qqq"), array("", "xyz", ""), array("", "CONCAT('abc', 'der', 10+22, MYFUNC(x AS y, bla))", "tst"), array("mytable", "field1", ""), array("mytable", "field2", "ad"), array("", "`mytable`.field3 + 10", "")), $columns); } public function testSplitColumns_Assoc() { $columns = $this->qs->splitColumns("abc AS qqq, xyz, CONCAT('abc', 'der', 10+22, MYFUNC(x AS y, bla)) AS tst, mytable.`field1`, adb.mytable.`field2` AS ad, `mytable`.field3 + 10", DB::SPLIT_ASSOC); $this->assertEquals(array("qqq"=>"abc", "xyz"=>"xyz", "tst"=>"CONCAT('abc', 'der', 10+22, MYFUNC(x AS y, bla))", 'field1'=>"mytable.`field1`", 'ad'=>"adb.mytable.`field2`", '`mytable`.field3 + 10'=>"`mytable`.field3 + 10"), array_map('trim', $columns)); } public function testSplitColumns_SplitFieldnameAssoc() { $columns = $this->qs->splitColumns("abc AS qqq, xyz, CONCAT('abc', 'der', 10+22, MYFUNC(x AS y, bla)) AS tst, mytable.`field1`, mytable.`field2` AS ad, `mytable`.field3 + 10", DB::SPLIT_IDENTIFIER | DB::SPLIT_ASSOC); $this->assertEquals(array("qqq"=>array("", "abc", "qqq"), "xyz"=>array("", "xyz", ""), "tst"=>array("", "CONCAT('abc', 'der', 10+22, MYFUNC(x AS y, bla))", "tst"), 'field1'=>array("mytable", "field1", ""), 'ad'=>array("mytable", "field2", "ad"), '`mytable`.field3 + 10'=>array("", "`mytable`.field3 + 10", "")), $columns); } public function testSplitColumns_Set() { $columns = $this->qs->splitColumns("SET @abc=18, def=CONCAT('test', '123', DATE_FORMAT(NOW(), '%d-%m-%Y %H:%M')), @uid=NULL"); $this->assertEquals(array("@abc=18", "def=CONCAT('test', '123', DATE_FORMAT(NOW(), '%d-%m-%Y %H:%M'))", "@uid=NULL"), array_map('trim', $columns)); } public function testSplitColumns_Set_Assoc() { $columns = $this->qs->splitColumns("SET @abc=18, def=CONCAT('test', '123', DATE_FORMAT(NOW(), '%d-%m-%Y %H:%M')), @uid=NULL", DB::SPLIT_ASSOC); $this->assertEquals(array("@abc"=>"18", "def"=>"CONCAT('test', '123', DATE_FORMAT(NOW(), '%d-%m-%Y %H:%M'))", "@uid"=>"NULL"), array_map('trim', $columns)); } public function testSplitColumns_Select() { $columns = $this->qs->splitColumns("SELECT abc, CONCAT('abc', 'der', 10+22, IFNULL(`qq`, 'Q')), test, 10+3 AS `bb`, 'Ho, Hi' AS HoHi, 22 FROM test INNER JOIN contact WHERE a='X FROM Y'"); $this->assertEquals(array("abc", "CONCAT('abc', 'der', 10+22, IFNULL(`qq`, 'Q'))", "test", "10+3 AS `bb`", "'Ho, Hi' AS HoHi", "22"), array_map('trim', $columns)); } public function testSplitColumns_SelectSubquery() { $columns = $this->qs->splitColumns("SELECT abc, CONCAT('abc', 'der', 10+22, IFNULL(`qq`, 'Q')), x IN (SELECT id FROM xy) AS subq FROM test"); $this->assertEquals(array("abc", "CONCAT('abc', 'der', 10+22, IFNULL(`qq`, 'Q'))", "x IN (SELECT id FROM xy) AS subq"), array_map('trim', $columns)); } public function testSplitColumns_SelectSubFrom() { $columns = $this->qs->splitColumns("SELECT abc, CONCAT('abc', 'der', 10+22, IFNULL(`qq`, 'Q')) FROM test INNER JOIN (SELECT id, desc FROM xy) AS subq ON test.id = subq.id"); $this->assertEquals(array("abc", "CONCAT('abc', 'der', 10+22, IFNULL(`qq`, 'Q'))"), array_map('trim', $columns)); } public function testSplitColumns_SelectRealLifeExample() { $columns = $this->qs->splitColumns("SELECT relation.id, IF( name = '', CONVERT( concat_name(last_name, suffix, first_name, '')USING latin1 ) , name ) AS fullname FROM relation LEFT JOIN relation_person_type ON relation.id = relation_person_type.relation_id LEFT JOIN person_type ON person_type.id = relation_person_type.person_type_id WHERE person_type_id =5 ORDER BY fullname"); $this->assertEquals(array("relation.id", "IF( name = '', CONVERT( concat_name(last_name, suffix, first_name, '')USING latin1 ) , name ) AS fullname"), array_map('trim', $columns)); } public function testSplitColumns_InsertValues() { $columns = $this->qs->splitColumns("INSERT INTO `test` (`id`, description, `values`) VALUES (NULL, 'abc', 10)"); $this->assertEquals(array('`id`', 'description', '`values`'), array_map('trim', $columns)); } public function testSplitColumns_InsertSelect() { $columns = $this->qs->splitColumns("INSERT INTO `test` (`id`, description, `values`) SELECT product_id, title, 22 AS values FROM `abc`"); $this->assertEquals(array('`id`', 'description', '`values`'), array_map('trim', $columns)); } public function testSplitColumns_InsertSet() { $columns = $this->qs->splitColumns("INSERT INTO `test` SET id=1, description='test', `values`=22", DB::SPLIT_ASSOC); $this->assertEquals(array('id'=>'1', "description"=>"'test'", 'values'=>'22'), array_map('trim', $columns)); } public function testSplitColumns_Update() { $columns = $this->qs->splitColumns("UPDATE `test` INNER JOIN `xyz` ON test.id=xyz.test_id SET description='test', `values`=22 WHERE test.id=1", DB::SPLIT_ASSOC); $this->assertEquals(array("description"=>"'test'", 'values'=>'22'), array_map('trim', $columns)); } public function testSplitColumns_Delete() { $columns = $this->qs->splitColumns("DELETE test.* FROM `test` INNER JOIN `xyz` ON test.id=xyz.test_id"); $this->assertEquals(array("test.*"), array_map('trim', $columns)); } // ------- public function testSplitTables_Simple() { $tables = $this->qs->splitTables("abc, xyz, test"); $this->assertEquals(array("abc", "xyz", "test"), array_map('trim', $tables)); } public function testSplitTables_DBAlias() { $tables = $this->qs->splitTables("abc `a`, `xyz`, mysql.test AS tt"); $this->assertEquals(array("abc `a`", "`xyz`", "mysql.test AS tt"), array_map('trim', $tables)); } public function testSplitTables_DBAlias_splitTablename() { $tables = $this->qs->splitTables("abc `a`, `xyz`, mysql.test AS tt", DB::SPLIT_IDENTIFIER); $this->assertEquals(array(array(null, "abc", "a"), array(null, "xyz", null), array("mysql", "test", "tt")), $tables); } public function testSplitTables_Join() { $tables = $this->qs->splitTables("abc `a` INNER JOIN ufd.zzz AS `xyz` ON abc.id = xyz.abc_id LEFT JOIN def ON abc.x IN (SELECT abc FROM `xyz_link`) AND abc.y = MYFUNCT(10, 12, xyz.abc_id) STRAIGHT_JOIN tuf, qwerty"); $this->assertEquals(array("abc `a`", "ufd.zzz AS `xyz`", "def", "tuf", "qwerty"), array_map('trim', $tables)); } public function testSplitTables_Subjoin() { $tables = $this->qs->splitTables("abc `a` INNER JOIN (ufd.zzz AS `xyz` LEFT JOIN def ON abc.x IN (SELECT abc FROM `xyz_link`) AND abc.y = def.id, qwerty) ON abc.id = MYFUNCT(10, 12, xyz.abc_id) STRAIGHT_JOIN tuf"); $this->assertEquals(array("abc `a`", "ufd.zzz AS `xyz`", "def", "qwerty", "tuf"), array_map('trim', $tables)); } public function testSplitTables_Subquery() { $tables = $this->qs->splitTables("abc `a` INNER JOIN (SELECT * FROM ufd.zzz AS `xyz` LEFT JOIN def ON abc.y = def.id, qwerty) AS xyz ON abc.id = MYFUNCT(10, 12, xyz.abc_id) STRAIGHT_JOIN tuf"); $this->assertEquals(array("abc `a`", "(SELECT * FROM ufd.zzz AS `xyz` LEFT JOIN def ON abc.y = def.id, qwerty) AS xyz", "tuf"), array_map('trim', $tables)); } public function testSplitTables_Select() { $tables = $this->qs->splitTables("SELECT aaa, zzz FROM abc `a` INNER JOIN ufd.zzz AS `xyz` ON abc.id = xyz.abc_id LEFT JOIN def ON abc.x IN (SELECT abc FROM `xyz_link`) AND abc.y = MYFUNCT(10, 12, xyz.abc_id) STRAIGHT_JOIN tuf, qwerty WHERE a='X FROM Y'"); $this->assertEquals(array("abc `a`", "ufd.zzz AS `xyz`", "def", "tuf", "qwerty"), array_map('trim', $tables)); } public function testSplitTables_InsertValues() { $tables = $this->qs->splitTables("INSERT INTO `test` (`id`, description, `values`) VALUES (NULL, 'abc', 10)"); $this->assertEquals(array('`test`'), array_map('trim', $tables)); } public function testSplitTables_InsertSelect() { $tables = $this->qs->splitTables("INSERT INTO `test` (`id`, description, `values`) SELECT product_id, title, 22 AS values FROM `abc`"); $this->assertEquals(array('`test`'), array_map('trim', $tables)); } public function testSplitTables_InsertSet() { $tables = $this->qs->splitTables("INSERT INTO `test` SET id=1, description='test', `values`=22"); $this->assertEquals(array('`test`'), array_map('trim', $tables)); } public function testSplitTables_Update() { $tables = $this->qs->splitTables("UPDATE `test` INNER JOIN `xyz` ON test.id=xyz.test_id SET description='test', `values`=22 WHERE test.id=1"); $this->assertEquals(array('`test`', '`xyz`'), array_map('trim', $tables)); } public function testSplitTables_Delete() { $tables = $this->qs->splitTables("DELETE test.* FROM `test` INNER JOIN `xyz` ON test.id=xyz.test_id"); $this->assertEquals(array("`test`", '`xyz`'), array_map('trim', $tables)); } // ------- public function testSplitCriteria_Simple() { $criteria = $this->qs->splitCriteria("abc=22 AND def > xyz OR test IS NOT TRUE"); $this->assertEquals(array(array('abc', '=', '22'), array('def', '>', 'xyz'), array('test', 'IS NOT', 'TRUE')), $criteria); } public function testSplitCriteria_Advanced() { $criteria = $this->qs->splitCriteria("abc='test or 22' AND func(abc) < 77 AND (def > dor XOR test IS NOT TRUE) AND (`date` between '2009-01-01' AND NOW() + INTERVAL 1 MONTH OR `date` IS NULL OR (`and` IN ('qq', 'or')))"); $this->assertEquals(array(array('abc', '=', "'test or 22'"), array('func(abc)', '<', '77'), array('def', '>', 'dor'), array('test', 'IS NOT', 'TRUE'), array('`date`', 'BETWEEN', "'2009-01-01' AND NOW() + INTERVAL 1 MONTH"), array('`date`', 'IS NULL', ''), array('`and`', 'IN', "('qq', 'or')")), $criteria); } public function testSplitCriteria_Subquery() { $criteria = $this->qs->splitCriteria("abc=22 AND (def > xyz OR test IS NOT TRUE) AND `type` IN (SELECT `type` FROM `something` WHERE a>1 AND b<2)"); $this->assertEquals(array(array('abc', '=', '22'), array('def', '>', 'xyz'), array('test', 'IS NOT', 'TRUE'), array('`type`', 'IN', "(SELECT `type` FROM `something` WHERE a>1 AND b<2)")), $criteria); } public function testSplitCriteria_Where() { $criteria = $this->qs->splitCriteria("SELECT aaa, zzz FROM `atable` WHERE abc='test or 22' AND (def > dor XOR test IS NOT TRUE) AND (`date` between '2009-01-01' AND NOW() + INTERVAL 1 MONTH OR `date` IS NULL OR (`and` IN ('qq', 'or'))) GROUP BY `group` HAVING count(*) > 5 AND AVG(total) > 50"); $this->assertEquals(array(array('abc', '=', "'test or 22'"), array('def', '>', 'dor'), array('test', 'IS NOT', 'TRUE'), array('`date`', 'BETWEEN', "'2009-01-01' AND NOW() + INTERVAL 1 MONTH"), array('`date`', 'IS NULL', ''), array('`and`', 'IN', "('qq', 'or')")), $criteria); } public function testSplitCriteria_Having() { $criteria = $this->qs->splitCriteria("SELECT aaa, zzz FROM `atable` WHERE abc='test or 22' AND (def > dor XOR test IS NOT TRUE) AND (`date` between '2009-01-01' AND NOW() + INTERVAL 1 MONTH OR `date` IS NULL OR (`and` IN ('qq', 'or'))) GROUP BY `group` HAVING count(*) > 5 AND AVG(total) > 50", DB::HAVING); $this->assertEquals(array(array("count(*)", ">", "5"), array("AVG(total)", ">", "50")), $criteria); } public function testSplitJoinOn_Simple() { $criteria = $this->qs->splitJoinOn("abc LEFT JOIN `def` ON abc.id = `def`.abc_id INNER JOIN klm ON klm.type != 'ON' AND abc.klm_id = klm.id"); $this->assertEquals(array(array("abc.id", "=", "`def`.abc_id"), array("klm.type", "!=", "'ON'"), array("abc.klm_id", "=", "klm.id")), $criteria); } public function testSplitJoinOn_Advanced() { $criteria = $this->qs->splitJoinOn("abc LEFT JOIN (`def` INNER JOIN klm ON klm.type != 'ON' AND abc.klm_id = klm.id) ON abc.id = `def`.abc_id AND (def.x IS NULL OR (def.x between 10 AND 20 AND def.y IN ('a', 'b', 'c')))"); $this->assertEquals(array(array("klm.type", "!=", "'ON'"), array("abc.klm_id", "=", "klm.id"), array("abc.id", "=", "`def`.abc_id"), array('def.x', 'IS NULL', ''), array('def.x', 'BETWEEN', '10 AND 20'), array('def.y', 'IN', "('a', 'b', 'c')")), $criteria); } public function testSplitJoinOn_Subquery() { $criteria = $this->qs->splitJoinOn("abc LEFT JOIN (SELECT def.*, count(*) as cnt FROM `def` INNER JOIN klm ON klm.type != 'ON' AND abc.klm_id = klm.id GROUP BY `def`.`id`) AS `def` ON abc.id = `def`.abc_id AND (def.x IS NULL OR (def.x between 10 AND 20 AND def.y IN ('a', 'b', 'c')))"); $this->assertEquals(array(array("abc.id", "=", "`def`.abc_id"), array('def.x', 'IS NULL', ''), array('def.x', 'BETWEEN', '10 AND 20'), array('def.y', 'IN', "('a', 'b', 'c')")), $criteria); } public function testSplitJoinOn_Select() { $criteria = $this->qs->splitJoinOn("SELECT * FROM abc LEFT JOIN (`def` INNER JOIN klm ON klm.type != 'ON' AND abc.klm_id = klm.id) ON abc.id = `def`.abc_id AND (def.x IS NULL OR (def.x between 10 AND 20 AND def.y IN ('a', 'b', 'c'))) WHERE xyz = 10"); $this->assertEquals(array(array("klm.type", "!=", "'ON'"), array("abc.klm_id", "=", "klm.id"), array("abc.id", "=", "`def`.abc_id"), array('def.x', 'IS NULL', ''), array('def.x', 'BETWEEN', '10 AND 20'), array('def.y', 'IN', "('a', 'b', 'c')")), $criteria); } public function testSplitJoinOn_Update() { $criteria = $this->qs->splitJoinOn("UPDATE abc LEFT JOIN (`def` INNER JOIN klm ON klm.type != 'ON' AND abc.klm_id = klm.id) ON abc.id = `def`.abc_id AND (def.x IS NULL OR (def.x between 10 AND 20 AND def.y IN ('a', 'b', 'c'))) SET some='thing' WHERE xyz = 10"); $this->assertEquals(array(array("klm.type", "!=", "'ON'"), array("abc.klm_id", "=", "klm.id"), array("abc.id", "=", "`def`.abc_id"), array('def.x', 'IS NULL', ''), array('def.x', 'BETWEEN', '10 AND 20'), array('def.y', 'IN', "('a', 'b', 'c')")), $criteria); } public function testSplitJoinOn_Delete() { $criteria = $this->qs->splitJoinOn("DELETE abc.* FROM abc LEFT JOIN (`def` INNER JOIN klm ON klm.type != 'ON' AND abc.klm_id = klm.id) ON abc.id = `def`.abc_id AND (def.x IS NULL OR (def.x between 10 AND 20 AND def.y IN ('a', 'b', 'c'))) WHERE xyz = 10"); $this->assertEquals(array(array("klm.type", "!=", "'ON'"), array("abc.klm_id", "=", "klm.id"), array("abc.id", "=", "`def`.abc_id"), array('def.x', 'IS NULL', ''), array('def.x', 'BETWEEN', '10 AND 20'), array('def.y', 'IN', "('a', 'b', 'c')")), $criteria); } //-------- public function testExtractSubsets_Select() { $set = $this->qs->extractSubsets("SELECT * FROM relatie WHERE status = 1"); $this->assertEquals(array("SELECT * FROM relatie WHERE status = 1"), array_map(array(__CLASS__, 'cleanQuery'), $set)); } public function testExtractSubsets_SelectSubqueryInWhere() { $set = $this->qs->extractSubsets("SELECT * FROM relatie WHERE id IN (SELECT relatie_id FROM relatie_groep) AND status = 1"); $this->assertEquals(array("SELECT * FROM relatie WHERE id IN (#sub1) AND status = 1", "SELECT relatie_id FROM relatie_groep"), array_map(array(__CLASS__, 'cleanQuery'), $set)); } public function testExtractSubsets_SelectSubqueryInJoin() { $set = $this->qs->extractSubsets("SELECT * FROM relatie LEFT JOIN (SELECT relatie_id, COUNT(*) FROM contactpersoon) AS con_cnt ON relatie.id = con_cnt.relatie_id WHERE id IN (SELECT relatie_id FROM relatie_groep STRAIGHT JOIN (SELECT y, COUNT(x) FROM xy GROUP BY y) AS xy) AND status = 1"); $this->assertEquals(array("SELECT * FROM relatie LEFT JOIN (#sub1) AS con_cnt ON relatie.id = con_cnt.relatie_id WHERE id IN (#sub2) AND status = 1", "SELECT relatie_id, COUNT(*) FROM contactpersoon", "SELECT relatie_id FROM relatie_groep STRAIGHT JOIN (#sub3) AS xy", "SELECT y, COUNT(x) FROM xy GROUP BY y"), array_map(array(__CLASS__, 'cleanQuery'), $set)); } public function testExtractSubsets_Insert() { $set = $this->qs->extractSubsets("INSERT INTO relatie_active SELECT * FROM relatie WHERE status = 1"); $this->assertEquals(array("INSERT INTO relatie_active #sub1", "SELECT * FROM relatie WHERE status = 1"), array_map(array(__CLASS__, 'cleanQuery'), $set)); } public function testExtractSubsets_InsertSubqueryInWhere() { $set = $this->qs->extractSubsets("INSERT INTO relatie_active SELECT * FROM relatie WHERE id IN (SELECT relatie_id FROM relatie_groep) AND status = 1"); $this->assertEquals(array("INSERT INTO relatie_active #sub1", "SELECT * FROM relatie WHERE id IN (#sub2) AND status = 1", "SELECT relatie_id FROM relatie_groep"), array_map(array(__CLASS__, 'cleanQuery'), $set)); } public function testExtractTree() { $set = $this->qs->ExtractTree("SELECT * FROM relatie WHERE status = 1"); $this->assertEquals(array("SELECT * FROM relatie WHERE status = 1"), $set); } public function testExtractTree_SubValues() { $set = $this->qs->ExtractTree("SELECT id, description, VALUES (SELECT categorie_id FROM relatie_categorie CASCADE ON relatie_id = relatie.id) AS cat, xyz FROM relatie WHERE id IN (SELECT relatie_id FROM relatie_groep) AND status = 1"); $set[0] = self::cleanQuery($set[0]); for ($i=1; $i<sizeof($set); $i++) $set[$i][1] = self::cleanQuery($set[$i][1]); $this->assertEquals(array("SELECT id, description, relatie.id AS cat, xyz FROM relatie WHERE id IN (SELECT relatie_id FROM relatie_groep) AND status = 1", array('cat', "SELECT categorie_id, relatie_id AS `tree:join` FROM relatie_categorie WHERE relatie_id IN (?) ORDER BY relatie_id", DB::FETCH_VALUE, true)), $set); } public function testExtractTree_SubRows() { $set = $this->qs->ExtractTree("SELECT id, description, ROWS(SELECT categorie_id, opmerking FROM relatie_categorie WHERE categorie_id != 2 CASCADE ON relatie_id = relatie.id) AS cat, xyz FROM relatie WHERE id IN (SELECT relatie_id FROM relatie_groep) AND status = 1"); $set[0] = self::cleanQuery($set[0]); for ($i=1; $i<sizeof($set); $i++) $set[$i][1] = self::cleanQuery($set[$i][1]); $this->assertEquals(array("SELECT id, description, relatie.id AS cat, xyz FROM relatie WHERE id IN (SELECT relatie_id FROM relatie_groep) AND status = 1", array('cat', "SELECT categorie_id, opmerking, relatie_id AS `tree:join` FROM relatie_categorie WHERE (categorie_id != 2) AND relatie_id IN (?) ORDER BY relatie_id", DB::FETCH_ORDERED, true)), $set); } public function testExtractTree_FakeSubValues() { $set = $this->qs->ExtractTree("SELECT id, description, 'VALUES (SELECT it)' AS cat, xyz FROM relatie WHERE id IN (SELECT relatie_id FROM relatie_groep) AND status = 1"); $set[0] = self::cleanQuery($set[0]); $this->assertEquals(array("SELECT id, description, 'VALUES (SELECT it)' AS cat, xyz FROM relatie WHERE id IN (SELECT relatie_id FROM relatie_groep) AND status = 1"), $set); } public function testExtractTree_WithBranch() { $set = $this->qs->ExtractTree("SELECT categorie.id, categorie.titel, categorie.verkopen_op, ROWS(SELECT product.id, product.titel, product.omschrijving, ROWS(SELECT product.id, product.name FROM product INNER JOIN product_accessoire ON product.id = product_accessoire.product_id INNER JOIN product_accessoire_product ON product_accessoire.id = product_accessoire_product.product_accessoire_id CASCADE ON product_accessoire_product.product_id = product.id) AS accessoire FROM product WHERE product.accessoire = 0 CASCADE ON product.categorie_id = categorie.id) as product"); $set[0] = self::cleanQuery($set[0]); for ($i=1; $i<sizeof($set); $i++) $set[$i][1] = self::cleanQuery($set[$i][1]); $this->assertEquals(array("SELECT categorie.id, categorie.titel, categorie.verkopen_op, categorie.id AS product", array('product', "SELECT product.id, product.titel, product.omschrijving, ROWS(SELECT product.id, product.name FROM product INNER JOIN product_accessoire ON product.id = product_accessoire.product_id INNER JOIN product_accessoire_product ON product_accessoire.id = product_accessoire_product.product_accessoire_id CASCADE ON product_accessoire_product.product_id = product.id) AS accessoire, product.categorie_id AS `tree:join` FROM product WHERE (product.accessoire = 0) AND product.categorie_id IN (?) ORDER BY product.categorie_id", DB::FETCH_ORDERED, true)), $set); $subset = $this->qs->ExtractTree($set[1][1]); $subset[0] = self::cleanQuery($subset[0]); for ($i=1; $i<sizeof($subset); $i++) $subset[$i][1] = self::cleanQuery($subset[$i][1]); $this->assertEquals(array("SELECT product.id, product.titel, product.omschrijving, product.id AS accessoire, product.categorie_id AS `tree:join` FROM product WHERE (product.accessoire = 0) AND product.categorie_id IN (?) ORDER BY product.categorie_id", array('accessoire', "SELECT product.id, product.name, product_accessoire_product.product_id AS `tree:join` FROM product INNER JOIN product_accessoire ON product.id = product_accessoire.product_id INNER JOIN product_accessoire_product ON product_accessoire.id = product_accessoire_product.product_accessoire_id WHERE product_accessoire_product.product_id IN (?) ORDER BY product_accessoire_product.product_id", DB::FETCH_ORDERED, true)), $subset); } //-------- public function testSelectStatement_AddColumn() { $s = $this->statement("SELECT id, description FROM `test`"); $s->addColumn("abc"); $this->assertEquals("SELECT id, description, `abc` FROM `test`", self::cleanQuery($s)); } public function testSelectStatement_AddColumn_Prepend() { $s = $this->statement("SELECT id, description FROM `test`"); $s->addColumn("abc", DB::PREPEND); $this->assertEquals("SELECT `abc`, id, description FROM `test`", self::cleanQuery($s)); } public function testSelectStatement_AddColumn_Replace() { $s = $this->statement("SELECT id, description FROM `test`"); $s->addColumn("abc", DB::REPLACE); $this->assertEquals("SELECT `abc` FROM `test`", self::cleanQuery($s)); } public function testSelectStatement_AddTable() { $s = $this->statement("SELECT id, description FROM `test` WHERE xy > 10"); $s->addTable("abc"); $this->assertEquals("SELECT id, description FROM (`test`), `abc` WHERE xy > 10", self::cleanQuery($s)); } public function testSelectStatement_AddTable_LeftJoin() { $s = $this->statement("SELECT id, description FROM `test` WHERE xy > 10"); $s->addTable("abc", "LEFT JOIN", array("test.id", "abc.idTest")); $this->assertEquals("SELECT id, description FROM (`test`) LEFT JOIN `abc` ON `test`.`id` = `abc`.`idTest` WHERE xy > 10", self::cleanQuery($s)); } public function testSelectStatement_AddTable_AsString() { $s = $this->statement("SELECT id, description FROM `test` LEFT JOIN x ON test.x_id = x.id"); $s->addTable("abc", "LEFT JOIN", "test.id = abc.idTest"); $this->assertEquals("SELECT id, description FROM (`test` LEFT JOIN x ON test.x_id = x.id) LEFT JOIN `abc` ON `test`.`id` = `abc`.`idTest`", self::cleanQuery($s)); } public function testSelectStatement_AddTable_StraightJoin() { $s = $this->statement("SELECT id, description FROM `test`"); $s->addTable("abc", "STRAIGHT JOIN"); $this->assertEquals("SELECT id, description FROM (`test`) STRAIGHT JOIN `abc`", self::cleanQuery($s)); } public function testSelectStatement_AddTable_Replace() { $s = $this->statement("SELECT id, description FROM `test`"); $s->addTable("abc", null, null, DB::REPLACE); $this->assertEquals("SELECT id, description FROM `abc`", self::cleanQuery($s)); } public function testSelectStatement_AddTable_Prepend() { $s = $this->statement("SELECT id, description FROM `test` LEFT JOIN x ON test.x_id = x.id"); $s->addTable("abc", 'LEFT JOIN', "test.id = abc.idTest", DB::PREPEND); $this->assertEquals("SELECT id, description FROM `abc` LEFT JOIN (`test` LEFT JOIN x ON test.x_id = x.id) ON `test`.`id` = `abc`.`idTest`", self::cleanQuery($s)); } public function testSelectStatement_Where_Simple() { $s = $this->statement("SELECT id, description FROM `test`"); $s->where("status = 1"); $this->assertEquals("SELECT id, description FROM `test` WHERE (`status` = 1)", self::cleanQuery($s)); } public function testSelectStatement_Where() { $s = $this->statement("SELECT id, description FROM `test` WHERE id > 10 GROUP BY type_id HAVING SUM(qty) > 10"); $s->where("status = 1"); $this->assertEquals("SELECT id, description FROM `test` WHERE (id > 10) AND (`status` = 1) GROUP BY type_id HAVING SUM(qty) > 10", self::cleanQuery($s)); } public function testSelectStatement_Where_Prepend() { $s = $this->statement("SELECT id, description FROM `test` WHERE id > 10 GROUP BY type_id HAVING SUM(qty) > 10"); $s->where("status = 1", null, null, DB::PREPEND); $this->assertEquals("SELECT id, description FROM `test` WHERE (`status` = 1) AND (id > 10) GROUP BY type_id HAVING SUM(qty) > 10", self::cleanQuery($s)); } public function testSelectStatement_Where_Replace() { $s = $this->statement("SELECT id, description FROM `test` WHERE id > 10 GROUP BY type_id HAVING SUM(qty) > 10"); $s->where("status = 1", null, null, DB::REPLACE); $s->where("xyz = 1"); $this->assertEquals("SELECT id, description FROM `test` WHERE (`status` = 1) AND (`xyz` = 1) GROUP BY type_id HAVING SUM(qty) > 10", self::cleanQuery($s)); } public function testSelectStatement_Having() { $s = $this->statement("SELECT id, description FROM `test` WHERE id > 10 GROUP BY type_id HAVING SUM(qty) > 10"); $s->where("status = 1", null, null, DB::HAVING); $this->assertEquals("SELECT id, description FROM `test` WHERE id > 10 GROUP BY type_id HAVING (SUM(qty) > 10) AND (`status` = 1)", self::cleanQuery($s)); } public function testSelectStatement_GroupBy_Simple() { $s = $this->statement("SELECT id, description FROM `test`"); $s->groupBy("parent_id"); $this->assertEquals("SELECT id, description FROM `test` GROUP BY `parent_id`", self::cleanQuery($s)); } public function testSelectStatement_GroupBy() { $s = $this->statement("SELECT id, description FROM `test` WHERE id > 10 GROUP BY type_id HAVING SUM(qty) > 10"); $s->groupBy("parent_id"); $this->assertEquals("SELECT id, description FROM `test` WHERE id > 10 GROUP BY type_id, `parent_id` HAVING SUM(qty) > 10", self::cleanQuery($s)); } public function testSelectStatement_OrderBy_Simple() { $s = $this->statement("SELECT id, description FROM `test`"); $s->orderBy("parent_id"); $this->assertEquals("SELECT id, description FROM `test` ORDER BY `parent_id`", self::cleanQuery($s)); } public function testSelectStatement_OrderBy() { $s = $this->statement("SELECT id, description FROM `test` WHERE id > 10 GROUP BY type_id HAVING SUM(qty) > 10 ORDER BY xyz"); $s->orderBy("parent_id"); $this->assertEquals("SELECT id, description FROM `test` WHERE id > 10 GROUP BY type_id HAVING SUM(qty) > 10 ORDER BY `parent_id`, xyz", self::cleanQuery($s)); } public function testSelectStatement_OrderBy_Append() { $s = $this->statement("SELECT id, description FROM `test` WHERE id > 10 GROUP BY type_id HAVING SUM(qty) > 10 ORDER BY xyz"); $s->orderBy("parent_id", DB::APPEND); $this->assertEquals("SELECT id, description FROM `test` WHERE id > 10 GROUP BY type_id HAVING SUM(qty) > 10 ORDER BY xyz, `parent_id`", self::cleanQuery($s)); } public function testSelectStatement_WhereCriteria_Equals() { $s = $this->statement("SELECT id, description FROM `test`"); $s->where("status", 1); $this->assertEquals("SELECT id, description FROM `test` WHERE (`status` = 1)", self::cleanQuery($s)); } public function testSelectStatement_WhereCriteria_GreatEq() { $s = $this->statement("SELECT id, description FROM `test`"); $s->where('id', 1, '>='); $this->assertEquals("SELECT id, description FROM `test` WHERE (`id` >= 1)", self::cleanQuery($s)); } public function testSelectStatement_WhereCriteria_Or() { $s = $this->statement("SELECT id, description FROM `test`"); $s->where(array('xyz', 'abc'), 10); $this->assertEquals("SELECT id, description FROM `test` WHERE (`xyz` = 10 OR `abc` = 10)", self::cleanQuery($s)); } public function testSelectStatement_WhereCriteria_In() { $s = $this->statement("SELECT id, description FROM `test`"); $s->where('xyz', array('a', 'b', 'c')); $this->assertEquals("SELECT id, description FROM `test` WHERE (`xyz` IN (\"a\", \"b\", \"c\"))", self::cleanQuery($s)); } public function testSelectStatement_WhereCriteria_Between() { $s = $this->statement("SELECT id, description FROM `test`"); $s->where('xyz', array(10, 12), 'BETWEEN'); $this->assertEquals("SELECT id, description FROM `test` WHERE (`xyz` BETWEEN 10 AND 12)", self::cleanQuery($s)); } public function testSelectStatement_WhereCriteria_BetweenXAndNull() { $s = $this->statement("SELECT id, description FROM `test`"); $s->where('xyz', array(10, null), 'BETWEEN'); $this->assertEquals("SELECT id, description FROM `test` WHERE (`xyz` >= 10)", self::cleanQuery($s)); } public function testSelectStatement_WhereCriteria_BetweenNullAndX() { $s = $this->statement("SELECT id, description FROM `test`"); $s->where('xyz', array(null, 12), 'BETWEEN'); $this->assertEquals("SELECT id, description FROM `test` WHERE (`xyz` <= 12)", self::cleanQuery($s)); } public function testSelectStatement_WhereCriteria_LikeWildcard() { $s = $this->statement("SELECT id, description FROM `test`"); $s->where('description', 'bea', 'LIKE%'); $this->assertEquals("SELECT id, description FROM `test` WHERE (`description` LIKE \"bea%\")", self::cleanQuery($s)); } public function testSelectStatement_WhereCriteria_WildcardLikeWildcard() { $s = $this->statement("SELECT id, description FROM `test`"); $s->where('description', array('bean', 'arnold'), '%LIKE%'); $this->assertEquals("SELECT id, description FROM `test` WHERE (`description` LIKE \"%bean%\" OR `description` LIKE \"%arnold%\")", self::cleanQuery($s)); } public function testSelectStatement_Limit() { $s = $this->statement("SELECT id, description FROM `test`"); $s->limit(10); $this->assertEquals("SELECT id, description FROM `test` LIMIT 10", self::cleanQuery($s)); } public function testSelectStatement_Limit_Replace() { $s = $this->statement("SELECT id, description FROM `test` LIMIT 12"); $s->limit(50, 30); $this->assertEquals("SELECT id, description FROM `test` LIMIT 50 OFFSET 30", self::cleanQuery($s)); } public function testSelectStatement_Limit_String() { $s = $this->statement("SELECT id, description FROM `test` LIMIT 12"); $s->limit("50 OFFSET 30"); $this->assertEquals("SELECT id, description FROM `test` LIMIT 50 OFFSET 30", self::cleanQuery($s)); } //-------- public function testInsertStatement_AddColumns() { $s = $this->statement("INSERT INTO `test` SET description='abc', type_id=10"); $s->addColumn("abc=12"); $this->assertEquals("INSERT INTO `test` SET description='abc', type_id=10, `abc`=12", self::cleanQuery($s)); } public function testInsertStatement_AddValues_String() { $s = $this->statement("INSERT INTO `test` VALUES (NULL, 'abc', 10)"); $s->addValues('DEFAULT, "xyz", 12'); $this->assertEquals("INSERT INTO `test` VALUES (NULL, 'abc', 10), (DEFAULT, \"xyz\", 12)", self::cleanQuery($s)); } public function testInsertStatement_AddValues_Array() { $s = $this->statement("INSERT INTO `test` VALUES (NULL, 'abc', 10)"); $s->addValues(array(null, 'xyz', 12)); $this->assertEquals("INSERT INTO `test` VALUES (NULL, 'abc', 10), (DEFAULT, \"xyz\", 12)", self::cleanQuery($s)); } public function testInsertSelectStatement_AddColumns() { $s = $this->statement("INSERT INTO `test` SELECT DEFAULT, description, type_id FROM abc"); $s->addColumn("xyz", 0, 1); $this->assertEquals("INSERT INTO `test` SELECT DEFAULT, description, type_id, `xyz` FROM abc", self::cleanQuery($s)); } public function testInsertSelectStatement_WhereCriteria() { $s = $this->statement("INSERT INTO `test` SELECT DEFAULT, description, type_id FROM abc"); $s->where("status", 1); $this->assertEquals("INSERT INTO `test` SELECT DEFAULT, description, type_id FROM abc WHERE (`status` = 1)", self::cleanQuery($s)); } public function testInsertSelectStatement_WhereCriteria_Like() { $s = $this->statement("INSERT INTO `test` SELECT DEFAULT, description, type_id FROM abc WHERE status = 1"); $s->where('description', 'qqq', 'LIKE%'); $this->assertEquals("INSERT INTO `test` SELECT DEFAULT, description, type_id FROM abc WHERE (status = 1) AND (`description` LIKE \"qqq%\")", self::cleanQuery($s)); } //-------- public function testUpdateStatement_AddColumns_Simple() { $s = $this->statement("UPDATE `test` SET description='abc', type_id=10"); $s->addColumn("abc=12"); $this->assertEquals("UPDATE `test` SET description='abc', type_id=10, `abc`=12", self::cleanQuery($s)); } public function testUpdateStatement_AddColumns() { $s = $this->statement("UPDATE `test` SET description='abc', type_id=10 WHERE xyz=10"); $s->addColumn("abc=12"); $this->assertEquals("UPDATE `test` SET description='abc', type_id=10, `abc`=12 WHERE xyz=10", self::cleanQuery($s)); } public function testUpdateStatement_AddColumns_Replace() { $s = $this->statement("UPDATE `test` SET description='abc', type_id=10 WHERE xyz=10"); $s->addColumn("abc=12", DB::REPLACE); $this->assertEquals("UPDATE `test` SET `abc`=12 WHERE xyz=10", self::cleanQuery($s)); } public function testUpdateStatement_AddTable() { $s = $this->statement("UPDATE `test` SET description='abc', type_id=10 WHERE xy > 10"); $s->addTable("abc", "LEFT JOIN", array("test.id", "abc.idTest")); $this->assertEquals("UPDATE (`test`) LEFT JOIN `abc` ON `test`.`id` = `abc`.`idTest` SET description='abc', type_id=10 WHERE xy > 10", self::cleanQuery($s)); } public function testUpdateStatement_AddTable_String() { $s = $this->statement("UPDATE `test` LEFT JOIN x ON test.x_id = x.id SET description='abc', type_id=10"); $s->addTable("abc", "LEFT JOIN", "test.id = abc.idTest"); $this->assertEquals("UPDATE (`test` LEFT JOIN x ON test.x_id = x.id) LEFT JOIN `abc` ON `test`.`id` = `abc`.`idTest` SET description='abc', type_id=10", self::cleanQuery($s)); } public function testUpdateStatement_AddTable_StraightJoin() { $s = $this->statement("UPDATE `test` SET description='abc', type_id=10"); $s->addTable("abc", "STRAIGHT JOIN"); $this->assertEquals("UPDATE (`test`) STRAIGHT JOIN `abc` SET description='abc', type_id=10", self::cleanQuery($s)); } public function testUpdateStatement_AddTable_Replace() { $s = $this->statement("UPDATE `test` SET description='abc', type_id=10"); $s->addTable("abc", null, null, DB::REPLACE); $this->assertEquals("UPDATE `abc` SET description='abc', type_id=10", self::cleanQuery($s)); } public function testUpdateStatement_AddTable_Prepend() { $s = $this->statement("UPDATE `test` LEFT JOIN x ON test.x_id = x.id SET description='abc', type_id=10"); $s->addTable("abc", 'LEFT JOIN', "test.id = abc.idTest", DB::PREPEND); $this->assertEquals("UPDATE `abc` LEFT JOIN (`test` LEFT JOIN x ON test.x_id = x.id) ON `test`.`id` = `abc`.`idTest` SET description='abc', type_id=10", self::cleanQuery($s)); } public function testUpdateStatement_Where_Simple() { $s = $this->statement("UPDATE `test` SET description='abc', type_id=10"); $s->where("status = 1"); $this->assertEquals("UPDATE `test` SET description='abc', type_id=10 WHERE (`status` = 1)", self::cleanQuery($s)); } public function testUpdateStatement_Where() { $s = $this->statement("UPDATE `test` SET description='abc', type_id=10 WHERE id > 10"); $s->where("status = 1"); $this->assertEquals("UPDATE `test` SET description='abc', type_id=10 WHERE (id > 10) AND (`status` = 1)", self::cleanQuery($s)); } public function testUpdateStatement_Where_Prepend() { $s = $this->statement("UPDATE `test` SET description='abc', type_id=10 WHERE id > 10"); $s->where("status = 1", null, null, DB::PREPEND); $this->assertEquals("UPDATE `test` SET description='abc', type_id=10 WHERE (`status` = 1) AND (id > 10)", self::cleanQuery($s)); } public function testUpdateStatement_Where_Replace() { $s = $this->statement("UPDATE `test` SET description='abc', type_id=10 WHERE id > 10"); $s->where("status = 1", null, null, DB::REPLACE); $s->where("xyz = 1"); $this->assertEquals("UPDATE `test` SET description='abc', type_id=10 WHERE (`status` = 1) AND (`xyz` = 1)", self::cleanQuery($s)); } public function testUpdateStatement_WhereCriteria() { $s = $this->statement("UPDATE `test` SET description='abc', type_id=10"); $s->where("status", 1); $this->assertEquals("UPDATE `test` SET description='abc', type_id=10 WHERE (`status` = 1)", self::cleanQuery($s)); } public function testUpdateStatement_WhereCriteria_Or() { $s = $this->statement("UPDATE `test` SET description='abc', type_id=10"); $s->where(array('xyz', 'abc'), 10); $this->assertEquals("UPDATE `test` SET description='abc', type_id=10 WHERE (`xyz` = 10 OR `abc` = 10)", self::cleanQuery($s)); } public function testUpdateStatement_WhereCriteria_Between() { $s = $this->statement("UPDATE `test` SET description='abc', type_id=10"); $s->where('xyz', array(10, 12), 'BETWEEN'); $this->assertEquals("UPDATE `test` SET description='abc', type_id=10 WHERE (`xyz` BETWEEN 10 AND 12)", self::cleanQuery($s)); } public function testUpdateStatement_WhereCriteria_LikeWildcard() { $s = $this->statement("UPDATE `test` SET description='abc', type_id=10"); $s->where('description', 'bea', 'LIKE%'); $this->assertEquals("UPDATE `test` SET description='abc', type_id=10 WHERE (`description` LIKE \"bea%\")", self::cleanQuery($s)); } public function testUpdateStatement_Limit() { $s = $this->statement("UPDATE `test` SET description='abc', type_id=10"); $s->limit(10); $this->assertEquals("UPDATE `test` SET description='abc', type_id=10 LIMIT 10", self::cleanQuery($s)); } public function testUpdateStatement_Limit_Replace() { $s = $this->statement("UPDATE `test` SET description='abc', type_id=10 LIMIT 12"); $s->limit(50, 30); $this->assertEquals("UPDATE `test` SET description='abc', type_id=10 LIMIT 50 OFFSET 30", self::cleanQuery($s)); } //-------- public function testDeleteStatement_AddColumn() { $s = $this->statement("DELETE FROM `test`"); $s->addColumn("test.*"); $this->assertEquals("DELETE `test`.* FROM `test`", self::cleanQuery($s)); } public function testDeleteStatement_AddTable() { $s = $this->statement("DELETE FROM `test`"); $s->addTable("abc", "LEFT JOIN", array("test.id", "abc.idTest")); $this->assertEquals("DELETE FROM (`test`) LEFT JOIN `abc` ON `test`.`id` = `abc`.`idTest`", self::cleanQuery($s)); } public function testDeleteStatement_AddTable_String() { $s = $this->statement("DELETE FROM `test` LEFT JOIN x ON test.x_id = x.id"); $s->addTable("abc", "LEFT JOIN", "test.id = abc.idTest"); $this->assertEquals("DELETE FROM (`test` LEFT JOIN x ON test.x_id = x.id) LEFT JOIN `abc` ON `test`.`id` = `abc`.`idTest`", self::cleanQuery($s)); } public function testDeleteStatement_AddTable_StraightJoin() { $s = $this->statement("DELETE FROM `test`"); $s->addTable("abc", "STRAIGHT JOIN"); $this->assertEquals("DELETE FROM (`test`) STRAIGHT JOIN `abc`", self::cleanQuery($s)); } public function testDeleteStatement_AddTable_Replace() { $s = $this->statement("DELETE FROM `test`"); $s->addTable("abc", null, null, DB::REPLACE); $this->assertEquals("DELETE FROM `abc`", self::cleanQuery($s)); } public function testDeleteStatement_AddTable_Prepend() { $s = $this->statement("DELETE FROM `test` LEFT JOIN x ON test.x_id = x.id"); $s->addTable("abc", 'LEFT JOIN', "test.id = abc.idTest", DB::PREPEND); $this->assertEquals("DELETE FROM `abc` LEFT JOIN (`test` LEFT JOIN x ON test.x_id = x.id) ON `test`.`id` = `abc`.`idTest`", self::cleanQuery($s)); } public function testDeleteStatement_Where_Simple() { $s = $this->statement("DELETE FROM `test`"); $s->where("status = 1"); $this->assertEquals("DELETE FROM `test` WHERE (`status` = 1)", self::cleanQuery($s)); } public function testDeleteStatement_Where() { $s = $this->statement("DELETE FROM `test` WHERE id > 10"); $s->where("status = 1"); $this->assertEquals("DELETE FROM `test` WHERE (id > 10) AND (`status` = 1)", self::cleanQuery($s)); } public function testDeleteStatement_Where_Prepend() { $s = $this->statement("DELETE FROM `test` WHERE id > 10"); $s->where("status = 1", null, null, DB::PREPEND); $this->assertEquals("DELETE FROM `test` WHERE (`status` = 1) AND (id > 10)", self::cleanQuery($s)); } public function testDeleteStatement_Where_Replace() { $s = $this->statement("DELETE FROM `test` WHERE id > 10"); $s->where("status = 1", null, null, DB::REPLACE); $s->where("xyz = 1"); $this->assertEquals("DELETE FROM `test` WHERE (`status` = 1) AND (`xyz` = 1)", self::cleanQuery($s)); } public function testDeleteStatement_WhereCriteria() { $s = $this->statement("DELETE FROM `test`"); $s->where("status", 1); $this->assertEquals("DELETE FROM `test` WHERE (`status` = 1)", self::cleanQuery($s)); } public function testDeleteStatement_WhereCriteria_Or() { $s = $this->statement("DELETE FROM `test`"); $s->where(array('xyz', 'abc'), 10); $this->assertEquals("DELETE FROM `test` WHERE (`xyz` = 10 OR `abc` = 10)", self::cleanQuery($s)); } public function testDeleteStatement_WhereCriteria_Between() { $s = $this->statement("DELETE FROM `test`"); $s->where('xyz', array(10, 12), 'BETWEEN'); $this->assertEquals("DELETE FROM `test` WHERE (`xyz` BETWEEN 10 AND 12)", self::cleanQuery($s)); } public function testDeleteStatement_WhereCriteria_LikeWildcard() { $s = $this->statement("DELETE FROM `test`"); $s->where('description', 'bea', 'LIKE%'); $this->assertEquals("DELETE FROM `test` WHERE (`description` LIKE \"bea%\")", self::cleanQuery($s)); } public function testDeleteStatement_Limit() { $s = $this->statement("DELETE FROM `test`"); $s->limit(10); $this->assertEquals("DELETE FROM `test` LIMIT 10", self::cleanQuery($s)); } public function testDeleteStatement_Limit_Replace() { $s = $this->statement("DELETE FROM `test` LIMIT 12"); $s->limit(50, 30); $this->assertEquals("DELETE FROM `test` LIMIT 50 OFFSET 30", self::cleanQuery($s)); } }
true
b8a882eeb1bae4c9b66df7f8eb079d80b9c66b21
PHP
mayankpatel1004/docker-with-php-mysql-phpmyadmin
/web/public/theme/default/underconstruction.php
UTF-8
2,149
2.53125
3
[]
no_license
<?php if(isset($_REQUEST['uc']) && $_REQUEST['uc'] == "No") { $sql = "UPDATE `site_config` SET `config_value` = 'No' WHERE `site_config`.`config_name` = 'SITE_CONSTRUCTION'"; $stmt = $conn->prepare($sql); $stmt->execute(); setConfigdata(); } function setConfigdata() { global $back_session_name,$conn,$theme_path,$url,$cf; $sql = "SELECT * FROM `site_config` WHERE `display_status` = 'Y' AND `deleted_status` = 'N'"; $arrData = $cf->getData($sql); $write = ""; $write .= "<?php"; $write .= "\r\n"; foreach($arrData as $key=>$value) { $key = $value['config_name']; $value = $value['config_value']; $write .= "define('".$key."','".addslashes($value)."');"; $write .="\r\n"; } $write .= "?>"; file_put_contents($theme_path."generated_files/configdata.php",$write); $sitemapType = "SELECT DISTINCT(item_type) FROM `items` WHERE admin_module = 'N' AND display_status = 'Y' AND deleted_status = 'N'"; $arrType = $cf->getData($sitemapType); if(isset($arrType) && !empty($arrType)) { $return = ""; $arrParent = []; foreach($arrType as $type) { $type = $type['item_type']; $sqlSitemap = "SELECT item_id,item_title,item_type,item_alias FROM `items` WHERE `html_sitemap` = 'Y' AND `item_type` = '$type' AND `admin_module` = 'N' AND `display_status` = 'Y' AND `deleted_status` = 'N' ORDER BY `html_sitemap_order` ASC,`item_id` DESC"; $arrData = $cf->getData($sqlSitemap); if(isset($arrData) && !empty($arrData)){ foreach($arrData as $key=>$value) { $arrParent[$type][] = array('title' => $value['item_title'],'alias' => $value['item_alias']); } } } } file_put_contents($theme_path."generated_files/sitemapdata.php",serialize($arrParent)); } ?> <!DOCTYPE html> <html> <head> <title>Site Under Construction</title> </head> <body> <img style="text-align:center;width:100%;margin:auto;" src="<?php echo $theme_url;?>images/maintenance.png" alt="Under Construction" /> </body> </html>
true
7b66c0c5773ce2cff6dc791f89402073a11020e1
PHP
dtbinh/CS331-SortPractice
/SortCount.php
UTF-8
1,082
3
3
[]
no_license
<?php require_once "InsertSort.php"; require_once "MergeSort.php"; require_once "QuickSort.php"; enableKeyCount(true); // insert | merge | quick1 | quick2 | quick3 if (count($argv) < 3) die("php SortCount.php <mode> <case file>\n"); $mode = $argv[1]; $fname = $argv[2]; $list = explode(",", file_get_contents($fname)); // initialize $sort = createSort($mode); if (is_null($sort)) die("Invalid sort mode: ".$mode."!\n"); // Evaluate the computation count $loopCount = 1; if ($mode == "quick3") { $loopCount = 100; } for ($i = 0; $i < $loopCount; $i ++) { $sort($list, 0, count($list) - 1); } // Show the result echo "Sort mode:\t".$sort."\n"; echo "List size:\t".count($list)."\n"; echo "Computation count:\t".intval(getKeyCount()/$loopCount)."\n"; function createSort($mode) { $sort = null; switch ($mode) { case "insert": $sort = "insertSort"; break; case "merge": $sort = "mergeSort"; break; case "quick1": $sort = "quickSort1"; break; case "quick2": $sort = "quickSort2"; break; case "quick3": $sort = "quickSort3"; break; } return $sort; }
true
993776d876197237d43825bf49d438f7544be7b2
PHP
dansc11/php-checkout-test
/app/Terminal.php
UTF-8
1,741
3.53125
4
[]
no_license
<?php namespace App; class Terminal { /** * @var array */ private $basket = []; /** * @var ProductPriceCalculator */ private $product_price_calculator; /** * Terminal constructor. */ public function __construct() { $this->product_price_calculator = new ProductPriceCalculator; } /** * Add a new pricing rule for a product to the product price calculator. * * @param string $product_code * @param float $price * @param int $quantity */ public function setPricing(string $product_code, float $price, int $quantity = 1): void { $this->product_price_calculator->addProductPrice($product_code, $price, $quantity); } /** * Add an item to the basket. * * @param string $product_code */ public function scanItem(string $product_code): void { $this->addBasketRow($product_code); $this->basket[$product_code] += 1; } /** * Add a new item to the basket if it doesn't already exist. * * @param string $product_code */ private function addBasketRow(string $product_code): void { if (array_key_exists($product_code, $this->basket)) { return; } $this->basket[$product_code] = 0; } /** * Get the total value of the basket. * * @return float */ public function getTotal(): float { $total = 0; foreach ($this->basket as $product => $quantity) { $total += $this->product_price_calculator->getTotalPrice($product, $quantity); } return $total; } }
true
b9ba42959d13700cd5a3f716f2960250d76a697f
PHP
qiu-jin/phpegg
/framework/driver/cache/Apcu.php
UTF-8
1,344
2.84375
3
[]
no_license
<?php namespace framework\driver\cache; /* * http://php.net/apcu */ class Apcu extends Cache { // 字段前缀 protected $prefix; /* * 构造函数 */ public function __construct($config) { parent::__construct($config); $this->prefix = $config['prefix']; } /* * 获取 */ public function get($key, $default = null) { return apcu_fetch($this->prefix.$key) ?? $default; } /* * 检查 */ public function has($key) { return apcu_exists($this->prefix.$key); } /* * 设置 */ public function set($key, $value, $ttl = null) { return apcu_store($this->prefix.$key, $value, $this->ttl($ttl)); } /* * 删除 */ public function delete($key) { return apcu_delete($this->prefix.$key); } /* * 自增 */ public function increment($key, $value = 1) { return apcu_inc($this->prefix.$key, $value); } /* * 自减 */ public function decrement($key, $value = 1) { return apcu_dec($this->prefix.$key, $value); } /* * 清理 */ public function clear() { return apcu_clear_cache(); } }
true
70c228b37755b255083a73b18e4eb960a0266f55
PHP
Malamego/LMS_Encryption
/app/Http/Controllers/ClassesController.php
UTF-8
3,609
2.546875
3
[]
no_license
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests\ClassesRequest; use App\DataTables\ClassesDataTable; use App\Models\ClassModel; class ClassesController extends Controller { private $viewPath = 'backend.classes'; /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(ClassesDataTable $dataTable) { return $dataTable->render("{$this->viewPath}.index", [ 'title' => trans('main.show-all') . ' ' . trans('main.classes') ]); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view("{$this->viewPath}.create", [ 'title' => trans('main.add') . ' ' . trans('main.classes'), ]); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(ClassesRequest $request) { $requestAll = $request->all(); $class = ClassModel::create($requestAll); session()->flash('success', trans('main.added-message')); return redirect()->route('classes.index'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $class = ClassModel::findOrFail($id); return view("{$this->viewPath}.show", [ 'title' => trans('main.show') . ' ' . trans('main.class') . ' : ' . $class->name, 'show' => $class, ]); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $class = ClassModel::findOrFail($id); return view("{$this->viewPath}.edit", [ 'title' => trans('main.edit') . ' ' . trans('main.class') . ' : ' . $class->name, 'edit' => $class, ]); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(ClassesRequest $request, $id) { $class = ClassModel::find($id); $class->name = $request->name; $class->slug = $request->slug; $class->save(); session()->flash('success', trans('main.updated')); return redirect()->route('classes.show', [$class->id]); } /** * Remove the specified resource from storage. * * @param int $id * @param bool $redirect * @return \Illuminate\Http\Response */ public function destroy($id, $redirect = true) { $class = ClassModel::findOrFail($id); $class->delete(); if ($redirect) { session()->flash('success', trans('main.deleted-message')); return redirect()->route('classes.index'); } } /** * Remove the multible resource from storage. * * @param array $data * @return \Illuminate\Http\Response */ public function multi_delete(Request $request) { if (count($request->selected_data)) { foreach ($request->selected_data as $id) { $this->destroy($id, false); } session()->flash('success', trans('main.deleted-message')); return redirect()->route('classes.index'); } } }
true
ee88b31afd38b19d504954085e6204affe827069
PHP
souleymane91/gestionLoyer.com
/src/SMB/LoyerBundle/Controller/PavionController.php
UTF-8
7,293
2.515625
3
[]
no_license
<?php //src\SMB\LoyerBundle\Controller\PavionController.php namespace SMB\LoyerBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Doctrine\Common\Collections\ArrayCollection; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security; use SMB\LoyerBundle\Entity\Pavion; use SMB\LoyerBundle\Form\PavionType; class PavionController extends Controller{ /*********************************************************** * l'action index qui permet de lister tous les pavions ***********************************************************/ public function indexAction(Request $request){ $listPavions = Pavion::listPavions($this); return $this->render("SMBLoyerBundle:Pavion:index.html.twig",array( 'listPavions' => $listPavions )); } /**************************************************************************** l'action add qui permet d'ajouter un nouveau pavion **********************************************************************/ public function addAction(Request $request){ //création de l'objet pavion $pavion = new Pavion(); //si nous avons une requête ajax, elle sera traité ici if($request->isXmlHttpRequest()){ $requete = $request->request->get('requete'); if($requete == "affichage"){ //création du formulaire d'ajout d'un pavion $form = $this->get('form.factory')->create(new PavionType(),$pavion); return $this->render("SMBLoyerBundle:Pavion:add.html.twig",array( 'form' => $form->createView() )); } else{ if($requete == "ajout"){ $nom_pavion = $request->request->get('nom_pavion'); $pavion->setLibelle($nom_pavion); $em = $this->getDoctrine() ->getManager(); //vérifions si ce pavion n'existe pas dans la base de données if(!$pavion->existe($this)){ $existe = false; $em->persist($pavion); $em->flush(); } else{//ce pavion est dans la base de données //vérifions si c'est supprimé ou pas if($pavion->estSupprime($this)){ //on le restaure $pavion->restaurer($this); $existe = false; } else{//le pavion existe et n'a pas été supprimé $existe = true; } } //on envoie la liste des pavions $listPavions = Pavion::listPavions($this); return $this->render("SMBLoyerBundle:Pavion:index.html.twig",array( 'listPavions' => $listPavions, 'erreur' => $existe )); } } } else{ throw new Exception("Pas de Requete envoyée!",1); } } /********************************************************************** l'action edit qui permet de modifier les informations d'un pavion **********************************************************************/ public function editAction($id,Request $request){ //création de l'objet pavion $pavion = new Pavion(); //on recupère l'objet pavion à editer $pavion = $this->getDoctrine() ->getManager() ->getRepository("SMBLoyerBundle:Pavion") ->find($id); //si nous avons une requête ajax, elle sera traité ici if($request->isXmlHttpRequest()){ //on recupère le type de la requete $requete = $request->request->get('requete'); //si on veut afficher le formulaire de modification if($requete == "affichage"){ //création du formulaire de modification d'un pavion $form = $this->get('form.factory')->create(new PavionType(),$pavion); return $this->render("SMBLoyerBundle:Pavion:edit.html.twig",array( 'id' => $id, 'form' => $form->createView() )); } else{ //si on veut modifier un pavion if($requete == "modification"){ $nom_pavion = $request->request->get('nom_pavion'); $pavion->setLibelle($nom_pavion); $em = $this->getDoctrine() ->getManager(); $em->flush(); //on envoie la liste des pavions $listPavions = Pavion::listPavions($this); return $this->render("SMBLoyerBundle:Pavion:index.html.twig",array( 'listPavions' => $listPavions )); } } } else{ throw new Exception("Pas de Requete envoyée!",1); } } /********************************************************************* * l'action delete qui permet de supprimer un pavion *********************************************************************/ public function deleteAction($id,Request $request){ //si nous avons une requête ajax, elle sera traité ici if($request->isXmlHttpRequest()){ //on recupère la liste des pavions à supprimer $listPavions = json_decode($request->request->get('listPavions')); $nbre = $request->request->get('nbre'); for ($i = 0; $i<$nbre; $i++){ $ident = $listPavions[$i]; $this->getDoctrine() ->getManager() ->getRepository("SMBLoyerBundle:Pavion") ->supprimer_pavion($ident); } //on retourne la liste de tous les pavions $listPavion = Pavion::listPavions($this); return $this->render("SMBLoyerBundle:Pavion:index.html.twig",array( 'listPavions' => $listPavion )); } else{ throw new \Exception("Pas de requête!",1); } } }
true
171e05d358d91dfbb8c0e55a11641f809fada64b
PHP
lymslive/expcode
/php/popen.php
UTF-8
103
2.578125
3
[]
no_license
<?php $file = popen("/bin/ls", 'r'); while (!feof($file)) { echo fgets($file); } pclose($file); ?>
true
257b5637e19ff7c3eeaecea9aae7f4e7fc2f9f67
PHP
Vlad5421/task_manger_mini
/Models/Model.php
UTF-8
628
2.796875
3
[]
no_license
<?php class Model { protected $pdo; public function __construct(){ $dsn = 'mysql:dbname=task_bee;host=127.0.0.1;charset=UTF8'; $user = 'pma'; $password = 'pmaPassword'; $opt = [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => false, ]; try { $this->pdo = new PDO($dsn, $user, $password, $opt); } catch (PDOException $e) { echo 'Подключение не удалось: ' . $e->getMessage(); } } }
true
b1da6f3cbb8ae4886b617bdb38707402050d743e
PHP
jorgitodf/pizzaria
/app/Models/Uf.php
UTF-8
1,907
2.75
3
[]
no_license
<?php namespace App\Models; use Core\BaseModel; use PDO; use PDOException; class Uf extends BaseModel { protected $table = "tb_uf"; private $sigla_uf; private $idUf; private $uf = array(); /** * Uf constructor. * @param $sigla_uf */ public function __construct($pdo, $sigla_uf) { parent::__construct($pdo); $this->sigla_uf = $sigla_uf; } public function getTable() { return $this->table; } /** * @param type $id * @return type */ public function setUf($id) { $this->idUf = $id; try { $query = "SELECT id_uf, sigla_uf FROM {$this->table} WHERE id_uf = ?"; $stmt = $this->pdo->prepare($query); $stmt->bindValue(1, $this->idUf, PDO::PARAM_INT); $stmt->execute(); if($stmt->rowCount() > 0) { $this->uf = $stmt->fetch(); $stmt->closeCursor(); } } catch (PDOException $exc) { if ($exc->getCode() == '42S02') { echo "A Tabela <b>{$this->table}</b> Ainda Não Existe.."; } exit; } } public function getUfCidade() { if (isset($this->uf)) { return $this->uf; } else { return false; } } public function getAllUf() { try { $query = "SELECT * FROM {$this->table}"; $stmt = $this->pdo->prepare($query); $stmt->execute(); $result = $stmt->fetchAll(); $stmt->closeCursor(); return $result; } catch (PDOException $exc) { if ($exc->getCode() == '42S02') { echo "A Tabela <b>{$this->table}</b> Ainda Não Existe.."; } exit; } } }
true
97704946ac0bbbe328994b8dc875171a11ca9d97
PHP
diego-ninja/blackmine
/src/Model/Project/File.php
UTF-8
1,186
2.671875
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); namespace Blackmine\Model\Project; use Blackmine\Model\FetchableInterface; use Blackmine\Model\Identity; use Blackmine\Model\User\User; use Carbon\CarbonImmutable; /** * @method setFilename(string $filename): void * @method setToken(string $token): void * @method setVersion(Version $version): void * @method setDescription(string $description): void * * @method string getFilename() * @method int getFilesize() * @method string getContentType() * @method string getDescription() * @method string getContentUrl() * @method User getUser() * @method Version getVersion() * @method string getDigest() * @method int getDownloads() * @method CarbonImmutable getCreatedOn() */ class File extends Identity implements FetchableInterface { public const ENTITY_NAME = "file"; protected string $filename; protected int $filesize; protected string $content_type; protected string $description; protected string $content_url; protected User $author; protected ?Version $version; protected string $digest; protected int $downloads; protected string $token; protected CarbonImmutable $created_on; }
true
1e34f20dac5d49120a52cb72519360702f63d0db
PHP
Sanchita-12345/APIATO_NEW_PROJECT
/app/Containers/AppSection/Bloguser/Tasks/DeleteBloguserTask.php
UTF-8
674
2.546875
3
[ "MIT" ]
permissive
<?php namespace App\Containers\AppSection\Bloguser\Tasks; use App\Containers\AppSection\Bloguser\Data\Repositories\BloguserRepository; use App\Ship\Exceptions\DeleteResourceFailedException; use App\Ship\Parents\Tasks\Task; use Exception; class DeleteBloguserTask extends Task { protected BloguserRepository $repository; public function __construct(BloguserRepository $repository) { $this->repository = $repository; } public function run($id): ?int { try { return $this->repository->delete($id); } catch (Exception $exception) { throw new DeleteResourceFailedException(); } } }
true
d12a4c9d4316fd678b9176e68e9741e263eca56d
PHP
benetta-cheng/ibm2104-assignment
/staff/schedule_search-copilot.php
UTF-8
2,776
2.5625
3
[]
no_license
<?php require('validateLogin.php'); ?> <html> <head> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" /> <?php require('../head.php'); require('navbar.php'); ?> <title>Flight Team | Search Co-Pilot</title> </head> <body> <div class="container"> <h3>Flight Team | Search Co-Pilot</h3> <p>Please enter the co-pilot's name or their staff id to search for a pilot</p> <?php $scheduleID = $_GET['id']; ?> <form action="schedule_search-copilot.php" method="get"> <div class="form-row"> <!-- Flight Number Search --> <div class="form-group col-md-6"> <label for="pilotName">Co-Pilot Name</label> <input type="text" class="form-control" name="coPilotName"> </div> <!-- Flight Status Search --> <div class="form-group col-md-6"> <label for="staffID">Staff ID</label> <input type="text" class="form-control" name="staffID"> </div> </div> <input type="hidden" class="form-control" name="id" value=<?php echo $_GET['id'] ?>> <input type="submit" class="btn btn-primary" value="Search"> </form> <?php //Connection to database establish $connection = new mysqli("localhost", "admin", null, "ibm2104_assignment"); if ($connection->connect_error) { die("Connection failed: " . $connection->connect_error); } echo '<table class = "table">'; echo '<thead class="thead-light">'; echo '<tr>'; echo '<th scope="col">Staff ID</th>'; echo '<th scope="col">Staff Name</th>'; echo '<th scope="col">Email</th>'; echo '</tr>'; echo '</thead>'; $staffQuery = "SELECT * FROM staff WHERE role = 1"; if (!empty($_GET['coPilotName'])) { $filterString[] = "staff_name LIKE '%" . $_GET['coPilotName'] . "%'"; } if (!empty($_GET['staffID'])) { $filterString[] = "id = '" . $_GET['staffID'] . "'"; } if (!empty($filterString)) { $staffQuery = $staffQuery . " AND " . implode(" AND ", $filterString); } $resultStaffQuery = $connection->query($staffQuery); while ($staffDetails = mysqli_fetch_assoc($resultStaffQuery)) { echo "<tr><td>" . $staffDetails['id'] . "</td>"; echo "<td>" . $staffDetails['staff_name'] . "</td>"; echo "<td>" . $staffDetails['email'] . "</td>"; echo "</tr>"; } echo '</table>'; $connection->close(); ?> </div> </body> </html>
true
98eef066c97f6a6834675a30af71e2645e5d8770
PHP
jiangbajin/insurance
/src/common/InvalidInstanceException.php
UTF-8
537
2.6875
3
[]
no_license
<?php /** * Created by PhpStorm. * User: 江艺勤 * Date: 2020/10/27 * Time: 14:10 */ namespace cncn\insurance\common; class InvalidInstanceException extends \Exception { /** * @var array */ public $raw = []; /** * InvalidResponseException constructor. * @param string $message * @param integer $code * @param array $raw */ public function __construct($message, $code = 0, $raw = []) { parent::__construct($message, intval($code)); $this->raw = $raw; } }
true
a5ee26f2cb14c3a6af98c0bfea23e16ead0df1f0
PHP
decanus/jukebox
/web/Framework/src/Backends/SQL/PostgreDatabaseBackend.php
UTF-8
1,800
2.84375
3
[]
no_license
<?php namespace Jukebox\Framework\Backends { class PostgreDatabaseBackend { /** * @var \PDO */ private $PDO; public function __construct(PDO $PDO) { $this->PDO = $PDO; } public function fetchAll(string $sql, array $parameters = []) { $statement = $this->prepare($sql); $statement->execute($parameters); return $statement->fetchAll(\PDO::FETCH_ASSOC); } public function fetch(string $sql, array $parameters = []) { $statement = $this->prepare($sql); $statement->execute($parameters); return $statement->fetch(\PDO::FETCH_ASSOC); } public function insert(string $sql, array $parameters = []): bool { $statement = $this->prepare($sql); return $statement->execute($parameters); } public function lastInsertId($name = null) { return $this->PDO->lastInsertId($name); } public function beginTransaction() { $this->PDO->beginTransaction(); } public function commit() { return $this->PDO->commit(); } public function rollBack() { $this->PDO->rollBack(); } public function inTransaction(): bool { return $this->PDO->inTransaction(); } public function prepare(string $statement): \PDOStatement { try { return $this->PDO->prepare($statement); } catch (\PDOException $e) { throw new \Exception('PDO failed to prepare the statement "' . $statement . '"', 0, $e); } } } }
true
2d4ae9909834001eeeabf76a4edc23c79b1d0e8a
PHP
JonasDoebertin/php-geofox-gti-client
/src/Response/ListStations.php
UTF-8
1,731
3.03125
3
[ "MIT" ]
permissive
<?php namespace JdPowered\Geofox\Response; use JdPowered\Geofox\Data; use JdPowered\Geofox\Objects\StationListEntry; class ListStations extends Base { /** * @var string */ protected $dataReleaseId; /** * @var \JdPowered\Geofox\Objects\StationListEntry[] */ protected $stations; /** * Create a new instance and fill it from a JSON object. * * @param int $statusCode * @param \JdPowered\Geofox\Data $data */ public function __construct(int $statusCode, Data $data) { parent::__construct($statusCode, $data); $this->setDataReleaseId($data->dataReleaseID) ->setStations($data->stations); } /** * Get data release id. * * @return string */ public function getDataReleaseId(): string { return $this->dataReleaseId; } /** * Set data release id. * * @param string $dataReleaseId * @return \JdPowered\Geofox\Response\ListStations */ protected function setDataReleaseId(string $dataReleaseId): self { $this->dataReleaseId = $dataReleaseId; return $this; } /** * Get stations. * * @return \JdPowered\Geofox\Objects\StationListEntry[] */ public function getStations(): array { return $this->stations ?? []; } /** * Set stations. * * @param array|null $stations * @return \JdPowered\Geofox\Response\ListStations */ protected function setStations(?array $stations): self { $this->stations = array_map(function (Data $station) { return new StationListEntry($station); }, $stations ?? []); return $this; } }
true
779ab6f6931a9739c237dc97805f3da9dc355eeb
PHP
lxdnz254/BIT695_TM4
/www/includes/helpers.inc.php
UTF-8
2,135
3.078125
3
[]
no_license
<?php /* ensure text doesnot get code injection */ function html($text) { return htmlspecialchars($text, ENT_QUOTES, 'UTF-8'); } /* Output html to text */ function htmlout($text) { echo html($text); } /* Convert from markdown to html */ function markdown2html($text) { $text = html($text); // Convert plain-text formatting to HTML // strong emphasis $text = preg_replace('/__(.+?)__/s', '<strong>$1</strong>', $text); $text = preg_replace('/\*\*(.+?)\*\*/s', '<strong>$1</strong>', $text); // emphasis $text = preg_replace('/_([^_]+)_/', '<em>$1</em>', $text); $text = preg_replace('/\*([^\*]+)\*/', '<em>$1</em>', $text); // Convert Windows (\r\n) to Unix (\n) $text = str_replace("\r\n", "\n", $text); // Convert Macintosh (\r) to Unix (\n) $text = str_replace("\r", "\n", $text); // Paragraphs $text = '<p>' . str_replace("\n\n", '</p><p>', $text) . '</p>'; // Line breaks $text = str_replace("\n", '<br>', $text); // Url links $text = preg_replace( '/\[([^\]]+)]\(([-a-z0-9._~:\/?#@!$&\'()*+,;=%]+)\)/i', '<a href="$2">$1</a>', $text); return $text; } /* Markdown to text function */ function markdownout($text) { echo markdown2html($text); } /* Replace {{tags}} in html form */ function replace_tags($template, $placeholders){ return str_replace(array_keys($placeholders), $placeholders, $template); } /* Prepare statements for all tables */ function statement_prep($connection, $sql) { if($stmt = $connection->prepare($sql)) { /*No Bind params */ /*execute statement*/ $stmt->execute(); /*get result*/ $result=$stmt->get_result(); $stmt->close(); } else { $result=null; echo 'Prepared statement error: %s\n'. $connection->error; } return $result; } /* stores a temporary file on users device */ function temporaryFile($name, $content) { $file = trim(sys_get_temp_dir(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . ltrim($name, DIRECTORY_SEPARATOR); file_put_contents($file, $content); register_shutdown_function(function() use($file) { unlink($file); }); return $file; }
true
6e595f80108a1997abc844084effa3b29baf37e3
PHP
pepesho/apahotel
/blog/app/Http/Controllers/MemberController.php
UTF-8
4,237
2.53125
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers; use App\Member; use App\Ledger; use Illuminate\Http\Request; class MemberController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(Request $request) { $query = Member::withCount('borrows'); if ($request->id) { $query->where('id', $request->id); } if ($request->email) { $query->where('email', 'LIKE', '%'.$request->email.'%'); } if($request->sort=='asc'){ $members = $query->orderBy('id')->paginate(15); } elseif($request->sort=='desc') { $members = $query->orderBy('id', 'desc')->paginate(15); } else { $members = $query->orderBy('id')->paginate(15); } //$members = $query->orderBy('id')->paginate(15); return view('members.index', ['members'=>$members]); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $member = new Member; return view('members.create', ['member'=>$member]); } public function confirm(Request $request) { $this->validate($request,[ 'name' => 'required|max:255', 'postal' => 'required|integer|max:10000000', 'address' => 'required|max:255', 'tel' => 'required|max:13', 'email' => 'required|email|max:255|unique:members,email', 'birthday' => 'required|date' ]); $member = $request; return view('members/confirm', ['member' => $member]); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $this->validate($request, [ 'name' => 'required|max:255', 'postal' => 'required|integer|max:10000000', 'address' => 'required|max:255', 'tel' => 'required|max:13', 'email' => 'required|email|max:255|unique:members,email', 'birthday' => 'required|date' ]); $member = new Member; $member->name=$request->name; $member->postal=$request->postal; $member->address=$request->address; $member->tel=$request->tel; $member->email=$request->email; $member->birthday=$request->birthday; $member->save(); return redirect(route('members.index'))->with('msg', '会員が登録されました'); } /** * Display the specified resource. * * @param \App\Member $member * @return \Illuminate\Http\Response */ public function show(Member $member) { return view('members.show', ['member'=>$member]); } /** * Show the form for editing the specified resource. * * @param \App\Member $member * @return \Illuminate\Http\Response */ public function edit(Member $member) { return view('members.edit', ['member'=>$member]); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Member $member * @return \Illuminate\Http\Response */ public function update(Request $request, Member $member) { $this->validate($request, [ 'name' => 'required|max:255', 'postal' => 'required|integer|max:11', 'address' => 'required|integer|max:255', 'tel' => 'required|integer|max:255', 'email' => 'required|email|max:255|unique', 'birthday' => 'required|date' ]); $member->update($request->all()); return redirect(route('members.show', $member)); } /** * Remove the specified resource from storage. * * @param \App\Member $member * @return \Illuminate\Http\Response */ public function destroy(Member $member) { $member->delete(); return redirect(route('members.index'))->with('msg', '会員が登録されました'); } }
true
46b8c6656065838d6b2df25a6e9f8e81c96cd801
PHP
wangwen1220/isweek.cn
/Application/Home/Controller/AllCategorysController.class.php
UTF-8
1,272
2.515625
3
[]
no_license
<?php namespace Home\Controller; use Think\Controller; // + ---------- ---------- // | 这是所有分类控制器 // | @author tan<admin@163.com> // + ---------- ---------- class AllCategorysController extends CommonController { public function __construct() { parent::__construct (); $this->assign ( "css_style", "category" ); $this->assign ( 'title', 'Industrial Products Categories - ISweek.com' ); $this->assign ( 'description', 'Industrial products categories of ISweek.com' ); $this->assign ( 'keywords', 'product categories, product catalog' ); } // + ---------- ---------- // | 这是默认方法 // | @author tan<admin@163.com> // + ---------- ---------- public function index() { // 所有允许在前台显示的菜单 $homepage_categorys = $this->get_homepage_show_categorys (); // 将结果集排序 $homepage_categorys = $this->leipi_to_tree ( $homepage_categorys ); $this->assign ( 'homepage_categorys', $homepage_categorys ); $this->assign ( 'title', '所有类目-工采网' ); $this->assign ( 'keywords', '产品目录,产品类目,工业品目录,工业品类目' ); $this->assign ( 'description', 'ISweek工采网所有类目' ); $this->display (); } }
true
8e2c74776ab4609c0e6d5baf5e4cc5dc2bb16978
PHP
jnsjrvs/phpprms
/php-file-01.php
UTF-8
138
3.015625
3
[]
no_license
<?php $m = [1, 4, 7, 11, 23, 55]; $s = implode(',', $m); $f = fopen('php-file-01.txt', 'w'); fwrite($f, $s); fclose($f); echo 'ok';
true
42868e9556f1d001c21d03e0dcf46d5515768c52
PHP
reneroboter/gli
/src/App.php
UTF-8
1,359
2.703125
3
[]
no_license
<?php namespace reneroboter\gli; use League\CLImate\CLImate; use ReflectionException; use reneroboter\gli\Command\CommandInterface; use reneroboter\gli\Service\HttpService; class App { /** * @var CLImate $climate */ private $climate; /** * @var array */ private $config; public function __construct(CLImate $climate, array $config) { $this->climate = $climate; $this->config = $config; } public function run(string $command): void { $namespace = 'reneroboter\gli\Command\\'; $className = $namespace . ucfirst($command) . 'Command'; // todo prepare git provider and pass it to $className() ... try { /** @var CommandInterface $className */ $reflection = new \ReflectionClass($className); if ($reflection->isInstantiable()) { $request = (new $className($this->climate))->handle(); if (!$request) { $this->climate->error('Something get wrong ...'); exit(1); } $httpService = new HttpService($this->climate, $this->config); $httpService->process($request); } } catch (ReflectionException $e) { $this->climate->error('Error: ' . $e->getMessage()); } } }
true
60b5308845d1b28c3040a44e4e41d6904aa77427
PHP
hmazter/advent-of-code-solutions
/2017/day8/test.php
UTF-8
2,693
3.09375
3
[]
no_license
<?php declare(strict_types=1); require_once './functions.php'; class Day8Test extends \PHPUnit\Framework\TestCase { /** * @test */ public function parseInstruction() { $result = parseInstruction('b inc 5 if a > 1'); self::assertEquals('b', $result['register']); self::assertEquals('inc', $result['operation']); self::assertEquals('5', $result['value']); self::assertEquals('a', $result['condition']['register']); self::assertEquals('>', $result['condition']['operator']); self::assertEquals('1', $result['condition']['value']); } /** * @test * @dataProvider evaluateConditionProvider * @param bool $expected * @param array $register * @param array $condition */ public function evaluateCondition(bool $expected, array $register, array $condition) { self::assertEquals($expected, evaluateCondition($condition, $register)); } public function evaluateConditionProvider() { return [ [false, [], ['register' => 'a', 'operator' => '>', 'value' => '5']], [false, ['a' => 0], ['register' => 'a', 'operator' => '>', 'value' => '5']], [true, [], ['register' => 'b', 'operator' => '<', 'value' => '5']], [true, ['a' => 0], ['register' => 'b', 'operator' => '<', 'value' => '5']], [true, ['a' => 1], ['register' => 'a', 'operator' => '>=', 'value' => '1']], ]; } /** * @test */ public function runInstruction_set1() { $register = []; runInstruction('b inc 5 if a > 1', $register); self::assertEmpty($register); } /** * @test */ public function runInstruction_set2() { $register = []; runInstruction('a inc 1 if b < 5', $register); self::assertArrayHasKey('a', $register); self::assertEquals(1, $register['a']); } /** * @test */ public function runInstruction_set3() { $register = ['a' => 1]; runInstruction('c dec -10 if a >= 1', $register); self::assertArrayHasKey('a', $register); self::assertEquals(1, $register['a']); self::assertArrayHasKey('c', $register); self::assertEquals(10, $register['c']); } /** * @test */ public function solveDay8() { $input = [ 'b inc 5 if a > 1', 'a inc 1 if b < 5', 'c dec -10 if a >= 1', 'c inc -20 if c == 10', ]; solveDay8($input, $endMax, $runningMax); self::assertEquals(1, $endMax); self::assertEquals(10, $runningMax); } }
true
7df0f915d7602b061fcfc6719308489074b88bde
PHP
msoderblom/ME-CMS
/admin/processing_post.php
UTF-8
803
2.5625
3
[]
no_license
<?php $success = true; if ($_SERVER['REQUEST_METHOD'] == 'POST') { $title = htmlspecialchars($_POST['title']); $body = $_POST['body']; $body = '<p>' . preg_replace('#(<br\s*?/?>\s*?){2,}#', '</p>' . "\n" . '<p>', nl2br($body)) . '</p>'; $body = htmlspecialchars($body); if (isset($_POST['embedded_iframe']) && !empty($_POST['embedded_iframe'])) { $iframe = ($_POST['embedded_iframe']); $iframe = htmlspecialchars($iframe); } require_once 'img_check.php'; if ($success) { $sql = "INSERT INTO mecms_posts (title, body, iframe, img) VALUES (:title, :body, :iframe, :img)"; $stmt = $db->prepare($sql); $stmt->bindParam(':title', $title); $stmt->bindParam(':body', $body); $stmt->bindParam(':iframe', $iframe); $stmt->bindParam(':img', $img); $stmt->execute(); header('Location:index.php'); } }
true
22186caf324369b8f266636b7bc0df19253451a8
PHP
m4di/founders-network-website
/router.php
UTF-8
614
3.21875
3
[]
no_license
<?php class Router { function __construct($routes) { /** * Get the requested uri and search for it against the $routes array, * displaying the corresponding file if possible * * @param array $routes */ $uri = isset($_GET['uri']) ? '/' . trim($_GET['uri'], '/') : '/'; foreach ($routes as $key => $value) { if ($key === $uri) { if (file_exists($value)) { require_once $value; exit(); } else { echo "<h1>The requested file exists but could not be found.</h1>"; exit(); } } } echo "<h1>404 File not found</h1>"; exit(); } }
true
e1caa776a45b9ab90059427a78497212ec706000
PHP
LuisCabrero/blog-symfony
/src/BlogBundle/Controller/EntryController.php
UTF-8
2,034
2.5625
3
[ "MIT" ]
permissive
<?php namespace BlogBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Session\Session; // Modelos use BlogBundle\Entity\Entry; // Formulario use BlogBundle\Form\EntryType; class EntryController extends Controller { private $session; public function __construct(){ $this->session = new Session(); } public function addAction(Request $request){ $entry = new Entry(); $form = $this->createForm(EntryType::class, $entry); $form->handleRequest($request); if($form->isSubmitted()){ if($form->isValid()){ $em = $this->getDoctrine()->getEntityManager(); $category_repo = $em->getRepository("BlogBunde:Category"); $entry = new Entry(); $entry->setTitle($form->get("title")->getData()); $entry->setContent($form->get("content")->getData()); $entry->setStatus($form->get("status")->getData()); $entry->setImage(null); $category = $category_repo->find($form->get("category")->getData()); $entry->setCategory($category); $user = $this->getUser(); $entry->setUser($user); $em->persist($entry); $flush = $em->flush(); if($flush == null){ $status = "La entrada se ha creado correctamente"; }else{ $status = "La entrada no se ha podido crear"; } }else{ $status = "Rellena los campos correctamente!"; } $this->session->getFlashBag()->add("status", $status); return $this->redirectToRoute("blog_index_entry"); } return $this->render( 'BlogBundle:Entry:add.html.twig', array( "form" => $form->createView() ) ); } }
true
bf28c59b74aad34a242ef7d13c1f20c913c57870
PHP
marcoscodnet/matriculados
/classes/com/cpiq/action/cdtregistrations/AddRegistroChequearAction.Class.php
UTF-8
1,145
2.65625
3
[]
no_license
<?php /** * Se chequea si un matriculado está cargado * * @author Marcos * @since 28-10-2013 * */ class AddRegistroChequearAction extends CdtAction{ /** * (non-PHPdoc) * @see CdtAction::execute(); */ public function execute(){ $result = ""; try{ $documento = CdtUtils::getParam("documento"); $valido = true; //TODO validar $oCriteria = new CdtSearchCriteria(); $oCriteria->addFilter('nroDocumento', $documento, '='); $managerMatriculado = ManagerFactory::getMatriculadoManager(); $oMatriculado = $managerMatriculado->getEntity($oCriteria); if (empty($oMatriculado)) { $valido=false; $mensajes=CPIQ_SECURE_MSG_REGISTRATION_MATRICULADO_CONTROL_ERROR; } else $mensajes=CPIQ_SECURE_MSG_REGISTRATION_MATRICULADO_CONTROL_1.' '.$oMatriculado->getApellido().', '.$oMatriculado->getNombre().' '.CPIQ_SECURE_MSG_REGISTRATION_MATRICULADO_CONTROL_2; $result['valido'] = $valido; $result['mensajes'] = $mensajes; }catch(Exception $ex){ $result['error'] = $ex->getMessage(); } echo json_encode( $result ); return null; } }
true
f5874a950781480f239623b0b7a57349f0f959e8
PHP
khelle/surume
/src/Loop/LoopInterface.php
UTF-8
1,958
3.078125
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
<?php namespace Surume\Loop; use Surume\Loop\Timer\TimerInterface; /** * @event start * @event stop */ interface LoopInterface { /** * Register a listener to be notified when a stream is ready to read. * * @param resource $stream * @param callable $listener */ public function addReadStream($stream, callable $listener); /** * Register a listener to be notified when a stream is ready to write. * * @param resource $stream * @param callable $listener */ public function addWriteStream($stream, callable $listener); /** * Remove the read event listener for the given stream. * * @param resource $stream */ public function removeReadStream($stream); /** * Remove the write event listener for the given stream. * * @param resource $stream */ public function removeWriteStream($stream); /** * Remove all listeners for the given stream. * * @param resource $stream */ public function removeStream($stream); /** * @param float $interval * @param callable $callback * @return TimerInterface */ public function addTimer($interval, callable $callback); /** * @param float $interval * @param callable $callback * @return TimerInterface */ public function addPeriodicTimer($interval, callable $callback); /** * @param TimerInterface $timer */ public function cancelTimer(TimerInterface $timer); /** * @param TimerInterface $timer * @return bool */ public function isTimerActive(TimerInterface $timer); /** * @param callable $listener */ public function startTick(callable $listener); /** * @param callable $listener */ public function beforeTick(callable $listener); /** * @param callable $listener */ public function afterTick(callable $listener); }
true
328871358392fbfd4b84bf14c8ca3e4c6d60611b
PHP
linkorb/timeular-client-php
/src/Client.php
UTF-8
1,870
2.796875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<?php namespace Timeular; use GuzzleHttp\Client as GuzzleClient; class Client { protected static $baseUrl = 'https://api.timeular.com/api/v2/'; protected $guzzle; // prevent direct instantiation protected function __construct() { // noop } public static function getToken($key, $secret) { $guzzle = new GuzzleClient(); $url = self::$baseUrl . '/developer/sign-in'; $data = [ 'apiKey' => $key, 'apiSecret' => $secret, ]; $res = $guzzle->request( 'POST', $url, [ 'headers' => [ 'Accept' => 'application/json', ], 'json' => $data, ] ); $body = $res->getBody(); $data = json_decode((string)$body, true); $token = $data['token']; return $token; } public static function createWithToken($token) { $client = new self(); $client->guzzle = new GuzzleClient( array( 'base_uri' => self::$baseUrl, 'headers' => [ 'Accept' => 'application/json', 'Authorization' => 'Bearer ' . $token ] ) ); return $client; } public function get($path) { $res = $this->guzzle->request('GET', $path); $body = $res->getBody(); $data = json_decode((string)$body, true); return $data; } public function post($path, $arguments = []) { $res = $this->guzzle->request( 'POST', $path, [ 'json' => $arguments ] ); $body = $res->getBody(); $data = json_decode((string)$body, true); return $data; } }
true
17da0618836f7bde057fff41c484027f30f75f09
PHP
morganevlrd/ISCC-2020-J07
/double-tableaux.php
UTF-8
366
2.640625
3
[]
no_license
<?php $panier = array ( array ("T-shirt rouge", 15,50,5), array ("T-shirt vert", 15.50, 6), array ("T-Shirt argent", 15.50, 8), array ("Short bleu", 16.50, 5), array ("Short vert",19.99,5) array ("Veste argent", 19.99, 10) array ("Veste marron", 35,3), ); function affichage_panier ($panier){ foreach ($panier as $element) { } }
true
6c96bc6a5fd8b8479c5d2b0cc5486f71467ee185
PHP
danter91/Programacion_Web
/Programacion_Web2/clases/bd.class.php
UTF-8
2,692
2.8125
3
[]
no_license
<?php //session_start(); // clase para el manejo de la conexion a base de datos date_default_timezone_set('America/Bogota'); class bd{ function bd(){ $this->pwd=""; $this->usuario="root"; $this->servidor="127.0.0.1"; $this->bd = "palopalito"; $this->conexion=""; $this->error=""; $this->sentencia=""; $this->muestra=0; $this->resultado=""; $this->ultimo_id=""; if(isset($_SESSION['user'])){ $this->usuario_accion= $_SESSION['user']; }else{ $this->usuario_accion= -1; } } // realiza la conexion a base de datos function fconectar(){ $this->conexion = new mysqli($this->servidor, $this->usuario, $this->pwd, $this->bd); if ($this->conexion->connect_error) { die('Error de Conexión (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error); } } //cierra la conexion a una base de datos function fdesconectar(){ $this->conexion->close(); $this->conexion=""; $this->error=""; } //ejecuta una sentencia sql function fsentencia(){ //$this->muestra=1; $this->resultado=""; $temp_resultado=""; $temp = explode(" ",$this->sentencia); $temp[0] = strtoupper($temp[0]); $this->fconectar(); if ($this->muestra == 1) echo $this->sentencia.";<br>"; $result = $this->conexion->query($this->sentencia); if (!$result){ $this->error = $this->conexion->error; $this->debug(); $this->fdesconectar(); return false; }else{ if ($temp[0] == "INSERT"){ //ejecuto un select $this->ultimo_id = $this->conexion->insert_id; }else if ($temp[0] == "SELECT" || $temp[0] == "SHOW"){ //ejecuto un select $temp_while=""; while($temp_while = $result->fetch_array()){ $temp_resultado[] = $temp_while; } if ($temp_resultado == ""){ $this->resultado = NULL; }else{ $this->resultado = $temp_resultado; } } if ($this->conexion->warning_count) { if ($result = $this->conexion->query("SHOW WARNINGS")) { $this->error= $result->fetch_row(); } } } if ($this->error != ""){ $this->debug(); die(); } //mysqli_free_result($result); $this->fdesconectar(); unset($temp,$result,$temp_while); } //trae los modulos del sistema function fmodulo(){ $this->sentencia="SELECT modulo_id,modulo_nombre FROM modulo ORDER BY modulo_orden ASC"; $this->fsentencia(); $this->modulo=$this->resultado; } //para mostrar como quedo el objeto function debug(){ $this->pwd=""; $this->usuario=""; $this->servidor=""; echo "<pre>"; print_r($this); echo "</pre>"; } function escapa(){ $this->fconectar(); $retorna=mysqli_real_escape_string($this->conexion,$this->escapar); $this->fdesconectar(); return $retorna; } } ?>
true
0e064a90c9f0999c5468f8d6d166fda5393d19dd
PHP
zbierajewski/SupportPress
/user-edit.php
UTF-8
4,800
2.640625
3
[]
no_license
<?php include_once( 'init.php' ); // Prevents non-admin from editing other users settings if ( !$current_user->has_cap( 'supportpressadmin' ) && $current_user->ID != $_GET['uid'] ) { wp_redirect( $site_url ); exit; } include( 'header.php' ); $uid = (int) $_GET['uid']; $this_user = get_user( $uid ); $message = ''; if ( isset( $_POST['save'] ) ) { $valid_roles = array( 'supporter', 'supportpressadmin' ); $valid_onclose = array( 'inbox', 'nextticket' ); $update_meta_flag = true; $display_name = isset( $_POST['displayname'] ) ? strip_tags( $_POST['displayname'] ) : ''; $user_email = isset( $_POST['email'] ) ? $_POST['email'] : ''; $user_role = in_array( $_POST['role'], $valid_roles ) ? $_POST['role'] : ''; $meta_onclose = in_array( $_POST['onclose'], $valid_onclose ) ? $_POST['onclose'] : ''; $signature = ( ! empty( $_POST['signature'] ) ) ? strip_tags( $_POST['signature'] ) : ''; // Update on close setting if ( ! empty( $meta_onclose ) && isset( $this_user->onclose ) && $this_user->onclose != $meta_onclose ) { if ( update_usermeta( $uid, 'onclose', $meta_onclose ) ) $message .= 'Ticket closed setting saved. '; else $message .= 'Error saving ticket closed setting. '; } // Update signature if ( ! empty( $signature ) && isset( $this_user->signature ) && $this_user->signature != $signature ) { if ( update_usermeta( $uid, 'signature', $signature ) ) $message .= 'Signature updated. '; else $message .= 'Error saving signature. '; } // Update role if ( ! empty( $user_role ) && ! $this_user->has_cap( $user_role ) ) { // quick hack to prevent accidental lockouts. See: // http://supportpress.trac.wordpress.org/ticket/64 if ( $current_user->ID == $this_user->ID ) { $message .= 'Error changing role. Demoting yourself is unhealthy!'; } else { $this_user->set_role( $user_role ); $message .= 'User role updated. '; } } // Validation if ( empty( $display_name ) ) { $message .= 'Display name is required. '; $update_meta_flag = false; } if ( empty( $user_email ) || ! is_email( $user_email ) ) { $message .= 'Email is required. '; $update_meta_flag = false; } // Update settings if ( ( $display_name != $this_user->display_name || $user_email != $this_user->user_email ) && $update_meta_flag ) { $update = array( 'display_name' => $display_name, 'user_email' => $user_email, 'plain_pass' => '' ); if ( !empty( $_POST['password1'] ) && !empty( $_POST['password2'] ) && $_POST['password1'] == $_POST['password2'] ) $update['user_pass'] = $_POST['password1']; $update_user = $wp_users_object->update_user( $uid, $update ); if ( $update_user ) { $message .= 'User settings saved. '; } else { $message .= 'Error saving message: ' . $db->last_error . ' '; } } } if ( $message ) { echo '<div id="message">' . esc_html( $message ) . '</div>'; } $updated_user = get_user( $uid ); ?> <form id="update-user" method="POST"> <h2>Edit user:</h2> <p> <label>Username:</label>&nbsp; <?php echo esc_html( $updated_user->user_login ); ?> </p> <p> <label for="password1">Password:</label> <input type="password" name="password1" id="password1" value=""/> </p> <p> <label for="password2">Confirm Password:</label> <input type="password" name="password2" value=""/> </p> <p> <label id="displayname">Display Name:</label> <input type="text" name="displayname" id="displayname" value="<?php echo esc_html( $updated_user->display_name ); ?>" /> </p> <p> <label for="email">Email:</label> <input type="text" name="email" id="email" value="<?php echo esc_html( $updated_user->user_email ); ?>" /> </p> <p> <label for="role">Role:</label> <select name="role" id="role"> <option value="supporter" <?php if ( !$updated_user->has_cap( 'supportpressadmin' ) ) echo 'selected="selected"'; ?>>Supporter</option> <option value="supportpressadmin" <?php if ( $updated_user->has_cap( 'supportpressadmin' ) ) echo 'selected="selected"'; ?>>Administrator</option> </select> </p> <p> <label for="onclose">After closing a ticket:</label> <select name="onclose" id="onclose"> <option value="inbox" <?php if ( isset( $updated_user->onclose ) && 'inbox' == $updated_user->onclose ) 'selected="selected"'; ?>>return to the inbox</option> <option value="nextticket" <?php if ( isset( $updated_user->onclose ) && 'nextticket' == $updated_user->onclose ) 'selected="selected"'; ?>>continue to next available ticket</option> </select> </p> <p> <label for="signature">Signature:</label> <textarea name="signature" id="signature"><?php if ( isset( $updated_user->signature ) ) echo esc_textarea( $updated_user->signature ); ?></textarea> </p> <input type="submit" name="save" value="Save" /> </form> <?php include( 'footer.php' );
true
3ee3b5ac5ece1c1fb119bc77327123c0ec714b99
PHP
omusico/jingbo
/code/admin/application/libraries/ProductsearchService.php
UTF-8
7,728
2.671875
3
[]
no_license
<?php defined('SYSPATH') OR die('No direct access allowed.'); /** * 商品搜索Service * * @author bin */ class ProductsearchService_Core extends DefaultService_Core { /* 兼容php5.2环境 Start */ private static $instance = NULL; //路由实例管理实例 private $serv_route_instance = NULL; // 获取单态实例 public static function get_instance(){ if(self::$instance === null){ $classname = __CLASS__; self::$instance = new $classname(); } return self::$instance; } /* 兼容php5.2环境 End */ /** * 更新搜索索引 * @param int $product_id * @param array $param('category_id','brand_id','title','brief','description') productsearch结构 */ public function update_single($product_id = 0,$param = array()) { $productsearch_struct = array(); if($product_id < 1) { return false; } if(count($param) > 0) { $productsearch_struct['product_id'] = (!empty($param['product_id']))?$param['product_id']:''; $productsearch_struct['category_id'] = (!empty($param['category_id']))?$param['category_id']:''; $productsearch_struct['brand_id'] = (!empty($param['brand_id']))?$param['brand_id']:''; $productsearch_struct['title'] = (!empty($param['title']))?$param['title']:''; $productsearch_struct['brief'] = (!empty($param['brief']))?$param['brief']:''; $productsearch_struct['description'] = (!empty($param['description']))?$param['description']:''; self::add($productsearch_struct); } else { $product = ProductService::get_instance()->get($product_id); if(is_array($product) && $product['id'] > 0) { $productsearch_struct['product_id'] = $product['id']; $productsearch_struct['category_id'] = $product['category_id']; $productsearch_struct['brand_id'] = $product['brand_id']; $productsearch_struct['title'] = $product['title']; $productsearch_struct['brief'] = $product['brief']; $productsearch_struct['description'] = ''; /* 获取产品描述 */ $query_struct = array ( 'where' => array ( 'product_id' => $product['id'] ) ); $productdescsection_service = ProductdescsectionService::get_instance(); $descsections = $productdescsection_service->query_assoc($query_struct); if(!empty($descsections)){ foreach($descsections as $val){ $productsearch_struct['description'] .= ' ' . $val['content']; } } $productsearch = $this->get_by_product_id($product_id); if(!empty($productsearch) && $productsearch['id'] > 0) { self::set($productsearch['id'],$productsearch_struct); } else { self::add($productsearch_struct); } } } } /** * 添加单条到产品搜索索引表 * @param int $product_id 产品ID * @param array $param('site_id','category_id','brand_id','title','brief','description') productsearch结构 * @return boolean */ public function add_single($product_id = 0,$param = array()) { $productsearch_struct = array(); if($product_id < 1) { return false; } if(count($param) > 0) { $productsearch_struct['product_id'] = (!empty($param['product_id']))?$param['product_id']:''; $productsearch_struct['category_id'] = (!empty($param['category_id']))?$param['category_id']:''; $productsearch_struct['brand_id'] = (!empty($param['brand_id']))?$param['brand_id']:''; $productsearch_struct['title'] = (!empty($param['title']))?$param['title']:''; $productsearch_struct['brief'] = (!empty($param['brief']))?$param['brief']:''; $productsearch_struct['description'] = (!empty($param['description']))?$param['description']:''; self::add($productsearch_struct); } else { $product = ProductService::get_instance()->get($product_id); if(is_array($product) && $product['id'] > 0) { $productsearch_struct['product_id'] = $product['id']; $productsearch_struct['category_id'] = $product['category_id']; $productsearch_struct['brand_id'] = $product['brand_id']; $productsearch_struct['title'] = $product['title']; $productsearch_struct['brief'] = $product['brief']; $productsearch_struct['description'] = ''; /* 获取产品描述 */ $query_struct = array ( 'where' => array ( 'product_id' => $product['id'] ) ); $productdescsection_service = ProductdescsectionService::get_instance(); $descsections = $productdescsection_service->query_assoc($query_struct); if(!empty($descsections)){ foreach($descsections as $val){ $productsearch_struct['description'] .= ' ' . $val['content']; } } self::add($productsearch_struct); } } } public function set_single($param) { /* static $attributes = array(); if (!empty($param['attributes'])) { $aids = array(); foreach ($param['attributes'] as $aid => $oids) { if (!isset($attributes[$aid])) { $aids[] = $aid; } } if (!empty($aids)) { $records = AttributeService::get_instance()->get_attribute_options(array('where' => array( 'id' => $aids, ))); foreach ($records as $record) { $attributes[$record['id']] = $record; } } foreach ($param['attributes'] as $aid => $oids) { if (isset($attributes[$aid])) { $options = $attributes[$aid]['options']; foreach ($oids as $oid) { if (isset($options[$oid])) { $param['title'] .= ' '.$options[$oid]['name']; } } } } } if (!empty($param['features'])) { // TODO 标题中加入特性值 } */ $search = ProductsearchService::get_instance()->query_row(array('where'=>array( 'product_id' => $param['product_id'], ))); if (empty($search)) { ProductsearchService::get_instance()->create($param); } else { ProductsearchService::get_instance()->set($search['id'], $param); } } /** * 根据商品搜索ID删除搜索内容 * @param int $id * @return throw */ public function delete_by_productsearch_id($id) { try{ $this->remove($id); }catch(MyRuntimeException $ex){ throw $ex; } } /** * 根据商品ID删除搜索内容 * @param int $id * @return throw */ public function delete_by_product_id($product_id) { $productsearch = ORM::factory('productsearch') ->where('product_id', $product_id) ->delete_all(); return $productsearch; } /** * 根据商品ID得到端口搜索详情 * @param int $product_id * @return array */ public function get_by_product_id($product_id) { $productsearch = ORM::factory('productsearch')->where(array('product_id'=>$product_id))->find(); return $productsearch->as_array(); } }
true
0f8c1e2ecaffeaca13be89f0872c2e8a404cfb92
PHP
michaelmeganet/crudphpcustomer
/ccf501/read-customer-info.php
UTF-8
975
2.625
3
[]
no_license
<?php include 'header.php'; if (isset($_GET['id'])) { $customer_info = $customer_obj->view_customer_by_cid($_GET['id']); } else { header('Location: index.php'); } ?> <div class="container " > <div class="row content"> <a href="index.php" class="button button-purple mt-12 pull-right">View Customer List</a> <h3>View Customer Info</h3> <hr/> <?php echo '<table border="0" cellspacing="2" cellpadding="2">'; foreach ($customer_info as $key => $value) { $keyname = $key; $keyvalue = $value; //echo "$keyname = $keyvalue <br>"; echo "<tr><td><label >$keyname: </label></td><td>$value</td></tr> "; } echo "</table>"; ?> <a href="<?php echo 'update-customer-info.php?id=' . $customer_info["cid"] ?>" class="button button-blue">Edit</a> </div> </div> <hr/> <?php include 'footer.php'; ?>
true
23176385eeea01fede7a2df759a0eeb1c4620a95
PHP
Dcodefrenzy/E-Commerce-Book-App
/www/admin/add_category.php
UTF-8
1,345
2.640625
3
[]
no_license
<?php $page_title ="Add Category"; session_start(); include "include/db.php"; include "include/function.php"; include "include/nav.php"; authentication($_SESSION); //form validation. $error= []; if(array_key_exists('add_category', $_POST)){ if(empty($_POST['category_name'])){ $error['category_name'] = "Please input a category name"; } if(empty($error)){ $input= array_map('trim', $_POST); //called the function bellow to be able to insert category into our database. addCategory($conn, $input); } } ?> <?/*php here we created a form for add category, we also created a table called add_category on our database and on our table we have category_id amd category_name.*/ ?> <div class="wrapper"> <h1 id="register-label">Add Category</h1> <hr> <form id="register" method="post"> <div> <?php $showError = displayError($error, 'category_name'); echo $showError; ?> <label>Category Name:</label> <input type="text" name="category_name" placeholder="Category name"> </div> <input type="submit" name="add_category" value="add"> </form> </div> </div> <?php include "include/footer.php"; ?> </body> </html>
true
af52441905971df204d1a897f6b2a4d593039f6a
PHP
dangpatrick/foods2
/index.php
UTF-8
2,066
3.15625
3
[]
no_license
<?php //This is my CONTROLLER page // Turn on error reporting ini_set('display_errors', 1); error_reporting(E_ALL); //Require the auto autoload file require_once('vendor/autoload.php'); //Create an instance of the Base class $f3 = Base::instance(); $f3->set('Debug',3); //Define a default route (home page) $f3->route('GET /', function(){ //echo"My food page2"; $view = new Template(); echo $view->render('views/home.html'); }); /* * Creating additional routes notes * Ex: Breakfast route below * 1. f3 object instantiated above -> invoking a method (java - $f3. (dot)-method call - PHP $f3 -> route * 2. route method takes 2 parameters (route (Always GET or POST), anonymous function (, function()) * 3. 'GET / - default use forward slash - additional routes we give name aka breakfast - 'GET /breakfast' - map onto this route * 4. server is now looking for an actual directory called breakfast in foods dir. Goal is we only want to name a route * 5. Tell server, if we want to add additional route, GO BACK TO SERVER PAGE/CONTROLLER PAGE * 6. Controller page handles by using an htaccess file * 7. htaccess file solves 2 problems - * 7.1. No going through pages directly / only through routes * 7.2. Typing in URL, we want our index/controller page to handle all request needs to go through the controller. * */ //Define a breakfast route $f3->route('GET /breakfast', function(){ //echo "Breakfast"; $view = new Template(); echo $view->render('views/breakfast.html'); }); /* * Route path/name does not have to match the physical file name - Local path can be apple and oranges 'GET /a/b/c' or luncharoo and still see my lunch.html page */ //Define a lunch route $f3->route('GET /lunch', function(){ //url - local route what we type in the search bar - anything u want ex GET/lunch/sanwhiches // echo "Lunch!"; $view = new Template(); echo $view->render('views/lunch.html'); // you can name this something else as well }); //Run fat free $f3->run();
true
8da881832e4eac83a5569b2b6d07f8dd8ee99813
PHP
desarrollo-bexandy-rodriguez/PHP-POO
/blog/index.php
UTF-8
5,959
2.578125
3
[]
no_license
<?php require_once 'class/classConexionBlog.php'; $blogbdd = new BlogBDD; ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>..:: Blog de Bexandy Rodríguez ::..</title> <link rel="stylesheet" type="text/css" href="css/estilos.css" > </head> <body> <center> <div id="principal"> <div id="header"> <div style="float:left; text-align: left;"> <img src="images/Bexandy-Rodriguez.jpg" height="100px" alt="Logo"> </div> <h1>..:: Blog de Bexandy Rodríguez ::..</h1> </div> <div id="main"> <div id="menu"> <?php include 'menu.php'; ?> <div id="buscador"> <form name="buscar"> <input type="text" name="s" style="width: 140px;"> <a href=""><img src="images/search32.png" alt="Buscar" style="width: 20px; height: 20px;"></a> </form> </div> </div> <div id="content"> <div id="contenedor"> <?php if (isset($_GET["pos"])) { $inicio = $_GET["pos"]; } else { $inicio = 0; } if (isset($_GET["cat"])) { $c = $_GET["cat"]; } else { $c = 1; } $datos = $blogbdd->get_paginacion_noticias($inicio,$c); if (count($datos)==0){ echo "<h2>No hay registros asociados a ésta categoría</h2>"; } else { for ($i=0; $i < sizeof($datos) ; $i++) { ?> <div id="separador_post"></div> <div id="post"> <div id="titulo_post"> <div id="titulo"><?php echo $datos[$i]["titulo"]; ?></div> <div id="fecha"><?php echo $datos[$i]["fecha_cadena"]; ?> </div> </div> <div id="texto_post"> <hr> <?php echo Conectar::corta_palabra($datos[$i]["detalle"],300); ?> ... </div> <div id="separador_debajo_texto"></div> <div id="debajo_post"> <div id="leer_mas"> <?php $texto = str_replace(" ","-",$datos[$i]["titulo"]); ?> <a href="<?php echo $texto."-p".$datos[$i]["id_noticia"].".html"; ?>">Leer Más</a> </div> <div id="comentarios">Tiene <?php echo $blogbdd->total_comentarios($datos[$i]["id_noticia"]); ?> comentarios </div> </div> <div id="div_entre_post"></div> </div> <?php } } ?> <div id="div_paginacion_post"> <hr> <?php if ($inicio == 0) { ?> Anteriores Publicaciones <?php } else { $anterior = $inicio - 5; ?> <a href="?pos=<?php echo $anterior; ?>&cat=<?php echo $c ?>" title="Anteriores Publicaciones" >Anteriores Publicaciones</a> <?php } ?> &nbsp;&nbsp;||&nbsp;&nbsp; <?php if (count($datos)==5) { $proximo =$inicio + 5; ?> <a href="?pos=<?php echo $proximo; ?>&cat=<?php echo $c; ?>" title="Siguientes Publicaciones">Siguientes Publicaciones</a> <?php } else { ?> Siguientes Publicaciones <?php } ?> </div> </div> <div id="sidebar"> <div id="separador_widget"></div> <div id="widget"> <div id="caja_widget"> <div id="titulo_widget">Categorías</div> <?php $categoria = $blogbdd->get_categorias(); for ($i=0; $i < sizeof($categoria); $i++) { ?> <div id="contenido_widget"><a href="?cat=<?php echo $categoria[$i]["id_categoria"] ?>" title="<?php echo $categoria[$i]["categoria"] ?>"><?php echo $categoria[$i]["categoria"]; ?></a></div> <?php } ?> </div> <div class="separador_lateral_widget"></div> </div> <div id="separador_widget"></div> <div> <iframe src="https://www.facebook.com/plugins/page.php?href=https%3A%2F%2Fwww.facebook.com%2Ffacebook&tabs=timeline&width=170&height=300&small_header=false&adapt_container_width=true&hide_cover=false&show_facepile=true&appId=314376128644434" width="170" height="300" style="border:none;overflow:hidden" scrolling="no" frameborder="0" allowTransparency="true"></iframe> </div> <div id="separador_widget"></div> <div id="widget"> <div id="caja_widget"> <div id="titulo_widget">Últimos Posts</div> <?php $not = $blogbdd->get_ultimos_5_posts(); for ($i=0; $i < count($not); $i++) { ?> <div id="contenido_widget"> <?php $texto = str_replace(" ","-",$not[$i]["titulo"]); ?> <a href="<?php echo $texto."-p".$not[$i]["id_noticia"].".html"; ?>" title="<?php echo $not[$i]['titulo']; ?>" > <?php echo Conectar::corta_palabra($not[$i]["titulo"],26); ?> ... </a> </div> <?php } ?> </div> <div class="separador_lateral_widget"></div> </div> </div> </div> <div id="footer"></div> <div id="footer"><hr>&copy; Desarrollado por Bexandy Rodríguez 2015 - <?php echo date("Y"); ?></div> </div> </div> </center> </body> </html>
true
2352612f8b4e0512fa42de81970d57b41b28207d
PHP
alexshadie/fns-billchecker
/test/VersionTest.php
UTF-8
316
2.59375
3
[]
no_license
<?php namespace alexshadie\fns; use PHPUnit\Framework\TestCase; class VersionTest extends TestCase { public function testCreate() { $v = new Version('1.1.1', 'aaabbbccc'); $this->assertEquals('1.1.1', $v->getVersion()); $this->assertEquals('aaabbbccc', $v->getRevision()); } }
true
6309e77e3791bc786c979fe1afdbc5ca6c1618b1
PHP
jvilata/wealthmgr
/php/lib/auth/delight-im/db/src/SimpleMeasurement.php
UTF-8
1,601
3.21875
3
[ "MIT" ]
permissive
<?php /* * PHP-DB (https://github.com/delight-im/PHP-DB) * Copyright (c) delight.im (https://www.delight.im/) * Licensed under the MIT License (https://opensource.org/licenses/MIT) */ namespace Delight\Db; /** Implementation of an individual measurement of a profiler that monitors performance */ final class SimpleMeasurement implements Measurement { /** @var float the duration in milliseconds */ private $duration; /** @var string the SQL query or statement */ private $sql; /** @var array|null the values that have been bound to the query or statement */ private $boundValues; /** @var array|null the trace that shows the path taken through the program until the operation was executed */ private $trace; /** * Constructor * * @param float $duration the duration in milliseconds * @param string $sql the SQL query or statement * @param array|null $boundValues (optional) the values that have been bound to the query or statement * @param array|null $trace (optional) the trace that shows the path taken through the program until the operation was executed */ public function __construct($duration, $sql, array $boundValues = null, $trace = null) { $this->duration = $duration; $this->sql = $sql; $this->boundValues = $boundValues; $this->trace = $trace; } public function getDuration() { return $this->duration; } public function getSql() { return $this->sql; } public function getBoundValues() { return $this->boundValues; } public function getTrace() { return $this->trace; } }
true
18f5e64c3f476b5e9b58370dfc18650483399e76
PHP
pdfkiwi/php-lib
/src/PdfKiwi.php
UTF-8
10,591
3.046875
3
[]
no_license
<?php namespace PdfKiwi; class PdfKiwi { public static $libVersion = '0.4.0'; private static $apiHost = 'https://pdf.kiwi'; private static $apiPort = 443; private $apiPrefix; private $userAgent; private $fields; private $httpResponseCode; private $errorNumber; private $errorMessage; /** * PdfKiwi constructor * * @param string $email Email address of a pdf.kiwi customer * @param string $apiToken Api key of the choosen customer's subscription */ public function __construct($email, $apiToken) { $this->apiPrefix = sprintf('%s/api', self::$apiHost); $this->fields = [ 'email' => $email, 'token' => $apiToken, 'options' => [] ]; $this->userAgent = sprintf('pdfkiwi_php_client_%s', self::$libVersion); } /** * To set the page width * * @param string $value The document's page width, with unit (eg. '210mm') */ public function setPageWidth($value) { $this->fields['options']['width'] = $value; } /** * To set the page height * * @param string $value The document's page height, with unit (eg. '297mm') */ public function setPageHeight($value) { $this->fields['options']['height'] = $value; } /** * To set the page width * * @param string $value The document's page size (eg. 'A3') * @throws PdfKiwiException if given page size is unknown */ public function setPageSize($value) { $allowedPageSize = [ 'A0', 'A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'A9', 'B0', 'B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'B8', 'B9', 'B10', 'C5E', 'Comm10E', 'DLE', 'Executive', 'Folio', 'Ledger', 'Legal', 'Letter', 'Tabloid' ]; if (!in_array($value, $allowedPageSize)) { throw new PdfKiwiException(sprintf( "The page size must be one of: [%s].", implode(', ', $allowedPageSize) )); } $this->fields['options']['page_size'] = $value; } /** * To set a HTML page header * * @param string $value The HTML content of the header */ public function setHeaderHtml($value) { $this->fields['options']['header_html'] = $value; } /** * To set the space between the header and the document's body * * @param float $value the space (in mm) between the header and the body, without unit */ public function setHeaderSpacing($value) { if ((float)$value) { $this->fields['options']['header_spacing'] = (float)$value; } } /** * To set some TEXT page headers * * @param mixed $value Can be either : * - string The (text) content of the header (will be left aligned) * - array An array with 3 values of text, respectively : [left, center, right] */ public function setHeaderText($value) { if (is_array($value)) { $this->fields['options']['header_text_left'] = $value[0]; $this->fields['options']['header_text_center'] = $value[1]; $this->fields['options']['header_text_right'] = $value[2]; } else { $this->fields['options']['header_text_left'] = $value; } } /** * To set a HTML page footer * * @param string $value The HTML content of the footer */ public function setFooterHtml($value) { $this->fields['options']['footer_html'] = $value; } /** * To set the space between the footer and the document's body * * @param float $value the space (in mm) between the footer and the body, without unit */ public function setFooterSpacing($value) { if ((float)$value) { $this->fields['options']['footer_spacing'] = (float)$value; } } /** * To set some TEXT page footers * * @param mixed $value Can be either : * - string The (text) content of the footer (will be left aligned) * - array An array with 3 values of text, respectively : [left, center, right] */ public function setFooterText($value) { if (is_array($value)) { $this->fields['options']['footer_text_left'] = $value[0]; $this->fields['options']['footer_text_center'] = $value[1]; $this->fields['options']['footer_text_right'] = $value[2]; } else { $this->fields['options']['footer_text_left'] = $value; } } /** * To set a list of pages numbers on which the header and footer won't be printed * * @param mixed $value Can be either : * - string A comma separated list of page numbers (without space, eg. '1,3,5') * - array An array with a list of page numbers (eg. [1, 3, 5]) */ public function setHeaderFooterPageExcludeList($value) { if (is_array($value)) { $this->fields['options']['header_footer_exclude_pages'] = implode(',', $value); } else { $this->fields['options']['header_footer_exclude_pages'] = $value; } } /** * To set page's margins * * @param string $top Top margin value, with unit (eg. '20mm') * @param string $right Right margin value, with unit (eg. '20mm') * @param string $bottom Bottom margin value, with unit (eg. '20mm') * @param string $left Left margin value, with unit (eg. '20mm') */ public function setPageMargins($top, $right, $bottom, $left) { $this->fields['options']['margin_top'] = $top; $this->fields['options']['margin_right'] = $right; $this->fields['options']['margin_bottom'] = $bottom; $this->fields['options']['margin_left'] = $left; } /** * To set page's orientation * * @param string $orientation The page's orientation. Can be either 'landscape', or 'portrait' */ public function setOrientation($orientation) { $this->fields['options']['orientation'] = $orientation; } /** * To convert an HTML string into PDF (calling pdf.kiwi API) * * @param string $src The HTML document's content to convert * @param string $outstream If null, returns a string containing the PDF * If defined, save the output into a file. It must set a path and filename * @return string The result of the PDF conversion */ public function convertHtml($src, $outstream = null) { if (empty($src)) { throw new PdfKiwiException("convertHTML(): the src parameter must not be empty!"); } $this->fields['html'] = $src; $uri = sprintf('%s/convert/html/', $this->apiPrefix); $postfields = http_build_query($this->fields); return $this->__httpPost($uri, $postfields, $outstream); } // —————————————————————————————————————————————————————— // — // — Private Methods // — // —————————————————————————————————————————————————————— private function __httpPost($url, $postfields, $outstream) { if (!function_exists("curl_init")) { throw new PdfKiwiException("PdfKiwi requires php-curl extension, which is not installed on your system."); } $curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => $url, CURLOPT_HEADER => false, CURLOPT_CONNECTTIMEOUT => 10, CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_PORT => self::$apiPort, CURLOPT_POSTFIELDS => $postfields, CURLOPT_USERAGENT => $this->userAgent, CURLOPT_SSL_VERIFYPEER => true ]); if ($outstream) { $this->outstream = $outstream; curl_setopt($curl, CURLOPT_WRITEFUNCTION, [$this, '__receiveToStream']); } $this->httpResponseCode = 0; $response = curl_exec($curl); $this->httpResponseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); $this->errorNumber = curl_errno($curl); $this->errorMessage = curl_error($curl); curl_close($curl); if ($this->errorNumber !== 0) { throw new PdfKiwiException($this->errorMessage, $this->errorNumber); } if ($this->httpResponseCode < 200 || $this->httpResponseCode >= 300) { $jsonResponse = json_decode($response, true); throw new PdfKiwiException( ($jsonResponse) ? $jsonResponse['error']['message'] : $response, ($jsonResponse) ? $jsonResponse['error']['code'] : $this->httpResponseCode ); } return $response; } private function __receiveToStream($curl, $data) { if ($this->httpResponseCode === 0) { $this->httpResponseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); } if ($this->httpResponseCode >= 400) { $jsonResponse = json_decode($data, true); throw new PdfKiwiException( ($jsonResponse) ? $jsonResponse['error']['message'] : $response, ($jsonResponse) ? $jsonResponse['error']['code'] : $this->httpResponseCode ); } $written = fwrite($this->outstream, $data); if ($written != strlen($data)) { if (get_magic_quotes_runtime()) { throw new PdfKiwiException( "Cannot write the PDF file because the 'magic_quotes_runtime' setting is enabled." . "Please disable it either in your php.ini file, or in your code by calling 'set_magic_quotes_runtime(false)'." ); } else { throw new PdfKiwiException("Writing the PDF to output stream failed."); } } return $written; } }
true
6ebb1002c62db6f9279987f09e2a6f1635164a59
PHP
breezi30/red-wechat
/wechat/core/scanin.lib.php
UTF-8
2,421
2.703125
3
[ "WTFPL" ]
permissive
<?php namespace LaneWeChat\Core; include 'lanewechat.php'; /** * 扫码关注获取客户关系 * User: lane * Date: 14-10-31 * Time: 下午4:15 * E-mail: * WebSite: */ class Scanin { /***************************** * 在扫码关注事件中取得二维码带的场景值$dataNO * * @param $type char $sceneid * @param $type char $oenpid * * @return $dataNO char */ public static function getSceneid($sceneid){ $dataNO = ltrim($sceneid,"qrscene_"); return $dataNO; } /***************************** * 创建扫码关注用户和场景值dataNO间的一一对应关系,并写入表名为noXXX的表中 * * @param $type char $sceneid * @param $type char $oenpid * * @return int 或者 array */ public static function dealwithTable($sceneid,$openid){ //连接数据库 $dsn = PDO_DSN;//使用config.php 配置赋值 $user = PDO_USER; $pass = PDO_PASS; try{ //用建立一个新PDO类的方法连接数据库 $dbh = new \PDO($dsn,$user,$pass); //echo 'ok!数据库连接成功<br>';测试语句 }catch(PDOException $e){ //echo '数据库连接失败:<br>'.$e->getMessage();测试语句 exit; } $dataNO = ltrim($sceneid,"qrscene_");//why self::getSceneid($secneid)不行?奇怪 $openid = $openid; $time =time(); $tablename = 'no'.$dataNO; //var_dump($tablename);测试表名使用 $query4 = "INSERT INTO {$tablename} (open_ID,followtime) VALUES ('{$openid}','{$time}')"; $stmt = $dbh->exec($query4); if($stmt){ //echo 'ok!数据写入成功<br>';测试时打开 $e = $stmt;//返回受影响的行数 return $e; }else{ //echo '数据写入失败<br>';测试时打开 $e = $dbh->errorInfo();//获得错误信息 return $e; } } /***************************** * 统计功能 * * @param $type char $oenpid * @param $type int $filter * * @return bool */ public static function queryUsers($openid,$filter){ } }
true
fac526237a307dbd6e04b278104d530e2b40be4a
PHP
JMPrestes/PHPXlsSheetMySQLIntegration
/db_connect.php
UTF-8
334
2.65625
3
[]
no_license
<?php //Conexão com DB $servername = "localhost"; $username = "admin"; $password = "insert your connection password here"; $db_name = "jordancrud"; $connect = mysqli_connect($servername, $username, $password, $db_name); mysqli_set_charset($connect, "utf-8"); if(mysqli_connect_error()): echo "<h1>Falha na Conexão: </h1>".mysqli_connect_error(); endif;
true
11c50ff90f63faa6869b6eafaa30993cd89dcb27
PHP
nittics1991/Concerto
/_mvc/dev/accessor/TypeCastInterface.php
UTF-8
519
2.625
3
[]
no_license
<?php /** * TypeCastInterface * * @version 190516 */ declare(strict_types=1); namespace candidate\accessor; interface TypeCastInterface { /** * set cast定義存在確認|定義取得 * * @param ?string $name * @return bool|mixed[] */ public function hasSetCastType(?string $name = null); /** * get cast定義存在確認|定義取得 * * @param ?string $name * @return bool|mixed[] */ public function hasGetCastType(?string $name = null); }
true