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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
864a06a6fb615901a64b9a7dd8d98d0d0892de8e | PHP | clusteramaryllis/erars | /app/models/User.php | UTF-8 | 523 | 2.53125 | 3 | [
"MIT"
] | permissive | <?php
class User extends Eloquent {
protected $table = 'user';
protected $primaryKey = 'no_id';
public $incrementing = false;
// protected $hidden = array('pass');
public $timestamps = false;
// relasi
public function facility()
{
return $this->belongsTo('Facility', 'tmp_dinas');
}
public function scopeFindByIdPass($query, $id, $pass)
{
return $query
->where('no_id', $id)
->where('pass', $pass);
}
public function scopeGetName($query, $id)
{
return $query
->where('no_id', $id);
}
} | true |
4730a55394f84d2c49572cc62cd1a45bd6947df5 | PHP | aaronross1/256activities | /LaravelActivity/app/Http/Controllers/Login3Controller.php | UTF-8 | 1,554 | 2.65625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers;
use App\Models\UserModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;
use App\Services\Business\SecurityService;
use Exception;
class Login3Controller extends Controller
{
// index function
public function index(Request $request)
{
try {
$this->validateForm($request);
$username = $request->input('username');
$password = $request->input('password');
$user = new UserModel(- 1, $username, $password);
$service = new SecurityService();
$status = $service->login($user);
if ($status) {
$data = [
'model' => $user
];
return view('loginPassed2')->with($data);
}
else {
return view('loginFailed2');
}
}
catch(ValidationException $e1)
{
throw $e1;
}
catch(Exception $e)
{
Log::error("Exception: ", array("message" => $e->getMessage()));
$data = ['errorMsg' => $e->getMessage()];
return view("systemException")->with($data);
}
}
private function validateForm(Request $request)
{
$rules = ['username' => 'Required | Between:4,10 | Alpha_num',
'password' => 'Required | Between:4,10'];
$this->validate($request, $rules);
}
}
| true |
d4d362e02106f53673d01fd367ab1ee57e338ba5 | PHP | CarlosR2/development_deployment_scripts | /home/user/public_html_test/install/install_db.php | UTF-8 | 8,406 | 2.515625 | 3 | [] | no_license | <?php
//error_reporting(E_ALL);
ini_set('display_errors', 1);
error_reporting(E_ALL ^ E_DEPRECATED);
$env = '';
if(isset($argv)){
$env = $argv[1];
}else{
if(isset($_GET['env'])) $env = $_GET['env'];
}
if(!$env) die('no env specified');
echo 'Selected environment: '.$env.'<br>';
define('DB_HOST','localhost');
// connect to db
if($env =='dev'){
define('DIR','');
define('DIR_BACKUP','');
define('DB_USER','DB_USER_DEV');
define('DB_PASS','DB_USER_PASS_DEV');
define('DB_DB','DB_NAME_DEV');
}else if($env =='test'){
define('DIR','');
define('DIR_BACKUP','');
define('DB_USER','DB_USER_TEST');
define('DB_PASS','DB_USER_PASS_TEST');
define('DB_DB','DB_NAME_TEST');
}else if($env =='prod'){
define('DIR','');
define('DIR_BACKUP','');
define('DB_USER','DB_USER');
define('DB_PASS','DB_USER_PASS');
define('DB_DB','DB_NAME');
}else if($env == 'localhost'){
define('DIR','');
define('DIR_BACKUP','');
define('DB_USER','DB_USER_LOCALHOST');
define('DB_PASS','DB_USER_PASS_LOCALHOST');
define('DB_DB','DB_NAME_LOCALHOST');
}else{
die('No env available');
}
// TODO: make a copy of the database here
// mysqldump DB_NAME > DIR_BACKUP/copyTIMESTAMP.txt . exec('mysqldump --user=... --password=... --host=... DB_NAME > /path/to/output/file.sql');
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_DB);
$table_definition = Array();
$table_definition['usuarios']=Array(
'definition'=>"CREATE TABLE `usuarios` (
`codigo` int(11) NOT NULL AUTO_INCREMENT,
`dni` VARCHAR(50) NOT NULL COLLATE 'utf8_bin',
`nombre` VARCHAR(100) NOT NULL COLLATE 'utf8_bin',
`email` VARCHAR(100) NOT NULL COLLATE 'utf8_bin',
`contrasenya` VARCHAR(100) NOT NULL COLLATE 'utf8_bin',
`telefono` VARCHAR(100) NOT NULL COLLATE 'utf8_bin',
`fecha_nacimiento` DATE NOT NULL,
`facebook` VARCHAR(200) NULL DEFAULT NULL COLLATE 'utf8_bin',
`twitter` VARCHAR(200) NULL DEFAULT NULL COLLATE 'utf8_bin',
PRIMARY KEY (`codigo`)
) COLLATE='utf8_bin' ENGINE=InnoDB AUTO_INCREMENT=2",
'cols'=>Array(
'codigo'=>Array('definition'=> "`codigo` int(11) NOT NULL AUTO_INCREMENT",
'type'=> 'int',
'size'=>11,
'allow_null'=>false,
'default'=>'',
'extra'=>'auto_increment'),
'dni'=>Array('definition'=> "`dni` VARCHAR(50) NOT NULL COLLATE 'utf8_bin'",
'type'=> 'varchar',
'size'=>50,
'allow_null'=>false,
'default'=>'',
'extra'=>''),
'nombre'=>Array('definition'=> "`nombre` VARCHAR(100) NOT NULL COLLATE 'utf8_bin'",
'type'=> 'varchar',
'size'=>100,
'allow_null'=>false,
'default'=>'',
'extra'=>''),
'email'=>Array('definition'=> "`email` VARCHAR(100) NOT NULL COLLATE 'utf8_bin'",
'type'=> 'varchar',
'size'=>100,
'allow_null'=>false,
'default'=>'',
'extra'=>''),
'contrasenya'=>Array('definition'=> "`contrasenya` VARCHAR(100) NOT NULL COLLATE 'utf8_bin'",
'type'=> 'varchar',
'size'=>"100",
'allow_null'=>false,
'default'=>'',
'extra'=>''),
'telefono'=>Array('definition'=> "`telefono` VARCHAR(100) NOT NULL COLLATE 'utf8_bin'",
'type'=> 'varchar',
'size'=>"100",
'allow_null'=>false,
'default'=>'',
'extra'=>''),
'fecha_nacimiento'=>Array('definition'=> "`fecha_nacimiento` DATE NOT NULL",
'type'=> 'int',
'size'=>11,
'allow_null'=>false,
'default'=>'',
'extra'=>''),
'facebook'=>Array('definition'=> "`facebook` VARCHAR(200) NULL DEFAULT NULL COLLATE 'utf8_bin'",
'type'=> 'varchar',
'size'=>'200',
'allow_null'=>true,
'default'=>'',
'extra'=>''),
'twitter'=>Array('definition'=> "`twitter` VARCHAR(200) NULL DEFAULT NULL COLLATE 'utf8_bin'",
'type'=> 'varchar',
'size'=>'200',
'allow_null'=>true,
'default'=>'',
'extra'=>''),
),
'indexes' =>'',
'primary_key' => 'codigo',
'engine' => '',
'auto_increment'=> '',
'default_charset' => '',
'data'=>"INSERT INTO `usuarios` (`codigo`, `dni`, `nombre`, `email`, `contrasenya`, `telefono`, `fecha_nacimiento`, `facebook`, `twitter`) VALUES (1, '123123123f', 'Francisco', 'fran@somemail.com', '1234', '111222333', '1995-03-20', 'somefacebook', '@twitter');"
);
$table_definition['categorias']=Array(
'definition'=>"CREATE TABLE `categorias` (
`codigo` INT(11) NOT NULL,
`nombre` VARCHAR(100) NOT NULL COLLATE 'utf8_bin',
`padre` INT(11) NOT NULL DEFAULT '0',
`imagen` VARCHAR(100) NOT NULL COLLATE 'utf8_bin',
`url` VARCHAR(100) NOT NULL COLLATE 'utf8_bin',
PRIMARY KEY (`codigo`)
) COLLATE='utf8_bin' ENGINE=InnoDB",
'cols'=>Array(
'codigo'=>Array('definition'=> "`codigo` INT(11) NOT NULL,",
'type'=> 'int',
'size'=>11,
'allow_null'=>false,
'default'=>'',
'extra'=>''),
'nombre'=>Array('definition'=> "`nombre` VARCHAR(100) NOT NULL COLLATE 'utf8_bin'",
'type'=> 'varchar',
'size'=>100,
'allow_null'=>false,
'default'=>'',
'extra'=>''),
'padre'=>Array('definition'=> "`padre` INT(11) NOT NULL DEFAULT '0'",
'type'=> 'int',
'size'=>11,
'allow_null'=>false,
'default'=>'0',
'extra'=>''),
'imagen'=>Array('definition'=> "`imagen` VARCHAR(100) NOT NULL COLLATE 'utf8_bin'",
'type'=> 'varchar',
'size'=>100,
'allow_null'=>false,
'default'=>'',
'extra'=>''),
'url'=>Array('definition'=> "`url` VARCHAR(100) NOT NULL COLLATE 'utf8_bin'",
'type'=> 'varchar',
'size'=>"100",
'allow_null'=>false,
'default'=>'',
'extra'=>'')
),
'indexes' =>'',
'primary_key' => 'codigo',
'engine' => '',
'auto_increment'=> '',
'default_charset' => '',
'data'=>"INSERT INTO `categorias` (`codigo`, `nombre`, `padre`, `imagen`, `url`)
VALUES
(0, 'Todas', 0, '', 'todas'),
(1, 'Alimentacion', 0, '/img/categorias/alimentacion/alimentacion.jpg', 'alimentacion'),
(2, 'Automoción', 0, '/img/categorias/automocion/automocion.jpg', 'automocion'),
;"
);
/*
ADD TABLES HERE
*/
// Fetch current tables
$current_tables = $mysqli->query("show tables");
if(!$current_tables) die('Error showing tables');
$aux = Array();
while($c = $current_tables->fetch_array()){
$aux[$c[0]] = $c;
}
$current_tables = $aux;
// CREATE / UPDATE TABLES
// its only incremental, we dont delete tables or columns
// check tables and create if not
foreach($table_definition as $table => $table_info){
if(!isset($current_tables[$table])){
// install table
$res = $mysqli->query($table_info['definition']);
if(!$res){
die('E1: '.$mysqli->error.' -> on table'.$table);
}
}else{
// check columns and create (alter table) if so
// check primary key and alter if so // SHOW KEYS FROM __correos WHERE Key_name = 'PRIMARY'
// check indexes and alter if so // SHOW indexes FROM __correos;
$current_columns = $mysqli->query("show full columns from `".$table."`");
if(!$current_columns) die('E2: '.$mysqli->error);
$aux = Array();
while($c = $current_columns->fetch_array()){
$aux[$c['Field']] = $c;
}
$current_columns = $aux;
$columns = $table_info['cols'];
foreach($columns as $col => $def){
if(!isset($current_columns[$col])){
echo 'Inserting col "'.$col.'" on table '.$table.'<br>';
$sql = "alter table `".$table."` ADD COLUMN ".$def['definition'];
$inserting_col = $mysqli->query($sql);
if(!$inserting_col) die('E3: '.$mysqli->error.' _on_ '.$sql);
}else{
//all ok (but we should test data type, length and so)
}
}
}
// if it has data, lets put it
if(isset($table_info['data'])){
$queries = explode(';',$table_info['data']);
echo 'Inserting data table '.$table.'<br>';
foreach($queries as $q){
if(!$q) continue;
$res = $mysqli->query($q);
if(!$res) echo 'E4 (data): '.$mysqli->error;
}
echo '<br>';
}
}
?> | true |
ba6be5cabf847ccada5ade7d4d743f080d740596 | PHP | EfraimKrug/Bostoner | /php/TimesAdmin.php | UTF-8 | 1,486 | 3.03125 | 3 | [] | no_license | <?php
unset($_POST['submit']);
$times = $_POST;
$daysArray = array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Shabbos");
$daviningArray = array("Shacharis","Mincha","Maariv","Ma'ariv");
$arr = array();
$holdDay = "";
$printDay = "";
$htmlFile = fopen("../html/DailyTimes.html", "w") or exit("DailyTimes.html could not be opened!");
fwrite($htmlFile, "<html><head>");
fwrite($htmlFile, "<style>.yomtif {color:yellow;}</style>");
fwrite($htmlFile, "</head><body><h1>Davining Times this week</h1><table>");
foreach ($times as $key => $value){
$key_hold = preg_replace("/([A-Z])/", " $1", $key);
$arr = explode(" ", $key_hold);
if(in_array("Yomtif", $arr)){
if(in_array($arr[1], $daysArray)){
if($value > ""){
if(in_array("Name", $arr)){
fwrite($htmlFile, "<tr><td></td><td class='yomtif'></td><td class='yomtif'>" . $value . "</td></tr>");
}
if(in_array("Time", $arr)){
fwrite($htmlFile, "<tr><td></td><td></td><td class='yomtif'>Licht Benchen:</td><td class='yomtif'>" . $value . "</td></tr>");
}
}
}
}
else {
if(in_array($arr[1], $daysArray)){
if($arr[1] == $holdDay){
$printDay = "";
}
else {
$printDay = $arr[1];
$holdDay = $arr[1];
}
}
fwrite($htmlFile, "<tr><td>" . $printDay . "</td><td>" . $arr[2] . "</td><td>" . $value . "</td></tr>");
}
}
fwrite ($htmlFile, "</table></body></html>");
fclose($htmlFile);
header("Location:../html/DailyTimes.html");
?> | true |
2eb467e4eaf8ea327c6f22c4783d538aa9b5e505 | PHP | raulvictorrosa/monitoramentodeafluentes-udesc | /teste2/myclasses/con-db.php | UTF-8 | 1,203 | 2.796875 | 3 | [] | no_license | <?php
// database
error_reporting(E_ERROR | E_PARSE);
$host = '127.0.0.1:3306';
$dbname = 'teste';
// $dbname = 'monitoramentodeafluentes';
$user = 'root';
$pass = 'root';
// get connection
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch(PDOException $e) {
if ($e->getCode() == 1045) {
die('<div class="alert alert-danger" style="margin:1%;">'
. 'Could not connect to the database. Set Database Username and Password in the file "/how-to/data-from-database.php"'
. '<br><br>'
. 'ERROR: ' . $e->getMessage()
. '</div>');
}
if ($e->getCode() == 1049) {
die('<div class="alert alert-danger" style="margin:1%;">'
. 'Required database does not exist. Please import the canvasjs_db.sql file in the downloaded zip package '
. '(<a href="https://www.digitalocean.com/community/tutorials/how-to-import-and-export-databases-and-reset-a-root-password-in-mysql" target="_blank">Instructions to Import.</a>).'
. '<br><br>'
. 'ERROR: ' . $e->getMessage()
. '</div>');
}
}
| true |
20b89350a1144e8bde967c5c4f82e148a1b4e3a3 | PHP | viosagara347/pasarapplication | /database/seeds/TabelKomoditiSeeder.php | UTF-8 | 2,483 | 2.65625 | 3 | [
"MIT"
] | permissive | <?php
use Illuminate\Database\Seeder;
class TabelKomoditiSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
//
$faker = \Faker\Factory::create();
\DB::table('komoditi')->truncate();
for ($i=0; $i < 10; $i++) {
DB::table('komoditi')->insert([
'nama' => $faker->sentence(1),
'kategori' => 'Sayur',
'stok' => $faker->numberBetween(1, 10),
'harga' => $faker->numberBetween(500, 50000),
'deskripsi' => $faker->text(30),
'file' => 'dummysayur.png',
'created_at' => now(),
'updated_at' => now(),
'gram' => $faker->numberBetween(1, 6000)
]);
}
for ($i=0; $i < 10; $i++) {
DB::table('komoditi')->insert([
'nama' => $faker->sentence(2),
'kategori' => 'Buah',
'stok' => $faker->numberBetween(10, 100),
'harga' => $faker->numberBetween(5000, 500000),
'deskripsi' => $faker->text(30),
'file' => 'dummybuah.png',
'created_at' => now(),
'updated_at' => now(),
'gram' => $faker->numberBetween(1, 10000)
]);
}
for ($i=0; $i < 10; $i++) {
DB::table('komoditi')->insert([
'nama' => $faker->sentence(3),
'kategori' => 'Rempah',
'stok' => $faker->numberBetween(100, 1000),
'harga' => $faker->numberBetween(100, 100000),
'deskripsi' => $faker->text(30),
'file' => 'dummyrempah.png',
'created_at' => now(),
'updated_at' => now(),
'gram' => $faker->numberBetween(1, 1000)
]);
}
for ($i=0; $i < 10; $i++) {
DB::table('komoditi')->insert([
'nama' => $faker->sentence(4),
'kategori' => 'BumbuDapur',
'stok' => $faker->numberBetween(1000, 10000),
'harga' => $faker->numberBetween(300, 3000000),
'deskripsi' => $faker->text(30),
'file' => 'dummybumbu.png',
'created_at' => now(),
'updated_at' => now(),
'gram' => $faker->numberBetween(1, 100)
]);
}
}
}
| true |
4823c4d1166b5af7dc4c2cbff3a18ccb21281ee0 | PHP | DingWeizhe/ntutcc | /plugin/crawlerNportal/network.php | UTF-8 | 1,987 | 2.828125 | 3 | [] | no_license | <?php
class Network {
var $cookies = null;
var $errorTimes = 0;
public function getCookies(){
return $this->cookies;
}
public function __construct($cookies = Array()){
$this->cookies = $cookies;
}
public function POST($url, $data = null){
$proxy = "tcp://42.159.145.189:1080";
$PROXY_HOST = "203.66.159.45"; // Proxy server address
$PROXY_PORT = "3128"; // Proxy server port
if (isset($_GET['host'])){
$PROXY_HOST = $_GET['host'];
}
if (isset($_GET['port'])){
$PROXY_PORT = $_GET['port'];
}
if ( is_null($data))
$data = Array();
$queryContent = http_build_query($data);
$requestHeaders = array(
'Content-type: application/x-www-form-urlencoded',
sprintf('Content-Length: %d', strlen($queryContent)),
'Cookie: ' . http_build_query($this->cookies,'',';')
);
ini_set('default_socket_timeout', 10);
$options = array(
'http' => array(
'header' => implode("\r\n", $requestHeaders),
'method' => 'POST',
'content' => $queryContent,
'timeout' => 10,
'proxy' => "tcp://$PROXY_HOST:$PROXY_PORT",
'request_fulluri' => true,
// 'header' => "Proxy-Authorization: Basic $auth"
)
);
$context = stream_context_create($options);
$result = @file_get_contents($url, false, $context);
// $result = @iconv("big5", "UTF-8", $result);
// echo $result;
if ($result === false || $result === true){
echo "<br>";
var_dump($http_response_header);
die("proxy server:tcp://$PROXY_HOST:$PROXY_PORT<br/> require url:{$url}<br/>無法取得學校資料</br>如果遇到這個頁面就去學校抗議吧!");
}
$this->errorTimes = 0;
foreach ($http_response_header as $hdr) {
if (preg_match('/^Set-Cookie:\s*([^;]+)/', $hdr, $matches)) {
parse_str($matches[1], $tmp);
$this->cookies = array_merge($this->cookies, $tmp);
}
}
//file_put_contents("tmp/" . date("Ymd_His") . ".txt", $result);
return $result;
}
}
?> | true |
07d14f9c57385804f5eda07ace9b962babe4bc3c | PHP | alanshortanjungkapal/Rapor-Digital | /application/models/dao/CbtKelasRuangDAO.class.php | UTF-8 | 1,470 | 2.78125 | 3 | [
"MIT"
] | permissive | <?php
/**
* Intreface DAO
*
* @author: http://phpdao.com
* @date: 2021-03-25 11:46
*/
interface CbtKelasRuangDAO{
/**
* Get Domain object by primry key
*
* @param String $id primary key
* @Return CbtKelasRuang
*/
public function load($id);
/**
* Get all records from table
*/
public function queryAll();
/**
* Get all records from table ordered by field
* @Param $orderColumn column name
*/
public function queryAllOrderBy($orderColumn);
/**
* Delete record from table
* @param cbtKelasRuang primary key
*/
public function delete($id_kelas_ruang);
/**
* Insert record to table
*
* @param CbtKelasRuang cbtKelasRuang
*/
public function insert($cbtKelasRuang);
/**
* Update record in table
*
* @param CbtKelasRuang cbtKelasRuang
*/
public function update($cbtKelasRuang);
/**
* Delete all rows
*/
public function clean();
public function queryByIdKelas($value, $single);
public function queryByIdRuang($value, $single);
public function queryByIdSesi($value, $single);
public function queryByIdTp($value, $single);
public function queryByIdSmt($value, $single);
public function queryBySetSiswa($value, $single);
public function deleteByIdKelas($value);
public function deleteByIdRuang($value);
public function deleteByIdSesi($value);
public function deleteByIdTp($value);
public function deleteByIdSmt($value);
public function deleteBySetSiswa($value);
}
?> | true |
e9fbfb11e74d4bae9330812079cd96970171c137 | PHP | OleksandrGudenko/Symfony-Exam-Project | /symfonyApp/src/Entity/Question.php | UTF-8 | 1,756 | 2.65625 | 3 | [] | no_license | <?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Question
*
* @ORM\Table(name="Question", uniqueConstraints={@ORM\UniqueConstraint(name="id_UNIQUE", columns={"id"})}, indexes={@ORM\Index(name="question_course_id_idx", columns={"course_id"})})
* @ORM\Entity
*/
class Question
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="question", type="string", length=255, nullable=false)
*/
private $question;
/**
* @var \Course
*
* @ORM\ManyToOne(targetEntity="Course")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="course_id", referencedColumnName="id")
* })
*/
private $course;
private $answers;
private $correctAnswer;
public function correctAnswer()
{
return $this->correctAnswer;
}
public function setCorrectAnswer($correctAnswer)
{
$this->correctAnswer = $correctAnswer;
return $this;
}
public function setAnswers($answers)
{
$this->answers = $answers;
return $this;
}
public function answers()
{
return $this->answers;
}
public function setCourse($course)
{
$this->course = $course;
return $this;
}
public function getCourse()
{
return $this->course;
}
public function setQuestion(string $question)
{
$this->question = $question;
return $this;
}
public function getQuestion()
{
return $this->question;
}
public function getId()
{
return $this->id;
}
}
| true |
e842471ff542a84f9a6553d0633005bea19a9e0b | PHP | deshi9012/workice | /Modules/Users/Emails/TellAFriend.php | UTF-8 | 791 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
namespace Modules\Users\Emails;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class TellAFriend extends Mailable implements ShouldQueue
{
use Queueable, SerializesModels;
public $friend;
public $name;
/**
* Create a new message instance.
*
* @return void
*/
public function __construct($friend, $name)
{
$this->friend = $friend;
$this->name = $name;
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->from(get_option('company_email'))
->subject('Invitation by '.$this->name)
->markdown('emails.tell_friend');
}
}
| true |
4147d8ceacd15513c5d0c5417468c9fa03aeef77 | PHP | GregoryAndrievskiy/219791-yeticave | /getwinner.php | UTF-8 | 1,519 | 2.671875 | 3 | [] | no_license | <?php
require_once 'init.php';
$winners = [];
$noWinnerQuery = 'SELECT id FROM lot WHERE winner_id IS NULL AND expire_date < NOW()';
$lots_without_winner = select_data($con, $noWinnerQuery);
$query = 'SELECT
user.id AS user_id,
user.name AS user_name,
user.email,
lot.id AS lot_id,
lot.name
FROM bet
INNER JOIN lot ON bet.lot_id = lot.id
INNER JOIN user ON bet.user_id = user.id
WHERE lot_id= ?
ORDER BY bet.id DESC
LIMIT 1 OFFSET 0';
$updateWinnerQuery = 'UPDATE lot SET winner_id = ? WHERE lot.id = ?';
if ($lots_without_winner) {
foreach ($lots_without_winner as $key) {
$temp = select_data($con, $query, [$key['id']]);
if ($temp) {
extract($temp[0], EXTR_SKIP);
exec_query($con, $updateWinnerQuery, [$temp[0]['user_id'], $key['id']]);
$winners[] = $temp[0];
}
}
}
foreach ($winners as $winner) {
$content = [
'name' => $winner['user_name'],
'lot_url' => 'lot.php?id='.$winner['lot_id'],
'lot_name' => $winner['name']
];
$letter = renderTemplate('templates/email.php', $content);
$transport = new Swift_SmtpTransport('smtp.mail.ru', 465, 'ssl');
$transport->setUsername('doingsdone@mail.ru');
$transport->setPassword('rds7BgcL');
$message = new Swift_Message();
$message->setSubject('Ваш ставка победила');
$message->setFrom('doingsdone@mail.ru');
$message->setTo($winner['email']);
$message->setContentType('text/html');
$message->setBody($letter);
$mailer = new Swift_Mailer($transport);
$mailer->send($message);
}
?> | true |
34e87f84645e8fcdb634d9b99a80328458b04eb8 | PHP | infohojin/php_www | /Module/Html/HtmlTable.php | UTF-8 | 1,201 | 3.296875 | 3 | [] | no_license | <?php
namespace Module\Html;
class HtmlTable
{
function table($rows)
{
$body = "<table class=\"table\">";
$body .= "<thead>";
/*
$body .= "<tr>
<th>번호</th>
<th>테이블명</th>
</tr>";
*/
$body .= "<tr>";
foreach ($rows[0] as $key => $value) {
$body .= "<th>".$key."</th>";
}
$body .= "</tr>";
$body .= "</thead>";
$body .= "<tbody>";
// https://github.com/infohojin/php_www
// 2차원 배열, 이중 반복문...
// for = 상위배열.
for($i=0;$i<count($rows);$i++) {
$body .= "<tr>";
// $body .= "<td>$i</td>";
// $body .= "<td><a href='/TableInfo/".$rows[$i]->Tables_in_php."'>".$rows[$i]->Tables_in_php."</a></td>";
// 하위배열
// 키, 값 연상배열 형태로 풀어서 작업함.
foreach ($rows[$i] as $key => $value) {
$body .= "<td>".$value."</td>";
}
$body .= "</tr>";
}
$body .= "</tbody>";
$body .= "</table>";
return $body;
}
}
| true |
f4f97449d5914e75b4c7dae938c501352db621d9 | PHP | richhildebrand/WP2_Character_Creation_Website | /Models/MemberProfile.php | UTF-8 | 466 | 3.296875 | 3 | [] | no_license | <?php
class UserProfile
{
private $_lastname;
private $_firstname;
private $_email;
public function __construct($userProfile)
{
$this->_lastname = $userProfile['lastname'];
$this->_firstname = $userProfile['firstname'];
$this->_email = $userProfile['email'];
}
public function GetLastName() {
return $this->_lastname;
}
public function GetFirstName() {
return $this->_firstname;
}
public function GetEmail() {
return $this->_email;
}
} | true |
dff56ca76f3c4ec2753204eead087b92c24e2d03 | PHP | ManagerTechnologyCO/admin-pacmec-pwa | /.pacmec/includes/models/Route.php | UTF-8 | 3,160 | 2.6875 | 3 | [
"MIT"
] | permissive | <?php
/**
*
* @author FelipheGomez <feliphegomez@gmail.com>
* @package PACMEC
* @category System
* @copyright 2020-2021 Manager Technology CO
* @license license.txt
* @version Release: @package_version@
* @link http://github.com/ManagerTechnologyCO/PACMEC
* @version 1.0.1
*/
namespace PACMEC;
class Route extends ModeloBase
{
public $id = -1;
public $is_actived = 1;
public $parent = null;
public $permission_access = null;
public $title = 'no_found';
public $theme = null;
public $description = 'No Found';
public $content = '';
public $request_uri = '/404';
public $component = 'pages-error';
public $components = [];
public $meta = [];
public function __construct($args=[])
{
$args = (array) $args;
parent::__construct("routes", false);
if(isset($args['id'])){ $this->getBy('id', $args['id']); }
if(isset($args['page_name'])){ $this->getBy('page_name', $args['page_name']); }
if(isset($args['page_slug'])){ $this->getBy('request_uri', $args['page_slug']); }
if(isset($args['request_uri'])){ $this->getBy('request_uri', $args['request_uri']); }
}
public static function allLoad() : array
{
$r = [];
if(!isset($GLOBALS['PACMEC']['DB']) || !isset($GLOBALS['PACMEC']['DB']['prefix'])){ return $r; }
foreach($GLOBALS['PACMEC']['DB']->FetchAllObject("SELECT * FROM {$GLOBALS['PACMEC']['DB']['prefix']}{$this->getTable()} ", []) as $menu){
$r[] = new Self($menu);
}
return $r;
}
public function getBy($column='id', $val="")
{
try {
$this->setThis($GLOBALS['PACMEC']['DB']->FetchObject("SELECT * FROM {$this->getTable()} WHERE `{$column}`=?", [$val]));
return $this;
}
catch(\Exception $e){
return $this;
}
}
private function setThis($arg)
{
if($arg !== null){
if(is_object($arg) || is_array($arg)){
$arg = (array) $arg;
foreach($arg as $k=>$v){
# if($k=="content") $v = do_shortcode($v);
$this->{$k} = ($v);
}
$this->getMeta();
$this->getComponents();
}
}
}
public function isValid()
{
return $this->id > 0 ? true : false;
}
public function getComponents()
{
try {
if($this->id>0){
$result = $GLOBALS['PACMEC']['DB']->FetchAllObject("SELECT * FROM `{$this->getTable()}_components` WHERE `route_id`=? ORDER BY `ordering` ASC", [$this->id]);
if(is_array($result)) {
$this->components = [];
foreach ($result as $component) {
$component->data = json_decode($component->data);
$this->components[] = $component;
}
}
return [];
}
}
catch(\Exception $e){
return [];
}
}
public function getMeta()
{
try {
if($this->id>0){
$result = $GLOBALS['PACMEC']['DB']->FetchAllObject("SELECT * FROM `{$this->getTable()}_meta` WHERE `route_id`=? ORDER BY `ordering` DESC", [$this->id]);
if(is_array($result)) {
$this->meta = [];
foreach ($result as $meta) {
$meta->attrs = json_decode($meta->attrs);
$this->meta[] = $meta;
}
}
return [];
}
}
catch(\Exception $e){
return [];
}
}
}
| true |
bb0771a02250e359b48d036f031c2e5ad368c19e | PHP | voidbergwow/softmur | /plan.php | UTF-8 | 453 | 2.90625 | 3 | [] | no_license | <?php
$filename = __DIR__ . DIRECTORY_SEPARATOR . 'kill.txt';
$file = fopen($filename, 'r') or die('unable to open file');
$resa = 0;
$murders = [];
while (!feof($file)) {
$resa++;
$line = explode(';', fgets($file));
$m = [];
$m['name'] = $line[0];
$m['target'] = $line[1];
$m['place'] = $line[2];
$m['time'] = trim($line[3]);
$murders[] = $m;
// echo fgets($file) . '<br>';
}
fclose($file);
| true |
8f3c3e50fb7ec92512f0d5bfffa4e2eedb544d3f | PHP | mymymyak/simdoanhnhan | /app/Console/Commands/CheckSoldNumber.php | UTF-8 | 4,332 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Console\Commands;
use App\Repositories\Bangso\BangsoRepository;
use App\Repositories\Domain\DomainRepository;
use App\Repositories\Elastic\ElasticInterface;
use App\Services\Cache\AppCache;
use App\Services\SimFilter;
use Illuminate\Console\Command;
class CheckSoldNumber extends Command {
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'checkSoldNumber';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
protected $elasticRepository;
protected $domainRepository;
protected $bangSoRepository;
private $simFilterService;
/**
* CheckSoldNumber constructor.
*
* @param ElasticInterface $elasticRepository
* @param DomainRepository $domainRepository
* @param BangsoRepository $bangSoRepository
*/
public function __construct (ElasticInterface $elasticRepository, DomainRepository $domainRepository, BangsoRepository $bangSoRepository) {
$this->elasticRepository = $elasticRepository;
$this->domainRepository = $domainRepository;
$this->bangSoRepository = $bangSoRepository;
$this->simFilterService = new SimFilter($elasticRepository);
parent::__construct();
}
/**
* @throws \App\Exceptions\Validation\ValidationException
*/
public function handle () {
$domain = $this->domainRepository->getDomainActive()->where('is_updated_bangso', 0)->first();
if ($domain) {
$domain->update(['is_updated_bangso' => 1]);
$this->bangSoRepository->setDomain($domain->domain);
echo "Tên miền " . $domain->domain . "\n";
$bangSoTong = $this->bangSoRepository->getBangsoTong($domain->domain);
$newBangSoTong = [];
$limit = 0;
$simCollect = [];
$soldNumbers = "";
foreach ($bangSoTong as $index => $soTong) {
$soSim = $this->getBeautyNumber($soTong['sim']);
if ($limit < 300 && $index < count($bangSoTong) - 1) {
$limit ++;
$simCollect[] = $soSim;
continue;
}
$searchResponseNumbers = $this->elasticRepository->searchByTerms($simCollect, $limit + 1);
echo "-Số lương sim check lần này " . count($searchResponseNumbers) . "\n";
foreach ($searchResponseNumbers as $searchResponseNumber) {
echo "--Check số " . $searchResponseNumber['id'] . "\n";
if (empty($searchResponseNumber) || (isset($searchResponseNumber['d']) && $searchResponseNumber['d'])) {
/** Nếu số không tìm thấy hoặc tìm thấy nhưng đã bán */
/** Loại khỏi bảng số tổng và lưu vào file so_da_ban.txt */
$soldNumbers .= $searchResponseNumber['id'] . "\n";
echo "Phát hiện số đã bán \n";
} else {
/** Số vẫn còn */
$newBangSoTong[] = $searchResponseNumber['simfull'] . "\t" . $soTong['price'];
}
$limit = 0;
$simCollect = [];
}
}
$bangSoTongNewContent = implode(PHP_EOL, $newBangSoTong);
$this->bangSoRepository->saveDanhmuc([
'danh_muc' => 'so_da_ban',
'bangso' => $soldNumbers,
]);
$this->bangSoRepository->setBangSoPath();
$this->bangSoRepository->save(['bangso' => $bangSoTongNewContent]);
$this->cacheHomePage($domain);
$domain->update(['is_updated_bangso' => 2]);
}
}
/**
* Cache lại trang chủ sau khi chạy xong cập nhật bảng sim mới
* Bao gồm cả 2 loại cache (trang chủ mặc định hoặc trang chủ shortcode)
*
* @param $domain
*
* @return mixed
*/
public function cacheHomePage ($domain) {
$cacheSevice = new AppCache(app('cache'), 'getSimHotForHome');
$keyEn = serialize($domain->domain);
$key = 'homepage.bangsim.' . md5($keyEn);
if ($cacheSevice->has($key)) {
$cacheSevice->forget($key);
}
$key = 'homepage.bangsim.shortcode.' . md5($keyEn);
if ($cacheSevice->has($key)) {
return $cacheSevice->get($key);
}
$shortCodeItems = json_decode($domain->home_shortcode);
$filterParams = [];
if ($shortCodeItems != null) {
$filterParams = $this->simFilterService->getHomepageFilterParamsByShortCode($shortCodeItems);
}
$this->simFilterService->getSimHotForHome($domain->domain, $filterParams);
}
private function getBeautyNumber ($number) {
$number = str_replace([
',',
'.',
], [
'',
'',
], $number);
return trim($number);
}
}
| true |
5394382d947d4bf2e1b9c2df54f96611617b8651 | PHP | justinrhodes/Rhodes-Store-Git | /index.php | UTF-8 | 5,598 | 2.90625 | 3 | [] | no_license | <?php
include ("dbconnect.php");
include ("class_lib_test.php");
$producttoadd = $_POST['product'];
$product_check = "SELECT * FROM product";
$order_check = "SELECT * FROM orders";
if (mysql_num_rows(mysql_query($product_check)) <= 0){
//Generate random products and build product table
$products = new product();
$products->randomize_product();
}
else{}
if (mysql_num_rows(mysql_query($order_check)) <= 0){
//Generate random orders and build order table
$orders = new orders();
$orders->make_order();
}
else{}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Rhodes Test Store</title>
<style type="text/css">
<!--
@import url("css/reset.css");
@import url("css/styles.css");
-->
</style>
</head>
<body>
<?
if (isset($_POST['add'])){
$addproduct = new addstock();
$addproduct->add_specific($producttoadd,1,20);
$select_query = "SELECT product, product_id
FROM product
WHERE product_id = $producttoadd";
$result = mysql_query($select_query);
$row=mysql_fetch_array($result);
$addedproduct = $row['product'];
print "<div class='info'><h2>Stock added to $addedproduct.</h2></div>";
}
else if (isset($_POST['addtoall'])){
$addstock = new addstock();
$addstock->add_random(1,30);
print "<div class='info'><h2>Stock added to all products.</h2></div>";
}
else if (isset($_POST['reset'])){
mysql_query("TRUNCATE TABLE orders");
mysql_query("TRUNCATE TABLE product");
print "<div class='info'><h2>Tables have been reset. <a href='index.php'>Rebuild Tables Again</a></h2></div>";
}
else{}
// CREATE TABLE OF PRODUCTS AND AVAILABILITY
$select_products = "SELECT product, product_id, avail, on_order, DATE_FORMAT(arrival,'%M %d, %Y') AS arrival
FROM product";
$products_result = mysql_query($select_products);
?>
<div class="container">
<div class="tables">
<table>
<tr>
<th>Product</th>
<th>Product ID</th>
<th>Available</th>
<th>On Order</th>
<th>Arrival Date</th>
<th>Amount Sold</th>
<th>Average in Orders</th>
<th>Average Purchased</th>
</tr>
<?php
while($row=mysql_fetch_array($products_result)){
$product = $row['product'];
$product_id = $row['product_id'];
$avail = $row['avail'];
$on_order = $row['on_order'];
$arrival = $row['arrival'];
print "\n\t<tr>";
print "\n\t\t<td>$product</td>";
print "\n\t\t<td>$product_id</td>";
print "\n\t\t<td>$avail</td>";
print "\n\t\t<td>$on_order</td>";
print "\n\t\t<td>$arrival</td>";
//Add the total of the current product that is in the orders table
$select_total = "SELECT SUM(quantity) AS quantity_total FROM orders WHERE product_id=$product_id";
$row=mysql_fetch_array(mysql_query($select_total));
$total = $row['quantity_total'];
if ($total == null){
print "\n\t\t<td>0</td>";
}
else{
print "\n\t\t<td>$total</td>";
}
//Find the average appearance of product in all orders
$select_appearances = mysql_query("SELECT * FROM orders WHERE product_id=$product_id");
$appearances = mysql_num_rows($select_appearances);
$average_appearance = (($appearances / 20) * 100);
print "\n\t\t<td>$average_appearance%</td>";
$average_total = round(($total / $appearances),2);
if ($average_total == null){
print "\n\t\t<td>0</td>";
}
else{
print "\n\t\t<td>$average_total</td>";
}
print "\n\t</tr>\n";
}
?>
</table>
<?php
//CREATE TABLE OF CURRENT ORDERS
$select_orders = "SELECT o.order_num, DATE_FORMAT(date,'%M %d, %Y') AS date, o.product_id, o.quantity, p.product, p.product_id
FROM orders as o, product as p
WHERE p.product_id = o.product_id
ORDER BY o.order_num ASC";
$orders_result = mysql_query($select_orders);
?>
<table>
<tr>
<th>Order #</th>
<th>Date Placed</th>
<th>Product</th>
<th>Quantity</th>
</tr>
<?php
while($row=mysql_fetch_array($orders_result)){
$order_num = $row['order_num'];
$date = $row['date'];
$product = $row['product'];
$quantity = $row['quantity'];
print "\n\t<tr>";
print "\n\t\t<td>$order_num</td>";
print "\n\t\t<td>$date</td>";
print "\n\t\t<td>$product</td>";
print "\n\t\t<td>$quantity</td>";
print "\n\t</tr>\n";
}
?>
</table>
</div>
<div class="admin">
<form name="reset" action="index.php" method="post">
<input type="submit" name="reset" class="form_button" value="Clear Table">
</form>
<form name="addrandom" action="index.php" method="post">
<input type="submit" name="addtoall" class="form_button" value="Add Stock To All">
</form>
<form name="addproduct" action="index.php" method="post">
<select name="product">
<?php
$dropdown_select = "SELECT product, product_id
FROM product";
$result = mysql_query($dropdown_select);
while($row=mysql_fetch_array($result)){
$product = $row['product'];
$product_id = $row['product_id'];
?>
<option value="<?php print $product_id;?>"><?php print $product;?></option>
<?php
}
?>
</select>
<input type="submit" name="add" class="form_button" value="Add Stock">
</form>
<h2><a href="products.php" target="_blank">Products XML</a></h2>
<h2><a href="orders.php" target="_blank">Orders XML</a></h2>
<?php
mysql_close($con);
?>
</div>
</div>
</body>
</html> | true |
7c4a3eaa5ef0e4dd2a4e4a18cfe59fe97bd98adc | PHP | fredcido/simuweb | /application/modules/student-class/forms/RegisterSearch.php | UTF-8 | 3,129 | 2.515625 | 3 | [] | no_license | <?php
/**
*
* @author Frederico Estrela
*/
class StudentClass_Form_RegisterSearch extends App_Form_Default
{
const ID = 60;
public function init()
{
$this->setAttrib( 'class', 'horizontal-form' )->setName( 'search' );
$elements = array();
$elements[] = $this->createElement( 'text', 'class_name' )
->setDecorators( $this->getDefaultElementDecorators() )
->addFilter( 'StringTrim' )
->addFilter( 'StringToUpper' )
->setAttrib( 'maxlength', 200 )
->setAttrib( 'class', 'm-wrap span12 focused' )
->setLabel( 'Naran Klase' );
$dbDec = App_Model_DbTable_Factory::get( 'Dec' );
$rows = $dbDec->fetchAll( array(), array( 'name_dec' ) );
$optCeop[''] = '';
foreach ( $rows as $row )
$optCeop[$row->id_dec] = $row->name_dec;
$elements[] = $this->createElement( 'select', 'fk_id_dec' )
->setDecorators( $this->getDefaultElementDecorators() )
->setLabel( 'CEOP' )
->addMultiOptions( $optCeop )
->setRequired( true )
->setAttrib( 'class', 'm-wrap span12' );
$mapperEducationInsitute = new Register_Model_Mapper_EducationInstitute();
$rows = $mapperEducationInsitute->listByFilters();
$optEducationInstitute[''] = '';
foreach ( $rows as $row )
$optEducationInstitute[$row->id_fefpeduinstitution] = $row->institution;
$elements[] = $this->createElement( 'select', 'fk_id_fefpeduinstitution' )
->setDecorators( $this->getDefaultElementDecorators() )
->setLabel( 'Instituisaun Ensinu' )
->addMultiOptions( $optEducationInstitute )
->setRegisterInArrayValidator( false )
->setAttrib( 'class', 'm-wrap span12 chosen' );
$optTransport['1'] = 'Loke';
$optTransport['0'] = 'Taka';
$optTransport['2'] = 'Kansela';
$elements[] = $this->createElement( 'select', 'active' )
->setDecorators( $this->getDefaultElementDecorators() )
->setLabel( 'Status' )
->addMultiOptions( $optTransport )
->setValue( 1 )
->setRequired( true );
$elements[] = $this->createElement( 'text', 'start_date' )
->setDecorators( $this->getDefaultElementDecorators() )
->setAttrib( 'maxlength', 10 )
->setAttrib( 'class', 'm-wrap span12 date-mask date' )
->setLabel( 'Loron Inisiu' );
$elements[] = $this->createElement( 'text', 'schedule_finish_date' )
->setDecorators( $this->getDefaultElementDecorators() )
->setAttrib( 'maxlength', 10 )
->setAttrib( 'class', 'm-wrap span12 date-mask date' )
->setLabel( 'Loron Planu Remata' );
$filters = array(
'type' => Register_Model_Mapper_PerTypeScholarity::NON_FORMAL
);
$mapperScholarity = new Register_Model_Mapper_PerScholarity();
$optScholarity = $mapperScholarity->getOptionsScholarity( $filters );
$elements[] = $this->createElement( 'select', 'fk_id_perscholarity' )
->setDecorators( $this->getDefaultElementDecorators() )
->setRegisterInArrayValidator( false )
->addMultiOptions( $optScholarity )
->setAttrib( 'class', 'm-wrap span12 chosen' )
->setLabel( 'Kursu' );
$this->addElements( $elements );
}
} | true |
2c81fb7f9983802d82cea65e5fa6d5e225a31137 | PHP | upuadhikari/mvc | /src/Core/Router.php | UTF-8 | 1,260 | 2.875 | 3 | [] | no_license | <?php
namespace App\Core;
class Router extends Common
{
private $controller;
public function process(){
$pathInfo = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : null;
// default controller for home path
if(!$pathInfo){
$controllerClass = 'DefaultController';
$parsedUrl = [];
}else{
$parsedUrl = $this->parse($pathInfo);
$controllerClass = $this->toCamelCase(array_shift($parsedUrl)) . 'Controller';
}
if (file_exists(APPPATH.'Controller/' . $controllerClass . '.php')){
$controllerClass = '\App\Controller\\'.$controllerClass;
$this->controller = new $controllerClass;
}
else{
return $this->redirect('error');
}
// default method index to load
if(empty($parsedUrl)) $parsedUrl[] = 'index';
call_user_func_array(array($this->controller, array_shift($parsedUrl)), $parsedUrl);
}
public function parse($url){
$parsedUrl = parse_url($url);
$parsedUrl['path'] = ltrim($parsedUrl['path'], '/');
$parsedUrl['path'] = trim($parsedUrl['path']);
$params = explode('/', $parsedUrl['path']);
return $params;
}
private function toCamelCase($text)
{
$text = str_replace('-', ' ', $text);
$text = ucwords($text);
$text = str_replace(' ', '', $text);
return $text;
}
} | true |
3c943d7152443a66537a006576938dbc365d4450 | PHP | dianam05/notas_uv | /libs/notas-utility/class_admin_user.php | UTF-8 | 4,343 | 2.859375 | 3 | [
"Apache-2.0"
] | permissive | <?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of class_admin_user
*
* @author Desarrollador1
*/
class class_admin_user {
private $id;
private $username;
private $password;
private $email;
private $id_profile;
private $fecha_registro;
private $estado;
public function __construct() {
//$this->usuario=array();
}
public function exchangeArray($data) {
$this->id = (isset($data['id'])) ? $data['id'] : null;
$this->username = (isset($data['username'])) ? $data['username'] : null;
$this->password = (isset($data['password'])) ? $data['password'] : null;
$this->email = (isset($data['email'])) ? $data['email'] : null;
$this->id_profile = (isset($data['id_profile'])) ? $data['id_profile'] : null;
$this->fecha_registro = (isset($data['fecha_registro'])) ? $data['fecha_registro'] : null;
$this->estado = (isset($data['estado'])) ? $data['estado'] : null;
}
public function getUser(){
$db = ntDB::getInstance();
$mysqlVerUsuario="select * from user";
$resultado= $db->prepare( $mysqlVerUsuario );
$resultado->execute();
return $resultado->fetchAll();
//return $this->usuario;
}
public static function getAllUser(){
try {
$db = ntDB::getInstance();
$mysqlVerUsuario='select id, username, password, email, id_profile, fecha_registro, estado from user';
$resultado= $db->prepare( $mysqlVerUsuario );
$resultado->execute();
$users = array();
while ( $row = $resultado->fetch() ) {
$user = new class_admin_user();
$user->exchangeArray($row);
$users[] = $user;
}
return $users;
}catch(Exception $e){
return array();
return $e->getMessage();
}
//return $this->usuario;
}
public function createUser($username, $password, $email, $id_profile, $estado){
try{
$password2 = md5($password);
$now = date('Y/m/d h:i:s');
$db = ntDB::getInstance();
$sql = ' insert into user (username, password, email, id_profile, fecha_registro, estado) values (?,?,?,?,?,?) ';
$s = $db->prepare( $sql );
$s->bindParam( 1, $username );
$s->bindParam( 2, $password2 );
$s->bindParam( 3, $email );
$s->bindParam( 4, $id_profile, PDO::PARAM_INT );
$s->bindParam( 5, $now );
$s->bindParam( 6, $estado, PDO::PARAM_INT );
$s->execute();
$this->id=$db->lastInsertId();
$this->username=$username;
$this->password=$password;
$this->email=$email;
$this->id_profile=$id_profile;
$this->fecha_registro=$now;
$this->estado=$estado;
return true;
}catch(Exception $e){
return false;
return $e->getMessage();
}
}
public function getTipo() {
if($this->id_profile == '1'){
return 'Admin';
}elseif($this->id_profile == '2'){
return 'Usuario';
}else{
return 'Desconocido';
}
}
public function getTipoEstado() {
if($this->estado == '1'){
return 'Activo';
}elseif($this->estado == '0'){
return 'Inactivo';
}else{
return 'Desconocido';
}
}
public function getId() {
return $this->id;
}
public function getUsername() {
return $this->username;
}
public function getPassword() {
return $this->password;
}
public function getEmail() {
return $this->email;
}
public function getIdProfile() {
return $this->id_profile;
}
public function getFechaRegistro() {
return $this->fecha_registro;
}
public function getEstado() {
return $this->estado;
}
}
?>
| true |
5a459540fcfe8970658f80052a7c11e5909860a3 | PHP | joaoinacio/LegacyBridge | /mvc/Templating/Twig/Template.php | UTF-8 | 2,006 | 2.84375 | 3 | [] | no_license | <?php
/**
* File containing the Template class.
*
* @copyright Copyright (C) eZ Systems AS. All rights reserved.
* @license For full copyright and license information view LICENSE file distributed with this source code.
* @version //autogentag//
*/
namespace eZ\Publish\Core\MVC\Legacy\Templating\Twig;
use Twig_Environment;
use Twig_TemplateInterface;
use eZ\Publish\Core\MVC\Legacy\Templating\LegacyEngine;
/**
* Twig Template class representation for a legacy template.
*/
class Template implements Twig_TemplateInterface
{
private $templateName;
/**
* @var \Twig_Environment
*/
private $env;
/**
* @var \eZ\Publish\Core\MVC\Legacy\Templating\LegacyEngine
*/
private $legacyEngine;
public function __construct($templateName, Twig_Environment $env, LegacyEngine $legacyEngine)
{
$this->templateName = $templateName;
$this->env = $env;
$this->legacyEngine = $legacyEngine;
}
/**
* Renders the template with the given context and returns it as string.
*
* @param array $context An array of parameters to pass to the template
*
* @return string The rendered template
*/
public function render(array $context)
{
return $this->legacyEngine->render($this->templateName, $context);
}
/**
* Displays the template with the given context.
*
* @param array $context An array of parameters to pass to the template
* @param array $blocks An array of blocks to pass to the template
*/
public function display(array $context, array $blocks = array())
{
echo $this->render($context);
}
/**
* Returns the bound environment for this template.
*
* @return Twig_Environment The current environment
*/
public function getEnvironment()
{
return $this->env;
}
/**
* @return string
*/
public function getTemplateName()
{
return $this->templateName;
}
}
| true |
8ee626d76c765d83400782b95ae482c7cee7fbcb | PHP | justjohn/foundry-core | /lib/Foundry/Core/Auth/User.php | UTF-8 | 1,274 | 2.84375 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
/**
* Authentication service user.
*
* @category Foundry-Core
* @package Foundry\Core\Auth
* @author John Roepke <john@justjohn.us>
* @copyright 2010-2011 John Roepke
* @license http://phpfoundry.com/license/bsd New BSD license
* @version 1.0.0
*/
namespace Foundry\Core\Auth;
use \Foundry\Core\Model;
/**
* Authentication service user.
*
* @category Foundry-Core
* @package Foundry\Core\Auth
* @author John Roepke <john@justjohn.us>
* @copyright 2010-2011 John Roepke
* @license http://phpfoundry.com/license/bsd New BSD license
* @since 1.0.0
*/
class User extends \Foundry\Core\BaseModel {
private $fields = array("username"=>Model::STR,
"displayName"=>Model::STR,
"email"=>Model::STR,
"firstName"=>Model::STR,
"surname"=>Model::STR);
private $key_field = "username";
function __construct($username='', $email='', $displayname='', $fisrtname='', $surname='') {
parent::__construct($this->fields, $this->key_field);
parent::setUsername($username);
parent::setEmail($email);
parent::setDisplayName($displayname);
parent::setFirstName($fisrtname);
parent::setSurname($surname);
}
}
?>
| true |
468a8e98bc80280314627634433e28c815941c1c | PHP | kozennnn/tmdb-api | /src/Api/v3/Collections.php | UTF-8 | 1,113 | 2.53125 | 3 | [] | no_license | <?php
namespace Kozennnn\TmdbAPI\Api\v3;
use Kozennnn\TmdbAPI\Api\Api;
class Collections extends Api
{
/**
* Get collection details by id.
*
* @param int $collectionId
* @param array $parameters
* @return array
*/
public function getDetails(int $collectionId, array $parameters = []): array
{
return $this->get(3, 'collection/' . $collectionId, $parameters);
}
/**
* Get the images for a collection by id.
*
* @param int $collectionId
* @param array $parameters
* @return array
*/
public function getImages(int $collectionId, array $parameters = []): array
{
return $this->get(3, 'collection/' . $collectionId . '/images', $parameters);
}
/**
* Get the list translations for a collection by id.
*
* @param int $collectionId
* @param array $parameters
* @return array
*/
public function getTranslations(int $collectionId, array $parameters = []): array
{
return $this->get(3, 'collection/' . $collectionId . '/translations', $parameters);
}
} | true |
d5c0682f1a53208654b62367b51f1244ea0ec2fa | PHP | KaterynaKostrubova/PHP-pool | /php_rush00/install.php | UTF-8 | 5,813 | 2.75 | 3 | [] | no_license | <?php
if ($_POST["msqlogin"] == false || $_POST["msqpasswd"] == false || $_POST["dbname"] == false || $_POST["submit"] != "OK") {
exit("BAD INPUT" . PHP_EOL);
}
// echo "Connection died(maybe you have already created a new database?)".PHP_EOL;
$servername = "localhost";
$username = $_POST['msqlogin'];
$password = $_POST['msqpasswd']; //Пароль mysql, который ты задавал при установке МАМПА
$dbname = $_POST['dbname'];
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Удаляем старую БД
unlink('shopdb.csv');
$sql = "DROP DATABASE IF EXISTS $dbname";
mysqli_query($conn, $sql);
// if (!mysqli_query($conn, $sql)) {
// die("Error dropping db: " . mysqli_error($conn));
// }
// Создаем БД
$sql = "CREATE DATABASE IF NOT EXISTS $dbname";
if (!mysqli_query($conn, $sql)) {
die("Error creating database: " . mysqli_error($conn));
}
mysqli_close($conn);
//Подключаемся к БД
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Создаем таблицу категории
$sql = "CREATE TABLE IF NOT EXISTS categories (
id INT(11) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL
)";
if (!mysqli_query($conn, $sql)) {
die("Error creating categories: " . mysqli_error($conn));
}
// Наполняем таблицу категорий
$sql = "INSERT INTO categories (id, title)
VALUES (1, 'Black'), (2, 'White'), (3, 'Red')";
if (!mysqli_query($conn, $sql)) {
die("Error filling categories: " . mysqli_error($conn));
}
// Создаем таблицу продуктов
$sql = "CREATE TABLE IF NOT EXISTS products (
id INT(11) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
img VARCHAR(255) DEFAULT NULL,
category VARCHAR(255) DEFAULT NULL,
intro text NOT NULL,
price DECIMAL(10,0) NOT NULL
)";
if (!mysqli_query($conn, $sql)) {
die("Error creating products: " . mysqli_error($conn));
}
// Наполняем таблицу продуктов
$sql = "INSERT INTO products (id, title, img, intro, price, category)
VALUES (1, 'Dusia', 'https://static.tbdcdn.com/uploads/2016/02/17/sub/75918-large-296708.jpg', 'Very good cat!!!', '15', 'Black'),
(2, 'Oliver', 'https://avatars.mds.yandex.net/get-pdb/163339/3ed630f1-5781-40dd-8ba2-a3ff7ac1c85b/s1200', 'Mrrrr', '13', 'Black'),
(3, 'Simba', 'https://i.pinimg.com/originals/55/6a/fc/556afca830d3ee27cf083ada67039f17.jpg', 'I like milk', '50', 'White'),
(4, 'Tigger', 'https://www.iizcat.com/uploads/2016/06/pt9mg-pb4.JPG', 'I am so cute', '7', 'Red'),
(5, 'Lucy', 'https://themeowthing.com/wp-content/uploads/2017/11/100-Unique-Black-Cat-Names-To-Know-For-The-First-Time5.jpg', 'I like to sleep', '30', 'Black'),
(6, 'Shroedinger `s cat', 'https://media.mnn.com/assets/images/2015/02/catinabox.jpg.653x0_q80_crop-smart.jpg', 'I am alive!!!', '20', 'Black'),
(7, 'Princess', 'https://ae01.alicdn.com/kf/HTB1DqO3NXXXXXbDaXXXq6xXFXXXm/simulation-white-cat-model-plastic-fur-handicraft-21x16-cm-right-prone-cat-with-yellow-head-home.jpg', 'I am princess, It’s obvious', '15', 'White'),
(8, 'Bella', 'https://vignette.wikia.nocookie.net/roseclan-roleplaying/images/2/29/Red-cat.jpg/revision/latest?cb=20140830030726', 'I princess too!', '42', 'Red'),
(9, 'Simon', 'https://img.buzzfeed.com/buzzfeed-static/static/2013-10/enhanced/webdr06/29/14/enhanced-buzz-orig-25698-1383070842-15.jpg?downsize=700:*&output-format=auto&output-quality=auto', 'I am happy', '9', 'Black')";
if (!mysqli_query($conn, $sql)) {
die("Error filling products: " . mysqli_error($conn));
}
// Создаем таблицу категорий продуктов для связи и заполняем ее в формате:
// (id категории, id товара)
$sql = "CREATE TABLE IF NOT EXISTS categories_products (
id_category INT(11) NOT NULL,
id_product INT(11) NOT NULL,
PRIMARY KEY (id_category, id_product)
)";
if (!mysqli_query($conn, $sql)) {
die("Error creating categories_products: " . mysqli_error($conn));
}
$sql = "INSERT INTO categories_products (id_category, id_product)
VALUES (1, 1), (2, 2), (3, 3), (1, 6), (2, 4), (3, 5), (1, 7), (2, 9), (3, 8)";
if (!mysqli_query($conn, $sql)) {
die("Error filling categories: " . mysqli_error($conn));
}
// Создаем таблицу заказов
$sql = "CREATE TABLE IF NOT EXISTS orders (
id_ord INT(11) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255) NOT NULL,
email VARCHAR(255),
address VARCHAR(255)
)";
if (!mysqli_query($conn, $sql)) {
die("Error creating order: " . mysqli_error($conn));
}
// Создаем таблицу юзеров и добавляем админа
$sql = "CREATE TABLE IF NOT EXISTS users (
id INT(11) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255) NOT NULL,
password TEXT NOT NULL,
isadmin BOOLEAN NOT NULL,
email VARCHAR(255),
address VARCHAR(255)
)";
if (!mysqli_query($conn, $sql)) {
die("Error creating users: " . mysqli_error($conn));
}
$adminPass = hash('whirlpool', 'admin');
$sql = "INSERT INTO users (id, username, password, isadmin)
VALUES (1, 'admin', '" . $adminPass . "', true)";
if (!mysqli_query($conn, $sql)) {
die("Error filling users: " . mysqli_error($conn));
}
file_put_contents('shopdb.csv', "$username;$password;$dbname");
mysqli_close($conn);
session_start();
foreach ($_SESSION as $key => $value) {
$_SESSION[$key] = false;
}
header('Location: index.php');
?>
| true |
d368930cb0fa77924c1f70aae16f4d10ee4d16fa | PHP | pascalwacker/msgphp | /src/Domain/Message/DomainMessageBus.php | UTF-8 | 774 | 2.8125 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types=1);
namespace MsgPhp\Domain\Message;
/**
* @author Roland Franssen <franssen.roland@gmail.com>
*/
final class DomainMessageBus implements DomainMessageBusInterface
{
private $commandBus;
private $eventBus;
private $eventClasses;
public function __construct(DomainMessageBusInterface $commandBus, DomainMessageBusInterface $eventBus, array $eventClasses)
{
$this->commandBus = $commandBus;
$this->eventBus = $eventBus;
$this->eventClasses = array_flip($eventClasses);
}
public function dispatch($message): void
{
if (isset($this->eventClasses[\get_class($message)])) {
$this->eventBus->dispatch($message);
} else {
$this->commandBus->dispatch($message);
}
}
}
| true |
2c673e468e3b878d4a0a582853e44540f0ff444c | PHP | gaspos/pehapkari.cz-1 | /packages/Training/src/Entity/Watchdog.php | UTF-8 | 1,711 | 2.515625 | 3 | [] | no_license | <?php declare(strict_types=1);
namespace Pehapkari\Training\Entity;
use Doctrine\ORM\Mapping as ORM;
use Knp\DoctrineBehaviors\Model\Timestampable\Timestampable;
/**
* @ORM\Entity
*/
class Watchdog
{
use Timestampable;
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
* @var int
*/
private $id;
/**
* @ORM\Column(type="text", length=255)
* @var string
*/
private $email;
/**
* @ORM\Column(type="text", length=255, nullable=true)
* @var string
*/
private $note;
/**
* @ORM\Column(type="boolean")
* @var bool
*/
private $isInformed = false;
/**
* @ORM\ManyToOne(targetEntity="Pehapkari\Training\Entity\Training")
* @var Training
*/
private $training;
public function getId(): ?int
{
return $this->id;
}
public function setId(?int $id): void
{
$this->id = $id;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(?string $email): void
{
$this->email = $email;
}
public function isInformed(): ?bool
{
return $this->isInformed;
}
public function setIsInformed(?bool $isInformed): void
{
$this->isInformed = $isInformed;
}
public function getNote(): ?string
{
return $this->note;
}
public function setNote(?string $note): void
{
$this->note = $note;
}
public function getTraining(): ?Training
{
return $this->training;
}
public function setTraining(?Training $training): void
{
$this->training = $training;
}
}
| true |
cafd25bf408cd3d30b2c83b87b7b2427d407f8bd | PHP | Jazzo/MyFw | /Savant3/Savant3/resources/Savant3_Plugin_inputField.php | UTF-8 | 4,007 | 2.984375 | 3 | [] | no_license | <?php
class Savant3_Plugin_inputField extends Savant3_Plugin {
/*
* Other attributes managed by a simple foreach
*/
public $_attr_other = array(
'id',
'size',
'maxlength',
'rows',
'cols',
'class',
'onclick',
'placeholder',
'pattern',
'step'
);
/**
*
* Generate an HTML for INPUT field
* Manage:
* <input type="$type" ...
* <input type="hidden" ...
* <textarea ...
*
* @access public
*
*/
public function inputField($name, $attrs = array())
{
$html = "";
// init TYPE Default Value: INPUT
$type = isset($attrs["type"]) ? $attrs["type"] : "text";
// init ID Default Value: INPUT
if(!isset($attrs["id"])) {
$attrs["id"] = $name;
}
// check if ERRORS exists
$hasError = isset($attrs["error"]) ? true : false;
if($hasError) {
$html .= '<div class="error">';
}
// set LABEL
if( $type != "hidden" && isset($attrs["label"]))
{
// $label = isset($attrs["label"]) ? $attrs["label"] : "Set Label...";
$html .= '<label for="'.htmlspecialchars($name).'">'.htmlspecialchars($attrs["label"]).':</label>'; // TODO: improve it with more kind of labels...
}
// set TYPE (manage also textarea)
$is_textarea = false;
if($type == "textarea") {
$html .= '<textarea ';
$is_textarea = true;
} else {
$html .= '<input type="'.$type.'"';
}
// set NAME
if(isset($attrs["set_array"])) {
$html .= ' name="'.htmlspecialchars($attrs["set_array"]).'['.htmlspecialchars($name).']"';
} else {
$html .= ' name="'.htmlspecialchars($name).'"';
}
// set OTHER ATTRIBUTES
foreach ($this->_attr_other AS $attribute) {
if(isset($attrs[$attribute])) {
$html .= ' '.htmlspecialchars($attribute).'="'.htmlspecialchars($attrs[$attribute]).'"';
}
}
// REQUIRED
if(isset($attrs["required"]) && $attrs["required"] === true) {
$html .= ' required';
}
// DISABLED
if(isset($attrs["disabled"]) && $attrs["disabled"] === true) {
$html .= ' disabled';
}
// READONLY
if(isset($attrs["readonly"]) && $attrs["readonly"] === true) {
$html .= ' readonly';
}
// set VALUE if it's defined by attributes
$value = null;
if(isset($attrs["value"]) && $attrs["value"] != "") {
$value = $attrs["value"];
}
// echo "Value: $value<br>";
// CLOSE TAG and SET Value
if( $is_textarea ) {
$html .= '>'.$value.'</textarea>';
} else {
$html .= !is_null($value) ? ' value="'.htmlspecialchars($value, ENT_QUOTES).'"' : '';
$html .= ' />';
}
// NOTE
if(isset($attrs["note"])) {
$html .= ' <span id="np_'.htmlspecialchars($name).'">'.$attrs["note"].'</span>';
}
$html .= ( $type != "hidden") ? '<br />' : '';
// ERRORS message
if($hasError) {
if( is_bool($attrs["error"]) ) {
if( isset($attrs["errorMessage"]) && $attrs["errorMessage"] != "" ) {
$error = $attrs["errorMessage"];
} else {
$error = 'Questo campo è obbligatorio!';
}
} else {
$error = $attrs["error"];
}
$html .= "<p>" . $error . "</p></div>";
}
return $html;
}
}
?> | true |
7193c4b525d3ffca668bf4f0189270ba348a0661 | PHP | edisonmoura/sgos | /exemplo_graficos/grafico_barras.php | UTF-8 | 513 | 2.890625 | 3 | [] | no_license | <?php
require("phplot-5.8.0/phplot.php");
// Cria objeto do gráfico passando o tamanho
$grafico = new PHPlot(350,350);
$dados = array(
array('Meninos','36'),
array('Meninas','2')
);
// Definindo o tipo de gráfico
$grafico->SetPlotType('bars');
// Passando os dados para o gráfico
$grafico->SetDataValues($dados);
// Define os títulos do gráfico
$grafico->SetTitle("Alunos e Alunas na Sala");
$grafico->SetXTitle('Sexo');
$grafico->SetYTitle('Quantidade');
// Desenha o gráfico
$grafico->DrawGraph();
| true |
111acf60871967d2356a5159e7f3e22b6cb62601 | PHP | satyaaec/satya1 | /module/Application/src/Application/Form/ContactForm.php | UTF-8 | 2,358 | 2.703125 | 3 | [] | no_license | <?php
namespace Application\Form;
use Zend\Form\Form;
class ContactForm extends Form {
public function __construct($name = null) {
// we want to ignore the name passed
parent::__construct('form');
$this->setAttribute('method', 'post');
$this->add(array(
'name' => 'id',
'attributes' => array(
'type' => 'hidden',
),
));
$this->add(array(
'name' => 'name',
'attributes' => array(
'type' => 'text',
'class' => 'form-control',
'id'=>'name'
),
'options' => array(
'label' => NULL,
),
));
$this->add(array(
'name' => 'email',
'attributes' => array(
'type' => 'email',
'class' => 'form-control',
'id'=>'email'
),
'options' => array(
'label' => NULL,
),
));
$this->add(array(
'name' => 'phone_no',
'attributes' => array(
'type' => 'number',
'class' => 'form-control',
'id'=>'phone_no'
),
'options' => array(
'label' => NULL,
),
));
$this->add(array(
'type' => 'Zend\Form\Element\Textarea',
'name' => 'message',
'attributes' => array(
'id'=>'message',
'class'=>'form-control',
'cols'=>25,
'rows'=>4
),
'options' => array(
'label' => NULL,
),
));
$this->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Contact Us',
'id' => 'submit',
'class' => 'btn btn-default'
),
));
$this->add(array(
'name' => 'cancel',
'attributes' => array(
'type' => 'reset',
'value' => 'Cancel',
'id' => 'cancelButton',
'class' => 'btn btn-default'
),
));
}
}
?> | true |
c5bc4dcbaf4165b7ef2539cb266d73cb336288e1 | PHP | joshredel/Orientation-Week-Registration-System | /old/ga/checkout-JoshAcer.php | UTF-8 | 5,624 | 2.75 | 3 | [] | no_license | <?
// connect to the database
$link = mysql_connect('localhost', 'orientation2011', 'regerd8') or die('Could not connect: ' . mysql_error());
mysql_select_db('fos') or die('Could not select database');
// if something was posted, add it to the database
if(isset($_POST['studentid'])) {
// first check if we actually have such a student in the database
// compose the select query to look for an existing student
$checkQuery = "SELECT * FROM GeneralAssembly WHERE StudentID=" . $_POST['studentid'] . " AND ClickerNumber='" . $_POST['clickernumber'] . "'";
$checkResult = mysql_query($checkQuery) or die('Check query failed: ' . mysql_error());
// see how many results we have (sloppy but it works for this application)
$foundCount = 0;
while($entry = mysql_fetch_array($checkResult, MYSQL_ASSOC)) {
$foundCount++;
}
// did we find it?
if($foundCount >= 1) {
// we found one, so delete it
// generate the MySQL query
$insertQuery = "DELETE FROM GeneralAssembly WHERE StudentID=" . $_POST['studentid'];
// generate a query to add a deletion entry into the permanent table
$insertQuery2 = "INSERT INTO GeneralAssemblyPermanent (StudentID, RegistrationTime) ";
$insertQuery2 .= "VALUES (-" . $_POST['studentid'] . ", "; // use a negative to denote check out
$insertQuery2 .= "NOW())";
// run the query
$insertResult = mysql_query($insertQuery) or die('Query 1 failed: ' . mysql_error());
$insertResult = mysql_query($insertQuery2) or die('Query 2 failed: ' . mysql_error());
// create a message
$message = "Student " . $_POST['studentid'] . " was successfully removed.";
} else {
// we didn't find one...
$badMessage = "Student " . $_POST['studentid'] . " with clicker " . $_POST['clickernumber'] . " was never checked in...";
}
}
// start the query to get all records
$query = 'SELECT * FROM GeneralAssembly';
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
// prepare stats
$totalStudents = 0;
$totalPress = 0;
$totalVolunteers = 0;
// iterate through all of the entries to get stats
while($entry = mysql_fetch_array($result, MYSQL_ASSOC)) {
// collect stats
$totalStudents++;
// check if they are in the press
if(substr($entry['PassInfo'], 0, -2) == 'PRESS') {
$totalPress++;
}
// check if they are a volunteer
if(substr($entry['PassInfo'], 0, -2) == 'STAFF') {
$totalStaff++;
}
// add them to the count for their faculty
$facultyCount[$entry['Faculty']]++;
}
// clean up
mysql_free_result($result);
mysql_close($link);
?>
<!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=utf-8" />
<title>General Assembly - Check Out</title>
<style>
table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
th {
width: 150px;
}
td {
text-align: left;
}
label {
display:block;
font-weight:bold;
text-align:right;
width:140px;
float:left;
}
input {
float:left;
font-size:12px;
padding:4px 2px;
border:solid 1px;
width:200px;
margin:2px 0 20px 10px;
}
.spacer {
clear:both;
height:1px;
}
button {
clear: both;
margin-left:150px;
width:125px;
height:31px;
text-align:center;
line-height:31px;
font-size:11px;
font-weight:bold;
}
#message {
color: #090;
}
#badmessage {
color: #900;
}
</style>
<script type="text/JavaScript">
function autoSelectAndFade() {
// auto select the faculty field
var textInput = document.getElementById('studentid');
textInput.focus();
textInput.select();
// fade out the message field after 3 seconds
setTimeout("var messageField = document.getElementById('message');messageField.style.display = 'none';", 3000);
//setTimeout("var messageField = document.getElementById('badmessage');messageField.style.display = 'none';", 3000);
}
function checkForm(form) {
// check for an ID
if(form.studentid.value == "") {
alert("Please enter a student ID.");
form.studentid.focus();
form.studentid.select();
return false;
}
// good to go!
return true;
}
</script>
</head>
<body onload="autoSelectAndFade()">
<h1>General Assembly - Check Out</h1>
<h2>Tools</h2>
<a href="index.php">Home</a> ||
<a href="checkin.php">Check In</a> ||
Check Out
<h2>Remove A Participant</h2>
<div id="message"><?= $message ?></div><br />
<div id="badmessage"><?= $badMessage ?></div><br />
<form method="post" onsubmit="return checkForm(this)">
<label for="studentid">Student ID:</label>
<input name="studentid" id="studentid" type="number" />
<div class="spacer"></div>
<label for="clickernumber">Clicker number:</label>
<input name="clickernumber" type="text" value="0" />
<div class="spacer"></div>
<button type="submit">Remove</button>
<div class="spacer"></div>
</form>
<br />
<br />
<h2>Current Statistics</h2>
<strong>Total Students:</strong><br />
<?= $totalStudents ?><br /><br />
<strong>Quorum Breakdown</strong>
<table>
<tr>
<th>Faculty</th>
<th>Count</th>
</tr>
<?
foreach($facultyCount as $faculty=>$count) {
echo("<tr><td>" . $faculty . "</td><td>" . $count . "</td></tr>");
}
?>
</table><br />
<strong>Total Press:</strong><br />
<?= $totalPress ?>
</body>
</html> | true |
466ce0c3577fa0f29b9b7f8a07988393eca4a874 | PHP | ministryofjustice/opg-use-an-lpa | /service-front/app/src/Common/src/Form/Fieldset/Date.php | UTF-8 | 710 | 2.640625 | 3 | [
"LicenseRef-scancode-proprietary-license",
"MIT"
] | permissive | <?php
declare(strict_types=1);
namespace Common\Form\Fieldset;
use Laminas\Form\Fieldset;
/**
* This fieldset is only suitable for catching AD dates
* To validate this fieldset use the Common\Validator\DateValidator or any of it's descendant validators
*/
class Date extends Fieldset
{
public function __construct(?string $name = null, array $options = [])
{
parent::__construct($name, $options);
$this->add([
'name' => 'day',
'type' => 'Text',
]);
$this->add([
'name' => 'month',
'type' => 'Text',
]);
$this->add([
'name' => 'year',
'type' => 'Text',
]);
}
}
| true |
61a1e78283921853a44e8871a099500755a25393 | PHP | thingsmart/Lacerenza | /lacerenza/lib/operazioni_polizza.lib.php | UTF-8 | 5,068 | 2.5625 | 3 | [] | no_license | <?php
include("../databases/db_function.php");
require_once("../lib/verificaConvertiData.php");
include("../lib/funzioni_sito.php");
require_once("../classi/class.Polizze.php");
require_once("../classi/class.Log.php");
session_start();
$tipo = $_POST['tipo'];
$log = new Log();
switch($tipo){
case "inserimento":
$id_commessa = $_POST['id_commessa'];
$descrizione = $_POST['descrizione'];
$importo = $_POST['importo'];
$polizza_svincolata = $_POST['polizza_svincolata'];
$data_stipula = $_POST['data_stipula'];
$data_stipula = Capovolgidata($data_stipula);
$scadenza = $_POST['scadenza'];
$scadenza = Capovolgidata($scadenza);
$descrizione = StringInputCleaner($descrizione);
//$descrizione = str_replace("°", "°", $descrizione);
$importo = str_replace(",", ".", $importo);
$tipo_cartella = $_POST['tipo_cartella'];
$cartella = $_POST['cartella'];
//perorso dove fare upload file
$target_path = "../uploads/".$cartella."/".$id_commessa."/".$tipo_cartella."/";
$target_path_inserimento = "uploads/".$cartella."/".$id_commessa."/".$tipo_cartella."/";
//nome del file
$filename = $_FILES['files']['name'];
if($filename != ""){
//creo cartella se non esiste
if (!is_dir($target_path)) {
$crea = mkdir($target_path, 0777, true);
}
//elimino file caricati prima
$link_file = "../uploads/".$cartella."/".$id_commessa."/".$tipo_cartella."/".$filename;
if (file_exists($link_file)) {
$filename = date("d_m_Y_h_i_s").$filename;
$link_file = "../uploads/".$cartella."/".$id_commessa."/".$tipo_cartella."/".$filename;
}
move_uploaded_file($_FILES["files"]["tmp_name"], $link_file);
}
$polizze = new Polizze();
$e_query_inserimento = $polizze->inserisciPolizza($id_commessa, $descrizione, $importo, $polizza_svincolata, $data_stipula, $scadenza, $target_path_inserimento, $filename);
//LOG
$log->inserisciLog("Inserimento polizza", $_SESSION['username'], "verde");
echo $e_query_inserimento;
break;
case "elimina":
$polizze = new Polizze();
$id = $_POST['id'];
$id_commessa = $_POST['id_commessa'];
$nome = $_POST['nome'];
$e_query_elimina = $polizze->eliminaPolizza($id);
if($e_query_elimina > 0){
if($nome != ""){
$target_path = "../uploads/commesse/".$id_commessa."/polizze/".$nome;
if (file_exists($target_path)) {
unlink($target_path);
}
}
}
//LOG
$log->inserisciLog("Eliminazione polizza", $_SESSION['username'], "rosso");
echo $e_query_elimina;
break;
case "elimina_allegato":
$polizze = new Polizze();
$id = $_POST['id'];
$id_commessa = $_POST['id_commessa'];
$nome = $_POST['nome'];
$e_query_elimina = $polizze->eliminaAllegato($id);
if($e_query_elimina >= 0){
//elimino fisicamente l'allegato
$target_path = "../uploads/commesse/".$id_commessa."/polizze/".$nome;
if (file_exists($target_path)) {
unlink($target_path);
}
}
echo $e_query_elimina;
break;
case "modifica":
$id = $_POST['id_da_modificare'];
$id_commessa = $_POST['id_commessa'];
$descrizione = $_POST['descrizione'];
$importo = $_POST['importo'];
$polizza_svincolata = $_POST['polizza_svincolata'];
$data_stipula = $_POST['data_stipula'];
$data_stipula = Capovolgidata($data_stipula);
$scadenza = $_POST['scadenza'];
$scadenza = Capovolgidata($scadenza);
$descrizione = StringInputCleaner($descrizione);
//$descrizione = str_replace("°", "°", $descrizione);
$importo = str_replace(",", ".", $importo);
$tipo_cartella = $_POST['tipo_cartella'];
$cartella = $_POST['cartella'];
//perorso dove fare upload file
$target_path = "../uploads/".$cartella."/".$id_commessa."/".$tipo_cartella."/";
$target_path_modifica = "uploads/".$cartella."/".$id_commessa."/".$tipo_cartella."/";
//nome del file
$filename = $_FILES['files']['name'];
if($filename != ""){
//creo cartella se non esiste
if (!is_dir($target_path)) {
$crea = mkdir($target_path, 0777, true);
}
$link_file = "../uploads/".$cartella."/".$id_commessa."/".$tipo_cartella."/".$filename;
if (file_exists($link_file)) {
$filename = date("d_m_Y_h_i_s").$filename;
$link_file = "../uploads/".$cartella."/".$id_commessa."/".$tipo_cartella."/".$filename;
}
move_uploaded_file($_FILES["files"]["tmp_name"], $link_file);
}
$polizze = new Polizze();
$e_query_inserimento = $polizze->modificaPolizza($id, $id_commessa, $descrizione, $importo, $polizza_svincolata, $data_stipula, $scadenza, $target_path_modifica, $filename);
$log->inserisciLog("Modifica polizza", $_SESSION['username'], "blu");
echo $e_query_inserimento;
break;
}
//To SANITIZE String value use
function StringInputCleaner($data) {
//remove space bfore and after
$data = trim($data);
//remove slashes
$data = stripslashes($data);
$data = (filter_var($data, FILTER_SANITIZE_STRING));
$data = utf8_encode($data);
return $data;
}
?> | true |
2f1ff7dcb4c670c424fa737664a299d2ce04adfc | PHP | CSE406/Crew_DB | /my DB/Billboard.php | UTF-8 | 1,504 | 2.578125 | 3 | [] | no_license | <?php
header("Content-type: text/html; charset=utf-8");
include('./DBHandler.php');
$dao = new Dao();
$query = $_REQUEST['query'];
$genres = $_REQUEST['genres'];
$user_id = $_REQUEST['user_id'];
$strTok =explode(',', $genres);
$count = count($strTok);
$genre = "";
for($i = 0 ; $i < $count-1 ; $i++){
$genre = $genre."genre = '".$strTok[$i]."' OR ";
}
$genre = $genre." genre = '".$strTok[$i]."' ";
// echo "$genre <br/>";
// error_reporting(E_ALL);
// ini_set("display_errors", 1);
if ($query == "selectGenreTop") {
$resultSet = $dao->getResultSet( $dao->getConnection(),
" SELECT DISTINCT id, album_spotify_id, title, artist, rating
FROM song LEFT OUTER JOIN ( SELECT song_id, rating FROM rating WHERE user_id = $user_id ) AS mysong
ON song.id = mysong.song_id
WHERE id IN (SELECT song_id FROM billboardGenreTop WHERE genre = $genre )
ORDER BY rand(); "
);
print_r( json_encode( $dao->selectSimpleSong( $resultSet ) ) );
} else if ($query == "selectHot100") {
$resultSet = $dao->getResultSet( $dao->getConnection(),
" SELECT DISTINCT id, album_spotify_id, title, artist, rating
FROM song JOIN billboardHot100
ON song.id = billboardHot100.song_id
LEFT OUTER JOIN ( SELECT song_id, rating FROM rating WHERE user_id = $user_id ) AS mysong
ON song.id = mysong.song_id
ORDER BY billboardHot100.rank
"
);
print_r( json_encode( $dao->selectSimpleSong( $resultSet ) ) );
}
?> | true |
b1496deb25806e2d6ab9eb4d9ae6ea3d1c85ba38 | PHP | mpirizdutra/stScreamTech | /core/app/model/clsEstado_garantiza.php | UTF-8 | 410 | 2.578125 | 3 | [] | no_license | <?php
class clsEstado_garantiza
{
public static $tablename = " estado_garantiza ";
public function __construct(){
$this->id_garantiza = "";
$this->estado_garantiza="";
}
public static function getAll(){
$sql = "select * from ".self::$tablename;
$query = Executor::doit($sql);
return Model::many($query[0],new clsEstado_garantiza());
}
}
?> | true |
ecf5f537969d41313c799af947683c9abe27fe17 | PHP | pinsoneatra/reimireal | /app/models/directory/Opendir.php | UTF-8 | 1,487 | 2.890625 | 3 | [] | no_license | <?php
namespace models\directory;
class Opendir {
public function __construct() {
}
public function targetFile($folder) {
$target_dir = $_SERVER['DOCUMENT_ROOT'] . URL_SUB_FOLDER . "/storage/" . $folder . "/";
$target_dir = str_replace('//', '/', $target_dir);
return $target_dir;
}
public function deleteFile($file, $folder) {
$target_dir = $_SERVER['DOCUMENT_ROOT'] . URL_SUB_FOLDER . "/storage/" . $folder . "/";
$target_dir = str_replace('//', '/', $target_dir);
if (unlink($target_dir . $file)) {
return true;
} else {
return false;
}
}
public function createFolder($path, $folder = "", $method = "") {
$newpath = $this->targetFile($path);
$dateTimeFolder = "";
$oldmask = "";
switch ($method) {
case "datetime":
$dateTimeFolder = strtotime(date('Y-m-d H:i:s'));
if (!file_exists($newpath . $dateTimeFolder)) {
$oldmask = umask(0);
mkdir($newpath . $dateTimeFolder);
umask($oldmask);
}
break;
default :
if (!file_exists($path . $folder)) {
$oldmask = umask(0);
mkdir($path . $folder, 0777);
umask($oldmask);
}
break;
}
return $folder;
}
}
?>
| true |
de51c24ad5e51c97dda3e710bdfdcdbd63f1d516 | PHP | mapkyca/pingback2hook | /engine/classes/pingback2hook/core/Input.class.php | UTF-8 | 3,100 | 2.953125 | 3 | [
"MIT"
] | permissive | <?php
/**
* @file
* Input handling functions.
*
* @package core
* @copyright Marcus Povey 2013
* @license The MIT License (see LICENCE.txt), other licenses available.
* @author Marcus Povey <marcus@marcus-povey.co.uk>
* @link http://www.marcus-povey.co.uk
*/
namespace pingback2hook\core {
/**
* Inputs
*/
class Input {
/// Cached and sanitised input variables
protected static $sanitised_input = array();
/**
* Retrieve input.
*
* @param string $variable The variable to retrieve.
* @param mixed $default Optional default value.
* @param callable $filter_hook Optional hook for input filtering, takes one parameter and returns the filtered version. eg function($var){return htmlentities($var);}
* @return mixed
*/
public static function get($variable, $default = null, $filter_hook = null) {
// Has input been set already
if (isset(self::$sanitised_input[$variable])) {
$var = self::$sanitised_input[$variable];
return $var;
}
if (isset($_REQUEST[$variable])) {
if (is_array($_REQUEST[$variable]))
$var = $_REQUEST[$variable];
else
$var = trim($_REQUEST[$variable]);
if (is_callable($filter_hook))
$var = $filter_hook($var);
return $var;
}
return $default;
}
/**
* Set an input value
*
* @param string $variable The name of the variable
* @param mixed $value its value
*/
public static function set($variable, $value) {
if (!isset(self::$sanitised_input))
self::$sanitised_input = array();
if (is_array($value)) {
foreach ($value as $key => $val)
$value[$key] = trim($val);
self::$sanitised_input[trim($variable)] = $value;
}
else
self::$sanitised_input[trim($variable)] = trim($value);
}
/**
* Get raw POST request data.
* @param callable $filter_hook Optional hook for input filtering, takes one parameter and returns the filtered version. eg function($var){return htmlentities($var);}
* @return string|false
*/
public static function getPOST($filter_hook = null) {
global $GLOBALS;
$post = '';
if (isset($GLOBALS['HTTP_RAW_POST_DATA']))
$post = $GLOBALS['HTTP_RAW_POST_DATA'];
// If always_populate_raw_post_data is switched off, attempt another method.
if (!$post)
$post = file_get_contents('php://input');
// If we have some results then return them
if ($post) {
if ((isset($filter_hook)) && (is_callable($filter_hook)))
$post = $filter_hook($post);
return $post;
}
return false;
}
}
} | true |
96022caf43b23edd5d80cb33f7de0bf51edad189 | PHP | HCC-Coder-Bootcamp/php103 | /chloe/tasks/tasks2.php | UTF-8 | 350 | 3.421875 | 3 | [] | no_license | <?php
$input = readline('number' . PHP_EOL);
if ($input > 0){
echo "Positive" . PHP_EOL;
}
else if ($input < 0){
echo "Negative" . PHP_EOL;
}
else {
echo "REJECT-0" . PHP_EOL;
}
if (($input % 2) == 1 ){
echo "Odd" . PHP_EOL;
}
else if ($input = 0){
echo "REJECT-1" . PHP_EOL;
}
else {
echo "Even" . PHP_EOL;
} | true |
3c6321e4ca687cf56b38fc46dc639f6dd7102487 | PHP | dark-wind/php-activiti-api | /src/Client/Model/Group/GroupMember.php | UTF-8 | 454 | 2.71875 | 3 | [] | no_license | <?php
namespace Activiti\Client\Model\Group;
class GroupMember
{
/**
* @var array
*/
private $data;
public function __construct(array $data)
{
$this->data = $data;
}
public function getUserId()
{
return $this->data['userId'];
}
public function getGroupId()
{
return $this->data['groupId'];
}
public function getUrl()
{
return $this->data['url'];
}
}
| true |
dc86726d0a7c697c853ea6ff1a6a0d672693028c | PHP | niftytushar/sugandh-vatika | /php/category.php | UTF-8 | 566 | 2.96875 | 3 | [] | no_license | <?php
class CATEGORY
{
public $mInterface;
public function __construct()
{
$this->mInterface = new MYSQL_INTERFACE();
}
public function add($data)
{
$queryPart = array();
foreach ($data as $key=>$value)
{
if(isset($key)) array_push($queryPart, $key."='".$value."'");
}
return $this->mInterface->categoryAdd(join(",", $queryPart));
}
public function getList()
{
return $this->mInterface->categoryList();
}
public function remove($id)
{
return $this->mInterface->categoryRemove($id);
}
}
?> | true |
43aff348cddf14c3da9a8ed4b7ee3113586264a0 | PHP | jesusantguerrero/atmosphere-core | /src/Http/Middleware/EnsureUserHasTeam.php | UTF-8 | 1,067 | 2.640625 | 3 | [] | no_license | <?php
namespace Freesgen\Atmosphere\Http\Middleware;
use App\Models\User;
use Closure;
use Illuminate\Http\Request;
class EnsureUserHasTeam
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
$currentUser = $request->user();
if ($currentUser) {
if (!$currentUser->allTeams()->count()) {
return Redirect()->route('onboarding.index');
} else if($this->ensureOneOfTeamIsCurrent($currentUser)) {
return Redirect('/dashboard');
}
}
return $next($request);
}
protected function ensureOneOfTeamIsCurrent(User $currentUser) {
if (!is_null($currentUser->current_team_id)) {
return;
}
$firstTeamId = $currentUser->allTeams()->first()->id;
$currentUser->current_team_id = $firstTeamId;
$currentUser->save();
return true;
}
}
| true |
90cc9a801ab0e97764104ac8e8a3f3055c85f02e | PHP | kasinooya/HotelSystem | /public/equipments.php | UTF-8 | 2,549 | 2.609375 | 3 | [] | no_license | <?php
include_once("../sys/core/init.inc.php");
/* 初始化页面信息 */
$page_title = "设备管理 | 酒店后勤管理系统";
$page_h1 = "酒店后勤管理——房务管理、设备管理、仓库管理";
/* 载入页头 */
include_once("assets/common/header.inc.php");
/* 载入CSS和JS部分 */
?>
<link href="assets/css/equipments.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="assets/js/equipments.js"></script>
<?php
/* 载入模板 */
include_once("assets/common/formwork.inc.php");
/* 查询所有的设备信息 */
$query = "SELECT equipment_id, equipment_name, equipment_state, equipment_position, equipment_price FROM `equipment`";
$result = @mysql_query($query);
if(mysql_num_rows($result) == 0) {
$lists = array();
} else {
$lists = array();
while( $row = mysql_fetch_assoc($result) ){
/** 构成设备信息数组 **/
$equ = array(
"id" => $row['equipment_id'],
"name" => $row['equipment_name'],
"state" => $row['equipment_state'],
"position" => $row['equipment_position'],
"price" => $row['equipment_price']
);
$lists[] = $equ;
}
}
/* 输出页面正文 */
echo '<div id="body">';
/* 添加增加设备记录按钮 */
echo '<p class="btnLine"><a class="admin" href="admin_equipments.php">+ 添加设备信息</a></p>';
/* 载入页面正文数据表格部分 */
if(count($lists) == 0) {
// 如果没有数据
echo '<div id="data_none">没有找到 符合要求 的记录</div>';
} else {
echo '<table cellpadding="0" cellspacing="0">
<tr>
<th>设备编号</th>
<th>设备名称</th>
<th>设备状态</th>
<th>设备位置</th>
<th>设备价格</th>
</tr>';
foreach($lists as $list) {
/** 解码设备状态代表的文字 **/
if($list['state'] == 0) {
$state = '<span class="STATE_YELLOW">设备空缺</span>';
} else if($list['state'] == 1) {
$state = '<span class="STATE_GREEN">正常使用</span>';
} else if($list['state'] == -1) {
$state = '<span class="STATE_RED">等待维修</span>';
} else {
$state = '<span class="STATE_YELLOW">状态未知</span>';
}
echo '<tr>
<td><a href="admin_equipments.php?id=' . $list['id'] . '">' . $list['id'] . '</td>
<td>' . $list['name'] . '</td>
<td>' . $state . '</td>
<td>' . $list['position'] . '</td>
<td>' . $list['price'] . '</td>
</tr>';
}
echo '</table>';
}
echo '</div>';
/* 载入页尾 */
include_once("assets/common/footer.inc.php");
?> | true |
cd2cd479d509569a08bddffab5154bc68d1d7ae6 | PHP | vasilaum/teste-monetizze | /tabela.php | UTF-8 | 815 | 2.71875 | 3 | [] | no_license | <!DOCTYPE html>
<html>
<head>
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
</style>
</head>
<body>
<table>
<tr>
<th>Jogo Feito</th>
<th>Jogo Sorteado</th>
<th>Acertos</th>
<th>Números acertados</th>
</tr>
<?php foreach($resultados as $resultado) { ?>
<tr>
<td><?php echo implode(',', $resultado->jogoAtual); ?></td>
<td><?php echo implode(',', $resultado->resultado); ?></td>
<td><?php echo $resultado->qtdAcertos; ?></td>
<td><?php echo implode(',', $resultado->numerosAcertados); ?></td>
</tr>
<?php } ?>
</table>
</body>
</html> | true |
23b219ad34c3dbd53c93f2754469660707a34e17 | PHP | shivram2609/diane | /trunk_bak/app/Controller/CountriesController.php | UTF-8 | 3,037 | 2.609375 | 3 | [] | no_license | <?php
App::uses('AppController', 'Controller');
/**
* Countries Controller
*
* @property Country $Country
*/
class CountriesController extends AppController {
public $conditions = array();
public $delarr = array();
public $updatearr = array();
public $paginate = array(
'limit' => 25,
'order' => array(
'Country.name' => 'asc'
)
);
function beforefilter() {
parent::beforefilter();
$allowed = array();
$this->checklogin($allowed);
$this->adminbreadcrumb();
}
/**
* index method
*
* @return void
*/
public function admin_index() {
$this->bulkactions();
/* code to perform search functionality */
if(isset($this->data) && !empty($this->data['Country']['searchval'])){
$this->Session->write('searchval',$this->data['Country']['searchval']);
$this->conditions = array("OR"=>array("name like"=>"%".$this->data['Country']['searchval']."%"));
}
if(isset($this->params['named']['page'])){
if($this->Session->read('searchval')){
$this->conditions = array("OR"=>array("name like"=>"%".$this->Session->read('searchval')."%"));
$this->data['Country']['searchval'] = $this->Session->read('searchval');
}
}elseif(empty($this->conditions)){
$this->Session->delete('searchval');
}
/* end of code to perform search functionality */
$this->Country->recursive = 0;
$this->set('countries', $this->paginate($this->conditions));
}
/**
* add method
*
* @return void
*/
public function admin_add() {
if ($this->request->is('post')) {
$this->Country->create();
if ($this->Country->save($this->request->data)) {
$this->Session->setFlash(__('The country has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The country could not be saved. Please, try again.'));
}
}
}
/**
* edit method
*
* @param string $id
* @return void
*/
public function admin_edit($id = null) {
$this->Country->id = $id;
if (!$this->Country->exists()) {
throw new NotFoundException(__('Invalid country'));
}
if ($this->request->is('post') || $this->request->is('put')) {
if ($this->Country->save($this->request->data)) {
$this->Session->setFlash(__('The country has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The country could not be saved. Please, try again.'));
}
} else {
$this->request->data = $this->Country->read(null, $id);
}
}
/**
* delete method
*
* @param string $id
* @return void
*/
public function admin_delete($id = null) {
die("here");
if (!$this->request->is('post')) {
throw new MethodNotAllowedException();
}
$this->Country->id = $id;
if (!$this->Country->exists()) {
throw new NotFoundException(__('Invalid country'));
}
if ($this->Country->delete()) {
$this->Session->setFlash(__('Country deleted'));
$this->redirect(array('action'=>'index'));
}
$this->Session->setFlash(__('Country was not deleted'));
$this->redirect(array('action' => 'index'));
}
}
| true |
6023313acf6fed10e6b387e371aff3983b247e3c | PHP | uyendt99/mongonew | /database/seeders/CustomerSeeder.php | UTF-8 | 949 | 2.53125 | 3 | [
"MIT"
] | permissive | <?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Faker;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
class CustomerSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$faker = Faker\Factory::create();
$limit = 10000;
for ($i = 0; $i < $limit; $i++) {
DB::table('customers')->insert([
'name' => $faker->name,
'age' => rand(1,100),
'gender' => rand(0,2),
'phone' => $faker->phoneNumber,
'email' => $faker->email,
'address' => $faker->address,
'classify' => "Khách hàng mới",
'company_id' => "60c8622030946aa27a623148",
'job' => "Nghề".Str::random(10),
'user_ids' => "60d5b233d9210000bc006ee7"
]);
}
}
}
| true |
c744edfb18a9cad976d66fda547e534f920459c7 | PHP | spaze/michalspacek.cz | /site/vendor/nette/neon/src/Neon/Node/LiteralNode.php | UTF-8 | 2,100 | 2.84375 | 3 | [
"MIT",
"GPL-2.0-only",
"GPL-1.0-or-later",
"BSD-3-Clause",
"GPL-3.0-only"
] | permissive | <?php
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
declare(strict_types=1);
namespace Nette\Neon\Node;
use Nette\Neon\Node;
/** @internal */
final class LiteralNode extends Node
{
private const SimpleTypes = [
'true' => true, 'True' => true, 'TRUE' => true, 'yes' => true, 'Yes' => true, 'YES' => true,
'false' => false, 'False' => false, 'FALSE' => false, 'no' => false, 'No' => false, 'NO' => false,
'null' => null, 'Null' => null, 'NULL' => null,
];
private const PatternDatetime = '#\d\d\d\d-\d\d?-\d\d?(?:(?:[Tt]| ++)\d\d?:\d\d:\d\d(?:\.\d*+)? *+(?:Z|[-+]\d\d?(?::?\d\d)?)?)?$#DA';
private const PatternHex = '#0x[0-9a-fA-F]++$#DA';
private const PatternOctal = '#0o[0-7]++$#DA';
private const PatternBinary = '#0b[0-1]++$#DA';
public function __construct(
public mixed $value,
) {
}
public function toValue(): mixed
{
return $this->value;
}
public static function parse(string $value, bool $isKey = false): mixed
{
if (!$isKey && array_key_exists($value, self::SimpleTypes)) {
return self::SimpleTypes[$value];
} elseif (is_numeric($value)) {
return $value * 1;
} elseif (preg_match(self::PatternHex, $value)) {
return hexdec($value);
} elseif (preg_match(self::PatternOctal, $value)) {
return octdec($value);
} elseif (preg_match(self::PatternBinary, $value)) {
return bindec($value);
} elseif (!$isKey && preg_match(self::PatternDatetime, $value)) {
return new \DateTimeImmutable($value);
} else {
return $value;
}
}
public function toString(): string
{
if ($this->value instanceof \DateTimeInterface) {
return $this->value->format('Y-m-d H:i:s O');
} elseif (is_string($this->value)) {
return $this->value;
} elseif (is_float($this->value)) {
$res = json_encode($this->value);
return str_contains($res, '.') ? $res : $res . '.0';
} elseif (is_int($this->value) || is_bool($this->value) || $this->value === null) {
return json_encode($this->value);
} else {
throw new \LogicException;
}
}
}
| true |
e0347cf8f99ed0b4ffe2777bb4413f3b13cc9877 | PHP | jessydan/ProjetPhp | /controler/afficher_nouvelles.ctrl.php | UTF-8 | 1,150 | 2.5625 | 3 | [] | no_license | <?php
session_start();
require_once('/users/info/etu-s3/chenavje/public_html/ProgWeb/ProjetPhp/model/DAO.class.php');
$idFlux = $_POST['idFlux'];
// On récupère le nombre de nouvelles a récuperer pour un flux rss donné.
$test = ($dao->db())->query("SELECT count(*) FROM nouvelle WHERE RSS_id='$idFlux'");
$nbNouvelle = intval($test->fetch()[0]);
// Récupère l'id de la première nouvelle du flux RSS de la base de donnée (Ce n'est pas 1 y'a des bugs avec l'autoincrément)
$requete = ($dao->db())->query("SELECT id FROM nouvelle WHERE RSS_id='$idFlux' LIMIT 1");
$idMin = intval($requete->fetch()[0]);
// Crée la liste qui contiendra toute les nouvelles
$listeNouvelle = array();
// On parcours toute les nouvelles
for ($i=$idMin; $i < $idMin+$nbNouvelle; $i++) {
// Pour chaque itération on crée un RSS avec ce que l'on récupère dans la bdd.
$nouvelle = new Nouvelle();
$requete = "SELECT * FROM nouvelle WHERE id='$i'";
$q = ($dao->db())->query($requete);
$q->setFetchMode(PDO::FETCH_CLASS, 'Nouvelle');
$nouvelle = $q->fetch();
$listeNouvelle[] = $nouvelle;
}
include('../view/afficher_nouvelles.view.php');
?>
| true |
7c4a236324c60cc67bc07b121f4ee63a66c604e6 | PHP | MlleDelphine/ascp | /src/ServiceCivique/Bundle/CoreBundle/Validator/OrganizationValidator.php | UTF-8 | 921 | 2.53125 | 3 | [
"MIT"
] | permissive | <?php
namespace ServiceCivique\Bundle\CoreBundle\Validator;
use Symfony\Component\Validator\ExecutionContextInterface;
use ServiceCivique\Bundle\CoreBundle\Entity\Organization;
class OrganizationValidator
{
/**
* Validate than approved organization isset if organization type is TYPE_HOST
*
* @param mixed $organization
* @param ExecutionContextInterface $context
*/
public static function validateApprovedOrganization($organization, ExecutionContextInterface $context)
{
if ($organization->isApprovedOrganization()) {
return;
}
if (!$organization->getApprovedOrganization()) {
$context->addViolationAt(
'approvedOrganization',
'un organisme d’accueil doit être rattaché à un organisme agréé',
array(),
null
);
}
}
}
| true |
d878a3cd2863ad80e374e832c63f50a19c8faef5 | PHP | mar4elkin/fast-form-lib | /main/factory.php | UTF-8 | 991 | 2.625 | 3 | [] | no_license | <?php
namespace Main;
abstract class Factory {
public static function getClass($class) {
switch($class) {
case 'head':
return new Head();
break;
case 'form':
return new Form();
break;
case 'input':
return new Input();
break;
case 'button':
return new Button();
break;
case 'lable':
return new Lable();
break;
case 'legend':
return new Legend();
break;
case 'fieldset':
return new Fieldset();
break;
case 'optgroup':
return new Optgroup();
break;
case 'option':
return new Option();
break;
case 'select':
return new Select();
break;
case 'textarea':
return new Textarea();
break;
case 'debug':
return new Debug();
break;
}
}
}
?>
| true |
75215e49981e616951eca908c6af86b752747ce9 | PHP | Pierrot62/Pierre-DWWM | /projet/Conventions/PHP/CONTROLLER/Utilisateurs.Class.php | UTF-8 | 2,969 | 3.375 | 3 | [] | no_license | <?php
class Utilisateurs
{
/*****************Attributs***************** */
private $_idUtilisateur;
private $_nomUtilisateur;
private $_prenomUtilisateur;
private $_emailUtilisateur;
private $_mdpUtilisateur;
private $_datePeremption;
private $_idRole;
/***************** Accesseurs ***************** */
public function getIdUtilisateur()
{
return $this->_idUtilisateur;
}
public function setIdUtilisateur($idUtilisateur)
{
$this->_idUtilisateur=$idUtilisateur;
}
public function getNomUtilisateur()
{
return $this->_nomUtilisateur;
}
public function setNomUtilisateur($nomUtilisateur)
{
$this->_nomUtilisateur=$nomUtilisateur;
}
public function getPrenomUtilisateur()
{
return $this->_prenomUtilisateur;
}
public function setPrenomUtilisateur($prenomUtilisateur)
{
$this->_prenomUtilisateur=$prenomUtilisateur;
}
public function getEmailUtilisateur()
{
return $this->_emailUtilisateur;
}
public function setEmailUtilisateur($emailUtilisateur)
{
$this->_emailUtilisateur=$emailUtilisateur;
}
public function getMdpUtilisateur()
{
return $this->_mdpUtilisateur;
}
public function setMdpUtilisateur($mdpUtilisateur)
{
$this->_mdpUtilisateur=$mdpUtilisateur;
}
public function getDatePeremption()
{
return $this->_datePeremption;
}
public function setDatePeremption($datePeremption)
{
$this->_datePeremption=$datePeremption;
}
public function getIdRole()
{
return $this->_idRole;
}
public function setIdRole($idRole)
{
$this->_idRole=$idRole;
}
/*****************Constructeur***************** */
public function __construct(array $options = [])
{
if (!empty($options)) // empty : renvoi vrai si le tableau est vide
{
$this->hydrate($options);
}
}
public function hydrate($data)
{
foreach ($data as $key => $value)
{
$methode = "set".ucfirst($key); //ucfirst met la 1ere lettre en majuscule
if (is_callable(([$this, $methode]))) // is_callable verifie que la methode existe
{
$this->$methode($value);
}
}
}
/*****************Autres Méthodes***************** */
/**
* Transforme l'objet en chaine de caractères
*
* @return String
*/
public function toString()
{
return "IdUtilisateur : ".$this->getIdUtilisateur()."NomUtilisateur : ".$this->getNomUtilisateur()."PrenomUtilisateur : ".$this->getPrenomUtilisateur()."EmailUtilisateur : ".$this->getEmailUtilisateur()."MdpUtilisateur : ".$this->getMdpUtilisateur()."DatePeremption : ".$this->getDatePeremption()."IdRole : ".$this->getIdRole()."\n";
}
/* Renvoit Vrai si lobjet en paramètre est égal
* à l'objet appelant
*
* @param [type] $obj
* @return bool
*/
public function equalsTo($obj)
{
return;
}
/**
* Compare l'objet à un autre
* Renvoi 1 si le 1er est >
* 0 si ils sont égaux
* - 1 si le 1er est <
*
* @param [type] $obj1
* @param [type] $obj2
* @return Integer
*/
public function compareTo($obj)
{
return;
}
} | true |
ddfe4ce49dcaed9305231f752b52b9d6283ef8ea | PHP | LaurenBugelli/capstone | /inc/signIn-inc.php | UTF-8 | 1,723 | 2.84375 | 3 | [] | no_license | <?php
//make sure user submits form properly
if(isset($_POST["submit"])){
//echo "It works";
//GRAB VARIABLE FROM signUP.php file
$name = $_POST["name"];
$email = $_POST["email"];
$username = $_POST["uid"];
$pass = $_POST["pass"];
$passRepeat = $_POST["passrepeat"];
//ERROR handlers
require_once 'dbh-inc.php';
require_once 'functions-inc.php';
//CATCH if User left inputs empty
if(emptyIn($name, $email, $username, $pass, $passRepeat) !== false){//if anything BUT false then wrong
header("location: /php/signIn.php?error=emptyinput");//url will show emptyinput
exit(); //makes sure script stops
}
//CHECK for proper Username
if(invalidUsername($username) !== false){//if anything BUT false then wrong
header("location: /php/signIn.php?error=invalidUserNameinput");//url will show emptyinput
exit(); //makes sure script stops
}
//CHECK for properemail
if(invalidEmail($email) !== false){
header("location: /php/signIn.php?error=invalidEmailInput");
exit(); //makes sure script stops
}
//CHECK for proper PASSWORD
if(passwordCheck($pass, $passRepeat) !== false){
header("location: /php/signIn.php?error=invalidPasswordInput");
exit(); //makes sure script stops
}
//CHECK IF USERNAME IS ALREADY TAKEN
if(usernameExists($connection, $username, $email) !== false){
header("location: /php/signIn.php?error=usernameExists");
exit(); //makes sure script stops
}
//USER MADE NO MISTAKES, SIGN UP User
createUser($connection, $name, $email, $username, $pass);
}else{
echo "please enter my site correctly";
header("location: ../signIn.php");
}
| true |
0d11b1ff4bb63b2fe948bbe13f761a33ec19c78a | PHP | tgmedia/php-colouring | /tests/PhpColouringTest.php | UTF-8 | 547 | 2.71875 | 3 | [] | no_license | <?php
use Tgmedia\PhpColouring\Colouring;
class PhpColouringTest extends PHPUnit_Framework_TestCase {
public function testColouringOriginal()
{
$colouring = new Colouring('#646464');
$this->assertTrue($colouring->colour() == '#646464');
}
public function testColouringLighten()
{
$colouring = new Colouring('#646464');
$this->assertTrue($colouring->lighten(20) == '#969696');
}
public function testColouringDarken()
{
$colouring = new Colouring('#646464');
$this->assertTrue($colouring->darken(20) == '#323232');
}
} | true |
ac6c369ec5b47c593f5e57fa2b66de95ae51ec3d | PHP | driftphp/command-bus-bundle | /Bus/Bus.php | UTF-8 | 3,528 | 2.828125 | 3 | [
"MIT"
] | permissive | <?php
/*
* This file is part of the DriftPHP Project
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* Feel free to edit as you please, and have fun.
*
* @author Marc Morera <yuhu@mmoreram.com>
*/
declare(strict_types=1);
namespace Drift\CommandBus\Bus;
use Drift\CommandBus\Exception\InvalidCommandException;
use Drift\CommandBus\Middleware\DebugableMiddleware;
use React\EventLoop\LoopInterface;
use React\Promise\Deferred;
/**
* Interface Bus.
*/
abstract class Bus
{
/**
* @var string
*/
const DISTRIBUTION_INLINE = 'inline';
/**
* @var string
*/
const DISTRIBUTION_NEXT_TICK = 'next_tick';
/**
* @var callable
*/
private $middlewareChain;
/**
* @var LoopInterface
*/
private $loop;
/**
* @var array
*/
private $middleware;
/**
* @param LoopInterface $loop
* @param array $middleware
* @param string $distribution
*/
public function __construct(
LoopInterface $loop,
array $middleware,
string $distribution
) {
$this->loop = $loop;
$this->middleware = array_map(function (DebugableMiddleware $middleware) {
return $middleware->getMiddlewareInfo();
}, $middleware);
$this->middlewareChain = self::DISTRIBUTION_NEXT_TICK === $distribution
? $this->createNextTickExecutionChain($middleware)
: $this->createInlineExecutionChain($middleware);
}
/**
* Executes the given command and optionally returns a value.
*
* @param object $command
*
* @return mixed
*
* @throws InvalidCommandException
*/
protected function handle($command)
{
if (!is_object($command)) {
throw new InvalidCommandException();
}
return ($this->middlewareChain)($command);
}
/**
* Create inline execution chain.
*
* @param array $middlewareList
*
* @return callable
*/
private function createInlineExecutionChain($middlewareList)
{
$lastCallable = function () {};
while ($middleware = array_pop($middlewareList)) {
$lastCallable = function ($command) use ($middleware, $lastCallable) {
return $middleware->execute($command, $lastCallable);
};
}
return $lastCallable;
}
/**
* Create next tick execution chain.
*
* @param array $middlewareList
*
* @return callable
*/
private function createNextTickExecutionChain($middlewareList)
{
$lastCallable = function () {};
while ($middleware = array_pop($middlewareList)) {
$lastCallable = function ($command) use ($middleware, $lastCallable) {
$deferred = new Deferred();
$this
->loop
->futureTick(function () use ($deferred, $middleware, $command, $lastCallable) {
$deferred->resolve($middleware->execute(
$command,
$lastCallable
));
});
return $deferred->promise();
};
}
return $lastCallable;
}
/**
* Get middleware list.
*
* @return array
*/
public function getMiddlewareList(): array
{
return $this->middleware;
}
}
| true |
455c32656ee5b5fc1a11745182b7cdb356e70682 | PHP | arnozou/bbs.arno.ren | /app/Repositories/Interfaces/AuthcodeInterface.php | UTF-8 | 250 | 2.640625 | 3 | [] | no_license | <?php namespace App\Repositories\Interfaces;
Interface AuthcodeInterface
{
public function getRecords($mobile, $ip, $timeLengthBefore);
public function newRecord($mobile, $ip, $expireTime, $code);
public function checkCode($mobile, $code);
} | true |
b37fbc19304ee27225c0f47fb2ab9e1ac76f34c5 | PHP | jamesmills/laravel-stats | /tests/ValueObjects/ClassifiedClassTest.php | UTF-8 | 1,510 | 2.65625 | 3 | [
"MIT"
] | permissive | <?php declare(strict_types=1);
namespace Wnx\LaravelStats\Tests\ValueObjects;
use Wnx\LaravelStats\Tests\TestCase;
use Wnx\LaravelStats\ReflectionClass;
use Wnx\LaravelStats\ValueObjects\ClassifiedClass;
use Wnx\LaravelStats\Classifiers\ControllerClassifier;
use Wnx\LaravelStats\Tests\Stubs\Controllers\UsersController;
class ClassifiedClassTest extends TestCase
{
public function getClassifiedClass()
{
return new ClassifiedClass(
new ReflectionClass(UsersController::class),
new ControllerClassifier
);
}
/** @test */
public function it_returns_number_of_methods_for_a_classified_class()
{
$this->assertEquals(
7,
$this->getClassifiedClass()->getNumberOfMethods()
);
}
/** @test */
public function it_returns_number_of_lines_of_code_for_a_classified_class()
{
$this->assertEquals(
41,
$this->getClassifiedClass()->getLines()
);
}
/** @test */
public function it_returns_number_of_logical_lines_of_code_for_a_classified_class()
{
$this->assertSame(
7.0,
$this->getClassifiedClass()->getLogicalLinesOfCode()
);
}
/** @test */
public function it_returns_average_number_of_logical_lines_of_code_per_method_for_a_classified_class()
{
$this->assertEquals(
1.0,
$this->getClassifiedClass()->getLogicalLinesOfCodePerMethod()
);
}
}
| true |
e7defb7e9f5f6e467a8e49d96a22acc48f939c3a | PHP | arbory/arbory | /src/Links/Link.php | UTF-8 | 658 | 2.921875 | 3 | [
"MIT"
] | permissive | <?php
namespace Arbory\Base\Links;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
/**
* @property int $id
* @property string $title
* @property bool $new_tab
* @property string $href
*/
class Link extends Model
{
use HasFactory;
/**
* @var array
*/
protected $fillable = [
'title',
'new_tab',
'href',
];
/**
* @return string
*/
public function __toString()
{
return (string) $this->href;
}
/**
* @return bool
*/
public function isNewTab(): bool
{
return (bool) $this->new_tab;
}
}
| true |
1d128d03eea33e48ee3dea7fad369ca5934eaaa4 | PHP | PyColmenero/task-mamager | /php/create_table.php | UTF-8 | 1,089 | 2.84375 | 3 | [] | no_license | <?php
// connectamos a la BBDD
include("connection.php");
$con = mysqli_connect('localhost', $database_user, $database_pasw);
mysqli_select_db($con, $database_name);
// recogemos variables
$name = $_POST["username"];
// obtenemos nuestra ID
$sql = mysqli_query($con, "SELECT * FROM $usertable WHERE nameUser = '$name'");
$id = mysqli_fetch_row($sql);
$id = $id[0];
// INTENTAMOS CREAR LA TABLA, si la ID existe
if( strlen($id) > 0){
$table_name = "task_table_" . $id;
$sentencia = "CREATE TABLE $table_name (idTask INT AUTO_INCREMENT PRIMARY KEY, nameTask VARCHAR(255), descriptionTask VARCHAR(2048), subjectTask VARCHAR(12), porcentajeTask INT, doneTask VARCHAR(1), dateTask DATE, typeTask VARCHAR(1) );";
if (mysqli_query($con, $sentencia)) {
$output = "0Table created ". $table_name;
} else {
$output = "-Error occurred: " . mysqli_error($con);
}
} else {
$output = "Username not found: " . $name;
}
echo $output;
?> | true |
3326b45a67ee3df37e9ca9995fe170bb9b3b6d29 | PHP | jwhulette/Filevuer | /src/services/UploadServiceInterface.php | UTF-8 | 460 | 2.578125 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types=1);
namespace Jwhulette\Filevuer\Services;
use Illuminate\Http\UploadedFile;
interface UploadServiceInterface
{
public function uploadFiles(string $path, array $files, ?bool $extract = false): void;
public function unzipArchive(string $path, UploadedFile $file): void;
public function uploadFile(string $path, UploadedFile $file): void;
public function getUploadPath(string $path, string $filename): string;
}
| true |
d22ae38a52f92d8713b2c0dfc1d954d189bb6eb2 | PHP | zekelon/zekelon.github.io | /process.php | UTF-8 | 1,919 | 2.609375 | 3 | [] | no_license | <?php
session_start();
//Defines
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_DATABASE', 'Login');
$link=mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
//Get username and password from the form
$_SESSION['username'] = $_POST['user'];
$_SESSION['password'] = $_POST['pass'];
$_SESSION['rights'] = $_POST['Rights'];
$username = $_POST['user'];
$password = $_POST['pass'];
$rights = $_POST['Rights'];
//Stop the hackers
$username = stripcslashes($username);
$password = stripcslashes($password);
$username = mysqli_real_escape_string($link,$username);
$password = mysqli_real_escape_string($link,$password);
//Search in the database
$result = mysqli_query($link,"select * from users where username = '$username' and password = '$password' and rights='$rights'") or die("Unable to query database Spiti soy".mysqli_error());
$row = mysqli_fetch_array($result);
if ($row['username'] == $username && $row['password'] == $password){
echo "Login succeed!!! <3 <3 <3 Welcome: ".$row['username']; echo" " .$rights;
if ($rights == 'Mathiths') { header('Location: /Solo/Mathiths.php'); }
if ($rights == 'Eisigiths') { header('Location: /Solo/Eisigiths.php'); }
if ($rights == 'Elexths') { header('Location: /Solo/elexths.php'); }
if ($rights == 'Kathigiths') { header('Location: /Solo/kathigiths.php'); }
if ($rights == 'Admin') { header('Location: /Solo/Admin/admin.php'); }
}
else{
}
?>
<!DOCTYPE html >
<html>
<head>
<meta charset='utf-8'>
<title>Login page </title>
<link rel="stylesheet" type="text/css" href="styleLogin.css">
</head>
<body>
<div id="frm">
<p><strong>Incorrect Username or Password (or Rights) :) </strong></p>
<a href="logout.php">Press here if you want to try another account</a>
</body>
</html> | true |
bc31311bcfced67133e353a8b8d1ab3b84dd0b9c | PHP | Millsmk92/IUPUI-work | /Unit05/Lab5MM/index.php | UTF-8 | 1,096 | 3.296875 | 3 | [] | no_license | <!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<?php
/*
* Author: Matthew Mills
* 10/3/2019
*/
?>
<html>
<head>
<meta charset="UTF-8">
<title>Drawing a Pattern with Nested Loops</title>
</head>
<body>
<h2>Drawing a Pattern with Nested Loops</h2>
<input align="left" type="submit" value="Refresh" onclick="window.location.reload()"/>
<BR>
<?php
//Establishing values for row and column
$patternRow = rand(1, 20);
//Nested loops to draw pattern
for ($i = 1; $i <= $patternRow; $i++) {
echo"<br>";
for ($patternCol = 1; $patternCol <= $i; $patternCol++) {
echo"<span style='color:white'>* </span>";
//echo"<br>";
}
for ($patternCol = 1; $patternCol <= $patternRow-$i+1; $patternCol++) {
echo"* ";
}
}
?>
</body>
</html>
| true |
27d3d3e211d3cd70622c69de6e0fdc7e91113e50 | PHP | hrybrn/ecssweb | /live/setup/ingestphotos.php | UTF-8 | 1,076 | 2.53125 | 3 | [
"MIT",
"Apache-2.0"
] | permissive | <?php
$relPath = "../";
include($relPath . "auth/forcelogin.php");
include($relPath . "auth/includedb.php");
//only webmaster can run this page
if(!$userInfo['username'] == 'hb15g16'){
exit;
}
//need directory for slideshow
if(!isset($_GET['directory']) | !isset($_GET['name'])){
exit;
}
$name = $_GET['name'];
$directory = $_GET['directory'];
//read files in directory
$files = scandir($relPath . "images/" . $directory);
//remove directory files
unset($files[array_search(".", $files)]);
unset($files[array_search("..", $files)]);
$slideshowEntry = "INSERT INTO slideshow(slideshowName, slideshowLocation) VALUES ('$name', '$directory');";
$db->query($slideshowEntry);
$sql = "SELECT slideshowID FROM slideshow ORDER BY slideshowID DESC;";
$statement = $db->query($sql);
$id = $statement->fetchObject();
$id = $id->slideshowID;
$fileEntries = [];
foreach($files as $file) {
$fileEntries[] = "INSERT INTO slideshowImage(slideshowID, slideshowImageName, activated) VALUES ($id, '$file', 1);";
}
foreach($fileEntries as $fileEntry){
$db->query($fileEntry);
}
| true |
7cd56769ad120f8b75f6c5aadccdd31af494c702 | PHP | omerkocaoglu/OPSkinsTradeService | /src/Services/ServiceBase.php | UTF-8 | 1,355 | 2.5625 | 3 | [] | no_license | <?php
namespace OmerKocaoglu\OPSkinsTradeService\Services;
use Fabstract\Component\Serializer\JSONSerializer;
use Fabstract\Component\Serializer\Normalizer\Type;
use GuzzleHttp\Client;
use OmerKocaoglu\OPSkinsTradeService\Model\Config\ConfigModel;
class ServiceBase
{
protected $client = null;
protected $serializer = null;
protected function getClient()
{
if ($this->client === null) {
$this->client = new Client(['http_errors' => false]);
return $this->client;
}
return $this->client;
}
/**
* @param string $key
* @param string $value
* @return string
*/
protected function createQueryString($key, $value)
{
return $key . '=' . $value . '&';
}
/**
* @return ConfigModel
*/
protected function getServiceConfig()
{
$config_path = __DIR__ . '/../Config/config.json';
$config_string = file_get_contents($config_path);
$serializer = new JSONSerializer();
return $serializer->deserialize($config_string, new Type(ConfigModel::class));
}
/**
* @return JSONSerializer
*/
protected function getJSONSerializer()
{
if ($this->serializer === null) {
$this->serializer = new JSONSerializer();
}
return $this->serializer;
}
}
| true |
60866ddf738f774965e0af48e929fe68f3a4d71f | PHP | php-enqueue/enqueue-dev | /pkg/enqueue/ConnectionFactoryFactory.php | UTF-8 | 2,493 | 2.671875 | 3 | [
"MIT"
] | permissive | <?php
namespace Enqueue;
use Enqueue\Dsn\Dsn;
use Interop\Queue\ConnectionFactory;
final class ConnectionFactoryFactory implements ConnectionFactoryFactoryInterface
{
public function create($config): ConnectionFactory
{
if (is_string($config)) {
$config = ['dsn' => $config];
}
if (false == is_array($config)) {
throw new \InvalidArgumentException('The config must be either array or DSN string.');
}
if (false == array_key_exists('dsn', $config)) {
throw new \InvalidArgumentException('The config must have dsn key set.');
}
$dsn = Dsn::parseFirst($config['dsn']);
if ($factoryClass = $this->findFactoryClass($dsn, Resources::getAvailableConnections())) {
return new $factoryClass(1 === count($config) ? $config['dsn'] : $config);
}
$knownConnections = Resources::getKnownConnections();
if ($factoryClass = $this->findFactoryClass($dsn, $knownConnections)) {
throw new \LogicException(sprintf(
'To use given scheme "%s" a package has to be installed. Run "composer req %s" to add it.',
$dsn->getScheme(),
$knownConnections[$factoryClass]['package']
));
}
throw new \LogicException(sprintf(
'A given scheme "%s" is not supported. Maybe it is a custom connection, make sure you registered it with "%s::addConnection".',
$dsn->getScheme(),
Resources::class
));
}
private function findFactoryClass(Dsn $dsn, array $factories): ?string
{
$protocol = $dsn->getSchemeProtocol();
if ($dsn->getSchemeExtensions()) {
foreach ($factories as $connectionClass => $info) {
if (empty($info['supportedSchemeExtensions'])) {
continue;
}
if (false == in_array($protocol, $info['schemes'], true)) {
continue;
}
$diff = array_diff($info['supportedSchemeExtensions'], $dsn->getSchemeExtensions());
if (empty($diff)) {
return $connectionClass;
}
}
}
foreach ($factories as $driverClass => $info) {
if (false == in_array($protocol, $info['schemes'], true)) {
continue;
}
return $driverClass;
}
return null;
}
}
| true |
7e02f6ffd7e869c5cba5c24f054405df083954ef | PHP | ipunkt/rancherize | /app/General/Services/ByKeyService.php | UTF-8 | 615 | 2.984375 | 3 | [
"MIT"
] | permissive | <?php namespace Rancherize\General\Services;
use Rancherize\General\Exceptions\KeyNotFoundException;
/**
* Class ByKeyService
* @package Rancherize\General\Services
*
* Case insensitive retrieval of a value by key
*/
class ByKeyService {
/**
* @param string $key
* @param array $data
* @return array ['CaSeSeNsItIvE KeY', $value]
*/
public function byKey(string $key, array $data) {
foreach($data as $currentKey => $currentValue) {
if( strtolower($key) === strtolower($currentKey) )
return [$currentKey, $currentValue];
}
throw new KeyNotFoundException($key, array_keys($data));
}
} | true |
9c41394c58da55c18fa3c30e6ae0e4dbcb2da47a | PHP | mtils/php-ems | /tests/unit/Core/Storages/LittleDataCachedStorageTest.php | UTF-8 | 3,268 | 2.640625 | 3 | [
"MIT"
] | permissive | <?php
/**
* * Created by mtils on 12.09.18 at 12:31.
**/
namespace Ems\Core\Storages;
use Ems\Contracts\Core\Storage;
use Ems\Core\Collections\StringList;
use Ems\TestCase;
class LittleDataCachedStorageTest extends TestCase
{
/**
* @test
*/
public function implements_interface()
{
$this->assertInstanceOf(Storage::class, $this->newStorage());
}
/**
* @test
*/
public function storageType_is_memory()
{
$this->assertEquals(Storage::UTILITY, $this->newStorage()->storageType());
}
/**
* @test
*/
public function persist_returns_true()
{
$this->assertTrue($this->newStorage()->persist());
}
/**
* @test
*/
public function isBuffered_returns_true()
{
$this->assertFalse($this->newStorage()->isBuffered());
}
/**
* @test
* @expectedException \Ems\Core\Exceptions\KeyNotFoundException
*/
public function offsetGet_throws_exception_if_key_not_found()
{
$storage = $this->newStorage();
$storage['foo'];
}
/**
* @test
*/
public function offsetSet_deletes_cache()
{
$data = ['test' => 'one','test2' => 'two'];
$array = new ArrayStorage($data);
$storage = $this->newStorage($array);
$this->assertEquals($data['test'], $storage['test']);
$storage['test'] = 'three';
$this->assertEquals('three', $storage['test']);
}
/**
* @test
*/
public function offsetUnset_deletes_cache()
{
$data = ['test' => 'one', 'test2' => 'two'];
$array = new ArrayStorage($data);
$storage = $this->newStorage($array);
$this->assertEquals($data['test'], $storage['test']);
unset($storage['test']);
$this->assertFalse(isset($storage['test']));
}
/**
* @test
*/
public function purge_clears_storage()
{
$data = ['test' => 'one'];
$storage = $this->newStorage(new ArrayStorage($data));
$this->assertEquals($data['test'],$storage['test']);
$this->assertTrue($storage->purge());
$this->assertFalse(isset($storage['test']));
}
/**
* @test
*/
public function clear_purges_storage()
{
$data = ['test' => 'one'];
$storage = $this->newStorage(new ArrayStorage($data));
$this->assertEquals($data['test'], $storage['test']);
$this->assertSame($storage, $storage->clear());
$this->assertFalse(isset($storage['test']));
}
/**
* @test
*/
public function keys()
{
$data = ['test' => 'one','test2' => 'two'];
$array = new ArrayStorage($data);
$storage = $this->newStorage($array);
$keys = $storage->keys();
$this->assertInstanceOf(StringList::class, $keys);
$this->assertCount(2, $keys);
$this->assertEquals('test', $keys[0]);
$this->assertEquals('test2', $keys[1]);
}
/**
* @param Storage $storage (optional)
*
* @return LittleDataCachedStorage
*/
protected function newStorage(Storage $storage=null)
{
$storage = $storage ?: new ArrayStorage();
return new LittleDataCachedStorage($storage);
}
} | true |
e8b6a9e074893b9b13adcb4401eccbd3fd96d91f | PHP | AdeelGalileo/GTM-App | /controller/skills.php | UTF-8 | 3,774 | 2.765625 | 3 | [] | no_license | <?php
class skills extends table {
public $params;
/* Construct the table */
function __construct($db, $params = array()) {
parent::__construct($db, 'consultant_skill');
$this->params = $params;
}
/*
function to add or update consultant_skill table
@param form array
return single row of data
*/
function addConsultantSkill($params = array()) {
$qry = 'CALL addConsultantSkill(%d,%d,%d,%d,"%s")';
$qry = $this->db->prepareQuery($qry,$params['userId'],$params['sessionClientId'],$params['skillUpdateId'],$params['cons_user_id'],DB_DATE_TIME);
$rslt = $this->db->getSingleRow($qry);
$this->addConsultantSkillItems($rslt['skillId'],$params['cons_service_type_id']);
return $rslt;
}
/*
function to add or update consultant_skill_items table
@param form array
return single row of data
*/
function addConsultantSkillItems($skillId,$serviceTypeIds) {
$qry = 'CALL addConsultantSkillItems(%d,"%s")';
$qry = $this->db->prepareQuery($qry,$skillId,$serviceTypeIds);
$rslt = $this->db->getSingleRow($qry);
return $rslt;
}
/*
* Function to get consultant skill by id
* return result of array
*/
function getConsultantSkillById($params = array()){
$qry = 'CALL getConsultantSkillById(%d)';
$qry = $this->db->prepareQuery($qry,$params['skillUpateId']);
$recordSet = $this->db->multiQuery($qry);
$rslt = $recordSet[0];
if($rslt){
$rslt['consultantSkillData'] = $recordSet[0][0];
$rslt['consultantSkillItems'] = $recordSet[1][0];
}
return $rslt;
}
/*
function to get skill list
@param skill array
return skill arary
*/
function getConsultantSkillList($params = array()){
$start = 0;
$limit = 50;
$page = ($params['page']) ? $params['page'] : 1;
if($params['fromDate']!='' && $params['toDate'] !='') {
$fromDate = convertDateToYMD($params['fromDate']);
$toDate = convertDateToYMD($params['toDate']);
}
if($params['recCount']){
$limit = (int) $params['recCount'];
$start = ($page-1)* $limit;
}
$sortBy = 'DESC';
$sorting="";
if($params['orderId'] && $params['sortId'] == 1) {
$sortOrder = $params['orderId'];
$sortBy = 'ASC';
$sorting= $sortOrder.' '.$sortBy;
} elseif($params['orderId'] && $params['sortId'] == 2) {
$sortOrder = $params['orderId'];
$sortBy = 'DESC';
$sorting= $sortOrder.' '.$sortBy;
}
$qry = 'CALL getConsultantSkillList(%d,%d,%d,"%s","%s",%d,%d,"%s",%d,%d,%d)';
$qry = $this->db->prepareQuery($qry, $params['userId'], $params['skillFilterBy'],$params['filterRoleId'],$fromDate, $toDate, $start, $limit, $sorting,$params['writerId'],$params['sessionClientId'],$params['skillFilterSkillId']);
$recordSet = $this->db->multiQuery($qry);
$rslt = $recordSet[1];
if($rslt){
$rslt[0]['totalRows'] = $recordSet[0][0]['total'];
$rslt['consultantSkillList'] = $recordSet[1];
$rslt['consultantSkillListItems'] = $recordSet[2];
}
return $rslt;
}
/*
* Function to delete consultant skill By Id
* return result of single row
*/
function deleteSkill($params = array()){
$qry = 'CALL deleteSkill(%d,%d,"%s")';
$qry = $this->db->prepareQuery($qry,$params['userId'],$params['skillDeleteId'],DB_DATE_TIME);
$rslt = $this->db->getSingleRow($qry);
return $rslt;
}
/*
* Function to get consultant by skill
* return result of array
*/
function getConsultantBySkill($params = array()){
$qry = 'CALL getConsultantBySkill(%d,%d,%d)';
$qry = $this->db->prepareQuery($qry,$params['serviceIdIp'],$params['sessionClientId'],$params['formStatus']);
$rslt = $this->db->getResultSet($qry);
return $rslt;
}
}
?> | true |
c5fcee8ce393c7eef3e335990bcd13f84baa84eb | PHP | Timoniann/kit | /system/Model.php | UTF-8 | 2,319 | 3.03125 | 3 | [] | no_license | <?php
class Model
{
protected $db, $table_name;
function __construct($table_name = null, $db = null)
{
$this->db = $db ? $db : Config::getDatabase();
$this->table_name = $table_name ? $table_name : strtolower(get_class($this));
}
public function setTableName($table_name)
{
$this->table_name = $table_name;
}
public function getById($id)
{
$sql = "SELECT * FROM $this->table_name WHERE id=$id";
return $this->db->query($sql);
}
public function get($array = array())
{
$where = "";
if (count($array)) {
$where = "WHERE ";
foreach ($array as $key => $value) {
$value = $this->db->escape($value);
$where .= " $key='$value' AND ";
}
$where = substr($where, 0, -4);
}
$sql = "SELECT * FROM $this->table_name $where";
return $this->db->query($sql);
}
public function getLike($where_array = array(), $addition = '')
{
$where = "";
if (count($where_array)) {
$where = "WHERE ";
foreach ($where_array as $key => $value) {
$value = $this->db->escape($value);
$where .= " $key LIKE '%$value%' AND ";
}
$where = substr($where, 0, -4);
}
$sql = "SELECT * FROM $this->table_name $where $addition";
return $this->db->query($sql);
}
public function deleteById($id)
{
$id = (int)$id;
$sql = "DELETE FROM $this->table_name WHERE id=$id";
return $this->db->query($sql);
}
public function getAll()
{
$sql = "SELECT * FROM $this->table_name";
return $this->db->query($sql);
}
public function update($id, $array)
{
$id = (int)$id;
$setts = "SET ";
if (count($array)) {
foreach ($array as $key => $value) {
$value = $this->db->escape($value);
$setts .= " $key='$value', ";
}
$setts = substr($setts, 0, -2);
} else return;
$sql = "UPDATE $this->table_name $setts WHERE id=$id";
return $this->db->query($sql);
}
public function count($where_array = array())
{
$where = "";
if (count($where_array)) {
$where = "WHERE ";
foreach ($where_array as $key => $value) {
$value = $this->db->escape($value);
$where .= " $key='$value' AND ";
}
$where = substr($where, 0, -4);
}
$sql = "SELECT COUNT(*) FROM $this->table_name $where";
return $this->db->query($sql)[0]["COUNT(*)"];
}
public function getLastId()
{
return $this->db->getConnection()->insert_id;
}
}
?> | true |
17c8c5edd5be18bce9da9bca429008989a0305e5 | PHP | svakhg/driver-apis | /app/Notifications/NewJobPosted.php | UTF-8 | 2,211 | 2.59375 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Notifications;
use App\Job;
use App\Passenger;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Support\Facades\Config;
use NotificationChannels\OneSignal\OneSignalChannel;
use NotificationChannels\OneSignal\OneSignalMessage;
class NewJobPosted extends Notification
{
use Queueable;
private $job;
/**
* Create a new notification instance.
*
* @param Job $job
*/
public function __construct( Job $job )
{
$this->job = $job;
}
/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
*
* @return array
*/
public function via( $notifiable )
{
return [ OneSignalChannel::class ];
}
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
*
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail( $notifiable )
{
return ( new MailMessage )
->line( 'The introduction to the notification.' )
->action( 'Notification Action', url( '/' ) )
->line( 'Thank you for using our application!' );
}
/**
* @param $notifiable
*
* @return OneSignalMessage
*/
public function toOneSignal( $notifiable )
{
$passenger = Passenger::find( $this->job->passenger_id );
$message = "New job has been posted by {$passenger->name}";
$action = Config::get( 'constants.notification.actions.single_job' );
if ( $this->job->status == 'bid' ) {
$message = "{$passenger->name} need a quotation";
$action = Config::get( 'constants.notification.actions.single_bid' );
}
return OneSignalMessage::create()
->subject( 'New Job' )
->body( $message )
->setData( 'action', $action )
->setData( 'id', $this->job->id )
->url( Config::get( 'constants.notification.host' ) . 'job/' . $this->job->id );
}
/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
*
* @return array
*/
public function toArray( $notifiable )
{
return [
//
];
}
}
| true |
62a17cd17ad726fc9367b8583c3c5640cdb55968 | PHP | matija888/FMS | /private/classes/session.class.php | UTF-8 | 1,676 | 3.15625 | 3 | [] | no_license | <?php
class Session {
public $user_id;
private $user_status;
private $logged_in = false;
private $last_login;
const MAX_LOGIN_PERIOD = 60*60*24;
function __construct() {
session_start();
$this->check_login();
}
private function check_login() {
if(isset($_SESSION['user_id'])) {
$this->user_id = $_SESSION['user_id'];
$this->user_status = $_SESSION['user_status'];
$this->last_login = $_SESSION['last_login'];
$this->logged_in = true;
} else {
unset($this->user_id);
unset($this->user_status);
unset($this->last_login);
$this->logged_in = false;
}
}
public function is_logged_in() {
// return $this->logged_in;
return $this->logged_in && !$this->is_login_expired();
}
public function login($user) {
if($user) {
$this->user_id = $_SESSION['user_id'] = $user->id;
$this->user_status = $_SESSION['user_status'] = $user->status;
$this->last_login = $_SESSION['last_login'] = time();
$this->logged_in = true;
}
}
public function logout() {
unset($_SESSION['user_id']);
unset($_SESSION['user_status']);
unset($this->user_id);
unset($this->user_status);
unset($this->last_login);
$this->logged_in = false;
}
private function is_login_expired() {
if(!isset($this->last_login)) {
return true;
} elseif(($this->last_login + self::MAX_LOGIN_PERIOD) < time()) {
return true;
} else {
return false;
}
}
public function display_session_message($msg="") {
$output = '';
if(isset($_SESSION['message'])) {
$msg = $_SESSION['message'];
$output .= "<div id=\"message\">";
$output .= $msg;
$output .= "</div>";
unset($_SESSION['message']);
}
return $output;
}
} | true |
f03a52052e5ad07ba2ea224860586d7baf2a4b8d | PHP | dvsa/olcs-internal | /module/Olcs/src/Service/Data/User.php | UTF-8 | 2,849 | 2.640625 | 3 | [
"MIT"
] | permissive | <?php
namespace Olcs\Service\Data;
use Common\Exception\DataServiceException;
use Common\Service\Data\AbstractDataService;
use Common\Service\Data\ListDataInterface;
use Dvsa\Olcs\Transfer\Query\User\UserList;
/**
* User data service
*
* @package Olcs\Service\Data
*/
class User extends AbstractDataService implements ListDataInterface
{
/**
* @var string
*/
protected $titleKey = 'loginId';
/**
* @var int
*/
protected $team = null;
/**
* Set team
*
* @param int $team Team id
*
* @return $this
*/
public function setTeam($team)
{
$this->team = $team;
return $this;
}
/**
* Get team
*
* @return int
*/
public function getTeam()
{
return $this->team;
}
/**
* Fetch back a set of options for a drop down list, context passed is parameters which may need to be passed to the
* back end to filter the result set returned, use groups when specified should, cause this method to return the
* data as a multi dimensioned array suitable for display in opt-groups. It is permissible for the method to ignore
* this flag if the data doesn't allow for option groups to be constructed.
*
* @param array|string $context Context
* @param bool $useGroups Use groups
*
* @return array
*/
public function fetchListOptions($context, $useGroups = false)
{
$data = $this->fetchUserListData($context);
$ret = [];
if (!is_array($data)) {
return [];
}
foreach ($data as $datum) {
$ret[$datum['id']] = $datum[$this->titleKey];
}
return $ret;
}
/**
* Fetch user list data
*
* @param array $context Context
*
* @return array
* @throw DataServiceException
*/
public function fetchUserListData($context = [])
{
if (is_null($this->getData('userlist'))) {
$params = [
'sort' => 'loginId',
'order' => 'ASC'
];
$team = $this->getTeam();
if (!empty($team)) {
$params['team'] = $team;
}
if (isset($context['isInternal'])) {
$params['isInternal'] = $context['isInternal'];
}
$dtoData = UserList::create($params);
$response = $this->handleQuery($dtoData);
if (!$response->isOk()) {
throw new DataServiceException('unknown-error');
}
$this->setData('userlist', false);
if (isset($response->getResult()['results'])) {
$this->setData('userlist', $response->getResult()['results']);
}
}
return $this->getData('userlist');
}
}
| true |
7a6a19979941c088c5ce4d21854a720803a5b4da | PHP | minorbread/GD_demo | /imageMark.php | UTF-8 | 1,203 | 2.9375 | 3 | [] | no_license | <?php
/*打开图片*/
// 1.配置图片路径
$src = 'image/2.png';
// 2.获取图片的基本信息
$info = getimagesize($src);
// 3.获取图片后缀名
$type = image_type_to_extension($info[2],false);
// 4.在内存中创建一个和我们图像一致的类型
$fun = "imagecreatefrom{$type}";
// 5.把要操作的图片复制到内存
$image = $fun($src);
/*操作图片*/
// 1.设置水印路径
$image_mark = "image/1.png";
// 2.获取水印信息
$info2 = getimagesize($image_mark);
// 3.获取水印后缀名
$type2 = image_type_to_extension($info2[2],false);
// 4.把内存中创建一个和我们水印图像一致的图像类型
$fun2 = "imagecreatefrom{$type2}";
// 5.把水印图片复制到内存中
$water = $fun2($image_mark);
// 6.合并图片
imagecopymerge($image, $water, 20, 20, 0, 0, $info2[0], $info2[1], 50);
// 7.销毁水印图片
imagedestroy($water);
/*输出图片*/
// 在浏览器中输出图片
header("Content-type:".$info['mime']);
$func = "image{$type}";
$func($image);
// 保存图片
$func($image,"waterImage1.".$type);
/*销毁图片*/
imagedestroy($image);
?> | true |
cd598a792191052ec754498e13434fb5eaad1475 | PHP | paolord/typo3_tdd_demo | /typo3/sysext/fluid/Classes/ViewHelpers/Format/StripTagsViewHelper.php | UTF-8 | 2,777 | 2.921875 | 3 | [
"MIT",
"GPL-2.0-only",
"CC-BY-2.5"
] | permissive | <?php
namespace TYPO3\CMS\Fluid\ViewHelpers\Format;
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
use TYPO3\CMS\Fluid\Core\ViewHelper\AbstractViewHelper;
use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;
use TYPO3Fluid\Fluid\Core\ViewHelper\Traits\CompileWithContentArgumentAndRenderStatic;
/**
* Removes tags from the given string (applying PHPs strip_tags() function)
*
* @see http://www.php.net/manual/function.strip-tags.php
*
* = Examples =
*
* <code title="default notation">
* <f:format.stripTags>Some Text with <b>Tags</b> and an Ümlaut.</f:format.stripTags>
* </code>
* <output>
* Some Text with Tags and an Ümlaut. (strip_tags() applied. Note: encoded entities are not decoded)
* </output>
*
* <code title="inline notation">
* {text -> f:format.stripTags()}
* </code>
* <output>
* Text without tags (strip_tags() applied)
* </output>
*
* @api
*/
class StripTagsViewHelper extends AbstractViewHelper
{
use CompileWithContentArgumentAndRenderStatic;
/**
* No output escaping as some tags may be allowed
*
* @var bool
*/
protected $escapeOutput = false;
/**
* Initialize ViewHelper arguments
*
* @throws \TYPO3Fluid\Fluid\Core\ViewHelper\Exception
*/
public function initializeArguments()
{
$this->registerArgument('value', 'string', 'string to format');
$this->registerArgument('allowedTags', 'string', 'Optional string of allowed tags as required by PHPs strip_tags() f
unction');
}
/**
* To ensure all tags are removed, child node's output must not be escaped
*
* @var bool
*/
protected $escapeChildren = false;
/**
* Applies strip_tags() on the specified value.
*
* @param array $arguments
* @param \Closure $renderChildrenClosure
* @param \TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface $renderingContext
* @see http://www.php.net/manual/function.strip-tags.php
* @return string
*/
public static function renderStatic(
array $arguments,
\Closure $renderChildrenClosure,
RenderingContextInterface $renderingContext
) {
$value = $renderChildrenClosure();
$allowedTags = $arguments['allowedTags'];
if (!is_string($value)) {
return $value;
}
return strip_tags($value, $allowedTags);
}
}
| true |
a672f3840d7209e3403772fb683a709b958135b9 | PHP | wesleyromualdo/PIM | /par3/classes/model/ObraDocumentoApoio.class.inc | UTF-8 | 5,797 | 2.828125 | 3 | [] | no_license | <?php
/**
* Classe de mapeamento da entidade par3.obra_documento_apoio.
*
* @version $Id$
* @since 2017.07.05
*/
/**
* Par3_Model_Obra_documento_apoio: sem descricao
*
* @package Par3\Model
* @uses Simec\Db\Modelo
* @author Renner Nascentes Tanizaki <rennertanizaki@mec.gov.br>
*
* @example
* <code>
* // -- Consultando registros
* $model = new Par3_Model_Obra_documento_apoio($valorID);
* var_dump($model->getDados());
*
* // -- Alterando registros
* $valores = ['campo' => 'valor'];
* $model = new Par3_Model_Obra_documento_apoio($valorID);
* $model->popularDadosObjeto($valores);
* $model->salvar(); // -- retorna true ou false
* $model->commit();
* </code>
*
* @property int $odaid - default: nextval('par3.obra_documento_apoio_odaid_seq'::regclass)
* @property int $arqid
* @property string $odadsc
* @property string $odasituacao
* @property string $odastatus
*/
class Par3_Model_ObraDocumentoApoio extends Modelo
{
/**
* @var string Nome da tabela mapeada.
*/
protected $stNomeTabela = 'par3.obra_documento_apoio';
/**
* @var string[] Chave primaria.
*/
protected $arChavePrimaria = array(
'odaid',
);
/**
* @var mixed[] Chaves estrangeiras.
*/
protected $arChaveEstrangeira = array(
'arqid' => array('tabela' => 'arquivo', 'pk' => 'arqid'),
);
/**
* @var mixed[] Atributos da tabela.
*/
protected $arAtributos = array(
'odaid' => null,
'arqid' => null,
'odadsc' => null,
'odasituacao' => null,
'odastatus' => null,
);
/**
* Validators.
*
* @param mixed[] $dados
* @return mixed[]
*/
public function getCamposValidacao($dados = array())
{
return array(
'odaid' => array('Digits'),
'arqid' => array('allowEmpty' => true,'Digits'),
'odadsc' => array('allowEmpty' => true,new Zend_Validate_StringLength(array('max' => 255))),
'odasituacao' => array('allowEmpty' => true,new Zend_Validate_StringLength(array('max' => 1))),
'odastatus' => array('allowEmpty' => true,new Zend_Validate_StringLength(array('max' => 1))),
);
}
/**
* Método de transformação de valores e validações adicionais de dados.
*
* Este método tem as seguintes finalidades:
* a) Transformação de dados, ou seja, alterar formatos, remover máscaras e etc
* b) A segunda, é a validação adicional de dados. Se a validação falhar, retorne false, se não falhar retorne true.
*
* @return bool
*/
public function antesSalvar()
{
// -- Implemente suas transformações de dados aqui
// -- Por padrão, o método sempre retorna true
return parent::antesSalvar();
}
//NOVO
public function montarSQLSimples($arrPost)
{
$odadsc = sanitizar_string_pesquisa($arrPost['odadsc']);
$where = $arrPost['odadsc']?" AND upper(removeacento(oda.odadsc)) LIKE '%{$odadsc}%'":'';
$where .= $arrPost['odasituacao']?" AND oda.odasituacao = '{$arrPost['odasituacao']}'":'';
$where .= $arrPost['odaid'] && validarInteiro($arrPost['odaid'])?" AND oda.odaid = {$arrPost['odaid']}":'';
$orderBy = $arrPost['ordenacao']? "ORDER BY {$arrPost['ordenacao']['campo']} {$arrPost['ordenacao']['sentido']}":"";
$sql = "SELECT
oda.odaid as id,
ROW_NUMBER() OVER ({$orderBy}) AS qtd,
oda.odaid as codigo, oda.odadsc as descricao, arq.arqnome||'.'||arq.arqextensao arquivo, odah.hodcpf, usu.usunome,odah.hoddtcriacao, oda.odasituacao, odahinativacao.hoddtcriacao as hoddtcriacaoinativacao, arq.arqid
FROM par3.obra_documento_apoio oda
JOIN par3.obra_documento_apoio_historico odah ON ((SELECT MIN(hodid) FROM par3.obra_documento_apoio_historico hist WHERE hist.odaid = oda.odaid) = odah.hodid )
LEFT JOIN par3.obra_documento_apoio_historico odahinativacao ON ((SELECT MAX(hodid) FROM par3.obra_documento_apoio_historico hist WHERE hist.odaid = oda.odaid AND odasituacao = 'I') = odahinativacao.hodid )
JOIN seguranca.usuario usu ON (odah.hodcpf = usu.usucpf)
JOIN public.arquivo arq ON (arq.arqid = oda.arqid)
WHERE oda.odastatus = 'A'
{$where}
{$orderBy}
";
return $sql;
}
public function getIniciativa(array $arrPost) {
$where = $arrPost['odaid']?" AND odaid != {$arrPost['odaid']}":'';
return $this->pegaUm("SELECT * FROM {$this->stNomeTabela} WHERE upper(odadsc) = '".str_to_upper($arrPost['odadsc'])."' AND odastatus = 'A' {$where}");
}
public function pegarSQLSelectCombo($indid = array())
{
$indid = is_array($indid) ? implode(',',$indid):$indid;
$where = "WHERE indstatus = 'A'";
$where = $indid ? " AND indid in({$indid})":'';
return "SELECT indid as codigo, inddsc as descricao FROM {$this->stNomeTabela} $where";
}
public function validarInput(array $campos)
{
//campos
$erros['erros']['odadsc'] = array();
//VALIDA CAMPOS
if(strlen($campos['odadsc']) > 255){array_push($erros['erros']['odadsc'],'Limite de caracteres excedido');}
if($campos['odadsc'] == '' || $campos['odadsc'] == null){array_push($erros['erros']['odadsc'],'O campo não pode ser vazio');}
//if($this->getIniciativa($campos)){array_push($erros['erros']['odadsc'],'A descrição informada já existe');}
//CASO HAJA ERROS, RETORNA ARRAY DE ERROS
foreach ($erros['erros'] as $key => $value){
if (!empty($erros['erros'][$key])){
return $erros;
}
}
return false;
}
}
| true |
a4cdc46d810ccca3df9d11abbdb9e903f097196f | PHP | Arshak0014/football-news | /application/controllers/admin/SportController.php | UTF-8 | 2,546 | 2.578125 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: GABRIELYAN
* Date: 14.07.2020
* Time: 13:53
*/
namespace application\controllers\admin;
use application\base\AdminBaseController;
use application\base\View;
use application\components\Auth;
use application\models\Sport;
class SportController extends AdminBaseController
{
public function actionIndex(){
if (Auth::isGuest()){
View::redirect('/not_found');
}
$sports = Sport::getSports();
$this->view->setTitle('Sports');
$this->view->render('admin/sport/index',[
'sports' => $sports
]);
return true;
}
public function actionCreate(){
if (Auth::isGuest()){
View::redirect('/not_found');
}
if (!empty($_POST) && isset($_POST['submit'])){
$sport_model = new Sport($_POST);
$validate = $sport_model->validate();
if (!empty($validate)){
$this->view->setTitle('Create Sports');
$this->view->render('admin/sport/create',[
'validate' => $validate,
]);
}
if ($sport_model->createSport()){
View::redirect('/admin/sport');
}
}
$this->view->setTitle('Create Sports');
$this->view->render('admin/sport/create');
return true;
}
public function actionUpdate($id){
if (Auth::isGuest()){
View::redirect('/not_found');
}
$sport = Sport::getSportById($id);
if (!empty($_POST) && isset($_POST['submit'])){
$sport_model = new Sport($_POST);
$validate = $sport_model->validate();
if (!empty($validate)){
$this->view->setTitle('Update');
$this->view->render('admin/sport/create',[
'validate' => $validate,
]);
}
if ($sport_model->updateSportById($id)){
View::redirect('/admin/sport');
}
}
$this->view->setTitle('Update');
$this->view->render('admin/sport/update',[
'sport' => $sport
]);
return true;
}
public function actionDelete($id){
if (Auth::isGuest()){
View::redirect('/not_found');
}
Sport::deleteSport($id);
View::redirect('/admin/sport');
return true;
}
} | true |
7ad9d9fbfdc21f293a0c04d46e2a713b7218e6e4 | PHP | VictoriaLasso/Proyect | /vendor/stephpy/timeline/src/ResolveComponent/ComponentDataResolverInterface.php | UTF-8 | 688 | 2.609375 | 3 | [
"MIT"
] | permissive | <?php
namespace Spy\Timeline\ResolveComponent;
use Spy\Timeline\Exception\ResolveComponentDataException;
use Spy\Timeline\ResolveComponent\ValueObject\ResolveComponentModelIdentifier;
use Spy\Timeline\ResolveComponent\ValueObject\ResolvedComponentData;
interface ComponentDataResolverInterface
{
/**
* @param ResolveComponentModelIdentifier $resolve The ResolveComponentModelIdentifier value object.
*
* @return ResolvedComponentData The resolved component data value object.
*
* @throws ResolveComponentDataException When not able to resolve the component data
*/
public function resolveComponentData(ResolveComponentModelIdentifier $resolve);
}
| true |
10397302a519aedb7a32b069faf706c639b26270 | PHP | melissahuertadev/42 | /_oldcursus/piscinePHP/d01/ex01/mlx.php | UTF-8 | 156 | 2.84375 | 3 | [] | no_license | #!/usr/bin/php
<?PHP
$my_cntr = 1;
while ($my_cntr <= 1000)
{
echo "X";
if ($my_cntr % 94 == 0)
echo "\n";
$my_cntr++;
}
echo "\n";
?> | true |
766fd4a6bbbed40f20a776ab9e301a281dc41472 | PHP | pozito31/pozito31-proyecto_integrado_daw | /proyecto-integrado-daw/rest-api/database/seeds/UsuariosSeeder.php | UTF-8 | 1,679 | 2.78125 | 3 | [
"MIT"
] | permissive | <?php
use Illuminate\Database\Seeder;
use App\Usuarios;
use Faker\Factory as Faker;
class UsuariosSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
//Creamos una instancia de Faker
$faker = Faker::create();
//Creamos un bucle para cubrir 5 usuarios:
for ($i=1; $i<=5; $i++){
//Cuando llamamos al método create del Modelo Usuarios
//se está creando una nueva fila en la tabla
Usuarios::create(
[
'nombre'=>$faker->name(),
'apellidos'=>$faker->lastname(),
'fecha_alta'=>$faker->date(),
'usuario'=>$faker->userName(),
'password'=>$faker->password()
]
);
}
if (Usuarios::where('usuario', '=', 'usuario')->first() === null){
$newUser = Usuarios::create([
'nombre' => 'usuario',
'apellidos' => 'usuario',
'fecha_alta' => '2020-05-18',
'usuario' => 'usuario',
'password' => bcrypt('usuario'),
]);
$newUser;
}
if (Usuarios::where('usuario', '=', 'administrador')->first() === null){
$newUser = Usuarios::create([
'nombre' => 'administrador',
'apellidos' => 'administrador administrador',
'fecha_alta' => '2020-05-18',
'usuario' => 'administrador',
'password' => bcrypt('administrador'),
]);
$newUser;
}
}
}
| true |
1f99add6045756617c0278508a56803f294098f8 | PHP | dealroom/avro-php | /src/Schema/PrimitiveSchema.php | UTF-8 | 684 | 2.921875 | 3 | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | permissive | <?php
namespace Avro\Schema;
use Avro\Exception\SchemaParseException;
class PrimitiveSchema extends AbstractSchema
{
/**
* @param string $type the primitive schema type name
* @throws SchemaParseException
*/
public function __construct($type)
{
if (!self::isPrimitiveType($type)) {
throw new SchemaParseException(sprintf('%s is not a valid primitive type.', $type));
}
parent::__construct($type);
}
/**
* @return mixed
*/
public function toAvro()
{
$avro = parent::toAvro();
if (count($avro) === 1) {
return $this->type;
}
return $avro;
}
} | true |
206b952d26f520d07483de442bb5bb8a8b07568a | PHP | utherp/ezfw | /methods/memcache_alerts.php | UTF-8 | 2,941 | 2.515625 | 3 | [] | no_license | <?php
function &get_memcache_connection($host = 'localhost') {
if (!isset($GLOBALS['_memcache_'][$host])) {
if (!is_array($GLOBALS['_memcache_']))
$GLOBALS['_memcache_'] = array();
$GLOBALS['_memcache_'][$host] = new Memcache();
$GLOBALS['_memcache_'][$host]->connect($host);
}
return $GLOBALS['_memcache_'][$host];
}
function add_alert($rawname, $value, $expires) {
$name = preg_replace('/;/', '\\;', $rawname);
$name = preg_quote($name, '/');
$c = get_memcache_connection();
while ($c->get('alerts/lock')) {
usleep(10000);
}
$c->set('alerts/lock', 'adding', 0, 2);
$tmp = $c->get('alerts/*');
if (!$tmp) {
$alerts = array();
} else {
$alerts = split_alert_list($tmp);
}
$rehash = fill_alert_list($alerts);
if (!isset($alerts[$rawname])) {
$alerts[$rawname] = true;
$rehash = true;
}
$c->set('alerts/' . $rawname, $value, 0, $expires);
if ($rehash)
save_alert_list($alerts);
$c->delete('alerts/lock');
return;
}
function save_alert_list($alerts) {
$c = get_memcache_connection();
$str = pack_alert_list($alerts);
if ($str)
$c->set('alerts/*', $str);
else
$c->delete('alerts/*');
return;
}
function remove_alert($rawname) {
$name = preg_replace('/;/', '\\;', $rawname);
$name = preg_quote($name, '/');
$c = get_memcache_connection();
while ($c->get('alerts/lock'))
usleep(10000);
$c->set('alerts/lock', 'removing', 0, 2);
$tmp = $c->get('alerts/*');
$alerts = split_alert_list($tmp);
$rehash = fill_alert_list($alerts);
if (isset($alerts[$rawname])) {
unset($alerts[$rawname]);
$rehash = true;
}
$c->delete('alerts/' . $rawname);
if ($rehash)
save_alert_list($alerts);
$c->delete('alerts/lock');
return;
}
function read_alerts() {
$c = get_memcache_connection();
$tmp = $c->get('alerts/*');
if ($tmp === false) return array();
if ($tmp[0] == ';') $tmp = substr($tmp, 1);
$l = strlen($tmp);
if ($l > 1 && $tmp[$l] == ';' && $tmp[$l-1] != "\\") $tmp = substr($tmp, 0, -1);
$alerts = split_alert_list($tmp);
if (fill_alert_list($alerts))
save_alert_list($alerts);
return $alerts;
}
function pack_alert_list($alerts) {
if (!count($alerts)) return '';
return ';' . implode(';', array_keys($alerts)) . ';';
}
function split_alert_list($list) {
if (!$list) return array();
$alerts = array();
$rec = false;
foreach (preg_split("/([^\\\\]);/", $list, -1, PREG_SPLIT_DELIM_CAPTURE) as $r)
if ($rec === false) $rec = $r;
else {
$alerts[$rec . $r] = false; //$c->get('alerts/'.$rec . $r);
$rec = false;
}
if ($rec)
$alerts[$rec] = false;
return $alerts;
}
function fill_alert_list(&$list) {
$c = get_memcache_connection();
$changed = false;
foreach (array_keys($list) as $n) {
$list[$n] = $c->get('alerts/'.$n);
if ($list[$n] === false) {
unset($list[$n]);
$changed = true;
}
}
return $changed;
}
| true |
b9091bd1b075528d2f0236a9a3c27a260093d58a | PHP | maddinen/php | /Oppimistehtava/naytaAsiakas.php | UTF-8 | 3,010 | 2.609375 | 3 | [] | no_license | <?php
require_once 'asiakastieto.php';
session_start();
if (isset($_SESSION["asiakastieto"])) {
$asiakastieto = $_SESSION["asiakastieto"];
} else {
header ("location: kaikkiAsiakkaat.php");
exit();
}
if (isset ( $_POST ["takaisin"] )) {
header ( "location: kaikkiAsiakkaat.php" );
exit ();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Asiakastietoportaali</title>
<meta name="author" content="Marita Klaavu">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.6.0/pure-min.css">
<link rel="stylesheet" href="cssmenu/styles.css">
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script src="cssmenu/script.js"></script>
</head>
<body>
<div class="container">
<div id='cssmenu'>
<ul>
<li class='active'><a href="index.php">Etusivu</a></li>
<li><a href="uusiAsiakastieto.php">Lisää asiakas</a></li>
<li><a href="kaikkiAsiakkaat.php">Listaa kaikki</a></li>
<li><a href="etsiAsiakasJSON.html">Etsi</a></li>
<li><a href="asetukset.php">Asetukset</a></li>
</ul>
</div>
<br><br>
<div class="etusivudiv">
<h1>Asiakastieto</h1>
<?php
//if(isset($_COOKIE["asiakastieto"])) { //keksiin asettamalla objekti pitää serialisoida, jotta sen voi lukea
//print("<p>Nimi: " . $_COOKIE["asiakastieto"]->getNimi() . "</p>");
//}
//if(isset($_GET["asiakastieto"])) { //getillä voi hakea vain yhden tiedon
//print("<p>Nimi: " . $_GET["asiakastieto"]. "</p>");
//}
print("<p><span><b>Nimi: </b></span>" . $asiakastieto[0]->getNimi());
print("<br><span><b>Katuosoite: </b></span>" . $asiakastieto[0]->getKatuosoite());
print("<br><span><b>Postinumero: </b></span>" . $asiakastieto[0]->getPostinumero());
print("<br><span><b>Postitmp: </b></span>" . $asiakastieto[0]->getPostitmp());
print("<br><span><b>Email: </b></span>" . $asiakastieto[0]->getEmail());
print("<br><span><b>Puhnro: </b></span>" . $asiakastieto[0]->getPuhnro());
print("<br><span><b>Ikä: </b></span>" . $asiakastieto[0]->getIka());
print("<br><span><b>Tavoitteet: </b></span>" . $asiakastieto[0]->getTavoitteet());
print("<br><span><b>Kokemus: </b></span>" . $asiakastieto[0]->getKokemus());
print("<br><span><b>Taajuus: </b></span>" . $asiakastieto[0]->getTaajuus());
print("<br><span><b>Vammat: </b></span>" . $asiakastieto[0]->getVammat());
unset($_SESSION["asiakastieto"]);
session_write_close();
?>
</div>
<div class="pure-control-group" style="margin-left: 5em; margin-top:2em">
<p>
<form action="naytaAsiakas.php" method="post"><a href="kaikkiAsiakkaat.php"><input class="pure-button" type="submit" name="takaisin" value="Takaisin"></a>
</form>
</p>
</div>
</div>
</body>
</html>
| true |
648735944336680fe483f73bf23f2d86bcdf5fd7 | PHP | jcferelloc/recettes | /src/stats.php | UTF-8 | 4,081 | 2.640625 | 3 | [] | no_license | <?php
include 'connect.php';
$connection = connect();
$returnData = new StdClass;
function getResults($result)
{
$returnData = array();
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
if (count($row) == 0) {
continue;
}
$rowEncode = array();
foreach ($row as $key => $value) {
$rowEncode[$key] = utf8_encode($value);
}
if ($result->num_rows == 1) {
return $rowEncode;
}
$returnData[] = $rowEncode;
}
}
return $returnData;
}
//nombre de recettes
$query = "SELECT COUNT( * ) as NB FROM `" . getTable("recettes") . "`;";
$returnData->{"nbRecettes"} = getResults($connection->query($query));
//nombre de recettes par catégories
$query = "SELECT categorie ,COUNT( * ) as NB FROM `" . getTable("recettes") . "` GROUP BY categorie;";
$returnData->{"nbRecettesPerCateg"} = getResults($connection->query($query));
//nombre de recettes sans photos
$query = "SELECT COUNT( * ) as NB FROM `" . getTable("recettes") . "` WHERE ! (url_plat > '') or ! (url_chef > '') ;";
$returnData->{"nbRecettesMissingPhoto"} = getResults($connection->query($query));
//Nombre famille loggées total
$query = "SELECT COUNT( DISTINCT login ) as NB FROM `" . getTable("logs") . "` WHERE (login > '') ;";
$returnData->{"familiesTotal"} = getResults($connection->query($query));
//Nombre visiteurs total
$query = "SELECT COUNT( DISTINCT ip ) as NB FROM `" . getTable("logs") . "` ;";
$returnData->{"visitorsTotal"} = getResults($connection->query($query));
//Nombre visiteurs les dernières 24h
$query = "SELECT COUNT( DISTINCT ip ) as NB FROM `" . getTable("logs") . "` WHERE date >= CURDATE() - INTERVAL 7 DAY ;";
$returnData->{"visitorsTotalAweek"} = getResults($connection->query($query));
//Nombre visiteurs aujourd'hui
$query = "SELECT COUNT( DISTINCT ip ) as NB FROM `" . getTable("logs") . "` WHERE date >= CURDATE();";
$returnData->{"visitorsTotalToday"} = getResults($connection->query($query));
//volume des photos
$size = new stdClass;
$size->{"size"} = format_size(foldersize("upload/"));
$returnData->{"photoFolderSize"} = $size;
function foldersize($dir)
{
$count_size = 0;
$count = 0;
$dir_array = scandir($dir);
foreach ($dir_array as $key => $filename) {
if ($filename != ".." && $filename != ".") {
if (is_dir($dir . "/" . $filename)) {
$new_foldersize = foldersize($dir . "/" . $filename);
$count_size = $count_size + $new_foldersize;
} else if (is_file($dir . "/" . $filename)) {
$count_size = $count_size + filesize($dir . "/" . $filename);
$count++;
}
}
}
return $count_size;
}
function format_size($size)
{
$mod = 1024;
$units = explode(' ', 'B KB MB GB TB PB');
for ($i = 0; $size > $mod; $i++) {
$size /= $mod;
}
return round($size, 2) . ' ' . $units[$i];
}
if (isset($_GET["js"])) {
echo json_encode($returnData);
} else {
$message = "<u>Statistiques</u>:<br>";
$message .= "<li><b>" . $returnData->{"nbRecettes"}["NB"] . "</b> recettes";
if ($returnData->{"nbRecettesMissingPhoto"}["NB"] > 0) {
$message .= "<li>Il manque au moins une photo sur <b>" . $returnData->{"nbRecettesMissingPhoto"}["NB"] . "</b> recettes </li>";
} else {
$message .= "<li>Toutes les recettes ont des photos</li>";
}
$message .= "<li><b>" . $returnData->{"familiesTotal"}["NB"] . "</b> familles logguées au moins une fois </li>";
$message .= "<li><b>" . $returnData->{"visitorsTotal"}["NB"] . "</b> personnes sont venues sur le site (" . $returnData->{"visitorsTotalToday"}["NB"] . " aujourd'hui, " . $returnData->{"visitorsTotalAweek"}["NB"] . " cette semaine) </li>";
$message .= "<li>Le volume occupé par les photos est <b>" . $returnData->{"photoFolderSize"}->{"size"} . "</b></li>";
header('content-type:text/html; charset=utf-8');
echo $message;
}
?> | true |
10765f5906ec21162bce8284cc76c2ec0a25e6cb | PHP | xBl4d3x/et | /library/Et/Object/Property/Trait.php | UTF-8 | 4,064 | 2.828125 | 3 | [] | no_license | <?php
namespace Et;
trait Object_Property_Trait {
/**
* @var string
*/
protected $property_name;
/**
* @var string|\Et\Object_Definable
*/
protected $class_name;
/**
* @var string
*/
protected $title = "";
/**
* @var string
*/
protected $description = "";
/**
* @var bool
*/
protected $required = false;
/**
* @var null|array|callable
*/
protected $allowed_values;
/**
* @var null|string|callable
*/
protected $format;
/**
* @var array
*/
protected $error_messages = array(
Object_Definable::ERR_REQUIRED => "Value may not be empty",
Object_Definable::ERR_INVALID_FORMAT => "Value has invalid format",
Object_Definable::ERR_INVALID_TYPE => "Invalid value type",
Object_Definable::ERR_NOT_ALLOWED_VALUE => "This value is not allowed",
Object_Definable::ERR_TOO_SHORT => "Value is too short (less than {MINIMAL_LENGTH} characters)",
Object_Definable::ERR_TOO_LONG => "Value is too long (more than {MAXIMAL_LENGTH} characters)",
Object_Definable::ERR_TOO_HIGH => "Value is too high (higher than {MAXIMAL_VALUE})",
Object_Definable::ERR_TOO_LOW => "Value is too low (lower than {MINIMAL_VALUE})",
Object_Definable::ERR_OTHER => "Value is not valid - {REASON}",
);
function __construct($class_name, $property_name, array $definition){
}
/**
* @param array|callable|null $allowed_values
* @throws Object_Definable_Exception
*/
protected function setAllowedValues($allowed_values) {
if(!is_array($allowed_values) && $allowed_values !== null && !is_callable($allowed_values)){
throw new Object_Definable_Exception(
"Allowed values for property {$this->getPropertyName(true)} must be array or callback returning array",
Object_Definable_Exception::CODE_INVALID_DEFINITION
);
}
$this->allowed_values = $allowed_values;
}
/**
* @throws Object_Definable_Exception
* @return array|callable|null
*/
public function getAllowedValues() {
if($this->allowed_values === null){
return null;
}
$allowed_values = $this->allowed_values;
if(is_callable($allowed_values)){
$allowed_values = $allowed_values($this);
}
if(!is_array($allowed_values)){
throw new Object_Definable_Exception(
"Allowed values for property {$this->getPropertyName(true)} must be array or callback returning array",
Object_Definable_Exception::CODE_INVALID_DEFINITION,
array(
"allowed values" => $allowed_values
)
);
}
return $this->allowed_values;
}
/**
* @return \Et\Object_Definable|string
*/
public function getClassName() {
return $this->class_name;
}
/**
* @param string $description
*/
protected function setDescription($description) {
$this->description = (string)$description;
}
/**
* @return string
*/
public function getDescription() {
return $this->description;
}
/**
* @param array $error_messages
*/
protected function setErrorMessages(array $error_messages) {
foreach($error_messages as $code => $message){
$this->error_messages[$code] = (string)$message;
}
$this->error_messages = $error_messages;
}
/**
* @return array
*/
public function getErrorMessages() {
return $this->error_messages;
}
/**
* @param callable|null|string $format
*/
protected function setFormat($format) {
$this->format = $format;
}
/**
* @return callable|null|string
*/
public function getFormat() {
return $this->format;
}
/**
* @param bool $full_name [optional]
* @return string
*/
public function getPropertyName($full_name = false) {
if($full_name){
return "{$this->class_name}::\${$this->property_name}";
}
return $this->property_name;
}
/**
* @param boolean $required
*/
protected function setRequired($required) {
$this->required = (bool)$required;
}
/**
* @return boolean
*/
public function getRequired() {
return $this->required;
}
/**
* @param string $title
*/
protected function setTitle($title) {
$this->title = (string)$title;
}
/**
* @return string
*/
public function getTitle() {
return $this->title;
}
} | true |
ab97d01e83cad69538fe38a437cf8784561f96e2 | PHP | anishdhakal54/newpooshak | /app/Http/Controllers/Backend/GalleryController.php | UTF-8 | 2,940 | 2.65625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers\Backend;
use App\Http\Requests\GalleryRequest;
use App\Repositories\Gallery\GalleryRepository;
use Exception;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class GalleryController extends Controller {
/**
* @var GalleryRepository
*/
private $gallery;
public function __construct( GalleryRepository $gallery ) {
$this->gallery = $gallery;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index() {
$gallerysCount = $this->gallery->getAll()->count();
return view( 'backend.gallerys.index', compact( 'gallerysCount' ) );
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create() {
return view( 'backend.gallerys.create' );
}
/**
* Store a newly created resource in storage.
*
* @param GalleryRequest|Request $request
*
* @return \Illuminate\Http\Response
* @throws Exception
*/
public function store( GalleryRequest $request ) {
try {
$this->gallery->create( $request->all() );
} catch ( Exception $e ) {
throw new Exception( 'Error in saving gallery: ' . $e->getMessage() );
}
return redirect()->back()->with( 'success', 'Gallery successfully created!' );
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
*
* @return \Illuminate\Http\Response
*/
public function edit( $id ) {
$gallery = $this->gallery->getById( $id );
return view( 'backend.gallerys.edit', compact( 'gallery' ) );
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
*
* @return \Illuminate\Http\Response
* @throws Exception
*/
public function update( Request $request, $id ) {
//try {
$this->gallery->update( $id, $request->all() );
// } catch ( Exception $e ) {
//
// throw new Exception( 'Error in updating gallery: ' . $e->getMessage() );
// }
return redirect()->back()->with( 'success', 'Gallery successfully updated!!' );
}
/**
* Remove the specified resource from storage.
*
* @param int $id
*
* @return \Illuminate\Http\Response
*/
public function destroy( $id ) {
$this->gallery->delete( $id );
return redirect()->back()->with( 'success', 'Gallery successfully deleted!!' );
}
/**
* @param Request $request
*
* @return \Illuminate\Http\JsonResponse
*/
public function getGalleriesJson( Request $request ) {
$gallerys = $this->gallery->getAll();
foreach ( $gallerys as $gallery ) {
$gallery->author = $gallery->user->full_name;
$image = null !== $gallery->getImage() ? $gallery->getImage()->smallUrl : $gallery->getDefaultImage()->smallUrl;
$gallery->featured_image = $image;
if(!isset($gallery->gallery_name))
$gallery->gallery_name = "";
}
return datatables( $gallerys )->toJson();
}
}
| true |
f2dce6fda9407b1f6ca8fc7fd55a9a22d3c60466 | PHP | staydecent/Gum | /src/Gum/Response.php | UTF-8 | 1,857 | 2.890625 | 3 | [] | no_license | <?php
/**
* Response
*
* @category Class
* @package Gum
* @author Adrian Unger <dev@staydecent.ca>
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version 0.3.0
* @link http://staydecent.ca
*/
namespace Gum;
/**
* Response
*
* @category Response
* @package Gum
* @author Adrian Unger <dev@staydecent.ca>
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version 0.3.0
* @link http://staydecent.ca
*/
class Response
{
/**
* Convert an array to JSON to respond with.
*
* @param array $data array to convert ot JSON
*
* @return json
*/
public static function json($data = array())
{
header('Content-Type: application/json');
return json_encode($data);
}
/**
* Render a template file, injecting data into it.
*
* @param string $file filename of template to render
* @param array $vars data to inject into the template
*
* @return html
*/
public static function renderTemplate($file, $vars = array())
{
extract($vars);
ob_start();
include $file;
$out = ob_get_contents();
ob_end_clean();
return $out;
}
/**
* Render a template file, including layout partials if not a PJAX request.
*
* @param string $file filename of template to render
* @param array $vars data to inject into the template
*
* @return html
*/
public static function render($file, $vars = array())
{
$file = 'templates/' . $file . '.html';
$vars['layout'] = function ($name) {
$isPJAX = !is_null($_SERVER['HTTP_X_PJAX']);
if (!$isPJAX) {
include 'templates/layout/' . $name . '.html';
}
};
return Response::renderTemplate($file, $vars);
}
}
| true |
e8b32c5a9a5876b8c6fac5b32a3df9dffa92f22f | PHP | carl6227/POSfinalProject | /restruant.php | UTF-8 | 14,196 | 2.90625 | 3 | [
"MIT"
] | permissive | <?php
class restaurant
{
// Initializing varaibles to be used in connecting to the online database using phpmyadmin
private $server = "mysql:host=remotemysql.com;dbname=Ca4Rze9t7d"; // server and db
private $user = "Ca4Rze9t7d"; // username
private $password = "3Lzjt7JmOu"; // password
// making some options
private $options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
protected $connection; // initalized variable connection
//Establishing connections
public function openConnection()
{
try {
$this->connection= new PDO(
$this->server,
$this->user,
$this->password,
$this->options
);
return $this->connection;
} catch (PDOException $error) {
echo "Erro connection:" . $error->getMessage();
}
}
// Function to close connection
public function closeConnection()
{
$this->$connection= null;
}
// login Function using session
public function login(){
if(isset($_POST['login'])){
$email=$_POST['email'];
$password=$_POST['password'];
$connection =$this->openConnection();
$statement=$connection->prepare("SELECT * FROM users_table WHERE email=? AND password=?");
$statement->execute([$email,$password]);
$user= $statement->fetch();
$total= $statement->rowCount();
if($total>0 ){
$_SESSION['username']=$user['fullName'];
$_SESSION['userImage']=$user['img'];
unset($_SESSION['errorMsg']);
// checking the type of the user and redirecting to a specific page whether the user is in waiters page or at admin side.
if($user['type']==1){
header('location:index.php');
}else if($user['type']==0){
header('location:waiterlanding.php');
}
}else{
$_SESSION['errorMsg']="* username or password is invalid";
}
//print_r($user[0]);
}
}//end of log in
//for admin functionalities
//display all menu details
public function dispMenu(){
$connection =$this->openConnection();
$statement=$connection->prepare("SELECT * FROM menu WHERE deleteAt is NULL");
$statement->execute();
$items = $statement->fetchAll();
foreach($items as $item)
{
echo' <tr>
<td>
'.$item['menuID'].'
</td>
<td>
'.$item['menuName'].'
</td>
<td>
'.$item['category'].'
</td>
<td>
'.$item['price'].'
</td>
<td>
<!-- Edit Menu Modal -->
<div class="modal fade editModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Edit Menu</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form method="post">
<input type="hidden" name="ID"value="'.$item['menuID'].'">
<div class="form-group input-group-lg">
<label for="exampleInputEmail1">Category</label>
<input type="text" class="form-control"name="newCategory" aria-label="Large" value="'.$item['category'].'">
</div>
<div class="form-group input-group-lg">
<label for="exampleInputEmail1">Menu Name</label>
<input type="text" class="form-control" name="newMenuName"aria-label="Large" value="'.$item['menuName'].'">
</div>
<div class="form-group input-group-lg">
<label for="exampleInputEmail1">Price</label>
<input type="number" class="form-control" name="newPrice"aria-label="Large" value="'.$item['price'].'" >
</div>
<div class="form-group input-group-lg">
<label for="exampleInputEmail1">New Menu image URL</label>
<input type="text" class="form-control" name="newmenuImg"aria-label="Large" value="'.$item['img'].'">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="submit" name="editMenuBtn"class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
</div>
<form method="post">
<button type="button"class="btn btn-info editBtn"><i class="fa fa-edit" aria-hidden="true"></i> Edit</button>
<input type="hidden" name="id"value="'.$item['menuID'].'">
<button type="submit"class="btn btn-danger" name="deleteBtn"><i class="fa fa-trash" aria-hidden="true"></i> Delete</button>
</form>
</td>
</tr>';
}
}
public function dispMenuForWaiter(){
$connection =$this->openConnection();
$statement=$connection->prepare("SELECT * FROM menu WHERE deleteAt is NULL");
$statement->execute();
$items = $statement->fetchAll();
foreach($items as $item)
{
echo '
<article class="card card--1">
<div class="card__info-hover">
</div>
<div class="card__img" align="center">
<img src="'.$item['img'].'" alt="..."style="height:200px;">
</div>
<a href="#" class="card_link">
<div class="card__img--hover"></div>
</a>
<div class="card__info">
<span class="card__category"><span>₱</span>'.$item['price'].' <span class="fa fa-star checked"></span>
<span class="fa fa-star checked"></span>
<span class="fa fa-star checked"></span>
<span class="fa fa-star checked"></span>
<span class="fa fa-star checked"></span></span>
<h3 class="card__title">'.$item['menuName'].'</h3>
<span class="card__by">Category: <a href="#" class="card__author" title="author">'.$item['category'].' </a></span>
</div>
</article>
';
}
}
// ADMIN functionalities
// Function to add menu.
public function addMenu(){
if(isset($_POST['addMenuBtn'])){
$dateAdded = date('Y-m-d H:i:s');
$category=$_POST['category'];
$menuName=$_POST['menuName'];
$price=$_POST['price'];
$image=$_POST['menuImg'];
$connection =$this->openConnection();
$statement=$connection->prepare("INSERT INTO menu(category,menuName,price,createdAt,img) VALUES(?,?,?,?,?)");
$statement->execute([$category,$menuName,$price,$dateAdded,$image,]);
}
}
// Admin functionalities to delete menu 'Soft delete'
public function deleteMenu(){
if(isset($_POST['deleteBtn'])){
$deletedAt = date('Y-m-d H:i:s');
$id=$_POST['id'];
$connection =$this->openConnection();
$statement=$connection->prepare("UPDATE menu SET deleteAt=? WHERE menuID=$id");
$statement->execute([$deletedAt]);
}
}
// Admin functionalities to update menu
public function updateMenu(){
if(isset($_POST['editMenuBtn'])){
$updatedAt = date('Y-m-d H:i:s');
$id=$_POST['ID'];
$newCategory=$_POST['newCategory'];
$newMenuName=$_POST['newMenuName'];
$newPrice= intVal($_POST['newPrice']);
$newimage=$_POST['newmenuImg'];
$connection =$this->openConnection();
$statement=$connection->prepare("UPDATE menu SET category=?, menuName=?,price=?,updatedAt=?, img=? WHERE menuID=$id");
$statement->execute([$newCategory,$newMenuName,$newPrice,$updatedAt,$newimage]);
}
}
// Waiter and Admin functionality to update personal information
public function updateInfo(){
if(isset($_POST['editProfileBtn'])){
$id=$_POST['id'];
$fullname=$_POST["full_name"];
$address=$_POST["address"];
$email=$_POST['email'];
$password= $_POST['password'];
$image=$_POST['userImg'];
$userType = $_POST['userType'];
$connection =$this->openConnection();
$statement=$connection->prepare("UPDATE users_table SET fullName=?, email=?, password=?,address=?, img=? WHERE user_id=$id");
$statement->execute([$fullname,$email,$password,$address,$image]);
if($userType=="1"){
echo "<script> location.replace('index.php'); </script>";
}else if ($userType=="0"){
echo "<script> location.replace('waiterlanding.php'); </script>";
}
}
}
// Waiterfunctionalities
//add order function
public function addOrder(){
if(isset($_REQUEST['addOrder'])){
$category=$_POST['category'];
$menuName=$_POST['menuName'];
$quantity=$_POST['quantity'];
$status="pending";
$tableNo=intVal($_POST['tablenum']);
$connection =$this->openConnection();
$getPriceStatement=$connection->prepare("SELECT price,img FROM menu WHERE menuName='$menuName'");
$getPriceStatement->execute();
$result=$getPriceStatement->fetch();
$price= $result['price'];
$image= $result['img'];
$subtotal=intVal($quantity)*intVal($price);
$statement=$connection->prepare("INSERT INTO order_table(category,menuName,quantity,status,price,tableNo,subtotal,img) VALUES (?,?,?,?,?,?,?,?)");
$statement->execute([$category, $menuName,$quantity, $status, $price,$tableNo,$subtotal,$image]);
echo "<script>
location.replace('example.php');
</script>";
}
}
public function addSales(){
if(isset($_POST['settlePayment'])){
$tableNo=$_POST['tableNumber'];
$amount=$_POST['amount'];
$soldAt= date("Y-m-d");
$connection =$this->openConnection();
$statement=$connection->prepare("INSERT INTO sales(amount,tableNo,date) VALUES (?,?,?)");
$statement->execute([$amount,$tableNo,$soldAt]);
$statement2=$connection->prepare("DELETE FROM order_table WHERE tableNo=$tableNo");
$statement2->execute();
echo "<script> location.replace('example.php'); </script>";
}
}
// Waiter functionalities to delete order
public function deleteOrder(){
if(isset($_POST['cancelBtn'])){
$menuName=$_POST['menuName'];
$connection =$this->openConnection();
$statement=$connection->prepare("DELETE FROM order_table WHERE menuName=$menuName");
$statement->execute();
}
}
// Function to get all the categories of the menu and add it to the dropdown
public function getCategories(){
$connection =$this->openConnection();
$statement=$connection->prepare("SELECT category FROM menu WHERE deleteAt is NULL GROUP BY category ");
$statement->execute();
$categories = $statement->fetchAll();
foreach($categories as $category)
{
echo' <a class="dropdown-item dropdownBtn" href="#" >'.$category['category'].'</a>';
}
}
// ADMIN and WAITER logout function
public function logout(){
if(isset($_POST['logout'])){
session_destroy();
echo "<script> location.replace('login.php'); </script>";
}
}
}
$myRestruant = new restaurant(); // Creating object of the class
?> | true |
458d82fa8f69346b57a8a5cf1d99dbc39e778f1a | PHP | bizbink/blog-bundle | /Tests/Entity/TagTest.php | UTF-8 | 1,224 | 2.578125 | 3 | [
"MIT"
] | permissive | <?php
/*
* Copyright (C) Matthew Vanderende - All Rights Reserved
* Unauthorized copying of this file, via any medium is strictly prohibited
*/
namespace Tests\BlogBundle\Entity;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\Persistence\ObjectRepository;
use PHPUnit\Framework\TestCase;
use BlogBundle\Entity\Tag;
/**
* Description of PostTest
*
* @author Matthew Vanderende <matthew@vanderende.ca>
*/
class TagTest extends TestCase {
public function testPostInteraction() {
$expectedTagValues = ["name" => "Sample Category", "slug"=>"category-sample"];
$category = new Tag($expectedTagValues["name"], $expectedTagValues["slug"]);
$categoryRepository = $this->createMock(ObjectRepository::class);
$categoryRepository->expects($this->any())
->method('find')
->willReturn($expectedTagValues);
$objectManager = $this->createMock(ObjectManager::class);
$objectManager->expects($this->any())
->method('getRepository')
->willReturn($category);
$this->assertEquals($expectedTagValues["name"], $category->getName());
$this->assertEquals($expectedTagValues["slug"], $category->getSlug());
}
} | true |
0177757fecd5872a087097588b1226337624668f | PHP | ThomVX/CampingMaasvallei | /reserveren.php | UTF-8 | 2,821 | 2.75 | 3 | [] | no_license | <?php
if (!isset($_SESSION['id'])) {
header('Location: login.php');
}
$errors = [];
if (isset($_POST['submit'])) {
if ($_POST['begintijd'] == '') {
$errors['begintijd'] = "Wat is de eerste dag dat je op de campging wilt staan? ontbreekt";
}
if ($_POST['eindtijd'] == '') {
$errors['eindtijd'] = "Wat is de laatste dag dat je op de campging wilt staan? ontbreekt";
}
if (count($errors) == 0) {
//Hier haal je de plaatsen op
$sql = "SELECT * FROM reservering WHERE type = ? ";
$stmt = $conn->prepare($sql);
$stmt->execute([$_POST['type']]);
$result = $stmt->fetchAll();
$begintijd = strtotime($_POST['begintijd']);
$eindtijd = strtotime($_POST['eindtijd']);
$reseveren = false;
$lengte = count($result);
for ($i = 0; $i < $lengte; $i++) {
//Hier haal je de reserveringstijden op
$sql1 = "SELECT * from reserveringstijden INNER JOIN reservering ON reservering.id=reserveringstijden.id_plaats where reservering.id = ? and `begintijd` <= ? OR eindtijd > ?";
$stmt1 = $conn->prepare($sql1);
$stmt1->execute([$result[$i]['id'], $begintijd, $eindtijd]);
$result1 = $stmt1->fetchAll();
if ( (empty($result1[$i]) || $result1[$i]['begintijd'] >= $begintijd || $result1[$i]['eindtijd'] < $eindtijd) && $reseveren == false ) {
echo'
<button onclick="thealert()">reserveren</button>
function thealert() {
alert( "Weet je zeker dat je wilt reserveren?");
}
</script>
';
$reseveren = true;
$sql2 = "INSERT INTO `reserveringstijden`(`id_plaats`, `begintijd`, `eindtijd`, `id_kampeerder`) VALUES (?,?,?,?) ";
$stmt2 = $conn->prepare($sql2);
$stmt2->execute([$result[0]['id'], $_POST['begintijd'], $_POST['eindtijd'], $_SESSION['id']]);
}
}
}
}
?>
<p>U wilt reserveren: </p>
<div class="blockform">
<form method="post">
<label for="Plaats">Waar slaap je in?</label><br>
<select id="type" name="type"><br>
<option value="tent">tent</option>
<option value="camper">camper</option>
</select>
<br>
<label>Eerste dag</label><br>
<input type="date" id="begintijd" name="begintijd" value=" <?php echo (isset($_POST['begintijd']) ? $_POST['begtintijd'] : ''); ?> "><br>
<label>Laatste dag</label><br>
<input type="date" id="eindtijd" name="eindtijd" value=" <?php echo (isset($_POST['eindtijd']) ? $_POST['eindtijd'] : ''); ?> "> <br>
<button type="submit" name="submit">reserveren</button>
</form>
</div> | true |
193bdd23d6eaf44310be521c0a10b5901ff547bd | PHP | Cadiducho/UGR-SIBW | /core/modelo/Comentario.php | UTF-8 | 811 | 2.9375 | 3 | [] | no_license | <?php
class Comentario {
// Id numerico del comentario
public $id;
// Autor del comentario
public $usuario;
// Fecha en la que se realizó el comentario
public $fecha;
// El cuerpo del comentario
public $mensaje;
// La referencia al evento donde se comentó
public $evento;
// La fecha en la que fue editado, si existe
public $fechaEditado;
// El admin que lo editó
public $editadoPor;
function Comentario($id, $usuario, $fecha, $mensaje, $evento = NULL, $fechaEditado = NULL, $editadoPor = NULL) {
$this->id = $id;
$this->usuario = $usuario;
$this->fecha = $fecha;
$this->mensaje = $mensaje;
$this->evento = $evento;
$this->fechaEditado = $fechaEditado;
$this->editadoPor = $editadoPor;
}
}
?>
| true |
14cc6822e9a3c1d887dcbf3e737d6460fb1a465e | PHP | lianiemiagdan/registration_system | /application/controllers/Auth.php | UTF-8 | 7,312 | 2.75 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | <?php
class Auth {
function doFbLogin() {
$user = $this->input->post('userdata');
/**
* check user email if existing
* true get entity then set session
* false register it
*/
if (!$this->tank_auth->is_email_available($user['email'])) {
if (!is_null($user = $this->users->get_user_by_email($user['email']))) { // login ok
$this->session->set_userdata(array(
'user_id' => $user->id,
'username' => $user->username,
'email' => $user->email,
'role_id' => $user->role_id,
'status' => 1,
));
echo json_encode(array('success' => true, 'message' => 'set userdata'));
} else { // fail - wrong login
echo json_encode(array('success' => false, 'message' => 'email not matched'));
}
} else {
$email_activation = $this->config->item('email_activation', 'tank_auth');
$user_data = array(
'username' => $user['name'],
'email' => $user['email'],
'password' => $this->get_random_password(),
);
$fb_data = array(
'first_name' => $user['first_name'],
'last_name' => $user['last_name']
);
// validation ok
if (!is_null($data = $this->tank_auth->create_user(
$user_data['username'], $user_data['email'], $user_data['password'], $email_activation, true, $fb_data))) { // success
$data['site_name'] = $this->config->item('website_name', 'tank_auth');
$this->_send_email('welcome', $data['email'], $data);
$data['login_by_username'] = ($this->config->item('login_by_username', 'tank_auth') AND
$this->config->item('use_username', 'tank_auth'));
$data['login_by_email'] = $this->config->item('login_by_email', 'tank_auth');
$this->tank_auth->login(
$user_data['username'], $user_data['password'], 0, $data['login_by_username'], $data['login_by_email']
);
unset($data['password']); // Clear password (just for any case)
echo json_encode(array('success' => true, 'message' => 'created new record; set userdata'));
} else {
echo json_encode(array('success' => false, 'message' => 'di macreate :('));
}
}
}
function get_random_password($chars_min = 6, $chars_max = 8, $use_upper_case = false, $include_numbers = false, $include_special_chars = false) {
$length = rand($chars_min, $chars_max);
$selection = 'aeuoyibcdfghjklmnpqrstvwxz';
if ($include_numbers) {
$selection .= "1234567890";
}
if ($include_special_chars) {
$selection .= "!@\"#$%&[]{}?|";
}
$password = "";
for ($i = 0; $i < $length; $i++) {
$current_letter = $use_upper_case ? (rand(0, 1) ? strtoupper($selection[(rand() % strlen($selection))]) : $selection[(rand() % strlen($selection))]) : $selection[(rand() % strlen($selection))];
$password .= $current_letter;
}
return $password;
}
function logout() {
$this->tank_auth->logout();
redirect('/auth/index/logout');
}
function register() {
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean|min_length[' . $this->config->item('username_min_length', 'tank_auth') . ']|max_length[' . $this->config->item('username_max_length', 'tank_auth') . ']|alpha_dash');
$this->form_validation->set_rules('reg_email', 'Email', 'trim|required|xss_clean|valid_email');
$this->form_validation->set_rules('reg_password', 'Password', 'trim|required|xss_clean|min_length[' . $this->config->item('password_min_length', 'tank_auth') . ']|max_length[' . $this->config->item('password_max_length', 'tank_auth') . ']|alpha_dash');
$this->form_validation->set_rules('confirm_password', 'Confirm Password', 'trim|required|xss_clean|matches[reg_password]');
$data['errors'] = array();
$agreement = $this->input->post('agreement');
if (isset($agreement) == false) {
$data['errors'] = array('agreement' => 'The Privacy Policy check is required.');
}
$email_activation = $this->config->item('email_activation', 'tank_auth');
if ($this->form_validation->run() && empty($data['errors'])) { // validation ok
if (!is_null($data = $this->tank_auth->create_user(
$this->form_validation->set_value('username'), $this->form_validation->set_value('reg_email'), $this->form_validation->set_value('reg_password'), $email_activation))) { // success
$data['site_name'] = $this->config->item('website_name', 'tank_auth');
// Start: login user
$login_by_username = ($this->config->item('login_by_username', 'tank_auth') AND $this->config->item('use_username', 'tank_auth'));
$login_by_email = $this->config->item('login_by_email', 'tank_auth');
$this->tank_auth->login($this->form_validation->set_value('reg_email'), $this->form_validation->set_value('reg_password'), null, $login_by_username, $login_by_email);
// End: login user
if ($email_activation) { // send "activate" email
$data['activation_period'] = $this->config->item('email_activation_expire', 'tank_auth') / 3600;
$this->_send_email('activate', $data['email'], $data);
unset($data['password']); // Clear password (just for any case)
echo json_encode(array('success' => true, 'message' => $this->lang->line('auth_message_registration_completed_1'), 'profile_link' => site_url() . '/settings/my-profile/' . $this->encrypt->encode($data['user_id'], $this->config->item('encryption_key'), true)));
} else {
if ($this->config->item('email_account_details', 'tank_auth')) { // send "welcome" email
$this->_send_email('welcome', $data['email'], $data);
}
unset($data['password']); // Clear password (just for any case)
echo json_encode(array('success' => true, 'message' => $this->lang->line('auth_message_registration_completed_2'), 'profile_link' => site_url() . '/settings/my-profile/' . $this->encrypt->encode($data['user_id'], $this->config->item('encryption_key'), true)));
}
} else {
$errors = $this->tank_auth->get_error_message();
foreach ($errors as $k => $v)
$data['errors'][$k] = $this->lang->line($v);
echo json_encode(array('success' => false, 'message' => $data['errors']));
}
} else {
$data['errors'] = array_merge($data['errors'], validation_errors_array());
echo json_encode(array('success' => false, 'message' => $data['errors']));
}
}
}
| true |
bc68aa4a16dd6a92b12387b4b344d660217a126d | PHP | atulgoswami21/Mickey | /Store/apps/magento/htdocs/pub/art-page/convert_image2.php | UTF-8 | 2,046 | 2.578125 | 3 | [] | no_license | <?php
//connect to the database
$connect = mysqli_connect("ars-aurora1-cluster-1.cluster-crymzjqricqv.us-west-2.rds.amazonaws.com","ars_dbroot","American1","ars_prod_magento1");
//$connect = mysqli_connect("ars-mysql.crymzjqricqv.us-west-2.rds.amazonaws.com","ars_dbroot","American1","ars_staging_magento1");
//$connect = mysqli_connect("ars-mysql.crymzjqricqv.us-west-2.rds.amazonaws.com","ars_dbroot","American1","ars_dev_magento1");
//$connect = mysqli_connect("localhost","ars_dbroot","American1","ars_prod_magento1");
// http://stackoverflow.com/questions/4565195/mysql-how-to-insert-into-multiple-tables-with-foreign-keys
//
if ($_FILES['csv']['size'] > 0) {
//get the csv file
$file = $_FILES['csv']['tmp_name'];
$fileName = $_FILES['csv']['name'];
$fileSize = $_FILES['csv']['size'];
$handle = fopen($file,"r");
$row_strings = "$file $fileName $fileSize";
$uploadfile = "/opt/bitnami/apps/magento/htdocs/pub/art-page/resized_image/".$fileName;
if (move_uploaded_file($file, $uploadfile)) {
$row_strings .= ". File is valid, and was successfully uploaded to $uploadfile.\n";
} else {
$row_strings .= ". Possible file upload attack! $fileName\n";
}
fclose($handle);
//redirect
header('Location: convert_image2.php?success=1&row_strings='.$row_strings); die;
}
?>
<!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" />
<title>Import URL Rewrite (no header in the file)</title>
</head>
<body>
<?php if (!empty($_GET[success])) { echo "<b>Your file has been imported.</b><br>".$_GET[row_strings]."<br>"; } //generic success notice ?>
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
Choose your file: <br />
<input name="csv" type="file" id="csv" />
<input type="submit" name="Submit" value="Submit" />
</form>
</body>
</html> | true |
f4634c85dac8b4c3032e9b2a5945ba0df36bec5a | PHP | dcto/varimax | /src/Http/Session/Handler/MemcachedSessionHandler.php | UTF-8 | 1,933 | 2.578125 | 3 | [] | no_license | <?php
/**
* Varimax The Slim PHP Frameworks.
* varimax
* FILE: 2020
* USER: 陶之11. <sdoz@live.com>
* Time: 2020-08-11 22:03
* SITE: https://www.varimax.cn/
*/
namespace VM\Http\Session\Handler;
/**
* NativeMemcachedSessionHandler.
*
* Driver for the memcached session save handler provided by the memcached PHP extension.
*
* @see http://php.net/memcached.sessions
*
* @author Drak <drak@zikula.org>
*/
class MemcachedSessionHandler extends \SessionHandler
{
/**
* Constructor.
*
* @param string $savePath Path of memcache server.
* @param array $options Session configuration options.
*/
public function __construct($savePath = null, array $options = array())
{
if (!extension_loaded('memcached')) {
throw new \RuntimeException('PHP does not have "memcached" session module registered');
}
$savePath = $savePath ?: sprintf('%s:%s',
config('cache.memcache.host', '127.0.0.1'),
config('cache.memcache.port', '11211')
);
$options['memcached.sess_prefix'] = config('session.prefix','vm:session');
ini_set('session.save_handler', 'memcached');
ini_set('session.save_path', $savePath);
$this->setOptions($options);
}
/**
* Set any memcached ini values.
*
* @see https://github.com/php-memcached-dev/php-memcached/blob/master/memcached.ini
*/
protected function setOptions(array $options)
{
$validOptions = array_flip(array(
'memcached.sess_locking', 'memcached.sess_lock_wait',
'memcached.sess_prefix', 'memcached.compression_type',
'memcached.compression_factor', 'memcached.compression_threshold',
'memcached.serializer',
));
foreach ($options as $key => $value) {
if (isset($validOptions[$key])) {
ini_set($key, $value);
}
}
}
} | true |
552cf9df0084ca886fe3d85901df055ced6f3e6f | PHP | tah33/ocas | /app/Http/Requests/RuleRequest.php | UTF-8 | 932 | 2.6875 | 3 | [] | no_license | <?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class RuleRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'department_id'=>'required',
'subject_id'=>'required',
'range'=>'required|between:1,100',
];
}
public function messages()
{
return [
'department_id.required' => "Please Choose a Department",
'subject_id.required' => "Please Choose a Subject",
'range.required' => "Please Enter The range",
'range.between' => "Please Enter The range between 1 to 100",
];
}
}
| true |
134d51e7353bd27dd0b8a1936125af4dc91ba625 | PHP | YadavAnurag/travel | /pro/ci/application/views/user_view.php | UTF-8 | 386 | 2.734375 | 3 | [
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>User View</title>
</head>
<body>
<?php
foreach($result as $object){
echo 'Id '.$object->id;
echo 'Username '.$object->email;
echo 'Password '.$object->password;
echo '<br/>';
}
// echo $result;
?>
</body>
</html>
| true |
e0528105aa0d176d1dddc7fe84b98d28a00d484d | PHP | rim2011/phpSession | /phpSession.php | UTF-8 | 533 | 2.9375 | 3 | [] | no_license | <?php
session_start();
if (!isset($_SESSION['counter'])) {
$_SESSION['counter'] = 0;
}
else {
$_SESSION['counter']++;
}
echo "You have visited this page ".$_SESSION['counter']." in this session";
echo "<form action='phpSession.php' method='POST'>
<input value='reset' type='submit' name='button'></form>";
if (isset($_POST['button']))
{
unset($_SESSION['counter']);
header("location:phpSession.php");//rediriger vers la page phpSession.php
}
| true |
784bbb1bea6b75ee08decc3c2e3a8624d849172b | PHP | ajenglaras/Praktikum5_PemrogramanWeb | /p2/proses.php | UTF-8 | 592 | 3.40625 | 3 | [] | no_license | <?php
include "inc.php"; //termasuk halaman inc.php
echo $angka; //variabel angka
echo "<br>";
if ($angka==100){ //jika angka=100
echo "Memuaskan"; //maka akan mencetak memuaskan
} elseif ($angka<100&&$angka>=85) { //jika angka=85
echo "Sangat Baik"; //maka akan mencetak sangat baik
} elseif ($angka<85&&$angka>=70) { //jika angka 85-70
echo "Baik"; //maka akan mencetak baik
} elseif ($angka<70&&$angka>=55) { //jika angka 70-55
echo "Cukup"; //maka akan mencetak cukup
} elseif ($angka<55&&$angka>=0) { //jika angka 55-0
echo "Kurang"; //maka akan mencetak kurang
}
?> | true |
7431e0d28562a02ed9e2d80f05bdacd35a786e8b | PHP | w-lopes/uffa | /core/Commands/Resource.php | UTF-8 | 1,666 | 3.03125 | 3 | [
"WTFPL"
] | permissive | <?php
namespace core\Commands;
use core\Bases\Command as BaseCommand;
use core\Utils\Custom;
use core\Utils\Normalizer;
use core\Utils\Template;
/**
* Handle custom Resource.
*/
class Resource extends BaseCommand
{
/**
* Constructor.
*/
public function __construct()
{
Custom::mkdirResource();
parent::__construct();
}
/**
* Create a new custom resource.
*
* @param string $resource Resource name
*/
public function create(string $resource)
{
$name = Normalizer::className($resource);
$file = PATH_CUSTOM_RESOURCES . "{$name}.php";
if (file_exists($file)) {
self::error("Resource already exists!", true);
}
$content = Template::parse("Resource", [
"name" => $name,
"machine" => Normalizer::toMachineName($name)
]);
if (!file_put_contents($file, $content)) {
self::error("Failed to create resource!");
return;
}
self::success("Resource {$name} created!");
self::warn(preg_replace("/.*\.\.\//", "", $file));
}
/**
* Delete a custom resource.
*
* @param string $resource Resource name
*/
public function delete(string $resource)
{
$name = Normalizer::className($resource);
$path = PATH_CUSTOM_RESOURCES . "{$name}.php";
if (!file_exists($path)) {
self::error("Resource not found!", true);
}
if (!unlink($path)) {
self::error("Failed to delete resource!");
return;
}
self::success("Resource deleted!");
}
}
| true |
1a7d3537e9f9e4a1728958e0be55486084d6b573 | PHP | Jtfnel/phPieces | /ping.php | UTF-8 | 710 | 2.765625 | 3 | [] | no_license | <?php
/*
@Author: Jtfnel
@Version: 1.0.0
@Description: pings a site and return if site is up or not
@TODO: - None
*/
function pingsite($domain){
$test = curl_init($domain);
$useragent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; rv:2.2) Gecko/20110201";
curl_setopt($test, CURLOPT_USERAGENT, $useragent);
curl_setopt($test, CURLOPT_RETURNTRANSFER, true);
curl_exec($test);
$httpcode = curl_getinfo($test, CURLINFO_HTTP_CODE);
if((($httpcode >= 200) && ($httpcode < 400)) && !($httpcode == 308)){
return true;
}else{
return false;
}
curl_close($test);
}
?>
| true |
2492ca913e60cfed8b630bbc7ec8125dfc6a5815 | PHP | plezzz/SoftUni-Technology-Fundamentals-with-PHP | /Associative Arrays Exercise/LegendaryFarming.php | UTF-8 | 2,506 | 3.015625 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: Niki
* Date: 17/03/2019
* Time: 10:50
*/
$materials = ["need" => ['shards'=>0,'fragments'=>0,'motes'=>0], "junk" => []];
$stop = false;
while (!$stop) {
$input = explode(" ", readline());
for ($i = 0; $i < count($input); $i += 2) {
$material = strtolower($input[$i + 1]);
$quantity = $input[$i];
if ($material == 'shards' || $material == 'fragments' || $material == 'motes') {
if (key_exists($material, $materials["need"]))
$materials["need"][$material] += $quantity;
else
$materials["need"][$material] = $quantity;
} else {
if (key_exists($material, $materials["junk"]))
$materials["junk"][$material] += $quantity;
else
$materials["junk"][$material] = $quantity;
}
if (key_exists("shards", $materials["need"])) {
if ($materials["need"]["shards"] >= 250) {
$materials["need"]["shards"] -= 250;
echo "Shadowmourne obtained!\n";
$stop = true;
break;
}
}
if (key_exists("fragments", $materials["need"])) {
if ($materials["need"]["fragments"] >= 250) {
$materials["need"]["fragments"] -= 250;
echo "Valanyr obtained!\n";
$stop = true;
break;
}
}
if (key_exists("motes", $materials["need"])) {
if ($materials["need"]["motes"] >= 250) {
$materials["need"]["motes"] -= 250;
echo "Dragonwrath obtained!\n";
$stop = true;
break;
}
}
}
}
uasort($materials["need"], function ($keyOne, $keyTwo) {
return $keyTwo <=> $keyOne;
});
uksort($materials["need"],function ($materialOne,$materialTwo)use ($materials){
$score1 = $materials["need"][$materialOne];
$score2 = $materials["need"][$materialTwo];
if($score1===$score2){
return $materialOne<=>$materialTwo;
}
return $score2<=>$score1;
});
foreach ($materials['need'] as $material => $quantity) {
echo $material . ": " . $quantity . PHP_EOL;
}
if (key_exists("junk", $materials)) {
uksort($materials["junk"], function ($keyOne, $keyTwo) {
return $keyOne <=> $keyTwo;
});
foreach ($materials['junk'] as $material => $quantity) {
echo $material . ": " . $quantity . PHP_EOL;
}
} | true |
1b0427fd20f6124e1bd91cb8e2ed6be6917b547b | PHP | Zheness/mCMS | /mcms/app/modules/admin/forms/AddPageForm.php | UTF-8 | 2,206 | 2.84375 | 3 | [
"MIT"
] | permissive | <?php
namespace Mcms\Modules\Admin\Forms;
use Phalcon\Forms\Element\Check;
use Phalcon\Forms\Element\Text;
use Phalcon\Forms\Element\TextArea;
use Phalcon\Validation\Validator\PresenceOf;
use Phalcon\Validation\Validator\Regex;
use Phalcon\Validation\Validator\StringLength;
class AddPageForm extends FormBase
{
public function initialize()
{
$this->add($this->title());
$this->add($this->slug());
$this->add($this->content());
$this->add($this->commentsOpen());
$this->add($this->isPrivate());
}
private function title()
{
$element = new Text("title");
$element->setLabel("Titre");
$element->addValidator(new PresenceOf([
"message" => self::FR_VALIDATOR_PRESENCE_OF
]));
$element->addValidator(new StringLength([
"max" => 80,
"maxMessage" => "Le titre de la page ne peut dépasser les 80 caractères."
]));
return $element;
}
private function slug()
{
$element = new Text("slug");
$element->setLabel("Url");
$element->addValidator(new StringLength([
"max" => 80,
"maxMessage" => "L'url de la page ne peut dépasser les 80 caractères."
]));
$element->addValidator(new Regex([
"pattern" => '/^[a-z0-9\-]+$/i',
"message" => "L'url de la page ne peut contenir que des lettres et chiffres (de A à Z et de 0 à 9) et des tirets (-).",
"allowEmpty" => true,
]));
return $element;
}
private function content()
{
$element = new TextArea("content");
$element->setLabel("Contenu");
$element->addValidator(new PresenceOf([
"message" => self::FR_VALIDATOR_PRESENCE_OF
]));
return $element;
}
private function commentsOpen()
{
$element = new Check("commentsOpen", ['value' => 'on']);
$element->setLabel("Commentaires ouverts");
return $element;
}
private function isPrivate()
{
$element = new Check("isPrivate", ['value' => 'on']);
$element->setLabel("Page privée");
return $element;
}
}
| true |
d31fb1b8ab04fb89afad061c4267e83427046dce | PHP | youssefbaba/learn-php | /comparaison.php | UTF-8 | 5,036 | 3.296875 | 3 | [] | no_license | <?php
// les operation de comparaison : == egale , != différent , < Inférieur strictement , > Supérieur strictement , <= Inférieur ou égal ,>= Supérieur ou égal
// boolean : true ou false , echo true => "1" , echo false => " "
// null equivalent 0 , true equivalent 1 , false equivalent 0
echo true ; // "1" chaine de caractere "1"
echo "</br>";
echo false ; // " " chaine de caractere vide " "
echo "</br>";
echo 5 < 10 ; // oui 5 < 10 cad true et donc echo du true donne un chaine caractere "1"
echo "</br>";
echo 5 > 30 ; // non cad false et donc echo du false donne un chaine de caractere vide " "
echo "</br>";
echo 5 != 6 ; // oui 5 est différent de 6 cad true et donc echo du false donne un chaine de caractere "1"
echo "</br>";
echo 5 == 5 ;// oui 5 egale 5 cad true et donc echo du true donne un chaine de caractere "1"
echo "</br>";
echo "Mohamed" < "Kamal" ; // kay9arane bi ma bine lettre1 dyal chaine1 et lettre1 dyal chaine2 suivant code ASCI par exemple M == 77 et K == 75 donc 77 < 75 donne false et echo du false donne un chaine de caractere vide " "
echo "</br>";
// Comparaison large avec == : $a == $b true si $a est égal à $b après le transtypage.
echo 1 == true ; // true => donne chaine de caractere "1"
echo "</br>";
echo 1 == false ; // false => donne chaine de caractere vide " "
echo "</br>";
echo 1 == 1; // true => donne chaine de caractere "1"
echo "</br>";
echo 1 == 0 ; // false => donne chaine de caractere vide " "
echo "</br>";
echo 1 == -1 ; // false => donne chaine de caractere vide " "
echo "</br>";
echo 1 == "1" ; // true => donne chaine de caractere "1"
echo "</br>";
echo 1 == "0"; // false => donne chaine de caractere vide ""
echo "</br>";
echo 1 == "-1" ; // false => donne chaine de caractere vide " "
echo "</br>";
echo 1 == null ; // false => donne chaine de caractere vide " "
echo "</br>";
echo 1 == "php" ; // false => donne chaine de caractere vide " "
echo "</br>";
echo 1 == "" ; // false => donne chaine de caractere vide " "
echo "</br>";
// Comparaison large avec != : $a != $b true si $a est différent de $b après le transtypage.
echo 1 != true ; // false => donne chaine de caractere vide " "
echo "</br>";
echo 1 != false ; // true => donne chaine de caractere "1"
echo "</br>";
echo 1 != 1; // false => donne chaine de caractere vide " "
echo "</br>";
echo 1 != 0 ; // true => donne chaine de caractere "1"
echo "</br>";
echo 1 != -1 ; // true => donne chaine de caractere "1"
echo "</br>";
echo 1 != "1" ; // false => donne chaine de caractere vide " "
echo "</br>";
echo 1 != "0"; // true => donne chaine de caractere "1"
echo "</br>";
echo 1 != "-1" ; // true => donne chaine de caractere "1"
echo "</br>";
echo 1 != null ; // true => donne chaine de caractere "1"
echo "</br>";
echo 1 != "php" ; // true => donne chaine de caractere "1"
echo "</br>";
echo 1 != "" ; // true => donne chaine de caractere "1"
echo "</br>";
//Comparaison stricte avec === $a === $b true si $a est égal à $b et qu'ils sont de même type.
echo 1 === true ; // false => donne chaine de caractere vide " "
echo "</br>";
echo 1 === false ; // false => donne chaine de caractere vide " "
echo "</br>";
echo 1 === 1; // true => donne chaine de caractere "1"
echo "</br>";
echo 1 === 0 ; // false => donne chaine de caractere vide " "
echo "</br>";
echo 1 === -1 ; // false => donne chaine de caractere vide " "
echo "</br>";
echo 1 === "1" ; // false => donne chaine de caractere vide " "
echo "</br>";
echo 1 === "0"; // false => donne chaine de caractere vide " "
echo "</br>";
echo 1 === "-1" ; // false => donne chaine de caractere vide " "
echo "</br>";
echo 1 === null ; // false => donne chaine de caractere vide " "
echo "</br>";
echo 1 === "php" ; // false => donne chaine de caractere vide " "
echo "</br>";
echo 1 === "" ; // false => donne chaine de caractere vide " "
echo "</br>";
//Comparaison stricte avec !== $a !== $b true si $a est différent de $b ou bien s'ils ne sont pas du même type.
echo 1 !== true ; // true => donne chaine de caractere "1"
echo "</br>";
echo 1 !== false ; //true => donne chaine de caractere "1"
echo "</br>";
echo 1 !== 1; // false => donne chaine de caractere vide " "
echo "</br>";
echo 1 !== 0 ; //true => donne chaine de caractere "1"
echo "</br>";
echo 1 !== -1 ; //true => donne chaine de caractere "1"
echo "</br>";
echo 1 !== "1" ; //true => donne chaine de caractere "1"
echo "</br>";
echo 1 !== "0"; //true => donne chaine de caractere "1"
echo "</br>";
echo 1 !== "-1" ; //true => donne chaine de caractere "1"
echo "</br>";
echo 1 !== null ; //true => donne chaine de caractere "1"
echo "</br>";
echo 1 !== "php" ; //true => donne chaine de caractere "1"
echo "</br>";
echo 1 !== "" ; //true => donne chaine de caractere "1"
echo "</br>";
?> | true |
4754ef496774571608fdcf3ac8cb380aed0f3294 | PHP | dnaber-de/Git-Automated-Mirror | /src/GitAutomatedMirror/Type/ArgumentInterface.php | UTF-8 | 403 | 2.5625 | 3 | [] | no_license | <?php # -*- coding: utf-8 -*-
namespace GitAutomatedMirror\Type;
interface ArgumentInterface {
/**
* @return string
*/
public function getName();
/**
* @return string
*/
public function getType();
/**
* @return string
*/
public function getShortName();
/**
* @return bool
*/
public function isRequired();
/**
* @return string
*/
public function getDescription();
} | true |