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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
0f521d0ca93d71cc9e6e8595fd2ae650765c52b9 | PHP | lukesnowden/laraview | /app/Console/Commands/LaraviewCompiler.php | UTF-8 | 1,473 | 2.609375 | 3 | [
"MIT"
] | permissive | <?php
namespace Laraview\Console\Commands;
use Illuminate\Console\Command;
use Laraview\Libs\Blueprints\RegisterBlueprint;
class LaraviewCompiler extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'laraview:compile {--o|--only=}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Compiles attached views, regions and elements into view blade files.';
public $only = [];
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
event( 'laraview:compile' );
$this->checkForSelectedViewGeneration();
app( RegisterBlueprint::class )
->console( $this )
->generate();
}
/**
* @return void
*/
protected function checkForSelectedViewGeneration()
{
if( $only = $this->option( 'only' ) ) {
foreach( array_filter( array_map( 'trim', explode( ',', $only ) ) ) as $class ) {
if( ! class_exists( $class ) ) {
$this->error( "{$class} does not exist..." );
} else {
$this->only[] = $class;
}
}
}
}
}
| true |
1ece4e63dd50a4bc60bf54c7bdac87a3a0464d2d | PHP | Moverr/myshop | /application/models/call_off_m.php | UTF-8 | 1,560 | 2.53125 | 3 | [] | no_license | <?php
// ******************************* INFORMATION ***************************//
// ***********************************************************************//
//
// ** contracts model - Handles all database requests concerning contracts
// **
// ** @author name <mcengkuru@newwavetech.co.ug>
// ** @date 4/jan/2016
// ** @access private
//
// ***********************************************************************//
// ********************************** START ******************************//
class call_off_m extends MY_Model
{
//constructor
function __construct()
{
parent::__construct();
$this->load->model('users_m');
$this->load->model('Query_reader', 'Query_reader', TRUE);
}
function get_sum_of_contract_values($contract_id)
{
$contract = !empty($contract_id) ? $contract_id : 0;
$sql = " SELECT SUM(contract_value) as calloff_contract_value FROM `call_of_orders` WHERE contractid = ".$contract_id." AND isactive= 'Y' GROUP BY contractid ";
$result = $this->db->query($sql)->result_array();
return $result;
}
function get_sum_of_totalpayments($contract_id)
{
$contract = !empty($contract_id) ? $contract_id : 0;
$sql = " SELECT SUM(total_actual_payments) as total_amount_paid FROM `call_of_orders` WHERE contractid = ".$contract_id." AND isactive= 'Y' GROUP BY contractid ";
$result = $this->db->query($sql)->result_array();
return $result;
}
} | true |
42a8a72b50a8bf24ea906153fa3d879a391354f9 | PHP | tyketd/tyketd | /app/RestServer.php | UTF-8 | 3,490 | 2.875 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: Stratege Takam
* Date: 02/08/2018
* Time: 22:45
*/
namespace App;
class RestServer
{
public $baseUrl = "";
public $baseHost = "";
public function __construct($api, $path)
{
$this->baseUrl = $api; // chemin vers l'api exemple (http://api.supfile.supinfo.com/v1/)
$this->baseHost = $path; // chemin vers la racine de l'api exemple (http://api.supfile.supinfo.com/)
//dump($baseUrl, $baseHost);
}
public function get($url){
$url = $this->baseUrl . $url;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
return $result;
}
public function post($url, $params){
$url = $this->baseUrl . $url;
$post_data = '';
foreach($params as $k => $v){
$post_data .= $k . '='.$v.'&';
}
rtrim($post_data, '&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, count($post_data));
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
public function put($url, $params){
$url = $this->baseUrl . $url;
$post_data = '';
foreach($params as $k => $v){
$post_data .= $k . '='.$v.'&';
}
rtrim($post_data, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, count($post_data));
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
public function delete($url, $params){
$url = $this->baseUrl . $url;
$post_data = '';
foreach($params as $k => $v){
$post_data .= $k . '='.$v.'&';
}
rtrim($post_data, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, count($post_data));
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
// exemple d'utilisation
//instancier le rest en passant les paramètres
//$restServer = new RestServer($this->getParameter("api"),$this->getParameter("path"));
//creer un objet
//$directory["name"] = $request->request->get("newFolderName");
//utiliser le verbe post en passant l'objet en paramètre
//$result = $restServer->post("directory",$directory);
//une url exemple
//$path = "directory/".$directoryId."/".$userId."?search=".$search;
// utiliser le verbe get en passant l'utl en paramètre
//$directories = $restServer->get($path);
//recuperer un id
//$directoryId = $val->get("directoryId");
//utiliser le verbe delete
//$result = $restServer->delete("directory/delete/many", ["data"=>$data]);
} | true |
d9d4c325cb63b84b137cae8b3123ef29adf708e6 | PHP | a1comms/vicidial-agent-reporting | /test/hourlyAgentTimesYesterday.php | UTF-8 | 3,298 | 2.796875 | 3 | [] | no_license | <?php
require "../config.php";
$camp = (@$_GET['camp'] != "" ? $_GET['camp'] : 'CS');
$data = new Campaign($camp);
function yday($time){
return $time - (24*3600);
}
$yday_start = yday(mktime(0,0,0));
$yday_end = yday(mktime(23,59,59));
$data->setTimePeriod($yday_start, $yday_end);
echo "<h1>Data For Campaign: " . $camp . "</h1>\n";
foreach ($data->fetchData()->getAgents() as $agent){
$data->setAgent($agent);
echo "<h2>Agent: " . $agent . "</h2>\n";
?>
<table border="1">
<tr>
<th>Time Period</th>
<th>Calls Taken</th>
<th>Calls Made</th>
<th>Talk Time</th>
<th>Park Time</th>
<th>Dispo Time</th>
<th>Dead Time</th>
<th>Wait Time</th>
<th>Pause Time</th>
<th>Wrap Time</th>
</tr>
<?php
for ($i = 0; $i < 24; $i++){
$start = yday(mktime($i, 0, 0));
$end = yday(mktime($i, 59, 59));
$data->setTimePeriod($start,$end);
echo "<tr>\n";
echo "<td>" . date("H:i:s", $start) . " - " . date("H:i:s", $end) . "</td>\n";
echo "<td>" . $data->byInbound()->byQueue($data->byInbound()->queues)->getTotalAnswered() . "</td>\n";
echo "<td>" . $data->byOutbound()->getTotal() . "</td>\n";
echo "<td>" . gmdate("H:i:s", (int)$data->fetchData()->fetchCallTimes()->getTotalTalkTime()) . "</td>\n";
echo "<td>" . gmdate("H:i:s", (int)$data->fetchData()->fetchCallTimes()->getTotalHoldTime()) . "</td>\n";
echo "<td>" . gmdate("H:i:s", (int)$data->fetchData()->fetchCallTimes()->getTotalDispoTime()) . "</td>\n";
echo "<td>" . gmdate("H:i:s", (int)$data->fetchData()->fetchCallTimes()->getTotalDeadTime()) . "</td>\n";
echo "<td>" . gmdate("H:i:s", (int)$data->fetchData()->fetchCallTimes()->getTotalWaitTime()) . "</td>\n";
echo "<td>" . gmdate("H:i:s", (int)$data->fetchData()->fetchCallTimes()->getTotalPausedTime()) . "</td>\n";
echo "<td>" . gmdate("H:i:s", (int)$data->fetchData()->fetchCallTimes()->getTotalWrapTime()) . "</td>\n";
echo "</tr>\n";
}
$data->setTimePeriod($yday_start, $yday_end);
echo "<tr>\n";
echo "<td><b>Total</b></td>\n";
echo "<td>" . $data->byInbound()->byQueue($data->byInbound()->queues)->getTotalAnswered() . "</td>\n";
echo "<td>" . $data->byOutbound()->getTotal() . "</td>\n";
echo "<td>" . gmdate("H:i:s", (int)$data->fetchData()->fetchCallTimes()->getTotalTalkTime()) . "</td>\n";
echo "<td>" . gmdate("H:i:s", (int)$data->fetchData()->fetchCallTimes()->getTotalHoldTime()) . "</td>\n";
echo "<td>" . gmdate("H:i:s", (int)$data->fetchData()->fetchCallTimes()->getTotalDispoTime()) . "</td>\n";
echo "<td>" . gmdate("H:i:s", (int)$data->fetchData()->fetchCallTimes()->getTotalDeadTime()) . "</td>\n";
echo "<td>" . gmdate("H:i:s", (int)$data->fetchData()->fetchCallTimes()->getTotalWaitTime()) . "</td>\n";
echo "<td>" . gmdate("H:i:s", (int)$data->fetchData()->fetchCallTimes()->getTotalPausedTime()) . "</td>\n";
echo "<td>" . gmdate("H:i:s", (int)$data->fetchData()->fetchCallTimes()->getTotalWrapTime()) . "</td>\n";
echo "</tr>\n";
?>
</table>
<?php
}
| true |
d08784a9068ddaaf409a8e8a7aad6277a93e5816 | PHP | mdomansky/laravel-markets-api | /app/Services/Markets/MOEX/ImportStocks.php | UTF-8 | 1,591 | 2.53125 | 3 | [] | no_license | <?php
namespace App\Services\Markets\MOEX;
use App\Repositories\CurrencyRepository;
use App\Repositories\StockRepository;
class ImportStocks
{
private StockRepository $stockRepository;
private CurrencyRepository $currencyRepository;
private string $moexStocksUrl = 'https://iss.moex.com/iss/engines/stock/markets/shares/boards/TQBR/securities.xml';
private $types = [
1 => 'general',
2 => 'privileges',
];
public function __construct(StockRepository $stockRepository, CurrencyRepository $currencyRepository)
{
$this->stockRepository = $stockRepository;
$this->currencyRepository = $currencyRepository;
}
public function import(): void
{
$xmlDataString = file_get_contents($this->moexStocksUrl);
$xmlObject = simplexml_load_string($xmlDataString);
$stocks = json_decode(json_encode($xmlObject), true)['data'][0]['rows']['row'] ?? null;
foreach ($stocks as $stock) {
$stock = $stock['@attributes'];
$this->stockRepository->findByTickerOrCreate(
$stock['SECID'],
[
'name' => $stock['SHORTNAME'],
'long_name' => $stock['SECNAME'],
'currency_id' => $this->currencyRepository->getCurrencyIdByCode($stock['CURRENCYID']),
'isin' => $stock['ISIN'],
'papers_in_lot' => $stock['LOTSIZE'],
'type' => $this->types[$stock['SECTYPE']] ?? $this->types[1],
]
)->refresh();
}
}
}
| true |
f9c37104fb37ab9431e35fd04dd094abe6244302 | PHP | DonValino/4th-Year-Project | /Entities/SignInEntities.php | UTF-8 | 1,314 | 2.890625 | 3 | [] | no_license | <?php
/*
* 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.
*/
/**
* Description of SignInEntities
*
* @author Jake Valino
*/
class SignInEntities {
public $id;
public $userId;
public $jobId;
public $date;
public $latest;
// Constructor
function __construct($id, $userId, $jobId, $date, $latest) {
$this->id = $id;
$this->userId = $userId;
$this->jobId = $jobId;
$this->date = $date;
$this->latest = $latest;
}
// Getters
function getId() {
return $this->id;
}
function getUserId() {
return $this->userId;
}
function getJobId() {
return $this->jobId;
}
function getDate() {
return $this->date;
}
function getLatest() {
return $this->latest;
}
// Setters
function setId($id) {
$this->id = $id;
}
function setUserId($userId) {
$this->userId = $userId;
}
function setJobId($jobId) {
$this->jobId = $jobId;
}
function setDate($date) {
$this->date = $date;
}
function setLatest($latest) {
$this->latest = $latest;
}
}
| true |
52765a71702b43a07c5c4868447fcc01edf29505 | PHP | Botnary/fusion-rewrite-lib | /src/Fusion/Rewrite/RewriteManager.php | UTF-8 | 1,850 | 2.703125 | 3 | [] | no_license | <?php
/**
* Created by IntelliJ IDEA.
* User: botnari
* Date: 15-03-30
* Time: 7:02 PM
*/
namespace Fusion\Rewrite;
use Symfony\Component\Yaml\Parser;
class RewriteManager
{
private $_begin = '#begin_rewrite';
private $_end = '#end_rewrite';
function enable()
{
if (!$this->isEnabled()) {
$rules = $this->getRules();
file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/.htaccess', $rules, FILE_APPEND);
}
}
function disable()
{
if ($this->isEnabled()) {
$content = file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/.htaccess');
$lines = explode("\n", $content);
$tmp = array();
$record = true;
foreach ($lines as $line) {
if (trim($line) == $this->_begin) {
$record = false;
}
if (trim($line) == $this->_end) {
$record = true;
}
if ($record && $line != $this->_end) {
$tmp[] = $line;
}
}
}
}
function getRules()
{
$rules = array();
$rules[] = $this->_begin;
$rules[] = 'RewriteEngine on';
$rules[] = 'RewriteBase /';
$parse = new Parser();
$staticRules = $parse->parse(file_get_contents(realpath(__FILE__) . '/rules.yml'));
foreach ($staticRules as $rule) {
$rules[] = $rule;
}
$rules[] = $this->_end;
return implode("\r\n", $rules);
}
function isEnabled()
{
if (file_exists($_SERVER['DOCUMENT_ROOT'] . '/.htaccess')) {
$content = file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/.htaccess');
return preg_match("/(begin_rewrite)/", $content);
}
return false;
}
} | true |
0863cd9ad9ae2c5de9934f5a0c38de3456e5b5f8 | PHP | terablaze/core | /src/Container/ContainerAwareTrait.php | UTF-8 | 1,529 | 2.765625 | 3 | [
"MIT"
] | permissive | <?php
namespace Terablaze\Container;
use ReflectionException;
use Terablaze\Container\Exception\ContainerException;
use Terablaze\Container\Exception\ParameterNotFoundException;
trait ContainerAwareTrait
{
/**
* @var ContainerInterface|Container $container
*/
protected $container;
/**
* @param ContainerInterface|null $container
* @return $this;
*/
public function setContainer(ContainerInterface $container = null): self
{
$this->container = $container;
return $this;
}
/**
* @param string $key
* @return bool
*/
public function has(string $key): bool
{
if (!$this->container instanceof Container) {
$this->container = Container::getContainer();
}
return $this->container->has($key);
}
/**
* @param string $key
* @return object
* @throws ReflectionException
*/
public function get(string $key)
{
if (!$this->container instanceof Container) {
$this->container = Container::getContainer();
}
return $this->container->get($key);
}
/**
* @param string $key
* @return array|mixed|string
* @throws ContainerException
* @throws ParameterNotFoundException
*/
public function getParameter(string $key)
{
if (!$this->container instanceof Container) {
$this->container = Container::getContainer();
}
return $this->container->getParameter($key);
}
}
| true |
1ef1cc13375d372805e57c08744422290e275759 | PHP | nikoedyr/WEB-AHP-TOPSIS | /ahp topsis/functions.php | UTF-8 | 9,272 | 2.578125 | 3 | [] | no_license | <?php
error_reporting(~E_NOTICE);
session_start();
include'config.php';
include'includes/db.php';
$db = new DB($config['server'], $config['username'], $config['password'], $config['database_name']);
include'includes/general.php';
include'includes/paging.php';
$mod = $_GET['m'];
$act = $_GET['act'];
$nRI = array (
1=>0,
2=>0,
3=>0.58,
4=>0.9,
5=>1.12,
6=>1.24,
7=>1.32,
8=>1.41,
9=>1.46,
10=>1.49,
11=>1.51,
12=>1.48,
13=>1.56,
14=>1.57,
15=>1.59
);
$rows = $db->get_results("SELECT kode_alternatif, nama_alternatif FROM tb_alternatif ORDER BY kode_alternatif");
foreach($rows as $row){
$ALTERNATIF[$row->kode_alternatif] = $row->nama_alternatif;
}
$rows = $db->get_results("SELECT kode_kriteria, nama_kriteria, atribut FROM tb_kriteria ORDER BY kode_kriteria");
foreach($rows as $row){
$KRITERIA[$row->kode_kriteria] = array(
'nama_kriteria'=>$row->nama_kriteria,
'atribut'=>$row->atribut,
'bobot'=>$row->bobot
);
}
function AHP_get_relkriteria(){
global $db;
$data = array();
$rows = $db->get_results("SELECT k.nama_kriteria, rk.ID1, rk.ID2, nilai
FROM tb_rel_kriteria rk INNER JOIN tb_kriteria k ON k.kode_kriteria=rk.ID1
ORDER BY ID1, ID2");
foreach($rows as $row){
$data[$row->ID1][$row->ID2] = $row->nilai;
}
return $data;
}
function AHP_get_relalternatif($kriteria=''){
global $db;
$rows = $db->get_results("SELECT * FROM tb_rel_alternatif WHERE kode_kriteria='$kriteria' ORDER BY kode1, kode2");
$matriks = array();
foreach($rows as $row){
$matriks[$row->kode1][$row->kode2] = $row->nilai;
}
return $matriks;
}
function get_kriteria_option($selected = 0){
global $KRITERIA;
foreach($KRITERIA as $key => $value){
if($key==$selected)
$a.="<option value='$key' selected>$value[nama_kriteria]</option>";
else
$a.="<option value='$key'>$value[nama_kriteria]</option>";
}
return $a;
}
function get_atribut_option($selected = ''){
$atribut = array('benefit'=>'Benefit', 'cost'=>'Cost');
foreach($atribut as $key => $value){
if($selected==$key)
$a.="<option value='$key' selected>$value</option>";
else
$a.= "<option value='$key'>$value</option>";
}
return $a;
}
function AHP_get_alternatif_option($selected = ''){
global $db;
$rows = $db->get_results("SELECT kode_alternatif, nama_alternatif FROM tb_alternatif ORDER BY kode_alternatif");
foreach($rows as $row){
if($row->kode_alternatif==$selected)
$a.="<option value='$row->kode_alternatif' selected>$row->kode_alternatif - $row->nama_alternatif</option>";
else
$a.="<option value='$row->kode_alternatif'>$row->kode_alternatif - $row->nama_alternatif</option>";
}
return $a;
}
function AHP_get_nilai_option($selected = ''){
$nilai = array(
'1' => 'Sama penting dengan',
'2' => 'Mendekati sedikit lebih penting dari',
'3' => 'Sedikit lebih penting dari',
'4' => 'Mendekati lebih penting dari',
'5' => 'Lebih penting dari',
'6' => 'Mendekati sangat penting dari',
'7' => 'Sangat penting dari',
'8' => 'Mendekati mutlak dari',
'9' => 'Mutlak sangat penting dari',
);
foreach($nilai as $key => $value){
if($selected==$key)
$a.="<option value='$key' selected>$key - $value</option>";
else
$a.= "<option value='$key'>$key - $value</option>";
}
return $a;
}
function AHP_get_total_kolom($matriks = array()){
$total = array();
foreach($matriks as $key => $value){
foreach($value as $k => $v){
$total[$k]+=$v;
}
}
return $total;
}
function AHP_normalize($matriks = array(), $total = array()){
foreach($matriks as $key => $value){
foreach($value as $k => $v){
$matriks[$key][$k] = $matriks[$key][$k]/$total[$k];
}
}
return $matriks;
}
function AHP_get_rata($normal){
$rata = array();
foreach($normal as $key => $value){
$rata[$key] = array_sum($value)/count($value);
}
return $rata;
}
function AHP_mmult($matriks = array(), $rata = array()){
$data = array();
$rata = array_values($rata);
foreach($matriks as $key => $value){
$no=0;
foreach($value as $k => $v){
$data[$key]+=$v*$rata[$no];
$no++;
}
}
return $data;
}
function AHP_consistency_measure($matriks, $rata){
$matriks = AHP_mmult($matriks, $rata);
foreach($matriks as $key => $value){
$data[$key]=$value/$rata[$key];
}
return $data;
}
function AHP_get_eigen_alternatif($kriteria=array()){
$data = array();
foreach($kriteria as $key => $value){
$kode_kriteria = $key;
$matriks = AHP_get_relalternatif($kode_kriteria);
$total = AHP_get_total_kolom($matriks);
$normal = AHP_normalize($matriks, $total);
$rata = AHP_get_rata($normal);
$data[$kode_kriteria] = $rata;
}
$new = array();
foreach($data as $key => $value){
foreach($value as $k => $v){
$new[$k][$key] = $v;
}
}
return $new;
}
function AHP_get_rank($array){
$data = $array;
arsort($data);
$no=1;
$new = array();
foreach($data as $key => $value){
$new[$key] = $no++;
}
return $new;
}
function TOPSIS_get_hasil_analisa(){
global $db;
$rows = $db->get_results("SELECT a.kode_alternatif, k.kode_kriteria, ra.nilai
FROM tb_alternatif a
INNER JOIN tb_rel_alternatif ra ON ra.kode_alternatif=a.kode_alternatif
INNER JOIN tb_kriteria k ON k.kode_kriteria=ra.kode_kriteria
ORDER BY a.kode_alternatif, k.kode_kriteria");
$data = array();
foreach($rows as $row){
$data[$row->kode_alternatif][$row->kode_kriteria] = $row->nilai;
}
return $data;
}
function TOPSIS_hasil_analisa($echo=true){
global $db, $ALTERNATIF, $KRITERIA;
$data = TOPSIS_get_hasil_analisa();
if(!$echo)
return $data;
$r.= "<tr><th></th>";
$no=1;
foreach($data[key($data)] as $key => $value){
$r.= "<th>".$KRITERIA[$key]['nama_kriteria']."</th>";
$no++;
}
$no=1;
foreach($data as $key => $value){
$r.= "<tr>";
$r.= "<th nowrap>".$ALTERNATIF[$key]."</th>";
foreach($value as $k => $v){
$r.= "<td>".$v."</td>";
}
$r.= "</tr>";
$no++;
}
$r.= "</tr>";
return $r;
}
function TOPSIS_nomalize($array, $max = true){
$data = array();
$kuadrat = array();
foreach($array as $key => $value){
foreach($value as $k => $v){
$kuadrat[$k]+= ($v * $v);
}
}
foreach($array as $key => $value){
foreach($value as $k => $v){
$data[$key][$k] = $v / sqrt($kuadrat[$k]);
}
}
return $data;
}
function TOPSIS_nomal_terbobot($array, $bobot){
$data = array();
foreach($array as $key => $value){
foreach($value as $k => $v){
$data[$key][$k] = $v * $bobot[$k];
}
}
return $data;
}
function TOPSIS_solusi_ideal($array){
global $KRITERIA;
$data = array();
$temp = array();
foreach($array as $key => $value){
foreach($value as $k => $v){
$temp[$k][] = $v;
}
}
foreach($temp as $key => $value) {
$max = max ($value);
$min = min ($value);
if($KRITERIA[$key]['atribut']=='benefit')
{
$data['positif'][$key] = $max;
$data['negatif'][$key] = $min;
}
else
{
$data['positif'][$key] = $min;
$data['negatif'][$key] = $max;
}
}
return $data;
}
function TOPSIS_jarak_solusi($array, $ideal){
$temp = array();
$arr = array();
foreach($array as $key => $value){
foreach($value as $k => $v){
$arr['positif'][$key][$k] = pow(($v - $ideal['positif'][$k]), 2);
$arr['negatif'][$key][$k] = pow(($v - $ideal['negatif'][$k]), 2);
$temp[$key]['positif']+= pow(($v - $ideal['positif'][$k]), 2);
$temp[$key]['negatif']+= pow(($v - $ideal['negatif'][$k]), 2);
}
$temp[$key]['positif'] = sqrt($temp[$key]['positif']);
$temp[$key]['negatif'] = sqrt($temp[$key]['negatif']);
}
return $temp;
}
function TOPSIS_preferensi($array){
global $KRITERIA;
$temp = array();
foreach($array as $key => $value){
$temp[$key] = $value['negatif'] / ($value['positif'] + $value['negatif']);
}
return $temp;
}
function get_rank($array){
$data = $array;
arsort($data);
$no=1;
$new = array();
foreach($data as $key => $value){
$new[$key] = $no++;
}
return $new;
} | true |
8e181e3eeb15194b273b8c608714900cec76e8f3 | PHP | code-action/sipra | /app/Http/Requests/ConstanciaRequest.php | UTF-8 | 914 | 2.59375 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class ConstanciaRequest 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 [
'archivo'=>'required|file|between:1,14800|mimes:pdf',
'f_estudiante'=>'required_if:bandera,1',
];
}
public function messages(){
return [
'archivo.required'=>'El archivo es obligatorio',
'archivo.file'=>'El archivo no fue subido correctamente',
'archivo.between'=>'El peso permitido es de 1 KB a 14MB',
'archivo.mimes'=>'Tipo de archivo no válido',
];
}
}
| true |
8f5dac262ae1de4cdd58dab87eaa966bb845fd0b | PHP | stratease/emvc | /data/SchemaList.class.php | UTF-8 | 7,324 | 3.203125 | 3 | [
"Apache-2.0"
] | permissive | <?php
class SchemaList extends ArrayIterator
{
/**
* Is loaded boolean.
* @var bool
*/
public $isLoaded = false;
/**
* Eelement array.
* @var array
*/
private $elements = array();
/**
* Key association array.
* @var array
*/
private $keyAssocation = array();
/**
* Index integer.
* @var int
*/
private $i = 0;
/**
* Count integer.
* @var int
*/
private $count = 0;
/**
* Object variable.
* @var object
*/
private $obj;
/**
* Requires an instance of the object type it will be using to map the iterator guts and searches.
* @param BaseUnit $obj The instance to be iterated on
*/
function __construct($obj)
{
$this->obj = $obj;
}
/**
* Returns the empty object that seeded the list
* @return Schema Base object
*/
public function getBaseObject()
{
return $this->obj;
}
/**
* Moves the internal pointer to the begging of the array.
*/
public function rewind()
{
$this->i = 0;
if(count($this->elements))
{
return $this->elements[$this->i];
}
}
/**
* Returns the current item.
* @return mixed
*/
public function current()
{
return $this->elements[$this->i];
}
/**
* Returns the index of the current location.
* @return int
*/
public function key()
{
return $this->elements[$this->i]->get($this->obj->primaryKey);
}
/**
* Moves the pointer to the next item.
*/
public function next()
{
$this->i++;
if( isset($this->elements[$this->i]) )
{
return $this->elements[$this->i];
}
return null;
}
/**
* If the current iteration exists.
* @return bool
*/
public function valid()
{
return isset($this->elements[$this->i]);
}
/**
* Counts how many items are in the list.
* @return int
*/
public function count()
{
return $this->count;
}
/**
* Check if the index is valid.
* @param mixed $index
* @return bool
*/
public function offsetExists($index)
{
return isset($this->elements[$this->keyAssocation[$index]]);
}
/**
* Gets an object at a particular index.
* @param mixed $index
* @return object
*/
public function offsetGet($index)
{
return $this->elements[$this->keyAssocation[$index]];
}
/**
* Pushes an object at a particular index
* @param mixed $index
* @param object $object
*/
public function offsetSet($index, $object)
{
if( $index === null )
{
$index = $object->get($this->obj->primaryKey);
}
if( !isset($this->keyAssocation[$index]) )
{
$this->keyAssocation[$index] = $this->count++;
}
$this->elements[$this->keyAssocation[$index]] = $object;
}
/**
* Seeks to the position specified.
* @param mixed $position
*/
public function seek($position)
{
$this->i = $position;
return $this->elements[$this->i];
}
/**
* Unsets at a particular index.
* @param mixed $index
*/
public function offsetUnset($index)
{
$this->count--;
unset($this->elements[$this->keyAssocation[$index]]);
unset($this->keyAssocation[$index]);
if( $index == $this->i )
{
$this->i--;
}
return $this->elements[$this->i];
}
/**
* Alias for push
* @param object $object
*/
public function append($object)
{
$this->push($object);
}
/**
* Push a loaded object on the list
* @param object $obj
*/
public function push($obj)
{
$this->isLoaded = true;
$this->keyAssocation[$obj->get($this->obj->primaryKey)] = $this->count++;
$this->elements[] = $obj;
}
/**
*Clears this list object pointers to any set of results
*/
public function clear()
{
$this->isLoaded = false;
$this->elements = array();
$this->keyAssocation = array();
$this->i = 0;
$this->count = 0;
}
/**
* Retrieves an individual instance on a field : value specified.
* PARAM string $field OPTIONAL The field name
* PARAM mixed $value OPTIONAL The value of the field. Treated as a string.
* PARAM mixed $more OPTIONAL The value of the field. Treated as a string.
* @return bool True if entry is found and loaded, false otherwise
*/
public function select()
{
$this->clear();
$where = null;
// no args, so I'm searching for ALL... or doing a specific search
if(func_num_args() === 0
|| ($where = call_user_func_array(array($this->obj, 'buildWhere'), func_get_args())))
{
$query = 'SELECT *
FROM '.$this->obj->buildFrom();
// pass args to where generator
if($where)
{
$query .= ' WHERE '.$where;
}
$results = $this->site->db->query($query);
$success = ($results->num_rows > 0);
while($row = $results->fetch_assoc())
{
$obj = new $this->obj->__CLASS__($this->obj->site);
if($obj->loadRow($row))
{
$this->push($obj);
}
}
return $success;
}
return false;
}
/**
* Magic method call function
* @param mixed $method
* @param mixed $arguments
* @return mixed
*/
function __call($method, $arguments)
{
switch( $method )
{
case 'buildFrom':
return $this->obj->buildFrom();
default:
$key = $this->obj->primaryKey;
$return = array();
foreach( $this->elements as $object )
{
$return[$object->get($key)] = call_user_func_array(array($object, $method), $arguments);
}
return $return;
}
}
/**
* Magic getter
* @param mixed $property
* @return mixed
*/
function __get($property)
{
switch( $property )
{
case '__CLASS__':
return $this->obj->__CLASS__;
case 'primaryKey':
return $this->obj->primaryKey;
case 'site':
return $this->obj->site;
default:
$key = $this->obj->primaryKey;
$return = array();
foreach( $this->elements as $object )
{
$return[$object->get($key)] = $object->$property;
}
return $return;
}
}
/**
* Magic setter
* @param mixed $property
* @param mixed $value
*/
function __set($property, $value)
{
foreach( $this->elements as $key => $object )
{
$object->$property = $value;
}
}
/**
* Sorts the list in reverse index order.
*/
public function krsort()
{
krsort($this->keyAssocation);
$i = 0;
$e = $this->elements;
foreach( $this->keyAssocation as $id => $v )
{
$e[$i++] = $this->elements[$v];
}
$this->elements = $e;
return $this;
}
/**
* Sorts the list in the index order.
*/
public function ksort()
{
ksort($this->keyAssocation);
$i = 0;
$e = $this->elements;
foreach( $this->keyAssocation as $id => $v )
{
$e[$i++] = $this->elements[$v];
}
$this->elements = $e;
return $this;
}
/**
* Pop object off the end of the array.
* @return mixed
*/
public function pop()
{
$this->count--;
$last = array_pop($this->elements);
$this->rewind();
return $last;
}
/**
* Shift object off the beginning of the array.
* @return mixed
*/
public function shift()
{
$this->count--;
$start = array_shift($this->elements);
$this->rewind();
return $start;
}
public function query()
{
$query = new SchemaQuery($this);
if($w = call_user_func_array(array($this->obj, 'buildWhere'), func_get_args()))
{
$query->where($w);
}
return $query;
}
}
| true |
e2b0d7a9148e70f56aab70c1738359081959781f | PHP | DimaFormaniuk/SeconTal.1 | /del.php | UTF-8 | 1,688 | 2.578125 | 3 | [] | no_license | <?php
session_start();
require_once "functions.php";
header('Content-Type: text/html; charset=utf-8');
$id = $_SESSION["id"];
echo "Привіт, ".$_SESSION["login"];
echo ' <a href="exit.php">Вихiд</a> <br>';
$m=getTovar($_SESSION["id"]);
$j=$_GET["id"];
for($i=0;$i<count($m);$i++) {
if ($m[$i]["id"] == $j) {
$j = $i;
break;
}
}
$i=$j;
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Document</title>
</head>
<body>
<form enctype="multipart/form-data" action="" method="POST" class="reg">
Ви хочете видалити товар<br>
Категорія<br>
<select name="categori">
<option value="Ноутбуки" <?php if($m[$i]["kategoria"]=="Ноутбуки")echo "selected";?> >Ноутбуки</option>
<option value="Телефони" <?php if($m[$i]["kategoria"]=="Телефони")echo "selected";?> >Телефони</option>
<option value="Планшети" <?php if($m[$i]["kategoria"]=="Планшети")echo "selected";?> >Планшети</option>
</select><br>
Назва<br>
<input type="text" name="name" required minlength="2" value=<?php echo $m[$i]["name"]?> ><br>
Опис<br>
<textarea name="opus" required cols="40" rows="3"><?php echo $m[$i]["opus"]?></textarea><br>
Ціна<br>
<input type="text" name="pric" required minlength="2" value=<?php echo $m[$i]["cina"]?>><br>
<input type="submit" name="submit" value="Видалити"><br>
</form>
</body>
</html>
<?php
if(isset($_POST["submit"])) {
DeleteTovar($m[$i]["id"]);
header("Location:/cabinetprobavca.php");
exit;
}
//header("Location:/index.php");
?>
| true |
f9857b3857e48aedc67b5b2cdc0b47581b8ee975 | PHP | shaikalimulla/Apps | /Web Applications/Travel Info Web Application/Source Code/signup.php | UTF-8 | 3,212 | 2.65625 | 3 | [] | no_license | <?php
//Name : Alimulla Shaik
//Purpose: A php page to handle signup functionalities
//Author : shal5122@colorado.edu
//Version: 1.0
//Date : 2016/04/22
session_start();
session_regenerate_id();
include_once('/var/www/html/project/project-lib.php');
isset($_REQUEST['s'])?$s=strip_tags($_REQUEST['s']):$s="";
isset($_REQUEST['new_username'])?$new_username=strip_tags($_REQUEST['new_username']):$new_username="";
isset($_REQUEST['new_pass'])?$new_pass=strip_tags($_REQUEST['new_pass']):$new_pass="";
isset($_REQUEST['email'])?$email=strip_tags($_REQUEST['email']):$email="";
$ip_address ='';
connect($db);
num_check($s);
switch($s){
case 1:
signup($db);
break;
case 3:
update_user_in_db($db, $new_username, $new_pass, $email);
break;
}
function signup(){
echo "
<html>
<head>
<title> TravelBook App </title>
<style>
th {border: 3px solid chocolate; padding:5px; }
td {padding: 5px; border: 3px solid darkcyan;}
</style>
</head>
<body background=\"turkey.jpg\">
<center>
<h1 style=\"color:blue\"> Travel Book </h1>
<div align=left>
<a href=index.php style=\"background-color:yellow\"> HomePage </a>
</div>
<hr>
<form action=signup.php method=post>
<table>
<tr>
<th>User Name </th>
<td><input type=\"text\" name=\"new_username\" requierd/></td>
</tr>
<tr>
<th>Email ID </th>
<td><input type=\"text\" name=\"email\" requierd/></td>
</tr>
<tr>
<th>Password </th>
<td><input type=\"password\" name=\"new_pass\" required/></td>
</tr>
</table>
<input type=\"submit\" name=\"submit\" value=\"SignUp\"/>
<input type=\"hidden\" name=\"s\" value=\"3\"/>
</form>
</div>
";
}
function update_user_in_db($db, $new_username, $new_pass, $email){
$new_username=mysqli_real_escape_string($db,$new_username);
$new_pass=mysqli_real_escape_string($db,$new_pass);
$email=mysqli_real_escape_string($db,$email);
$salt = rand(10,10000);
$hash_salt=hash('sha256',$salt);
$hash_pass=hash('sha256',$new_pass.$hash_salt);
$cnt = 0;
$query="select count(*) from users where email=?";
if($stmt=mysqli_prepare($db,$query))
{
mysqli_stmt_bind_param($stmt,"s",$email);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $cnt);
while(mysqli_stmt_fetch($stmt))
{
$cnt = htmlspecialchars($cnt);
}
mysqli_stmt_close($stmt);
}
if($cnt >= 1)
{
header("Location:/project/login.php?s=5");
exit;
} else
{
/*if($query = mysqli_prepare($db, "SET foreign_key_checks = 0")){
mysqli_stmt_execute($query);
mysqli_stmt_close($query);
}
*/
if($query = mysqli_prepare($db, "insert into users set userid='', username=?, password=?, email=?, salt=?"))
{
mysqli_stmt_bind_param($query, "ssss", $new_username,$hash_pass, $email, $hash_salt);
mysqli_stmt_execute($query);
mysqli_stmt_close($query);
header("Location:/project/login.php?s=4");
}
else {
echo "Error!!! Can not update new user details in database";
header("Location:/project/index.php");
}
}
}
function num_check($var) {
if ($var != null) {
if(!is_numeric($var)) {
print "<b> [ERROR]: Invalid Syntax. </b> <br>";
exit;
}
}
}
?>
| true |
94b3ac3ae7168319db74106d5903f269855b409c | PHP | connorhu/szamlazzhu | /src/Item/InvoiceItem.php | UTF-8 | 3,065 | 2.734375 | 3 | [] | no_license | <?php
namespace SzamlaAgent\Item;
use SzamlaAgent\Ledger\InvoiceItemLedger;
use SzamlaAgent\SzamlaAgentException;
use SzamlaAgent\Util;
/**
* Számlatétel
*
* @package SzamlaAgent\Item
*/
class InvoiceItem extends Item {
/**
* Tételhez tartozó főkönyvi adatok
*
* @var InvoiceItemLedger
*/
protected $ledgerData;
/**
* Számlatétel példányosítás
*
* @param string $name tétel név
* @param double $netUnitPrice nettó egységár
* @param double $quantity mennyiség
* @param string $quantityUnit mennyiségi egység
* @param string $vat áfatartalom
*/
public function __construct($name, $netUnitPrice, $quantity = self::DEFAULT_QUANTITY, $quantityUnit = self::DEFAULT_QUANTITY_UNIT, $vat = self::DEFAULT_VAT) {
parent::__construct($name, $netUnitPrice, $quantity, $quantityUnit, $vat);
}
/**
* @return array
* @throws SzamlaAgentException
*/
public function buildXmlData() {
$data = [];
$this->checkFields();
$data['megnevezes'] = $this->getName();
if (Util::isNotBlank($this->getId())){
$data['azonosito'] = $this->getId();
}
$data['mennyiseg'] = Util::doubleFormat($this->getQuantity());
$data['mennyisegiEgyseg'] = $this->getQuantityUnit();
$data['nettoEgysegar'] = Util::doubleFormat($this->getNetUnitPrice());
$data['afakulcs'] = $this->getVat();
if (Util::isNotNull($this->getPriceGapVatBase())) {
$data['arresAfaAlap'] = Util::doubleFormat($this->getPriceGapVatBase());
}
$data['nettoErtek'] = Util::doubleFormat($this->getNetPrice());
$data['afaErtek'] = Util::doubleFormat($this->getVatAmount());
$data['bruttoErtek'] = Util::doubleFormat($this->getGrossAmount());
if (Util::isNotBlank($this->getComment())) {
$data['megjegyzes'] = $this->getComment();
}
if (Util::isNotNull($this->getLedgerData())) {
$data['tetelFokonyv'] = $this->getLedgerData()->buildXmlData();
}
return $data;
}
/**
* @return float
*/
public function getPriceGapVatBase() {
return $this->priceGapVatBase;
}
/**
* @param float $priceGapVatBase
*/
public function setPriceGapVatBase($priceGapVatBase) {
$this->priceGapVatBase = (float)$priceGapVatBase;
}
/**
* @return InvoiceItemLedger
*/
public function getLedgerData() {
return $this->ledgerData;
}
/**
* @param InvoiceItemLedger $ledgerData
*/
public function setLedgerData(InvoiceItemLedger $ledgerData) {
$this->ledgerData = $ledgerData;
}
/**
* @return string
*/
public function getComment() {
return $this->comment;
}
/**
* @param string $comment
*/
public function setComment($comment) {
$this->comment = $comment;
}
} | true |
b90de97f2f8dc231ed7a50b374a1dc1a04838efa | PHP | alaa-almaliki/graphql-custom-scalar-types | /src/GraphQL/Custom/Scalar/Types/AbstractType.php | UTF-8 | 2,422 | 2.921875 | 3 | [
"MIT"
] | permissive | <?php
namespace GraphQL\Custom\Scalar\Types;
use GraphQL\Error\Error;
use GraphQL\Language\AST\StringValueNode;
use GraphQL\Type\Definition\CustomScalarType;
use GraphQL\Utils;
/**
* Class AbstractType
* @package GraphQL\Custom\Scalar\Types
* @author Alaa Al-Maliki <alaa.almaliki@gmail.com>
*/
abstract class AbstractType extends CustomScalarType implements TypeValidationInterface, TypeMessageInterface
{
/**
* @return string
*/
abstract protected function getTypeName();
/**
* @param string $value
* @return mixed
*/
abstract protected function evaluateValue($value);
/**
* BasicEmailType constructor.
* @param array $config
*/
public function __construct(array $config = [])
{
$config = [
'name' => $this->getTypeName(),
'serialize' => [$this, 'serialize'],
'parseValue' => [$this, 'parseValue'],
'parseLiteral' => [$this, 'parseLiteral'],
];
parent::__construct($config);
}
/**
* @param string $value
* @return mixed
*/
public function validateValue($value)
{
if (!$this->evaluateValue($value)) {
throw new \UnexpectedValueException($this->getValueErrorMessage() . ': ' . Utils::printSafe($value));
}
return $this;
}
/**
* @param \GraphQL\Language\AST\Node $valueNode
* @return $this
* @throws Error
*/
public function validateLiteral($valueNode)
{
if (!$valueNode instanceof StringValueNode) {
throw new Error($this->getLiteralErrorMessage() . ': ' . $valueNode->kind, [$valueNode]);
}
if (!$this->evaluateValue($valueNode->value)) {
throw new Error("Not a valid email", [$valueNode]);
}
return $this;
}
/**
* @param string $value
* @return mixed
*/
public function serialize($value)
{
return $this->parseValue($value);
}
/**
* @param string $value
* @return mixed
*/
public function parseValue($value)
{
$this->validateValue($value);
return $value;
}
/**
* @param \GraphQL\Language\AST\Node $valueNode
* @return string
* @throws Error
*/
public function parseLiteral($valueNode)
{
$this->validateLiteral($valueNode);
return parent::parseLiteral($valueNode->value);
}
}
| true |
5add5b2024d761c507621f1b3ceb88cf40aafa7a | PHP | paultmutai/etsprojectzeta.github.io | /dhandlesignup.php | UTF-8 | 1,401 | 2.625 | 3 | [] | no_license | <?php
include "config.php";
if(isset(
$_POST['firstname'],
$_POST['lastname'],
$_POST['ward'],
$_POST['schools'],
$_POST['pnumber'],
$_POST['email'],
$_POST['password'],
$_POST['confpassword']
))
{
$firstname= trim ($_POST['firstname']);
$lastname=trim ($_POST['lastname']);
$ward=trim ($_POST['ward']);
$schools=trim($_POST['schools']);
$pnumber=trim ($_POST['pnumber']);
$email=trim($_POST['email']);
$password=trim($_POST['password']);
$confpassword=trim($_POST['confpassword']);
if(strlen($password)<6){
$password_error="ERROR";
}
else{
$store_password=password_hash($password, PASSWORD_DEFAULT);
}
if($confpassword!=$password){
$confpassword_pass_error="Passwords not same";
echo "conf_pass_error";
header("location:dSignup.php");
}
else{
$store_confirm_pass=password_hash($confpassword, PASSWORD_DEFAULT);
}
}
if(empty($password_error)and empty($confpassword_pass_error)){
$sql="INSERT INTO `drivers`( `firstname`, `lastname`, `ward`, `school`, `pnumber`, `email`, `password`)VALUES ('$firstname','$lastname','$ward','$schools','$pnumber','$email','$store_password')";
}
$result=mysqli_query($link, $sql);
if($result) {
// echo "You have been registered successfully";
header("location:dLogin.php");
}
else{
echo "ERROR executing $sql". mysqli_error($link);
header("location:error.php");
} | true |
19299e4086e354469de2a7c18c86ba5b7a401dad | PHP | prajputpmp/pack-repository | /src/Config/Config.php | UTF-8 | 1,219 | 2.796875 | 3 | [] | no_license | <?php
/**
* An implementor class for IConfig interface
*
* @package repository
* @version 1.0.0
* @author Prakash Rajput
* @license Proprietary
* @copyright
*/
namespace PCH\Library\Config;
use PCH\Library\Config\iConfig;
/**
* A configuration class to set/get configurations
* @author prajput
*
*/
class Config implements iConfig {
private $config = array ();
public function __construct() {
$this->config = array(
'database' => array(
'mysql' => [
'host' => 'localhost',
'driver' => 'pdo_mysql',
'dbname' => 'pack-repository',
'user' => 'root',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
]
),
'isDevMode' =>true
);
}
public function get($section, $parameter = null) {
if (! isset ( $this->config [$section] )) {
throw new \Exception ( "{$section} is NOT a valid section in config" );
}
if ($parameter) {
if (! isset ( $this->config [$section] [$parameter] )) {
throw new \Exception ( "{$parameter} is NOT a valid parameter in {$section} Section" );
}
return $this->config [$section] [$parameter];
}
return $this->config [$section];
}
}
| true |
54599584e01c77662df6002576aca7b819a50208 | PHP | yannlo/image-ressource | /src/Image.php | UTF-8 | 2,461 | 3.28125 | 3 | [] | no_license | <?php
namespace Yannlo\ImageRessource;
use Yannlo\ImageRessource\Exceptions\ImageException;
class Image
{
private string $name;
private string $type;
private string $extension;
public const BIG_SIZE = 'big';
public const MEDIUM_SIZE = 'medium';
public const LITTLE_SIZE = 'little';
public const PNG = ['type' => 'png','extension' => 'png'];
public const JPEG = ['type' => 'jpeg','extension' => 'jpg'];
public function __construct(array $data = [])
{
$this->hydrate($data);
}
private function hydrate(array $data)
{
foreach ($data as $key => $value) {
$method = 'set' . ucfirst($key);
if (method_exists($this, $method)) {
$this->$method($value);
}
}
}
// GETTERS
public function name(): string
{
return $this->name;
}
public function type(): string
{
return $this->type;
}
public function extension(): string
{
return $this->extension;
}
// SETTERS
public function setName(string $name): void
{
if (!(bool)preg_match('/^img[0-9]+_[a-z]+/', $name)) {
throw new ImageException();
return;
}
$endName = substr($name, strpos($name, '_') + 1);
$sizes = [
self::BIG_SIZE,
self::LITTLE_SIZE,
self::MEDIUM_SIZE
];
if (!in_array($endName, $sizes)) {
throw new ImageException();
return;
}
$this->name = $name;
}
public function setType(string $type): void
{
if (substr($type, 0, strpos($type, '/')) !== "image") {
throw new ImageException();
return;
}
$endType = substr($type, strpos($type, '/') + 1);
if (!in_array($endType, [self::JPEG["type"],self::PNG["type"]])) {
throw new ImageException();
return;
}
$this->type = $type;
}
public function setExtension(string $extension): void
{
if (!in_array($extension, [self::JPEG["extension"],self::PNG["extension"]])) {
throw new ImageException();
return;
}
$this->extension = $extension;
}
// public function getImageURL(): string
// {
// $url = $this->path . DIRECTORY_SEPARATOR . $this-> name . "." . $this -> extension;
// return $url;
// }
}
| true |
ee0b79aace10fc89ce1b67622b60bd365ceee8f3 | PHP | bin612/PHP7 | /dutchpay.php | UTF-8 | 208 | 2.890625 | 3 | [] | no_license | <?php
##amount를 4명으로 나눈 금액 구하기
$amount = 54750;
$rest = $amount % 4;
$person = ($amount - $rest)/4;
echo "1 인 {$person}원, 부족{$rest}원";
##결과 1인 13687원, 부족 2원
?> | true |
5ec8a7929179193c0e5fa5888466059ae3c689da | PHP | elickzhao/laravel-study | /app/Providers/AppServiceProvider.php | UTF-8 | 2,548 | 2.6875 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Providers;
use App\Models\Post;
use Illuminate\Support\ServiceProvider;
use DB;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//视图间共享数据
view()->share('sitename','Laravel学院-- 我是共享数据');
//视图Composer
view()->composer('hello',function($view) {
$view->with('user', array('name' => 'test', 'avatar' => public_path('images/touxiang.jpg')));
});
//多个视图
view()->composer(['hello','home'],function($view) {
$view->with('user', array('name' => 'test', 'avatar' => public_path('images/touxiang.jpg')));
});
//所有视图
view()->composer('*',function($view) {
$view->with('user', array('name' => 'test', 'avatar' => public_path('images/touxiang.jpg')));
});
//和composer功能相同 因为实例化后立即消失 也许可以减少内存消耗吧
view()->creator('profile', 'App\Http\ViewCreators\ProfileCreator');
/*
* 这个东西怎么理解呢
* share() 不可变共享数据 比如 网站名 网站地址之类的
* composer() 可变共享数据 比如用户名和头像 还有就是快速变化的信息 比如网站在线人数
* 这个每个页面加载都得请求 所以直接放到这里共享出来
*/
// DB::listen(function($sql,$bindings,$time){
// echo 'SQL语句执行: '.$sql.',参数: '.json_encode($bindings).',耗时: '.$time.'ms';
// });
Post::saving(function($post){
echo 'saving event is fired<br>';
//看来同样道理 必须是可见的参数
//必须在fillable里
if($post->user_id == 1)
return false;
});
Post::creating(function($post){
echo 'creating event is fired<br>';
//看来同样道理 必须是可见的参数
//必须在fillable里
if($post->name == 'test content')
return false;
});
Post::created(function($post){
echo 'created event is fired<br>';
});
Post::saved(function($post){
echo 'saved event is fired<br>';
});
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}
| true |
638d78654b9e690f68d0c80164b5f2ed3c095488 | PHP | zedektador/cental_pet | /register.php | UTF-8 | 3,048 | 2.765625 | 3 | [] | no_license | <?php
include("connect.php");
$firstname = $_POST["firstname"];
$lastname = $_POST["lastname"];
$email = $_POST["email"];
$password = $_POST["password"];
$repassword = $_POST["repassword"];
$mobile = $_POST["mobile"];
$address = $_POST["address"];
$emailvalidation = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9]+(\.[a-z]{2,4})$/";
$number = "/^[0-9]+$/";
if(empty($firstname) || empty($lastname) || empty($email) || empty($password) || empty($repassword) || empty($mobile) || empty($address)){
echo "
<div class='alert alert-warning'>
<a href='#' class = 'close' data-dismiss='alert' arial-label='close'>×</a><b>Fill all Fields</b>
</div>
";
exit();
} else {
if(!preg_match($emailvalidation, $email)){
echo "
<div class='alert alert-warning'>
<a href='#' class = 'close' data-dismiss='alert' arial-label='close'>×</a><b>This $email is not Valid</b>
</div>
";
exit();
}
if(strlen($password) < 9){
echo "
<div class='alert alert-warning'>
<a href='#' class = 'close' data-dismiss='alert' arial-label='close'>×</a><b>Password is to weak</b>
</div>
";
exit();
}
if(strlen($repassword) < 9){
echo "
<div class='alert alert-warning'>
<a href='#' class = 'close' data-dismiss='alert' arial-label='close'>×</a><b>Password is to weak</b>
</div>
";
exit();
}
if($password != $repassword){
echo "
<div class='alert alert-warning'>
<a href='#' class = 'close' data-dismiss='alert' arial-label='close'>×</a><b>Password is not same</b>
</div>
";
}
if(!preg_match($number, $mobile)){
echo "
<div class='alert alert-warning'>
<a href='#' class = 'close' data-dismiss='alert' arial-label='close'>×</a><b>Mobile Number $mobile is not valid</b>
</div>
";
exit();
}
if(!(strlen($mobile) ==11)){
echo "
<div class='alert alert-warning'>
<a href='#' class = 'close' data-dismiss='alert' arial-label='close'>×</a><b>Mobile Number must 11 digit</b>
</div>
";
exit();
}
//exisiting email kung meron na sa db
$sql = "SELECT user_id From user_info WHERE email = '$email' LIMIT 1 ";
$check_query = mysqli_query($con,$sql);
$count_email = mysqli_num_rows($check_query);
if($count_email > 0 ){
echo "
<div class='alert alert-danger'>
<a href='#' classx = 'close' data-dismiss='alert' arial-label='close'>×</a><b>Email Address is already available. Try Another Email Address</b>
</div>
";
exit();
}else {
$password = md5($password);
$sql = "INSERT INTO `user_info` (`user_id`, `firstname`, `lastname`, `email`, `password`, `mobile`, `address`) VALUES (NULL, '$firstname', '$lastname', '$email', '$password', '$mobile', '$address')";
$run_query = mysqli_query($con,$sql);
if($run_query){
echo "
<div class='alert alert-success'>
<a href='#' class = 'close' data-dismiss='alert' arial-label='close'>×</a><b>You are Registered successfully You may now Login to the Page</b>
</div>
";
header('Refresh:0; customer_registratioin.php');
}
}
}
?> | true |
4c188147022090298b532602d63648ff212f2337 | PHP | F4N70M/fw | /Fw/Components/Classes/DbItem.php | UTF-8 | 558 | 3.109375 | 3 | [] | no_license | <?php
namespace Fw\Components\Classes;
use Fw\Components\Services\Database\QueryBuilder;
class DbItem
{
protected $db;
protected $table;
protected $id;
public function __construct(QueryBuilder $db, string $table, int $id)
{
$this->db = $db;
$this->table = $table;
$this->id = $id;
}
public function get(string $column)
{
return ($request = $this->db->select()->from($this->table)->where(['id'=>$this->id])->result()) && isset($request[0][$column]) ? $request[0][$column] : false;
}
} | true |
9e1d6d42767667ffd71e2ea2839657eb2d7249ee | PHP | JnMik/api-generics | /src/Generic/Paging/PaginatorService.php | UTF-8 | 734 | 2.5625 | 3 | [] | no_license | <?php
namespace Support3w\Api\Generic\Paging;
class PaginatorService
{
/**
* @var PagingAbstract
*/
private $paging;
public function __construct(PagingAbstract $paging)
{
$this->paging = $paging;
}
public function getBaseOnePaging()
{
return $this->paging;
}
public function getBaseZeroPaging()
{
if ($this->paging instanceof BaseOnePaging) {
$baseOneToBaseZeroTransformer = new BaseOneToBaseZeroTransformer($this->paging);
return $baseOneToBaseZeroTransformer->transform();
}
return $this->paging;
}
public function setRowsCount($rowsCount)
{
$this->paging->setRowsCount($rowsCount);
}
} | true |
58d7b4ea0266db1b4cebd6b74b765ddf51b235a4 | PHP | samira2016/bourse | /Models/Entitys/Societe.php | UTF-8 | 3,222 | 3.3125 | 3 | [] | no_license | <?php
namespace Bourse\Models\Entitys;
use \Exception;
class Societe {
private $nom;
private $cp; //constant capital propre
private $cb; //capital boursier
private $nbta; //constant nombre total d'ation
private $nbad; //nombre d'action disponible
private $va; //valeur de l'action
private $ac; //prix de l'action a l'achat
private $email;
function __construct($nom, $cp, $cb, $nbta, $nbad) {
$this->setNom($nom);
try {
$this->setCp($cp);
$this->setCb($cb);
$this->setNbta($nbta);
$this->setNbad($nbad);
} catch (Exception $e) {
echo"une exception a ete lancee message : ".$e->getMessage();
}
$this->va = $this->calculVa();
$this->ac = $this->calculAc();
//$this->_cb=$this->calculCb();
}
//les getters
public function nom() {
return $this->nom;
}
public function cp() {
return $this->cp;
}
public function cb() {
return $this->cb;
}
public function nbta() {
return $this->nbta;
}
public function nbad() {
return $this->nbad;
}
public function va() {
return $this->va;
}
public function ac() {
return $this->ac;
}
public function email() {
return $this->email;
}
//les setters
public function setNom($nom) {
$this->nom = $nom;
}
public function setCp($cp) {
if (is_float($cp)) {
$this->cp = $cp;
} else {
throw new Exception("nombre cp doit entre un float");
}
}
public function setCb($cb) {
if (is_float($cb)) {
$this->cb = $cb;
} else {
throw new Exception("nombre cb doit entre un float");
}
}
public function setNbta($nbta) {
if (is_int($nbta)) {
$this->nbta = $nbta;
} else {
throw new Exception("nombre nbta doit entre un entier");
}
}
public function setNbad($nbad) {
if (is_int($nbad)) {
$this->nbad = $nbad;
} else {
throw new Exception("nombre nbad doit entre un entier");
}
}
public function setVa($va) {
if (is_float($va)) {
$this->va = $va;
} else {
throw new Exception("va doit entre un de type float");
}
}
public function setAc($ac) {
$this->ac = $ac;
}
public function setEmail($email) {
//todoo
/*
1-validation de la variable email avec une methode validateMail dans mes outils
2- une exeption si le champs mail n'est pas valide
*/
$this->email = $email;
}
//--------------Calcul de va ac et cb
//calcul de valeur de l'action
public function calculVa() {
return ($this->cp + $this->cb) / $this->nbta;
}
//calcul de prix de l'action a l'achat
public function calculAc() {
return $this->va * (1 + ($this->nbta - $this->nbad) / $this->nbta);
}
//calcul du capital boursier
public function calculCb() {
return $this->cp;
}
}
?> | true |
5b078fce8687f6532147549a46145f25343b12ae | PHP | michelsacher/giennale | /typo3conf/ext/razor/Classes/ViewHelpers/Condition/Client/IsBrowserViewHelper.php | UTF-8 | 2,114 | 2.671875 | 3 | [
"CC-BY-3.0"
] | permissive | <?php
namespace RZ\Razor\ViewHelpers\Condition\Client;
/*
* 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!
*/
/**
*
* ### Condition: Client's Browser
*
* Condition ViewHelper which renders the `then` child if client's
* browser matches the `browser` argument
*
* ### Examples
*
* <!-- simple usage, content becomes then-child -->
* <razor:if.client.isBrowser browser="chrome">
* Thank you for using Google Chrome!
* </razor:if.client.isBrowser>
* <!-- display a nice warning if not using Chrome -->
* <razor:if.client.isBrowser browser="chrome">
* <f:else>
* <div class="alert alert-info">
* <h2 class="alert-header">Please download Google Chrome</h2>
* <p>
* The particular system you are accessing uses features which
* only work in Google Chrome. For the best experience, download
* Chrome here:
* <a href="http://chrome.google.com/">http://chrome.google.com/</a>
* </p>
* </f:else>
* </razor:if.client.isBrowser>
*
* @author Raphael Zschorsch <rafu1987@gmail.com>
* @package Razor
* @subpackage ViewHelpers\Condition\Client
*/
class IsBrowserViewHelper extends AbstractClientInformationViewHelper
{
/**
* Render method
*
* @param string $browser
* @param string $version
* @return string
*/
public function render($browser, $version)
{
if (array_key_exists($browser, $this->getBrowsers()) && $this->getVersion($browser) == $version) {
$content = $this->renderThenChild();
} else {
$content = $this->renderElseChild();
}
return $content;
}
}
| true |
22a55fdb08fc1b0885aa5d7d55ae00f06ea74fb9 | PHP | ofix/panda-log | /core/BinaryStream.php | UTF-8 | 9,286 | 2.875 | 3 | [
"MIT"
] | permissive | <?php
/*
* This file is part of panda-log.
*
* Licensed under The MIT License
* For full copyright and license information, please see the MIT-LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @author code lighter
* @copyright https://github.com/ofix
* @we-chat 981326632
* @license http://www.opensource.org/licenses/mit-license.php MIT License
* @Date 2017/11/30
* @Time 9:28
*
* @desc binary stream is a wrapper for PHP pack/unpack functions
*/
namespace ofix\PandaLog\core;
class BinaryStream
{
private $data = '';
private $position = 0;
private $endian;
private $isLittleEndian;
public $needConvertEndian;
private static $systemEndian = null;
public static function systemEndian()
{
if(self::$systemEndian === null){
self::$systemEndian = pack('v', 1) == pack('s', 1) ?
Endian::LITTLE_ENDIAN : Endian::BIG_ENDIAN;
}
return self::$systemEndian;
}
public function __construct($data = null)
{
$this->setEndian(self::systemEndian());
$this->data = is_null($data) ? $this->data : $data;
}
/*
* Endian::LITTLE_ENDIAN or Endian::BIG_ENDIAN
*/
public function getEndian()
{
return $this->endian;
}
public function setEndian($value)
{
$this->endian = $value == Endian::BIG_ENDIAN ? Endian::BIG_ENDIAN : Endian::LITTLE_ENDIAN;
$this->isLittleEndian = $this->endian == Endian::LITTLE_ENDIAN;
$this->needConvertEndian = $this->endian != self::systemEndian();
}
public function getLength()
{
return strlen($this->data);
}
public function getPosition()
{
return $this->position;
}
public function setPosition($value)
{
$this->position = $value;
}
public function getBytesAvailable()
{
return strlen($this->data) - $this->position;
}
public function clear()
{
$this->data = '';
$this->position = 0;
}
public function readBoolean()
{
if($this->getBytesAvailable() < 1){
return null;
}
$arr = unpack('@' . $this->position . '/ck', $this->data);
$this->position++;
return boolval($arr['k']);
}
public function readByte()
{
if($this->getBytesAvailable() < 1){
return false;
}
$arr = unpack('@' . $this->position . '/ck', $this->data);
$this->position++;
return $arr['k'];
}
public function readUByte()
{
if($this->getBytesAvailable() < 1){
return false;
}
$arr = unpack('@' . $this->position . '/Ck', $this->data);
$this->position++;
return $arr['k'];
}
public function readInt16()
{
//php缺少有符号型整数的大小端读取,参见补码相关知识
if(($i = $this->readUInt16()) !== false && $i > 0x7fff){
$i = -(~($i - 1) & 0xffff);
}
return $i;
}
public function readUInt16()
{
if($this->getBytesAvailable() < 2){
return false;
}
$key = $this->needConvertEndian ? ($this->isLittleEndian ? '/vk' : '/nk') : '/Sk';
$arr = unpack('@' . $this->position . $key, $this->data);
$this->position += 2;
return $arr['k'];
}
public function readInt32()
{
if(($i = $this->readUInt32()) !== false && $i > 0x7fffffff){
$i = -(~($i - 1) & 0xffffffff);
}
return $i;
}
public function readUInt32()
{
if($this->getBytesAvailable() < 4){
return false;
}
$key = $this->needConvertEndian ? ($this->isLittleEndian ? '/Vk' : '/Nk') : '/Lk';
$arr = unpack('@' . $this->position . $key, $this->data);
$this->position += 4;
return $arr['k'];
}
public function readInt64()
{
if(($i = $this->readUInt64()) !== false && $i > 0x7fffffffffffffff){
$i = -(~($i - 1));
}
return $i;
}
/**
* php has't uint64,so be sure the number is in int64.min ~ int64.max
* @return [type] [description]
*/
public function readUInt64()
{
if($this->getBytesAvailable() < 8){
return false;
}
$key = $this->needConvertEndian ? ($this->isLittleEndian ? '/Pk' : '/Jk') : '/Qk';
$arr = unpack('@' . $this->position . $key, $this->data);
$this->position += 8;
return $arr['k'];
}
public function readFloat()
{
if($this->getBytesAvailable() < 4){
return false;
}
if($this->needConvertEndian){
$data = $this->readBytes(4);
$arr = unpack('fk', strrev($data));
} else{
$arr = unpack('@' . $this->position . '/fk', $this->data);
$this->position += 4;
}
return $arr['k'];
}
public function readDouble()
{
if($this->getBytesAvailable() < 8){
return false;
}
if($this->needConvertEndian){
$data = $this->readBytes(8);
$arr = unpack('dk', strrev($data));
} else{
$arr = unpack('@' . $this->position . '/dk', $this->data);
$this->position += 8;
}
return $arr['k'];
}
public function readBytes($count)
{
if($this->getBytesAvailable() < $count){
return false;
}
$key = '/a'. $count . 'k';
$arr = unpack('@' . $this->position . $key, $this->data);
$this->position += $count;
return $arr['k'];
}
/**
* first read strlen(2byte), then read str
*/
public function readString()
{
$len = $this->readUInt16();
if($len <=0 || $this->getBytesAvailable() < $len){
return false;
}
$key = '/a'. $len . 'k';
$arr = unpack('@' . $this->position . $key, $this->data);
$this->position += $len;
return $arr['k'];
}
/*
* @func 读取指定字节字符串
* @author code lighter
*/
public function readStringClean($len){
if($len <=0){
return false;
}
$key = '/a'. $len . 'k';
$arr = unpack('@' . $this->position . $key, $this->data);
$this->position += $len;
return $arr['k'];
}
public function writeBoolean($value)
{
$this->data .= pack('c', $value ? 1 : 0);
$this->position++;
}
public function writeByte($value)
{
$this->data .= pack('c', $value);
$this->position++;
}
public function writeUByte($value)
{
$this->data .= pack('C', $value);
$this->position++;
}
public function writeInt16($value)
{
//php缺少有符号型整数的大小端写入,参见补码相关知识
if($value < 0){
$value = -(~($value & 0xffff) + 1);
}
$this->writeUInt16($value);
}
public function writeUInt16($value)
{
$key = $this->needConvertEndian ? ($this->isLittleEndian ? 'v' : 'n') : 'S';
$this->data .= pack($key, $value);
$this->position += 2;
}
public function writeInt32($value)
{
if($value < 0){
$value = -(~($value & 0xffffffff) + 1);
}
$this->writeUInt32($value);
}
public function writeUInt32($value)
{
$key = $this->needConvertEndian ? ($this->isLittleEndian ? 'V' : 'N') : 'L';
$this->data .= pack($key, $value);
$this->position += 4;
}
public function writeInt64($value)
{
if ($value < 0) {
$value = -(~$value + 1);
}
$this->writeUInt64($value);
}
/**
* php has't uint64,so be sure the number is in int64.min ~ int64.max
* @return [type] [description]
*/
public function writeUInt64($value)
{
$key = $this->needConvertEndian ? ($this->isLittleEndian ? 'P' : 'J') : 'Q';
$this->data .= pack($key, $value);
$this->position += 8;
}
public function writeFloat($value)
{
$this->data .= $this->needConvertEndian ? strrev(pack('f', $value)) : pack('f', $value);
$this->position += 4;
}
public function writeDouble($value)
{
$this->data .= $this->needConvertEndian ? strrev(pack('d', $value)) : pack('d', $value);
$this->position += 8;
}
public function writeBytes($value)
{
$len = strlen($value);
$this->data .= pack('a' . $len, $value);
$this->position += $len;
}
/*
* first read strlen(2byte), then read str
*/
public function writeString($value)
{
$len = strlen($value);
$this->writeUInt16($len);
$this->data .= pack('a' . $len, $value);
$this->position += $len;
}
/*
* @func 写入二进制流补充版
* @author code lighter
*/
public function writeStringClean($data,$byte_count)
{
$this->data .=pack('a'.$byte_count,$data);
$this->position += $byte_count;
}
public function toBytes()
{
return $this->data;
}
} | true |
d98e379efdd8b0c4a996d25c188fe545ce6606bb | PHP | Samah87/sushi_Webseite | /admin/eanlass.php | UTF-8 | 4,207 | 2.96875 | 3 | [] | no_license | <?PHP
session_start();
include("../inc/const.php");
if(!isset($_SESSION['login'])){
header("location: login".PHPEND);
}
$db = new mysqli(HOST,USER,PASS,DBANK);
if ($db->connect_errno) {
die('Sorry - gerade gibt es ein Problem: '.$db->connect_error);
}
$fehler[] = "";
$erfolg[] = "";
if(isset($_POST['submit']) && !empty($_POST['submit'])){
$anlass = $_POST['anlass'];
if(strlen($anlass) <= 4){
$fehler[] += 1;
}else{
// prüfen ob eintrag schon vorhanden
$sql = "select aid from anlass where lower(aname) = lower('$anlass') limit 1";
$eintrag = $db->query($sql);
if($eintrag->num_rows){
$fehler[] += 3;
}else{
$sql = "insert into anlass (aname) values ('$anlass')";
$db->query($sql);
if(!$db->insert_id){
$fehler[] += 2;
}else{
$erfolg[] += 1;
}
}
}
}
if(isset($_POST['kill']) && !empty($_POST['kill'])){
$aid = $_POST['aid'];
if(!empty($aid)){
$sql = "delete from anlass where aid = '$aid'";
$db->query($sql);
if($db->affected_rows){
$erfolg[] += 2;
}else{
$fehler[] += 4;
}
}
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Eingabe Anlass</title>
<style type="text/css">
@import url("css/standart.css");
@import url("css/menue.css");
</style>
</head>
<body>
<?PHP
include("inc/menue.php");
?>
<main>
<article class="links">
<section>
<h1>Vorhandene Anlässe</h1>
<?PHP
if(in_array("4",$fehler)){
echo("<p class='fehler'>Anlass konnte nicht gelöscht werden!</p>\n");
}
if(in_array("2",$erfolg)){
echo("<p class='erfolg'>Anlass wurde gelöscht.</p>\n");
}
$sql = "select * from anlass";
$eintrag = $db->query($sql);
if($eintrag->num_rows){
while($zeile = $eintrag->fetch_assoc()){
echo('<form method="post" action="'.$_SERVER['PHP_SELF'].'" enctype="multipart/form-data" accept-charset="UTF-8">'."\n");
echo("<span class='breite'>".$zeile['aname']."</span>\n");
echo('<input type="hidden" name="aid" value="'.$zeile['aid'].'">'."\n");
echo('<input type="submit" name="kill" value="Löschen">'."\n");
echo("</form>\n");
}
}else{
echo("<p>Leider noch kein Anlass vorhanden.</p>\n");
}
?>
</section>
</article>
<article class="rechts">
<section>
<h1>Eingabe Anlass</h1>
<?PHP
if(in_array("1",$fehler)){
echo("<p class='fehler'>Der Anlass ist zu kurz!</p>\n");
}
if(in_array("2",$fehler)){
echo("<p class='fehler'>Anlass konnte nicht in die DB geschriben werden!</p>\n");
}
if(in_array("3",$fehler)){
echo("<p class='fehler'>Diesen Eintrag gibt es schon!</p>\n");
}
if(in_array("1",$erfolg)){
echo("<p class='erfolg'>Anlass wurde hinzugefügt.</p>\n");
}
?>
<form method="post" action="<?PHP $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data" accept-charset="UTF-8">
<p>
<label for="anlass">Anlass:</label>
<input type="text" name="anlass" id="anlass" value="">
</p>
<p>
<input type="submit" name="submit">
</p>
</form>
</section>
</article>
</main>
<?PHP
$eintrag->free();
$db->close();
unset($eintrag,$sql,$db,$fehler,$erfolg);
?>
</body>
</html> | true |
ece9ec2060f64be3b0af33c35fe95808d04cd862 | PHP | Team0003/Swim-Meet-Signup | /Ver 2.0/src/GetKidEvents.php | UTF-8 | 4,416 | 2.75 | 3 | [] | no_license | <?php
include 'connectDB.php';
function calculateAge($a,$b){
$conn = $GLOBALS['conn'];
$sql = "select TIMESTAMPDIFF(YEAR,'".$a."',"."'".$b."')";
$row = fetchFromDB($conn, $sql);
return $row[0];
}
$dob = $_GET["dob"];
$sex = $_GET["sex"];
$meetId=$_GET["meetId"];
$conn = connectToDB();
$GLOBALS['conn'] = $conn;
$sqlMeetInfo = "select meet_date1, meet_date2, payable_to, payment_instructions, per_event_charge, max_per_kid_signup, signup_deadline, min_eligible_age, additionalInfo1, additionalInfo2 from meet where meet_id=$meetId";
$meetResult= mysqli_query($conn, $sqlMeetInfo);
$meetArr = array();
while($meetRow=mysqli_fetch_row ($meetResult)){
$meetArr= array("meetDate1"=>$meetRow[0],"meetDate2"=>$meetRow[1],"payableTo"=>$meetRow[2],"paymentInstr"=>$meetRow[3],"eventCharge"=>$meetRow[4],"maxSignUps"=>$meetRow[5],"deadline"=>$meetRow[6],"min_eligible_age"=>$meetRow[7],"additionalInfo1"=>$meetRow[8],"additionalInfo2"=>$meetRow[9]);
$meet1Date = $meetRow[0];
$meet2Date = $meetRow[1];
$min_eligible_age = $meetRow[7];
}
/*$meet1Date = '2017-11-16';
$meet2Date = '2017-11-15';*/
$sqlEvent = "select event_number, event_name,eligibile_sex, eligible_age, event_date ,min_eligible_time, session_type, additional_info from event where meet_id=$meetId";
$kidsAgeAtFirstMeet = calculateAge($dob, $meet1Date);
$kidsAgeAtSecondMeet = calculateAge($dob, $meet2Date);
//echo "<script>console.log('kidsAgeAtFirstMeet'.$kidsAgeAtFirstMeet);</script>";
$result = mysqli_query($conn,$sqlEvent);
$filteredEvents = array();
$count=0;
while ($row=mysqli_fetch_row ($result)){
$count++;
$eligible_age = $row[3];
//echo "<script>console.log('Eligible Age '.$eligible_age);</script>";
$eligible_sex = $row[2];
//echo "<script>console.log('Eligible Sex '.$eligible_sex);</script>";
$eventDate = $row[4];
//echo "<script>console.log('Event Date '.$eventDate);</script>";
if($eventDate == $meet1Date){
// echo "<script>console.log('Event Date '.$eventDate);</script>";
// echo "<script>console.log('Meet Date '.$meet1Date);</script>";
$kidsAge = $kidsAgeAtFirstMeet;
}
else{
$kidsAge = $kidsAgeAtSecondMeet;
}
// echo "<script>console.log('Age at event date '.$kidsAge);</script>";
if($eligible_sex == $sex || $eligible_sex=="Mixed"){
if($eligible_age!="OPEN"){
//get range of eligible ages
if(strpos($eligible_age, "-")==true){
$ageRange = explode("-",$eligible_age);
$minAge = $ageRange[0];
$maxAge = $ageRange[1];
}
if(strpos($eligible_age, "&")==true){
$ageRange = explode("&",$eligible_age);
$minAge = $ageRange[0];
$maxAge = $ageRange[1];
}
}
if($eligible_age=="OPEN" && $kidsAge>$min_eligible_age){
array_push($filteredEvents, array("event_number"=>$row[0],"event_name"=>$row[1],"eligibile_sex"=>$row[2],"eligible_age"=>$row[3],"event_date"=>$row[4],"min_eligible_time"=>$row[5],"session_type"=>$row[6],"additional_info"=>$row[7],"addButton"=>true));
}
else{
if($kidsAge >=$minAge){
if(is_numeric($maxAge[0])){
if($kidsAge<=$maxAge){
array_push($filteredEvents, array("event_number"=>$row[0],"event_name"=>$row[1],"eligibile_sex"=>$row[2],"eligible_age"=>$row[3],"event_date"=>$row[4],"min_eligible_time"=>$row[5],"session_type"=>$row[6],"additional_info"=>$row[7],"addButton"=>true));
}
}
else{
//It will be Up or O. In that case kid satisfies the criteria by satisfying min Age criteria only.
array_push($filteredEvents, array("event_number"=>$row[0],"event_name"=>$row[1],"eligibile_sex"=>$row[2],"eligible_age"=>$row[3],"event_date"=>$row[4],"min_eligible_time"=>$row[5],"session_type"=>$row[6],"additional_info"=>$row[7],"addButton"=>true));
}
}
}
}
}
//echo "<script>console.log('total events checked'.$count);</script>";
array_push($filteredEvents, $meetArr);
// $newArr[] = array();
//echo var_dump($filteredEvents);
/*
$arr[] = array();
while ($row=mysqli_fetch_row ($result)){
// echo "<script>console.log('aaaa');</script>";
array_push($arr, array("event_number"=>$row[0],"event_name"=>$row[1],"eligibile_sex"=>$row[2],"eligible_age"=>$row[3],"event_date"=>$row[4],"min_eligible_time"=>$row[5],"session_type"=>$row[6],"additional_info"=>$row[7]));
// array_push($newArr,$arr);}*/
//echo var_dump($arr);
echo json_encode($filteredEvents);
?> | true |
f61d04199573d89ffb279114972e7f5030ec4156 | PHP | tyoro/tyozo | /delete.php | UTF-8 | 855 | 2.71875 | 3 | [
"WTFPL"
] | permissive | <?php
include_once "./conf.inc";
if( empty($_POST['url']) ){
print 'param not found.';
exit;
}
$file_path = $DIR_PATH.$_POST['url'].'.png';
if( !is_public_file( $public_dir ,$file_path, false ) ){
print 'file not found.';
exit;
}
if( !unlink( $file_path )){
print 'file delete error.';
exit;
}
print "success.";
function is_public_file($public_dir, $path, $permit_sub_dir = true )
{
if (! is_string($path)) {
return false;
}
$realpath = realpath($path);
if ($realpath === false) {
return false;
}
if (file_exists($realpath) === false) {
return false;
}
if (strncmp($public_dir, $realpath, strlen($public_dir)) !== 0) {
return false;
}
if( !$permit_sub_dir && substr_count( $public_dir, '/' ) !== substr_count( $realpath, '/' ) ){
return false;
}
return true;
}
| true |
fd5ead875ba93087d3ec3acbf2fb526ab0c76a80 | PHP | July-c/hundred | /application/common/model/store/RoleAccess.php | UTF-8 | 2,985 | 2.515625 | 3 | [
"Apache-2.0"
] | permissive | <?php
// +----------------------------------------------------------------------
// | Common
// +----------------------------------------------------------------------
// | 版权所有 2015-2020 武汉市微易科技有限公司,并保留所有权利。
// +----------------------------------------------------------------------
// | 网站地址: https://www.kdfu.cn
// +----------------------------------------------------------------------
// | 这不是一个自由软件!您只能在不用于商业目的的前提下使用本程序
// +----------------------------------------------------------------------
// | 不允许对程序代码以任何形式任何目的的再发布
// +----------------------------------------------------------------------
// | Author: 微小易 Date: 2018-12-01
// +----------------------------------------------------------------------
namespace app\common\model\store;
use app\common\model\BaseModel;
/**
* 商家用户角色权限关系模型
* Class RoleAccess
* @package app\common\model\admin
*/
class RoleAccess extends BaseModel
{
protected $name = 'role_access';
protected $updateTime = false;
/**
* 新增关系记录
* @param $role_id
* @param array $access
* @return array|false
* @throws \Exception
*/
public function add($role_id, $access)
{
$data = [];
foreach ($access as $access_id) {
$data[] = [
'role_id' => $role_id,
'access_id' => $access_id,
'app_id' => self::$app_id,
];
}
return $this->saveAll($data);
}
/**
* 更新关系记录
* @param $role_id
* @param array $newAccess 新的权限集
* @return array|false
* @throws \Exception
*/
public function edit($role_id, $newAccess)
{
$where['role_id']=$role_id;
self::deleteAll($where);
/**
* 找出添加的权限
* 假如已有的权限集合是A,界面传递过得权限集合是B
* 权限集合B当中的某个权限不在权限集合A当中,就应该添加
* 使用 array_diff() 计算补集
*/
$data = [];
foreach ($newAccess as $key) {
$data[] = [
'role_id' => $role_id,
'access_id' => $key,
'app_id' => self::$app_id,
];
}
return $this->saveAll($data);
}
/**
* 获取指定角色的所有权限id
* @param int|array $role_id 角色id (支持数组)
* @return array
*/
public static function getAccessIds($list,$role_id)
{
$roleIds = is_array($role_id) ? $role_id : [(int)$role_id];
return (new self)->where('role_id', 'in', $roleIds)->column('access_id');
}
/**
* 删除记录
* @param $where
* @return int
*/
public static function deleteAll($data)
{
return self::destroy($data);
}
} | true |
b3df8a9cd7b8ac87d9fada698bc5f8eede43fd5c | PHP | FortuneSeafood/meowtemple | /app/Repositories/Meow/Lottery.php | UTF-8 | 557 | 3.046875 | 3 | [] | no_license | <?php
namespace App\Repositories\Meow;
use App\Models\Meow\Lottery as LotteryModel;
class Lottery
{
private $oLotteryModel;
/**
* 建構子
*
* @param LotteryModel $_oModel
*/
public function __construct(LotteryModel $_oModel)
{
$this->oLotteryModel = $_oModel;
}
/**
* 取籤
*
* @param [int] $_iLotteryID 籤號
* @return array
*/
public function getLottery(int $_iLotteryID)
{
return $this->oLotteryModel->where('ID', $_iLotteryID)->get()->toArray();
}
}
| true |
9defc391ce1dfe26c69d5029175a8ba002726950 | PHP | rentpost/forte-payments-php | /src/HttpClient/RequestOverrideHack.php | UTF-8 | 591 | 2.546875 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types = 1);
namespace Rentpost\ForteApi\HttpClient;
/**
* @author Sam Anthony <sam@rentpost.com>
*
* This is a bit of a hack that allows Automated tests to bypass the HTTP request
* to forte and instead pass specific JSON.
*/
class RequestOverrideHack
{
static protected $overrideData = null;
static public function setOverrideJson(string $json): void
{
self::$overrideData = $json;
}
static public function getOverrideJson(): ?string
{
$json = self::$overrideData;
self::$overrideData = null;
return $json;
}
} | true |
dd64e5ba51b8b50261a5dcc2f45038693e78e12d | PHP | Nico-17/Exercices-PHP | /modules/module-7/12-nometsexe.php | UTF-8 | 365 | 2.546875 | 3 | [] | no_license | <HTML>
<head>
<meta charset="utf-8" />
</head>
<BODY>
<?php
if ($_GET['sexe']=="M") {
echo "Bonjour Monsieur ". $_GET['nom'].".";
} else {
echo "Bonjour Madame ". $_GET['nom'].".";
}
?>
</BODY></HTML>
| true |
af1b3ea1df0b2a42fa1dcde78e94343798826856 | PHP | jemzubiri/PetShop | /login.php | UTF-8 | 1,531 | 2.765625 | 3 | [] | no_license | <?php
session_start();// Starting Session
// Define $username and $password
$username=$_POST['email'];
$password=$_POST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = @mysqli_connect('localhost', 'root', '', 'petshopdb');
// To protect MySQL injection for Security purpose
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($connection, $username);
$password = mysqli_real_escape_string($connection, $password);
$ses_sql = mysqli_query($connection,"select userName,id,userRole from usertbl where userEmail='$username'");
$row = mysqli_fetch_assoc($ses_sql);
$userRole = $row['userRole'];
// SQL query to fetch information of registerd users and finds user match.
$query = mysqli_query($connection,"select * from usertbl where userPassword='$password' AND userEmail='$username' ");
$rows = mysqli_num_rows($query);
if ($rows == 1){
$_SESSION['login_user']=$username;
// Initializing Session
// header("location: home-user.php"); // Redirecting To Other Page
if($userRole == "Member"){
echo "member login";
}
elseif($userRole == "Admin"){
echo "admin login";
}
elseif($userRole == "Secretary"){
echo "secretary login";
}
elseif($userRole == "Doctor"){
echo "doctor login";
}
else{
echo "error";
}
}
else{
echo "error";
}
mysqli_close($connection); // Closing Connection
?> | true |
5784206a8403cd4959ee64672a07fbd43b2f151c | PHP | maxim-barbotkin1/test-lara-vue | /api/app/Models/Team.php | UTF-8 | 745 | 2.65625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Team extends Model
{
use HasFactory;
protected $fillable = ['name'];
/**
* The attributes that are not mass assignable.
*
* @var array
*/
protected $guarded = [];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
];
/**
* The attributes that load relations
* @var array
*/
protected $with = [
'players',
];
/**
* The players that related to Team.
*/
public function players()
{
return $this->belongsToMany(Player::class);
}
}
| true |
b90ff94bceb9626189272733144d5a944fdea5ec | PHP | tulparbot/tulpar | /app/Tulpar/Commands/General/AboutUserCommand.php | UTF-8 | 2,478 | 2.53125 | 3 | [] | no_license | <?php
namespace App\Tulpar\Commands\General;
use App\Enums\CommandCategory;
use App\Models\UserRank;
use App\Tulpar\Commands\BaseCommand;
use App\Tulpar\CommandTraits\HasMemberArgument;
use App\Tulpar\Contracts\CommandInterface;
use App\Tulpar\Helpers;
use Discord\Parts\Embed\Embed;
use Discord\Parts\Guild\Role;
use Illuminate\Support\Carbon;
class AboutUserCommand extends BaseCommand implements CommandInterface
{
use HasMemberArgument;
public static string $command = 'about-user';
public static string $description = 'Show about user.';
public static array $permissions = [];
public static array $usages = [
'user-id',
'@username',
];
public static string $category = CommandCategory::General;
public function run(): void
{
$member = $this->getMemberArgument(failMessage: true);
if ($member === false) {
return;
}
if ($member === null) {
$member = $this->message->member;
}
$registered_at = $member->user->createdTimestamp();
$joined_at = $member->joined_at;
$roles = [];
/** @var Role $role */
foreach ($member->roles as $role) {
$roles[$role->id] = '<@&' . $role->id . '>';
}
$embed = new Embed($this->discord);
$embed->setAuthor($member->username, $member->user->getAvatarAttribute());
$embed->setThumbnail($member->user->getAvatarAttribute());
$embed->setDescription(Helpers::userTag($member->id));
$embed->addFieldValues($this->translate('Joined At'), $joined_at->shortRelativeToNowDiffForHumans(), true);
$embed->addFieldValues($this->translate('Registered At'), Carbon::createFromTimestamp($registered_at)->shortRelativeToNowDiffForHumans(), true);
$embed->addFieldValues($this->translate('Rank'), 0, true);
$embed->addFieldValues($this->translate('Messages in ````:server````', ['server' => $this->message->guild->name]), ($rank = UserRank::find($this->message->guild_id, $this->message->user_id))->message_count, true);
$embed->addFieldValues($this->translate('Messages in ````:channel````', ['channel' => '#' . $this->message->channel->name]), $rank->getChannelMessageCount($this->message->channel_id), true);
$embed->addFieldValues($this->translate('Roles [:count]', ['count' => count($roles)]), implode(' ', $roles), false);
$this->message->channel->sendEmbed($embed);
}
}
| true |
77e667a14a21e19433e7662b288276c4983f8fea | PHP | smlparry/Check-In | /app/models/ConnectedUser.php | UTF-8 | 254 | 2.578125 | 3 | [
"MIT"
] | permissive | <?php
class ConnectedUser extends Eloquent {
protected $fillable = ['user_id', 'connected_users'];
protected $table = 'connected_users';
public function connectedUsers( $id )
{
return $this->whereUserId( $id )->pluck( 'connected_users' );
}
} | true |
a01777cc0ef12702f797658e8968ed08d4a5e2fb | PHP | phillipsharring/profphp | /src/User/Domain/UserRepository.php | UTF-8 | 246 | 2.78125 | 3 | [] | no_license | <?php declare(strict_types=1);
namespace SocialNews\User\Domain;
interface UserRepository
{
public function add(User $user): void;
public function save(User $user): void;
public function findByUsername(string $username): ?User;
}
| true |
4b220e0944bca0fe63e56a4d4c85efc18ba5e797 | PHP | shreenivasan/Tutorials | /php/oops/inheritance.php | UTF-8 | 298 | 3.359375 | 3 | [] | no_license | <?php
class B
{
public $bname='B';
public function getName()
{
echo $this->bname;
}
}
class A extends B
{
private $aname='A';
public function getName()
{
echo parent::getName();
echo $this->aname;
}
}
$aobj=new A();
echo $aobj->getName();
| true |
79012916c97bf9996180d148646dd0ef6d2904bf | PHP | EdwinWalela/php-auth | /db.php | UTF-8 | 2,079 | 3.15625 | 3 | [] | no_license | <?php
session_start();
// This function establishes db connection
function connect(){
$servername = "localhost";
$username = "root";
$pass = "";
$db = "login";
return new mysqli($servername,$username,$pass,$db);
}
// This function recieves a username and password
// and creates a new user & stores it into the db
// after account creation the user is redirected
// to the index page in order to login
function register($username,$password){
$conn = connect(); // connect to db
$password = sha1($password); // hash password before saving it to the db
// notice 'userID' is not included since the primary key has the attribute 'AUTO_INCREMENT'
$sql = "INSERT INTO users (username,pass) VALUES('".$username."','".$password."')";
if($conn->query($sql)){
header("Location: ./index.php"); // redirect to index.phph
}else{
echo($conn->error); // print error
// header("Location: ./index.php?register=fail");
}
}
// This function authenticates a user. It recieves a username and password(plain-text)
// the password is hashed and then is compared with the stored password
// if they match user is redirected to the profile
// session is used to store username
function login($username,$password){
$conn = connect(); // connect to db
$sql = "SELECT * FROM users WHERE username = '" . $username . "'";
$result = $conn->query($sql);
// convert result to an associative array
$result = $result->fetch_assoc();
$password = sha1($password); // hash password
// compare password provided during login with stored password
if($result["pass"] === $password){
$_SESSION["username"] = $result["username"];
header("Location: ./profile.php"); // redirect to user profile
}else{
header("Location: ./index.php?login=fail"); // redirect back to index.php
}
}
?> | true |
6e86b300b25dd3269c2428230f5c22c6485aa7ad | PHP | BennyC/zeus-barcode | /test/Upc/Ean13Test.php | UTF-8 | 4,210 | 2.53125 | 3 | [] | no_license | <?php
namespace ZeusTest\Barcode\Upc;
use Zeus\Barcode\Upc\Ean13;
/**
*
* @author Rafael M. Salvioni
*/
class Ean13Test extends \PHPUnit_Framework_TestCase
{
/**
* @test
*/
public function validationTest()
{
$dataArr = [
'5901234123457' => [true, true],
'9780735200449' => [true, true],
'002210034567' => [false, true],
'7123456789011' => [false, false],
'412345678908' => [false, false],
'8x60603226779' => [false, false],
'8' => [true, false],
'' => [false, false],
];
foreach ($dataArr as $data => &$info) {
try {
$bc = new Ean13($data, $info[0]);
$this->assertTrue($info[1]);
$this->assertEquals($bc->getProductCode(), \substr($data, 7, 5));
$this->assertEquals($bc->withProductCode('56')->getProductCode(), '00056');
$this->assertEquals($bc->isUpcaCompatible(), $data{0} == '0');
if ($bc->isUpcaCompatible()) {
$this->assertStringStartsWith(\substr($data, 1), $bc->toUpca()->getData());
}
else {
try {
$bc->toUpca();
$this->assertTrue(false);
}
catch (\Zeus\Barcode\Exception $ex) {
$this->assertTrue(true);
}
}
}
catch (\Exception $ex) {
$this->assertFalse($info[1]);
}
}
}
/**
* @test
* @depends validationTest
*/
public function withChecksumTest()
{
$bc = new Ean13('7501031311309');
$this->assertEquals($bc->getData(), '7501031311309');
$this->assertEquals($bc->getChecksum(), '9');
$this->assertEquals($bc->getRealData(), '750103131130');
$this->assertEquals($bc->getEncoded()->getBinary(), '10101100010100111001100101001110111101011001101010100001011001101100110100001011100101110100101');
}
/**
* @test
* @depends validationTest
*/
public function withoutChecksumTest()
{
$bc = new Ean13('750103131130', false);
$this->assertEquals($bc->getData(), '7501031311309');
$this->assertEquals($bc->getChecksum(), '9');
$this->assertEquals($bc->getRealData(), '750103131130');
$this->assertEquals($bc->getEncoded()->getBinary(), '10101100010100111001100101001110111101011001101010100001011001101100110100001011100101110100101');
}
/**
* @test
* @depends validationTest
*/
public function fieldsTest()
{
$bc = new Ean13('750103131130', false);
$this->assertEquals($bc->getSystemCode(), '750');
$this->assertEquals($bc->getManufacturerCode(), '1031');
$this->assertEquals($bc->getProductCode(), '31130');
$bc = new Ean13('990010313113', false);
$this->assertEquals($bc->getSystemCode(), '99');
$this->assertEquals($bc->getManufacturerCode(), '00103');
$this->assertEquals($bc->getProductCode(), '13113');
}
/**
* @test
* @depends fieldsTest
*/
public function withTest()
{
$bc = new Ean13('750103131130', false);
$bc = $bc->withSystemCode('99');
$this->assertEquals($bc->getSystemCode(), '99');
$bc = $bc->withManufacurerCode('104');
$this->assertEquals($bc->getManufacturerCode(), '00104');
$this->assertEquals($bc->getProductCode(), '31130');
$bc = $bc->withSystemCode('750');
$this->assertEquals($bc->getSystemCode(), '750');
$bc = $bc->withManufacurerCode('154');
$this->assertEquals($bc->getManufacturerCode(), '0154');
$this->assertEquals($bc->getProductCode(), '31130');
}
/**
* @test
* @depends withTest
* @expectedException \Zeus\Barcode\Upc\Ean13Exception
*/
public function systemCodeErrorTest()
{
$bc = new Ean13('991103131130', false);
$bc = $bc->withSystemCode('750');
}
}
| true |
697945bd9ffc814d167aa2804d83378fa468f9c7 | PHP | therealEthanGoldman/SmartPillBottle | /pillbottle/www/page3.php | UTF-8 | 1,045 | 2.59375 | 3 | [] | no_license | <?PHP
session_start();
if (!(isset($_SESSION['login']) && $_SESSION['login'] != '')) {
header ("Location: login3.php");
}
?>
<html>
<head>
<title>IOT Device User Interface</title>
</head>
<body>
<p><big><b>User Logged in</b></big></p>
<p><b>Dosing Schedule</b></p>
<table border cols=2>
<tr><td>Time of dose</td><td> amount </td></tr>
<?PHP
$connection = mysql_connect('localhost', 'root', 'p3gasus');
mysql_select_db('iotdevdb',$connection);
$query = "SELECT * FROM doses";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){ //Creates a loop to loop through results
echo "<tr><td>" . $row[1] . "</td><td>" . $row[2] . "</td></tr>"; //$row['index'] the index here is a field name
}
echo "</table>"; //Close the table in HTML
mysql_close(); //Make sure to close out the database connection
?>
<p> </p>
<FORM METHOD = "BEEP" ACTION="page3.php" >
<button type="button" onclick="parent.location='findme.php'">Find Me!</button>
</FORM>
<A HREF = page2.php>Log out</A>
</body>
</html>
| true |
c1fca52a06eda747f59f276723a39499c2c9c9b4 | PHP | DominikStyp/PHPDesignPatterns | /SPL/SplObserver/SplSubjectTrait.php | UTF-8 | 558 | 3.078125 | 3 | [] | no_license | <?php
/*
* This trait can be used in every class that has to implement SplSubject interface
*/
trait SplSubjectTrait {
private $observersArray = array();
public function attach(SplObserver $observer){
$id = spl_object_hash($observer);
$this->observersArray[$id] = $observer;
}
public function detach(SplObserver $observer){
$id = spl_object_hash($observer);
unset($this->observersArray[$id]);
}
public function notify(){
foreach($this->observersArray as $observer){
$observer->update($this);
}
}
}
| true |
82a79d69a727b1f8f09936662411626265609418 | PHP | elliexu119/personal-website-code-old | /contact me.php | UTF-8 | 934 | 2.640625 | 3 | [] | no_license | <?php
$errors = '';
$myemail = 'elliexu119@gmail.com';//<—–Put Your email address here.
if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['message'])){
$errors = '\n Error: all fields are required';
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['message'];
if(empty($errors)){
$to = $myemail;
$email_subject = 'Contact form submission: $name';
$email_body = 'You have received a new message. '.
' Here are the details:\n Name: $name \n '.
'Email: $email_address \n Message \n $message';
$headers = 'From: $myemail \nReply-To: $email_address';
if (mail($to,$email_subject,$email_body,$headers)){
echo 'Your mail has been sent successfully.';
header('Location: main.html');
} else{
echo 'Unable to send email. Please try again.';
}
//redirect to the 'thank you' page
} else {
header('Location: main.html');
}
?> | true |
0820211c905ee888e88c6d2d31776176cdcdb2f6 | PHP | raghast/Projet_blog | /Blog_Aurelien/Utils/flashbag.php | UTF-8 | 283 | 2.734375 | 3 | [] | no_license | <?php
// Fonction d'attribution du message 'succés' à la variable SESSION['flashbag']
function addFlash($message)
{
$_SESSION['flashbag'] = $message;
}
// Fonction qui renvois le message 'succés'
function getFlash()
{
return ($_SESSION['flashbag']);
} | true |
e87a7d9c27ff96a34f830e0bbd462ee2a5a0c019 | PHP | Ndu-Systems/plant-tech-php-api | /models/Plant.php | UTF-8 | 2,786 | 3.09375 | 3 | [] | no_license |
<?php
class Plant
{
//DB Stuff
private $conn;
//Constructor to DB
public function __construct($db)
{
$this->conn = $db;
}
public function getAll()
{
$query = "SELECT * FROM plant";
$stmt = $this->conn->prepare($query);
$stmt->execute(array());
return $stmt;
}
//Add
public function add(
$Name,
$Description,
$Views,
$MedicineId,
$CreateUserId,
$ModifyUserId,
$StatusId
) {
$PlantId = getUuid($this->conn);
$query = "INSERT INTO plant (
PlantId,
Name,
Description,
Views,
MedicineId,
CreateUserId,
ModifyUserId,
StatusId
)
VALUES (?,?, ?, ?, ?, ?,?,?)
";
try {
$stmt = $this->conn->prepare($query);
if ($stmt->execute(array(
$PlantId,
$Name,
$Description,
$Views,
$MedicineId,
$CreateUserId,
$ModifyUserId,
$StatusId
))) {
return $this->getById($PlantId);
}
} catch (Exception $e) {
return $e;
}
}
//update
public function update(
$Name,
$Description,
$Views,
$MedicineId,
$CreateUserId,
$ModifyUserId,
$StatusId,
$PlantId
) {
$query = "UPDATE plant
SET
Name=?,
Description=?,
Views=?,
MedicineId=?,
CreateUserId=?,
ModifyUserId=?,
StatusId=?,
ModifyDate = NOW()
Where
PlantId=?
";
try {
$stmt = $this->conn->prepare($query);
$stmt->execute(array(
$Name,
$Description,
$Views,
$MedicineId,
$CreateUserId,
$ModifyUserId,
$StatusId,
$PlantId
));
return $this->getById($PlantId);
} catch (Exception $e) {
return $e;
}
}
public function getById($PlantId)
{
$query = "SELECT * FROM plant WHERE PlantId = ?";
$stmt = $this->conn->prepare($query);
$stmt->execute(array($PlantId));
if ($stmt->rowCount()) {
return $stmt->fetch(PDO::FETCH_ASSOC);
}
}
}
| true |
0415c760f3275fb4d8ad647c6d26526038c67ab6 | PHP | surfingdirt/rest-api | /library/Lib/Form/Element/Level.php | UTF-8 | 652 | 2.546875 | 3 | [] | no_license | <?php
class Lib_Form_Element_Level extends Zend_Form_Element_Select
{
const BEGINNER = 'level_beginner';
const INTERMEDIATE = 'level_intermediate';
const PRO = 'level_pro';
public static $levels = array(
1 => self::BEGINNER,
2 => self::INTERMEDIATE,
3 => self::PRO,
);
public function __construct($spec = 'level', $label = 'level', $options = null)
{
parent::__construct($spec, $options);
$inArrayValidator = new Zend_Validate_InArray(array_keys(self::$levels));
$this->setLabel(ucfirst(Globals::getTranslate()->_($label)))
->addValidator($inArrayValidator)
->setMultiOptions(self::$levels);
}
} | true |
e35f7e081dd7de1e42b0c58d05bf1dff176f8b9c | PHP | hpunforgettable/servidor | /otros/post.php | UTF-8 | 589 | 3.21875 | 3 | [] | no_license | <?php
$mensaje = "";
if (isset($_POST["nombre"])&& $_POST["nombre"]!= "") //genera un true or un false para sabaer si existe o no nombre
{
$mensaje = "El nombre es: ". $_POST["nombre"];
}
else
{
$mensaje = "Debe escribir su nombre antes de continuar";
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8">
</head>
<body>
<form method="POST" action="post.php">
<input type="text" name="nombre" placeholder="nombre">
<input type="submit" value="Enviar">
</form>
<?php
if ($mensaje!= "")
{
echo ($mensaje);
}
?>
</body>
</html> | true |
3adc8e4561766116669abc4d585a613da57b5b37 | PHP | asmahar545/schoolFree | /Modele/Adult.php | UTF-8 | 2,214 | 2.859375 | 3 | [] | no_license | <?php
require_once 'Framework/Modele.php';
class Adult extends Modele
{
//return un tout les adults
public function getAdults()
{
$sql = "select * from adult";
$personnel= $this->executerRequete($sql);
return $personnel;
}
//return une seul adult
public function getadult($id)
{
$sql="select * from adult where id_adult= $id";
$rep= $this->executerRequete($sql);
$ligne= $rep->fetch();
return $ligne;
}
public function getAdultClass(){
}
public function getEducateurs(){
$sql= "select * from adult where id_adultCategory=2";
$rep= $this->executerRequete($sql);
return $rep;
}
//return le nombre d'adult
public function getnbadults()
{
$rqt='select count(*) as nb from adult ';
$rep= $this->executerRequete($rqt);
$ligne= $rep->fetch();
return $ligne['nb'];
}
//ajoute un adult
public function addAdult($name,$firstname,$adress,$birthday,$sexe,$phone,$email,$password,$id_adultCategory)
{
$sql='INSERT INTO `adult` (`id_adult`, `name`, `firstname`, `adress`, `birthday`, `sexe`, `phone`, `email`, `password`, `id_adultCategory`) VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, ?,?)';
$rep=$this->executerRequete($sql,array($name,$firstname,$adress,$birthday,$sexe,$phone,$email,$password,$id_adultCategory));
}
//return tableau de catégory
public function getCat(){
$sql="select * from adultcategory";
$cat= $this->executerRequete($sql);
return $cat;
}
//modifie l'adult
public function editAdult($name,$firstname,$adress,$birthday,$sexe,$phone,$email,$password,$id_adultCategory,$id){
$sql="UPDATE `adult` SET `name` = ?, `firstname` = ?, `adress` = ?,
`birthday` = ?, `sexe` = ?, `phone` = ?,
`email` = ?, `password` = ?,
`id_adultCategory` = ? WHERE `adult`.`id_adult` = ?";
$rep=$this->executerRequete($sql,array($name,$firstname,$adress,$birthday,$sexe,$phone,$email,$password,$id_adultCategory,$id));
}
} | true |
707f85e3cbab4cebc740ef08cd7fff09802dd4d4 | PHP | Titil364/jreadsfirstproject | /model/ModelAssocFormPI.php | UTF-8 | 1,605 | 2.78125 | 3 | [] | no_license | <?php
require_once File::build_path(array('model', 'ModelAssoc.php'));
class ModelAssocFormPI extends ModelAssoc{
private $formId;
private $personnalInformationName;
protected static $object = "AssocFormPI";
protected static $primary1 = "formId";
protected static $primary2 = "personnalInformationName";
public function getFormId(){return $this->formId;}
public function setFormId($formId){$this->formId = $formId;}
public function getPersonnalInformationName(){return $this->personnalInformationName;}
public function setPersonnalInformationName($personnalInformationName){$this->personnalInformationName = $personnalInformationName;}
public function __construct($formId = NULL, $personnalInformationId = NULL){
if (!is_null($formId) && !is_null($personnalInformationId)) {
$this->formId = $formId;
$this->personnalInformationName = $personnalInformationName;
}
}
public static function getAssocFormPIByFormId($id){
try{
$sql = "SELECT * FROM AssocFormPI WHERE formId=:id";
$prep = Model::$pdo->prepare($sql);
$values = array(
"id" => $id
);
$prep-> execute($values);
$prep->setFetchMode(PDO::FETCH_CLASS,'ModelAssocFormPI');
$assoc_array = $prep->fetchAll();
return $assoc_array;
}catch (PDOException $ex) {
if (Conf::getDebug()) {
echo $ex->getMessage();
} else {
echo "Error";
}
return false;
}
}
}
| true |
d7565bf704972b8b026c412f37259c6d9564af3f | PHP | jacomyma/GEXF-Atlas | /atlas/engine/ezc/ConsoleTools/tests/question_dialog_regex_validator_test.php | UTF-8 | 5,581 | 2.640625 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
/**
* ezcConsoleQuestionDialogRegexValidatorTest class.
*
* @package ConsoleTools
* @subpackage Tests
* @version 1.5.1
* @copyright Copyright (C) 2005-2009 eZ Systems AS. All rights reserved.
* @license http://ez.no/licenses/new_bsd New BSD License
*/
/**
* Test suite for ezcConsoleQuestionDialogRegexValidator class.
*
* @package ConsoleTools
* @subpackage Tests
*/
class ezcConsoleQuestionDialogRegexValidatorTest extends ezcTestCase
{
public static function suite()
{
return new PHPUnit_Framework_TestSuite( "ezcConsoleQuestionDialogRegexValidatorTest" );
}
public function testGetAccessDefaultSuccess()
{
$validator = new ezcConsoleQuestionDialogRegexValidator( "//" );
$this->assertEquals( "//", $validator->pattern );
$this->assertNull( $validator->default );
}
public function testGetAccessCustomSuccess()
{
$validator = new ezcConsoleQuestionDialogRegexValidator(
"/[0-9]+/",
23
);
$this->assertEquals( "/[0-9]+/", $validator->pattern );
$this->assertEquals( 23, $validator->default );
}
public function testGetAccessFailure()
{
$validator = new ezcConsoleQuestionDialogRegexValidator( "//" );
try
{
echo $validator->foo;
}
catch ( ezcBasePropertyNotFoundException $e )
{
return;
}
$this->fail( "Exception not thrown on invalid property foo." );
}
public function testSetAccessSuccess()
{
$validator = new ezcConsoleQuestionDialogRegexValidator( "//" );
$validator->pattern = "@^\s+$@";
$validator->default = 23.42;
$this->assertEquals( "@^\s+$@", $validator->pattern );
$this->assertEquals( 23.42, $validator->default );
}
public function testSetAccessFailure()
{
$validator = new ezcConsoleQuestionDialogRegexValidator( "//" );
$exceptionCaught = false;
try
{
$validator->pattern = "";
}
catch ( ezcBaseValueException $e )
{
$exceptionCaught = true;
}
$this->assertTrue( $exceptionCaught, "Exception not thrown on invalid value for property type." );
$exceptionCaught = false;
try
{
$validator->default = array();
}
catch ( ezcBaseValueException $e )
{
$exceptionCaught = true;
}
$this->assertTrue( $exceptionCaught, "Exception not thrown on invalid value for property default." );
$exceptionCaught = false;
try
{
$validator->foo = "Foo";
}
catch ( ezcBasePropertyNotFoundException $e )
{
$exceptionCaught = true;
}
$this->assertTrue( $exceptionCaught, "Exception not thrown on nonexistent property foo." );
}
public function testIssetAccess()
{
$validator = new ezcConsoleQuestionDialogRegexValidator( "//" );
$this->assertTrue( isset( $validator->pattern ), "Property pattern not set." );
$this->assertTrue( isset( $validator->default ), "Property default not set." );
$this->assertFalse( isset( $validator->foo ), "Property foo set." );
}
public function testValidate()
{
$validator = new ezcConsoleQuestionDialogRegexValidator( "//" );
$this->assertTrue( $validator->validate( "foo" ), "Value foo is invalid." );
$this->assertTrue( $validator->validate( true ) );
$this->assertTrue( $validator->validate( 23 ) );
$validator->pattern = "/^[0-9]+\.[a-z]+$/";
$this->assertTrue( $validator->validate( "123.abc" ), "Value 123.abc is invalid." );
$this->assertFalse( $validator->validate( "abc" ) );
$this->assertFalse( $validator->validate( 23 ) );
$validator->default = "foo";
$this->assertTrue( $validator->validate( "" ), "Empty value is invalid." );
}
public function testFixup()
{
$validator = new ezcConsoleQuestionDialogRegexValidator( "//" );
$this->assertEquals( "23", $validator->fixup( "23" ) );
$this->assertEquals( "-23", $validator->fixup( "-23" ) );
$this->assertEquals( "foo", $validator->fixup( "foo" ) );
$this->assertEquals( "23.42", $validator->fixup( "23.42" ) );
$this->assertEquals( "-23.42", $validator->fixup( "-23.42" ) );
$this->assertEquals( "true", $validator->fixup( "true" ) );
$this->assertEquals( "false", $validator->fixup( "false" ) );
$this->assertEquals( "1", $validator->fixup( "1" ) );
$this->assertEquals( "0", $validator->fixup( "0" ) );
$this->assertEquals( "", $validator->fixup( "" ) );
$validator->default = "foo";
$this->assertEquals( "foo", $validator->fixup( "" ) );
}
public function testGetResultString()
{
$validator = new ezcConsoleQuestionDialogRegexValidator( "//" );
$this->assertEquals( "(match //)", $validator->getResultString() );
$validator->default = "foo";
$this->assertEquals( "(match //) [foo]", $validator->getResultString() );
$validator->pattern = "/^[0-9]+\.[a-z]+$/";
$validator->default = null;
$this->assertEquals( "(match /^[0-9]+\.[a-z]+$/)", $validator->getResultString() );
$validator->default = "foo";
$this->assertEquals( "(match /^[0-9]+\.[a-z]+$/) [foo]", $validator->getResultString() );
}
}
?>
| true |
3a73f2904306ff3e9cfdc65701db25f51e4a8467 | PHP | JonNixonCodes/TravelBees | /index.php | UTF-8 | 2,845 | 2.546875 | 3 | [] | no_license | <!DOCTYPE html>
<?php
include("session.php");
include('connect.php');
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['inputUsername'];
$password = $_POST['inputPassword'];
$registered = false;
//execute query
$sqlQuery = "SELECT * FROM user WHERE Username = '" . $username . "';";
$result = $conn->query($sqlQuery);
if (!$result) {
echo "Error executing query";
exit();
}
if ($result->num_rows == 1) {
$row = $result->fetch_assoc();
} else if ($result->num_rows > 1) {
echo "Too many rows";
exit();
} else if ($result->num_rows == 0) {
echo "No rows found: Invalid username";
exit();
}
//check password
if ($password == $row['Password']) {
$registered = true;
$admin = $row['Admin'];
} else {
echo "Wrong password";
exit();
}
$password = null; //clear password
//add to session data
$_SESSION['username'] = $username;
$_SESSION['admin'] = $admin;
$_SESSION['registered'] = $registered;
//echo $_SESSION['registered'];
//close connection
$conn->close();
}
?>
<html lang="en">
<head>
<meta charset="utf-8"/>
<link rel="icon" href="images/bees.png">
<title>Home | TravelBees</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="style/jumbotron.css">
</head>
<body>
<?php
//echo ($_SERVER["REQUEST_METHOD"] == "POST");
if(isset($registered)) {
//echo isset($registered);
}
?>
<div class="container">
<!--======== Navigation ========-->
<?php include 'header.php'; ?>
<!--======== Masthead ========-->
<!-- **Possibly add a carousel instead later**-->
<div class="row">
<div class="jumbotron">
<div class="container">
<h1>TravelBees</h1>
<p>This is a template for a simple marketing or informational website. It includes a large callout called a jumbotron and three supporting pieces of content. Use it as a starting point to create something more unique.</p>
<p><a class="btn btn-primary btn-lg" href="#" role="button">Learn more »</a></p>
</div>
</div>
</div>
<!--======== Search form ========-->
<div class="row">
<div class="col-sm-6 col-sm-offset-3">
<form>
<div class="form-group search-form">
<div class="input-group">
<input type="text" class="form-control" id="itemQuery" placeholder="Search">
<div class="input-group-btn">
<button class="btn btn-default" type="submit">
<i class="glyphicon glyphicon-search"></i>
</button>
</div>
</div>
</div>
</form>
</div><!--/col-sm-4 col-sm-offset-4-->
</div><!--/row-->
</div><!--/container-->
<!--include JS scripts-->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html> | true |
5d40ac720cb25a2bc144bb8cb149114385184b85 | PHP | kinglozzer/silverstripe-cacheinclude | /src/Configs/YamlConfig.php | UTF-8 | 1,003 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
namespace Heyday\CacheInclude\Configs;
use Doctrine\Common\Cache\CacheProvider;
use Symfony\Component\Yaml\Yaml;
/**
* Class YamlConfig
* @package Heyday\CacheInclude\Configs
*/
class YamlConfig extends ArrayConfig
{
/**
* @param $yaml
* @param CacheProvider $cache
*/
public function __construct($yaml, CacheProvider $cache = null)
{
if ($cache instanceof CacheProvider) {
if (strpos($yaml, "\n") === false && is_file($yaml)) {
$yaml = file_get_contents($yaml);
}
$key = md5($yaml);
if ($cache->contains($key)) {
$result = $cache->fetch($key);
} else {
$result = Yaml::parse($yaml);
$cache->save($key, $result);
}
} else {
$result = Yaml::parse($yaml);
}
if (!isset($result)) {
$result = array();
}
parent::__construct($result);
}
}
| true |
bd7f68295f0eb8094dc08dcd493f6464fed44826 | PHP | EdgarEmmanuel/Banque_Peuple_SamaneMVC | /src/model/AgencesRepository.php | UTF-8 | 750 | 2.6875 | 3 | [] | no_license | <?php
namespace src\model;
use libs\system\Model;
class AgencesRepository extends Model{
public function __construct(){
parent::__construct();
}
public function getAgenceById($id){
if($this->db != null){
$data = $this->db->getRepository("Agences")->find($id);
}
if($data!=null){
return $data;
}else{
return null;
}
}
public function getOneAgenceById($id){
if($this->db != null){
$data = $this->db->getRepository("Agences")->find($id);
}
// foreach($data as $d){
// $id = $d->getId();
// }
// var_dump($data);
// die;
return $data;
}
}
?> | true |
6b7082d1bd91c9e49aa9509b83bfd229307af2dd | PHP | Jovalga/Web-Judicatura | /EvaluarEscrito.php | UTF-8 | 8,756 | 3.0625 | 3 | [
"MIT"
] | permissive | <?php
// Iniciamos las variables de sesión
if(session_status()==PHP_SESSION_NONE){
session_start();
}
// Activamos que se muestren los errores
error_reporting(E_ALL);
ini_set('display_errors', '1');
// Declaramos que necesitamos el archivo db.php para acceso a base de datos
// Necesitamos también el archivo Corregir.php
require "db.php";
?>
<script type="text/javascript">
// Declaramos las siguientes líneas para que se llame
// a la función aplicarPorcentaje nada más cargar la
// página, de este modo el textarea aparecerá con el
// texto del artículo ya codificado con el porcentaje
// indicado al llamar a la función aplicarPorcentaje.
window.onload = function(){
aplicarPorcentaje(100);
};
// Función que dado un string se reemplaza la letra en el indice
// index por la letra indicada en replace
function replaceAt(string, index, replace){
return string.substring(0, index) + replace + string.substring(index + 1);
}
/////////////////////////////////////////////////////////////////////
function aplicarPorcentaje(porcentaje){
// Si el porcentaje que han puesto está vacío avisamos al respecto
if(porcentaje.length == 0)
alert("El valor del porcentaje está vacío. Por favor, ponga un valor válido entre 0 y 100.");
else{
var texto = document.getElementById('ContenidoArticulo').value;
var longitud = texto.length;
// Vamos a obtener un valor entre 0 y 100 para
// luego comparar con el porcentaje dado y así
// saber si hay que borrar una palabra o no
var azar = Math.floor(Math.random() * 101);
if(porcentaje > azar -1)
var borrar = true;
else
var borrar = false;
// Recorremos todos los caracteres del texto
for(var i=0 ; i<longitud; i++){
// Comprobamos que el caracter a reemplazar
// no sea un punto, ni una coma, ni un salto de línea
if(texto.charAt(i) != ',' &&
texto.charAt(i) != '.' &&
texto.charAt(i) != '\n' ){
// Si el caracter a reemplazar es un espacio en blanco se respeta.
// En el caso de encontrarnos con un espacio en blanco
// volvemos a lanzar el azar para ver si vamos a borrar
// a partir de este espacio en blanco hasta el siguiente
if(texto.charAt(i) == ' '){
azar = Math.floor(Math.random() * 101);
if(porcentaje > azar -1)
borrar = true;
else
borrar = false;
}
else{
// Solo se borra si el variable borrar == true
if(borrar)
texto = replaceAt(texto, i, '_');
}
}
}
document.getElementById('TextoBruto').innerHTML = texto;
}
}
/////////////////////////////////////////////////////////////////////
function corregir(){
// Guardamos los textos (el original y el escrito por el alumno)
// en sus respectivas variables
var textoOriginal = document.getElementById('ContenidoArticulo').value;
var textoAlumno = document.getElementById('TextoBruto').textContent;
// Guardamos las palabras del texto original y
// las palabras del texto escrito por el alumno
var palabrasOriginal = textoOriginal.split(' ');
var palabrasAlumno = textoAlumno.split(' ');
// Primero comprobamos que estén escritas todas las palabras
// Si no, mostramos el nº de palabras que sobran/faltan
if (palabrasAlumno.length != palabrasOriginal.length){
if(palabrasAlumno.length < palabrasOriginal.length){
var falta = palabrasOriginal.length - palabrasAlumno.length;
alert("Te faltan " + falta + " palabras por escribir.");
}
else{
var sobra = palabrasAlumno.length - palabrasOriginal.length;
alert("Te sobran " + sobra + " palabras");
}
}
// Una vez comprobado que los textos tienen las mismas palabras
// pasamos a comprobar si las palabras coinciden, si no es
// así, mandamos la palabra incorrecta al método highlight,
// el cual se encarga de pintarla en rojo para indicar que
// es incorrecta.
else{
textoFinal = new Array(); // Declaramos el array que contendrá
// el textoFinal que irá al textarea
for (i=0 ; i < palabrasOriginal.length; i++){
// Si hay error ponemas la palabra en rojo
if (palabrasAlumno[i] != palabrasOriginal[i]){
palabraNueva = "<span class='highlightError'>" + palabrasAlumno[i] + '</span>';
textoFinal.push(palabraNueva);
}
// Si las palabras son iguales simplemente añadimos
// la palabra correcta.
else{
palabraNueva = "<span class='highlightAcierto'>" + palabrasAlumno[i] + '</span>';
textoFinal.push(palabraNueva);
}
}
// Tras acabar el bucle mandamos mostrar el textoAlumno
// con aquellas palabras que han sido marcadas con highlight
document.getElementById('TextoBruto').innerHTML = textoFinal.join(" ");
}
}
</script>
<?php
echo <<< HTML
<main id="Contenido">
HTML;
// Nos conectamos a la base de datos y le pedimos un
// artículo aleatorio de todos los que hay
$db = DB_conectar();
if($db != 'error'){
$articulo = DB_getArticuloAleatorio($db);
if ($articulo != 'error'){
// Si no ha habido errores mostramos el título del artículo
// que el alumno deberá completar
echo "<h3>".htmlentities($articulo['Titulo'], ENT_QUOTES)."</h3>";
// Guardamos los valores del artículo
// de una forma más cómoda
$titulo = $articulo['Titulo'];
$contenido = $articulo['Contenido'];
$tema = $articulo['Tema'];
$materia = $articulo['Materia'];
// Mostramos seguidamente el área de texto donde el alumno
// deberá escribir el artículo.
// Vamos a crear el div editable donde
// el alumno escribirá el artículo.
// Vamos a llamar al método aplicarPorcentaje, que lo
// que hace es borrar palabras con un porcentaje dado,
// al comienzo será del 100, pero el alumno lo puede
// cambiar siempre que quiera
// Hay un textarea inicial con id=ContenidoArticulo y
// display none; que contiene el contenido original
// del artículo para poder cambiar el
// del alumno en todo momento mediante Javascript
echo <<< HTML
<div class="CuadroTexto">
<textarea id='ContenidoArticulo'
name='ContenidoArticulo'
style='display: none;'>
HTML;
echo "".$articulo['Contenido']."</textarea>";
echo <<< HTML
<label>Escriba el artículo:<br>
<div contenteditable="true"
id='TextoBruto'
name='TextoBruto'
></div>
</label>
<div class='BotonesCuadroTexto'>
<input type='submit' name='EvaluarCorregir' value='Corregir'
onclick="corregir()">Porcentaje de vaciado:<br>
<input type='number' id='Porcentaje' name='Porcentaje' value='100'
min='0' max ='100' onchange="aplicarPorcentaje(document.getElementById('Porcentaje').value)">
HTML;
// Código para que aparezca un botón aplicar
//<input type='button' name='BotonAplicarPorcentaje' value='Aplicar'
// onclick="aplicarPorcentaje(document.getElementById('Porcentaje').value)">
echo <<< HTML
</div>
</div>
HTML;
}
}
// Damos la opción de mostrar otro artículo si el alumno desea
// resolver otro distinto del que ha aparecido
echo <<< HTML
<div class="BotonAtras">
<form action="index.php?p=EvaluarEscrito" method="post">
<input type='submit' name='CambiarArticulo' value='Cambiar Artículo'>
</form>
</div>
HTML;
// Finalmente mostramos el botón para volver a
// la lista de artículos completa
echo <<< HTML
<div class="BotonAtras">
<form action="index.php?p=Evaluar" method="post">
<input type='submit' name='VolverEvaluarEscrito' value='Salir'>
</form>
</div>
HTML;
echo <<< HTML
</main>
HTML;
?> | true |
de22106058465a69d8e58445848c1dc30c2eed65 | PHP | Korbeil/dhl-express-php-api | /generated/Model/SupermodelIoLogisticsExpressRatesProductsItemItemsItemBreakdownItemPriceBreakdownItem.php | UTF-8 | 3,600 | 2.8125 | 3 | [
"MIT"
] | permissive | <?php
namespace Korbeil\DHLExpress\Api\Model;
class SupermodelIoLogisticsExpressRatesProductsItemItemsItemBreakdownItemPriceBreakdownItem
{
/**
* @var array
*/
protected $initialized = [];
public function isInitialized($property): bool
{
return \array_key_exists($property, $this->initialized);
}
/**
* Discount or tax type codes as provided by DHL.<BR> Example values;<BR> For discount;<BR> P: promotional<BR> S: special.
*
* @var string|null
*/
protected $priceType;
/**
* If a breakdown is provided, details can either be; - "TAX",<BR> - "DISCOUNT".
*
* @var string|null
*/
protected $typeCode;
/**
* The actual amount of the discount/tax.
*
* @var float|null
*/
protected $price;
/**
* Percentage of the discount/tax.
*
* @var float|null
*/
protected $rate;
/**
* The base amount of the service charge.
*
* @var float|null
*/
protected $basePrice;
/**
* Discount or tax type codes as provided by DHL.<BR> Example values;<BR> For discount;<BR> P: promotional<BR> S: special.
*/
public function getPriceType(): ?string
{
return $this->priceType;
}
/**
* Discount or tax type codes as provided by DHL.<BR> Example values;<BR> For discount;<BR> P: promotional<BR> S: special.
*/
public function setPriceType(?string $priceType): self
{
$this->initialized['priceType'] = true;
$this->priceType = $priceType;
return $this;
}
/**
* If a breakdown is provided, details can either be; - "TAX",<BR> - "DISCOUNT".
*/
public function getTypeCode(): ?string
{
return $this->typeCode;
}
/**
* If a breakdown is provided, details can either be; - "TAX",<BR> - "DISCOUNT".
*/
public function setTypeCode(?string $typeCode): self
{
$this->initialized['typeCode'] = true;
$this->typeCode = $typeCode;
return $this;
}
/**
* The actual amount of the discount/tax.
*/
public function getPrice(): ?float
{
return $this->price;
}
/**
* The actual amount of the discount/tax.
*/
public function setPrice(?float $price): self
{
$this->initialized['price'] = true;
$this->price = $price;
return $this;
}
/**
* Percentage of the discount/tax.
*/
public function getRate(): ?float
{
return $this->rate;
}
/**
* Percentage of the discount/tax.
*/
public function setRate(?float $rate): self
{
$this->initialized['rate'] = true;
$this->rate = $rate;
return $this;
}
/**
* The base amount of the service charge.
*/
public function getBasePrice(): ?float
{
return $this->basePrice;
}
/**
* The base amount of the service charge.
*/
public function setBasePrice(?float $basePrice): self
{
$this->initialized['basePrice'] = true;
$this->basePrice = $basePrice;
return $this;
}
}
| true |
8b64366205fcede47c3d1b7a496e0218a21a2bb6 | PHP | ellenli32/ica | /app/lib/jointsources.php | UTF-8 | 19,369 | 2.625 | 3 | [
"MIT"
] | permissive | <?php
namespace ICA\JointSources;
require_once(__DIR__ . "/shared.php");
require_once(__DIR__ . "/contents.php");
require_once(__DIR__ . "/sources.php");
/**
* Abstract for joint source.
*/
class JointSource {
public $meta = [];
}
/**
* Returns a list of JointSource instances created according to the result from a database query from `jointsources`.
*/
function createJointSourcesFromQueryResult($result) {
if ($result->num_rows == 0) return [];
$data = [];
// Iterate through joint sources
while ($row = $result->fetch_assoc()) {
$jointSourceId = $row["jointsource_id"];
if (empty($data[$jointSourceId])) {
$jointSource = new JointSource;
// Populating metadata from the database
$jointSource->meta["title"] = getJointSourceMetaTitleOfLatestRevision($row["title_id"]);
$jointSource->meta["intro"] = getJointSourceMetaIntroOfLatestRevision($row["intro_id"]);
$jointSource->meta["themes"] = getJointSourceMetaThemesOfLatestRevision($jointSourceId);
$jointSource->meta["participants"] = getJointSourceMetaParticipantsOfLatestRevision($jointSourceId);
$jointSource->meta["region"] = getJointSourceMetaRegionOfLatestRevision($jointSourceId);
// Run all sources joint by joint source
$jointSource->sources = \ICA\Sources\getSources($jointSourceId);
$data[$jointSourceId] = $jointSource;
}
}
return $data;
}
/**
* Returns a list of JointSource instances which title contains the query text.
*/
function getJointSourcesByMetaTitle($q, $limit = 200) {
$stateEncoded = STATE_PUBLISHED_ENCODED;
$result = query("SELECT jointsource.*
FROM jointsources_summary AS jointsource
INNER JOIN contents_langs_summary AS lang
ON lang.content_id = jointsource.title_id AND
lang.state = {$stateEncoded} AND
lang.content LIKE '%{$q}%'
WHERE jointsource.state = {$stateEncoded}
LIMIT {$limit};");
return createJointSourcesFromQueryResult($result);
}
/**
* Returns a list of most recent JointSource instances.
*/
function getJointSources($limit = 200) {
$stateEncoded = STATE_PUBLISHED_ENCODED;
$result = query("SELECT *
FROM jointsources_summary
WHERE state = {$stateEncoded}
LIMIT {$limit};");
return createJointSourcesFromQueryResult($result);
}
/**
* Inserts a new joint source record into the database.
*/
function insertJointSource($jointSource, $state = STATE_PUBLISHED) {
global $DATABASE;
$accountId = \Session\getAccountId();
retainDatabaseTransaction();
// Request content versioning unit id
$titleId = \ICA\Contents\requestContentId();
$introId = \ICA\Contents\requestContentId();
// Create a new joint source
$result = query("INSERT INTO jointsources
(`author_id`, `title_id`, `intro_id`)
VALUES ({$accountId}, {$titleId}, {$introId});");
$jointSourceId = $DATABASE->insert_id;
$stateId = insertJointSourceState($jointSourceId, $state);
if (!empty($jointSource->meta["title"])) partialPutJointSourceMetaTitle($titleId, $jointSource->meta["title"]);
if (!empty($jointSource->meta["intro"])) partialPutJointSourceMetaIntro($introId, $jointSource->meta["intro"]);
if (!empty($jointSource->meta["themes"])) partialPutJointSourceMetaThemes($jointSourceId, $jointSource->meta["themes"]);
if (!empty($jointSource->meta["participants"])) partialPutJointSourceMetaParticipants($jointSourceId, $jointSource->meta["participants"]);
if (!empty($jointSource->meta["region"])) partialPutJointSourceMetaRegion($jointSourceId, $jointSource->meta["region"]);
releaseDatabaseTransaction();
return $jointSourceId;
}
/**
* Inserts a new state for the specified joint source.
*/
function insertJointSourceState($jointSourceId, $state = STATE_PUBLISHED) {
global $DATABASE;
$accountId = \Session\getAccountId();
$stateEncoded = encodeState($state);
$result = query("INSERT INTO jointsources_states
(`jointsource_id`, `author_id`, `state`)
VALUES ($jointSourceId, $accountId, $stateEncoded);");
$stateId = $DATABASE->insert_id;
return $stateId;
}
/**
* Partially puts the meta for the specified joint source.
*/
function partialPutJointSourceMeta($jointSourceId, $meta) {
$result = query("SELECT *
FROM jointsources
WHERE id = {$jointSourceId};");
if ($result->num_rows == 0) {
return false; // Joint source not found
}
$row = $result->fetch_assoc();
retainDatabaseTransaction();
if (!empty($meta["title"])) partialPutJointSourceMetaTitle($row["title_id"], $meta["title"]);
if (!empty($meta["intro"])) partialPutJointSourceMetaIntro($row["intro_id"], $meta["intro"]);
if (!empty($meta["themes"])) partialPutJointSourceMetaThemes($jointSourceId, $meta["themes"]);
if (!empty($meta["participants"])) partialPutJointSourceMetaParticipants($jointSourceId, $meta["participants"]);
if (!empty($meta["region"])) partialPutJointSourceMetaRegion($jointSourceId, $meta["region"]);
releaseDatabaseTransaction();
}
/**
* Puts the meta for the specified joint source.
*/
function putJointSourceMeta($jointSourceId, $meta) {
$result = query("SELECT *
FROM jointsources
WHERE id = {$jointSourceId};");
if ($result->num_rows == 0) {
return false; // Joint source not found
}
$row = $result->fetch_assoc();
retainDatabaseTransaction();
if (!empty($meta["title"])) putJointSourceMetaTitle($row["title_id"], $meta["title"]);
if (!empty($meta["intro"])) putJointSourceMetaIntro($row["intro_id"], $meta["intro"]);
if (!empty($meta["themes"])) putJointSourceMetaThemes($jointSourceId, $meta["themes"]);
if (!empty($meta["participants"])) putJointSourceMetaParticipants($jointSourceId, $meta["participants"]);
if (!empty($meta["region"])) putJointSourceMetaRegion($jointSourceId, $meta["region"]);
releaseDatabaseTransaction();
}
/**
* Joint source meta title
*/
/**
* Returns the latest revision of the title.
*/
function getJointSourceMetaTitleOfLatestRevision($titleId) {
return \ICA\Contents\getContentLanguagesOfLatestRevision($titleId);
}
/**
* Partially puts a new meta title with the content id of the title.
*/
function partialPutJointSourceMetaTitle($titleId, $metaTitle) {
\ICA\Contents\partialPutContentLanguages($titleId, $metaTitle);
}
/**
* Puts a new meta title with the content id of the title.
*/
function putJointSourceMetaTitle($titleId, $metaTitle) {
\ICA\Contents\putContentLanguages($titleId, $metaTitle);
}
/**
* Joint source meta introduction
*/
/**
* Returns the latest revision of the introduction.
*/
function getJointSourceMetaIntroOfLatestRevision($introId) {
return \ICA\Contents\getContentLanguagesOfLatestRevision($introId);
}
/**
* Partially puts a new meta introduction with the content id of the text.
*/
function partialPutJointSourceMetaIntro($introId, $metaIntro) {
\ICA\Contents\partialPutContentLanguages($introId, $metaIntro);
}
/**
* Puts a new meta introduction with the content id of the text.
*/
function putJointSourceMetaIntro($titleId, $metaTitle) {
\ICA\Contents\putContentLanguages($titleId, $metaTitle);
}
/**
* Joint source meta theme delegations
*/
/**
* Returns the latest revision of the cluster of themes.
*/
function getJointSourceMetaThemesOfLatestRevision($jointSourceId) {
$stateEncoded = STATE_PUBLISHED_ENCODED;
$result = query("SELECT *
FROM jointsources_themes_summary
WHERE jointsource_id = {$jointSourceId}
AND state = {$stateEncoded};");
$themes = [];
while ($row = $result->fetch_assoc()) {
$lang = decodeLang($row["lang"]);
if (!array_key_exists($lang, $themes)) {
$themes[$lang] = [];
}
array_push($themes[$lang], $row["theme"]);
}
return $themes;
}
/**
* Partially puts the cluster of themes for the joint source.
*/
function partialPutJointSourceMetaThemes($jointSourceId, $metaThemes, $state = STATE_PUBLISHED) {
global $DATABASE;
$accountId = \Session\getAccountId();
retainDatabaseTransaction();
$stateEncoded = encodeState($state);
foreach ($metaThemes as $lang => $content) {
$langEncoded = encodeLang($lang);
foreach ($content as $theme) {
$themeEncoded = $DATABASE->real_escape_string($theme);
// Get theme id
$result = query("SELECT id
FROM themes
WHERE theme = '{$themeEncoded}'
LIMIT 1;");
if ($result->num_rows == 0) {
query("INSERT INTO themes
(`theme`, `author_id`)
VALUES ('{$themeEncoded}', {$accountId});");
$themeId = $DATABASE->insert_id;
} else {
$row = $result->fetch_assoc();
$themeId = $row["id"];
}
// Get joint source-theme delegate
$result = query("SELECT *
FROM jointsources_themes_summary
WHERE jointsource_id = {$jointSourceId}
AND lang = {$langEncoded}
AND theme_id = {$themeId}
LIMIT 1;");
if ($result->num_rows == 0) {
query("INSERT INTO jointsources_themes
(`jointsource_id`, `theme_id`, `lang`, `author_id`)
VALUES ({$jointSourceId}, {$themeId}, {$langEncoded}, {$accountId})");
$delegId = $DATABASE->insert_id;
} else {
$row = $result->fetch_assoc();
if (decodeState($row["state"]) == $state) {
// Skip the current theme if already up to date
continue;
}
$delegId = $row["deleg_id"];
}
// Update delegate status
insertJointSourceMetaThemeState($delegId, $state);
}
}
releaseDatabaseTransaction();
}
/**
* Inserts a new state for the theme.
*/
function insertJointSourceMetaThemeState($delegId, $state = STATE_PUBLISHED) {
global $DATABASE;
$accountId = \Session\getAccountId();
$stateEncoded = encodeState($state);
$result = query("INSERT INTO jointsources_themes_states
(`deleg_id`, `state`, `author_id`)
VALUES ({$delegId}, {$stateEncoded}, {$accountId});");
$stateId = $DATABASE->insert_id;
return $stateId;
}
/**
* Puts the cluster of themes for the joint source.
*/
function putJointSourceMetaThemes($jointSourceId, $metaThemes) {
retainDatabaseTransaction();
// Add new languages to the database
partialPutJointSourceMetaThemes($jointSourceId, $metaThemes);
// Unpublish languages no longer listed in the content put
$result = query("SELECT *
FROM jointsources_themes_summary
WHERE jointsource_id = {$jointSourceId};");
while ($row = $result->fetch_assoc()) {
$lang = decodeLang($row["lang"]);
if (!array_key_exists($lang, $metaThemes)
|| !in_array($row["theme"], $metaThemes[$lang])) {
$delegId = $row["deleg_id"];
insertJointSourceMetaThemeState($delegId, STATE_UNPUBLISHED);
}
}
releaseDatabaseTransaction();
}
/**
* Joint source meta participant delegations
*/
/**
* Returns the latest revision of the cluster of participants.
*/
function getJointSourceMetaParticipantsOfLatestRevision($jointSourceId) {
$stateEncoded = STATE_PUBLISHED_ENCODED;
$result = query("SELECT *
FROM jointsources_participants_summary
WHERE jointsource_id = {$jointSourceId}
AND state = {$stateEncoded};");
$participants = [];
while ($row = $result->fetch_assoc()) {
$lang = decodeLang($row["lang"]);
if (!array_key_exists($lang, $participants)) {
$participants[$lang] = [];
}
array_push($participants[$lang], $row["participant"]);
}
return $participants;
}
/**
* Partially puts the cluster of participants for the joint source.
*/
function partialPutJointSourceMetaParticipants($jointSourceId, $metaParticipants, $state = STATE_PUBLISHED) {
global $DATABASE;
$accountId = \Session\getAccountId();
retainDatabaseTransaction();
$stateEncoded = encodeState($state);
foreach ($metaParticipants as $lang => $content) {
$langEncoded = encodeLang($lang);
foreach ($content as $participant) {
$participantEncoded = $DATABASE->real_escape_string($participant);
// Get participant id
$result = query("SELECT id
FROM participants
WHERE participant = '{$participantEncoded}'
LIMIT 1;");
if ($result->num_rows == 0) {
query("INSERT INTO participants
(`participant`, `author_id`)
VALUES ('{$participantEncoded}', {$accountId});");
$participantId = $DATABASE->insert_id;
} else {
$row = $result->fetch_assoc();
$participantId = $row["id"];
}
// Get joint source-participant delegate
$result = query("SELECT *
FROM jointsources_participants_summary
WHERE jointsource_id = {$jointSourceId}
AND lang = {$langEncoded}
AND participant_id = {$participantId}
LIMIT 1;");
if ($result->num_rows == 0) {
query("INSERT INTO jointsources_participants
(`jointsource_id`, `participant_id`, `lang`, `author_id`)
VALUES ({$jointSourceId}, {$participantId}, {$langEncoded}, {$accountId})");
$delegId = $DATABASE->insert_id;
} else {
$row = $result->fetch_assoc();
if (decodeState($row["state"]) == $state) {
// Skip the current participant if already up to date
continue;
}
$delegId = $row["deleg_id"];
}
// Update delegate status
insertJointSourceMetaParticipantState($delegId, $state);
}
}
releaseDatabaseTransaction();
}
/**
* Inserts a new state for the participant.
*/
function insertJointSourceMetaParticipantState($delegId, $state = STATE_PUBLISHED) {
global $DATABASE;
$accountId = \Session\getAccountId();
$stateEncoded = encodeState($state);
$result = query("INSERT INTO jointsources_participants_states
(`deleg_id`, `state`, `author_id`)
VALUES ({$delegId}, {$stateEncoded}, {$accountId});");
$stateId = $DATABASE->insert_id;
return $stateId;
}
/**
* Puts the cluster of participants for the joint source.
*/
function putJointSourceMetaParticipants($jointSourceId, $metaParticipants) {
retainDatabaseTransaction();
// Add new languages to the database
partialPutJointSourceMetaParticipants($jointSourceId, $metaParticipants);
// Unpublish languages no longer listed in the content put
$result = query("SELECT *
FROM jointsources_participants_summary
WHERE jointsource_id = {$jointSourceId};");
while ($row = $result->fetch_assoc()) {
$lang = decodeLang($row["lang"]);
if (!array_key_exists($lang, $metaParticipants)
|| !in_array($row["participant"], $metaParticipants[$lang])) {
$delegId = $row["deleg_id"];
insertJointSourceMetaParticipantState($delegId, STATE_UNPUBLISHED);
}
}
releaseDatabaseTransaction();
}
/**
* Joint source meta region
*/
/**
* Returns the latest revision of the language-specific regions.
*/
function getJointSourceMetaRegionOfLatestRevision($jointSourceId) {
$stateEncoded = STATE_PUBLISHED_ENCODED;
$result = query("SELECT *
FROM jointsources_regions_langs_summary
WHERE jointsource_id = {$jointSourceId}
AND state = {$stateEncoded};");
$region = [];
while ($row = $result->fetch_assoc()) {
$lang = decodeLang($row["lang"]);
$region[$lang] = $row["region"];
}
return $region;
}
/**
* Partially puts the language-specific regions for the joint source.
*/
function partialPutJointSourceMetaRegion($jointSourceId, $metaRegion, $state = STATE_PUBLISHED) {
global $DATABASE;
$accountId = \Session\getAccountId();
retainDatabaseTransaction();
$stateEncoded = encodeState($state);
foreach ($metaRegion as $lang => $region) {
$langEncoded = encodeLang($lang);
$regionEncoded = $DATABASE->real_escape_string($region);
// Get region id
$result = query("SELECT id
FROM regions
WHERE region = '{$regionEncoded}'
LIMIT 1;");
if ($result->num_rows == 0) {
query("INSERT INTO regions
(`region`, `author_id`)
VALUES ('{$regionEncoded}', {$accountId})");
$regionId = $DATABASE->insert_id;
} else {
$row = $result->fetch_assoc();
$regionId = $row["id"];
}
// Get joint source-region language
$result = query("SELECT *
FROM jointsources_regions_langs_summary
WHERE jointsource_id = {$jointSourceId}
AND lang = {$langEncoded}
AND region_id = {$regionId}
LIMIT 1;");
if ($result->num_rows == 0) {
query("INSERT INTO jointsources_regions_langs
(`jointsource_id`, `lang`, `author_id`)
VALUES ({$jointSourceId}, {$langEncoded}, {$accountId});");
$langId = $DATABASE->insert_id;
// Set initial state
insertJointSourceMetaRegionLanguageState($langId, $state);
} else {
$row = $result->fetch_assoc();
$langId = $row["lang_id"];
if (decodeState($row["state"]) != $state) {
// Update existing state
insertJointSourceMetaRegionLanguageState($langId, $state);
}
if ($region == $row["region"]) {
continue;
}
}
// Add new revision
query("INSERT INTO jointsources_regions_langs_revs
(`lang_id`, `author_id`, `region_id`)
VALUES ({$langId}, {$accountId}, {$regionId});");
}
releaseDatabaseTransaction();
}
/**
* Inserts a new state for the language-specific region.
*/
function insertJointSourceMetaRegionLanguageState($langId, $state = STATE_PUBLISHED) {
global $DATABASE;
$accountId = \Session\getAccountId();
$stateEncoded = encodeState($state);
$result = query("INSERT INTO jointsources_regions_langs_states
(`lang_id`, `state`, `author_id`)
VALUES ({$langId}, {$stateEncoded}, {$accountId});");
$stateId = $DATABASE->insert_id;
return $stateId;
}
/**
* Puts the language-specific region for the joint source.
*/
function putJointSourceMetaRegion($jointSourceId, $metaRegion) {
retainDatabaseTransaction();
// Add new languages to the database
partialPutJointSourceMetaRegion($jointSourceId, $metaRegion);
// Unpublish languages no longer listed in the content put
$result = query("SELECT *
FROM jointsources_regions_langs_summary
WHERE jointsource_id = {$jointSourceId};");
while ($row = $result->fetch_assoc()) {
$lang = decodeLang($row["lang"]);
if (!array_key_exists($lang, $metaRegion)) {
insertJointSourceMetaRegionLanguageState($row["lang_id"], STATE_UNPUBLISHED);
}
}
releaseDatabaseTransaction();
}
?> | true |
ade9eb012e9edbecf52ed426be41cfde26d1e8f3 | PHP | Codentia/Cloudeware-PHP-Wrapper | /app/cloudeware.config.php | UTF-8 | 1,334 | 2.578125 | 3 | [
"MIT"
] | permissive | <?php
/* cloudeware.config.php
*
* Configuration related functionality.
*
* Copyright Mattched IT 2012 onwards.
* * 18/05/2012 - MC: Created file.
*/
class CloudewareConfig
{
const cloudeware_core_version = 1.0;
public $cloudeware_parts_url;
public $cloudeware_api_wsdl;
public $cloudeware_api_url;
public $cloudeware_parts_key = "8F1BEFCD-5272-4C23-A1AD-4FC2F5846CAB";
public $cloudeware_api_key = "xxx";
public function __construct()
{
$this->cloudeware_parts_url = self::GetPartsUrl();
$this->cloudeware_api_wsdl = self::GetAPIUrl(true);
$this->cloudeware_api_url = self::GetAPIUrl(false);
}
private function GetPartsUrl()
{
$partsUrl = "";
switch(gethostname())
{
case "MIDEV01":
$partsUrl = "localhost:52530";
break;
}
return $partsUrl;
}
private function GetAPIUrl($isWSDL)
{
$apiUrl = "";
switch(gethostname())
{
case "MIDEV01":
$apiUrl = "localhost/api.mattchedit.com/CMS/v111/Service.asmx";
break;
}
if($isWSDL)
{
$apiUrl .= "?wsdl";
}
return $apiUrl;
}
}
?>
| true |
ed120472077fcb95af459541f712f4de426f482d | PHP | syedomair/ct-api-bk | /src/SyedOmair/Bundle/AppBundle/Services/ProductService.php | UTF-8 | 2,714 | 2.578125 | 3 | [] | no_license | <?php
namespace SyedOmair\Bundle\AppBundle\Services;
use SyedOmair\Bundle\AppBundle\Entity\Product;
use SyedOmair\Bundle\AppBundle\Exception\ProductServiceException;
class ProductService extends BaseService
{
public function __construct($entityManager, $errorService)
{
parent::__construct($entityManager, $errorService);
}
public function getAProduct($id)
{
if(!is_numeric($id) )
$this->errorService->throwException((new ProductServiceException())->getProductsInvalidParameterId());
$product = $this->entityManager->getRepository('AppBundle:Product')->findOneById($id);
$dataArray = array('product' => $this->responseArray($product));
return $this->successResponse($dataArray);
}
public function getProductsForCategory($category_id, $page, $limit, $orderby, $sort)
{
$products = $this->entityManager->getRepository('AppBundle:Product')->findProductsForCategory($category_id, $page, $limit, $orderby, $sort);
$productsCount = $this->entityManager->getRepository('AppBundle:Product')->findProductsForCategoryCount($category_id);
$rtnProducts = array();
$i=0;
foreach($products as $key=>$product)
{
$rtnProducts[$i] = $this-> responseArray($product);
$i++;
}
return $this->successResponseList($rtnProducts, $productsCount['product_count'], $page, $limit);
}
public function create($parameters, $category_id)
{
$category = $this->entityManager->getRepository('AppBundle:Category')->findOneById($category_id);
$product = new Product();
$product->setName($parameters['name']);
$product->setSku($parameters['sku']);
$product->setPrice($parameters['price']);
$product->setShortDescription($parameters['short_desc']);
$product->setImage($parameters['image']);
$product->setCategory($category);
$this->entityManager->persist($product);
$this->entityManager->flush();
$dataArray = array('product_id' => $product->getId());
return $this->successResponse($dataArray);
}
private function responseArray($product)
{
$responseArray = array(
'id' => $product->getId(),
'catalog_name' => $product->getCategory()->getCatalog()->getName(),
'category_name' => $product->getCategory()->getName(),
'name' => $product->getName(),
'sku' => $product->getSku(),
'price' => $product->getPrice(),
'short_desc' => $product->getShortDescription(),
'image' => $product->getImage(),
);
return $responseArray;
}
}
| true |
7e8eac27ea61834135a55cf83e846d1a29c4f38a | PHP | shakti2520/Employee-management | /index.php | UTF-8 | 3,301 | 2.703125 | 3 | [] | no_license | <?php
$servername = "localhost";
$username = "USER_NAME";
$password = "PASSWORD";
$dbname = "convergesol";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>ConvergeSol</title>
<style>
table{
margin-top: 10px;
border:1px solid black;
}
table, tr, td{
padding:6px 10px;
border-left: 1px solid black;
border-right: 1px solid black;
border-collapse: collapse;
font-size: 16px;
}
table thead tr{
background-color: lightgrey;
font-family: sans-serif;
padding:
}
</style>
</head>
<body>
<section id="emploee-details">
<h1>List os Applications</h1>
<button onclick="location.href = 'AddEmployee.html';" id="addNew">
Add New
</button>
<table>
<thead>
<tr>
<td>Name</td>
<td>Email ID</td>
<td>Mobile</td>
<td>Gender</td>
<td>Post</td>
<td>Action</td>
</tr>
</thead>
<tbody>
<?php
$sql = "SELECT name, email, mobile, gender, post FROM employees";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr>
<td>".$row["name"]."
</td><td>" .$row["email"]."
</td><td>". $row["mobile"]."
</td> <td>".$row["gender"]."
</td><td>".$row["post"]."</td>";
$email= $row["email"] ;
?>
<td>
<button class="edit" onclick="location.href = 'updateEmployee.php?name=<?php echo $email ?>'">Edit</button>
<a href="deleteEmployee.php?email=<?php echo $row["email"] ?>" class="delete"><button class="delete" name="<?php echo $row["email"] ?>">
Delete
</button></a>
</td>
</tr>
<?php
}
} else {
echo "NO entries";
}
?>
</tbody>
</table>
</section>
<!-- <div class="model">
<h4>Are you sure?</h4>
<br>
<button>YES</button>
<button>NO</button>
</div> -->
<?php
$conn->close();
?>
</body>
</html> | true |
6727c2bae1a3fede46440581a2dc80cd5378315f | PHP | Danack/intahwebz-routing | /src/Intahwebz/Routing/Route.php | UTF-8 | 11,968 | 2.796875 | 3 | [
"MIT"
] | permissive | <?php
namespace Intahwebz\Routing;
use Intahwebz\Request;
use Intahwebz\Exception\UnsupportedOperationException;
class Route implements \Intahwebz\Route {
use \Intahwebz\SafeAccess;
private $name; // "pictures"
private $pattern; // "/pictures/{page}/{debugVar}",
private $regex; // "#^/pictures/(?\d+)(?:/(?[^/]+))?$#s",
private $staticPrefix; // "/pictures",
private $methodRequirement = null;
private $defaults = array();
private $optionalInfo = array();
private $fnCheck = array();
private $extra = array();
/**
* @var $variables RouteVariable[]
*/
public $variables = array();
/** @var callable */
public $callable;
private $requirements = array();
public function getDefaults() {
return $this->defaults;
}
/**
* @return callable
*/
public function getCallable() {
return $this->callable;
}
function getName() {
return $this->name;
}
/**
* Makes a route out of an array of config data.
*
* @param $routeInfo
*/
public function __construct($routeInfo) {
$this->name = $routeInfo['name'];
$this->pattern = $routeInfo['pattern'];
foreach ($routeInfo as $key => $value) {
switch($key) {
case ('requirements'): {
$this->requirements = $value;
if(is_array($value)) {
if(array_key_exists('_method', $value)) {
$this->methodRequirement = $value['_method'];
}
}
break;
}
case ('_method'): {
$this->methodRequirement = $value;
break;
}
case ('defaults'): {
$this->defaults = $value;
break;
}
case ('fnCheck'): {
$this->fnCheck = $routeInfo['fnCheck'];
break;
}
case('name'):
case('pattern'):{
break;
}
case('optional'): {
$this->optionalInfo = $routeInfo['optional'];
break;
}
default:{
$this->extra[$key] = $value;
break;
}
}
}
$this->calculateStaticPrefix();
//For paths other than the route path '/' allow the last '/' to be optional
//If the string terminates there.
if(mb_strlen($this->staticPrefix) > 1) {
if(mb_substr($this->staticPrefix, mb_strlen($this->staticPrefix)-1) == '/'){
$this->staticPrefix = mb_substr($this->staticPrefix, 0, mb_strlen($this->staticPrefix)-1);
}
if(mb_substr($this->pattern, mb_strlen($this->pattern)-1) == '/'){
$this->pattern = mb_substr($this->pattern, 0, mb_strlen($this->pattern)-1);
}
}
$this->buildRegex();
}
function get($key) {
if (array_key_exists($key, $this->extra) == true) {
return $this->extra[$key];
}
return null;
}
function calculateStaticPrefix() {
$firstBracketPosition = mb_strpos($this->pattern, '{');
if($firstBracketPosition === false){
//No variables
$this->staticPrefix = $this->pattern;
}
else{
$this->staticPrefix = mb_substr($this->pattern, 0, $firstBracketPosition);
}
}
function buildRegex() {
$matches = array();
// We need the position of the matches to allow us to rebuild the pattern string
// as the regex string
preg_match_all('#\{(\w+)\}#', $this->pattern, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
$currentPosition = 0;
$this->regex = '';
$matchCount = 0;
foreach ($matches as $match) {
$matchCount++;
$variableNameWithWrapping = $match[0][0]; // '/{page}'
$variableNameWithWrappingPosition = $match[0][1]; // '/{page}'
$variableName = $match[1][0]; //'page'
//$variableNamePosition = $match[1][1];
if($currentPosition < $variableNameWithWrappingPosition){
$nextPart = mb_substr($this->pattern, $currentPosition, $variableNameWithWrappingPosition - $currentPosition);
$this->regex .= $nextPart;
}
$optional = false;
if (array_key_exists($variableName, $this->optionalInfo) == true) {
$optional = $this->optionalInfo[$variableName];
}
$default = null;
if(array_key_exists($variableName, $this->defaults) == true){
$default = $this->defaults[$variableName];
}
$requirement = null;
if(array_key_exists($variableName, $this->requirements) == true){
$requirement = $this->requirements[$variableName];
}
$routerVariable = new RouteVariable(
$variableName,
$variableNameWithWrapping,
$default,
$requirement,
$optional
);
// if ($optional == true ||
// array_key_exists($variableName, $this->defaults) == true) {
// }
// else {
// $lastRequiredVarPosition = strlen($this->regex);
// }
$varRegex = $routerVariable->getRegex();
//TODO - I am really not sure if this is a good idea - it appears far too magic.
//It would be less magic to only have the variables which are explicitly marked as
//optional to be, er, optional, so excluding the ones that have defaults.
$lastPos = strlen($this->regex) - 1;
$lastSlash = strrpos($this->regex, '/');
if ($lastSlash == $lastPos) {
$varRegex = $routerVariable->getRegex('/');
$this->regex = substr($this->regex, 0, -1);
}
$this->regex .= $varRegex;
$this->variables[] = $routerVariable;
$currentPosition = $variableNameWithWrappingPosition + mb_strlen($variableNameWithWrapping);
}
$this->regex .= mb_substr($this->pattern, $currentPosition);
//let there be an optional last slash
$this->regex .= '(/)?';
$REGEX_DELIMITER = '#';
$this->regex = $REGEX_DELIMITER.'^'.$this->regex.'$'.$REGEX_DELIMITER;
}
/**
* Test that a request meets the path and other requirements for a route.
* Returns true if the route wash matched.
*
* @param Request $request
* @return array|bool
*/
function matchRequest(Request $request) {
$requestPath = $request->getPath();
if (mb_strpos($requestPath, $this->staticPrefix) !== 0) {
return false;
}
if ($this->methodRequirement != null){
if(mb_strcasecmp($this->methodRequirement, $request->getMethod()) != 0){
return false;
}
}
$result = preg_match($this->regex, $requestPath, $matches);
if ($result == false) {
return false;
}
foreach ($this->fnCheck as $fnCheck) {
$result = $fnCheck($request);
if (!$result) {
return false;
}
}
//Route has matched
$params = array();
foreach($this->variables as $routeVariable){
if(array_key_exists($routeVariable->name, $matches) == true &&
strlen($matches[$routeVariable->name]) != 0) {
$params[$routeVariable->name] = $matches[$routeVariable->name];
}
else if($routeVariable->default != null){
$params[$routeVariable->name] = $routeVariable->default;
}
}
return $params;
}
function getDefaultParams() {
return $this->defaults;
}
private function getRequiredPathComponents($params) {
$notBracketMatch = "\{\w+\}";
$notParenthesis = "\(.*\)\?";
$anythingElse = "[\w\d_\/\\\\]+";
preg_match_all("#(($notBracketMatch)|($notParenthesis)|($anythingElse))#", $this->pattern, $matches, PREG_OFFSET_CAPTURE|PREG_PATTERN_ORDER);
$parts = $matches[0];
$requiredString = false;
$requiredOffset = false;
foreach ($parts as $part) {
$string = $part[0];
$offset = $part[1];
$firstChar = mb_substr($string, 0, 1);
$required = false;
switch($firstChar){
case('{'):{
$pattern = str_replace(array('{', '}'), '', $string);
if (array_key_exists($pattern, $params) == true) {
$required = true;
}
break;
}
case('('):{
break;
}
default:{
$required = true;
}
}
if ($required == true) {
$requiredString = $string;
$requiredOffset = $offset;
}
}
$actualRequired = false;
if ($requiredOffset != false) {
$actualRequired = $requiredOffset + mb_strlen($requiredString);
}
return $actualRequired;
}
/**
* Generate a URL for a route with the given parameters. Throws an exception if the route can't be generated
* e.g. due to missing parameters
*
* @param \Intahwebz\Domain $domain
* @param $parameters
* @param bool $absolute
* @throws \Intahwebz\Exception\UnsupportedOperationException
* @return mixed|string
*/
public function generateURL($parameters, \Intahwebz\Domain $domain = null, $absolute = false) {
$search = array();
$replace = array();
//TODO - this doens't pickup provided non-default parameters.
$patternToGenerate = $this->pattern;
$actualRequired = $this->getRequiredPathComponents($parameters);
if ($actualRequired !== false) {
$patternToGenerate = mb_substr($patternToGenerate, 0, $actualRequired);
}
foreach($this->variables as $routeVariable) {
$variableName = $routeVariable->name;
if(array_key_exists($variableName, $parameters) == true){
$search[] = '{'.$variableName.'}';
$replace[] = $parameters[$variableName];
unset($parameters[$variableName]);
}
else if($routeVariable->default !== null) {
$search[] = '{'.$variableName.'}';
$replace[] = $routeVariable->default;
}
else if ($routeVariable->optional !== null) {
$search[] = '{'.$variableName.'}';
$replace[] = '';
}
else{
throw new UnsupportedOperationException("Cannot generate route '".$this->name."'. Parameter '".$routeVariable->name."' is not set and has no default.");
}
}
$search[] = '//';
$replace[] = '/';
$url = str_replace($search, $replace, $patternToGenerate);
if ($url === '') {
$url = '/';
}
// add a query string if needed
if(count($parameters) > 0){
$query = http_build_query($parameters);
$url .= '?'.$query;
}
if($absolute == true){
//TODO Global function - eww.
$url = $domain->getURLForCurrentDomain($url);
}
return $url;
}
}
| true |
e3deabc6a3f38b31c40c13b1bdf87f0870d8c43e | PHP | odracci/EventbriteBundle | /Eventbrite/AbstractMapper.php | UTF-8 | 863 | 2.6875 | 3 | [] | no_license | <?php
namespace SFBCN\EventbriteBundle\Eventbrite;
/**
* The abstract entity mapper
*
* @author Christian Soronellas <theunic@gmail.com>
*/
abstract class AbstractMapper implements MapperInterface
{
/**
* @var \SFBCN\EventbriteBundle\Eventbrite\Mapper
*/
private $mapper;
/**
* @param \SFBCN\EventbriteBundle\Eventbrite\Mapper $mapper
*/
public function setMapper(\SFBCN\EventbriteBundle\Eventbrite\Mapper $mapper)
{
$this->mapper = $mapper;
}
/**
* @return \SFBCN\EventbriteBundle\Eventbrite\Mapper
*/
public function getMapper()
{
return $this->mapper;
}
/**
* Class constructor. Sets the mapper manager.
*
* @param Mapper $mapper
*/
public function __construct(\SFBCN\EventbriteBundle\Eventbrite\Mapper $mapper)
{
$this->setMapper($mapper);
}
}
| true |
54b0cbc2352a8eac02958f14124c50e803833d36 | PHP | heckme/photo-blog | /backend/src/app/Services/Photo/ThumbnailsGeneratorService.php | UTF-8 | 1,528 | 2.6875 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Services\Photo;
use App\Services\Photo\Contracts\ThumbnailsGeneratorService as ThumbnailsGeneratorServiceContract;
use Illuminate\Contracts\Filesystem\Factory as Storage;
use Lib\ThumbnailsGenerator\Contracts\ThumbnailsGenerator;
/**
* Class ThumbnailsGeneratorService.
*
* @package App\Services\Photo
*/
class ThumbnailsGeneratorService implements ThumbnailsGeneratorServiceContract
{
/**
* @var Storage
*/
private $storage;
/**
* @var ThumbnailsGenerator
*/
private $thumbnailsGenerator;
/**
* ThumbnailsGeneratorService constructor.
*
* @param Storage $storage
* @param ThumbnailsGenerator $thumbnailsGenerator
*/
public function __construct(Storage $storage, ThumbnailsGenerator $thumbnailsGenerator)
{
$this->storage = $storage;
$this->thumbnailsGenerator = $thumbnailsGenerator;
}
/**
* @inheritdoc
*/
public function generate(string $filePath): array
{
$thumbnails = $this->thumbnailsGenerator->generateThumbnails(
$this->storage->getDriver()->getAdapter()->getPathPrefix() . $filePath
);
foreach ($thumbnails as $thumbnail) {
$thumbnailPath = dirname($filePath) . '/' . basename($thumbnail['path']);
$data[] = [
'path' => $thumbnailPath,
'width' => $thumbnail['width'],
'height' => $thumbnail['height'],
];
}
return $data ?? [];
}
}
| true |
dcb4e57f82057a1ecc7e5e80b0879fe5ef94f9c7 | PHP | fundacion-ciudad-del-saber/ivvy-sdk-php | /tests/Model/InvoiceTest.php | UTF-8 | 4,015 | 2.6875 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types=1);
namespace Fcds\IvvyTest\Model;
use Fcds\IvvyTest\BaseTestCase;
use Fcds\Ivvy\Model\Address;
use Fcds\Ivvy\Model\Invoice;
use Fcds\Ivvy\Model\InvoiceItem;
/**
* Class: InvoiceTest
*
* @see BaseTestCase
* @final
* @covers Fcds\Ivvy\Model\Invoice
*/
class InvoiceTest extends BaseTestCase
{
public function testInstantiateWithArguments()
{
$address = new Address;
$items = [new InvoiceItem];
$invoice = new Invoice([
'id' => 100,
'reference' => 'foo',
'title' => 'bar',
'description' => 'baz',
'totalCost' => '100.00',
'totalTaxCost' => '7.01',
'amountPaid' => '89.02',
'toContactEmail' => 'john@mail.com',
'toContactName' => 'john',
'currentStatus' => 2,
'createdDate' => '2017-02-22',
'modifiedDate' => '2017-02-22',
'refType' => 3,
'refId' => 'grault',
'taxRateUsed' => 'garply',
'isTaxCharged' => true,
'paymentDueDate' => '2017-02-21',
'eventId' => 200,
'venueId' => 300,
'toContactId' => 400,
'toAddress' => $address,
'items' => $items,
]);
$this->assertEquals(100, $invoice->id);
$this->assertEquals('foo', $invoice->reference);
$this->assertEquals('bar', $invoice->title);
$this->assertEquals('baz', $invoice->description);
$this->assertEquals('100.00', $invoice->totalCost);
$this->assertEquals('7.01', $invoice->totalTaxCost);
$this->assertEquals('89.02', $invoice->amountPaid);
$this->assertEquals('john@mail.com', $invoice->toContactEmail);
$this->assertEquals('john', $invoice->toContactName);
$this->assertEquals(2, $invoice->currentStatus);
$this->assertEquals('2017-02-22', $invoice->createdDate);
$this->assertEquals('2017-02-22', $invoice->modifiedDate);
$this->assertEquals(3, $invoice->refType);
$this->assertEquals('grault', $invoice->refId);
$this->assertEquals('garply', $invoice->taxRateUsed);
$this->assertEquals(true, $invoice->isTaxCharged);
$this->assertEquals('2017-02-21', $invoice->paymentDueDate);
$this->assertEquals(200, $invoice->eventId);
$this->assertEquals(300, $invoice->venueId);
$this->assertEquals(400, $invoice->toContactId);
$this->assertEquals($address, $invoice->toAddress);
$this->assertEquals($items, $invoice->items);
}
public function testInstantiateWithDefaultValues()
{
$invoice = new Invoice;
$this->assertEquals(0, $invoice->id);
$this->assertEquals(null, $invoice->reference);
$this->assertEquals(null, $invoice->title);
$this->assertEquals(null, $invoice->description);
$this->assertEquals(null, $invoice->totalCost);
$this->assertEquals(null, $invoice->totalTaxCost);
$this->assertEquals(null, $invoice->amountPaid);
$this->assertEquals(null, $invoice->toContactEmail);
$this->assertEquals(null, $invoice->toContactName);
$this->assertEquals(0, $invoice->currentStatus);
$this->assertEquals(null, $invoice->createdDate);
$this->assertEquals(null, $invoice->modifiedDate);
$this->assertEquals(null, $invoice->refType);
$this->assertEquals(0, $invoice->refId);
$this->assertEquals(null, $invoice->taxRateUsed);
$this->assertEquals(null, $invoice->isTaxCharged);
$this->assertEquals(null, $invoice->paymentDueDate);
$this->assertEquals(null, $invoice->eventId);
$this->assertEquals(null, $invoice->venueId);
$this->assertEquals(null, $invoice->toContactId);
$this->assertEquals(null, $invoice->toAddress);
$this->assertEquals(null, $invoice->items);
}
}
| true |
d022f67c64795987001643a9218a19763c5df950 | PHP | aakritikishore/factory | /PropertyFetcherDOA.php | UTF-8 | 398 | 2.875 | 3 | [] | no_license | <?php
require_once("PropertyFetcherInterface.php");
require_once("ThirdPartyCustomers/HomeAway.php");
require_once("ThirdPartyCustomers/CondoWorld.php");
class PropertyFetcherDOA {
public function getPropertyFetcher($name) {
switch ($name) {
case 'HA':
return new HomeAway();
break;
case 'CW':
return new CondoWorld();
break;
}
}
}
?>
| true |
97e371195790519c1a85511daca7df4e3835e367 | PHP | AloneCoder/NoCaptcha-PHP | /src/NoCaptcha/RequestMethod/SocketGet.php | UTF-8 | 1,915 | 2.84375 | 3 | [
"MIT"
] | permissive | <?php
namespace NoCaptcha\RequestMethod;
use NoCaptcha\RequestMethod;
use NoCaptcha\RequestParameters;
class SocketGet implements RequestMethod
{
const NOCAPTCHA_HOST = 'api-nocaptcha.mail.ru';
const SITE_VERIFY_PATH = '/check';
const BAD_REQUEST = '{"status": "bad request", "code": 0 }';
const BAD_RESPONSE = '{"success": "internal error", "code": 0 }';
/**
* @var Socket
*/
private $socket;
/**
* @param Socket $socket
*/
public function __construct(Socket $socket = null)
{
if (!is_null($socket)) {
$this->socket = $socket;
} else {
$this->socket = new Socket();
}
}
/**
* @param RequestParameters $params
* @return string
*/
public function submit(RequestParameters $params)
{
$errno = 0;
$errstr = '';
if ($this->socket->fsockopen('ssl://' . self::NOCAPTCHA_HOST, 443, $errno, $errstr, 30) !== false) {
$content = $params->toQueryString();
$request = "GET " . self::SITE_VERIFY_PATH . " HTTP/1.1\r\n";
$request .= "Host: " . self::NOCAPTCHA_HOST . "\r\n";
$request .= "Content-Type: application/x-www-form-urlencoded\r\n";
$request .= "Content-length: " . strlen($content) . "\r\n";
$request .= "Connection: close\r\n\r\n";
$request .= $content . "\r\n\r\n";
$this->socket->fwrite($request);
$response = '';
while (!$this->socket->feof()) {
$response .= $this->socket->fgets(4096);
}
$this->socket->fclose();
if (0 === strpos($response, 'HTTP/1.1 200 OK')) {
$parts = preg_split("#\n\s*\n#Uis", $response);
return $parts[1];
}
return self::BAD_RESPONSE;
}
return self::BAD_REQUEST;
}
} | true |
02c37a97b490137d554bce92e533bfebc46769d4 | PHP | Skandy1/WAD-Lab | /Program-2/index.php | UTF-8 | 463 | 2.921875 | 3 | [] | no_license | <!DOCTYPE html>
<html>
<head>
<title>Cookie</title>
</head>
<body>
<?php
$cookie_name="skanda";
$cookie_value="NULL";
$t=60*60*24*60+time();
setcookie($cookie_name,date("G:i-m/d/y"),$t);
if (!isset($_COOKIE[$cookie_name])) {
?>
<h1>Cookie Name: <?php echo $cookie_name; ?> is not set! </h1>
<?php
}else{
?>
<h1>Cookie: <?php echo $cookie_name; ?> is set!</h1><br>
<h2>Value: <?php echo $_COOKIE[$cookie_name] ?> </h2>
<?php
}
?>
</body>
</html> | true |
635aa5da1f11790c0a89466ce51b306ed7395431 | PHP | polrg/webbteknik | /future-stuff/inriktningsval/printcodes.php | UTF-8 | 1,198 | 2.828125 | 3 | [] | no_license | <?php
/*
* Skriv ut koder
*
* @author Lars Gunther <gunther@keryx.se>
*/
error_reporting(E_ALL);
ini_set("display_errors", "on");
// Inloggad?
/**
* Databasanslutning
*/
require_once("dbcx.php");
$dbh = dbcx();
// Borde det finnas en "vad är min kod" funktion? JA - via mejl!
$stmt = $dbh->prepare("SELECT fornamn, efternamn, klass, kod FROM elever ORDER BY klass ASC, efternamn ASC");
$stmt->execute();
$data = "";
while ( $e = $stmt->fetch() ) {
$data .= "<tr><td>{$e['fornamn']}</td><td>{$e['efternamn']}</td>" .
"<td>{$e['klass']}</td><td>{$e['kod']}</td><tr>";
}
// Sidmall
?>
<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="utf-8" />
<title>För utskrift: Personliga koder</title>
<style>
body {
font-family: Calibri, sans-serif;
font-size: 13pt;
}
table, td {
padding: 0.7cm 0.2cm;
border-top: 1px solid silver;
border-bottom: 1px solid silver;
border-collapse: collapse;
}
td:last-of-type {
padding-left: 2cm;
}
</style>
</head>
<body>
<h1>För utskrift: Personliga koder</h1>
<table>
<?php echo $data; ?>
</table>
<p>Fattas det någon? Är det något fel?</p> | true |
1eaffe99836b3511f249f8a7711b9db8a8b14ac0 | PHP | imisiuk/manao_test | /2/4.php | UTF-8 | 284 | 3.921875 | 4 | [] | no_license | <?php
/*
* 4. В массиве А(N) найти количество пар одинаковых соседних элементов.
*/
$n = 5;
$a = [2, 1, 2, 4, 4];
$count = 0;
for ($i = 1; $i < $n; $i++) {
if ($a[$i] == $a[$i - 1]) {
$count++;
}
}
echo $count; | true |
a3c014a7bf4cee7967cac512238dd03f4fd6587c | PHP | WraRapap/Boutique | /system/widgets/admin/data/models/meta.php | UTF-8 | 490 | 2.515625 | 3 | [] | no_license | <?php
class Meta_Model extends WidgetModel{
public function getClassMeta(){
return $this -> widgetMeta -> class_fields;
}
public function getSpecialClassMeta(){
}
public function getItemMeta(){
return $this -> widgetMeta -> item_fields;
}
public function getSearchMeta(){
if(isset($this -> widgetMeta -> search_fields)){
$meta = json_decode($this -> widgetMeta -> search_fields);
return ($meta == "") ? array() : $meta;
}
else{
return array();
}
}
}
?> | true |
4c18ad0f3493ac3f1f43f2c7cade7b4fc1e82b65 | PHP | hardzal/electionApps | /application/db/migrations/20191021074112_roles.php | UTF-8 | 1,086 | 2.640625 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | <?php
class Migration_roles extends CI_Migration
{
public function up()
{
$this->dbforge->add_field(array(
'id' => array(
'type' => 'INT',
'constraint' => 11,
'unsigned' => TRUE,
'auto_increment' => TRUE
),
'role' => array(
'type' => 'VARCHAR',
'constraint' => 255,
'default' => 'mahasiswa',
),
'description' => array(
'type' => 'TEXT'
),
'created_at' => array(
'type' => 'TIMESTAMP'
),
'updated_at' => array(
'type' => 'DATETIME'
)
));
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('roles');
// INSERT `roles` TABLE
$data = array(
array(
'role' => 'admin',
'description' => 'Admin mengatur pemilihan secara keseluruhan',
),
array(
'role' => 'mahasiswa',
'description' => 'Status default mahasiswa',
),
array(
'role' => 'kandidat',
'description' => 'Role kandidat sebagai siapa yang akan dipilih dalam pemilihan',
)
);
$this->db->insert_batch('roles', $data);
}
public function down()
{
$this->dbforge->drop_table('roles');
}
}
| true |
fcd62ab571c5f09f18edd2216e3aeadb0160f0ee | PHP | KudzaisheRanganai/SP | /pages/admin/PHPcode/audit_log.php | UTF-8 | 1,365 | 2.59375 | 3 | [] | no_license |
<?php
include_once("../../sessionCheckPages.php");
//check if all values are set
if (!isset($_POST["Sub_Functionality_ID"]) && !isset($_POST["changes"]) ) {
echo "You are missing a Functionality_ID or changes in your post method";
exit;
}
$Functionality_ID= $_POST["Sub_Functionality_ID"];
$changes=$_POST["changes"];
//db connection
$url = 'mysql://lf7jfljy0s7gycls:qzzxe2oaj0zj8q5a@u0zbt18wwjva9e0v.cbetxkdyhwsb.us-east-1.rds.amazonaws.com:3306/c0t1o13yl3wxe2h3';
$dbparts = parse_url($url);
$hostname = $dbparts['host'];
$username = $dbparts['user'];
$password = $dbparts['pass'];
$database = ltrim($dbparts['path'],'/');
$con = mysqli_connect($hostname, $username, $password, $database);
//Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
else
{
// receive all input values from the form
$DateAudit = date('Y-m-d H:i:s');
$add_query="INSERT INTO AUDIT_LOG (AUDIT_DATE,USER_ID,SUB_FUNCTIONALITY_ID,CHANGES) VALUES('$DateAudit','$userID','$Functionality_ID','$changes')";
$add_result=mysqli_query($con,$add_query);
if($add_result)
{
echo "success";
}
else
{
echo "failure";
}
//Close database connection
mysqli_close($con);
}
?>
| true |
32b0b4e0753e82938e8a28c313272dde0c898e86 | PHP | petemikhaeil/PDOsAndSQLPractice | /linkingPHPtoSQL.php | UTF-8 | 1,320 | 2.71875 | 3 | [] | no_license | <?php
$db = new PDO('mysql:host=127.0.0.1;dbname=families', 'root');
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$query = $db->prepare(
"SELECT `children`. `name`
FROM `children`
INNER JOIN `colors`
ON `children`.`f_color` = `colors`.`id`
WHERE `colors`.`color` = 'red';
");
$query->execute();
$result = $query->fetchAll();
var_dump($result);
echo("<br>");
$query2 = $db->prepare(
"SELECT `children`.`name`
FROM `children`
INNER JOIN `adults`
ON `children`.`id` = `adults`.`child1`
WHERE `adults`.`pet_name` = 'Syd'
GROUP BY `children`.`name`;
");
$query2->execute();
$result2 = $query2->fetchAll();
var_dump($result2);
echo("<br>");
$query3 = $db->prepare(
"SELECT `children`.`name`, `adults`.`pet_name`
FROM `children`
INNER JOIN `adults`
ON `children`.`id` = `adults`.`child1`
WHERE `adults`.`DOB` > '1985-01-01';
");
$query3->execute();
$result3 = $query3->fetchAll();
var_dump($result3);
echo("<br>");
$query4 = $db->prepare(
"SELECT `colors`.`color`
FROM `colors`
INNER JOIN `children`
ON `colors`.`id` = `children`.`f_color`
JOIN `adults`
ON `children`.`id` = `adults`.`child1`
WHERE `adults`.`DOB` >= '1991-01-01'
GROUP BY f_color
ORDER BY COUNT(f_color) DESC LIMIT 1;
");
$query4->execute();
$result4 = $query4->fetchAll();
var_dump($result4);
| true |
86e73541f2227f3b9eee73111f9042eac7e7ab41 | PHP | AStateOfCode/Dadatata | /src/Filter/Jpegoptim/OptimizeOptions.php | UTF-8 | 1,722 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
namespace Asoc\Dadatata\Filter\Jpegoptim;
use Asoc\Dadatata\Filter\Options;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* Class OptimizeOptions
*
* @package Asoc\Dadatata\Filter\Jpegoptim
*/
class OptimizeOptions extends Options
{
const OPTION_QUALITY = 'quality';
const OPTION_THRESHOLD = 'threshold';
const OPTION_ALL = 'all';
const OPTION_STRIP = 'all';
public function getQuality()
{
return $this->options[self::OPTION_QUALITY];
}
public function getThreshold()
{
return $this->options[self::OPTION_THRESHOLD];
}
public function getAll()
{
return $this->options[self::OPTION_ALL];
}
public function getStrip()
{
return $this->options[self::OPTION_STRIP];
}
protected function setDefaultOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(
[
self::OPTION_STRIP => 'all'
]
);
$resolver->setAllowedValues(self::OPTION_ALL, [
'normal',
'progressive'
]);
$resolver->setAllowedValues(self::OPTION_STRIP, [
'all',
'com',
'exif',
'iptc',
'icc'
]);
}
protected function setRequiredOptions(OptionsResolver $resolver)
{
$resolver->setRequired(
[
self::OPTION_QUALITY
]
);
}
protected function setOptionalOptions(OptionsResolver $resolver)
{
$resolver->setDefined(
[
self::OPTION_THRESHOLD,
self::OPTION_ALL,
self::OPTION_STRIP
]
);
}
}
| true |
26438b68d33ed3dc442fb22453bd90b0b9f5e985 | PHP | ibneturabhassan/ZKITS | /req.php | UTF-8 | 1,660 | 2.671875 | 3 | [] | no_license | <?php
include 'conn.php';
$DD = $_POST['Date'];
$MM = $_POST['Month'];
$YY = $_POST['Year'];
$birth = "$YY-$MM-$DD";
$p1 = $_POST['pass'];
$p2 = $_POST['pass2'];
$a = $_POST['firstname'];
$b = $_POST['lastname'];
$c = $_POST['username'];
$d = $_POST['gender'];
$e = $_POST['classsection'];
$f = $_POST['zno'];
$g = $_POST['shouse'];
$h = $_POST['email'];
$i = $_POST['phno'];
$j = $_POST['houseaddress'];
// new start
if ( strlen($a) <= 2) {
echo 'error';
exit;
}
if (!get_magic_quotes_gpc()) {
$c = addslashes($c);
}
$usercheck = $c;
$check = mysqli_query($conn,"SELECT username FROM users WHERE username = '$usercheck'")
or die(mysqli_error());
$check2 = mysqli_num_rows($check);
if ($check2 != 0) {
die('Sorry, the username '.$c.' is already in use.');
}
// this makes sure both passwords entered match
if ($p1 != $p2) {
die('Your passwords did not match. ');
}
// here we encrypt the password and add slashes if needed
$p1 = md5($p1);
if (!get_magic_quotes_gpc()) {
$p1 = addslashes($p1);
$c = addslashes($c);
}
// Create connection
include 'conn.php';
// new end
$sql = "INSERT INTO req (firstname, lastname, username, password, gender, birth, classsection, zno, shouse, email, phno, houseaddress, status)
VALUES ('$a', '$b', '$c', '$p1', '$d', '$birth', '$e', '$f', '$g', '$h', '$i', '$j', 'unseen')";
if (mysqli_query($conn,$sql)) {
echo "Your Request have been sent successfully. Our team will contact you shortly for confirmation of your account. Stay tuned to your e-mail address and phone. Your account will be verified within 4 or 5 days.";
}
mysqli_close($conn);
?> | true |
8a6656e86d12023645dcac464b078c73cde3a370 | PHP | gadixsystem/systeminformation | /src/tests/LegacyTest.php | UTF-8 | 1,333 | 2.609375 | 3 | [
"MIT"
] | permissive | <?php
namespace gadixsystem\systeminformation\tests;
use gadixsystem\systeminformation\CPU;
use gadixsystem\systeminformation\Disk;
use gadixsystem\systeminformation\Memory;
use PHPUnit\Framework\TestCase;
class LegacyTest extends TestCase
{
protected const LEGACY_REPORT_KEYS = [
'free',
'used',
'total',
'freePercentage',
'usedPercentage',
'bufferPercentage',
];
public function testLegacyDiskGetReport()
{
$disk = new Disk();
$diskReport = $disk->getReport();
$this->assertIsArray($diskReport);
foreach (self::LEGACY_REPORT_KEYS as $key) {
$this->assertArrayHasKey($key, $diskReport);
}
}
public function testLegacyCPUGetReport()
{
$cpu = new CPU();
$cpuReport = $cpu->getReport();
$this->assertIsArray($cpuReport);
foreach (self::LEGACY_REPORT_KEYS as $key) {
$this->assertArrayHasKey($key, $cpuReport);
}
}
public function testLegacyMemoryGetReport()
{
$memory = new Memory();
$memoryReport = $memory->getReport();
$this->assertIsArray($memoryReport);
foreach (self::LEGACY_REPORT_KEYS as $key) {
$this->assertArrayHasKey($key, $memoryReport, "$key not found");
}
}
}
| true |
0d760fd32c0e4e52b0ce5fb5529593a9f94f7504 | PHP | M-Belanda/web_php_BD_AUT-2017 | /modeles/Biere.class.php | UTF-8 | 5,088 | 3.03125 | 3 | [] | no_license | <?php
/**
* Class Biere
*
*
* @version 1.0
* @update 2017-08-16
* @license MIT
* @license http://opensource.org/licenses/MIT
*
*/
class Biere {
const NOMBRE_PAR_PAGE =10;
private $_db;
function __construct ()
{
$this->_db = new mysqli("localhost", "root", "", "bieres");//aller chercher la base de donne
}
function __destruct ()
{
}
/*
* @access public
* @return Array
*/
function verifLogin($nom, $motpasse){
$login = false;
$nom = $this->_db->real_escape_string($nom);
$mySQLRes = $this->_db->query("select * from usager where nom='".$nom."'");
if($mySQLRes){
$res = $mySQLRes->fetch_assoc();
}
if(isset($res['nom']) && isset($res['motpasse'])){
$hash = crypt($motpasse, $res['motpasse']);
if($hash == $res['motpasse'])
{
$login = true;
var_dump("entree");
}
//var_dump("motdepasse:".$hash);
//var_dump($res['motpasse']);
}
return $login;
}
public function getDonnees()
{
return $this->_db;
}
/**
* Retourne les produits d'une page
* @access public
* @param
* @return Array
*/
public function getBieres($nPage=1)
{
$res = array();
if(count($this->_db))
{
$nMaxPage =ceil(count($this->_db)/self::NOMBRE_PAR_PAGE);
if($nPage>$nMaxPage)
{
$nPage = $nMaxPage;
}
$mSQLRes = $this->_db->query("select * from bieres");
if($mSQLRes){
$res = $mSQLRes->fetch_all(MYSQLI_ASSOC);
}
$aBiere = array_chunk($res, 10);
if(isset($aBiere[$nPage-1]))
{
$res = $aBiere[$nPage-1];
}
}
return $res;
}
/**
* Retourne les informations d'une bière
* @access public
* @param
* @return Array
*/
public function getBiere($id_biere)
{
$id_biere = $id_biere + 1;
$res = array();
$query = "SELECT * FROM bieres where id =" .$id_biere; //prendre l'informations d'une biere
$result = $this->_db->query($query);
$res = $result->fetch_array(MYSQLI_ASSOC);//https://stackoverflow.com/questions/16525413/fatal-error-cannot-use-object-of-type-mysqli-result
$pieces = explode(",", $res['format']);
$res['format']= array();
$res['format'] = array_merge($res['format'], $pieces); //mettre le format en tableau
//var_dump($res['format']);
return $res;
}
/**
*
* @access public
* @param
* @return Array
*/
public function modifBiere($id_biere,$aBiere)
{
$id_biere = $id_biere+1; //mettre le bon id pour la base de donnee
$res = array();
if(isset($aBiere)){
//var_dump($id_biere);
//var_dump($aBiere['format']);
//$tableau=$aBiere['format'];
//$vide= array();
//$aBiere['format'] = array_merge($vide,$tableau);
$aBiere['format'] = implode(",", $aBiere['format']);//mettre le format en string
$mSQLRes = $this->_db->query("UPDATE bieres set nom = \"". $aBiere['nom'].'", brasserie = "'. $aBiere['brasserie'].'", description = "'. $aBiere['description']
.'",format ="'.$aBiere['format'] .'", public = "'. $aBiere['public'].'", type = "'. $aBiere['type'].'" where id =' .$id_biere);//modifier la bonne biere
}
$id_biere = $id_biere-1; //mettre le bon id pour php
$res = $this->getBiere($id_biere);// chercher la biere
return $res;
}
/**
* Méthode d'ajout de bière
* @access public
* @param Array $aDonnees Contient les données envoyer par le formulaire d'ajout
* @return Array La bière qui a été ajouté
*/
public function ajouterBiere($aBiere)
{
$id = 0;
if(!empty($aBiere['nom']) && !empty($aBiere['brasserie']) && !empty($aBiere['description']) && !empty($aBiere['type']) && isset($aBiere['format']) && isset($aBiere['public']))
{
$aBiere['format'] = implode(',', $aBiere['format']);//mettre le format en string
//var_dump($aBiere['format'] );
//var_dump($aBiere['type'] );
$res = $this->_db->query("INSERT INTO bieres VALUES ('".$id."','". $aBiere['nom']."','". $aBiere['brasserie']."','". $aBiere['description']."','". $aBiere['format']."','". $aBiere['public'] ."','". $aBiere['type'] ."')");
//var_dump("INSERT INTO bieres VALUES ('".$id."','". $aBiere['nom']."','". $aBiere['brasserie']."','". $aBiere['description']."','". $aBiere['type']."','". $aBiere['format'] ."','". $aBiere['public'] ."')");
}
if($this->_db->insert_id != 0){ //incrémenter l'id
$id = $this->_db->insert_id;
}
//var_dump("id:".$id);
return $res;
}
public function effacerBiere($id_biere)
{
$id_biere = $id_biere+1;//mettre le bon id pour base de donnee
$res = $this->_db->query("DELETE FROM bieres WHERE id =" .$id_biere);
//var_dump($id_biere);
return $res;
}
/**
* Retourne les produits d'une page
* @access public
* @param
* @return Array
*/
public function getNombrePages()
{
var_dump($this->_db);
return ceil(count($this->_db)/self::NOMBRE_PAR_PAGE);
//return $aBiere[$nPage-1];
}
}
?> | true |
3b5df96b2b12ba52f70f045ad1e0a760fc81c94f | PHP | huizhang-php/GraduationProject | /application/common/tool/ProcessTool.php | UTF-8 | 1,299 | 2.828125 | 3 | [
"Apache-2.0"
] | permissive | <?php
/**
* User: yuzhao
* CreateTime: 2019/3/20 下午12:13
* Description:
*/
namespace app\common\tool;
class ProcessTool {
/**
* User: yuzhao
* CreateTime: 2019/3/19 下午4:18
* Description: 守护进程模式启动
*/
public static function daemonStart() {
// 守护进程需要pcntl扩展支持
if (!function_exists('pcntl_fork'))
{
exit('Daemonize needs pcntl, the pcntl extension was not found');
}
umask( 0 );
$pid = pcntl_fork();
if( $pid < 0 ){
exit('fork error.');
} else if( $pid > 0 ) {
exit();
}
if( !posix_setsid() ){
exit('setsid error.');
}
$pid = pcntl_fork();
if( $pid < 0 ){
exit('fork error');
} else if( $pid > 0 ) {
// 主进程退出
exit;
}
// 子进程继续,实现daemon化
}
/**
* User: yuzhao
* CreateTime: 2019/3/20 下午1:05
* @param $file
* Description: 不能重复启动
*/
public static function noRepeatStart($file) {
$fhanlde = fopen($file,'r');
$r = flock($fhanlde,LOCK_EX|LOCK_NB);
if(!$r){
die('不能重复启动');
}
}
} | true |
7f03334510e80fdf6d215bf9c4b6ac7cb58a7919 | PHP | callseven/ecommerce | /crud/app/Entity/Vaga.php | UTF-8 | 1,083 | 3.03125 | 3 | [] | no_license | <?php
namespace App\Entity;
use \App\Db\Database;
use \PDO;
class Vaga {
/**
* Identificador unico da vaga
* @var integer
*/
public $id;
/**
*Titulo da vaga
*@var string
*/
public $titulo;
/**
*Descricao da vaga (pode conter html)
*@var string
*/
public $descricao;
/**
*Defini-se a vaga que esta ativa
*@var string(s/n)
*/
public $ativo;
/**
*Data de publicacao da vaga
*@var string
*/
public $data;
/**
*Metodo responsavel por cadastrar a nova vaga
*@return boolean
*/
public function cadastrar()
{
//DEFINIR A DATA
$this->data = date('Y-m-d H:i:s');
//INSERIR A VAGA NO BANCO
$obDatabase = new Database('vagas');
$obDatabase->insert([
'titulo' => $this->titulo,
'descricao' => $this->descricao,
'ativo' => $this->ativo,
'data' => $this->data
]);
//echo "<pre>"; print_r($obDatabase); echo "</pre>"; exit;
//ATRIBUIR O ID DA VAGA NA INSTANCIA
//RETORNAR SUCESSO
}
} | true |
ce041126c2fb71dce00aeb750f4e94119ea6be07 | PHP | SBaof/msgBoard | /cookie/login.php | UTF-8 | 1,096 | 2.515625 | 3 | [] | no_license | <?php
if (isset($_POST['submit']) && !empty($_POST['submit'])) {
setcookie('user', $_POST['user'], time() + 24 * 3600);
header("location: index.php");
if (isset($_COOKIE['user'])) {
var_dump($_COOKIE);
}
}
?>
<html >
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<form action="" method="post" name="form1" enctype="multipart/form-data">
<table width="405" border="1" cellpadding="1" cellspacing="1" bordercolor="#FFFFFF" bgcolor="#999999">
<tr>
<td width="103" height="25" align="right">name: </td>
<td width="144" height="25"><input name="user" type="text" id="user" size="20" maxlength="100"></td>
</tr>
<tr>
<td width="103" height="25" align="right">password: </td>
<td width="144" height="25"><input type="password" name="pwd" id="pwd" size="20" maxlength="100"></td>
</tr>
<tr align="center">
<td height="25" colspan="3"><input type="submit" name="submit" value="signin">
<input type="submit" name="signup" value="signup"></td>
</tr>
</table>
</form>
</body>
</html>
| true |
716820a56c488746b92a5e7e34abca9be54b4536 | PHP | jeka-pc13/rentacar | /application/libraries/Carro.php | UTF-8 | 2,921 | 3.046875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | <?php if ( ! defined('BASEPATH')) exit('No se permite el acceso directo al script');
/**
* Class for carro.
*/
class Carro {
public $id;
public $modelo;
public $fabricante;
public $cor;
public $disponibilidade;
/**
* Gets the value of id.
*
* @return int
*/
public function getId():int{
return $this->id;
}
/**
* Gets the value of modelo.
*
* @return mixed
*/
public function getModelo():string{
return $this->modelo;
}
/**
* Sets the value of modelo.
*
* @param mixed $modelo the modelo
*
* @return self
*/
public function _setModelo(string $modelo):string{
$this->modelo = $modelo;
return $this;
}
/**
* Gets the value of fabricante.
*
* @return mixed
*/
public function getFabricante():string{
return $this->fabricante;
}
/**
* Sets the value of fabricante.
*
* @param mixed $fabricante the fabricante
*
* @return self
*/
public function _setFabricante(string $fabricante):string{
$this->fabricante = $fabricante;
return $this;
}
/**
* Gets the value of cor.
*
* @return mixed
*/
public function getCor():string{
return $this->cor;
}
/**
* Sets the value of cor.
*
* @param mixed $cor the cor
*
* @return self
*/
public function _setCor(string $cor):string{
$this->cor = $cor;
return $this;
}
/**
* Gets the value of disponibilidade.
*
* @return mixed
*/
public function getDisponibilidade():bool{
return $this->disponibilidade;
}
/**
* Sets the value of disponibilidade.
*
* @param mixed $disponibilidade the disponibilidade
*
* @return self
*/
public function toggleDisponibilidade():bool{
$this->disponibilidade = ($this->disponibilidade) ? FALSE : TRUE ;
return $this->disponibilidade;
}
/**
* Gets the value of disponibilidade.
*
* @return mixed
*/
public function imprimeDisponibilidade():string{
return $retVal = ($this->disponibilidade) ? "Disponível" : "Ocupado" ;
}
public function imprimeEditar():string{
return "";
}
public function imprimeMatriculaFormatada(){
$aux[0] = substr($this->matricula, 0,1);
$aux[2] = substr($this->matricula, 2,3);
$aux[3] = substr($this->matricula, 4,5);
return implode("-", $aux);
}
public function retornaMatriculaEmArray(){
$aux[0] = substr($this->matricula, 0,1);
$aux[2] = substr($this->matricula, 2,3);
$aux[3] = substr($this->matricula, 4,5);
return $aux;
}
public function formataMatricula(string $matriculaFormatada):string{
return implode("", $matriculaFormatada);
}
}
| true |
96850ac2335c2fd9f338a38de23ba2002ee9849c | PHP | Rinanopiyana/php-prak-8 | /lat_15.php | UTF-8 | 252 | 3.328125 | 3 | [] | no_license | <!DOCTYPE html>
<html>
<head>
<title>lat_15</title>
</head>
<body>
<?php
$jk;
print("Masukkan kode Jenis Kelamin : ");
if($jk = 1)
{print(" laki-laki ");}
elseif ($jk =2)
{print("perempuan");}
else
{print("Semua perempuan");}
?>
</body>
</html> | true |
f614c52668377d07f01808669c8eca3643e94477 | PHP | loevgaard/linkmobility-php-sdk | /src/ValueObject/Sender.php | UTF-8 | 407 | 2.78125 | 3 | [
"MIT"
] | permissive | <?php declare(strict_types=1);
namespace Loevgaard\Linkmobility\ValueObject;
use Assert\Assert;
class Sender extends StringValueObject
{
public function __construct(string $value)
{
// if the sender is alphanumeric, test the length
if (!preg_match('/^\+[0-9]+$/i', $value)) {
Assert::that($value)->maxLength(11);
}
parent::__construct($value);
}
}
| true |
cc5e0f2a4e95778812bf127d82f7d72f8613761d | PHP | ibrahim-kardi/crm_proj | /Blab/Mvc/Models/Blab_Model.php | UTF-8 | 1,476 | 2.8125 | 3 | [
"MIT"
] | permissive | <?php
namespace Blab\Mvc\Models;
use Blab\Libs\Database;
use Blab\Libs\Configuration;
class Blab_Model
{
protected $_db=null;
private static $_instance=null;
public function __construct(){
$configuration = new Configuration(array(
"type" => "ini"
));
$path = ROOT.DS.'App'.DS.'Config'.DS.'database';
$configuration = $configuration->initialize();
$parsed = $configuration->parse($path);
//print_r($parsed);
$dbType = $parsed->default->database->type;
$hostName = $parsed->default->database->host;
$username = $parsed->default->database->username;
$password = $parsed->default->database->password;
$dbName = $parsed->default->database->dbName;
$port = $parsed->default->database->port;
$engine = $parsed->default->database->engine;
$database = new Database(array(
"type" =>$dbType,
"options" =>array(
"host" =>$hostName,
"username" =>$username,
"password" =>$password,
"dbName" =>$dbName,
"port" =>$port,
"engine"=>$engine
)
));
$this->_db = $database->initialize()->connect();
/*
// Get All Data
$all = $this->_db->query()
->from("users")
->where(array(
"last"=>"Basir"
))
->order("first", "desc")
->limit(100)
->all();
$print = print_r($all, true);
echo "all = >{$print}";
*/
}
public static function getDBInstance(){
if (!isset(self::$_instance)) {
self::$_instance = new BLAB_Model();
return self::$_instance->_db;
}
return false;
}
} | true |
8f7e85635821151e46e0d5799608cb3760d8476e | PHP | nemanjavx/news-portal | /app/Models/User.php | UTF-8 | 2,044 | 2.671875 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use App\Models\UserRole;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
class User extends Authenticatable
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'first_name',
'last_name',
'email',
'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
protected $table = 'users';
private $roles = [
'USER' => 1,
'EDITOR' => 2,
'ADMIN' => 3,
];
public function role()
{
return $this->belongsTo(UserRole::class, 'role');
}
/**
* Create a full user name
*
* @return string
*/
public function fullName()
{
return $this->first_name . ' ' . $this->last_name;
}
/**
* Determine if a user is an editor / has the editor role (2)
*
*/
public function isEditor()
{
return $this->role()->where('id', $this->roles['EDITOR'])->exists();
}
public function updateMainInfo($data)
{
return DB::table($this->table)
->where(['id' => $data['id']])
->update(['first_name' => $data['first_name'], 'last_name' => $data['last_name'], 'updated_at' => Carbon::now()]);
}
public function updateAvatar($data)
{
return DB::table($this->table)
->where(['id' => $data['id']])
->update(['avatar' => $data['avatar'], 'updated_at' => Carbon::now()]);
}
}
| true |
38d5bdb6df2653d4e8ce0056b0015745d8456bbc | PHP | HansPeterOrding/codefights_solutions_arcade_php | /03_Corner_Of_0s_And_1s/02_ArrayPacking.php | UTF-8 | 187 | 2.921875 | 3 | [] | no_license | <?php
function arrayPacking($a) {
$output = "";
foreach($a as $val) {
$output = str_pad(decbin($val), 8, "0", STR_PAD_LEFT) . $output;
}
return bindec($output);
}
| true |
b5260defa8e9749651505891b619c7a8aa42655f | PHP | HochschuleLuzern/EventoImport | /classes/administration/scripts/ResetHiddenAdminPermissions.php | UTF-8 | 3,635 | 2.625 | 3 | [] | no_license | <?php declare(strict_types=1);
namespace EventoImport\administration\scripts;
use ILIAS\DI\RBACServices;
use ILIAS\UI\Factory;
use ILIAS\UI\Component\Modal\Modal;
use EventoImport\import\data_management\repository\HiddenAdminRepository;
use EventoImport\db\HiddenAdminsTableDef;
class ResetHiddenAdminPermissions implements AdminScriptInterface
{
use AdminScriptCommonMethods;
private const FORM_TITLE = 'evento_title';
private const CMD_SET_PERMISSION = 'set_permissions';
private $db;
private $ctrl;
private $tree;
public function __construct(\ilDBInterface $db, \ilCtrl $ctrl, \ilTree $tree)
{
$this->db = $db;
$this->ctrl = $ctrl;
$this->tree = $tree;
}
public function getTitle() : string
{
return "Set the permissions for all Hidden Admin roles including subobjects";
}
public function getScriptId() : string
{
return 'set_hidden_roles_permission_for_subobjs';
}
public function getParameterFormUI() : \ilPropertyFormGUI
{
$this->ctrl->setParameterByClass(\ilEventoImportUIRoutingGUI::class, 'script', $this->getScriptId());
$url = $this->ctrl->getFormActionByClass(\ilEventoImportUIRoutingGUI::class);
$form = new \ilPropertyFormGUI();
$form->setFormAction($url);
$form->addCommandButton(self::CMD_SET_PERMISSION, 'Set Permissions');
return $form;
}
public function getResultModalFromRequest(string $cmd, Factory $f) : Modal
{
$form = $this->getParameterFormUI();
if(!$form->checkInput() || $cmd != self::CMD_SET_PERMISSION) {
throw new \InvalidArgumentException("Invalid Form Input!");
}
$successfull_changes = [];
$errors = [];
$sql = "SELECT * FROM " . HiddenAdminsTableDef::TABLE_NAME;
$result = $this->db->query($sql);
while ($row = $this->db->fetchAssoc($result)) {
try {
$role_id = (int) $row[HiddenAdminsTableDef::COL_HIDDEN_ADMIN_ROLE_ID];
$obj_ref_id = (int) $row[HiddenAdminsTableDef::COL_OBJECT_REF_ID];
if (!\ilObject::_exists($role_id)) {
$errors[] = "Role with role_id $role_id does not exist";
} else if (!\ilObject::_exists($obj_ref_id, true)) {
$errors[] = "Object with ref_id $obj_ref_id does not exist";
} else if (!$this->tree->isInTree($obj_ref_id)) {
$errors[] = "Object with ref_id $obj_ref_id is not in tree";
} else {
$this->resetPermissionsForRole(
$role_id,
$obj_ref_id
);
$successfull_changes[] = "Successfull for role_id = $role_id and ref_id = $obj_ref_id";
}
} catch (\Exception $e) {
$errors[] = "Error for role_id= $role_id: " . $e->getMessage();
}
}
$lists_as_str = 'Error:<br>'.implode('<br>', $errors)
.'<br><hr><br>Successfull:<br>' . implode('<br>', $successfull_changes);
return $f->modal()->lightbox(
$f->modal()->lightboxTextPage(
$lists_as_str,
$this->getTitle()
)
);
}
private function resetPermissionsForRole(int $role_id, int $obj_ref_id)
{
$role_object = new \ilObjRole($role_id, false);
$role_object->changeExistingObjects(
$obj_ref_id,
\ilObjRole::MODE_UNPROTECTED_KEEP_LOCAL_POLICIES,
array('all')
);
}
} | true |
9e4e73f0e649f80bd98a76d290eef3023169f95c | PHP | JLPoulpe/mp | /override/classes/ProductDto.php | UTF-8 | 6,877 | 2.5625 | 3 | [] | no_license | <?php
class ProductDto
{
private $id_market;
private $id_product;
private $price;
private $unity;
private $unit_price_ratio;
private $productName;
private $description_short;
private $description;
private $id_supplier;
private $supplierName;
private $poids;
private $commandeAvantJ;
private $poidsAuChoix;
private $link_rewrite;
private $id_image;
private $catLinkRewrite;
private $attributes = array();
private $maxCaractere = 53;
private $categoryId;
private $ownerProduct;
private $reference;
private $id_tax_rules_group;
private $taxRate;
private $specificPrice;
private $reduction;
private $onSale;
private $produitAilleurs;
private $tax;
private $delayBeforeMarket;
function getDelayBeforeMarket() {
return $this->delayBeforeMarket;
}
function setDelayBeforeMarket($delayBeforeMarket) {
$this->delayBeforeMarket = $delayBeforeMarket;
}
function getTax() {
return $this->tax;
}
function setTax($tax) {
$this->tax = $tax;
}
function getProduitAilleurs() {
return $this->produitAilleurs;
}
function setProduitAilleurs($produitAilleurs) {
$this->produitAilleurs = $produitAilleurs;
}
function getSpecificPrice() {
return $this->specificPrice;
}
function getReduction() {
return $this->reduction;
}
function getOnSale() {
return $this->onSale;
}
function setSpecificPrice($specificPrice) {
$this->specificPrice = $specificPrice;
}
function setReduction($reduction) {
$this->reduction = $reduction;
}
function setOnSale($onSale) {
$this->onSale = $onSale;
}
function getTaxRate() {
return $this->taxRate;
}
function setTaxRate($taxRate) {
$this->taxRate = $taxRate;
}
function getIdTaxRulesGroup() {
return $this->id_tax_rules_group;
}
function setIdTaxRulesGroup($id_tax_rules_group) {
$this->id_tax_rules_group = $id_tax_rules_group;
}
function getReference() {
return strtolower($this->reference);
}
function setReference($reference) {
$this->reference = $reference;
}
function getOwnerProduct() {
return $this->ownerProduct;
}
function setOwnerProduct($ownerProduct) {
$this->ownerProduct = $ownerProduct;
}
function getCategoryId() {
return $this->categoryId;
}
function setCategoryId($categoryId) {
$this->categoryId = $categoryId;
}
function getIdMarket() {
return $this->id_market;
}
function getIdProduct() {
return $this->id_product;
}
function getTTCPrice() {
return $this->price*(1+($this->taxRate/100));
}
function getPrice() {
return $this->price;
}
function getUnity() {
return $this->unity;
}
function getUnitPriceRatio() {
return $this->unit_price_ratio;
}
function getUnitPrice() {
if($this->unit_price_ratio>0) {
return number_format($this->price/$this->unit_price_ratio, 2, ',', ' ');
}
return null;
}
function setListAttribute(array $attribute) {
$this->attributes[$attribute['id_product_attribute']] = $attribute;
}
function getListAttribute() {
return $this->attributes;
}
function getProductName() {
return $this->productName;
}
function getDescriptionShort() {
return $this->description_short;
}
function getDescription() {
return $this->description;
}
function getIdSupplier() {
return $this->id_supplier;
}
function getSupplierName($isName = true) {
if($isName) {
return $this->supplierName;
} else {
return MPTools::rewrite($this->supplierName);
}
}
function getPoids() {
return $this->poids;
}
function getCommandeAvantJ() {
return $this->commandeAvantJ;
}
function getPoidsAuChoix() {
return $this->poidsAuChoix;
}
function getIdImage() {
return $this->id_image;
}
function getListImage($type='home_default') {
$image = new Image();
$listIdImage = $image->getListIdImageForIdProduct($this->id_product);
$listImage = array();
foreach($listIdImage as $idImage) {
$image = new Image($idImage['id_image']);
$path = $image->getImgPath();
if($path) {
$imgPath = '/img/p/' . $image->getImgPath() . '-' . $type . '.jpg';
unset($image);
$listImage[] = $imgPath;
}
}
return $listImage;
}
function getImgPath($type='home_default') {
$image = new Image($this->id_image);
$path = $image->getImgPath();
if($path) {
$imgPath = '/img/p/' . $image->getImgPath() . '-' . $type . '.jpg';
unset($image);
return $imgPath;
}
return null;
}
function getCatLinkRewrite() {
return $this->catLinkRewrite;
}
function setIdMarket($id_market) {
$this->id_market = $id_market;
}
function setIdProduct($id_product) {
$this->id_product = $id_product;
}
function setPrice($price) {
$this->price = $price;
}
function setUnity($unity) {
$this->unity = $unity;
}
function setUnitPriceRatio($unit_price_ratio) {
$this->unit_price_ratio = $unit_price_ratio;
}
function setProductName($productName) {
$this->productName = $productName;
}
function setDescriptionShort($description_short) {
$this->description_short = $description_short;
}
function setDescription($description) {
$this->description = $description;
}
function setIdSupplier($id_supplier) {
$this->id_supplier = $id_supplier;
}
function setSupplierName($supplierName) {
$this->supplierName = str_replace('"', '', $supplierName);
}
function setPoids($poids) {
$this->poids = $poids;
}
function setCommandeAvantJ($commandeAvantJ) {
$this->commandeAvantJ = $commandeAvantJ;
}
function setPoidsAuChoix($poidsAuChoix) {
$this->poidsAuChoix = $poidsAuChoix;
}
function getLinkRewrite() {
return $this->link_rewrite;
}
function setLinkRewrite($link_rewrite) {
$this->link_rewrite = $link_rewrite;
}
function setIdImage($id_image) {
$this->id_image = $id_image;
}
function setCatLinkRewrite($catLinkRewrite) {
$this->catLinkRewrite = $catLinkRewrite;
}
} | true |
3208b6f4ed1ef2ab279feb7b6e621cccd2bd5487 | PHP | LxIllan/what_clothes_i_wore | /UserDAO.php | UTF-8 | 4,596 | 2.859375 | 3 | [
"MIT"
] | permissive | <?php
require_once 'Connection.php';
require_once 'Util.php';
require_once 'User.php';
class UserDAO {
private $_connection;
function __construct() {
$this->_connection = new Connection();
}
public function addUser(User $user) : bool {
return $this->_connection->insert("INSERT INTO user(firstname, lastname, email, password, "
. "photo_location, root, sex_id, verified) "
. "VALUES ('" . $user->getFirstname() . "', '"
. $user->getLastname() . "', '"
. $user->getEmail() . "', '"
. $user->getPassword() . "', '"
. $user->getPhotoLocation() . "', "
. $user->getRoot() . ", "
. $user->getSexID() . ", "
. $user->getVerified() . ")");
}
public function verifyUser(int $userID) : bool {
return $this->_connection->update("UPDATE user SET verified = 1 WHERE user_id = $userID");
}
public function getNextID() : int {
$tuple = $this->_connection->select("SELECT AUTO_INCREMENT FROM "
. "INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'user'")->fetch_array();
return $tuple[0];
}
public function editUser(User $user) : bool {
return $this->_connection->update("UPDATE user SET "
. "firstname = '" . $user->getFirstname() . "', "
. "lastname = '" . $user->getLastname() . "', "
. "email = '" . $user->getEmail() . "', "
. "password = '" . $user->getPassword() . "', "
. "photo_location = '" . $user->getPhotoLocation() . "' "
. "WHERE user_id = " . $user->getUserID());
}
// try this funcion, see if all records are deleted, dress items.
public function deleteUser(int $userID) : bool {
$photoLocation = "img/users/IMG_" . $userID . ".jpg";
if (file_exists($photoLocation)) {
unlink($photoLocation);
}
return $this->_connection->delete("DELETE FROM user WHERE user_id = $userID");
}
public function getUser(int $userID) : ?User {
$tuple = $this->_connection->select("SELECT user_id, firstname, lastname, "
. "email, password, photo_location, root, sex_id, verified "
. "FROM user WHERE user_id = " . $userID)->fetch_array();
if (isset($tuple)) {
return new User($tuple[0], $tuple[1], $tuple[2], $tuple[3], $tuple[4], $tuple[5], $tuple[6], $tuple[7], $tuple[8]);
} else {
return null;
}
}
public function getUserByEmail(string $email) : ?User {
$tuple = $this->_connection->select("SELECT user_id FROM user WHERE email LIKE '$email'")->fetch_array();
if (isset($tuple)) {
return self::getUser($tuple['user_id']);
} else {
return null;
}
}
public function getUsers(bool $verified = true) : array {
$users = [];
$verified = intval($verified);
$result = $this->_connection->select("SELECT user_id FROM user WHERE verified = $verified");
while ($row = $result->fetch_array()) {
$users[] = self::getUser($row['user_id']);
}
$result->free();
return $users;
}
public function getEmailAdmins() : array {
$emails = [];
$result = $this->_connection->select("SELECT user_id FROM user WHERE root = 1");
while ($row = $result->fetch_array()) {
$emails[] = self::getUser($row['user_id'])->getEmail();
}
$result->free();
return $emails;
}
public function validateSession(string $email, string $password) : ?array {
$result = $this->_connection->select("SELECT user_id, firstname, lastname, sex_id, root FROM user "
. "WHERE verified = 1 AND email LIKE '$email' AND email = '$email' "
. "AND password = '$password'");
if ($result->num_rows == 1) {
$row = $result->fetch_array();
$data = [
'id' => $row['user_id'],
'firstname' => $row['firstname'],
'lastname' => $row['lastname'],
'sex' => $row['sex_id'],
'root' => $row['root']
];
}
return isset($data) ? $data : null;
}
public function existsEmail(string $email) : bool {
$tuple = $this->_connection->select("SELECT email "
. "FROM user WHERE email LIKE '" . $email . "'")->fetch_array();
return (isset($tuple) && Util::validateEmail($tuple[0]));
}
} | true |
42e9b401e3aec8d7c1acc58be32418d1c08ec698 | PHP | kotaro-kawashiki/sekigae | /sekigae_result.php | UTF-8 | 2,853 | 2.640625 | 3 | [] | no_license |
<?php
$names = [$_POST['ironman'],$_POST['captain'],$_POST['hulk'],$_POST['blackpanther'],$_POST['drstrange']];
$seats = ["三人席のプロジェクター側","三人席の真ん中","三人席のテーブル側","二人席のメンターさん側","二人席のテーブル側"];
$cnt = count($names);
$uranai = "のあなたは運勢最強!今日一日世界の主役はあなたです。王様のように好き勝手に生き、思いつく限りのわがまま言いましょう";
$uranai1 ="のあなたは運勢最弱。世の中のすべてに懺悔して生きてください";
$uranai2 ="のあなたの運勢はふつう。可もなく不可もないです。特にコメントはありません。";
$uranai3 ="のあなたの運勢はそこそこ良いです。ガリガリ君を3本も買えばあたりが出るであろう程度にはついてるので、前向きにいきましょう。";
$uranai4 ="のあなたの運勢はちょっと悪いです。通勤電車で意地悪な人に肩でガツガツやられるかもしれません。ちょっと筋トレして気合を入れときましょう。";
$uranai_all = [$uranai,$uranai1,$uranai2,$uranai3,$uranai4];
$ar_num = range('0',$cnt-1);
shuffle($ar_num);
for ($i=0;$i<$cnt;$i++) {
$ar_num[$i];
}
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="sekigae_result.css" type="text/css" />
</head>
<body>
<h1>席替え結果!</h1>
<p><div id="result1"><b><?php echo $names[$ar_num[0]];?>さんは<?php echo $seats[$ar_num[0]];?></b></div><br>
<?php echo $seats[$ar_num[0]];?><?php echo $uranai_all[$ar_num[0]];?></p>
<p><div id="result2"><b><?php echo $names[$ar_num[1]];?>さんは<?php echo $seats[$ar_num[1]];?></b></div><br>
<?php echo $seats[$ar_num[1]];?><?php echo $uranai_all[$ar_num[1]];?></p>
<p><div id="result3"><b><?php echo $names[$ar_num[2]];?>さんは<?php echo $seats[$ar_num[2]];?></b></div><br>
<?php echo $seats[$ar_num[2]];?><?php echo $uranai_all[$ar_num[2]];?></p>
<p><div id="result4"><b><?php echo $names[$ar_num[3]];?>さんは<?php echo $seats[$ar_num[3]];?></b></div><br>
<?php echo $seats[$ar_num[3]];?><?php echo $uranai_all[$ar_num[3]];?></p>
<p><div id="result5"><b><?php echo $names[$ar_num[4]];?>さんは<?php echo $seats[$ar_num[4]];?></b></div><br>
<?php echo $seats[$ar_num[4]];?><?php echo $uranai_all[$ar_num[4]];?></p>
</body>
</html> | true |
d21dc7eddd7de70b1ce1d97e285952edf57640bb | PHP | ertprs/es | /application/detregra.php | UTF-8 | 9,459 | 2.625 | 3 | [] | no_license | <?php
include '../core.php';
if(!isset($_GET['hash'])){
header("Location: ../my/inicio");
}
try {
$idCasa = tratarString($_GET['hash'])/3237;
$sql = "SELECT * FROM `casa` WHERE `idCasa` = '$idCasa'";
$casa = $db->query($sql);
$casa = $casa->fetchAll();
if(count($casa) != 1){
header("Location: ../my/inicio");
}
$casa = $casa[0];
//Carrega regras cadastradas
$sql = "SELECT `idRegra`, `mes`, `ano` FROM `regra` WHERE `idCasa` = '$idCasa' ORDER BY `dataCadastro` DESC";
$regras = $db->query($sql);
$regras = $regras->fetchAll();
//Carrega informação da regra selecionada
if(isset($_POST['idRegra'])){
//Se uma regra de outro mes foi selecinada, carrega ela...
$idRegra = tratarString($_POST['idRegra'])/11;
$sql = "SELECT * FROM `regra` WHERE `idRegra` = '$idRegra'";
} else {
//Senão carrega a última regra cadastrada
$sql = "SELECT * FROM `regra` WHERE `idCasa` = '$idCasa' ORDER BY `dataCadastro` DESC LIMIT 1";
}
$regra = $db->query($sql);
$regra = $regra->fetchAll();
if(count($regra) == 0){
$regra = false;
} else {
$regra = $regra[0];
$ano = $regra['ano'];
$mes = $regra['mes'];
$idRegra = $regra['idRegra'];
$qtdSem = countSemanasMes($ano, $mes);
$qtdDias = cal_days_in_month(CAL_GREGORIAN, $mes, $ano);
$frstDay = date("w", strtotime($ano."-".$mes."-1"));
//Carrega os dias da semana trabalhados
$diaSem = $regra['diasSem'];
$diaSemTemp = "";
if($diaSem == ""){
$diaSem = "Nenhum";
} else {
$diaSem = explode("-", $diaSem);
foreach ($diaSem as $dia) {
if($dia != ""){
$diaSemTemp .= retDiaSem($dia). ", ";
}
}
}
if($diaSemTemp == "Segunda, Terça, Quarta, Quinta, Sexta, "){
$diaSemTemp = "Segunda à sexta";
} else if($diaSemTemp == "Segunda, Terça, Quarta, Quinta, Sexta, Sábado, "){
$diaSemTemp = "Segunda à sábado";
} else if($diaSemTemp == "Domingo, Segunda, Terça, Quarta, Quinta, Sexta, Sábado, "){
$diaSemTemp = "Domingo à domingo";
} else if($diaSemTemp == "Terça, Quarta, Quinta, Sexta, Sábado, "){
$diaSemTemp = "Terça à sábado";
} else {
$diaSemTemp = substr($diaSemTemp, 0, -2);
}
//Carrega o horário de atendimento
$hrAt = explode("-",$regra['hrat']);
if(count($hrAt) == 4){
$hrAt = $hrAt[0]." às ".$hrAt[3];
} else {
$hrAt = "Horário desconhecido";
}
//Carrega intervalo entre agendamentos
if($regra['tint'] == 20){
$tInt = "20 em 20 min";
} else if($regra['tint'] == 30){
$tInt = "30 em 30 min";
} else if($regra['tint'] == 60){
$tInt = "60 em 60 min";
} else {
$tInt = "Desconhecido";
}
//Carrega RecallDay
if($regra['dataRecall'] == "" || $regra['dataRecall'] == 0){
$recall = false;
} else {
$recall = true;
}
//Carrega promoções da cancessionária
$sql = "SELECT * FROM `promocao` WHERE `casa` = '$idCasa'";
$promocoes = $db->query($sql);
$promocoes = $promocoes->fetchAll();
if(count($promocoes) == 0){
$promocoes = false;
}
//Carrega produtos da cancessionária
$sql = "SELECT * FROM `produto` WHERE `casa` = '$idCasa'";
$produtos = $db->query($sql);
$produtos = $produtos->fetchAll();
if(count($produtos) == 0){
$produtos = false;
}
/*TRECHO AGENDA.PHP*/
//Carrega agenda da casa
$erro = false;
if(!isset($_POST['data'])){
$data = date("Y-m-d");
} else {
$data = tratarString($_POST['data']);
}
$dataSplit = explode("-", $data);
//Carrega técnicos
$sql = "SELECT `idUser`, `nome`, `sobrenome`, `avatar`, `filas` FROM `user` WHERE `tipo` = 'tecnico' AND `status` = '1' AND `ramal` = '$idCasa'";
$tecs = $db->query($sql);
$tecs = $tecs->fetchAll();
//Carrega bloqueios no periodo selecionado
$dataini = $data." 00:00:00";
$datafim = $data." 23:59:59";
$sql = "SELECT * FROM `bloqueio` WHERE `dataInicio` >= '$dataini' AND `dataInicio` <= '$datafim' ORDER BY `motivo`";
$blocks = $db->query($sql);
$blocks = $blocks->fetchAll();
//Cria array dos bloqueios
$int = $regra['tint'];
$arrayBlocks = array();
$last = "";
foreach ($blocks as $bl) {
//echo $bl['dataInicio'];
$hora = explode(" ", $bl['dataInicio']);
$hora = explode(":", $hora[1]);
$h = (int) $hora[0];
$m = (int) $hora[1];
if($int == 20){
do{
if($m == 0 || $m == 20 || $m == 40){
$loop = false;
} else {
$m++;
if($m == 60){
$m = 0;
$h++;
}
$loop = true;
}
}while($loop);
} else if($int == 30){
do{
if($m == 0 || $m == 30){
$loop = false;
} else {
if($m > 30){
$m++;
} else {
$m--;
}
if($m == 60){
$m = 0;
$h++;
}
$loop = true;
}
}while($loop);
} else {
if($m != 0){
$m = 0;
}
}
if($last == $bl['motivo']){
$motivo .= "-cont";
} else {
$last = $bl['motivo'];
$motivo = $bl['motivo'];
}
$hora = fixHora($h.":".$m);
$index = $hora."-".$bl['idTecnico'];
$arrayBlocks[$index] = array(
'dataini' => $bl['dataInicio'],
'datafim' => $bl['dataFim'],
'motivo' => $bl['motivo'],
'obs' => $bl['obs'],
'idBloc' => $bl['idBloqueio']
);
do{
$loop = true;
if(date("Y-m-d H:i:s", strtotime($arrayBlocks[$index]['datafim'])) > date("Y-m-d H:i:s", strtotime($arrayBlocks[$index]['dataini']." +".$regra['tint']." minutes"))){
$indexOld = $index;
$index = explode("-", $index);
$it = $index[1];
$index = explode(":", $index[0]);
$ih = (int) $index[0];
$im = (int) $index[1] + $regra['tint'];
if($im >= 60){
$ih++;
$im = $im-60;
}
if($ih > 23){
$loop = false;
}
$hora = fixHora($ih.":".$im);
$index = $hora."-".$it;
$dataIniLoop = date("Y-m-d H:i:s", strtotime($arrayBlocks[$indexOld]['dataini']." +".$regra['tint']." minutes"));
if(strpos($bl['motivo'], "cont") === false){
$bl['motivo'] .= "-cont";
}
$arrayBlocks[$index] = array(
'dataini' => $dataIniLoop,
'datafim' => $bl['dataFim'],
'motivo' => $bl['motivo'],
'obs' => $bl['obs'],
'idBloc' => $bl['idBloqueio']
);
} else {
$loop = false;
}
}while($loop);
}
//Seta horário de inicio e fim da agenda com base na regra de negócio ativa
if(!$erro){
$horario = explode('-', $regra['hrat']);
if(count($horario) != 4){
$erro = "horario";
} else {
$hIni = $horario[0];
$hIni = explode(":", $hIni);
$mIni = $hIni[1];
$hIni = $hIni[0];
$hFim = $horario[3];
$hFim = explode(":", $hFim);
$mFim = $hFim[1];
$hFim = $hFim[0];
$tint = $regra['tint'];
if($tint == 20){
$th = $hFim - $hIni;
$th = $th*3;
if($mFim >= 40){
$th = $th+2;
} else if($mFim >= 20){
$th++;
}
} else if($tint == 30){
$th = $hFim - $hIni;
$th = $th*2;
if($mFim >= 30){
$th++;
}
} else if($tint == 60){
$th = $hFim - $hIni;
} else {
$erro = "intervalo";
}
}
}
}
/* Função para cortar o nome do técnico se for muito grande
* para evitar quebra de layout da agenda
*/
function fixName($name){
if(strlen($name) > 20){
return substr($name, 0, 18)."...";
} else {
return $name;
}
}
function segHora($h, $m = false){
if(!$m){
$h = explode(":", $h);
$m = $h[1];
$h = $h[0];
}
$h = (int) $h;
$m = (int) $m;
return (($h*60)*60) + ($m*60);
}
function setBloqueio($jor, $agora){
if(segHora($agora) < segHora($jor['entrada']) || segHora($agora) > segHora($jor['saida'])){
//Fora do horário
return "fora";
} if(segHora($agora) >= segHora($jor['almoco']) && segHora($agora) < segHora($jor['retorno'])){
//Horário de almoco
return 'almoco';
} else {
return "livre";
}
}
function retHoraAgenda($dataini, $datafim = "0000-00-00 00:00:00", $local = false){
if(!$local){
$dataini = explode(" ", $dataini);
$horaini = explode(":", $dataini[1]);
$horaini = $horaini[0]."h".$horaini[1];
$datafim = explode(" ", $datafim);
$horafim = explode(":", $datafim[1]);
$horafim = $horafim[0]."h".$horafim[1];
return "Das ".$horaini." às ".$horafim;
} else if($local == "almoco"){
$horaini = explode(":", $dataini['almoco']);
$horaini = $horaini[0]."h".$horaini[1];
$horafim = explode(":", $dataini['retorno']);
$horafim = $horafim[0]."h".$horafim[1];
return "Das ".$horaini." às ".$horafim;
}
}
include 'util_regra.php';
} catch (\Exception $e) {
echo $e;
}
?>
| true |
d776ff7f63f7cbab4477b83339d339f4623f821a | PHP | robicse11127/ct-user-login-register | /admin/settings.php | UTF-8 | 1,831 | 2.53125 | 3 | [] | no_license | <?php
class Ct_User_Rl_Settings {
public function __construct() {
add_action( 'admin_menu', array( $this, 'ct_user_rl_admin_page' ) );
add_action( 'admin_init', array( $this, 'ct_user_rl_setting_options' ) );
}
public function ct_user_rl_admin_page() {
add_submenu_page( "options-general.php", "User Register/Login", "User Register/Login", "manage_options", "ct-user-rl", array($this, 'ct_user_rl_menu_page') );
}
public function ct_user_rl_menu_page() {
?>
<div class="wrap">
<h2>CT User Register/Login Settings</h2>
<form action="options.php" method="post">
<?php
settings_fields( 'ct_user_rl_settings_section' );
do_settings_sections( 'ct-user-rl' );
submit_button();
?>
</form>
</div>
<?php
}
public function ct_user_rl_setting_options() {
add_settings_section( 'ct_user_rl_settings_section', '', null, 'ct-user-rl' );
add_settings_field( 'ct-user-rl-login-slug', 'Login Page Slug', array( $this, 'ct_user_login_slug' ), 'ct-user-rl', 'ct_user_rl_settings_section' );
add_settings_field( 'ct-user-rl-register-slug', 'Register Page Slug', array( $this, 'ct_user_register_slug' ), 'ct-user-rl', 'ct_user_rl_settings_section' );
register_setting( 'ct_user_rl_settings_section', 'ct-user-rl-login-slug' );
register_setting( 'ct_user_rl_settings_section', 'ct-user-rl-register-slug' );
}
/**
* Settings Fields
*/
public function ct_user_login_slug() {
?>
<input type="text" name="ct-user-rl-login-slug" value="<?php echo esc_attr(get_option('ct-user-rl-login-slug')); ?>">
<?php
}
public function ct_user_register_slug() {
?>
<input type="text" name="ct-user-rl-register-slug" value="<?php echo esc_attr(get_option('ct-user-rl-register-slug')); ?>">
<?php
}
}
new Ct_User_Rl_Settings;
| true |
462b67799ecb10534bd19ef5079763ac2ef29140 | PHP | whatyouhide/university-gamespot | /app/controllers/backend_posts_controller.php | UTF-8 | 3,028 | 2.9375 | 3 | [] | no_license | <?php
/**
* This file contains the definition of the BackendPostsController class.
*/
namespace Controllers;
use Models\Post;
use Models\Tag;
/**
* A controller for managing blog posts in the backend.
*/
class BackendPostsController extends BackendController {
/**
* {@inheritdoc}
*/
protected static $before_filters = array(
'restrict' => 'all',
'set_post' => ['edit', 'toggle_published', 'update', 'destroy'],
'restrict_to_author' => ['edit', 'toggle_published', 'update', 'destroy']
);
/**
* GET /posts
* List all the posts in the website.
*/
public function index() {
$this->posts = Post::all();
}
/**
* GET /posts/nuevo
* Create a new post, save it to the database and redirect to the edit page of
* the new post.
*/
public function nuevo() {
// Create a new post without validating.
$new_post = Post::create(['author_id' => $this->current_user->id], false);
redirect('/backend/posts/edit', [], ['id' => $new_post->id]);
}
/**
* GET /posts/edit?id=1
* Edit a post.
*/
public function edit() {
$this->tags = Tag::all();
}
/**
* POST /posts/update?id=1
* Update a post.
*/
public function update() {
$this->post->update($this->post_params());
if ($this->post->is_valid()) {
$flash = ['notice' => 'Saved Successfully'];
} else {
$flash = ['error' => $this->post->errors_as_string()];
}
redirect('/backend/posts/edit', $flash, ['id' => $this->post->id]);
}
/**
* GET /posts/destroy?id=1
* Destroy a post.
*/
public function destroy() {
$this->post->destroy();
redirect('/backend/posts', ['notice' => 'Successfully destroyed']);
}
/**
* POST /posts/toggle_published?id=1
* Publish an unbpublished post and unpublish a published one.
*/
public function toggle_published() {
$will_be_published = !$this->post->is_published();
$this->post->toggle_published();
redirect(
'/backend/posts/edit',
['notice' => $will_be_published ? 'Published' : 'Unpublished'],
['id' => $this->post->id]
);
}
/**
* <b>Filter</b>
* Restrict the actions of this controller to users which have a specific
* permission.
*/
protected function restrict() {
$this->restrict_to_permission('blog');
}
/**
* <b>Filter</b>
* Ensure the target post belongs to the current user.
*/
protected function restrict_to_author() {
if ($this->post->author_id != $this->current_user->id) {
forbidden();
}
}
/**
* <b>Filter</b>
* Set the `post` instance variable.
*/
protected function set_post() {
$this->post = $this->safe_find_from_id('Post');
}
/**
* Return an array of parameters to pass to Post::update().
* @return array
*/
private function post_params() {
return [
'title' => $this->params['title'],
'excerpt' => $this->params['excerpt'],
'content' => $this->params['content'],
'tags' => $this->params['tags']
];
}
}
?>
| true |
1365b5ed742b31d22b188ac97c2ff1cd96b432df | PHP | pranjal07pandey/rt-dashboard-backend | /app/Repositories/V2/UserRepository.php | UTF-8 | 2,340 | 2.703125 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Repositories\V2;
use App\AppInterface\IRepository;
use App\User;
class UserRepository implements IRepository
{
public function getModel()
{
return new User();
}
public function getDataById($request = null)
{
return $this->getModel()->find($request->id);
}
public function getDataWhere($array = [])
{
return $this->getModel()->where($array);
}
public function insertAndUpdate($request = null)
{
if ($request->has('user_id')) {
$user = $this->getModel()->find($request->user_id);
} else {
$user = $this->getModel();
}
(!$request->has('user_type'))?: $user->user_type = $request->user_type;
(!$request->has('first_name'))?: $user->first_name = $request->first_name;
(!$request->has('last_name'))?: $user->last_name = $request->last_name;
(!$request->has('email'))?: $user->email = $request->email;
(!$request->has('image'))?: $user->image = $request->image;
(!$request->has('password'))?: $user->password = $request->password;
(!$request->has('device_type'))?: $user->device_type = $request->device_type;
(!$request->has('deviceToken'))?: $user->deviceToken = $request->deviceToken;
(!$request->has('hashToken'))?: $user->hashToken = $request->hashToken;
(!$request->has('remember_token'))?: $user->remember_token = $request->remember_token;
(!$request->has('email_verification'))?: $user->email_verification = $request->email_verification;
(!$request->has('isActive'))?: $user->isActive = $request->isActive;
(!$request->has('receive_docket_copy'))?: $user->receive_docket_copy = $request->receive_docket_copy;
$user->save();
return $user;
}
public function deleteDataById($request = null)
{
$user = $this->getModel()->find($request->id);
$user->delete();
return $user;
}
}
| true |
f720b2cc53aca9efcd5c69a95f35966bd0d71134 | PHP | pedrocavt/phpcourse | /arrays/ordenacao.php | UTF-8 | 1,593 | 3.21875 | 3 | [] | no_license | <?php
echo "<h1>Ordenação</h1>";
echo "<h2>Sort</h2>";
$array = [
'banana',
'goiaba',
'morango',
'abacaxi'
];
echo '<pre>';
print_r($array);
echo '</pre>';
sort($array);
echo '<pre>';
print_r($array);
echo '</pre>';
echo "<h2>Asort</h2>";
$array = [
'banana',
'goiaba',
'morango',
'abacaxi'
];
echo '<pre>';
print_r($array);
echo '</pre>';
asort($array);
echo '<pre>';
print_r($array);
echo '</pre>';
echo "<h2>Ksort</h2>";
$array = [
'nome' => 'Pedro',
'email' => 'pedro@',
'altura' => '1.82',
];
echo '<pre>';
print_r($array);
echo '</pre>';
ksort($array);
echo '<pre>';
print_r($array);
echo '</pre>';
echo "<h2>Krsort</h2>";
$array = [
'nome' => 'Pedro',
'email' => 'pedro@',
'altura' => '1.82',
];
echo '<pre>';
print_r($array);
echo '</pre>';
krsort($array);
echo '<pre>';
print_r($array);
echo '</pre>';
echo "<h2>Ursort</h2>";
$array = [
'pessoas' => [
[
'id' => 1,
'nome' => 'Pedro',
'idade' => 25
],
[
'id' => 2,
'nome' => 'Vitor',
'idade' => 24
]
]
];
echo '<pre>';
print_r($array);
echo '</pre>';
usort($array,function($a,$b){
//SÃO IGUAIS
if($a['idade'] == $b['idade']) return 0;
return $a['idade'] < $b['idade'] ? -1 : 1;
});
echo '<pre>';
print_r($array);
echo '</pre>';
echo "<h2>Natsort</h2>";
$array = [
'10.0v',
'1.0v',
'2.0v'
];
echo '<pre>';
print_r($array);
echo '</pre>';
natsort($array);
echo '<pre>';
print_r($array);
echo '</pre>'; | true |
89018adc92dede57bd290b02fd6a03382d9e7bca | PHP | chinakungfu/panda | /publish/compile/tpl_tour_page_content.php | UTF-8 | 1,550 | 2.546875 | 3 | [] | no_license |
<ul>
<?php if (!empty($this->_tpl_vars["listContentPage"]["url"]["prePage"])){?>
<li><a href="/<?php echo $this->_tpl_vars["listContentPage"]["pageInfo"]["prePage"];?>" class="next">< 上一页</a></li>
<?php }else{ ?>
<li><a href="#" class="next" title="已经是第一页了">< 上一页</a></li>
<?php } ?>
<?php if(!empty($this->_tpl_vars["listContentPage"]["url"]["list"])){
foreach ($this->_tpl_vars["listContentPage"]["url"]["list"] as $this->_tpl_vars['key']=>$this->_tpl_vars['var']){ ?>
<?php if ($this->_tpl_vars["listContentPage"]["pageInfo"]["currentPage"] != $this->_tpl_vars["key"]){?>
<li><a href="/<?php echo $this->_tpl_vars["var"];?>"><?php echo $this->_tpl_vars["key"];?></a></li>
<?php }else{ ?>
<li><span><?php echo $this->_tpl_vars["key"];?></span></li>
<?php } ?>
<?php }
} ?>
<?php if (!empty($this->_tpl_vars["listContentPage"]["pageInfo"]["nextPage"])){?>
<li><a href="/<?php echo $this->_tpl_vars["listContentPage"]["pageInfo"]["nextPage"];?>" class="next">下一页 ></a></li>
<?php }else{ ?>
<li><a href="#" class="next" title="已经到最后一页了">下一页 ></a></li>
<?php } ?>
</ul> | true |
710cf8336cc4d16d2d05cb9c2e2c346a4b4ec074 | PHP | guillaume-goubel/dev-bases | /php/projects/pizzastore/errors.php | UTF-8 | 526 | 2.53125 | 3 | [] | no_license |
<div class="container" id="errors">
<div id="activate-<?php echo (!empty($errors_array)) ? " on" : '' ; ?>" class="alert alert-danger" role="alert">
<?php
foreach ($errors_array as $key => $value) {
echo $value ."<br>";
}
?>
</div>
</div>
<div class="container" id="success">
<div id="activate-<?php echo (!empty($success_array)) ? " on" : '' ; ?>" class="alert alert-success" role="alert">
<?php // Affichage du succès
foreach ($success_array as $key => $value) {
echo $value ."<br>";
}
?>
</div>
</div>
| true |
a8d2a5aa5c54a30ad2f264e37f2e4328df723721 | PHP | evgen7171/clock | /views/layouts/menu.php | UTF-8 | 667 | 2.578125 | 3 | [] | no_license | <?php
/**
* @var $menuUnits (array) то, что будет отображено в меню
*/
?>
<ul>
<?php if($menuUnits):?>
<?php foreach ($menuUnits as $tableNames => $arr) {
?>
<li class="menu-list"><a href="?action=showAll&table=<?= $tableNames ?>"><?= $tableNames ?></a>
<ul class="drop-menu">
<?php foreach ($arr as $item): ?>
<li><a href="?action=showOne&table=<?= $tableNames ?>&id=<?= $item['id'] ?>">
<?= $item['prop'] ?></a></li>
<?php endforeach; ?>
</ul>
</li>
<?php
}
?>
<?php endif;?>
</ul> | true |
eae2b1265d53f086f22db8aa58bbe90b8fd9e263 | PHP | rumur/pimpled | /app/Assets/AssetsFront.php | UTF-8 | 1,964 | 2.6875 | 3 | [
"MIT"
] | permissive | <?php
namespace Pmld\App\Assets;
use Pimple\Container;
use Pmld\Support\Facades\Asset;
use Pmld\Support\ServiceProvider;
class AssetsFront extends ServiceProvider
{
/** @inheritdoc */
public function register(Container $app)
{
\add_action('wp_enqueue_scripts', [$this, 'scripts']);
\add_action('wp_enqueue_scripts', [$this, 'styles']);
/**
* Add <body> classes.
* Helps JS to determine on which page is user right now.
*/
\add_filter('body_class', function (array $classes) {
/** Add page slug if it doesn't exist */
if (\is_single() || \is_page() && ! \is_front_page()) {
if (! in_array(basename(\get_permalink()), $classes)) {
$classes[] = basename(\get_permalink());
}
}
return array_filter($classes);
});
/**
* Load the assets with defer.
*/
\add_filter( 'script_loader_tag', function($tag, $handle) {
$replace = in_array($handle, [
'pmld.vendor',
'pmld.main',
'pmld.app'
]);
return ! $replace
? $tag
: str_replace(' src', ' defer src', $tag);
}, 10, 2);
}
/**
* Registered Scripts;
*
* @author rumur
*/
public function scripts()
{
$to_footer = true;
$to_header = false;
\wp_enqueue_script('pmld.app', Asset::get('js/app.js'), ['pmld.vendor'], null, $to_header );
\wp_enqueue_script('pmld.main', Asset::get('js/main.js'), ['jquery', 'pmld.vendor'], null, $to_footer );
}
/**
* Registered Styles;
*
* @author rumur
*/
public function styles()
{
\wp_enqueue_style('pmld.app', Asset::get('css/app.css'), [], null );
\wp_enqueue_style('pmld.main', Asset::get('css/main.css'), [], null );
}
}
| true |
c1d4ef974fb6feda6be707f12537921c131d60a6 | PHP | SaevichAlexandr/kis_lab_4 | /src/Controller/FlightController.php | UTF-8 | 7,555 | 2.703125 | 3 | [] | no_license | <?php
namespace App\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use App\Error\Error;
class FlightController
{
private $departurePoint = 'MOW';
private $arrivalPoint = 'LED';
private $departureDatetime = '2017-07-21T18:30:00Z';
private $arrivalDatetime = '2017-07-24T08:00:00Z';
private $airCompany = 'UT';
private $flightNumber = 'UT-450';
private $cost = 10900.00;
public function getFlight($flightId)
{
$response = new Response();
if($flightId > 0 && $flightId <= 10) {
$response->setContent(json_encode(
[
'id' => $flightId,
'departurePoint' => $this->departurePoint,
'arrivalPoint' => $this->arrivalPoint,
'departureDatetime' => $this->departureDatetime,
'arrivalDatetime' => $this->arrivalDatetime,
'airCompany' => $this->airCompany,
'flightNumber' => $this->flightNumber,
'cost' => $this->cost
]
));
$response->headers->set('Content-type', 'application/json');
return $response;
}
else
{
$error = new Error();
$response->setContent(json_encode($error->get404()));
$response->headers->set('Content-type', 'application/json');
return $response;
}
}
public function getFlights()
{
$flights = [
[
'id' => 1,
'departurePoint' => $this->departurePoint,
'arrivalPoint' => $this->arrivalPoint,
'departureDatetime' => $this->departureDatetime,
'arrivalDatetime' => $this->arrivalDatetime,
'airCompany' => $this->airCompany,
'flightNumber' => $this->flightNumber,
'cost' => $this->cost
],
[
'id' => 2,
'departurePoint' => "LED",
'arrivalPoint' => "MOW",
'departureDatetime' => "2020-07-21T18:30:00Z",
'arrivalDatetime' => "2020-08-24T08:00:00Z",
'airCompany' => "SU",
'flightNumber' => "SU-7090",
'cost' => 29300.00
]
];
$response = new Response();
$response->headers->set('Content-type', 'application/json');
$response->setContent(json_encode($flights));
return $response;
}
public function createFlight()
{
$request = Request::createFromGlobals();
$reqBody = json_decode($request->getContent(), true);
$response = new Response();
if($this->isValidReqBody($reqBody)) {
// здесь потом добавится добавление данных
$response->setContent(json_encode(['id' => rand(11, 100)]));
$response->headers->set('Content-type', 'application/json');
return $response;
}
else {
$error = new Error();
$response->setContent(json_encode($error->get422()));
$response->headers->set('Content-type', 'application/json');
return $response;
}
}
public function updateFlight()
{
$request = Request::createFromGlobals();
$reqBody = json_decode($request->getContent(), true);
$response = new Response();
if($this->isValidReqBody($reqBody)) {
// здесь потом добавится изменение данных
// а пока так
$response->setContent(json_encode($reqBody));
$response->headers->set('Content-type', 'application/json');
return $response;
}
else {
$error = new Error();
$response->setContent(json_encode($error->get422()));
$response->headers->set('Content-type', 'application/json');
return $response;
}
}
public function deleteFlight($flightId)
{
$response = new Response();
if($flightId > 0 && $flightId <= 10) {
$response->setContent(json_encode(['isDeleted' => true]));
$response->headers->set('Content-type', 'application/json');
return $response;
} else {
$error = new Error();
$response->setContent(json_encode($error->get404()));
$response->headers->set('Content-type', 'application/json');
return $response;
}
}
public function getFlightTariffs($flightId)
{
$response = new Response();
if($flightId > 0 && $flightId <= 10)
{
$tariffs = [
'flightId' => $flightId,
[
'code' => "UTOW10S",
'description' => "APPLICATION AND OTHER CONDITIONS RULE - 304/UT23 ".
"UNLESS OTHERWISE SPECIFIED ONE WAY MINIMUM FARE APPLICATION AREA THESE ".
"FARES APPLY WITHIN AREA 2. CLASS OF SERVICE THESE FARES APPLY FOR ".
"ECONOMY CLASS SERVICE. TYPES OF TRANSPORTATION THIS RULE GOVERNS ONE-WAY ".
"FARES. FARES GOVERNED BY THIS RULE CAN BE USED TO CREATE ONE-WAY JOURNEYS.",
'refundable' => true,
'exchangeable'=> false,
'baggage' => "1PC"
],
[
'code' => "UTOW20S",
'description' => "APPLICATION AND OTHER CONDITIONS RULE - 304/UT23 ".
"UNLESS OTHERWISE SPECIFIED ONE WAY MINIMUM FARE APPLICATION AREA THESE ".
"FARES APPLY WITHIN AREA 2. CLASS OF SERVICE THESE FARES APPLY FOR ".
"ECONOMY CLASS SERVICE. TYPES OF TRANSPORTATION THIS RULE GOVERNS ONE-WAY ".
"FARES. FARES GOVERNED BY THIS RULE CAN BE USED TO CREATE ONE-WAY JOURNEYS.",
'refundable' => true,
'exchangeable'=> true,
'baggage' => "2PC"
]
];
$response->headers->set('Content-type', 'application/json');
$response->setContent(json_encode($tariffs));
return $response;
}
else
{
$error = new Error();
$response->setContent(json_encode($error->get404()));
$response->headers->set('Content-type', 'application/json');
return $response;
}
}
private function isValidReqBody($reqBody)
{
if (
isset($reqBody['departurePoint']) &&
isset($reqBody['arrivalPoint']) &&
isset($reqBody['departureDatetime']) &&
isset($reqBody['arrivalDatetime']) &&
isset($reqBody['airCompany']) &&
isset($reqBody['flightNumber']) &&
isset($reqBody['cost'])
) {
if (
is_string($reqBody['departurePoint']) &&
is_string($reqBody['arrivalPoint']) &&
is_string($reqBody['departureDatetime']) &&
is_string($reqBody['arrivalDatetime']) &&
is_string($reqBody['airCompany']) &&
is_string($reqBody['flightNumber']) &&
is_float($reqBody['cost'])
) {
return true;
}
}
return false;
}
} | true |