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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
3bd9179c9d5d06c207ba3f53c7cb113aad9ceb5d | PHP | Voziv/house | /app/Enum/Permission.php | UTF-8 | 423 | 2.53125 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Enum;
final class Permission
{
const CREATE_ANY = 'create';
const READ_ANY = 'read';
const UPDATE_ANY = 'update';
const DELETE_ANY = 'delete';
const SENSOR_READING_READ = 'sensor_reading:read';
const SENSOR_READING_WRITE = 'sensor_reading:write';
public function __construct()
{
throw new \RuntimeException("You cannot instantiate this enum class.");
}
}
| true |
7a1903a2dd9e4def59f98c0d2696d29cb5d40094 | PHP | dsacheti/emailmkt | /src/EmailMkt/Application/Action/Teste2PageAction.php | UTF-8 | 1,266 | 2.8125 | 3 | [] | no_license | <?php
namespace EmailMkt\Application\Action;
use EmailMkt\Domain\Entity\Customer;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Zend\Diactoros\Response\HtmlResponse;
use Zend\Expressive\Template;
use EmailMkt\Domain\Persistence\CustomerRepositoryInterface;
class Teste2PageAction
{
private $template;
/**
* @var CustomerRepositoryInterface
*/
private $repository;
public function __construct(CustomerRepositoryInterface $repository,Template\TemplateRendererInterface $template = null)
{
$this->template = $template;
$this->repository = $repository;
}
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null)
{
$customer = new Customer();
$customer->setName("Jovair Novaes");
$customer->setEmail("jnovaes@hotmail.com");
$this->repository->create($customer);
$customers = $this->repository->findAll();
//app::teste2 é o templates/app/teste2.html.twig
return new HtmlResponse($this->template->render(
"app::teste2",
[
"data"=>"Dados passados para o template",
"customers" => $customers
]));
}
}
| true |
cbef1b11861c0c13ee1c653a70e0f38325810511 | PHP | PhuongNgan2103/the_house_rental_project | /app/Http/Controllers/AuthController.php | UTF-8 | 2,425 | 2.5625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers;
use App\Http\Requests\LoginUserRequest;
use App\Http\Requests\RegisterUserRequest;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Session;
use Laravel\Socialite\Facades\Socialite;
class AuthController extends Controller
{
public function showPageLogin()
{
return view('login');
}
public function login(LoginUserRequest $request)
{
if (Auth::attempt(['email' => $request->email, 'password' => $request->password], $request->remember_me)) {
$request->session()->regenerate();
return redirect()->route('house.list'); // đường dẫn sau khi login ở đây
}
return back()->withErrors([
'username' => 'Tên người dùng hoặc mật khẩu sai !',
]);
}
public function loginWithGoogle()
{
return Socialite::driver('google')->redirect();
}
public function loginWithGoogleCallBack()
{
try {
$user = Socialite::driver('google')->user();
} catch (\Exception $e) {
return redirect()->route('auth.login');
}
$existingUser = User::where('email', $user->email)->first();
if ($existingUser) {
auth()->login($existingUser, true);
} else {
$newUser = new User();
$newUser->username = $user->email;
$newUser->password = Hash::make('password');
$newUser->email = $user->email;
$newUser->save();
auth()->login($newUser, true);
}
return redirect()->route('home');
}
public function showPageRegister()
{
return view('register');
}
public function register(RegisterUserRequest $request)
{
$user = new User();
$user->username = $request->username;
$user->phone = $request->phone;
$user->password = Hash::make($request->password);
$user->email = $request->email;
$user->save();
$request->session()->flash('message','Đăng ký thành công. Vui lòng đăng nhập để bắt đầu');
return redirect()->route('auth.login');
}
public function logout(){
Auth::logout();
Session::flash('message_1','Đăng xuất thành công');
return redirect()->route('auth.login');
}
}
| true |
74214adbc65976d519082983c4e1fbff6a7ce1c8 | PHP | Tosini13/tournament | /php/structures.php | UTF-8 | 16,673 | 3.265625 | 3 | [] | no_license | <?php
// --------------------------------------------------------------------
// >>>>>>>>>>>>>>>>>>>>>>>>>>>TOURNAMENT<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// --------------------------------------------------------------------
class Tournament {
private $id;
private $name;
private $host;
private $sponsor;
private $participants_qtt;
private $group_qtt;
private $play_offs_qtt; //i.e. quaterfinal
private $start_date;
private $end_date;
public $no_last_place;
private $mode; //0-group; 1-play-offs; 2-both
public $groups = array();
public $play_offs;
public $teams = array();
//SET
public function set_name($arg) {
$this->name = $arg;
}
public function set_participants_qtt($arg) {
$this->participants_qtt = $arg;
}
public function set_group_qtt($arg) {
if ($arg > $this->participants_qtt) {
$this->group_qtt = $this->participants_qtt;
} else {
$this->group_qtt = $arg;
}
}
//WHY I divide it one more time!
public function set_play_offs_qtt($arg) {
while ($arg * 2 > $this->participants_qtt) { //when there's more play offs than participants
$arg /= 2;
}
if ($arg * 2 < $this->group_qtt) {
$arg = $this->group_qtt / 2;
}
//$this->play_offs_qtt = $arg / 2;
$this->play_offs_qtt = $arg;
}
public function set_no_last_place($arg) {
$this->no_last_place = $arg;
}
public function set_mode($arg) {
$this->mode = $arg;
}
public function set_host($name, $logo, $url) {
$this->host->set_name($name);
$this->host->set_logo($logo);
$this->host->set_url($url);
}
public function set_sponsor($name, $logo, $url) {
$this->sponsor->set_name($name);
$this->sponsor->set_logo($logo);
$this->sponsor->set_url($url);
}
public function set_id($arg) {
$this->id = $arg;
}
public function set_start_date($arg) {
$this->start_date = $this->datetime_validation($arg);
}
public function set_end_date($arg) {
$this->end_date = $this->datetime_validation($arg);
}
//GET
public function get_name() {
return $this->name;
}
public function get_start_date() {
return $this->start_date;
}
public function get_end_date() {
return $this->end_date;
}
public function get_participants_qtt() {
return $this->participants_qtt;
}
public function get_group_qtt() {
return $this->group_qtt;
}
public function get_play_offs_qtt() {
return $this->play_offs_qtt;
}
public function get_no_last_place() {
return $this->no_last_place;
}
public function get_mode() {
return $this->mode;
}
public function get_host() {
return $this->host;
}
public function get_sponsor() {
return $this->sponsor;
}
public function get_id() {
return $this->id;
}
//FUNCTIONS
function datetime_validation($arg) {
if ($arg == '') {
return date('Ymd');
} else {
$arg = str_replace('-', '', $arg);
$arg = str_replace(':', '', $arg);
$arg = str_replace('T', '', $arg);
for ($i = strlen($arg); $i < 14; $i++) {
$arg .= "0"; //seconds
}
}
return $arg;
}
public function declare_teams() {
for ($i = 0; $i < $this->participants_qtt; $i++) {
$this->teams[$i] = new Team();
$this->teams[$i]->set_name("Zespół nr " . ($i + 1));
}
}
public function declare_groups($group_qtt, $play_offs_qtt) {
$team_qtt = 0;
$this->set_group_qtt($group_qtt);
$this->set_play_offs_qtt($play_offs_qtt);
//when odd number of participants
if ($this->get_group_qtt() != 1) {
$rest_teams = $this->get_participants_qtt() % $this->get_group_qtt();
} else {
$rest_teams = 0;
}
for ($i = 0; $i < $this->get_group_qtt(); $i++) {
//check if in group shouldn't be the same amount of teams
if ($rest_teams != 0) {
$add = 1;
$rest_teams--;
} else {
$add = 0;
}
//how many team should to be in particular group
$this->groups[$i] = new Group('Grupa ' . chr(65 + $i), $this->teams_qtt_in_group() + $add);
$this->groups[$i]->promoted_teams_qtt($this->group_qtt, $this->get_play_offs_qtt());
//create teams in group
for ($j = 0; $j < $this->groups[$i]->teams_qtt; $j++) {
$this->groups[$i]->teams[$j] = $this->teams[$team_qtt++];
//$this->groups[$i]->teams[$j]->set_name('Zespół nr ' . ($j + 1) . ' G: ' . $this->groups[$i]->name);
}
$this->groups[$i]->create_matches();
}
}
public function promoted_all_teams() {
$promoted_all_teams = array();
$i = 0;
foreach ($this->groups as $index => $group) {
$j = 0;
foreach ($group->promoted_teams() as $index => $team) {
if ($i == 0) {
$promoted_all_teams[$j] = array();
}
$promoted_all_teams[$j++][$i] = $team;
}
$i++;
}
for ($i = count($promoted_all_teams) / 2; $i < (count($promoted_all_teams)); $i++) { //second half of teams
$temp = array();
for ($j = 0; $j < count($promoted_all_teams[$i]); $j++) {
$temp[$j] = $promoted_all_teams[$i][count($promoted_all_teams[$i]) - $j - 1];
}
$promoted_all_teams[$i] = $temp;
}
return $promoted_all_teams;
}
public function play_offs_preparation() {
//order group of promoted teams for first round of play-offs
//reverse
$all = array();
if ($this->mode == 1) {
//DECLARING TEAMS!!!!
$all[0] = array();
$all[0] = $this->teams;
} else {
$all = $this->promoted_all_teams();
}
$places_qtt = count($all);
$promoted_qtt = count($all[0]); //group_qtt?!?
$new_order = array();
$new_order_qtt = -1;
for ($i = 0; $i < $places_qtt; $i++) {
if ($i % 2 == 0) {
$place = $i;
$new_order_qtt++;
} else {
$place = $places_qtt - $i;
}
for ($j = 0; $j < $promoted_qtt; $j++) {
if ($i % 2 == 0) {
$new_order[$new_order_qtt * $promoted_qtt + $j] = new Match();
$new_order[$new_order_qtt * $promoted_qtt + $j]->set_team1($all[$place][$j]);
} else {
$new_order[$new_order_qtt * $promoted_qtt + $j]->set_team2($all[$place][$j]);
}
}
}
return $new_order;
}
public function declare_play_offs($play_offs_qtt, $no_last_place) {
$this->set_play_offs_qtt($play_offs_qtt);
$this->set_no_last_place($no_last_place);
$this->play_offs = new Play_offs($this->play_offs_qtt, $this->no_last_place);
$this->play_offs->create_structure();
$this->play_offs->create_place_matches();
$this->play_offs->fill_structure_from_group($this->play_offs_preparation()); //if groups are available!!!
}
public function teams_qtt_in_group() {
return intval($this->participants_qtt / $this->group_qtt);
}
//CONSTRUCTORS
public function __construct($name, $participants_qtt, $start_time, $end_time) {
$this->name = $name;
$this->participants_qtt = $participants_qtt;
$this->host = new Entity();
$this->sponsor = new Entity();
$this->declare_teams();
$this->set_start_date($start_time);
$this->set_end_date($end_time);
/*
//$this->mode = $mode;
switch ($mode) {
case 1:
$this->play_offs = null;
$this->groups = array();
$this->declare_groups();
break;
case 2:
$this->group = null;
break;
case 3:
$this->groups = array();
$this->declare_groups();
break;
}
* */
}
}
// --------------------------------------------------------------------
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>GROUP<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// --------------------------------------------------------------------
class Group {
private $id;
public $name;
public $teams_qtt;
public $teams = array();
public $result; //aktualna tabela
public $promoted_teams_qtt;
private $matches = array();
//SET
public function set_name($arg) {
$this->name = $arg;
}
public function set_teams_qtt($arg) {
$this->teams_qtt = $arg;
}
public function set_promoted_teams_qtt($arg) {
$this->promoted_teams_qtt = $arg;
}
public function set_teams($arg) {
$this->teams = $arg;
}
public function set_id($arg) {
$this->id = $arg;
}
//GET
public function get_name() {
return $this->name;
}
public function get_teams_qtt() {
return $this->teams_qtt;
}
public function get_promoted_teams_qtt() {
return $this->promoted_teams_qtt;
}
public function get_teams() {
return $this->teams;
}
public function get_matches() {
return $this->matches;
}
public function get_id() {
return $this->id;
}
//FUNCTIONS
public function promoted_teams() {
$promoted = array();
for ($i = 0; $i < $this->promoted_teams_qtt; $i++) {
array_push($promoted, $this->teams[$i]);
}
return $promoted;
}
public function promoted_teams_qtt($groups, $play_off) {
$this->promoted_teams_qtt = ($play_off * 2) / $groups;
}
public function create_matches() {
for ($i = 0; $i < count($this->teams) - 1; $i++) {
for ($j = $i + 1; $j < count($this->teams); $j++) {
$group_match = new Match();
$group_match->set_team1($this->teams[$i]);
$group_match->set_team2($this->teams[$j]);
array_push($this->matches, $group_match);
}
}
}
public function count_results() {
foreach ($this->matches as $key => $match) {
}
}
//CONSTRUCTOR
public function __construct($name, $teams_qtt) {
$this->name = $name;
$this->teams_qtt = $teams_qtt;
}
}
// --------------------------------------------------------------------
// >>>>>>>>>>>>>>>>>>>>>>>>>>GROUP TABLE<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// --------------------------------------------------------------------
class Group_table {
private $id;
public $team;
public $points;
public $wins;
public $loses;
public $draws;
public $scores;
public $lost_goals;
//SET
public function set_id($arg) {
$this->id = $arg;
}
//GET
public function get_id() {
return $this->id;
}
}
// --------------------------------------------------------------------
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>PLAY-OFFS<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// --------------------------------------------------------------------
class Play_offs {
//public $name;
private $id;
public $rounds_qtt;
public $no_last_place;
public $rounds = array(); //key=round; values=matches(array)
public $places = array(); //key=round; values=matches(array)
public $matches = array();
public $round = array(1 => "Finał", 2 => "Półfinał", 4 => "Ćwierćfinał", 8 => "1/16", 16 => "1/32");
//SET
public function set_id($arg) {
$this->id = $arg;
}
//GET
public function get_id() {
return $this->id;
}
public function create_structure() {
for ($i = $this->rounds_qtt; $i >= 1; $i /= 2) {
$this->rounds[$this->round[$i]] = array();
for ($j = 0; $j < $i; $j++) {
$this->rounds[$this->round[$i]][$j] = new Match();
//set name of play-off
if ($i != 1) {
$this->rounds[$this->round[$i]][$j]->set_name($this->round[$i]);
} else {
$this->rounds[$this->round[$i]][$j]->set_name($this->round[$i]); //when final
}
}
}
}
public function fill_structure_from_group($groups) {
$j = 0;
for ($i = 0; $i < $this->rounds_qtt; $i++) {
$this->rounds[$this->round[$this->rounds_qtt]][$i]->set_team1($groups[$j]->get_team1());
if ($groups[$j]->get_team2()->get_name() !== null) {
$this->rounds[$this->round[$this->rounds_qtt]][$i]->set_team2($groups[$j++]->get_team2());
} else {//when there's only one team promoted from each group
$this->rounds[$this->round[$this->rounds_qtt]][$i]->set_team2($groups[++$j]->get_team1());
$j++;
}
}
}
public function create_place_matches() {
for ($i = $this->no_last_place; $i > 1; $i -= 2) {
$this->places[$i] = new Match();
}
}
public function __construct($rounds_qtt, $no_last_place) {
$this->rounds_qtt = $rounds_qtt;
$this->no_last_place = $no_last_place;
}
}
// --------------------------------------------------------------------
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>MATCH<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// --------------------------------------------------------------------
class Match {
private $id;
private $name;
private $team1;
private $team2;
private $result = array();
//SET
public function set_name($arg) {
$this->name = $arg;
}
public function set_team1($arg) {
$this->team1 = $arg;
}
public function set_team2($arg) {
$this->team2 = $arg;
}
public function set_result($home, $away) {
$this->result[0] = $home;
$this->result[1] = $away;
}
public function set_id($arg) {
$this->id = $arg;
}
//GET
public function get_name() {
return $this->name;
}
public function get_team1() {
return $this->team1;
}
public function get_team2() {
return $this->team2;
}
public function get_result() {
return $this->result;
}
public function get_id() {
return $this->id;
}
//functions
public function winner() {
if ($this->result[0] > $this->result[1]) {
return $this->team1;
} else {
return $this->team2;
}
}
//constructor
public function __construct() {
$this->team1 = new Team();
$this->team2 = new Team();
$this->set_result(1, 1);
}
}
// --------------------------------------------------------------------
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>TEAM<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// --------------------------------------------------------------------
class Team {
private $name;
private $id;
//SET
public function set_name($arg) {
$this->name = $arg;
}
public function set_id($arg) {
$this->id = $arg;
}
//SET
public function get_name() {
return $this->name;
}
public function get_id() {
return $this->id;
}
}
// --------------------------------------------------------------------
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>ENTITY<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// --------------------------------------------------------------------
class Entity {
private $name;
private $logo;
private $url;
//SET
public function set_name($arg) {
$this->name = $arg;
}
public function set_logo($arg) {
$this->logo = $arg;
}
public function set_url($arg) {
$this->url = $arg;
}
//GET
public function get_name() {
return $this->name;
}
public function get_logo() {
return $this->logo;
}
public function get_url() {
return $this->url;
}
/*
public function __construct($name, $logo, $url) {
$this->name = $name;
$this->logo = $logo;
$this->url = $url;
}
*/
public function __construct() {
}
}
| true |
fe90b29019c11df41a3f7451668b3337a20f5532 | PHP | NRaudseps/codelex-19-09-MD | /arithmetic-operators/ex5.php | UTF-8 | 647 | 4.25 | 4 | [] | no_license | <?php declare(strict_types=1);
echo "I'm thinking of a number between 1-100. Try to guess it." . "\n";
$num = (int) readline();//Input from user
function guessNumber (int $num):string {
$pc = rand(1,100);//Random number the computer generates
//Guess is too high
if($num > $pc){
return 'Sorry, you are too high. I was thinking of ' . strval($pc) . "\n";
}
//Guess is too low
elseif ($num < $pc){
return 'Sorry, you are too low. I was thinking of ' . strval($pc) . "\n";
}
//Guess is correct
else {
return 'You guessed it! What are the odds?!?' . "\n";
}
}
echo guessNumber($num);
| true |
2c2a51d7efd25ba711aae5ebcad3b882202a9fca | PHP | ElijahCuff/PHP-Crypto | /Cryto.php | UTF-8 | 1,866 | 3.171875 | 3 | [
"MIT"
] | permissive | <?php
// --------------------
// PHP Crypto
// --------------------
// input payload
$payload = "bkhgghvghvvhuvhgyyhh";
// set scripts hidden password
// This password is secured will only be used in conjunction with a secure random byte salt.
$password = "Password";
// start ms consumption timer
timer(true);
// encrypt payload example
$encrypted_payload = crypto($payload,$password);
// decrypt payload example
$decrypted_payload = crypto($encrypted_payload,$password,true);
// stop timer & get ms consumption
$consumption = timer(false);
// return time consumption of operation
echo "Time consumption = ".$consumption.' ms';
// Crypto 2-Way Random Encrypt/Decrypt Function
function crypto($payload, $password, $doDecrypt = false)
{
$encryption_protocol = ('aes-256-cbc');
$output = '';
if($doDecrypt)
{
$payload = urlDecode($payload);
list($aes256iv, $encrypted_payload, $decryption_salt) = explode('::', base64_decode($payload), 3);
$encryption_key = base64_decode($password.$decryption_salt);
$output = openssl_decrypt($encrypted_payload, $encryption_protocol, $encryption_key, 0, $aes256iv);
}
else
{
$encryption_salt = openssl_random_pseudo_bytes(10);
$encryption_key = base64_decode($password.$encryption_salt);
$aes256iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($encryption_protocol));
$encrypted_payload = openssl_encrypt($payload, $encryption_protocol, $encryption_key, 0, $aes256iv);
$output = base64_encode($aes256iv . '::' . $encrypted_payload. '::'.$encryption_salt);
}
return urlEncode($output);
}
// Timer Function & Global Time Start Variable
$milliStart = 0;
function timer($start)
{
global $milliStart;
$out = 0;
if ($start)
{
$milliStart = round(microtime(true)*1000);
}
else
{
$out = round(microtime(true)*1000);
$out = $out - $milliStart;
$milliStart = 0;
}
return $out;
}
?>
| true |
2de5df85dcd04e377268420491b2def7aa64dfad | PHP | pipihaa/tp5_layui_vue | /tp5/application/admin/Utils/FormatArrayUtils.class.php | UTF-8 | 4,221 | 3.046875 | 3 | [
"Apache-2.0"
] | permissive | <?php
/**
* Created by PhpStorm.
* User: daweicc
* Date: 2018/3/7
* Time: 11:50
*/
namespace Common\Utils;
class FormatArrayUtils
{
/**
* 数组键名转换为指定字段值
* @param array $data
* @param string $key
* @param string $val
* @return array
*/
public static function changeKey($data=array(), $key='', $val = '')
{
if(empty($data) || empty($key)) return $data;
$returnRes = array();
if (empty($val)) { //返回的是键名随影数组 1 =>array(id=>1,name='dawei'), 2=>array(id=>2,name='xixi')
foreach ($data as $k => $v) {
if($v[$key])
$returnRes[$v[$key]] = $v;
}
} else {
foreach ($data as $k => $v) { //返回的是键名对应键值 1 =>'dawei', 2=>'xixi'
if($v[$key])
$returnRes[$v[$key]] = $v[$val];
}
}
return $returnRes;
}
/**
* 根据字段值分组
* @param $data
* @param $key
* @return array
*/
public static function changeKeyArray($data, $key)
{
if(empty($data) || empty($key)) return $data;
$resData = array();
foreach ($data as $k=>$v) {
$resData[$v[$key]][] = $data[$k];
}
return $resData;
}
/**
* @param $data 被匹配数据源
* @param $key 被匹配数据对应的字段名
* @param $val 匹配值
* @param $fields 返回的数据对应的字段名
* @param string $default 默认值
* @return mixed 字段$fields对应的值
*/
public static function returnValueByKv($data, $key, $val, $fields, $default = '')
{
$reVal = $default;
foreach ($data as $k => $v) {
if ($v[$key] == $val) {
$reVal = $fields ? $v[$fields] : $data[$k];
break;
}
}
return $reVal;
}
/**
* 给定字段名,合并相同字段名的值
* @param $initVal 初始值
* @param array $data 数据源
* @param $key 想要获取数据的键名
* @return array
*/
public static function unionValueByKey($data=array(),$key,$initVal){
unset($v);
$lists = array();
if (!empty($initVal)) $lists[] = $initVal;
unset($v);
foreach($data as $k=>$v){
$lists[] = $v[$key];
}
$lists = array_unique($lists);
return $lists;
}
/**
* 将数组2中满足数组1条件的数据合并到数组1
* @param $arrOne
* @param $arrTwo
* @param string $field
* @param int $defaultVal
* @return mixed
*/
public static function unionArrayMerge($arrOne, $arrTwo, $field = 'id', $defaultVal = 0)
{
if (empty($arrOne) || empty($arrTwo)) return $arrOne;
$default = array();
foreach ($arrTwo as $two) { //获取默认下标
if (empty($default)) {
if(!empty($two)) $default = $two;
} else {
break;
}
}
foreach ($arrOne as $k => $v) {
if (!empty($arrTwo[$v[$field]])) {
$arrOne[$k] = array_merge($arrTwo[$v[$field]], $arrOne[$k]);
} else {
unset($val);
foreach ($default as $key=>$val) { //没有符合条件的数据时,字段值用空格填充
$arrTwo[$v[$field]][$key] = $defaultVal;
}
$arrOne[$k] = array_merge($arrTwo[$v[$field]], $arrOne[$k]);
}
}
return $arrOne;
}
/**
*
* @param array $data 二维数组
* @param array $arr 一维数组
* @return array 相同字段数据
*/
public static function arrayEquals($data = array(), $arr)
{
if(empty($data) || empty($arr)) return $data;
$equals = array();
foreach ($data as $k => $v) {
if (in_array($k, $arr)) {
$equals[$k] = $v;
}
}
return $equals;
}
} | true |
f2bd87b5e560663f2c84cc0cb7febd983d51813d | PHP | thinkgem/openwan | /lib/qeephp-2.1/tests/include/bddtest_common.php | UTF-8 | 1,024 | 2.96875 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
/**
* 用于 BDD 测试的公共文件
*/
require_once 'PHPUnit/Extensions/Story/TestCase.php';
/**
* PHPUnit_Extensions_Story_Runner 使用 PHP 5.3 的闭包来改善 BDD 代码的书写
*
* 在继承类中,不再需要实现 runGiven()、runWhen() 和 runThen() 方法。
*/
abstract class PHPUnit_Extensions_Story_Runner extends PHPUnit_Extensions_Story_TestCase
{
protected function runStepWithClosure(& $world, $action, $arguments)
{
if (isset($arguments[0]) && $arguments[0] instanceof Closure)
{
$lambda = $arguments[0];
$lambda($world, $action);
}
}
function runGiven(&$world, $action, $arguments)
{
$this->runStepWithClosure($world, $action, $arguments);
}
function runWhen(&$world, $action, $arguments)
{
$this->runStepWithClosure($world, $action, $arguments);
}
function runThen(&$world, $action, $arguments)
{
$this->runStepWithClosure($world, $action, $arguments);
}
}
| true |
05acdae4d4ecfb7114709f8a6ec2aa0c834ade53 | PHP | vda789/projecthaina | /database/migrations/2021_09_29_160235_create_turmas.php | UTF-8 | 784 | 2.6875 | 3 | [
"MIT"
] | permissive | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateTurmas extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('turmas', function (Blueprint $table) {
$table->id();
$table->time('ano');
$table->boolean('nivel'); //fundamental e médio
$table->integer('serie');
$table->unsignedInteger('turno'); //1 = manha, 2 = tarde, 3 = noite
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('turmas');
}
}
| true |
9207d8d15a22c2d93b6db2bca2658c99e882e43c | PHP | Matrix-aas/nstu-tracker | /app/Services/Repositories/IProfessorDisciplineRepository.php | UTF-8 | 414 | 2.609375 | 3 | [] | no_license | <?php
namespace App\Services\Repositories;
interface IProfessorDisciplineRepository
{
public function attachDiscipline(int $professorId, int $disciplineId): bool;
public function attachProfessor(int $disciplineId, int $professorId): bool;
public function detachDiscipline(int $professorId, int $disciplineId): bool;
public function detachProfessor(int $disciplineId, int $professorId): bool;
} | true |
5040af1e6b2a935f6ba6c569c2ea4616be08dd59 | PHP | opgginc/php-riotapi-request | /src/RequestMethod/Match/MatchesByAccount.php | UTF-8 | 2,136 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
/**
* Created by PhpStorm.
* User: kargnas
* Date: 2017-06-26
* Time: 03:41
*/
namespace RiotQuest\RequestMethod\Match;
use DateTime;
use RiotQuest\Constant\EndPoint;
use RiotQuest\Constant\Platform;
use RiotQuest\Dto\Match\MatchlistDto;
use RiotQuest\RequestMethod\Request;
use RiotQuest\RequestMethod\RequestMethodAbstract;
use GuzzleHttp\Psr7\Response;
use JsonMapper;
/** @deprecated */
class MatchesByAccount extends RequestMethodAbstract
{
public $path = EndPoint::MATCH__LIST_BY_ACCOUNT;
/** @deprecated */
public $accountId;
/** @var string */
public $encryptedAccountId;
/** @var DateTime */
public $beginTime, $endTime;
/** @var integer */
public $queue, $season, $champion;
/** @var integer */
public $beginIndex, $endIndex;
function __construct(Platform $platform, $encryptedAccountId) {
parent::__construct($platform);
$this->encryptedAccountId = $encryptedAccountId;
}
public function getRequest() {
$uri = $this->platform->apiScheme . "://" . $this->platform->apiHost . "" . $this->path;
$uri = str_replace("{encryptedAccountId}", $this->encryptedAccountId, $uri);
$query = http_build_query([
'beginTime' => ($this->beginTime ? $this->beginTime->getTimestamp() * 1000 : null),
'endTime' => ($this->endTime ? $this->endTime->getTimestamp() * 1000 : null),
'beginIndex' => $this->beginIndex,
'endIndex' => $this->endIndex,
'queue' => $this->queue,
'season' => $this->season,
'champion' => $this->champion,
]);
if (strlen($query) > 0) {
$uri .= "?{$query}";
}
return $this->getPsr7Request('GET', $uri);
}
public function mapping(Response $response) {
$json = \GuzzleHttp\json_decode($response->getBody());
$mapper = new JsonMapper();
/** @var MatchlistDto $object */
$object = $mapper->map($json, new MatchlistDto());
return $object;
}
} | true |
58352c9d738693b2dc0ace5b42a051dfeba26e1f | PHP | dukejib/teatimekc | /app/Mail/InviteNewMemberMail.php | UTF-8 | 854 | 2.515625 | 3 | [] | no_license | <?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Support\Facades\Log;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class InviteNewMemberMail extends Mailable
{
use Queueable, SerializesModels;
public $regToken;
/**
* Create a new message instance.
*
* @return void
*/
public function __construct($regToken)
{
// Log::info('04 : in NPCM Construct()');
$this->regToken = $regToken;
// dd($regToken);
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
Log::info('05 : in INMM build()');
return $this->from(config('blog.email_address'))->subject('Teatime Blog Registration Invite!')
->view('emails.invite');
}
}
| true |
41746f5dbc0867d6abae83becc9309637c91c41e | PHP | sashkomatviychuk/framework | /components/composer/kuria/console/src/Command/CommandInput.php | UTF-8 | 2,547 | 3 | 3 | [
"MIT"
] | permissive | <?php
namespace Kuria\Console\Command;
use Kuria\Console\Input\Input;
use Kuria\Console\Input\InputInterface;
/**
* Command input class
*
* Represents subset of input containing data
* specific to given Command instance.
*
* @author ShiraNai7 <shira.cz>
*/
class CommandInput extends Input
{
/**
* Constructor
*
* @param Command $command
* @param InputInterface $input
* @throws \RuntimeException
*/
public function __construct(Command $command, InputInterface $input)
{
// extract and validate parameters
$params = array();
$inputParams = $input->getParameters();
$usedParams = array();
foreach ($command->getParameters() as $commandParamName => $commandParam) {
if (array_key_exists($commandParamName, $inputParams)) {
// full name
$params[$commandParamName] = $inputParams[$commandParamName];
$usedParams[] = $commandParamName;
} elseif (null !== $commandParam['alias'] && array_key_exists($commandParamAlias = "-{$commandParam['alias']}", $inputParams)) {
// alias
$params[$commandParamName] = $inputParams[$commandParamAlias];
$usedParams[] = $commandParamAlias;
} elseif ($commandParam['required']) {
// missing required
throw new \RuntimeException(sprintf('Missing required parameter "%s"', $commandParamName));
} else {
// use default
$params[$commandParamName] = $commandParam['default'];
}
}
// detect unknown parameters
if (!$command->getIgnoreExtraParameters()) {
$unknownParameters = array_diff(array_keys($inputParams), $usedParams);
if (!empty($unknownParameters)) {
throw new \RuntimeException(sprintf('Unknown parameter(s): %s', implode(', ', $unknownParameters)));
}
}
// extract and validate arguments
$args = $input->getArguments();
$argCount = sizeof($args);
if ($argCount < $command->getMinArguments()) {
throw new \RuntimeException('Not enough arguments');
}
if (null !== $command->getMaxArguments() && $argCount > $command->getMaxArguments()) {
throw new \RuntimeException('Too many arguments');
}
// set
$this->params = $params;
$this->args = $args;
$this->interactive = $input->isInteractive();
}
}
| true |
58a333ef77ad94e78ecbd537b3c8e8a68bf949d2 | PHP | Faria-kaniz/Admin-template | /app/Http/Controllers/HomeController.php | UTF-8 | 1,508 | 2.53125 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Session;
class HomeController extends Controller
{
public function submt(){
return view('welcome');
}
public function addcour()
{
return view('Student.add');
}
public function store( Request $request)
{
$userObj = new User();
$userObj->name = $request['name'];
$userObj->email = $request['email'];
$userObj->password = $request['password'];
$userObj->roll = $request['roll'];
$userObj->section = $request['section'];
$userObj->class = $request['class'];
if($userObj->save()){
return back()->with('success','Submitted Successfully');
}else{
return back()->with('success','Cannot submit');
}
//
// DB::table('users')->insert([
// 'name'=>$request->name,
// 'email'=>$request->email,
// 'password'=>$request->password,
// 'roll'=>$request->roll,
// 'section'=>$request->section,
// 'class'=>$request->class,
//
// 'created_at' => date('Y-m-d h:m:s'),
//
// ]);
// return back()->with('success','Submitted Successfully');
}
public function admin(){
return view('welcome');
}
public function studentList(){
$userList = User::all();
return view('Student.list')->with('userList',$userList);
}
}
| true |
2263411625fffad9c9d3b66c7df1743cbcf56056 | PHP | ar2labs/wiring | /src/Http/Controller/AbstractViewController.php | UTF-8 | 417 | 2.59375 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
declare(strict_types=1);
namespace Wiring\Http\Controller;
use Wiring\Interfaces\ViewStrategyInterface;
abstract class AbstractViewController extends AbstractController
{
/**
* Get a view renderer.
*
* @return ViewStrategyInterface
* @throws \Exception
*/
public function view(): ViewStrategyInterface
{
return $this->get(ViewStrategyInterface::class);
}
}
| true |
025c4c3987a6431ab9d0f80debfebbefa5dbe61d | PHP | KatterinaM/example-of-work | /Models/Sessions.php | UTF-8 | 590 | 2.765625 | 3 | [] | no_license | <?php
namespace Models;
use Core\Model;
class Sessions extends Model{
protected static $instance;
public static function instance(){
if(self::$instance == null){
self::$instance = new self();
}
return self::$instance;
}
public function __construct(){
parent::__construct();
$this->table = 'sessions';
$this->pk = 'id_session';
}
public function getByToken($token){
$res = $this->sql->select("SELECT * FROM $this->table WHERE token=:token",
['token' => $token]);
return $res[0] ?? false;
}
protected function validation($fields){
}
}
?> | true |
12d89b2e118f54cbb41b85be3f6b42caa1b4e5f0 | PHP | iannazzi/craiglorious | /app/Models/Tenant/Role.php | UTF-8 | 6,829 | 2.625 | 3 | [] | no_license | <?php namespace App\Models\Tenant;
use App\Models\BaseModel;
use App\Models\Craiglorious\System;
class Role extends BaseModel
{
protected $guarded = ['id'];
//there are two views
//one is the allowed view for the user
//one is the list of permissions for a view
public function isAdmin()
{
if (strtolower($this->name) == 'administrator')
{
return true;
}
return false;
}
//waht views can the user access
public function userViews()
{
$system = \Config::get('tenant_system');
//$system = \Auth::user()->system;
//all of the possible views
// $system_id = session('system');
// $system = System::find($system_id);
$views = $system->views();
//Views for the role - limited results
$query = \DB::table('role_view');
$query->where('role_id', '=', $this->id);
$results = $query->get();
//we need to manually add the name back in for the view
foreach ($results as $result)
{
foreach ($views as $view)
{
if ($result->view_id == $view->id)
{
$result->name = $view->name;
$result->icon = $view->icon;
$result->route = $view->route;
$result->place = $view->place;
}
}
}
foreach ($results as $result)
{
if ($result->access != 'none')
{
$return[] = $result;
}
}
return $return;
}
//what views can the system access
public function systemViews()
{
//$system = \Auth::user()->system;
// $system_id = session('system');
// $system = System::find($system_id);
$system = \Config::get('tenant_system');
//all of the possible views
$views = $system->views();
$query = \DB::table('role_view');
$query->where('role_id', '=', $this->id);
$results = $query->get();
//we need to return view id, access = none, write, or read
//we need to manually add the name back in for the view
foreach ($results as $result)
{
foreach ($views as $view)
{
if ($result->view_id == $view->id)
{
$result->name = $view->name;
}
}
}
return $results;
}
public function createDefaultViews(){
$system = \Config::get('tenant_system');
//all of the possible views
$views = $system->views();
foreach ($views as $view){
\DB::table('role_view')->insert(['view_id' => $view->id, 'role_id' => $this->id, 'access'=> 'write']);
}
}
public function users()
{
return $this->hasMany('App\Models\Tenant\User');
}
public function views()
{
// $cg = new \App\Models\Craiglorious\View;
// $database = $cg->getConnection()->getDatabaseName();
// return $this->hasMany('App\Models\Craiglorious\View', $database.'.views', 'role_id','view_id');
//can not do this as the system // or should i?
//return $this->hasMany('App\Models\Craiglorious\View');
}
//each category might have one parent
public function parent()
{
return $this->belongsToOne(static::class, 'parent_id');
}
//each category might have multiple children
public function children()
{
return $this->hasMany(static::class, 'parent_id');
}
function getRoleChildrenIds()
{
if ($this->isAdmin())
{
return $this->all()->pluck('id')->toArray();
}
$roles = $this->all();
$ids = $this->findChildrenIds($roles, $this->id, 1);
return $ids;
}
function findChildrenIds($roles, $parent_id, $level)
{
$cat_array = [];
for ($c = 0; $c < sizeof($roles); $c ++)
{
if ($roles[ $c ]['parent_id'] == $parent_id)
{
$child_id = $roles[ $c ]->id;
$cat_array[] = $child_id;
$children_array = $this->findChildrenIds($roles, $child_id, $level + 1);
$cat_array = array_merge($cat_array, $children_array);
}
}
return $cat_array;
}
function getRoleSelectTree()
{
//with exception of the admin
//find all roles below users current role
$roles = $this->all();
if (\Config::get('user')->isAdmin())
{
return [[
'name' => $this->name,
'value' => $this->id,
'children' => $this->findChildren($roles, $this->id, 1)
]];
}
return $this->findChildren($roles, $this->id, 1);
}
function findChildren($roles, $parent_id, $level)
{
$cat_array = array();
for ($c = 0; $c < sizeof($roles); $c ++)
{
if ($roles[ $c ]['parent_id'] == $parent_id)
{
$ret_array = [];
$ret_array['value'] = $roles[ $c ]->id;
$ret_array['name'] = $roles[ $c ]->name;
$children = $this->findChildren($roles, $roles[ $c ]->id, $level + 1);
if (sizeof($children) > 0)
{
$ret_array['children'] = $children;
}
$cat_array[] = $ret_array;
}
}
return $cat_array;
}
function getSelectableParents()
{
//take the tree array and delete the node where the id is....
$roles = $this->all();
$tree = $this->findChildren($roles, 0, 1);
//recursively go trough the array and delete....
$trimmed_tree = $this->removeTreeNode($tree, $this->id);
return $trimmed_tree;
}
function removeTreeNode($tree, $id)
{
$cat_array = array();
for ($c = 0; $c < sizeof($tree); $c ++)
{
if ($tree[ $c ]["value"] == $id)
{
//kill this node
//return false;
}
else{
// dd($tree[$c]);
$ret_array = [];
$ret_array['value'] = $tree[ $c ]['value'];
$ret_array['name'] = $tree[ $c ]['name'];
if (isset($tree[$c]['children']))
{
$tmp = $this->removeTreeNode($tree[$c]['children'], $id);
if($tmp){
$ret_array['children'] = $tmp;
}
}
//dd($ret_array);
$cat_array[] = $ret_array;
}
}
return $cat_array;
}
} | true |
06cca9cc86e6e89be651e1f2183d9b23a0c4909c | PHP | fangzesheng/algorithm | /src/Subject/lengthOfLastWord.php | UTF-8 | 904 | 3.765625 | 4 | [] | no_license | <?php
/**
*最后一个单词的长度
*
* @author fzs
* @version 1.0 版本号
*/
namespace Algorithm\Subject;
class lengthOfLastWord
{
/**
* 最后一个单词的长度算法
*
* @access public
* @param string $s 目标值
* @return int
*/
public function achieve($s)
{
if (empty($s)) return 0;
$count = strlen($s);
$len = 0;
for ($i=$count-1;$i>=0;$i--) {
if ($s[$i] != ' ') {
$len++;
}
if ($len !=0 && $s[$i] == ' ') {
break;
}
}
return $len;
}
/**
* thinking
* 最后一个单词的长度算法思路
*
* @access public
* @return string
*/
public function thinking()
{
return <<<EOF
从后往前遍历,有空格且有计算过字符时返回。
EOF;
}
}
| true |
4c7f2f158bac001aaf7d44a2155d99f1e5ffb35e | PHP | tejas1508/Expense-analyzer | /userFunctionalityPages/viewTrendings.php | UTF-8 | 870 | 2.75 | 3 | [] | no_license | <?php
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ip-project";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: ".$conn->connect_error);
}
$sql = "SELECT * FROM trendings";
if($conn->query($sql)){
$result = $conn->query($sql);
}
else {
echo "string".$conn->error;
}
$conn->close();
?>
<div class="card shadow1" id="abcd">
<table class="table">
<tr>
<th>Title</th>
<th>Details</th>
</tr>
<?php while($row = $result->fetch_assoc()) { ?>
<tr>
<td>
<?php echo $row['title']; ?>
</td>
<td>
<?php echo $row['t_description']; ?>
</td>
</tr>
<?php } ?>
</table>
</div>
| true |
84edcdabffc20934e9b198a2ed3e8f365d9d862b | PHP | panos323/testing | /loginRegister/register.php | UTF-8 | 5,829 | 2.59375 | 3 | [] | no_license | <?php include_once "../includes/header.php";?>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
require_once "../functions/db.php";
require_once "../functions/functions.php";
$firstName = htmlspecialchars(trim($_POST["registerName"])) ?? "";
$lastName = htmlspecialchars(trim($_POST["registerLastName"])) ?? "";
$email = htmlspecialchars(trim($_POST["registerEmail"])) ?? "";
$password = htmlspecialchars(trim($_POST["registerPassword"])) ?? "";
$registerCheckbox = isset($_POST['registerCheckbox']) ? 1 : 0;
$firstName = mysqli_real_escape_string($conn, $firstName);
$lastName = mysqli_real_escape_string($conn, $lastName);
$email = mysqli_real_escape_string($conn, $email);
$password = mysqli_real_escape_string($conn, $password);
if (!registerErrors($firstName, $lastName, $email, $password, $registerCheckbox)) {
insertQuery($firstName, $lastName, $email, $password);
}
}
?>
<div class="container">
<div class="row">
<div class="col-md-12 py-5">
<h1 class="text-warning">Register</h1>
</div>
<div class="col-md-7 col-sm-12">
<!-- start form -->
<form method="POST" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
<div class="form-group">
<label for="registerName">First Name</label>
<input type="text" class="form-control" id="registerName" name="registerName" placeholder="First Name" required
value = "<?php if(isset($firstName)){echo $firstName;}?>"
>
<span class='errorValidationMsg'>
<?php
if (isset($_SESSION['fNameError'])) {
echo $_SESSION['fNameError'];
}
?>
</span>
</div>
<div class="form-group">
<label for="registerLastName">First Name</label>
<input type="text" class="form-control" id="registerLastName" name="registerLastName" placeholder="Last Name" required
value = "<?php if(isset($lastName)){echo $lastName;}?>"
>
<span class='errorValidationMsg'>
<?php
if (isset($_SESSION['lNameError'])) {
echo $_SESSION['lNameError'];
}
?>
</span>
</div>
<div class="form-group">
<label for="registerEmail">Email address</label>
<input type="email" class="form-control" id="registerEmail" name="registerEmail" required aria-describedby="emailHelp" placeholder="Enter email"
value = "<?php if(isset($email)){echo $email;}?>"
>
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
<span class='errorValidationMsg'>
<?php
if (isset($_SESSION['emailError'])) {
echo $_SESSION['emailError'];
}
?>
</span>
<span class='errorValidationMsg'>
<?php
if (isset($_SESSION['emailValid'])) {
echo "<br>";
echo $_SESSION['emailValid'];
}
if (isset($_SESSION['emailExist'])) {
echo "<br>";
echo $_SESSION['emailExist'];
}
?>
</span>
</div>
<div class="form-group">
<label for="registerPassword">Password</label>
<input type="password" class="form-control" id="registerPassword" name="registerPassword" placeholder="Password" required
value = "<?php if(isset($password)){echo $password;}?>"
>
<span class='errorValidationMsg'>
<?php
if (isset($_SESSION['pwdError'])) {
echo $_SESSION['pwdError'];
}
?>
</span>
</div>
<div class="form-group form-check">
<input type="checkbox" class="form-check-input" id="registerCheckbox" name="registerCheckbox" required
value = "<?php if(isset($registerCheckbox)){ ?>
checked = "checked" <?php } ?>
>
<label class="form-check-label" for="registerCheckbox">Check me out</label>
<span class='errorValidationMsg'>
<?php
if (isset($_SESSION['checkBoxChecked'])) {
echo $_SESSION['checkBoxChecked'];
}
?>
</span>
</div>
<button name="btnRegister" type="submit" class="btn btn-primary">Submit</button>
</form>
<!-- end form -->
</div>
<div class="col-md-5 col-sm-12">
<img src="../images/para1.jpg" alt="register image" class="img-fluid" style="border-radius:50%;">
</div>
</div>
</div>
<?php include_once "../includes/footer.php";?> | true |
2885d9dc112048b447395c4d2180e3bed922644d | PHP | ambermiao/manage | /inc/class/class_platform.php | UTF-8 | 521 | 2.59375 | 3 | [] | no_license | <?php
class class_platform{
public static function getList(){ //
global $db;
$colname = coderDBConf::$col_platform;
$sql = "select {$colname['name']} as name,{$colname['id']} as value
from ".coderDBConf::$platform."
ORDER BY `{$colname['id']}` DESC";
return $db->fetch_all_array($sql);
}
public static function getName($_val){
$ary = self::getList();
return coderHelp::getArrayPropertyVal($ary, 'value', $_val, 'name');
}
} | true |
f7395dafeaf12030e441ce17a0a722c0e43de1d9 | PHP | octalmage/wib | /php-7.3.0/ext/standard/tests/array/array_map_001.phpt | UTF-8 | 299 | 3.203125 | 3 | [
"BSD-4-Clause-UC",
"BSD-3-Clause",
"LicenseRef-scancode-other-permissive",
"TCL",
"ISC",
"Zlib",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"blessing",
"MIT"
] | permissive | --TEST--
array_map() and exceptions in the callback
--FILE--
<?php
$a = array(1,2,3);
function foo() {
throw new exception(1);
}
try {
array_map("foo", $a, array(2,3));
} catch (Exception $e) {
var_dump("exception caught!");
}
echo "Done\n";
?>
--EXPECT--
string(17) "exception caught!"
Done
| true |
1b9f52eda9baa733600c9bdab7663b574f0102ec | PHP | joelvanpatten/Jtf-Library | /Jtf/BigInt.php | UTF-8 | 4,599 | 3.21875 | 3 | [
"MIT"
] | permissive | <?php
/**
* @category Jtf
*
* @package Jtf_BigInt
*
* @copyright Copyright (C) 2011 Joseph Fallon <joseph.t.fallon@gmail.com>
* All rights reserved.
*
* @license REDISTRIBUTION AND USE IN SOURCE AND BINARY FORMS, WITH OR
* WITHOUT MODIFICATION, IS NOT PERMITTED WITHOUT EXPRESS
* WRITTEN APPROVAL OF THE AUTHOR.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
final class Jtf_BigInt
{
/************************************************************************
* Instance Variables
***********************************************************************/
/* @var string */
private $_value;
/************************************************************************
* Public Methods
***********************************************************************/
/**
* __construct
*
* @param string $value
*/
public function __construct($value)
{
$this->_value = $value;
}
/**
* add
*
* @param Jtf_BigInt $value
* @return Jtf_BigInt
*/
public function add(Jtf_BigInt $value)
{
$result = bcadd($this->_value, $value->_value, 0);
return new Jtf_BigInt($result);
}
/**
* subtract
*
* @param Jtf_BigInt $value
* @return Jtf_BigInt
*/
public function subtract(Jtf_BigInt $value)
{
$result = bcsub($this->_value, $value->_value, 0);
return new Jtf_BigInt($result);
}
/**
* multiply
*
* @param Jtf_BigInt $value
* @return Jtf_BigInt
*/
public function multiply(Jtf_BigInt $value)
{
$result = bcmul($this->_value, $value->_value, 0);
return new Jtf_BigInt($result);
}
/**
* divide
*
* @param Jtf_BigInt $value
* @return Jtf_BigInt
*/
public function divide(Jtf_BigInt $value)
{
$result = bcdiv($this->_value, $value->_value, 0);
return new Jtf_BigInt($result);
}
/**
* modulus
*
* @param Jtf_BigInt $value
* @return Jtf_BigInt
*/
public function modulus(Jtf_BigInt $value)
{
$result = bcmod($this->_value, $value->_value);
return new Jtf_BigInt($result);
}
/**
* compare
*
* This function compares this Jtf_Integer with the provided value. If the
* provided value is greater than this value, then 1 is returned. If the
* provided value is less than this value, -1 is returned. If the provided
* value is equal to the current value, 0 is returned.
*
* Quick Reference:
*
* -1 $this < $value
* 0 $this = $value
* 1 $this > $value
*
* @param Jtf_BigInt $value
*
* @param float $maxDelta - This parameter is the maximum difference
* between the two values. This is because floats are very difficult
* to compare for exactness when equal. Reference the IEEE floating
* point standard.
*/
public function compare(Jtf_BigInt $value)
{
if($this->_value < $value->_value)
{
return -1;
}
else if($this->_value > $value->_value)
{
return 1;
}
return 0;
}
/**
* toString
*
* @return string
*/
public function toString()
{
if($this->_value == 0)
{
return '0';
}
return rtrim($this->_value, '0.');
}
/**
* sprintf
*
* @param string $format
*/
public function sprintf($format)
{
return sprintf($format, $this->toString());
}
}
| true |
6c545fa88b71e53bd5283f16d80d87c538098881 | PHP | kishorhase/magento2-extended-product-repository | /Model/CachedProductRepository.php | UTF-8 | 2,136 | 2.640625 | 3 | [
"MIT"
] | permissive | <?php
namespace SnowIO\ExtendedProductRepository\Model;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Api\Filter;
use Magento\Framework\Api\Search\FilterGroup;
use Magento\Framework\Api\SearchCriteria;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Phrase;
class CachedProductRepository
{
private $productRepository;
private $productsById = [];
private $productsBySku = [];
public function __construct(ProductRepositoryInterface $productRepository)
{
$this->productRepository = $productRepository;
}
public function findBySku(array $skus) : ProductSet
{
$products = $this->getProductsBySku($skus);
$missingSkus = array_diff($skus, array_keys($products));
if (!empty($missingSkus)) {
$additionalProducts = $this->loadProducts('sku', $missingSkus);
foreach ($additionalProducts as $product) {
$this->addProduct($product);
$products[] = $product;
}
}
return new ProductSet($products);
}
/**
* @return ProductInterface[]
*/
private function loadProducts($field, array $idsOrSkus)
{
$searchCriteria = (new SearchCriteria())
->setFilterGroups([
(new FilterGroup)->setFilters([
(new Filter)
->setField($field)
->setConditionType('in')
->setValue($idsOrSkus),
]),
]);
$result = $this->productRepository->getList($searchCriteria);
return $result->getItems();
}
/**
* @return ProductInterface[]
*/
private function getProductsBySku(array $skus)
{
$flippedSkus = array_flip($skus);
return array_intersect_key($this->productsBySku, $flippedSkus);
}
private function addProduct(ProductInterface $product)
{
$this->productsById[$product->getId()] = $product;
$this->productsBySku[$product->getSku()] = $product;
}
}
| true |
b61e6c141da0c82f80c1bf0522a0880e756b267f | PHP | mdoutreluingne/APIDeuxiemeSituation | /tesapi/src/Operation/RecupReservationHandler.php | UTF-8 | 456 | 2.515625 | 3 | [] | no_license | <?php
namespace App\Operation;
use Doctrine\Persistence\ManagerRegistry;
class RecupReservationHandler
{
protected $em;
/**
* RecupReservationHandler constructor.
* @param ManagerRegistry $em
*/
public function __construct(ManagerRegistry $em)
{
$this->em = $em;
}
public function handle($id){
return $this->em->getRepository('App:Reservation')->findByClient($id);
}
} | true |
8fa1b442ab28843385fcabf92eb1415365457845 | PHP | maxprofs-llcio/hal-agent | /tests/src/MemoryLogger.php | UTF-8 | 1,477 | 2.78125 | 3 | [
"MIT"
] | permissive | <?php
/**
* @copyright (c) 2016 Quicken Loans Inc.
*
* For full license information, please view the LICENSE distributed with this source code.
*/
namespace Hal\Agent\Testing;
use ArrayAccess;
use Psr\Log\AbstractLogger;
/**
* A simple logger that stores logs in memory for later analyzation.
*
* Mostly useful for unit testing.
*/
class MemoryLogger extends AbstractLogger implements ArrayAccess
{
/**
* Each entry is an array containing:
* - (string) $level
* - (string) $message
* - (array) $context
*
* @var array
*/
private $messages;
public function __construct()
{
$this->messages = [];
}
/**
* Logs with an arbitrary level.
*
* @param mixed $level
* @param string $message
* @param array $context
* @return null
*/
public function log($level, $message, array $context = array())
{
$this[] = [$level, $message, $context];
}
public function offsetExists($offset)
{
return isset($this->messages[$offset]);
}
public function offsetGet($offset)
{
return $this->messages[$offset];
}
public function offsetSet($offset, $value)
{
if ($offset === null) {
$this->messages[] = $value;
return;
}
$this->messages[$offset] = $value;
}
public function offsetUnset($offset)
{
unset($this->messages[$offset]);
}
}
| true |
759dd4f21f8e83be591fd98b7d0dc1b011a6a01f | PHP | palepoivre/swaterland | /src/SwaterLand/QualiteBundle/Entity/Qualite.php | UTF-8 | 995 | 2.515625 | 3 | [] | no_license | <?php
namespace SwaterLand\QualiteBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Qualite
*
* @ORM\Table()
* @ORM\Entity(repositoryClass="SwaterLand\QualiteBundle\Entity\QualiteRepository")
*/
class Qualite
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="Qualite", type="string", length=255)
*/
private $qualite;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set qualite
*
* @param string $qualite
* @return Qualite
*/
public function setQualite($qualite)
{
$this->qualite = $qualite;
return $this;
}
/**
* Get qualite
*
* @return string
*/
public function getQualite()
{
return $this->qualite;
}
}
| true |
6a2fe40fa7a5cfed01ebdca7004cd39a730df79d | PHP | reidarsets/Web_Sprints | /Sprint07/t07/index.php | UTF-8 | 1,414 | 2.984375 | 3 | [] | no_license | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Data to XML</title>
<style>
table {
border: 1px double gray;
width: 100%;
}
table td {
border: 1px double black;
}
</style>
</head>
<body>
<h1>Data to XML</h1>
<?php
// function autoload($pClassName) {
// include(__DIR__. '/' . $pClassName. '.php');
// }
// spl_autoload_register("autoload");
// $avengerQuote1 = new AvengerQuote(1, "Oleg Savich", "Text", [ "oleg1.jpg", "oleg2.jpg"]);
// $avengerQuote1->addComment("Help");
// $avengerQuote1->addComment("Hate API");
// $avengerQuote2 = new AvengerQuote(2, "Kaneki Ken", "Chel ti", [ "ken.jpg" ]);
// $avengerQuote2->addComment("1000-7");
// $listAvengerQuote = new ListAvengerQuotes();
// $listAvengerQuote->addAvengerQuote($avengerQuote1);
// $listAvengerQuote->addAvengerQuote($avengerQuote2);
// $listAvengerQuote->toXML("file.xml");
// echo '<table><tr><td><pre>';
// print_r($listAvengerQuote);
// echo '</pre></td><td><pre>';
// print_r($listAvengerQuote->fromXML("file.xml"));
// echo '</pre></td></tr></table>';
?>
</body>
</html>
| true |
deed77f00f8589c06a0659885e970c7a4828f2e2 | PHP | j00ml4/joomla-svn-clone | /development/branches/update/libraries/joomla/tasks/taskset.php | UTF-8 | 3,757 | 2.671875 | 3 | [] | no_license | <?php
jimport('joomla.tasks.task');
/**
* A set of tasks
* @since 1.6
*/
class JTaskSet extends JTable {
protected $tasksetid;
protected $tasksetname;
protected $extension_id;
protected $execution_page;
protected $landing_page;
protected $_startTime;
/** Time to run */
protected $run_time;
/** Maximum time to run */
protected $max_time;
/** Percentage Threshold */
protected $threshold = 75;
function __construct(& $database) {
parent::__construct('#__tasksets', 'tasksetid', $database);
$app =& JFactory::getApplication();
$this->_startTime = $app->get('startTime', JProfiler::getmicrotime());
$max_php_run = ini_get('max_execution_time');
if($max_php_run > 0) {
$this->max_time = $max_php_run;
$this->run_time = intval($max_php_run * ($this->threshold / 100));
} else {
// set this to a safe default in case this version of PHP is buggy
$this->max_time = 30;
$this->run_time = 15;
}
}
public function setThreshold($threshold) {
$this->threshold = $threshold;
$this->run_time = intval($this->max_time * ($this->threshold / 100));
}
function & getNextTask() {
$this->_db->setQuery('SELECT taskid FROM #__tasks WHERE tasksetid = '. $this->tasksetid .' ORDER BY taskid LIMIT 0,1');
$taskid = $this->_db->loadResult();// or die('Failed to find next task: ' . $this->db->getErrorMsg());
$false = false;
if(!$taskid) return $false;
$task = new JTask($this->_db, $this);
if($task->load($taskid)) return $task; else return $false; //die('Task '. $taskid .' failed to load:'. print_r($this,1));
}
function listAll() {
$this->_db->setQuery('SELECT taskid FROM #__tasks WHERE tasksetid = '. $this->tasksetid.' ORDER BY taskid');
$results = $this->_db->loadResultArray();
$task = new JTask($this->_db, $this);
foreach ($results as $result) {
$task->load($result);
echo $task->toString();
}
}
function countTasks() {
$this->_db->setQuery('SELECT count(*) FROM #__tasks WHERE tasksetid = '. $this->tasksetid);
return $this->_db->loadResult();
}
function run($callback, &$context=null) {
while($task = $this->getNextTask()) $task->execute($callback, $context);
$app =& JFactory::getApplication();
$this->delete();
if(!$this->landing_page) $this->landing_page = 'index.php';
$app->redirect($this->landing_page);
}
public function &createTask() {
$task = new JTask($this->_db, $this);
$task->set('tasksetid', $this->tasksetid);
return $task;
}
public function addTask($obj) {
$task =& $this->createTask();
$task->store();
$task->setInstance($obj);
$obj->setTask($task);
}
public function load($pid=null) {
$res = parent::load($pid);
if($res) $this->data = unserialize($this->data); // pull the data back out
return $res;
}
public function store($updateNulls=false) {
$this->params = serialize($this->params);
$res = parent::store($updateNulls);
$this->params = unserialize($this->params);
return $res;
}
public function delete( $oid=null )
{
$k = $this->_tbl_key;
if ($oid) {
$this->$k = intval( $oid );
}
$query = 'DELETE FROM '.$this->_db->nameQuote( $this->_tbl ).
' WHERE '.$this->_tbl_key.' = '. $this->_db->Quote($this->$k);
$this->_db->setQuery( $query );
try {
$this->_db->query();
} catch (JException $e) {
$this->setError($e->getMessage());
return false;
}
// Clean up any subtasks just in case
$query = 'DELETE FROM #__tasks WHERE tasksetid = '. $this->_db->Quote($this->$k);
$this->_db->setQuery($query);
try {
$this->_db->query();
return true;
} catch(JException $e) {
$this->setError($e->getMessage());
return false;
}
}
public function redirect() {
$app =& JFactory::getApplication();
$app->redirect($this->landing_page);
}
} | true |
3e196662377a77f5c4cbd699ee5e94a64b8d37bd | PHP | farhan0581/dashboard | /dash.php | UTF-8 | 2,893 | 2.890625 | 3 | [] | no_license | <?php
//php substr(string,start,length);
require_once('database.php');
//this function is to skip any character you want from the csv enteries...
function check_appro($str)
{
for ($i=0; $i<strlen($str); $i++){
if ($str[$i]=="`"){
$str[$i]='';
}
}
return $str;
}
//to read the csv file and insert into the database....
function read_csv($db)
{
$query="INSERT into dishes(did,dname,resturant) values";
$temp=array();
$handle=fopen('sample.csv', 'r');
if(!$handle)
{
echo "error";
}
$temp=fgetcsv($handle);//skip the heading...
while(!feof($handle))
{
$temp=fgetcsv($handle);
$did=$db->mysqlready($temp[0]);
$dname=$db->mysqlready($temp[1]);
$dname=check_appro($dname);
$rest=$db->mysqlready($temp[2]);
$rest=check_appro($rest);
$query.="($did,'$dname','$rest'),";
}
$fquery=substr($query, 0,-1);
$fquery.=";";
$status=$db->query($fquery);
if(!$status)
{
return false;
}
else
{
return true;
}
}
$flag=0;
$query2="SELECT * from dishes where uploaded=0";
$result=$db->query($query2);
$fetched=mysqli_num_rows($result);
if($fetched==0) // means table is empty or all photos are uploaded...
{
$check="SELECT * from dishes";
$check_row=$db->query($check);
$fetched=mysqli_num_rows($check_row);
if($fetched==0)
{
//table is empty
read_csv($db);
$result=$db->query($query2);
}
//all photos are uploaded...
else
{
echo "all photos done...";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>dash board</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h2>Dashboard</h2>
<a href="upload_manual.php">Upload Images Manually...</a>
<table class="table table-hover">
<tr>
<th>Dish</th>
<th>Resturant</th>
<th>Tags</th>
<th>Select Image</th>
<th>Submit</th>
</tr>
<?php
while($rs=mysqli_fetch_array($result))
{
?>
<form action="dash_up_multipe.php" method="post" enctype="multipart/form-data">
<tr>
<td><?php echo $rs['dname']; ?></td>
<td><?php echo $rs['resturant']; ?></td>
<td><input class="form-control" placeholder="tags" name="tags"></td>
<td><input name="upload[]" type="file" value="upload" multiple></td>
<td><input class="btn btn-primary" type="submit" value="submit" name="submit"></td>
<input type="hidden" value="<?php echo $rs['did']; ?>" name="id">
</tr>
</form>
<?php
}
?>
</table>
</div>
</body>
</html>
| true |
894d9110ad44ad4bc49058e6c4fc6419c6060676 | PHP | WBPierre/Veg-N-Bio | /src/LanguageController.php | UTF-8 | 2,129 | 3 | 3 | [
"MIT"
] | permissive | <?php
/*
* Class LanguageController
* Permet de définir la langue utilisé par l'utilisateur, de charger la traduction correspondante, et de la modifier
*/
class LanguageController{
/*
* Récupère les traductions selon la langue
*
* @param $lang
* @return PHP object
*/
private function getFile($lang){
switch($lang){
case 'fr':
$trans = file_get_contents(ROOT.'/translations/'.$lang.'/'.$lang.'_translations.json');
break;
default:
$trans = file_get_contents(ROOT.'/translations/en/en_translations.json');
}
return json_decode($trans);
}
/*
* GETTER Envoie les traductions pour la page demandée
* @param $page
* @return PHP Object
*/
/*
* Commentaire à DELETE :
* public signifie qu'on peut atteindre cette fonction depuis n'importe quelle instance de la classe, directement. Notion de Getter/setter. Dans une classe il y a majoritairement ces 2 types. Getter pour GET, pour obtenir une infos. Setter pour du coup "mettre en place une info", la conserver. L'intérêt de mettre en private est d'éviter tous les affichages des fichiers, ou chemin etc. + boost de sécurité et de propreté comme fonction = 30 lignes max. Ici ce n'est pas une obligation de tout séparer, mais si on met en backoffice un changement de texte ou autre, cela peut être intéressant d'avoir cette fonction déjà faite. Toujours penser à la réutilisation ! On aura beaucoup de classes outils. Du genre celle qui récupère les données bdd, celle qui va faire les vérifs d'un formulaire, qui va mettre en place un formulaire, celle pour la connexion user, tout est imbriqué.
* private signie qu'on ne peut atteindre cette fonction que depuis une instance de la classe.
* static signife qu'on peut appeler simplement cette fonction sans déclarer d'instance de la classe. Pour faire simple, une instance = tableau/structure avec des fonctions et des propriétés.
* self fait référence à la classe dans laquelle on est.
*/
public static function translate($page){
$data = self::getFile($_SESSION['lang']);
return $data->$page;
}
}
| true |
762dec20e959bb4e2e5d86ac8c7a66bbd299164a | PHP | Phil-Thibeault/exercice-10 | /front-page.php | UTF-8 | 1,341 | 2.640625 | 3 | [] | no_license | <?php
/**
* The template for displaying all single posts
*
* @link https://developer.wordpress.org/themes/basics/template-hierarchy/#single-post
*
* @package WordPress
* @subpackage Twenty_Nineteen
* @since 1.0.0
*/
get_header();
?>
//////////FRONT_PAGE.PHP TEST/////////////
<section id="primary" class="content-area">
<main id="main" class="site-main">
<?php
/* Start the Loop */
while ( have_posts() ) :
the_post();
get_template_part( 'template-parts/content/content', 'page' );
// If comments are open or we have at least one comment, load up the comment template.
if ( comments_open() || get_comments_number() ) {
comments_template();
}
endwhile; // End of the loop.
/* The 2nd Query (without global var) */
$args2 = array( 'category_name' => 'evenements' );
$query2 = new WP_Query( $args2 );
if ( $query2->have_posts() ) {
// The 2nd Loop
?>
<div class="wrapper2">
<?php
while ( $query2->have_posts() ) {
$query2->the_post();
//echo '<li>' . get_the_title( $query2->post->ID ) . '</li>';
the_title( sprintf( '<h2 class="entry-title"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h2>' );
}
?>
</div>
<?php
// Restore original Post Data
wp_reset_postdata();
}
?>
</main><!-- #main -->
</section><!-- #primary -->
<?php
get_footer();
| true |
d7a3e33e9584652e9ee300bd901fe6911e868323 | PHP | keeprich/php-pagination-coding | /index.php | UTF-8 | 2,680 | 3 | 3 | [] | no_license | <?php
include_once'dbConnection.php';
// PAGINATION CODING START
if(isset($_GET['page'])){
$page = $_GET['page'];
}else{
$page = 1;
}
// number of pages wishing to display on the browser
$num_per_page = 01;
$start_form = ($page -1) * 01;
// PAGINATION CODING ENDS
// QUERY FOR PAGINATION IN PHP
$query = "SELECT * FROM toys LIMIT $start_form, $num_per_page";
// $query = "SELECT * FROM toys";
$result = mysqli_query($conn, $query);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<title>Pagination</title>
<style>
.btn {
margin:10px;
}
</style>
</head>
<body>
<table class="table table-striped">
<tr>
<td><strong>Product id</strong></td>
<td><strong>Product name</strong></td>
<td><strong>Product code</strong></td>
<td><strong>Product category</strong></td>
<td><strong>Product price</strong></td>
<td><strong>Product stock_count</strong></td>
</tr>
<tr>
<?php
while($row=mysqli_fetch_assoc($result)){
?>
<td> <?php echo $row['id'] ?></td>
<td><?php echo $row['name'] ?></td>
<td><?=$row['code'] ?></td>
<td><?=$row['category'] ?></td>
<td><?=$row['price'] ?></td>
<td><?=$row['stock_count'] ?></td>
</tr>
<?php } ?>
</table>
<!-- PAGINARION CONT. -->
<?php
$pr_query = "SELECT * FROM toys";
$pr_result = mysqli_query($conn, $pr_query);
// CHECKING THE TOTAL NUMBER OF RECORDS
$total_record = mysqli_num_rows($pr_result);
// echo $total_record;
$total_page = ceil($total_record/$num_per_page);
// echo $total_page;
if($page > 1) {
echo "<a href='index.php?page=".($page - 1)."' class='btn btn-danger'>Prev</a>";
}
for($i = 1; $i < $total_page; $i++ ) {
// echo "<a href='index.php?page=".$i."' class='btn btn-primary'>$i</a>";
}
if($i > $page) {
echo "<a href='index.php?page=".($page + 1)."' class='btn btn-danger'>Next</a>";
}
elseif($i = $page) {
echo "<a href='index.php?page=".($page + 1)."' class='btn btn-info'>Submit</a>";
}
?>
<!-- PAGINARION CONT. -->
<!-- echo "<a href="index.php?page=".$i.""></a>" -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
</body>
</html> | true |
ba9639806f28e2368e0f67936ca834ca914e5b6f | PHP | usmanessaadi/spot | /app/Event.php | UTF-8 | 442 | 2.640625 | 3 | [
"MIT"
] | permissive | <?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
class Event extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'title', 'description', 'price', 'duration', 'date', 'featured'
];
public function setDateAttribute($value)
{
$this->attributes['date'] = (new Carbon($value))->format('d/m/y');
}
}
| true |
87d272aaad10f563b83f3e69a6b26cc77ac53437 | PHP | SuzanneSoy/2010-moteur-site-simple | /__cms__/code/modules/site/site-index.php | UTF-8 | 2,632 | 2.640625 | 3 | [] | no_license | <?php
class SiteIndex {
public static function action($chemin, $action, $paramètres) {
if (isset($paramètres["nom_site"])) {
Stockage::set_prop($chemin, "nom_site", $paramètres["nom_site"]);
}
if (isset($paramètres["prochain_evenement"])) {
Stockage::set_prop($chemin, "prochain_evenement", $paramètres["prochain_evenement"]);
}
if (isset($paramètres["description"])) {
Stockage::set_prop($chemin, "description", $paramètres["description"]);
}
if (isset($paramètres["vue"])) {
return self::vue($chemin, $paramètres["vue"]);
} else {
return self::vue($chemin);
}
}
public static function vue($chemin, $vue = "normal") {
if ($vue == "normal") {
$ret = '';
$ret .= '<div class="prochain-evenement">';
$ret .= '<h2>Prochain évènement</h2>';
if (Permissions::vérifier_permission($chemin, "set_prop", Authentification::get_utilisateur())) {
$ret .= '<form method="post" action="' . $chemin->get_url() . '">';
$ret .= formulaire_édition_texte_enrichi(Stockage::get_prop($chemin, "prochain_evenement"), "prochain_evenement");
$ret .= '<p><input type="submit" value="appliquer" /></p>';
$ret .= '</form>';
} else {
$ret .= Stockage::get_prop($chemin, "prochain_evenement");
}
$ret .= '</div>';
$ret .= '<div class="description-site">';
if (Permissions::vérifier_permission($chemin, "set_prop", Authentification::get_utilisateur())) {
$ret .= '<form class="nom_site infos" method="post" action="' . $chemin->get_url() . '">';
$ret .= '<h2><input type="text" name="nom_site" value="' . Stockage::get_prop($chemin, "nom_site") . '" /></h2>';
$ret .= '<p><input type="submit" value="appliquer" /></p>';
$ret .= '</form>';
} else {
$ret .= "<h2>" . Stockage::get_prop($chemin, "nom_site") . "</h2>";
}
if (Permissions::vérifier_permission($chemin, "set_prop", Authentification::get_utilisateur())) {
$ret .= '<form method="post" action="' . $chemin->get_url() . '">';
$ret .= formulaire_édition_texte_enrichi(Stockage::get_prop($chemin, "description"), "description");
$ret .= '<p><input type="submit" value="appliquer" /></p>';
$ret .= '</form>';
} else {
$ret .= Stockage::get_prop($chemin, "description");
}
$ret .= '</div>';
return new Page($ret, Stockage::get_prop($chemin, "nom_site"));
} else if ($vue == "css") {
return new Page(get_css(), "text/css", "raw");
}
return new Page('',''); // TODO : devrait renvoyer une page d'erreur !
}
}
Modules::enregister_module("SiteIndex", "site-index", "vue", "nom_site prochain_evenement description");
?> | true |
742f9c2330c5ed26bab8568582c33ad003c315a3 | PHP | marcelofuchs/slim_microservices | /Application/Administracao/Http/Actions/Empresas/EmpresaCreate.php | UTF-8 | 878 | 2.65625 | 3 | [] | no_license | <?php
namespace Application\Administracao\Http\Actions\Empresas;
use Application\Administracao\Contracts\Commands\Empresas\EmpresaCreateInterface;
use Domain\Abstractions\AbstractAction;
use Psr\Http\Message\ResponseInterface as Response;
use Slim\Http\Request;
/**
* Action Create
*/
class EmpresaCreate extends AbstractAction
{
/**
* Invoke
*
* @param Request $request
* @param Response $response
* @param array $args
* @return mixed
*/
public function process(Request $request, Response $response, $args = [])
{
$data = $request->getParsedBody() ?? [];
/** @var EmpresaCreateInterface $command */
$command = $this->container->get(EmpresaCreateInterface::class)::fromArray($data);
$this->commandBus->dispatch($command);
return $response->withJson($command->toArray(), 201);
}
}
| true |
406affa139fabdd6db4ed846c364a5ee5d887431 | PHP | gitdestroy/adminLT | /src/org/fmt/controller/SessionController.php | UTF-8 | 2,902 | 2.65625 | 3 | [] | no_license | <?php
namespace org\fmt\controller;
use Exception;
use NeoPHP\web\http\Response;
use NeoPHP\web\WebController;
use org\fmt\manager\UsersManager;
use org\fmt\view\ForgetfulnessPasswordView;
use stdClass;
/**
* @route (path="session")
*/
class SessionController extends WebController
{
/**
* @routeAction (method="PUT")
*/
public function createSession ($username, $password)
{
$response = new Response();
$responseObject = new stdClass();
try
{
$this->getSession()->destroy();
$sessionId = false;
$user = UsersManager::getInstance()->getUserByUsernameAndPassword($username, $password);
if (!empty($user) )
{
$this->getSession()->start();
$this->getSession()->sessionId = session_id();
$this->getSession()->sessionName = session_name();
$this->getSession()->userId = $user->getId();
$this->getSession()->firstname = $user->getFirstname();
// $this->getSession()->lastname = $user->getLastname();
// $this->getSession()->type = $user->getType()->getId();
$responseObject->success = true;
$responseObject->sessionId = $this->getSession()->getId();
$response->setContent(json_encode($responseObject));
}
else
{
$responseObject->success = false;
$responseObject->errorMessage = "Nombre de usuario o contraseña incorrecta";
$response->setStatusCode(401);
$response->setContent(json_encode($responseObject));
}
}
catch (Exception $ex)
{
$responseObject->success = false;
$responseObject->errorMessage = $ex->getMessage();
$response->setStatusCode(500);
$response->setContent(json_encode($responseObject));
}
return $response;
}
/**
* @routeAction (action="reset",method="GET")
*/
public function forgetfulnessPassword($email){
$view = new ForgetfulnessPasswordView();
if ( !empty($email) ) {
$hashUpdate = UsersManager::getInstance()->setUserHash($email);
$body = '';
$notification = new SMTPMailer();
$notification->addRecipient($email);
$notification->setFrom("\"Fuenn.com\" <notifications@fuenn.com>");
$notification->setSubject('Blanque de contraseña');
$notification->setMessage($body);
$notification->send();
$view->setMessage('El email no pertenece a nuestra base de datos');
}
return $view;
}
}
?> | true |
2ca0dce0358d55c14b4c01b01041c324f933c146 | PHP | isamukhtarov/symfony_project | /src/Ria/Bundle/PostBundle/Messenger/Message/PostUpdated.php | UTF-8 | 555 | 2.65625 | 3 | [] | no_license | <?php
declare(strict_types=1);
namespace Ria\Bundle\PostBundle\Messenger\Message;
use Ria\Bundle\PostBundle\Dto\PlainPostDto;
class PostUpdated
{
public function __construct(
private int $postId,
private int $userId,
private PlainPostDto $plainPostDto,
){}
public function getPostId(): int
{
return $this->postId;
}
public function getUserId(): int
{
return $this->userId;
}
public function getPlainPostDto(): PlainPostDto
{
return $this->plainPostDto;
}
} | true |
2d454c9bf5df25654d58eaba2cbb3940fd3f3c40 | PHP | rgattermann/course-alura-tdd-php | /tests/LeilaoTest.php | UTF-8 | 2,728 | 2.890625 | 3 | [] | no_license | <?php
namespace App\tests;
use App\Leilao;
use App\Lance;
use App\Usuario;
use PHPUnit\Framework\TestCase;
class LeilaoTest extends TestCase
{
public function testDeveReceberUmLance()
{
$leilao = new Leilao("Macbook Pro 15");
$this->assertEquals(0, count($leilao->getLances()));
$leilao->propoe(new Lance(new Usuario("Steve Jobs"), 2000));
$this->assertEquals(1, count($leilao->getLances()));
$this->assertEquals(2000, $leilao->getLances()[0]->getValor(), 0.00001);
}
public function testDeveReceberVariosLances()
{
$leilao = new Leilao("Macbook Pro 15");
$leilao->propoe(new Lance(new Usuario("Steve Jobs"), 2000));
$leilao->propoe(new Lance(new Usuario("Steve Wozniak"), 3000));
$this->assertEquals(2, count($leilao->getLances()));
$this->assertEquals(2000, $leilao->getLances()[0]->getValor(), 0.00001);
$this->assertEquals(3000, $leilao->getLances()[1]->getValor(), 0.00001);
}
public function testDeveProporUmLance()
{
$leilao = new Leilao('Macbook caro');
$this->assertEquals(0, count($leilao->getLances()));
$joao = new Usuario('João');
$leilao->propoe(new Lance($joao, 2000));
$this->assertEquals(1, count($leilao->getLances()));
$this->assertEquals(2000, $leilao->getLances()[0]->getValor());
}
public function testDeveBarrarDoisLancesSeguidos()
{
$leilao = new Leilao('Macbook caro');
$joao = new Usuario('João');
$leilao->propoe(new Lance($joao, 2000));
$leilao->propoe(new Lance($joao, 3000));
$this->assertEquals(1, count($leilao->getLances()));
$this->assertEquals(2000, $leilao->getLances()[0]->getValor());
}
public function testDeveDarNoMaximo5Lances()
{
$leilao = new Leilao('Notebook dell');
$jobs = new Usuario('Jobs');
$gates = new Usuario('Gates');
$leilao->propoe(new Lance($jobs, 2000));
$leilao->propoe(new Lance($gates, 2100));
$leilao->propoe(new Lance($jobs, 2200));
$leilao->propoe(new Lance($gates, 2300));
$leilao->propoe(new Lance($jobs, 2400));
$leilao->propoe(new Lance($gates, 2500));
$leilao->propoe(new Lance($jobs, 2600));
$leilao->propoe(new Lance($gates, 2700));
$leilao->propoe(new Lance($jobs, 2800));
$leilao->propoe(new Lance($gates, 3000));
$leilao->propoe(new Lance($jobs, 3100));
$this->assertEquals(10, count($leilao->getLances()));
$ultimo = count($leilao->getLances()) - 1;
$ultimoLance = $leilao->getLances()[$ultimo];
$this->assertEquals(3000, $ultimoLance->getValor(), 0.00001);
}
} | true |
7c0f5434fb11b9c16eae3772059e937a37a4b7b2 | PHP | ProfoundFerret/Fish | /fish/libs/CacheControl.php | UTF-8 | 696 | 2.84375 | 3 | [] | no_license | <?
class CacheControl
{
static function fileLocation($file)
{
$file = 'fish/cache/' . $file;
return $file;
}
static function cacheUpToDate($file)
{
$cache = self::fileLocation($file);
$fileTime = filemtime($file);
if (file_exists($cache))
{
$cacheTime = filemtime($cache);
} else {
$cacheTime = 0;
}
return ($fileTime <= $cacheTime);
}
static function writeFile($file, $contents)
{
$file = self::fileLocation($file);
$dirname = dirname($file);
if (! file_exists($dirname))
{
$old = umask(0);
mkdir($dirname, 0777, true);
umask($old);
}
if (file_exists($file)) chmod($file, 0777);
file_put_contents($file,$contents,LOCK_EX);
}
}
?>
| true |
8f21f22e39fa9e7937b7a4a3d3f44909e99b22e1 | PHP | killbus/jd-kepler | /kepler/src/Api/Goods/JdKeplerXuanPinSkuPromotionBatch.php | UTF-8 | 741 | 2.828125 | 3 | [] | no_license | <?php
/**
* 批量获取sku推广信息
* User: smallsea
* Date: 2018/8/17
* Time: 17:43
*/
namespace Jd\Kepler\Api\Goods;
use Jd\Kepler\KeplerBase;
class JdKeplerXuanPinSkuPromotionBatch extends KeplerBase
{
/**
* 批量获取sku推广信息
* @var int|int[]
*/
protected $skuIds;
/**
* @return int|int[]
*/
public function getSkuIds()
{
return $this->skuIds;
}
/**
* @param int|int[] $skuIds
*/
public function setSkuIds($skuIds): void
{
$this->skuIds = $skuIds;
}
/**
* 接口方法
* @return string
*/
public function getApiMethod(): string
{
return 'jd.kepler.xuanpin.sku.promotion.batch';
}
} | true |
ad5d60888d92d5c7c0f59ec59ba3026a0978f984 | PHP | kenichi0126/laravel_clean_arch | /packages/Smart2/src/Application/Validation/ParameterValidator.php | UTF-8 | 1,404 | 3.203125 | 3 | [] | no_license | <?php
namespace Smart2\Application\Validation;
class ParameterValidator
{
/**
* バイト数チェック.
*
* 半角1バイト、全角2バイトで計算し、
* 指定した値を超過している場合はエラーとする。
*
* @param $attribute
* @param $value
* @param $parameters
* @return bool
*/
public function validateStrLenOver($attribute, $value, $parameters)
{
$num = $parameters[0];
// パラメータが不正の場合は強制的にエラー
if (!isset($num) && ctype_digit($num)) {
return false;
}
$num = (int) $num;
// 指定のバイト数を超えている場合はエラー
if ($num < strlen(mb_convert_encoding($value, 'SJIS', 'UTF-8'))) {
return false;
}
return true;
}
/**
* カンマかダブルクォート含みチェック.
*
* カンマかダブルクォートがパラメータに含まれている場合はエラーとする。
*
* @param $attribute
* @param $value
* @param $parameters
* @return bool
*/
public function validateStrInCommaOrDoublequote($attribute, $value, $parameters)
{
if (strpos($value, ',') !== false
|| strpos($value, '"') !== false) {
return false;
}
return true;
}
}
| true |
9e858db733efd988f04ba344e8c5f4a91292b93d | PHP | imacuchc/PHP-y-MySQL | /test.php | UTF-8 | 165 | 2.6875 | 3 | [] | no_license | <html>
<head>
<title>Prueba PHP</title>
</head>
<body>
<p>Esto es una linea HTML<P>
<?php
echo "Esto es una linea PHP";
phpinfo();
?>
</body>
</html> | true |
1fb6cb4237fad582007660aa7e14d60b0342e49d | PHP | sydboys/extension-point-api | /src/Cloud/Extension/Param/Dto/CheckinSelectPrizeDTO.php | UTF-8 | 738 | 2.53125 | 3 | [
"MIT"
] | permissive | <?php
namespace Com\Youzan\Cloud\Extension\Param\Dto;
/**
* {}
* @author Baymax
* @create 2021-06-28 23:33:49.0
*/
class CheckinSelectPrizeDTO implements \JsonSerializable {
/**
* 选出的奖品id列表
* @var array
*/
private $selectedPrizeConfigId;
/**
* @return array
*/
public function getSelectedPrizeConfigId(): ?array
{
return $this->selectedPrizeConfigId;
}
/**
* @param array $selectedPrizeConfigId
*/
public function setSelectedPrizeConfigId(?array $selectedPrizeConfigId): void
{
$this->selectedPrizeConfigId = $selectedPrizeConfigId;
}
public function jsonSerialize() {
return get_object_vars($this);
}
} | true |
3ebd3980582dafda32d62742f33ba46d9270236d | PHP | ncsuwebdev/otframework | /library/Ot/Auth/Adapter/Wrap.php | UTF-8 | 4,690 | 2.59375 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
/**
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
*
* This license is also available via the world-wide-web at
* http://itdapps.ncsu.edu/bsd.txt
*
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to itappdev@ncsu.edu so we can send you a copy immediately.
*
* @package Ot_Auth_Adapter_Wrap
* @category Authentication Adapter
* @copyright Copyright (c) 2007 NC State University Office of
* Information Technology
* @license http://itdapps.ncsu.edu/bsd.txt BSD License
* @version SVN: $Id: $
*/
/**
* This adapter users the WRAP authentication mechanism that is provided on campus
* webservers at NC State. The default username and password passed to the constructor
* are blank because WRAP handles the kerberos authentication to ensure the user is
* an NCSU user.
*
* @package Ot_Auth_Adapter_Wrap
* @category Authentication Adapter
* @copyright Copyright (c) 2007 NC State University Office of
* Information Technology
*/
class Ot_Auth_Adapter_Wrap implements Zend_Auth_Adapter_Interface, Ot_Auth_Adapter_Interface
{
/**
* Username of the user to authenticate
*
* @var string
*/
protected $_username = '';
/**
* Password of the user to authenticate
*
* @var string
*/
protected $_password = '';
/**
* Constant for default username for auto-login
*
*/
const defaultUsername = '';
/**
* Constant for default password for auto-login
*
*/
const defaultPassword = '';
/**
* Constructor to create new object
*
* @param string $username
* @param string $password
*/
public function __construct($username = self::defaultUsername, $password = self::defaultPassword)
{
$this->_username = $username;
$this->_password = $password;
}
/**
* Authenticates the user passed by the constructor, however in this case we
* user the WRAP server variable "WRAP_USERID" to get this appropriate username.
*
* @return new Zend_Auth_Result object
*/
public function authenticate()
{
$username = (getenv('WRAP_USERID') == '') ? getenv('REDIRECT_WRAP_USERID') : getenv('WRAP_USERID');
if ($username == '') {
$username = getenv('REDIRECT_WRAP_USERID');
}
if ($username == '') {
setrawcookie('WRAP_REFERER', $this->_getUrl(), 0, '/', '.ncsu.edu');
header('location:https://webauth.ncsu.edu/wrap-bin/was16.cgi');
die();
}
if (strtolower($username) == 'guest') {
$this->autoLogout();
return new Zend_Auth_Result(
false,
new stdClass(),
array('Guest access is not allowed for this application')
);
}
$class = new stdClass();
$class->username = $username;
$class->realm = 'wrap';
return new Zend_Auth_Result(true, $class, array());
}
/**
* Gets the current URL
*
* @return string
*/
protected function _getURL()
{
$s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
$protocol = substr(
strtolower($_SERVER["SERVER_PROTOCOL"]), 0, strpos(strtolower($_SERVER["SERVER_PROTOCOL"]), "/")
) . $s;
$port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
return $protocol."://".$_SERVER['SERVER_NAME'].$port.$_SERVER['REQUEST_URI'];
}
/**
* Setup this adapter to autoLogin
*
* @return boolean
*/
public static function autoLogin()
{
return true;
}
/**
* Logs the user out by removing all the WRAP cookies that are created.
*
*/
public static function autoLogout()
{
foreach (array_keys($_COOKIE) as $name) {
if (preg_match('/^WRAP.*/', $name)) {
// Set the expiration date to one hour ago
setcookie($name, "", time() - 3600, "/", "ncsu.edu");
}
}
}
/**
* Flag to tell the app where the authenticaiton is managed
*
* @return boolean
*/
public static function manageLocally()
{
return false;
}
/**
* flag to tell the app whether a user can sign up or not
*
* @return boolean
*/
public static function allowUserSignUp()
{
return false;
}
} | true |
6f554419e8a6bb7234fc8f0b59ed161c28959a2f | PHP | aKolsi/AjaxNotificationGoMyCode | /src/AppBundle/Entity/Ville.php | UTF-8 | 1,272 | 2.59375 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: Kolsi Ahmed
* Date: 08/07/2017
* Time: 09:49
*/
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\Table(name="ville")
*/
class Ville
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="string",length=255)
*/
private $nom;
/**
* @ORM\Column(type="string",length=255, nullable=true)
*/
private $code;
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* @return mixed
*/
public function getNom()
{
return $this->nom;
}
/**
* @param mixed $nom
*/
public function setNom($nom)
{
$this->nom = $nom;
}
/**
* @return mixed
*/
public function getCode()
{
return $this->code;
}
/**
* @param mixed $code
*/
public function setCode($code)
{
$this->code = $code;
}
} | true |
ccd39cb84ffcd6904792a0f2536bdf3746fb69b6 | PHP | Seifyuuu/Laravel | /8) CRUD/exoCreateStore1/app/Http/Controllers/PokemonController.php | UTF-8 | 634 | 2.625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers;
use App\Models\Pokemon;
use Illuminate\Http\Request;
class PokemonController extends Controller
{
public function index(){
$data = Pokemon::all();
return view("welcome", compact("data"));
}
public function create(){
return view("boom");
}
public function store(Request $request){
$newEntry = new Pokemon;
$newEntry->name = $request->name;
$newEntry->type = $request->type;
$newEntry->level= $request->level;
$newEntry->save();
// return redirect() -> back();
return redirect ("/");
}
}
| true |
40b075ee4a2e158519bd7056e61f0941404bb0c9 | PHP | QinShangQs/training | /training/Apps/Admin/Repository/BaseRepository.class.php | UTF-8 | 863 | 2.890625 | 3 | [] | no_license | <?php
namespace Admin\Repository;
class BaseRepository {
/**
* 产品经理
* @var unknown
*/
const PRO_PRODUCT = 1;
/**
* UI讲师
* @var unknown
*/
const PRO_UI = 2;
public static function getProfileName($profile_id){
switch ($profile_id){
case 1:
return "产品经理";
case 2:
return "UI设计师";
default:
return "";
}
}
protected static function format($datas, $single=false){
if($single){
if(array_key_exists('profile_id', $datas)){
$datas['profile'] = static::getProfileName($datas['profile_id']);
}
}else{
foreach ($datas as $key=> $val){
if(array_key_exists('profile_id', $val)){
$datas[$key]['profile'] = static::getProfileName($val['profile_id']);
}
}
}
return $datas;
}
} | true |
cd609b35b4d81713f39623fbb4380d4a9e4d116c | PHP | jeevangnanam/Mihinlanka | /app/controllers/survey_questions_controller.php | UTF-8 | 5,915 | 2.578125 | 3 | [] | no_license | <?php
class SurveyQuestionsController extends AppController {
var $name = 'SurveyQuestions';
var $scaffold;
function take() {
$this->banner ="one";
$this->set('surveyUserName',$this->Session->read('survey_user_name'));
if(!$this->Session->check('survey_user_id')){
$this->redirect('/survey_users/add');
}else{
$userId = $this->Session->read('survey_user_id');
}
$answer = NULL;
$allDone = NULL;
if (!empty($_POST)) {
//debug($_POST);die();
for($a=1;$a<9;$a++){
if($a == 1){
if($_POST['how_did_you_know_mihin_web'] == '' and !isset($_POST['1'])){
$error[] = "Please put, how did you get to know of Mihin Lanka.";
}
}
if($a == 2){
if(!isset($_POST['2'])){
$error[] = "Please put, your main objective of visiting the Mihin Lanka Website.";
}
}
if($a == 6){
if($_POST['main_reason_of_your_travel'] == '' and !isset($_POST['6'])){
$error[] = "Please put, your main reason of your travel.";
}
}
if($a == 7){
if($_POST['what_made_to_choose_mihinlanka'] == '' and !isset($_POST['7'])){
$error[] = "Please put, what made you choose mihinlanka.";
}
}
}
if(isset($error)){
$displayError = NULL;
foreach($error as $err){
$displayError .= "<li>".$err."</li>";
}
$this->set('error',$displayError);
$allDone = false;
}else{
$allDone = true;
}
if($allDone)
for($i=1;$i<9;$i++){
if($i == 1){
if($_POST['how_did_you_know_mihin_web'] != ''){
$answer = $_POST['how_did_you_know_mihin_web'];
}else{
if(!isset($_POST['1'])){
$error[] = "Please put how did you get to know of Mihin Lanka.";
}else{
foreach($_POST['1'] as $answers){
$answer .= $answers.",";
}
}
}
}
if($i == 2){
if(!isset($_POST['2'])){
$error[] = "Please put your main objective of visiting the Mihin Lanka Website.";
}else{
foreach($_POST['2'] as $answers){
$answer .= $answers.",";
}
}
}
if($i == 3){
$answer = $_POST['3'];
}
if($i == 4){
$answer = $_POST['4'];
}
if($i == 5){
if(isset($_POST['5'])){
$answer = $_POST['5'];
}else{
$answer = NULL;
}
}
if($i == 6){
if($_POST['main_reason_of_your_travel'] != ''){
$answer = $_POST['main_reason_of_your_travel'];
}else{
if(!isset($_POST['6'])){
$error[] = "Please put your main reason of your travel.";
}else{
foreach($_POST['6'] as $answers){
$answer .= $answers.",";
}
}
}
}
if($i == 7){
if($_POST['what_made_to_choose_mihinlanka'] != ''){
$answer = $_POST['what_made_to_choose_mihinlanka'];
}else{
if(!isset($_POST['7'])){
$error[] = "Please put what made you choose mihinlanka.";
}else{
foreach($_POST['7'] as $answers){
$answer .= $answers.",";
}
}
}
}
if($i == 8){
$answer = $_POST['8'];
}
if($i == 9){
if(isset($_POST['9'])){
$answer = $_POST['9'];
}else{
$answer = NULL;
}
}
if(!isset($error)){
$answer = mysql_real_escape_string(strip_tags($answer));
$query = "insert into survey_answers values(NULL,$userId,$i,'$answer')";
$answer = NULL;
$answers = NULL;
$this->SurveyQuestion->query($query);
$allDone = true;
}else{
$this->set('error',$error[0]);
$allDone = false;
}
}
if($allDone)
$this->redirect('/survey_questions/thankyou');
}
}
function thankyou(){
$this->Session->delete('survey_user_id');
}
}
?> | true |
67287260fedd220b70a64f2475f4e8f6ef343fec | PHP | iggyvolz/class-properties-conditions | /tests/GreaterThanTest.php | UTF-8 | 931 | 2.828125 | 3 | [
"MIT"
] | permissive | <?php
namespace iggyvolz\ClassProperties\tests;
use PHPUnit\Framework\TestCase;
use iggyvolz\ClassProperties\Conditions\GreaterThan;
use iggyvolz\ClassProperties\Conditions\ConditionException;
class GreaterThanTest extends TestCase
{
public function testGreaterThan():void
{
$this->assertTrue(true);
$condition = new GreaterThan(6);
$condition->check(8);
}
public function testGreaterThanErrors():void
{
$this->expectException(ConditionException::class);
$this->expectExceptionMessage("6 is not greater than 8");
$condition = new GreaterThan(8);
$condition->check(6);
}
public function testComparisonInvalidInput():void
{
$this->expectException(ConditionException::class);
$this->expectExceptionMessage("Invalid type array, needed int|float");
$condition = new GreaterThan(8);
$condition->check([]);
}
}
| true |
fc4be03c704a99a74cc988e88d2c1f1a9d5aee43 | PHP | busyphp/busyphp | /src/app/admin/model/system/file/SystemFile.php | UTF-8 | 7,805 | 2.53125 | 3 | [
"Apache-2.0"
] | permissive | <?php
namespace BusyPHP\app\admin\model\system\file;
use BusyPHP\App;
use BusyPHP\exception\VerifyException;
use BusyPHP\exception\SQLException;
use BusyPHP\helper\file\File;
use BusyPHP\model;
use BusyPHP\helper\util\Transform;
/**
* 文件管理模型
* @author busy^life <busy.life@qq.com>
* @copyright 2015 - 2017 busy^life <busy.life@qq.com>
* @version $Id: 2017-05-30 下午7:38 SystemFile.php busy^life $
*/
class SystemFile extends Model
{
//+--------------------------------------
//| 文件类型
//+--------------------------------------
/** 图片 */
const FILE_TYPE_IMAGE = 'image';
/** 视频 */
const FILE_TYPE_VIDEO = 'video';
/** 附件 */
const FILE_TYPE_FILE = 'file';
//+--------------------------------------
//| 其它
//+--------------------------------------
/** 临时附件前缀 */
const MARK_VALUE_TMP_PREFIX = 'tmp_';
/**
* 获取附件信息
* @param int $id
* @return array
* @throws SQLException
*/
public function getInfo($id)
{
return parent::getInfo(floatval($id), '附件不存在');
}
/**
* 执行添加
* @param SystemFileField $insert
* @return int
* @throws SQLException
*/
public function insertData($insert)
{
$insert->createTime = time();
$insert->urlHash = md5($insert->url);
if (!$insertId = $this->addData($insert)) {
throw new SQLException('插入附件记录失败', $this);
}
return $insertId;
}
/**
* 通过临时文件标识转正
* @param string $type 文件分类
* @param string $tmp 临时文件分类值
* @param string $value 新文件分类值
* @throws SQLException
*/
public function updateMarkValueByTmp($type, $tmp, $value)
{
$where = SystemFileField::init();
$where->markType = trim($type);
$where->markValue = trim($tmp);
$save = SystemFileField::init();
$save->markValue = trim($value);
if (false === $result = $this->whereof($where)->saveData($save)) {
throw new SQLException('修正附件标识失败', $this);
}
}
/**
* 通过文件ID转正
* @param string $type 文件分类
* @param int $id 附件ID
* @param string $value 新文件分类值
* @throws SQLException
*/
public function updateMarkValueById($type, $id, $value)
{
$where = SystemFileField::init();
$where->markType = trim($type);
$where->id = floatval($id);
$save = SystemFileField::init();
$save->markValue = trim($value);
if (false === $this->whereof($where)->saveData($save)) {
throw new SQLException('修正附件标识失败', $this);
}
}
/**
* 通过文件分类标识获取文件地址
* @param string $markType
* @param string $markValue
* @return string
* @throws SQLException
*/
public function getUrlByMark($markType, $markValue)
{
$where = SystemFileField::init();
$where->markType = trim($markType);
$where->markValue = trim($markValue);
$url = $this->whereof($where)->getField('url');
if (!$url) {
throw new SQLException('附件不存在', $this);
}
return $url;
}
/**
* 通过ID获取文件地址
* @param $id
* @return string
* @throws SQLException
*/
public function getUrlById($id)
{
$url = $this->one($id)->getField('url');
if (!$url) {
throw new SQLException('附件不存在', $this);
}
return $url;
}
/**
* 执行删除
* @param int $id
* @return int
* @throws VerifyException
* @throws SQLException
*/
public function del($id)
{
$fileInfo = $this->getInfo($id);
$filePath = App::urlToPath($fileInfo['url']);
$res = parent::del($id);
if (is_file($filePath) && !unlink($filePath)) {
throw new VerifyException('无法删除附件', $filePath);
}
return $res;
}
/**
* 通过附件地址删除附件
* @param string $url 附件地址
* @throws VerifyException
* @throws SQLException
*/
public function delByUrl($url)
{
if (!$url) {
return;
}
$where = SystemFileField::init();
$where->urlHash = md5(trim($url));
if (false === $this->whereof($where)->deleteData()) {
throw new SQLException('删除附件记录失败', $this);
}
$filePath = App::urlToPath($url);
if (is_file($filePath) && !unlink($filePath)) {
throw new VerifyException('无法删除附件', $filePath);
}
}
/**
* 通过附件标识删除附件
* @param string $markType 标识类型
* @param string|null $markValue 标识值
* @throws SQLException
* @throws VerifyException
*/
public function delByMark($markType, $markValue = null)
{
$where = SystemFileField::init();
$where->markType = trim($markType);
if ($markValue) {
$where->markValue = trim($markValue);
}
$fileInfo = $this->whereof($where)->findData();
if (!$fileInfo) {
return;
}
if (false === $this->deleteData($fileInfo['id'])) {
throw new SQLException('删除附件记录失败', $this);
}
$filePath = App::urlToPath($fileInfo['url']);
if (is_file($filePath) && !unlink($filePath)) {
throw new VerifyException('无法删除附件', $filePath);
}
}
/**
* 获取附件类型
* @param null|string $var
* @return array|mixed
*/
public static function getTypes($var = null)
{
$array = [
self::FILE_TYPE_IMAGE => '图片',
self::FILE_TYPE_VIDEO => '视频',
self::FILE_TYPE_FILE => '附件',
];
if (is_null($var)) {
return $array;
}
return $array[$var];
}
/**
* 创建唯一临时文件标识
* @param null|string $value
* @return string
*/
public static function createTmpMarkValue($value = null)
{
return self::MARK_VALUE_TMP_PREFIX . md5(($value ? $value : uniqid()) . $_SERVER['HTTP_USER_AGENT'] . request()->ip() . rand(1000000, 9999999));
}
/**
* 解析数据列表
* @param array $list
* @return array
*/
public static function parseList($list)
{
return parent::parseList($list, function($list) {
foreach ($list as $i => $r) {
$r['classify_name'] = self::getTypes($r['classify']);
$r['format_create_time'] = Transform::date($r['create_time']);
$r['is_admin'] = Transform::dataToBool($r['is_admin']);
$sizes = Transform::formatBytes($r['size'], true);
$r['size_unit'] = $sizes['unit'];
$r['size_num'] = $sizes['number'];
$r['format_size'] = "{$r['size_num']} {$r['size_unit']}";
$r['filename'] = File::pathInfo($r['url'], PATHINFO_BASENAME);
$list[$i] = $r;
}
return $list;
});
}
} | true |
f8b2e9bb2a8983aed905849ea5683d9c2cfe5631 | PHP | mehta-shreyas/Birthday-Reminder | /findContact.php | UTF-8 | 3,408 | 2.578125 | 3 | [] | no_license | <?php
session_start();
$nameresult="";
$noneFoundError="";
if ($_SERVER['REQUEST_METHOD'] == "POST" && strlen($_POST['contactname']) > 0)
{
require("load_user_db.php");
$contact = trim($_POST['contactname']);
$user=$_SESSION['user'];
$query = "SELECT * FROM $user WHERE Name='$contact'";
//$query = "SELECT * FROM loganhylton99 WHERE Name='$contact'";
$statement = $db->prepare($query);
$statement->execute();
$result = $statement->fetch();
$statement->closeCursor();
//if name found in db
if (strlen($result['Name']) > 0){
$nameresult=$result['Name'];
$noneFoundError="";
$_SESSION['contactname'] = $nameresult;
header('Location: modExisting.php');
}else{
$noneFoundError="<br>Could not find contact with name \"".$contact."\" in your contact book. <br> Please search again or click \"Add New Birthday\" to create a new contact";
}
}
?>
<!DOCTYPE html>
<!-- Used Bootstrap documentation as source -->
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Find Contact</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" />
<style>
.error{color: red; font-style: italic; padding: 5px;}
.nav-link {
color: white;
}
.col-md-auto{font-size: 30px;}
.col-lg-2{font-size: 24px;}
.col-lg-4{font-size: 24px;}
/* The popup form - hidden by default */
.form-popup {
display: none;
position: absolute;
left: 50%;
top: 38%;
transform: translate(-50%, -50%);
border: 3px solid black;
background-color: white;
}
.form-container {
max-width: 800px;
max-height: 800px;
padding: 10px;
background-color: white;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(function(){
$("#header").load("navbar_header.html");
});
</script>
</head>
<!-- Header -->
<body>
<div id="header"></div>
<div class = "container">
<div class= "text-center">
<br>
<h1>Search for Contact to Modify<h1>
<hr/>
</div>
</div>
<br>
<!-- search contacts for name given as input -->
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<div class="container" id="searchName">
<div class="row justify-content-md-center">
<div class="col col-lg-2">
<div class= "text-right"><p >Contact Name:</p></div>
</div>
<div class="col col-lg-4">
<input name="contactname" type="text" class="form-control" id="contactnamecheck">
</div>
<div class="col col-lg-3">
<button name="checkContacts" type="submit" id="change_user" class="btn btn-block btn-success btn-lg" onClick="checkName()">Check Contacts</button>
</div>
</div>
<p class="text-md-center text-danger" id="nocontactfounderror"><?php echo $noneFoundError;?></p>
<br><br>
</div>
</form>
</body>
</html>
| true |
8c812f0e227e6a0c8f4a6a5093619b44354c4d31 | PHP | Olataiwo/gradecalculator | /includes/functions.php | UTF-8 | 1,901 | 2.78125 | 3 | [] | no_license | <?php
function displayErrors($arr, $name) {
$result = "";
if(isset($arr[$name])) {
$result = '<span class="err">'. $arr[$name]. '</span>';
}
return $result;
}
function doRegistration($dbconn, $input) {
# prepared statement
$stmt = $dbconn->prepare("INSERT INTO user(first_name, last_name, email, password) VALUES(:fn, :ln, :e, :h)");
#bind params
$data = [
':fn' => $input['fname'],
':ln' => $input['lname'],
':e' => $input['e_mail'],
':h' => $input['password']
];
# execute prepared statement
$stmt->execute($data);
}
function adminLogin($dbconn, $enter) {
$result = [];
# prepared statement
$statement = $dbconn->prepare("SELECT * FROM user WHERE email=:em");
# bind params
$statement->bindParam(":em", $enter['e_mail']);
$statement->execute();
$row = $statement->fetch(PDO::FETCH_ASSOC);
$count = $statement->rowCount();
if( !password_verify($enter['pword'], $row['password'])){
# error handler, so if this is false, handle it and exit no need for else
redirect("login.php?msg=invalid email or password");
exit();
} else {
$result[] = true;
$result[] = $row;
}
return $result;
}
function redirect($loca){
header("Location: ".$loca);
}
function createTable($dbconn){
$result = "";
$query = $dbconn->prepare("SELECT * FROM modules");
$query->execute();
while($row = $query->fetch(PDO::FETCH_ASSOC)){
$module_id = $row['id'];
$course_id = $row['course_id'];
$course_name = $row['course_name'];
$course_credit = $row['credits'];
$result .= '<tr><td>'.$row['course_id'].'</td>';
$result.= '<td>'.$row['course_name'].'</td>';
$result.='</tr>';
}
return $result;
}
function LoginCheck() {
if(!isset($_SESSION['id']) ) {
header("Location:login.php");
}
}
| true |
b90ada649dd525f05f5d5afed01e0cf4263fab0b | PHP | silinternational/simplesamlphp-module-silauth | /src/system/System.php | UTF-8 | 2,672 | 2.6875 | 3 | [
"MIT"
] | permissive | <?php
namespace Sil\SilAuth\system;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use Sil\SilAuth\auth\IdBroker;
use Sil\SilAuth\config\ConfigManager;
use Sil\SilAuth\models\FailedLoginIpAddress;
use \SimpleSAML\Configuration;
use Throwable;
class System
{
protected $logger;
/**
* Constructor.
*
* @param LoggerInterface|null $logger (Optional:) A PSR-3 compatible logger.
*/
public function __construct($logger = null)
{
$this->logger = $logger ?? new NullLogger();
}
protected function isDatabaseOkay()
{
try {
FailedLoginIpAddress::getMostRecentFailedLoginFor('');
return true;
} catch (Throwable $t) {
$this->logError($t->getMessage());
return false;
}
}
protected function isRequiredConfigPresent()
{
$globalConfig = Configuration::getInstance();
/*
* NOTE: We require that SSP's baseurlpath configuration is set (and
* matches the corresponding RegExp) in order to prevent a
* security hole in \SimpleSAML\Utils\HTTP::getBaseURL() where the
* HTTP_HOST value (provided by the user's request) is used to
* build a trusted URL (see SimpleSaml\Module::authenticate()).
*/
$baseURL = $globalConfig->getString('baseurlpath', '');
$avoidsSecurityHole = (preg_match('#^https?://.*/$#D', $baseURL) === 1);
return $avoidsSecurityHole;
}
/**
* Check the status of the system, and throw an exception (that is safe to
* show to the public) if any serious error conditions are found. Log any
* problems, even if recoverable.
*
* @throws \Exception
*/
public function reportStatus()
{
if ( ! $this->isRequiredConfigPresent()) {
$this->reportError('Config problem', 1485984755);
}
if ( ! $this->isDatabaseOkay()) {
$this->reportError('Database problem', 1485284407);
}
echo 'OK';
}
/**
* Add an entry to our log about this error.
*
* @param string $message The error message.
*/
protected function logError($message)
{
$this->logger->error($message);
}
/**
* Log this error and throw an exception (with an error message) for the
* calling code to handle.
*
* @param string $message The error message.
* @param int $code An error code.
* @throws \Exception
*/
protected function reportError($message, $code)
{
$this->logError($message);
throw new \Exception($message, $code);
}
}
| true |
1b3c8ceac7d8dd449339cca8ae2091603796bcf0 | PHP | andrewgilmartin/mws_signup | /lib/EventParser.php | UTF-8 | 8,762 | 3 | 3 | [] | no_license | <?php
class EventParser {
private $lexer;
private $keyToData = array();
function __construct( $tokens, $contacts ) {
$this->lexer = new Lexer($tokens);
foreach ( $contacts as $contact ) {
$this->put($contact->getId(),$contact);
$this->put($contact->getName(),$contact);
}
}
static function fromScript( $script, $contacts = array() ) {
$parser = new EventParser($script,$contacts);
return $parser->parse();
}
function parse() {
try {
$event = null;
while ( $t = $this->t() ) {
switch ( $t ) {
case 'event':
$event = $this->parseEvent();
break;
case 'comment':
$comment = $this->t();
break;
default:
throw new Exception( "unexpected token \"$t\" while parsing script");
}
}
return $event;
}
catch ( Exception $e ) {
throw new Exception(
"Exception \""
.$e->getMessage()
."\" in parsing context "
.$this->context()
." in file "
.$e->getFile().":".$e->getLine()
.' with stack '
.$e->getTraceAsString()
);
}
return null;
}
private function parseEvent() {
$event = new Event();
$event->setName( $this->t() );
while ( $t = $this->t() ) {
switch( $t ) {
case 'id':
$event->setId( $this->t() );
break;
case 'description':
$event->setDescription( $this->t() );
break;
case 'contact':
$contact = $this->get( $this->t() );
if ( $contact ) {
$event->setContact( $contact );
}
else {
throw new Exception( "expected contact while parsing event");
}
break;
case 'role':
$role = $this->parseRole();
if ( $role ) {
$event->addRole($role);
$this->put( $role->getName(), $role );
}
else {
throw new Exception( "expected role while parsing event");
}
break;
case 'day':
$day = $this->parseDay();
if ( $day ) {
$event->addDay($day);
$this->put( $day->getName(), $day );
}
else {
throw new Exception( "expected day while parsing event");
}
break;
case 'activity':
$activity = $this->parseActivity();
if ( $activity ) {
$event->addActivity($activity);
}
else {
throw new Exception( "expected activity while parsing event");
}
break;
case 'hint':
$hint = $this->parseHint();
$event->addHint($hint);
break;
case 'volunteer-property': {
$volunteerProperty = $this->parseVolunteerProperty();
$event->addVolunteerProperty($volunteerProperty);
break;
}
case 'end':
return $event;
case 'comment':
$comment = $this->t();
break;
default:
throw new Exception( "unexpected token $t while parsing event");
}
}
return null;
}
private function parseHint() {
$hint = new Hint();
$hint->setName($this->t());
$hint->setValue($this->t());
return $hint;
}
private function parseVolunteerProperty() {
$name = $this->t();
while ( $t = $this->t() ) {
switch( $t ) {
case 'description': {
$description = $this->t();
break;
}
case 'end': {
$volunteerProperty = new VolunteerProperty( $name, $description );
return $volunteerProperty;
}
default: {
throw new Exception( "unexpected token $t while parsing volunteer property");
}
}
}
return null;
}
private function parseDay() {
$day = new Day();
$day->setName( $this->t() );
while ( $t = $this->t() ) {
switch( $t ) {
case 'id':
$day->setId( $this->t() );
break;
case 'date':
$day->setDate( $this->t() );
break;
case 'contact':
$name = $this->t();
$contact = $this->get( $name );
if ( $contact ) {
$day->setContact($contact);
}
else {
throw new Exception( "expecting contact name but found \"$name\"");
}
break;
case 'hours':
$hours = $this->parseHours();
$day->addHours( $hours );
break;
case 'end': {
return $day;
}
case 'comment':
$comment = $this->t();
break;
default: {
throw new Exception( "unexpected token $t while parsing day");
}
}
}
return null;
}
private function parseHours() {
$hours = new Hours();
$hours->setName( $this->t() );
while ( $t = $this->t() ) {
switch( $t ) {
case 'id':
$hours->setId( $this->t() );
break;
case 'starting':
$hours->setStarting( $this->t() );
break;
case 'ending':
$hours->setEnding( $this->t() );
break;
case 'end':
return $hours;
case 'comment':
$comment = $this->t();
break;
default:
throw new Exception( "unexpected token $t while parsing hours");
}
}
return null;
}
private function parseRole() {
$role = new Role();
$role->setName( $this->t() );
while ( $t = $this->t() ) {
switch( $t ) {
case 'id':
$role->setId( $this->t() );
break;
case 'description':
$role->setDescription( $this->t() );
break;
case 'end':
return $role;
case 'comment':
$comment = $this->t();
break;
default:
throw new Exception( "unexpected token $t while parsing role");
}
}
return null;
}
private function parseActivity() {
$activity = new Activity();
$activity->setName( $this->t() );
while ( $t = $this->t() ) {
switch( $t ) {
case 'id':
$activity->setId( $this->t() );
break;
case 'description':
$activity->setDescription( $this->t() );
break;
case 'contact':
$name = $this->t();
$contact = $this->get( $name );
if ( $contact ) {
$activity->setContact($contact);
}
else {
throw new Exception( "expected contact while parsing activity but found name \"$name\"");
}
break;
case 'day':
$name = $this->t();
$day = $this->get( $name );
if ( $day ) {
$shifts = $this->parseShifts();
foreach ( $shifts as $shift ) {
$day->addShift($shift);
$activity->addShift($shift);
}
}
else {
throw new Exception( "expected day while parsing activity but found name \"$name\"");
}
break;
case 'end': {
return $activity;
}
case 'comment':
$comment = $this->t();
break;
default: {
throw new Exception( "unexpected token \"$t\" while parsing event's activity");
}
}
}
return null;
}
private function parseShifts() {
$shifts = array();
while ( $t = $this->t() ) {
switch( $t ) {
case 'shift': {
foreach ( $this->parseShift() as $shift ) {
$shifts[] = $shift;
}
break;
}
case 'end': {
return $shifts;
}
default: {
throw new Exception( "unexpected token \"$t\" while parsing activity's day's shifts");
}
}
}
return null;
}
private function parseShift() {
$shift = new Shift();
$count = 1;
$role = $this->get( $this->t() );
if ( $role ) {
$shift->setRole( $role );
}
else {
throw new Exception("expecting a role name while parsing shift");
}
while ( $t = $this->t() ) {
switch( $t ) {
case 'id':
$shift->setId( $this->t() );
break;
case 'count': {
$count = $this->t();
break;
}
case 'starting':
$shift->setStarting( $this->t() );
break;
case 'ending':
$shift->setEnding( $this->t() );
break;
case 'end':
$shifts = array( $shift );
while ( $count > 1 ) {
$copy = $shift->copy();
$shifts[] = $copy;
$count -= 1;
}
return $shifts;
case 'comment':
$comment = $this->t();
break;
default:
throw new Exception( "unexpected token $t while parsing shift");
}
}
return null;
}
private function parseVolunteer() {
$volunteer = new Volunteer();
$contact = $this->get( $this->t() );
if ( $contact ) {
$volunteer->setContact( $contact );
}
else {
throw new Exception("expecting a contact name while parsing volunteer");
}
while ( $t = $this->t() ) {
switch( $t ) {
case 'id':
$volunteer->setId( $this->t() );
break;
case 'property':
$name = $this->t();
$value = $this->t();
$volunteer->addProperty( $name, $value );
break;
case 'end':
return $volunteer;
case 'comment':
$comment = $this->t();
break;
default:
throw new Exception( "unexpected token \"$t\" while parsing volunteer");
}
}
return null;
}
private function put( $key, $data ) {
$this->keyToData[ $key ] = $data;
return $this;
}
private function get( $key ) {
return $this->keyToData[$key];
}
private function t() {
return $this->lexer->t();
}
private function context() {
return $this->lexer->context();
}
}
?> | true |
055f36946c853f9dda506b902bf632f572fbb6d3 | PHP | StanciuDragosIoan/symfony_code | /stellar_development/notes.php | UTF-8 | 11,366 | 2.734375 | 3 | [] | no_license | <?
/*
App structure:
'public' is the document root for all public assets
index.php is the front controller (entry point for the app)
'config' holds configuration files
'src' contains the source code
Some cmds used:
composer require server
./bin/console/server:run (starts server) -> this works because the project has a 'bin'
directory with a console file inside
### Routes/Controllers/Pages
route = configuration that defines the url for a page
controller = a function that we write that builds the content for that page
the main routing file is in config/routes.yaml
a controller must return a symfony response object
I created a first controller and a homepage
in the Controller directory created an ArticleController class
the class uses the namespace App\Controller and the
Symfony\Component\HttpFoundation\Response namespace and it
has a single method home() which returns a symfony Response()
in the config/routes.yaml file I added the route for the page:
path: /
controller: App\Controller\ArticleController::homepage()
# ran composer requier annotations
commented out the .yaml route
defined the route through an annotation in the ArticleController
imported the namespace:
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
added the route annotation (symfony allows for routes to be defined
either in the .yaml file or directly in the controller through an annotation)
### Symfony Flex and Aliases
# I ran composer require sec-checker --dev
Flex (symfony/flex) is a composer plug-in that does 2 things:
1. the Alias system (https://flex.symfony.com/)
recipes are sets of instructions ran in the terminal through a shortuct
command
2. recipes (sets of instructions)
if when installing a package, it has a recipe, the recipe will be ran
recipes can modify configuration/files/create directories/update the
.gitignore file, etc..
symfony.lock keeps track of which recipes have been installed
ran ./bin/console security:check (to check if any package has a security vulnerability)
### The Twig Recipe
the symfony response can render templates/make API requests/DB queries, etc...
ran composer requier twig
this modified bundles.php among other files (bundles.php keeps track of all 3rd party
bundles)
### Twig
opened ArticleController.php and made it extend AbstractController + added namespace
removed the return new Response() and replaced with
return $this->render();
twig has 3 types of syntax:
1. {{ variable }} (prints the variable)
2. {%%} (does something/performs logic)
3. {##} (comments syntax)
passed a template to render and an array with elements of the template
opened: http://localhost:8000/news/why-asteroids-taste-like-bacon
added a $comments var inside show() method of controler
passed $comments to a 'comments' variable in the template (array param of render() )
looped over comments in twig inside {%%} and displayed them on page:
{% for comment in comments %}
<li>{{comment}}</li>
{% endfor %}
added a 'filter' to the Comments title
{{comments|length}} (note the pipe character that prints the number of comments)
made the template extend the base template:
{% extends 'base.html.twig' %}
wrapped the content in blocks:
{% block body %} {% endblock %}
{% block title %} {% endblock %}
### Web Debug Toolbar and the profiler
ran composer require profiler --dev
this added a debugger toolbar at the top of the page with many features
note the dump() method that prints variables nicely coloured on the screen
//dump($slug, $this);
use dump like this in twig templates: {{ dump() }} -no param
### Debugging and packs
ran composer require debug --dev (to get all the debugging tools)
packs are bundled packages installed together with a single command (e.g.
installing 6 packages for debug with a single cmd)
ran composer unpack debug (to split the packages in the composer.json)
instead of having a single debug pack containing all the composing packages:
"symfony/debug-pack": "^1.0",
we now have each individual package in the composer.json file:
"easycorp/easy-log-handler": "^1.0.7",
"sensiolabs/security-checker": "^6.0",
"symfony/debug-bundle": "*",
"symfony/monolog-bundle": "^3.0",
"symfony/profiler-pack": "*",
"symfony/var-dumper": "*"
### Assets CSS & JS
replaced the base.html.twig from the templates with the 1 from the tutorial directory
ran rm -rf var/cache/dev* to clear the cache (symfony does that automatically)
might be required when we copy into a template file without actually modifiying
the file
copied the css,fonts and images directory from tutorial to public
referenced CSS and images in the base.html.twig
ran composer require asset and wrapped the path to .css in asset() in twig block
images can also be used with asset()
<link rel="stylesheet" href="{{ asset('/css/font-awesome.css') }}">
<img src="{{ asset('images/astronaut-profile.png') }}">
copied the contents from article.html.twig from tutorial to the show.html.twig template
replaced the title and comments (hard coded ) with dynamic data from controller
### Generating URLs
configured the route for the homepage:
ran ./bin/console debug:router to see all routes in the app
note this shows us the routes names:
for homepage its:
app_article_homepage
we can reference these names
copied the name for homepage route and added it to the anchor tag on the nav in the
base.html.twig:
href="{{ path('app_article_homepage')}}"
now the homepage route works
changed the homepage annotation (added a 2nd param - the route name):
*@Route("/", name="app_homepage")
ran ./bin/console debug:router and now the homepage route name changed from
app_article_homepage to app_homepage;
changed the route in the show.html.twig route to the new name (and it works)
added an html template for the homepage in the home() in the controller:
return $this->render('article/homepage.html.twig');
created the template and added a route to it:
gave the route a name:
*@Route("/news/{slug}", name="article_show")
added the variable as associative array in the twig template:
{slug: 'why-asteroids-taste-like-bacon'}
now the route works
### JS and page specific assets
created a 'js' directory in the public directory
created article_show.js inside 'js'
added some JS code
included the js file in the show.html.twig template
we could add it in base.html.twig (but we want this js file only on article_show
page)
if we add it in the body block of the article.show.twig, it will appear too early
(as the JS block is after the body)
we have to overwrite the JS block in show.html.twig.show:
{% block javascripts %}
{{ parent() }}
<script src="{{asset('js/article_show.js')}}"></script>
{% endblock %}
*note how we append the parent() js block (with JQ and all dependencies) before
our file
### JSON API endpoint
when clicking the heart icon we will send an ajax request to the server that will
update the DB and show our like
the API endpoint needs to return the new number of hearts to show on the page
created a new method in the ArticleController.php (note the route and the
fact that method can only be POST)
**
* @Route("/news/{slug}/heart", name="article_toggle_heart", methods={"POST"});
*
public function toggleArticleHeart($slug)
{
//TODO - actually heart/unheart the article
return new JsonResponse(['hearts' => rand(5,100)]);
}
in the show.html.twig, modified the href attribute of the heart icon:
href="{{ path('article_toggle_heart', {slug: 'slug'})}}"
modified the show() meth in ArticleController.php (added the slug param):
public function show($slug)
{
$comments = [
'Comment One for post One',
'Comment Two for post Two',
'Comment 3 for Post 3'
];
// dump($slug, $this);
return $this->render('article/show.html.twig', [
'title'=> ucwords(str_replace('-', ' ', $slug)),
'slug' => $slug, //added the slug as variable
'comments' => $comments
]);
}
added te ajax call in the artcile_show.js file:
$.ajax({
method: 'POST',
url: $link.attr('href')
}).done((data)=>{
$('.js-like-article-count').html(data.hearts);
});
now in the browser, when we click the heart, it makes a post request and it returns the
number of hearts and sets it as the actual number of hearts in the html template
### SERVICES
symfony = a bunch of useful objects that do stuff
router object = object that matches routes and generates URLs
twig object = object that renders templates
log object = object that symfony uses to store logs in var/log/dev.log
these objects are also called services (a service is an object that 'does wor' like
generating URLs, sending emails, saving things to a database)
ran tail -f var/log/dev.log (displays the logs)
in order to use a service, we pass it as argument to the method (and we type-hint it)
e.g.
public function toggleArticleHeart($slug, LoggerInterface $logger)
{
//TODO - actually heart/unheart the article
return new JsonResponse(['hearts' => rand(5,100)]);
}
in symfony anything is a service (an object with methods that does something)
*/
| true |
9e5147ba2e0e47aa2f3679afe0de6bc444e84248 | PHP | LuizDoPc/quansquie | /CONTROLE/Caracteristica/RetornaAllCaracteristica.php | UTF-8 | 337 | 2.515625 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: Luiz
* Date: 07/01/2018
* Time: 20:42
*/
require_once '../../MODELO/Caracteristica.php';
$carac = new Caracteristica();
$res = $carac->findAll();
for($i=0; $i<count($res); $i++){
echo '<option value="'.$res[$i]->idCaracteristica.'">'.$res[$i]->Nome.'</option>';
} | true |
d3f43f508c08c22f570283201a5178426468d1f4 | PHP | thunder-spb/blog | /Services/Gate/My/Controller/MainController.php | UTF-8 | 526 | 2.625 | 3 | [] | no_license | <?php
namespace My\Controller;
use My\Engine\Request;
use My\Engine\Response;
use My\Engine\Storage;
use My\Engine\Session;
class MainController {
/**
* @var Response
*/
public $response;
/**
* @var Request
*/
public $request;
/**
* @var Session
*/
public $session;
public function __construct()
{
$this->response = Storage::get('Response');
$this->request = Storage::get('Request');
$this->session = Storage::get('Session');
}
} | true |
ea2631b13b80fb5d20d9fd2b1cea20a4f065b401 | PHP | vbodv/oxideshop_ce | /tests/Unit/Core/Database/Adapter/Doctrine/DatabaseTest.php | UTF-8 | 6,088 | 2.703125 | 3 | [] | no_license | <?php
/**
* This file is part of OXID eShop Community Edition.
*
* OXID eShop Community Edition is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OXID eShop Community Edition is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OXID eShop Community Edition. If not, see <http://www.gnu.org/licenses/>.
*
* @link http://www.oxid-esales.com
* @copyright (C) OXID eSales AG 2003-2016
* @version OXID eShop CE
*/
namespace OxidEsales\EshopCommunity\Tests\Unit\Core\Database;
use OxidEsales\EshopCommunity\Core\Database\Adapter\Doctrine\Database;
use OxidEsales\TestingLibrary\UnitTestCase;
/**
* Unit tests for our database abstraction layer object.
*
* @group database-adapter
*/
class DatabaseTest extends UnitTestCase
{
/**
* @var Database The doctrine database we want to test in this class.
*/
protected $database = null;
/**
* Set up the test
*/
public function setUp()
{
parent::setUp();
$this->database = \oxDb::getDb();
}
/**
* Test, that the method 'quote' works with null.
*/
public function testQuoteWorksWithNull()
{
$quoted = $this->database->quote(null);
$this->assertEquals("''", $quoted);
}
/**
* Test, that the method 'quote' works with an empty string.
*/
public function testQuoteWorksWithEmptyString()
{
$quoted = $this->database->quote('');
$this->assertEquals("''", $quoted);
}
/**
* Test, that the method 'quote' works with a non empty value.
*/
public function testQuoteWorksWithNonEmptyValue()
{
$quoted = $this->database->quote('NonEmptyValue');
$this->assertEquals("'NonEmptyValue'", $quoted);
}
/**
* Test, that the method 'quote' works with an already quoted value.
*/
public function testQuoteWorksWithAlreadyQuotedValue()
{
$quoted = $this->database->quote("NonEmptyValue");
$quoted = $this->database->quote($quoted);
$this->assertEquals("'\'NonEmptyValue\''", $quoted);
}
/**
* Test, that the method 'quoteArray' works with an empty array.
*/
public function testQuoteArrayWithEmptyArray()
{
$originalArray = array();
$quotedArray = $this->database->quoteArray($originalArray);
$this->assertEquals($originalArray, $quotedArray);
}
/**
* Test, that the method 'quoteArray' works with a non empty array.
*/
public function testQuoteArrayWithFilledArray()
{
$originalArray = array('Hello', 'quoteThis');
$quotedArray = $this->database->quoteArray($originalArray);
$expectedQuotedArray = array("'Hello'", "'quoteThis'");
$this->assertEquals($expectedQuotedArray, $quotedArray);
}
/**
* @dataProvider dataProviderTestQuoteIdentifier
*
* @param $string
* @param $expectedResult
* @param $message
*/
public function testQuoteIdentifier($string, $expectedResult, $message)
{
$actualResult = $this->database->quoteIdentifier($string);
$this->assertSame($expectedResult, $actualResult, $message);
}
/**
* This test is MySQL database specific, the identifier for other database platforms my be different.
*
* @return array
*/
public function dataProviderTestQuoteIdentifier()
{
$identifierQuoteCharacter = '`';
return [
[
'string to be quoted',
$identifierQuoteCharacter . 'string to be quoted' . $identifierQuoteCharacter,
'A normal string will be quoted with "' . $identifierQuoteCharacter . '""'
],
[
$identifierQuoteCharacter . 'string to be quoted' . $identifierQuoteCharacter,
$identifierQuoteCharacter . 'string to be quoted' . $identifierQuoteCharacter,
'An already quoted string will be quoted with "' . $identifierQuoteCharacter . '"'
],
[
$identifierQuoteCharacter . $identifierQuoteCharacter .$identifierQuoteCharacter . 'string to be quoted' . $identifierQuoteCharacter . $identifierQuoteCharacter . $identifierQuoteCharacter,
$identifierQuoteCharacter . 'string to be quoted' . $identifierQuoteCharacter,
'An already quoted string will be quoted with "' . $identifierQuoteCharacter . '"'
],
[
$identifierQuoteCharacter . 'string to be quoted' . $identifierQuoteCharacter . $identifierQuoteCharacter . $identifierQuoteCharacter,
$identifierQuoteCharacter . 'string to be quoted' . $identifierQuoteCharacter,
'An already quoted string will be quoted with "' . $identifierQuoteCharacter . '"'
],
[
$identifierQuoteCharacter . 'string to ' . $identifierQuoteCharacter . ' be quoted' . $identifierQuoteCharacter,
$identifierQuoteCharacter . 'string to be quoted' . $identifierQuoteCharacter,
'An already quoted string will be quoted with "' . $identifierQuoteCharacter . '"'
],
[
'',
$identifierQuoteCharacter . '' . $identifierQuoteCharacter,
'An empty string will be quoted with "' . $identifierQuoteCharacter . '"'
],
[
null,
$identifierQuoteCharacter . '' . $identifierQuoteCharacter,
'An empty string will be quoted as an empty string with "' . $identifierQuoteCharacter . '"'
],
];
}
}
| true |
12364b6870508ae6ddeae8df3a0e9b487b3f8bc0 | PHP | wp-plugins/wanderfly | /functions.php | UTF-8 | 1,683 | 2.53125 | 3 | [] | no_license | <?php
/*
Function: wf_widget();
Variables,
- locationID: Integer which is the ID of the destination,
*/
function wf_template_widget($retData=false) {
global $post;
$error = 'Error while adding the widget, please report to <a href="http://blog.wanderfly.com/wordpress-plugin/">http://blog.wanderfly.com/wordpress-plugin/</a>.';
$widgetHTML = false;
if($post) {
//Get the Destination ID from the post's metas,
$wf_meta = get_post_meta($post->ID, "wf_destination", true);
//Display the wanderfly widget,
if($wf_meta) {
$wf_metas = explode(':', $wf_meta);
$widgetHTML = wf_widget($wf_metas[0]);
}
}
//Echo the widget,
if($widgetHTML !== false) {
if($retData) { return $widgetHTML; }
else { echo $widgetHTML; }
}
//Return the widget's HTML,
else {
if($retData) { return $widgetHTML; }
else { echo $error; }
}
}
/*
Function: wf_widget();
Variables,
- locationID: Integer which is the ID of the destination,
*/
function wf_widget($destinationID=null) {
if($destinationID === null) {
print('You need to provide the destination ID from <a href="http://wanderfly.com">Wanderfly</a>.');
return false;
}
//Connect to the OSCommerce database
$apikey = get_option('wf_apikey');
return '<iframe srcolling="no" frameborder="0" border="0" width="596" height="130" name="wf-widget-checkitout-'.$destinationID.'" id="wf-widget-checkitout-'.$destinationID.'" src="http://partners.wanderfly.com/widgets/checkitout?apiKey='.$apikey.'&destinationID='.$destinationID.'" style="border:none; overflow:hidden; width:596px; height:130px;" allowTransparency="true"></iframe>';
}
?> | true |
8f45e120410b19812f4d3202fd5cee2866577b53 | PHP | netflo300/FSF | /class/node.class.php | UTF-8 | 843 | 2.953125 | 3 | [] | no_license | <?php
class Node {
private $value;
private $listOfNode;
public function __construct( $value) {
$this->value = $value;
$listOfNode = array();
}
public function addChildNode($node) {
$this->listOfNode[$node->value] = $node;
}
public function explore(&$listSaw) {
global $db;
$db->query("SELECT id_step_target FROM fsf_step_link WHERE id_step_origin ='".$this->value."' ;");
if($db->get_num_rows() > 0) {
foreach($db->fetch_array() as $k => $v) {
//echo 'Node courant '.$this->value . ' - Noeud suivant : ' . $v['id_step_target']."\n";
$newNode = new Node($v['id_step_target']);
$this->addChildNode($newNode);
if(!key_exists($v['id_step_target'], $listSaw)) {
$listSaw[$v['id_step_target']] = 1;
$newNode->explore($listSaw);
} else {
$newNode->listOfNode = 'R';
}
}
}
}
} | true |
a4659123fc1478e1901e9c7ae1703189dfbf5ace | PHP | timurmametev/slim-rest-api | /app/Support/NotAllowedHandler.php | UTF-8 | 1,594 | 2.75 | 3 | [] | no_license | <?php
declare(strict_types=1);
namespace App\Support;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Slim\Interfaces\ErrorHandlerInterface;
use Slim\Routing\RouteContext;
use Throwable;
class NotAllowedHandler implements ErrorHandlerInterface
{
/**
* @var ResponseFactoryInterface
*/
private ResponseFactoryInterface $factory;
/**
* NotFoundHandler constructor.
*
* @param ResponseFactoryInterface $factory
*/
public function __construct(ResponseFactoryInterface $factory)
{
$this->factory = $factory;
}
/**
* @param ServerRequestInterface $request
* @param Throwable $exception
* @param bool $displayErrorDetails
* @param bool $logErrors
* @param bool $logErrorDetails
* @return ResponseInterface
*/
public function __invoke(
ServerRequestInterface $request,
Throwable $exception,
bool $displayErrorDetails,
bool $logErrors,
bool $logErrorDetails
): ResponseInterface
{
$routeContext = RouteContext::fromRequest($request);
$routingResults = $routeContext->getRoutingResults();
$methods = $routingResults->getAllowedMethods();
$response = $this->factory->createResponse(405);
$response->getBody()->write('Method must be one of: ' . implode(', ', $methods));
return $response
->withHeader('Allow', implode(', ', $methods))
->withHeader('Content-type', 'text/html');
}
} | true |
44b2ef4e2c08027c35727e6ce29beda381ae5d6b | PHP | djdarkblazer/cswd_rms | /scheme/helpers/language_helper.php | UTF-8 | 2,365 | 2.5625 | 3 | [
"MIT"
] | permissive | <?php
defined('PREVENT_DIRECT_ACCESS') OR exit('No direct script access allowed');
/**
* ------------------------------------------------------------------
* LavaLust - an opensource lightweight PHP MVC Framework
* ------------------------------------------------------------------
*
* MIT License
*
* Copyright (c) 2020 Ronald M. Marasigan
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @package LavaLust
* @author Ronald M. Marasigan <ronald.marasigan@yahoo.com>
* @copyright Copyright 2020 (https://ronmarasigan.github.io)
* @since Version 1
* @link https://lavalust.pinoywap.org
* @license https://opensource.org/licenses/MIT MIT License
*/
if ( ! function_exists('lang'))
{
/**
* Use to translate text on you app in different languages
*
* @param string $key key value from your language file
* @param array $params optional parameters
* @return string
*/
function lang($key, $params = array(), $xss = FALSE)
{
$translated = lava_instance()->lang->translate($key, $params);
if($xss == TRUE)
return lava_instance()->security->xss_clean($translated);
else
return $translated;
}
}
if ( ! function_exists('language'))
{
/**
* Use to select the Language to use
*
* @param string $lang
* @return $this
*/
function language($lang)
{
return lava_instance()->lang->language($lang);
}
}
?> | true |
a8cc473b77378da38f71da2d1e251fce866cfb3f | PHP | creyes-dev/curso-fullstack | /3_AJAX/23_evaluacion/includes/obtener_propiedades.php | UTF-8 | 1,033 | 2.71875 | 3 | [] | no_license |
<?php
include('configuracion.php');
$selectSql = "SELECT id, barrio, calle_altura, descripcion, ";
$selectSql.= " descripcion_corta, valor, entre_calles";
$selectSql.= " FROM propiedad";
if(isset($_REQUEST['prop'])){
if($_REQUEST['prop'] != "0"){
$selectSql.= " WHERE id = " . $_REQUEST['prop'];
}
}
if($conexion = getConexionMysqli()){
$comando = mysqli_query($conexion, $selectSql);
while($row = mysqli_fetch_array($comando))
{
$resultados[] = array(
'id' => $row['id'],
'barrio' => $row['barrio'],
'calleAltura' => $row['calle_altura'],
'descripcion' => $row['descripcion'],
'descripcionCorta' => $row['descripcion_corta'],
'entreCalles' => $row['entre_calles']
);
}
}
// convertimos el array de datos a formato json
echo json_encode($resultados, JSON_UNESCAPED_UNICODE);
?>
| true |
7b9ed1bcc261e7c121c25275c5a87053c8ed5d93 | PHP | coffbr01/PHP-Email | /email.php | UTF-8 | 11,235 | 3.046875 | 3 | [] | no_license | <?php
include "mimetype.php";
/*
Usage
=====
set $this->to
set $this->subject
set $this->message (with html tags)
set $this->from (Optional)
set $this->cc (this can be an array or a variable) (Optional)
set $this->bcc (this can be an array or a variable) (Optional)
set $this->reply_to (Optional)
set $this->return_path (Optional)
set $this->x_mailer (Optional)
set $this->attach_name (this can be an array or a variable) (Optional)
set $this->attach_file_name (this can be an array or a variable, must correspond to attach_name) (Optional)
$this->SendMail();
This function returns an array of 2 elements which e[0] = true (on success) or false and e[1] = message
*/
class EMail {
var $to;
var $from;
var $cc;
var $bcc;
var $reply_to;
var $return_path;
var $x_mailer;
var $subject;
var $message;
var $attach_file_name;
function EMail() {
$this->to = "";
$this->subject = "";
$this->message = "";
$this->from = "Administrator <admin@" . $_SERVER['SERVER_NAME'] . ">";
$this->cc = "";
$this->bcc = "";
$this->reply_to = $this->from;
$this->return_path = $this->from;
$this->x_mailer = "PHP v" . phpversion();
$this->attach_name = "";
$this->attach_file_name = "";
}
// Setters.
function setTo($to) {
$this->to = $to;
}
function setSubject($subject) {
$this->subject = $subject;
}
function setMessage($message) {
$this->message = $message;
}
function setFrom($from) {
$this->from = $from;
}
function setCC($cc) {
$this->cc = $cc;
}
function setBCC($bcc) {
$this->bcc = $bcc;
}
function setReplyTo($replyTo) {
$this->reply_to = $replyTo;
}
function setReturnPath($returnPath) {
$this->return_path = $returnPath;
}
function setAttachFileName($attachFileName) {
$this->attach_file_name = $attachFileName;
}
function setAttachName($attachName) {
$this->attach_name = $attachName;
}
function makeFileName ($url) {
$pos=true;
$PrePos=0;
while (!$pos==false) {
$pos = strpos($url,'\\',$PrePos);
if ($pos===false) {
$temp = substr($url,$PrePos);
}
else {
$PrePos = $pos + 1;
}
}
return $temp;
}
function processAttachment() {
if(is_array($this->attach_file_name)) {
$s = sizeof($this->attach_file_name);
for($i=0; $i<$s; $i++) {
if($this->attach_file_name[$i] != "") {
$handle = fopen($this->attach_file_name[$i], 'rb');
$file_contents = fread($handle, filesize($this->attach_file_name[$i]));
$Attach['contents'][$i] = chunk_split(base64_encode($file_contents));
fclose($handle);
$Attach['file_name'][$i] = $this->makeFileName ($this->attach_name[$i]);
$pos=true;
$PrePos=0;
while (!$pos==false) {
$pos = strpos($this->attach_file_name[$i], '.', $PrePos);
if ($pos===false) {
$Attach['file_type'][$i] = substr($this->attach_file_name[$i], $PrePos);
}
else {
$PrePos = $pos+1;
}
}
}
}
return $Attach;
}
else {
$handle = fopen($this->attach_file_name, 'rb');
$file_contents = fread($handle, filesize($this->attach_file_name));
$Attach['contents'][0] = chunk_split(base64_encode($file_contents));
fclose($handle);
$Attach['file_name'][0] = $this->makeFileName ($this->attach_name);
$pos=true;
$PrePos=0;
while (!$pos==false) {
$pos = strpos($this->attach_file_name, '.', $PrePos);
if ($pos===false) {
$Attach['file_type'][0] = substr($this->attach_file_name, $PrePos);
}
else {
$PrePos = $pos+1;
}
}
}
return $Attach;
}
function validateMailAddress($MAddress) {
if (eregi("@", $MAddress) && eregi(".", $MAddress)) {
return true;
}
else {
return false;
}
}
function Validate() {
if(is_array($this->to)) {
$msg[0] = false;
$msg[1] = "You should provide only one receiver email address";
return $msg;
}
if(is_array($this->from)) {
$msg[0] = false;
$msg[1] = "You should provide only one sender email address";
return $msg;
}
if($this->to == "") {
$msg[0] = false;
$msg[1] = "You should provide a receiver email address";
return $msg;
}
if($this->subject == "") {
$msg[0] = false;
$msg[1] = "You should provide a subject for your email";
return $msg;
}
if($this->message == "") {
$msg[0] = false;
$msg[1] = "You should provide message for your email";
return $msg;
}
if(!$this->validateMailAddress($this->to)) {
$msg[0] = false;
$msg[1] = "Receiver E-Mail Address is not valid";
return $msg;
}
if(!$this->validateMailAddress($this->from)) {
$msg[0] = false;
$msg[1] = "Sender E-Mail Address is not valid";
return $msg;
}
if(is_array($this->cc)) {
$s = sizeof($this->cc);
for($i=0; $i<$s; $i++) {
if(!$this->validateMailAddress($this->cc[$i]) && $this->cc[$i] != "") {
$msg[0] = false;
$msg[1] = $this->cc[$i] . " is not a valid E-Mail Address";
return $msg;
}
}
}
else {
if(!$this->validateMailAddress($this->cc) && $this->cc != "") {
$msg[0] = false;
$msg[1] = "CC E-Mail Address is not valid";
return $msg;
}
}
if(is_array($this->bcc)) {
$s = sizeof($this->bcc);
for($i=0; $i<$s; $i++) {
if(!$this->validateMailAddress($this->bcc[$i]) && $this->bcc[$i] != "") {
$msg[0] = false;
$msg[1] = $this->bcc[$i] . " is not a valid E-Mail Address";
return $msg;
}
}
}
else {
if(!$this->validateMailAddress($this->bcc) && $this->bcc != "") {
$msg[0] = false;
$msg[1] = "BCC E-Mail Address is not valid";
return $msg;
}
}
if(is_array($this->reply_to)) {
$msg[0] = false;
$msg[1] = "You should provide only one Reply-to address";
return $msg;
}
else {
if(!$this->validateMailAddress($this->reply_to)) {
$msg[0] = false;
$msg[1] = "Reply-to E-Mail Address is not valid";
return $msg;
}
}
if(is_array($this->return_path)) {
$msg[0] = false;
$msg[1] = "You should provide only one Return-Path address";
return $msg;
}
else {
if(!$this->validateMailAddress($this->return_path)) {
$msg[0] = false;
$msg[1] = "Return-Path E-Mail Address is not valid";
return $msg;
}
}
$msg[0] = true;
return $msg;
}
function SendMail() {
$mess = $this->Validate();
if(!$mess[0]) {
return $mess;
}
# Common Headers
$headers = "From: " . $this->from . "\r\n";
$headers .= "To: <" . $this->to . ">\r\n";
if(is_array($this->cc)) {
$headers .= "Cc: " . implode(", ", $this->cc) . "\r\n";
}
else {
if($this->cc != "") {
$headers .= "Cc: " . $this->cc . "\r\n";
}
}
if(is_array($this->bcc)) {
$headers .= "BCc: " . implode(", ", $this->bcc) . "\r\n";
}
else {
if($this->bcc != "") {
$headers .= "BCc: " . $this->bcc . "\r\n";
}
}
// these two to set reply address
$headers .= "Reply-To: " . $this->reply_to . "\r\n";
$headers .= "Return-Path: " . $this->return_path . "\r\n";
// these two to help avoid spam-filters
$headers .= "Message-ID: <message-on " . date("d-m-Y h:i:s A") . "@".$_SERVER['SERVER_NAME'].">\r\n";
$headers .= "X-Mailer: " . $this->x_mailer . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
# Tell the E-Mail client to look for multiple parts or chunks
$headers .= "Content-type: multipart/mixed; boundary=AttachMail0123456\r\n";
# Message Starts here
$msg = "--AttachMail0123456\r\n";
$msg .= "Content-type: multipart/alternative; boundary=AttachMail7890123\r\n\r\n";
$msg .= "--AttachMail7890123\r\n";
$msg .= "Content-Type: text/plain; charset=iso-8859-1\r\n";
$msg .= "Content-Transfer-Encoding: quoted-printable\r\n\r\n";
$msg .= strip_tags($this->message) . "\r\n";
$msg .= "--AttachMail7890123\r\n";
$msg .= "Content-Type: text/html; charset=iso-8859-1\r\n";
$msg .= "Content-Transfer-Encoding: quoted-printable\r\n\r\n";
$msg .= "<html><head></head><body>" . $this->message . "</body></html>\r\n";
$msg .= "--AttachMail7890123--\r\n";
if($this->attach_file_name != "" || is_array($this->attach_file_name)) {
$Attach = $this->processAttachment();
$s = sizeof($Attach['file_name']);
for($i=0; $i<$s; $i++) {
# Start of Attachment chunk
$msg .= "--AttachMail0123456\r\n";
$mimeHelper = new MimeType();
$mimeType = $mimeHelper->getMimeType($Attach['file_name'][$i]);
$msg .= "Content-Type: " . $mimeType . "; name=" . $Attach['file_name'][$i] . "\r\n";
$msg .= "Content-Transfer-Encoding: base64\r\n";
$msg .= "Content-Disposition: attachment; filename=" . $Attach['file_name'][$i] . "\r\n\r\n";
$msg .= $Attach['contents'][$i] . "\r\n";
}
}
$msg .= "--AttachMail0123456--";
$result = mail($this->to, $this->subject, $msg, $headers);
if ($result) {
$mess[0] = true;
$mess[1] = "Mail successfully delivered.";
}
else {
$mess[0] = false;
$mess[1] = "Mail can not be sent this time. Please try later.";
}
return $mess;
}
}
?>
| true |
99cdae9b342c71ec405b1f513fe4097cd25241c4 | PHP | klerik86elvin/lio | /app/Http/Controllers/API/DepartmentController.php | UTF-8 | 2,488 | 2.625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers\API;
use App\Department;
use App\Http\Controllers\Controller;
use App\Http\Requests\DepartmentRequest;
use Illuminate\Http\Request;
class DepartmentController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$data = [
'message' => 'success',
'data' => Department::all(),
];
return response()->json($data,200);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(DepartmentRequest $request)
{
$data = [
'message' => '',
'data' => null,
];
$dep = Department::create([
'name' => $request->name,
]);
if ($dep)
{
$data['message'] = 'success';
return response()->json($data, 200);
}
else
{
$data['message'] = 'error';
return response()->json($data, 500);
}
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$department = Department::findOrFail($id);
$data = [
'message' => 'success',
'data' => $department,
];
return response()->json($data, 200);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(DepartmentRequest $request, $id)
{
$department = Department::findOrFail($id);
$data = [
'message' => 'success',
'data' => $department,
];
$department->update([
'name' => $request->name,
]);
return response()->json($data, 200);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$department = Department::findOrFail($id);
$data = [
'message' => 'success',
'data' => null
];
$department->delete();
return response()->json($data, 200);
}
}
| true |
5457562a24fa9deea2e188f423a242afa4d22a74 | PHP | Y-B-Preethishchandra/RFID-Attendance-System | /MARKATTENDANCE/code.php | UTF-8 | 1,794 | 2.71875 | 3 | [] | no_license | <?php
$comPort = "/dev/ttyACM0"; //The com port address. This is a debian address
$msg = '';
include 'php_serial.class.php';
if(isset($_POST["Recieve"])){
$flag=0;
$serial = new phpSerial;
$serial->deviceSet($comPort);
$serial->confBaudRate(9600);
$serial->confParity("none");
$serial->confCharacterLength(8);
$serial->confStopBits(1);
$serial->deviceOpen();
sleep(2); //Unfortunately this is nessesary, arduino requires a 2 second delay in order to receive the message
$read = $serial->readPort();
//print_r($read);
if((strlen($read)!=0))
{
$uid=explode(" ",$read);
$uidno=array($uid[1],$uid[2],$uid[3],$uid[4]);
$uidstr=$uid[1].$uid[2].$uid[3].$uid[4];
$fp=fopen("classdetails.txt","r") or die ("Unable to open file");
$subject=fgets($fp);
$date=explode("-",fgets($fp));
$date1=$date[0]."/".$date[1]."/".$date[2];
$classtype=fgets($fp);
$classno=(int)fgets($fp);
echo $classno;
//echo $uidstr;
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "attendance";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//echo $subject;
$query = "INSERT INTO ".$subject." (RFID,DATE,CLASS) VALUES ('$uidstr','$date1','$classno');";
//echo $query;
mysqli_query($conn, $query);
if(strcmp($classtype,"Block")){
$classno=$classno+1;
//echo $classno;
$query = "INSERT INTO ".$subject." (RFID,DATE,CLASS) VALUES ('$uidstr','$date1','$classno');";
mysqli_query($conn, $query);
}
echo "<script>alert('success');</script>";
mysqli_close($conn);
$serial->deviceClose();
echo "<script>alert('Marked')</script>";
sleep(5);
header("Location: firstadd.php");
}
else{
echo "<script>alert('RFID NOT FOUND')</script>";
$serial->deviceClose();
//header("Location: error.php");
}
}
?>
| true |
6e2899783305379d0471a1bbb9e209dfaf95b083 | PHP | brunofalcaodev/nidavellir-cube | /src/helpers.php | UTF-8 | 251 | 3.09375 | 3 | [] | no_license | <?php
if (! function_exists('array_to_string')) {
function array_to_string($array)
{
$result = '';
foreach ($array as $key => $value) {
$result .= $key.':'.$value."\r\n";
}
return $result;
}
}
| true |
600db9744346547efa31d7bbe53b1956e3fbf0dc | PHP | muranodesign/Hospital | /beans/GrauInstrucao.php | UTF-8 | 804 | 2.515625 | 3 | [] | no_license |
<?php
/*
*
* -------------------------------------------------------
* CLASSNAME: GrauInstrucao
* GENERATION DATE: 11.06.2015
* FOR MYSQL TABLE: grau_instrucao
* FOR MYSQL DB: hcb_criancas
* -------------------------------------------------------
* CODE GENERATED BY:
* @MURANO DESIGN
* -------------------------------------------------------
*
*/
class GrauInstrucao
{
private $grt_id;
private $grt_instrucao;
public function GrauInstrucao()
{
}
public function getGrt_id()
{
return $this->grt_id;
}
public function getGrt_instrucao()
{
return $this->grt_instrucao;
}
public function setGrt_id($val)
{
$this->grt_id = $val;
}
public function setGrt_instrucao($val)
{
$this->grt_instrucao = $val;
}
}
?>
| true |
4c7cf32d8089f84a3402939a835a6523efd7e666 | PHP | girish979/CodingChallenges | /001_Calculate_Process_Running_Time/index.php | UTF-8 | 1,175 | 2.765625 | 3 | [] | no_license | <?php
require __DIR__ . '/StateUtils.class.php';
require __DIR__ . '/SomeObject.class.php';
// Feel free to test your code here - we'll have our own tester to run the code
// you wrote in the StateUtils class.
// ===== THE TEST CASES =====
// TEST CASE 13
$startDate = null;
$stopDate = date("U", strtotime("2015-10-15"));
$statusLog = array(
array(
'date' => date("U", strtotime("2015-10-13")),
'oldState' => null,
'newState' => 'PAUSED'
),
array(
'date' => date("U", strtotime("2015-10-14")),
'oldState' => 'PAUSED',
'newState' => 'RUNNING'
),
array(
'date' => date("U", strtotime("2015-10-15")),
'oldState' => 'RUNNING',
'newState' => 'PAUSED'
),
array(
'date' => date("U", strtotime("2015-10-16")),
'oldState' => 'PAUSED',
'newState' => 'RUNNING'
),
array(
'date' => date("U", strtotime("2015-10-17")),
'oldState' => 'RUNNING',
'newState' => 'PAUSED'
)
);
$answer9 = 24 * 60 * 60;
$testObject9 = new SomeObject($statusLog, $startDate, $stopDate);
echo "Required: $answer9<br>";
echo "---actual : ".StateUtils::calculateTimeInState($statusLog, $startDate, $stopDate)."<br><br>";
?> | true |
47496c826cd5290f055d2767609b403ca938572b | PHP | 1-Touch/midrubPost | /application/base/classes/plans/usage.php | UTF-8 | 1,647 | 3.046875 | 3 | [] | no_license | <?php
/**
* Usage Class
*
* This file loads the Usage Class with properties used to display plan's usage
*
* @author Scrisoft
* @package Midrub
* @since 0.0.8.0
*/
// Define the page namespace
namespace MidrubBase\Classes\Plans;
// Constants
defined('BASEPATH') OR exit('No direct script access allowed');
/*
* Usage class loads the properties used to display plan's usage
*
* @author Scrisoft
* @package Midrub
* @since 0.0.8.0
*/
class Usage {
/**
* Contains and array with saved usage
*
* @since 0.0.8.0
*/
public static $the_usage = array();
/**
* The public method set_usage adds a collection with plan's usage to the list
*
* @param array $args contains the plan's usage
*
* @since 0.0.8.0
*
* @return void
*/
public function set_usage($args) {
if ( $args ) {
foreach ( $args as $arg ) {
// Verify if collection with plan's usage is valid
if ( isset($arg['name']) && isset($arg['value']) && isset($arg['limit']) && isset($arg['left']) ) {
// Add usage to the list
self::$the_usage[] = $arg;
}
}
}
}
/**
* The public method load_usage loads all apps usage
*
* @since 0.0.8.0
*
* @return array with usage or boolean false
*/
public function load_usage() {
// Verify if usage exists
if ( self::$the_usage ) {
return self::$the_usage;
} else {
return false;
}
}
}
/* End of file usage.php */ | true |
52a7e473f729f96631890bfbc7837a85c4f371a2 | PHP | syakirali/Registrasi-Slim- | /app/controllers/AuthController.php | UTF-8 | 2,570 | 2.546875 | 3 | [] | no_license | <?php
namespace App\Controllers;
use Slim\Container;
use App\User;
class AuthController
{
protected $container;
protected $view;
public static $user;
public function __construct(Container $container) {
$this->container = $container;
$this->view = $this->container->get('view');
$this->logger = $this->container->get('logger');
}
public function login($request, $response, $args) {
if (isset ($_POST['email']) && isset ($_POST['katasandi'])) {
$user = User::where('email', $_POST['email'])
->where('password', $_POST['katasandi']);
if ($user = $user->first()) {
$token = md5(date('Y-m-d H:i:s'));
$user->token = $token;
$user->save();
if (isset($_POST['simpan'])) {
setcookie('ppmb_unair_token', $token, time()+86400, "/", $_SERVER['HTTP_HOST'], 0, 1);
setcookie('ppmb_unair_email', $user->email, time()+86400, "/", $_SERVER['HTTP_HOST'], 0, 1);
$_SESSION['ppmb_unair_token'] = $token;
$_SESSION['ppmb_unair_email'] = $user->email;
} else {
$_SESSION['ppmb_unair_token'] = $token;
$_SESSION['ppmb_unair_email'] = $user->email;
}
return $response->withRedirect('/tampil');
}
$this->logger->warning('email:' . $_POST['email'] . ', katasandi:' . $_POST['katasandi']);
}
return $this->view->render($response, 'login.phtml');
}
public function form($request, $response, $args)
{
if (self::getUser()) {
return $response->withStatus(302)->withHeader('Location', '/tampil');
}
return $this->view->render($response, 'login.phtml');
}
public static function getUser() {
$email;
$token;
if (isset($_SESSION['ppmb_unair_token'])) {
if (isset($_SESSION['ppmb_unair_email'])) {
$email = $_SESSION['ppmb_unair_email'];
$token = $_SESSION['ppmb_unair_token'];
}
} else if (isset($_COOKIE['ppmb_unair_token'])) {
if (isset($_COOKIE['ppmb_unair_email'])) {
$email = $_COOKIE['ppmb_unair_email'];
$token = $_COOKIE['ppmb_unair_token'];
}
} else {
return false;
}
$user = User::where('email', $email)
->where('token', $token)
->first();
return $user;
}
}
| true |
a186f4c9e81211fa82983c12dc250b2f66cc87b1 | PHP | Astrarel/php_injectionSQL | /tests/InjectionTest.php | UTF-8 | 1,449 | 2.84375 | 3 | [] | no_license | <?php
// Pour exécuter le test, il faut rentrer dans le terminal la commande suivante : ./vendor/bin/phpunit
class InjectionTest extends \PHPUnit\Framework\TestCase {
public function test_unNomUnique_trouverUtilisateur_devraitRetournerLeLclient()
{
$bdd = new Model\Bdd.php();
$Nomuser = new Controller\Nom('Jalel');
$this->assertEquals(1,'Ligne de commande pour savoir si $Nomuser contitent le prénom Jalel','il doit contenir le prénom Jalel');
}
public function test_doublonDeNom_trouverParNom_devraitRetournerLesDeuxClients(){
$bdd = new Model\Bdd();
$Nomuser = new Controller\Nom('Kyllian');
$this->assertEquals(2,'Ligne de commande pour savoir si $Nomuser contitent deux fois le prénom Kyllian','il doit contenir deux fois le prénom Kyllian');
}
public function test_aucunNom_trouverParNom_devraitRetournerZeroClient()
{
$bdd = new Model\Bdd();
$Nomuser = new Controller\Nom('Toto');
$this->assertEquals(0,'Ligne de commande pour savoir si $Nomueser contitent le prénom Toto','il ne doit avoir aucun utilisateur Toto');
}
public function test_injection_trouverparnom_devraitrenvoyerZeroClient(){
$bdd = new Model\Bdd();
$Nomuser = new Controller\Nom("Pirate or '1' = '1'");
$this->assertEquals(0,'Ligne de commande pour savoir si $Nomuser contient le prénom Kyllian','Injection réussi');
}
} | true |
8a85710b015b6f5211ab981a5ac03f19ccc8326c | PHP | fikrirasyid/parchment | /content-hentry-separator.php | UTF-8 | 1,727 | 2.515625 | 3 | [] | no_license | <?php
// Update the date in given condition
if( isset( $GLOBALS['wp_query'] ) && is_sticky() ){
$GLOBALS['wp_query']->has_sticky = true;
}
if( isset( $GLOBALS['wp_query'] ) && !is_sticky() ){
// Define date index
if( !isset( $GLOBALS['wp_query']->parchment_date ) ){
$date_index = 0;
} else {
$date_index = $GLOBALS['wp_query']->parchment_date;
}
// Define timestamp
$timestamp = strtotime( $post->post_date );
// Define date, month and year
$date = date( 'Y-m-d', $timestamp );
// Print hentry-day
if( $date_index != $date ){
if( !isset( $GLOBALS['wp_query']->query['paged'] ) && !isset( $GLOBALS['wp_query']->has_sticky ) && $date_index == 0 ){
echo '<h4 class="hentry-day on-page-cover" data-date="'. $date .'"><span class="label">' . date( __( 'l, j F Y', 'parchment' ), $timestamp ) . '</span><span class="border"></span></h4>';
} else if( isset( $GLOBALS['wp_query']->query['paged'] ) && !isset( $GLOBALS['wp_query']->has_sticky ) && $date_index == 0 && !isset( $GLOBALS['wp_query']->query['nopaging'] ) ){
echo '<h4 class="hentry-day on-page-cover" data-date="'. $date .'"><span class="label">' . date( __( 'l, j F Y', 'parchment' ), $timestamp ) . '</span><span class="border"></span></h4>';
} else {
echo '<h4 class="hentry-day" data-date="'. $date .'"><span class="label">' . date( __( 'l, j F Y', 'parchment' ), $timestamp ) . '</span><span class="border"></span></h4>';
}
}
// Print marker
$month_label = date( 'F', $timestamp );
echo "<span style='display: none;' class='article-marker' data-date='$date' data-month='$month_label' data-year='$year'></span>";
// Set globals
$GLOBALS['wp_query']->parchment_date = $date;
} | true |
69ad8276d5a29893f553fc610b63e2817cf7a8d1 | PHP | NANAADDO/Teknasyon-PHP-Challenge | /app/Helpers/Backend/Report.php | UTF-8 | 645 | 2.546875 | 3 | [] | no_license | <?php
namespace App\Helpers\Backend;
use Illuminate\Support\Facades\DB;
class Report {
protected static $country_table = 'country_c';
public static function get_country_admin_level($countryID){
$resp = DB::table(self::$country_table)->select('admin_level')->where('id',$countryID)->first();
if(!empty($resp)){
$data =$resp->admin_level;
}
else{
$data = 0;
}
return $data;
}
public static function validate_data($data){
if(isset($data)){
return $data;
}
else{
return '';
}
}
}
| true |
875c224c93256a5d201db3719bc99295816e8650 | PHP | phpCedu/micro-service-framework | /src/MSF/Response/HTTPResponse.php | UTF-8 | 756 | 2.765625 | 3 | [
"MIT"
] | permissive | <?php
namespace MSF\Response;
class HTTPResponse extends \MSF\Response {
// associative
public $headers = array();
// The idea is that we can add annotations, but not all transports have a way of supporting them, maybe?
// We were going to encode some data in HTTP headers, so an HTTPTransport would take the annotations and convert them to headers
protected $_oob = array();
public function oob($key=null, $value=null) {
if (is_null($key)) {
return $this->_oob;
}
if (is_null($value)) {
if (isset($this->_oob[$key])) {
return $this->_oob[$key];
} else {
return null;
}
}
$this->_oob[$key] = $value;
}
}
| true |
94706aac9384d58439438234b08feae981d0784a | PHP | Mario-Cipriano/hw2 | /app/Http/Controllers/LoginController.php | UTF-8 | 790 | 2.546875 | 3 | [
"MIT"
] | permissive | <?php
use Illuminate\Routing\Controller;
use App\Models\User;
class LoginController extends Controller{
public function login(){
if(session("user_id")!==null){
return redirect("home");
}
else {
return view("login");
}
}
public function checkLogin(){
$request=request();
$hash_pass=hash('sha256', $request->password);
$pass_base64=base64_encode($hash_pass);
$user=User::where('username',request('username'))->where('password',$pass_base64)->first();
if(isset($user)){
Session::put('user_id',$user->id);
return redirect("home");
}
else {
return view("login")->with("errore","Credenziali non valide.");
}
}
public function logout(){
Session::flush();
return redirect("homepage_no_session");
}
}
?> | true |
f94e9773328525a3d62371a5a2dc14dbd4496c54 | PHP | flyyi/fend | /tests/fend/Db/sqlBuilderTest.php | UTF-8 | 25,186 | 2.546875 | 3 | [
"Apache-2.0"
] | permissive | <?php
declare(strict_types = 1);
namespace App\Test\Fend\Db;
use Fend\Read;
use Fend\Write;
use http\Exception\RuntimeException;
use PHPUnit\Framework\TestCase;
class moduleTest extends TestCase
{
private $_table = 'users';
private $_db = 'fend_test';
public function testDateQueryCondition()
{
$mod = Read::Factory($this->_table, $this->_db);
$conditions = [
'>=' => [
'created_at' => '2019-09-02'
]
];
try{
$list = $mod->getListByCondition($conditions);
}catch(\Exception $e) {
}
self::assertEquals($mod->getLastSQL()["sql"],"SELECT * FROM users WHERE created_at >= '2019-09-02' LIMIT 0,20");
$conditions = [
"id" => "03883231207814667379197355882525",
];
try{
$list = $mod->getListByCondition($conditions);
}catch(\Exception $e) {
}
self::assertEquals($mod->getLastSQL()["sql"],"SELECT * FROM users WHERE `id` = '03883231207814667379197355882525' LIMIT 0,20");
}
public function testNewWhere()
{
$mod = Read::Factory($this->_table, $this->_db);
$where = [
"(",
"(",
['fend_test.`db`.user_id', 14],
['users.user_name', 'oak'],
['`users`.user_id', ">=", 0],
")",
"OR",
"(",
['`user_id`', "<=", 10000],
['user_id', "like", '57%'],
")",
")",
"OR",
['user_id', "in", [1, 2, 3, 4, 5, 6]],
"OR",
"(",
['user_id', "not in", ['a', 'c', 'd', 'f']],
" `user_name` = 'yes' ",
")",
];
$mod->where($where);
$sql = $mod->getSql();
self::assertEquals('SELECT * FROM users WHERE ( ( `fend_test`.`db`.`user_id` = \'14\' AND `users`.`user_name` = \'oak\' AND `users`.`user_id` >= \'0\' ) OR ( `user_id` <= \'10000\' AND `user_id` like \'57%\' ) ) OR `user_id` in (\'1\',\'2\',\'3\',\'4\',\'5\',\'6\') OR ( `user_id` not in (\'a\',\'c\',\'d\',\'f\') AND `user_name` = \'yes\' ) ', $sql);
}
public function testNoPrepareGetList()
{
$con = array(">" => ["id" => 0], "user_sex" => 1);
$field = array("*");
$start = 0;
$limit = 20;
$mod = Read::Factory($this->_table, $this->_db);
$mod->setConditions($con);
$mod->setField($field);
$mod->setLimit($start, $limit);
$sql = $mod->getSql();
self::assertEquals("SELECT * FROM users WHERE id > '0' AND `user_sex` = '1' LIMIT 0,20", $sql);
$q = $mod->query($sql);
//return check
self::assertNotEmpty($q);
self::assertIsObject($q);
self::assertInstanceOf(\mysqli_result::class, $q);
self::assertEquals(2, $mod->getSum());
while ($rs = $mod->fetch($q)) {
$result['list'][] = $rs;
}
//result check
self::assertEquals($result["list"][0]["id"], 3);
self::assertEquals($result["list"][1]["id"], 5);
$count = $mod->getSum();
self::assertEquals(2, $count);
}
public function testNoPrepareGetListFirstIsNum()
{
$con = array("user_sex" => 1, ">" => ["id" => 0]);
$field = array("*");
$start = 0;
$limit = 20;
$mod = Read::Factory($this->_table, $this->_db);
$mod->setConditions($con);
$mod->setField($field);
$mod->setLimit($start, $limit);
$sql = $mod->getSql();
self::assertEquals("SELECT * FROM users WHERE `user_sex` = '1' AND id > '0' LIMIT 0,20", $sql);
}
public function testPrepareGetList()
{
$con = array(">" => ["id" => '?'], "user_sex" => '?');
$bindparam = array(0, 1);
$field = array("*");
$start = 0;
$limit = 20;
$mod = Read::Factory($this->_table, $this->_db);
$mod->setConditions($con);
$mod->setField($field);
$mod->setLimit($start, $limit);
$sql = $mod->getSql();
self::assertEquals("SELECT * FROM users WHERE id > ? AND `user_sex` = ? LIMIT 0,20", $sql);
$q = $mod->query($sql, $bindparam);
//return check
self::assertNotEmpty($q);
self::assertIsObject($q);
self::assertInstanceOf(\mysqli_result::class, $q);
self::assertEquals(2, $mod->getSum($bindparam));
while ($rs = $mod->fetch($q)) {
$result['list'][] = $rs;
}
//result check
self::assertEquals($result["list"][0]["id"], 3);
self::assertEquals($result["list"][1]["id"], 5);
$count = $mod->getSum($bindparam);
self::assertEquals(2, $count);
}
public function testPrepareNewWhere()
{
$mod = Read::Factory($this->_table, $this->_db);
$where = [
"(",
"(",
['fend_test.`db`.user_id', '?'],
['users.user_name', '?'],
['`users`.user_id', ">=", '?'],
")",
"OR",
"(",
['`user_id`', "<=", '?'],
['user_id', "like", '?'],
")",
")",
"OR",
['user_id', "in", ['?', '?', '?', '?', '?', '?']],
"OR",
"(",
['user_id', "not in", ['?', '?', '?', '?']],
" `user_name` = ? ",
")",
];
$mod->where($where);
$sql = $mod->getSql();
self::assertEquals('SELECT * FROM users WHERE ( ( `fend_test`.`db`.`user_id` = ? AND `users`.`user_name` = ? AND `users`.`user_id` >= ? ) OR ( `user_id` <= ? AND `user_id` like ? ) ) OR `user_id` in (?,?,?,?,?,?) OR ( `user_id` not in (?,?,?,?) AND `user_name` = ? ) ', $sql);
}
////////////////////////////////////////
/// PDO
////////////////////////////////////////
public function testPDONewWhere()
{
$mod = Read::Factory($this->_table, $this->_db, "MysqlPDO");
$where = [
"(",
"(",
['fend_test.`db`.user_id', 14],
['users.user_name', 'oak'],
['`users`.user_id', ">=", 0],
")",
"OR",
"(",
['`user_id`', "<=", 10000],
['user_id', "like", '57%'],
")",
")",
"OR",
['user_id', "in", [1, 2, 3, 4, 5, 6]],
"OR",
"(",
['user_id', "not in", ['a', 'c', 'd', 'f']],
" `user_name` = 'yes' ",
")",
];
$mod->where($where);
$sql = $mod->getSql();
self::assertEquals('SELECT * FROM users WHERE ( ( `fend_test`.`db`.`user_id` = \'14\' AND `users`.`user_name` = \'oak\' AND `users`.`user_id` >= \'0\' ) OR ( `user_id` <= \'10000\' AND `user_id` like \'57%\' ) ) OR `user_id` in (\'1\',\'2\',\'3\',\'4\',\'5\',\'6\') OR ( `user_id` not in (\'a\',\'c\',\'d\',\'f\') AND `user_name` = \'yes\' ) ', $sql);
}
public function testPDONoPrepareGetList()
{
$con = array(">" => ["id" => 0], "user_sex" => 1);
$field = array("*");
$start = 0;
$limit = 20;
$mod = Read::Factory($this->_table, $this->_db, "MysqlPDO");
$mod->setConditions($con);
$mod->setField($field);
$mod->setLimit($start, $limit);
$sql = $mod->getSql();
self::assertEquals("SELECT * FROM users WHERE id > '0' AND `user_sex` = '1' LIMIT 0,20", $sql);
$q = $mod->query($sql);
//return check
self::assertNotEmpty($q);
self::assertIsObject($q);
self::assertInstanceOf(\PDOStatement::class, $q);
self::assertEquals(2, $mod->getSum());
while ($rs = $mod->fetch($q)) {
$result['list'][] = $rs;
}
//result check
self::assertEquals($result["list"][0]["id"], 3);
self::assertEquals($result["list"][1]["id"], 5);
$count = $mod->getSum();
self::assertEquals(2, $count);
}
public function testPDONoPrepareGetListFirstIsNum()
{
$con = array("user_sex" => 1, ">" => ["id" => 0]);
$field = array("*");
$start = 0;
$limit = 20;
$mod = Read::Factory($this->_table, $this->_db, "MysqlPDO");
$mod->setConditions($con);
$mod->setField($field);
$mod->setLimit($start, $limit);
$sql = $mod->getSql();
self::assertEquals("SELECT * FROM users WHERE `user_sex` = '1' AND id > '0' LIMIT 0,20", $sql);
}
public function testPDOPrepareGetList()
{
$con = array(">" => ["id" => '?'], "user_sex" => '?');
$bindparam = array(0, 1);
$field = array("*");
$start = 0;
$limit = 20;
$mod = Read::Factory($this->_table, $this->_db, "MysqlPDO");
$mod->setConditions($con);
$mod->setField($field);
$mod->setLimit($start, $limit);
$sql = $mod->getSql();
self::assertEquals("SELECT * FROM users WHERE id > ? AND `user_sex` = ? LIMIT 0,20", $sql);
$q = $mod->query($sql, $bindparam);
//return check
self::assertNotEmpty($q);
self::assertIsObject($q);
self::assertInstanceOf(\PDOStatement::class, $q);
self::assertEquals(2, $mod->getSum($bindparam));
while ($rs = $mod->fetch($q)) {
$result['list'][] = $rs;
}
//result check
self::assertEquals($result["list"][0]["id"], 3);
self::assertEquals($result["list"][1]["id"], 5);
$count = $mod->getSum($bindparam);
self::assertEquals(2, $count);
}
public function testPDOPrepareNewWhere()
{
$mod = Read::Factory($this->_table, $this->_db, "MysqlPDO");
$where = [
"(",
"(",
['fend_test.`db`.user_id', '?'],
['users.user_name', '?'],
['`users`.user_id', ">=", '?'],
")",
"OR",
"(",
['`user_id`', "<=", '?'],
['user_id', "like", '?'],
")",
")",
"OR",
['user_id', "in", ['?', '?', '?', '?', '?', '?']],
"OR",
"(",
['user_id', "not in", ['?', '?', '?', '?']],
" `user_name` = ? ",
")",
];
$mod->where($where);
$sql = $mod->getSql();
self::assertEquals('SELECT * FROM users WHERE ( ( `fend_test`.`db`.`user_id` = ? AND `users`.`user_name` = ? AND `users`.`user_id` >= ? ) OR ( `user_id` <= ? AND `user_id` like ? ) ) OR `user_id` in (?,?,?,?,?,?) OR ( `user_id` not in (?,?,?,?) AND `user_name` = ? ) ', $sql);
}
private function getModuleInstance($table, $db, $style = 1)
{
if (1 === (int)$style) {
return Read::Factory($table, $db);
} else {
return Read::Factory($table, $db, "MysqlPDO");
}
}
public function testSetGetTable()
{
$resetTableName = 'user_info';
$this->getModuleInstance($this->_table, $this->_db)->setTable($resetTableName,$this->_db);
self::assertEquals($resetTableName,$this->getModuleInstance($resetTableName, $this->_db)->getTable());
}
public function testSqlSafe()
{
$mod = $this->getModuleInstance($this->_table, $this->_db);
$mod->setSqlSafe(true);
$sql = "select load_file('/tmp/1.txt')";
try{
$mod->query($sql);
} catch(\Exception $e) {
$res = $mod->getErrorInfo();
$worker = 1;
}
self::assertEquals(1, $worker);
}
public function testSetWhere()
{
$mod = $this->getModuleInstance($this->_table, $this->_db);
$mod->setWhere('id = 200');
self::assertEquals('id = 200',$mod->getWhere());
$mod->setWhere();
self::assertEquals('',$mod->getWhere());
}
public function testSetGroup()
{
$mod = $this->getModuleInstance($this->_table, $this->_db);
$mod->setGroup('id');
self::assertEquals('SELECT * FROM users GROUP BY id',$mod->getSql());
}
public function testRelation()
{
$table = 'user_info';
$mod = $this->getModuleInstance($this->_table, $this->_db);
$mod->setRelationTable($table);
$on = array(
'id' => 'user_id'
);
$mod->setRelationOn($on);
$field = array(
'user_id',
'score',
'gold'
);
$mod->setRelationField($field);
$conditions = 'users.id > 3';
$mod->setRelationWhere($conditions);
self::assertEquals('SELECT user_info.user_id,user_info.score,user_info.gold FROM users LEFT JOIN user_info ON users.id = user_info.user_id WHERE users.id > 3',$mod->getSql());
$mod->setField(array('users.id','users.account','users.user_name'));
$on = 'users.id = user_info.user_id';
$mod->setRelationOn($on);
$conditions = ['>'=>['id'=>3], '=' => ['gold'=>'1']];
$mod->setRelationWhere($conditions);
self::assertEquals('SELECT users.id,users.account,users.user_name,user_info.user_id,user_info.score,user_info.gold FROM users LEFT JOIN user_info ON users.id = user_info.user_id WHERE `user_info`.`id` > \'3\' AND `user_info`.`gold` = \'1\' ',$mod->getSql());
$infoMod = $this->getModuleInstance($table, $this->_db);
$infoMod->setRelationTable('users');
$infoMod->setRelationOn(array('user_id' => 'id'));
$infoMod->setRelationField(array('id','account','user_name'));
$conditions = ['>' => ['id' => 3], '=' =>['user_name' => 'hehe4']];
$infoMod->setRelationWhere($conditions);
$infoMod->setField($field);
self::assertEquals('SELECT user_id,score,gold,users.id,users.account,users.user_name FROM user_info LEFT JOIN users ON user_info.user_id = users.id WHERE `users`.`id` > \'3\' AND `users`.`user_name` = \'hehe4\' ', $infoMod->getSql());
$conditions = ['id' => 6, 'user_name' => 'hehe4'];
$infoMod->setRelationWhere($conditions);
self::assertEquals('SELECT user_id,score,gold,users.id,users.account,users.user_name FROM user_info LEFT JOIN users ON user_info.user_id = users.id WHERE `users`.`id` = \'6\' AND `users`.`user_name` = \'hehe4\'',$infoMod->getSql());
$conditions = ['<' => ['user_sex' => 1] ,'id' => 6, 'user_name' => 'hehe4'];
$infoMod->setRelationWhere($conditions);
self::assertEquals('SELECT user_id,score,gold,users.id,users.account,users.user_name FROM user_info LEFT JOIN users ON user_info.user_id = users.id WHERE `users`.`user_sex` < \'1\' AND `users`.`id` = \'6\' AND `users`.`user_name` = \'hehe4\'', $infoMod->getSql());
}
public function testGet()
{
$mod = $this->getModuleInstance($this->_table, $this->_db);
$sql = "select * from users where id = 1";
$res = $mod->get($sql);
self::assertEquals(null, $res);
}
public function testUseDb()
{
$mod = $this->getModuleInstance($this->_table, $this->_db);
self::assertArrayHasKey('test', array_flip($mod->fetch($mod->useDb('test')->query("select database()"))));
$res = $mod->fetch(array());
$mod->useDb('fend_test');
self::assertEquals(false, $res);
}
public function testSetTimeout()
{
$mod = $this->getModuleInstance($this->_table, $this->_db);
$mod->setTimeout();
$worker = 1;
self::assertEquals(1, $worker);
}
public function testGetErrorInfo()
{
$mod = $this->getModuleInstance($this->_table, $this->_db);
try{
$mod->useDb('userssssss;');
} catch(\Exception $e) {
$res = $mod->getErrorInfo();
$worker = 1;
}
self::assertEquals(1, $worker);
}
public function testSubSQL()
{
$mod = Write::Factory($this->_table, $this->_db);
$data = [
[
"account" => "test1",
"passwd" => "fjdklsfjdkslhfjdk",
"user_sex" => 1,
"user_name" => "test1",
"create_time" => 1565074615,
"update_time" => 1565074615
],
[
"account" => "test2",
"passwd" => "fjdkl'sf",
"user_sex" => 1,
"user_name" => "test10",
"create_time" => 1565074915,
"update_time" => 1565074415
],
];
//insertall
$sql = $mod->subSQL($data, $this->_table,'insertall');
self::assertEquals('INSERT INTO users (account,passwd,user_sex,user_name,create_time,update_time) VALUES (\'test1\',\'fjdklsfjdkslhfjdk\',\'1\',\'test1\',\'1565074615\',\'1565074615\'),(\'test2\',\'fjdkl\\\'sf\',\'1\',\'test10\',\'1565074915\',\'1565074415\')', $sql);
//insetall conditions = null
$sql = $mod->subSQL(array(), $this->_table,'insertall');
self::assertEquals(null, $sql);
//replace
$data = array(
"id" => 7,
"account" => "test2",
"passwd" => "locobve",
"user_sex" => 1,
"user_name" => "test10",
"create_time" => 1565074915,
"update_time" => 1565074415
);
$sql = $mod->subSQL($data, $this->_table,'replace');
self::assertEquals('REPLACE INTO users SET `id` = \'7\' , `account` = \'test2\' , `passwd` = \'locobve\' , `user_sex` = \'1\' , `user_name` = \'test10\' , `create_time` = \'1565074915\' , `update_time` = \'1565074415\' ', $sql);
//ifupdate $duplicate = array()
$sql = $mod->subSQL($data, $this->_table,'ifupdate', null, array());
self::assertEquals('INSERT INTO users SET `id` = \'7\' , `account` = \'test2\' , `passwd` = \'locobve\' , `user_sex` = \'1\' , `user_name` = \'test10\' , `create_time` = \'1565074915\' , `update_time` = \'1565074415\' ON DUPLICATE KEY UPDATE `id` = \'7\' , `account` = \'test2\' , `passwd` = \'locobve\' , `user_sex` = \'1\' , `user_name` = \'test10\' , `create_time` = \'1565074915\' , `update_time` = \'1565074415\' ', $sql);
//ifupdate $duplicate = !empty
$duplicate = array(
"id" => 7,
"account" => "test2",
"passwd" => "yngwie",
"user_sex" => 1,
"user_name" => "test10",
"create_time" => 1565074915,
"update_time" => 1565074415
);
$sql = $mod->subSQL($data, $this->_table,'ifupdate', null, $duplicate);
self::assertEquals('INSERT INTO users SET `id` = \'7\' , `account` = \'test2\' , `passwd` = \'locobve\' , `user_sex` = \'1\' , `user_name` = \'test10\' , `create_time` = \'1565074915\' , `update_time` = \'1565074415\' ON DUPLICATE KEY UPDATE `id`=\'7\',`account`=\'test2\',`passwd`=\'yngwie\',`user_sex`=\'1\',`user_name`=\'test10\',`create_time`=\'1565074915\',`update_time`=\'1565074415\'',$sql);
$duplicate = $mod->makePrepareData($data);
$sql = $mod->subSQL($data, $this->_table,'ifupdate', null, $duplicate[0]);
self::assertEquals('INSERT INTO users SET `id` = \'7\' , `account` = \'test2\' , `passwd` = \'locobve\' , `user_sex` = \'1\' , `user_name` = \'test10\' , `create_time` = \'1565074915\' , `update_time` = \'1565074415\' ON DUPLICATE KEY UPDATE `id`=?,`account`=?,`passwd`=?,`user_sex`=?,`user_name`=?,`create_time`=?,`update_time`=?',$sql);
//default
$sql = $mod->subSQL($data, $this->_table,'xxx');
self::assertEquals(null, $sql);
//make += operation
$sql = $mod->subSQL(["create_time" => ["+", 1]],$this->_table,'update', [],[]);
self::assertEquals('UPDATE users SET `create_time` = `create_time` + 1',$sql);
}
/**
* 方法未完成
*/
public function testGetSqlSum()
{
$mod = $this->getModuleInstance($this->_table, $this->_db);
$mod->setRelationTable('user_info');
$mod->setRelationOn(['id' => 'user_id']);
$sql = $mod->getSqlSum();
self::assertEquals('SELECT COUNT(*) AS total FROM users LEFT JOIN user_info ON users.id = user_info.user_id', $sql);
$mod->setRelationWhere('user_info.user_id > 3');
$mod->setWhere('users.id > 3'); //setWhere before setRelationWhere
$sql = $mod->getSqlSum();
//todo:方法未完成
//var_dump($sql);
//self::assertEquals('', $sql);
$mod->setWhere('');
$sql = $mod->getSqlSum();
self::assertEquals('SELECT COUNT(*) AS total FROM users LEFT JOIN user_info ON users.id = user_info.user_id WHERE user_info.user_id > 3', $sql);
$mod->setGroup('id');
$sql = $mod->getSqlSum();
self::assertEquals('SELECT COUNT(*) AS total FROM users LEFT JOIN user_info ON users.id = user_info.user_id WHERE user_info.user_id > 3 GROUP BY id',$sql);
}
public function testDoQuerySafe()
{
$mod = $this->getModuleInstance($this->_table, $this->_db);
$sql = "select * from users into outfile '/tmp/test.txt'";
self::assertEquals(false, $mod->checkquery($sql));
$sql = "select (@i:=@i+1) as rownum from users,(select @i:=1) as init /*sth here*/";
self::assertEquals(false, $mod->checkquery($sql));
$sql = "select (@i:=@i+1) as rownum from users,(select @i:=1) as init #sth here \n";
self::assertEquals(false, $mod->checkquery($sql));
//$sql = "select * from users -- sth here";
//self::assertEquals(false, $mod->checkquery($sql));
$sql = "select * from users where user_name like 0x736563757265";
self::assertEquals(false, $mod->checkquery($sql));
}
public function testOthers()
{
$mod = $this->getModuleInstance($this->_table, $this->_db);
$res = $mod->makePrepareCondition("id > 1");
self::assertEquals(['id > 1',[]],$res);
$res = $mod->makePrepareWhere(['id > 1']);
self::assertEquals([['id > 1'],[]],$res);
$mod->setConditions('id > 3');
$worker = 1;
self::assertEquals(1, $worker);
$mod->setConditions(['>' => ['id' => 3], '=' =>['user_name' => 'hehe4']]);
$worker = 2;
self::assertEquals(2, $worker);
$mod->setConditions(['id' => null]);
$worker = 3;
self::assertEquals(3, $worker);
$table = 'user_info';
$mod->setRelationTable($table);
$on = array(
'id' => 'user_id'
);
$mod->setRelationOn($on);
$field = array(
'user_id',
'score',
'gold'
);
$mod->setRelationField($field);
$conditions = 'user_info.user_id > 3';
$mod->setRelationWhere($conditions);
$mod->setWhere('users.id > 3');
self::assertEquals('SELECT user_info.user_id,user_info.score,user_info.gold FROM users LEFT JOIN user_info ON users.id = user_info.user_id WHERE users.id > 3 AND user_info.user_id > 3', $mod->getSql());
unset($mod);
$mod = $this->getModuleInstance($this->_table, $this->_db);
$where = [
"(",
"(",
['fend_test.`db`.user_id', 14],
['users.user_name', 'oak'],
['`users`.user_id', ">=", 0],
")",
"OR",
"(",
['`user_id`', "<=", 10000],
['user_id', "like", '57%'],
")",
")",
"OR",
['user_id', "in", [1, 2, 3, 4, 5, 6]],
"OR",
"(",
['user_id', "not in", ['a', 'c', 'd', 'f']],
" `user_name` = 'yes' ",
")",
"AND",
"'user_id' != 0"
];
$mod->where($where);
$sql = $mod->getSql();
self::assertEquals("SELECT * FROM users WHERE ( ( `fend_test`.`db`.`user_id` = '14' AND `users`.`user_name` = 'oak' AND `users`.`user_id` >= '0' ) OR ( `user_id` <= '10000' AND `user_id` like '57%' ) ) OR `user_id` in ('1','2','3','4','5','6') OR ( `user_id` not in ('a','c','d','f') AND `user_name` = 'yes' ) AND 'user_id' != 0",$sql);
}
public function testLock()
{
$con = array(">" => ["id" => 0], "user_sex" => 1);
$field = array("*");
$start = 0;
$limit = 20;
$mod = Read::Factory($this->_table, $this->_db);
$sql = $mod->clean()->setConditions($con)->setField($field)->setLimit($start, $limit)->lock()->getSql();
self::assertEquals($sql, "SELECT * FROM users WHERE id > '0' AND `user_sex` = '1' LIMIT 0,20 FOR UPDATE");
$sql = $mod->clean()->setConditions($con)->setField($field)->setLimit($start, $limit)->shareLock()->getSql();
self::assertEquals($sql, "SELECT * FROM users WHERE id > '0' AND `user_sex` = '1' LIMIT 0,20 LOCK IN SHARE MODE");
}
} | true |
3bc95550f8015d46f84211c0ecf4aa6aa4a06428 | PHP | ipetrovbg/homeworks | /php-if/task5.php | UTF-8 | 1,087 | 3.078125 | 3 | [] | no_license |
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Задача 5 - Точка в окръжност или извън окръжност</title>
</head>
<body>
<?php
if(!empty($_GET['sub'])){
$centerx = 0;
$centery = 0;
$radius = 2;
$coordinatex = $_GET['x'];
$coordinatey = $_GET['y'];
$sqrt = sqrt(($centerx - $coordinatex) * ($centerx - $coordinatex) + ($centery - $coordinatey) * ($centery - $coordinatey));
if($sqrt < $radius){
echo 'Координатите са в окръжността';
}elseif($sqrt == $radius){
echo 'Координатите са на окръжността';
}else{
echo 'Координатите са извън окръжността';
}
}
?>
<form method="get" action="">
Въведете координати по х: <input type="numeric" name="x" value="" /><br />
Въведете координати по y: <input type="numeric" name="y" value="" /><br />
<input type="submit" name="sub" value="Изчисляване" />
</form>
</body>
</html> | true |
052f414166dc7bb8a3e33806862fabf0f0d43778 | PHP | phptek/cwp | /code/pagetypes/DatedUpdateHolder.php | UTF-8 | 15,501 | 2.75 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
class DatedUpdateHolder extends Page {
// Meant as an abstract base class.
private static $hide_ancestor = 'DatedUpdateHolder';
private static $update_name = 'Updates';
private static $update_class = 'DatedUpdatePage';
private static $singular_name = 'Dated Update Holder';
private static $plural_name = 'Dated Update Holders';
/**
* Find all distinct tags (TaxonomyTerms) associated with the DatedUpdatePages under this holder.
*/
public function UpdateTags() {
$tags = TaxonomyTerm::get()
->innerJoin('BasePage_Terms', '"TaxonomyTerm"."ID"="BasePage_Terms"."TaxonomyTermID"')
->innerJoin(
'SiteTree',
sprintf('"SiteTree"."ID" = "BasePage_Terms"."BasePageID" AND "SiteTree"."ParentID" = \'%d\'', $this->ID)
)
->sort('Name');
return $tags;
}
/**
* Wrapper to find all updates belonging to this holder, based on some filters.
*/
public function Updates($tagID = null, $dateFrom = null, $dateTo = null, $year = null, $monthNumber = null) {
$className = Config::inst()->get($this->ClassName, 'update_class');
return static::AllUpdates($className, $this->ID, $tagID, $dateFrom, $dateTo, $year, $monthNumber);
}
/**
* Find all site's updates, based on some filters.
* Omitting parameters will prevent relevant filters from being applied. The filters are ANDed together.
*
* @param string $className The name of the class to fetch.
* @param int|null $parentID The ID of the holder to extract the updates from.
* @param int|null $tagID The ID of the tag to filter the updates by.
* @param string|null $dateFrom The beginning of a date filter range.
* @param string|null $dateTo The end of the date filter range. If empty, only one day will be searched for.
* @param int|null $year Numeric value of the year to show.
* @param int|null $monthNumber Numeric value of the month to show.
*
* @returns DataList | PaginatedList
*/
public static function AllUpdates($className = 'DatedUpdatePage', $parentID = null, $tagID = null, $dateFrom = null,
$dateTo = null, $year = null, $monthNumber = null) {
$items = $className::get();
$dbTableName = ClassInfo::table_for_object_field($className, 'Date');
if (!$dbTableName) {
$dbTableName = 'DatedUpdatePage';
}
// Filter by parent holder.
if (isset($parentID)) {
$items = $items->filter(array('ParentID'=>$parentID));
}
// Filter down to a single tag.
if (isset($tagID)) {
$items = $items->innerJoin(
'BasePage_Terms',
sprintf('"%s"."ID" = "BasePage_Terms"."BasePageID"', $className)
)->innerJoin(
'TaxonomyTerm',
sprintf('"BasePage_Terms"."TaxonomyTermID" = "TaxonomyTerm"."ID" AND "TaxonomyTerm"."ID" = \'%d\'', $tagID)
);
}
// Filter by date
if (isset($dateFrom)) {
if (!isset($dateTo)) {
$dateTo = $dateFrom;
}
$items = $items->where(array(
sprintf('"%s"."Date" >= \'%s\'', $dbTableName, Convert::raw2sql("$dateFrom 00:00:00")),
sprintf('"%s"."Date" <= \'%s\'', $dbTableName, Convert::raw2sql("$dateTo 23:59:59"))
));
}
// Filter down to single month.
if (isset($year) && isset($monthNumber)) {
$year = (int)$year;
$monthNumber = (int)$monthNumber;
$beginDate = sprintf("%04d-%02d-01 00:00:00", $year, $monthNumber);
$endDate = date('Y-m-d H:i:s', strtotime("{$beginDate} +1 month"));
$items = $items->where(array(
sprintf('"%s"."Date" >= \'%s\'', $dbTableName, Convert::raw2sql($beginDate)),
sprintf('"%s"."Date" < \'%s\'', $dbTableName, Convert::raw2sql($endDate))
));
}
// Unpaginated DataList.
return $items;
}
/**
* Produce an ArrayList of available months out of the updates contained in the DataList.
*
* Here is an example of the returned structure:
* ArrayList:
* ArrayData:
* YearName => 2013
* Months => ArrayList:
* MonthName => Jan
* MonthNumber => 1
* MonthLink => (page URL)year=2012&month=1
* Active => true
* ArrayData:
* YearName => 2012
* Months => ArrayList:
* ...
*
* @param $updates DataList DataList to extract months from.
* @param $link Link used as abase to construct the MonthLink.
* @param $currentYear Currently selected year, for computing the link active state.
* @param $currentMonthNumber Currently selected month, for computing the link active state.
*
* @returns ArrayList
*/
public static function ExtractMonths(DataList $updates, $link = null, $currentYear = null, $currentMonthNumber = null) {
// Set the link to current URL in the same way the HTTP::setGetVar does it.
if (!isset($link)) {
$link = Director::makeRelative($_SERVER['REQUEST_URI']);
}
$dates = $updates->dataQuery()
->groupby('YEAR("Date")')
->groupby('MONTH("Date")')
->sort('Date', 'DESC')
->query()
->setSelect(array(
'Year' => 'YEAR("Date")',
'Month' => 'MONTH("Date")',
))
->addWhere('"Date" IS NOT NULL')
->execute();
$years = array();
foreach ($dates as $date) {
$monthNumber = $date['Month'];
$year = $date['Year'];
$dateObj = new Datetime(implode('-', array($year, $monthNumber, 1)));
$monthName = $dateObj->Format('M');
// Set up the relevant year array, if not yet available.
if (!isset($years[$year])) {
$years[$year] = array('YearName'=>$year, 'Months'=>array());
}
// Check if the currently processed month is the one that is selected via GET params.
$active = false;
if (isset($year) && isset($monthNumber)) {
$active = (((int)$currentYear)==$year && ((int)$currentMonthNumber)==$monthNumber);
}
// Build the link - keep the tag and date filter, but reset the pagination.
if ($active) {
// Allow clicking to deselect the month.
$link = HTTP::setGetVar('month', null, $link, '&');
$link = HTTP::setGetVar('year', null, $link, '&');
} else {
$link = HTTP::setGetVar('month', $monthNumber, $link, '&');
$link = HTTP::setGetVar('year', $year, $link, '&');
}
$link = HTTP::setGetVar('start', null, $link, '&');
$years[$year]['Months'][$monthNumber] = array(
'MonthName'=>$monthName,
'MonthNumber'=>$monthNumber,
'MonthLink'=>$link,
'Active'=>$active
);
}
// ArrayList will not recursively walk through the supplied array, so manually build nested ArrayLists.
foreach ($years as &$year) {
$year['Months'] = new ArrayList($year['Months']);
}
// Reverse the list so the most recent years appear first.
return new ArrayList($years);
}
public function getDefaultRSSLink() {
return $this->Link('rss');
}
public function getDefaultAtomLink() {
return $this->Link('atom');
}
public function getSubscriptionTitle() {
return $this->Title;
}
}
/**
* The parameters apply in the following preference order:
* - Highest priority: Tag & date (or date range)
* - Month (and Year)
* - Pagination
*
* So, when the user click on a tag link, the pagination, and month will be reset, but not the date filter. Also,
* changing the date will not affect the tag, but will reset the month and pagination.
*
* When the user clicks on a month, pagination will be reset, but tags retained. Pagination retains all other
* parameters.
*/
class DatedUpdateHolder_Controller extends Page_Controller {
private static $allowed_actions = array(
'rss',
'atom',
'DateRangeForm'
);
private static $casting = array(
'MetaTitle' => 'Text',
'FilterDescription' => 'Text'
);
/**
* Get the meta title for the current action
*
* @return string
*/
public function getMetaTitle() {
$title = $this->data()->getTitle();
$filter = $this->FilterDescription();
if($filter) {
$title = "{$title} - {$filter}";
}
$this->extend('updateMetaTitle', $title);
return $title;
}
/**
* Returns a description of the current filter
*
* @return string
*/
public function FilterDescription() {
$params = $this->parseParams();
$filters = array();
if ($params['tag']) {
$term = TaxonomyTerm::get_by_id('TaxonomyTerm', $params['tag']);
if ($term) {
$filters[] = _t('DatedUpdateHolder.FILTER_WITHIN', 'within') . ' "' . $term->Name . '"';
}
}
if ($params['from'] || $params['to']) {
if ($params['from']) {
$from = strtotime($params['from']);
if ($params['to']) {
$to = strtotime($params['to']);
$filters[] = _t('DatedUpdateHolder.FILTER_BETWEEN', 'between') . ' '
. date('j/m/Y', $from) . ' and ' . date('j/m/Y', $to);
} else {
$filters[] = _t('DatedUpdateHolder.FILTER_ON', 'on') . ' ' . date('j/m/Y', $from);
}
} else {
$to = strtotime($params['to']);
$filters[] = _t('DatedUpdateHolder.FILTER_ON', 'on') . ' ' . date('j/m/Y', $to);
}
}
if ($params['year'] && $params['month']) {
$timestamp = mktime(1, 1, 1, $params['month'], 1, $params['year']);
$filters[] = _t('DatedUpdateHolder.FILTER_IN', 'in') . ' ' . date('F', $timestamp) . ' ' . $params['year'];
}
if ($filters) {
return $this->getUpdateName() . ' ' . implode(' ', $filters);
}
}
public function getUpdateName() {
return Config::inst()->get($this->data()->ClassName, 'update_name');
}
public function init() {
parent::init();
RSSFeed::linkToFeed($this->Link() . 'rss', $this->getSubscriptionTitle());
}
/**
* Parse URL parameters.
*
* @param $produceErrorMessages Set to false to omit session messages.
*/
public function parseParams($produceErrorMessages = true) {
$tag = $this->request->getVar('tag');
$from = $this->request->getVar('from');
$to = $this->request->getVar('to');
$year = $this->request->getVar('year');
$month = $this->request->getVar('month');
if ($tag=='') $tag = null;
if ($from=='') $from = null;
if ($to=='') $to = null;
if ($year=='') $year = null;
if ($month=='') $month = null;
if (isset($tag)) $tag = (int)$tag;
if (isset($from)) {
$from = urldecode($from);
$parser = new SS_Datetime;
$parser->setValue($from);
$from = $parser->Format('Y-m-d');
}
if (isset($to)) {
$to = urldecode($to);
$parser = new SS_Datetime;
$parser->setValue($to);
$to = $parser->Format('Y-m-d');
}
if (isset($year)) $year = (int)$year;
if (isset($month)) $month = (int)$month;
// If only "To" has been provided filter by single date. Normalise by swapping with "From".
if (isset($to) && !isset($from)) {
list($to, $from) = array($from, $to);
}
// Flip the dates if the order is wrong.
if (isset($to) && isset($from) && strtotime($from)>strtotime($to)) {
list($to, $from) = array($from, $to);
if ($produceErrorMessages) {
Session::setFormMessage(
'Form_DateRangeForm',
_t('DateUpdateHolder.FilterAppliedMessage','Filter has been applied with the dates reversed.'),
'warning'
);
}
}
// Notify the user that filtering by single date is taking place.
if (isset($from) && !isset($to)) {
if ($produceErrorMessages) {
Session::setFormMessage(
'Form_DateRangeForm',
_t('DateUpdateHolder.DateRangeFilterMessage','Filtered by a single date.'),
'warning'
);
}
}
return array(
'tag' => $tag,
'from' => $from,
'to' => $to,
'year' => $year,
'month' => $month
);
}
/**
* Build the link - keep the date range, reset the rest.
*/
public function AllTagsLink() {
$link = HTTP::setGetVar('tag', null, null, '&');
$link = HTTP::setGetVar('month', null, $link, '&');
$link = HTTP::setGetVar('year', null, $link, '&');
$link = HTTP::setGetVar('start', null, $link, '&');
return $link;
}
/**
* List tags and attach links.
*/
public function UpdateTagsWithLinks() {
$tags = $this->UpdateTags();
$processed = new ArrayList();
foreach ($tags as $tag) {
// Build the link - keep the tag, and date range, but reset month, year and pagination.
$link = HTTP::setGetVar('tag', $tag->ID, null, '&');
$link = HTTP::setGetVar('month', null, $link, '&');
$link = HTTP::setGetVar('year', null, $link, '&');
$link = HTTP::setGetVar('start', null, $link, '&');
$tag->Link = $link;
$processed->push($tag);
}
return $processed;
}
/**
* Get the TaxonomyTerm related to the current tag GET parameter.
*/
public function CurrentTag() {
$tagID = $this->request->getVar('tag');
if (isset($tagID)) {
return TaxonomyTerm::get_by_id('TaxonomyTerm', (int)$tagID);
}
}
/**
* Extract the available months based on the current query.
* Only tag is respected. Pagination and months are ignored.
*/
public function AvailableMonths() {
$params = $this->parseParams();
return DatedUpdateHolder::ExtractMonths(
$this->Updates($params['tag'], $params['from'], $params['to']),
Director::makeRelative($_SERVER['REQUEST_URI']),
$params['year'],
$params['month']
);
}
/**
* Get the updates based on the current query.
*/
public function FilteredUpdates($pageSize = 20) {
$params = $this->parseParams();
$items = $this->Updates(
$params['tag'],
$params['from'],
$params['to'],
$params['year'],
$params['month']
);
// Apply pagination
$list = new PaginatedList($items, $this->request);
$list->setPageLength($pageSize);
return $list;
}
/**
* @return Form
*/
public function DateRangeForm() {
$dateFromTitle = DBField::create_field('HTMLText', sprintf(
'%s <span class="field-note">%s</span>',
_t('DatedUpdateHolder.FROM_DATE', 'From date'),
_t('DatedUpdateHolder.DATE_EXAMPLE', '(example: 2017/12/30)')
));
$dateToTitle = DBField::create_field('HTMLText', sprintf(
'%s <span class="field-note">%s</span>',
_t('DatedUpdateHolder.TO_DATE', 'To date'),
_t('DatedUpdateHolder.DATE_EXAMPLE', '(example: 2017/12/30)')
));
$fields = new FieldList(
DateField::create('from', $dateFromTitle)
->setConfig('showcalendar', true),
DateField::create('to', $dateToTitle)
->setConfig('showcalendar', true),
HiddenField::create('tag')
);
$actions = new FieldList(
FormAction::create("doDateFilter")->setTitle("Filter")->addExtraClass('btn btn-primary primary'),
FormAction::create("doDateReset")->setTitle("Clear")->addExtraClass('btn')
);
$form = new Form($this, 'DateRangeForm', $fields, $actions);
$form->loadDataFrom($this->request->getVars());
$form->setFormMethod('get');
// Manually extract the message so we can clear it.
$form->ErrorMessage = $form->Message();
$form->ErrorMessageType = $form->MessageType();
$form->clearMessage();
return $form;
}
public function doDateFilter() {
$params = $this->parseParams();
// Build the link - keep the tag, but reset month, year and pagination.
$link = HTTP::setGetVar('from', $params['from'], $this->AbsoluteLink(), '&');
$link = HTTP::setGetVar('to', $params['to'], $link, '&');
if (isset($params['tag'])) $link = HTTP::setGetVar('tag', $params['tag'], $link, '&');
$this->redirect($link);
}
public function doDateReset() {
$params = $this->parseParams(false);
// Reset the link - only include the tag.
$link = $this->AbsoluteLink();
if (isset($params['tag'])) $link = HTTP::setGetVar('tag', $params['tag'], $link, '&');
$this->redirect($link);
}
public function rss() {
$rss = new RSSFeed(
$this->Updates()->sort('Created DESC')->limit(20),
$this->Link('rss'),
$this->getSubscriptionTitle()
);
return $rss->outputToBrowser();
}
public function atom() {
$atom = new CwpAtomFeed(
$this->Updates()->sort('Created DESC')->limit(20),
$this->Link('atom'),
$this->getSubscriptionTitle()
);
return $atom->outputToBrowser();
}
}
| true |
c4eb5a80fd913ab69ea9f5aa67dbc550be5c2bcd | PHP | andzub/vavto | /backend/api/article/get/article_get.php | UTF-8 | 1,527 | 2.578125 | 3 | [] | no_license | <?php
$article_get = article_get::getInstance();
class article_get {
protected static $_instance;
private function __clone() {}
private function __wakeup() {}
private function __construct() {}
public static function getInstance() {
if (self::$_instance === null) { self::$_instance = new self; }
return self::$_instance;
}
public function usual($data)
{
$data['lang']=isset($data['lang']) ? $data['lang'] : 'ru';
$db = db::getInstance();
return $db->getRow('SELECT a.id,a.address,al.title,al.text,al.short_desc,al.lang,a.img,a.img_min,a.type FROM `articles` a LEFT JOIN articles_lang al ON (a.id=al.article_id AND al.lang="'.$data['lang'].'") WHERE a.`id`=?i', (int)$data['id']);
}
public function all($data)
{
$db = db::getInstance();
return $db->getAll('SELECT a.*,al.title,al.short_desc,al.lang FROM `articles` a LEFT JOIN articles_lang al ON (a.id=al.article_id AND al.lang="ru") WHERE a.`type`=1');
}
public function franch($data)
{
$db = db::getInstance();
$lang=(isset($data['lang'])) ? $data['lang'] : 'ru';
return $db->getAll('SELECT a.*,al.title,al.short_desc,al.lang FROM `articles` a INNER JOIN articles_lang al ON (a.id=al.article_id AND al.lang=?s) WHERE a.`is_franch`=1 AND a.type=1 ORDER BY a.`id` DESC',$lang);
}
}
?> | true |
d7a5c0ff32763ae945bbe54bba266550de1f8c4f | PHP | Night75/webmixin-2014 | /src/Night/DisplayBundle/Model/Model/Image.php | UTF-8 | 1,610 | 2.609375 | 3 | [
"MIT",
"BSD-3-Clause"
] | permissive | <?php
namespace Night\DisplayBundle\Model\Model;
use Doctrine\ORM\Mapping as ORM;
/**
* Image
*/
class Image
{
const DATA_TYPE_SVG = 'svg';
/**
* @var integer
*/
protected $id;
/**
* @var string
*/
protected $title;
/**
* @var string
*/
protected $path;
/**
* @var string
*/
protected $dataType;
/**
* @var string
*/
protected $data;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
* @param string $title
*/
public function setTitle($title)
{
$this->title = $title;
}
/**
* Set path
*
* @param string $path
* @return Image
*/
public function setPath($path)
{
$this->path = $path;
return $this;
}
/**
* Get path
*
* @return string
*/
public function getPath()
{
return $this->path;
}
/**
* @return string
*/
public function getDataType()
{
return $this->dataType;
}
/**
* @param string $dataType
*/
public function setDataType($dataType)
{
$this->dataType = $dataType;
}
/**
* @return string
*/
public function getData()
{
return $this->data;
}
/**
* @param string $data
*/
public function setData($data)
{
$this->data = $data;
}
}
| true |
9a72acc2340fe5cf6f5db3478a2451229686dd8f | PHP | rads-io/php7-mapnik | /docs/prototypes/Mapnik/AggRenderer.php | UTF-8 | 563 | 2.546875 | 3 | [
"MIT"
] | permissive | <?php
namespace Mapnik;
/**
* @package Mapnik
* @see https://github.com/mapnik/mapnik/blob/master/include/mapnik/agg_renderer.hpp C++ agg_renderer include
* @see https://github.com/mapnik/mapnik/wiki/MapnikRenderers Mapnik renderers documentation
*/
class AggRenderer
{
/**
* AggRenderer constructor.
*
* @param Map $map Map object
* @param Image $image Image object
*/
public function __construct(Map $map, Image $image) {}
/**
* Render/paint image from Map configuration.
*/
public function apply() {}
} | true |
75f1b23d4b939dd1b15822c1c93ea873ae9287e0 | PHP | chuchujie/sockets | /src/Core/Routing/SocketRoute.php | UTF-8 | 6,903 | 2.6875 | 3 | [] | no_license | <?php
// Created by dealloc. All rights reserved.
namespace Experus\Sockets\Core\Routing;
use Experus\Sockets\Core\Middlewares\MiddlewareDispatcher;
use Experus\Sockets\Core\Middlewares\Pipeline;
use Experus\Sockets\Core\Server\SocketRequest;
use Experus\Sockets\Exceptions\InvalidActionException;
use Illuminate\Contracts\Foundation\Application;
use ReflectionFunction;
use ReflectionFunctionAbstract;
use ReflectionMethod;
use RuntimeException;
/**
* Class SocketRoute represents a route in the sockets routing system, holding information about it's path, action etc.
* @package Experus\Sockets\Core\Routing
*/
class SocketRoute
{
/**
* The key the route will use to search for the name property.
*
* @var string
*/
const NAME = 'name';
/**
* The key the route will use to search for the middlewares property.
*
* @var string
*/
const MIDDLEWARE = 'middlewares';
/**
* The key the route will use to search for the action property.
*
* @var string
*/
const ACTION = 'uses';
/**
* The key the route will use to search for the namespace property.
*
* @var string
*/
const DOMAIN = 'namespace';
/**
* The key the route will use to search for the prefix property.
*
* @var string
*/
const PREFIX = 'prefix';
/**
* All the attributes of this route.
*
* @var array
*/
private $attributes;
/**
* The URI for which the route is responsible.
*
* @var string
*/
private $path;
/**
* The laravel application
*
* @var Application
*/
private $app;
/**
* The middleware pipeline.
*
* @var Pipeline
*/
private $pipeline;
/**
* SocketRoute constructor.
* @param string $path
* @param array $action
* @param array $attributes
* @param Application $app
*/
public function __construct($path, array $action, $attributes = [], Application $app)
{
$this->app = $app;
$this->path = $path;
$this->pipeline = new Pipeline();
$this->attributes = array_merge($attributes, $action, compact('channel'));
}
/**
* Check if the request should be dispatched to this route.
*
* @param SocketRequest $request
* @return bool
*/
public function match(SocketRequest $request)
{
return ($this->path() == $request->path());
}
/**
* Run the request through the handler and middlewares of this route.
*
* @param SocketRequest $request
* @return array|null|object
*/
public function run(SocketRequest $request)
{
if (!empty($this->middlewares())) {
$response = $this->pipeline->through($this->middlewares())->run($request);
if (!is_null($response)) {
return $response;
}
}
if ($this->isControllerAction()) {
return $this->dispatchController($request);
}
return $this->dispatchCallable($request);
}
/**
* Get the name of the route if an alias is set, otherwise this function returns the route's path.
*
* @return string
*/
public function name()
{
if (isset($this->attributes[self::NAME])) {
return $this->attributes[self::NAME];
}
return $this->path();
}
/**
* Check if this route is a controller action.
*
* @return bool
*/
private function isControllerAction()
{
return is_string($this->attributes[self::ACTION]);
}
/**
* Get the middlewares that should be applied to this route.
*
* @return array
*/
private function middlewares()
{
if (isset($this->attributes[self::MIDDLEWARE])) {
if (is_string($this->attributes[self::MIDDLEWARE])) {
return [$this->attributes[self::MIDDLEWARE]];
}
return $this->attributes[self::MIDDLEWARE];
}
return [];
}
/**
* Dispatch the route to a controller method passed to this route.
*
* @param SocketRequest $request
* @return array|null|object
*/
private function dispatchController(SocketRequest $request)
{
if (!str_contains($this->attributes[self::ACTION], '@')) {
throw new InvalidActionException($this->name());
}
list($controller, $action) = explode('@', $this->attributes[self::ACTION]);
$namespace = (isset($this->attributes[self::DOMAIN]) ? $this->attributes[self::DOMAIN] : '');
$controller = $this->app->make($namespace . '\\' . $controller);
$method = new ReflectionMethod($controller, $action);
$parameters = $this->buildParameters($method, $request);
return call_user_func_array([$controller, $action], $parameters);
}
/**
* Dispatch the route to the callable passed to this route.
*
* @param SocketRequest $request
* @return array|null|object
* @throws RuntimeException when a non-callable is passed as an action.
*/
private function dispatchCallable(SocketRequest $request)
{
if (!is_callable($this->attributes[self::ACTION])) {
throw new InvalidActionException($this->name());
}
$method = new ReflectionFunction($this->attributes[self::ACTION]);
$parameters = $this->buildParameters($method, $request);
return $method->invokeArgs($parameters);
}
/**
* Build an array of resolved parameters to call the method with.
*
* @param ReflectionFunctionAbstract $method
* @param SocketRequest $request
* @return array
* @throws \ReflectionException
*/
private function buildParameters(ReflectionFunctionAbstract $method, SocketRequest $request)
{
$parameters = [];
foreach ($method->getParameters() as $parameter) {
if ($parameter->hasType()) {
if ($parameter->getType() == SocketRequest::class) {
$parameters[] = $request;
} else {
$parameters[] = $this->app->make((string)$parameter->getType());
}
} else {
if ($parameter->isDefaultValueAvailable()) {
$parameters[] = $parameter->getDefaultValue();
} else {
throw new \ReflectionException('Cannot resolve ' . $parameter->getName() . ' for ' . $method->getName());
}
}
}
return $parameters;
}
/**
* Get the path of this route.
*
* @return string
*/
public function path()
{
$prefix = (isset($this->attributes[self::PREFIX]) ? $this->attributes[self::PREFIX] : '');
return $prefix . $this->path;
}
} | true |
95a95933d69faad655f0f9793a606bd4a4ebc99d | PHP | some-random-username/student-list | /src/classes/Template.php | UTF-8 | 393 | 2.796875 | 3 | [] | no_license | <?php
namespace src\classes;
class Template
{
public function __construct() {
}
public function render($file, $params = []) {
$path = '../src/views/';
$file = $path . $file . '.php';
if(file_exists($file)) {
include('../src/views/header.php');
include($file);
include('../src/views/footer.php');
}
}
}
| true |
7f812588c9db9ec7d353b2e18a2274a3b6d1a458 | PHP | ifrolikov/tsn | /components/managers/PasswordManager.php | UTF-8 | 656 | 3.15625 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
namespace app\components\managers;
/**
* Class PasswordManager
* @package app\components\managers
*/
class PasswordManager
{
/** @var string */
private $password;
/**
* @return string
*/
public function encrypt(): string
{
return md5(md5($this->password));
}
/**
* @param string $password
* @return PasswordManager
*/
public function setPassword(string $password): PasswordManager
{
$this->password = $password;
return $this;
}
/**
* @return string
*/
public function getPassword(): string
{
return $this->password;
}
} | true |
9a49f9edee8d02269fde24961289aeb4eea65fdc | PHP | foresitegroup/Belardi | /admin/schedule.php | UTF-8 | 2,286 | 2.5625 | 3 | [] | no_license | <?php
include "login.php";
$PageTitle = "Schedule";
include "header.php";
?>
<div class="content-width schedule">
<div class="one-half">
<h3>Add Event</h3><br>
<form action="schedule-db.php?a=add" method="POST">
<div>
<input type="text" name="round" placeholder="Round"><br>
<br>
<input type="text" name="startdate" class="startdate" placeholder="Start Date">
<input type="text" name="enddate" class="enddate" placeholder="End Date (optional)">
<div style="clear: both;"></div><br>
<input type="text" name="location" placeholder="Location"><br>
<br>
<input type="text" name="track" placeholder="Track"><br>
<br>
<input type="text" name="tracktype" placeholder="Track Type"><br>
<br>
<input type="text" name="trackimg" placeholder="Track Image"><br>
<br>
<input type="text" name="details" placeholder="Details"><br>
<br>
<input type="submit" name="submit" value="SUBMIT" id="submit">
<div style="clear: both;"></div>
</div>
</form>
</div>
<div class="one-half last">
<h3>Events</h3><br>
<?php
$result = $mysqli->query("SELECT * FROM schedule ORDER BY startdate ASC");
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
echo "<div class=\"controls\">";
echo "<a href=\"schedule-edit.php?id=" . $row['id'] . "\" title=\"Edit\" class=\"c-edit\"><i class=\"fa fa-pencil\"></i></a><br>";
echo "<a href=\"schedule-db.php?a=delete&id=" . $row['id'] . "\" onClick=\"return(confirm('Are you sure you want to delete this record?'));\" title=\"Delete\" class=\"c-delete\"><i class=\"fa fa-trash\"></i></a>";
echo "</div>";
echo "<strong>" . date("n/j/y", $row['startdate']);
if ($row['startdate'] != $row['enddate']) {
echo ($row['enddate'] - $row['startdate'] == 86400) ? " & " : "-";
echo date("n/j/y", $row['enddate']);
}
echo "</strong><br>";
echo $row['round'] . "<br>";
echo $row['location'] . "/" . $row['track'] . "<br>";
echo "<div style=\"clear: both; height: 0.7em\"></div><br>";
}
$result->close();
?>
</div>
<div style="clear: both;"></div>
</div>
<?php include "footer.php"; ?> | true |
7f7db570e38b3e7ce8cbbe1888fc87cdb1fc62a8 | PHP | MrHanFeng/code | /Post_邮政订阅系统/book/Model/AuthModel.class.php | UTF-8 | 1,226 | 2.796875 | 3 | [] | no_license | <?php
namespace Model;
use Think\Model;
//权限模型
class AuthModel extends Model{
// 添加权限方法
function addAuth($auth){
// $auth里面存在四个信息还缺少两个关键信息:auth_path 和 auth_level;
// ① insert 生成一个新纪录
// ② update把auth_path 和 auth_level更新进去;
$new_id = $this ->add($auth);//返回新纪录和主键id值
// path的值分为两种情况
// 全路径:父级全路径与本身id的连接信息
// ①当前权限是顶级权限,path=$new_id;
// ②当前权限是非顶级权限,path=父级全路径+$new_id;
if($auth['auth_pid']==0){
$auth_path = $new_id;
}else{
// 查询指定父级全路径,条件:$auth['auth_pid']
$pinfo = $this -> find($auth['auth_pid']);
$p_path = $pinfo['auth_path']; //父级全路径
$auth_path = $p_path."-".$new_id;
}
// auth_level数目:全路径里面中恒线的个数
// 把全路径变为数组,计算数组的个数和-1,就是level的信息
$auth_level = count(explode('-',$auth_path))-1;
$dt = array(
'auth_id' => $new_id,
'auth_path' => $auth_path,
'auth_level' => $auth_level,
);
// show_bug($dt);
return $this->save($dt);
}
} | true |
2132842f96bba80ceb19af9c4526d73d6e2567a8 | PHP | maxlutzfl/LayoutsComponentsGuide | /config/document-functions.php | UTF-8 | 2,047 | 2.84375 | 3 | [] | no_license | <?php
/**
*
*/
DEFINE('APP_DIRECTORY', dirname(__DIR__) . '/');
DEFINE('DEBUG', true);
/**
* Debug mode
*/
if ( DEBUG === true ) {
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
}
/**
* Functions
*/
function get_components_navigation_items() {
// Loop through the directory and return the file
// @todo - add argument for 'type', so this function works for both components & layouts
$files = glob('guides/*.php');
$menu_items = array();
foreach ( $files as $file ) {
$menu_items[] = array(
'location' => $file
);
}
return $menu_items;
}
function get_file_comments_for_data($file) {
// Get comments from file
$comments = array_filter(
token_get_all(file_get_contents($file)), function($entry) {
return $entry[0] == T_DOC_COMMENT;
}
);
// Return the comments in a string
$comments_string = array_shift($comments);
return $comments_string;
}
function get_file_data($file) {
// Run the function to grab comments from file
$file = APP_DIRECTORY . $file;
$file_comments = get_file_comments_for_data($file);
// Split the comments string by line
$file_comments_array = preg_split('/\R/', $file_comments[1]);
// Loop through each line and search for data
// @todo - add argument to search for title or slug, etc
// @todo - add comment data for type - so layouts/components can live in 1 directory
$file_data = array();
foreach ( $file_comments_array as $comment_line ) {
if (strpos($comment_line, '@title') !== false) {
$file_data['title'] = str_replace(' * @title ', '', $comment_line);
}
if (strpos($comment_line, '@slug') !== false) {
$file_data['slug'] = str_replace(' * @slug ', '', $comment_line);
}
if (strpos($comment_line, '@type') !== false) {
$file_data['type'] = str_replace(' * @type ', '', $comment_line);
}
}
// Return data
return $file_data;
}
function display_file_contents_by_query_string() {
if ( !isset($_GET['guide']) ) {
return;
}
$guide_to_show = $_GET['guide'];
include $guide_to_show;
}
| true |
5905e6df6fd4c381494d73a59559dac9a62e4db1 | PHP | FrankM1/layerwp-plugin | /core/widgets/modules/base.php | UTF-8 | 8,635 | 3.078125 | 3 | [] | no_license | <?php /**
* Layers Widget Class
*
* This file is used to register the base layers widget Class
*
* @package Layers
* @since Layers 1.0.0
*/
if( !class_exists( 'Layers_Widget' ) ) {
class Layers_Widget extends WP_Widget {
/**
* Check option with isset() and echo it out if it exists, if it does not exist, return false
*
* @param array $widget Widget Object
* @param varchar $option Widget option to check on
* @param varchar $array_level_1 Array level one to check for (optional)
* @param varchar $array_level_2 Array level two to check for (optional)
* @return varchar false if not set, otherwise returns value
*/
function check_and_return( $widget = NULL , $option = NULL, $array_level_1 = NULL, $array_level_2 = NULL ){
// If there is no widget object
if( $widget == NULL ) return false;
if( !isset( $widget[$option] ) ){
return false;
} else {
$widget_option = $widget[$option];
}
if( NULL != $array_level_1 ){
if( !isset( $widget_option[ $array_level_1 ] ) ){
return false;
} elseif( '' != $widget_option[ $array_level_1 ] ){
if( NULL != $array_level_2 ){
if( !isset( $widget_option[ $array_level_1 ][ $array_level_2 ] ) ){
return false;
} elseif( '' != $widget_option[ $array_level_1 ][ $array_level_2 ] ) {
return $widget_option[ $array_level_1 ][ $array_level_2 ];
}
} elseif( '' != $widget_option[ $array_level_1 ] ) {
return $widget_option[ $array_level_1 ];
}
}
} elseif( '' != $widget_option ){
return $widget_option;
}
}
/**
* This function determines whether or not a widget is boxed or full width
*
* @return varchar widget layout class
*/
function get_widget_layout_class( $widget = NULL ){
if( NULL == $widget ) return;
// Setup the layout class for boxed/full width/full screen
if( 'layout-boxed' == $this->check_and_return( $widget , 'design' , 'layout' ) ) {
$layout_class = 'container';
} elseif('layout-full-screen' == $this->check_and_return( $widget , 'design' , 'layout' ) ) {
$layout_class = 'full-screen';
} elseif( 'layout-full-width' == $this->check_and_return( $widget , 'design' , 'layout' ) ) {
$layout_class = 'full-width';
} else {
$layout_class = '';
}
return $layout_class;
}
/**
* Get widget spacing as class names
*
* @return string Class names
*/
function get_widget_spacing_class( $widget = NULL ){
if( NULL == $widget ) return;
// Setup the class for all the kinds of margin and padding
$classes = array();
if( $this->check_and_return( $widget , 'design' , 'advanced', 'margin-top' ) ) $classes[] = 'margin-top-' . $this->check_and_return( $widget , 'design' , 'advanced', 'margin-top' );
if( $this->check_and_return( $widget , 'design' , 'advanced', 'margin-right' ) ) $classes[] = 'margin-right-' . $this->check_and_return( $widget , 'design' , 'advanced', 'margin-right' );
if( $this->check_and_return( $widget , 'design' , 'advanced', 'margin-bottom' ) ) $classes[] = 'margin-bottom-' . $this->check_and_return( $widget , 'design' , 'advanced', 'margin-bottom' );
if( $this->check_and_return( $widget , 'design' , 'advanced', 'margin-left' ) ) $classes[] = 'margin-left-' . $this->check_and_return( $widget , 'design' , 'advanced', 'margin-left' );
if( $this->check_and_return( $widget , 'design' , 'advanced', 'padding-top' ) ) $classes[] = 'padding-top-' . $this->check_and_return( $widget , 'design' , 'advanced', 'padding-top' );
if( $this->check_and_return( $widget , 'design' , 'advanced', 'padding-right' ) ) $classes[] = 'padding-right-' . $this->check_and_return( $widget , 'design' , 'advanced', 'padding-right' );
if( $this->check_and_return( $widget , 'design' , 'advanced', 'padding-bottom' ) ) $classes[] = 'padding-bottom-' . $this->check_and_return( $widget , 'design' , 'advanced', 'padding-bottom' );
if( $this->check_and_return( $widget , 'design' , 'advanced', 'padding-left' ) ) $classes[] = 'padding-left-' . $this->check_and_return( $widget , 'design' , 'advanced', 'padding-left' );
$classes = implode( ' ', $classes );
return $classes;
}
/**
* Apply advanced styles to widget instance
*
* @param string $widget_id id css selector of widget
* @param object $widget Widget object to use
*/
function apply_widget_advanced_styling( $widget_id, $widget = NULL ){
// We need a widget to get the settings from
if( NULL == $widget ) return;
// Apply Margin & Padding
$types = array( 'margin', 'padding', );
$fields = array( 'top', 'right', 'bottom', 'left', );
// Loop the Margin & Padding
foreach ( $types as $type ) {
// Get the TopRightBottomLeft TRBL array of values
$values = $this->check_and_return( $widget , 'design' , 'advanced', $type );
if( NULL != $values && is_array( $values ) ) {
foreach ( $fields as $field ) {
if( isset( $values[ $field ] ) && '' != $values[ $field ] && is_numeric( $values[ $field ] ) ) {
// If value is set, and is number, then add 'px' to it
$values[ $field ] .= 'px';
}
}
// Apply the TRBL styles
layers_inline_styles( '#' . $widget_id, $type, array( $type => $values ) );
}
}
// Custom CSS
if( $this->check_and_return( $widget, 'design', 'advanced', 'customcss' ) ) layers_inline_styles( NULL, 'css', array( 'css' => $this->check_and_return( $widget, 'design', 'advanced', 'customcss' ) ) );
}
/**
* Design Bar Class Instantiation, we'd rather have it done here than in each widget
*
* @return html Design bar HTML
*/
public function design_bar( $type = 'side' , $widget = NULL, $instance = array(), $components = array( 'columns' , 'background' , 'imagealign' ) , $custom_components = array() ) {
// Instantiate design bar
$design_bar = new Layers_Design_Controller( $type, $widget, $instance, $components, $custom_components );
// Return design bar
return $design_bar;
}
/**
* Form Elements Class Instantiation, we'd rather have it done here than in each widget
*
* @return html Design bar HTML
*/
public function form_elements() {
// Instantiate Widget Inputs
$form_elements = new Layers_Form_Elements();
// Return design bar
return $form_elements;
}
/**
* Widget sub-module input name generation, for example see Slider and Content Widgets
*
* @param object $widget_details Widget object to use
* @param varchar $level1 Level 1 name
* @param varchar $level2 Level 2 name
* @param string $field_name Field name
* @return string Name attribute for $field_name
*/
function get_custom_field_name( $widget_details = NULL, $level1 = '' , $level2 = '', $field_name = '' ) {
// If there is no widget object then ignore
if( NULL == $widget_details ) return;
$final_field_name = 'widget-' . $widget_details->id_base . '[' . $widget_details->number . ']';
// Add first level of input string
if( '' != $level1 ) $final_field_name .= '[' . $level1 . ']';
// Add second level of input string
if( '' != $level2 ) $final_field_name .= '[' . $level2 . ']';
// Add field name
if( '' != $field_name ) $final_field_name .= '[' . $field_name . ']';
return $final_field_name;
}
/**
* Widget sub-module input id generation, for example see Slider and Content Widgets
*
* @param object $widget_details Widget object to use
* @param varchar $level1 Level 1 name
* @param varchar $level2 Level 2 name
* @param string $field_name Field name
* @return string Name attribute for $field_name
*/
function get_custom_field_id( $widget_details = NULL, $level1 = '' , $level2 = '', $field_id = '' ) {
// If there is no widget object then ignore
if( NULL == $widget_details ) return;
$final_field_id = 'widget-' . $widget_details->id_base . '-' . $widget_details->number;
// Add first level of input string
if( '' != $level1 ) $final_field_id .= '-' . $level1;
// Add second level of input string
if( '' != $level2 ) $final_field_id .= '-' . $level2;
// Add field name
if( '' != $field_id ) $final_field_id .= '-' . $field_id;
return $final_field_id;
}
/**
* Enqueue Masonry When Need Be
*/
function enqueue_masonry(){
wp_enqueue_script( 'masonry' ); // Wordpress Masonry
wp_enqueue_script(
LAYERS_THEME_SLUG . '-layers-masonry-js' ,
LAYERS_TEMPLATE_URI . 'assets/admin/js/layers.masonry.js',
array(
'jquery'
),
LAYERS_VERSION
); // Layers Masonry Function
}
}
} | true |
21ef0976d7c17faea7028591c602e22d197f05be | PHP | medic911/stage-app | /src/App.php | UTF-8 | 2,590 | 2.9375 | 3 | [] | no_license | <?php
namespace StageApp;
use StageApp\Exceptions\NotAllowedResponseException;
use StageApp\Http\Request;
use StageApp\Interfaces\ErrorHandlerInterface;
use StageApp\Traits\Singleton;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use Throwable;
class App
{
use Singleton;
/**
* @var Request
*/
protected $request;
/**
* @var Response
*/
protected $response;
/**
* @var Session
*/
protected $session;
/**
* App constructor.
*/
public function __construct()
{
$this->request = new Request;
$this->session = new Session;
$this->response = new Response;
}
/**
* @param array $stages
* @param ErrorHandlerInterface $errorHandler
*/
public function run(array $stages, ErrorHandlerInterface $errorHandler): void
{
try {
$stageLine = new StageLine;
array_walk($stages, function ($stage) use ($stageLine) {
$stageLine->stage($stage);
});
$stageLine->process($this, function ($result) {
$this->handleStage($result);
});
$this->sendResponse();
} catch (Throwable $e) {
$errorHandler->handle($e);
}
}
/**
* @throws NotAllowedResponseException
*/
protected function sendResponse(): void
{
if (!$this->response instanceof Response) {
throw new NotAllowedResponseException;
}
$this->response->send();
}
/**
* @param Response $response
* @throws NotAllowedResponseException
*/
public function terminateWith(Response $response): void
{
$this->response = $response;
$this->sendResponse();
}
/**
* @return Request
*/
public function getRequest(): Request
{
return $this->request;
}
/**
* @return Response
*/
public function getResponse(): Response
{
return $this->response;
}
/**
* @return Session
*/
public function getSession(): Session
{
return $this->session;
}
/**
* @param mixed $result
*/
protected function handleStage($result): void
{
if ($result instanceof Request) {
$this->request = $result;
}
if ($result instanceof Response) {
$this->response = $result;
}
if ($result instanceof Session) {
$this->session = $result;
}
}
} | true |
ebda0589ffa5ddba9ca647c91a18f17fa89cb0eb | PHP | vivait/TenantBundle | /src/Vivait/TenantBundle/Locator/CookieLocator.php | UTF-8 | 2,195 | 2.78125 | 3 | [
"MIT"
] | permissive | <?php
namespace Vivait\TenantBundle\Locator;
use Symfony\Component\HttpFoundation\Request;
use Vivait\TenantBundle\Registry\TenantRegistry;
class CookieLocator implements TenantLocator
{
/**
* @var Request
*/
private $request;
/**
* @var string
*/
private $cookieName;
/**
* @var TenantRegistry
*/
private $tenantRegistry;
/**
* @param Request $request
* @param $cookieName
* @param TenantRegistry $tenantRegistry
*/
public function __construct(Request $request, $cookieName, TenantRegistry $tenantRegistry)
{
$this->request = $request;
$this->cookieName = $cookieName;
$this->tenantRegistry = $tenantRegistry;
}
/**
* @return string
*/
public function getTenant()
{
$tenantName = $this->request->cookies->get($this->cookieName);
$this->checkTenantName($tenantName);
return $tenantName;
}
/**
* @param Request $request
* @param string $cookieName
* @param TenantRegistry $tenantRegistry
*
* @return string Tenant key
*/
public static function getTenantFromRequest(
Request $request,
$cookieName = 'tenant',
TenantRegistry $tenantRegistry
) {
$locator = new self($request, $cookieName, $tenantRegistry);
return $locator->getTenant();
}
/**
* @param $tenantName
*
* @return bool
*/
private function tenantNameIsValid($tenantName)
{
return $this->tenantRegistry->contains($tenantName) && $tenantName !== 'dev' && $tenantName !== 'test';
}
/**
* @throws \RuntimeException
* @throws \OutOfBoundsException
*
* @param $tenantName
*/
private function checkTenantName($tenantName)
{
// if no cookie, throw runtime so it'll continue as prod
if ($tenantName === null) {
throw new \RuntimeException;
}
// if tenant is set and doesn't exist, throw out of bounds
if ( ! $this->tenantNameIsValid($tenantName)) {
throw new \OutOfBoundsException;
}
}
}
| true |
da890807e07027ba942ee50249964d3b7e3d9d6c | PHP | Reunion90/WebPhim_CI | /application/models/Genres_model.php | UTF-8 | 803 | 2.578125 | 3 | [] | no_license | <?php
class Genres_model extends MY_Model
{
function __construct()
{
parent::__construct();
}
public function getGenres()
{
return $this->db->where("status", 1)->order_by("name")->get("genres")->result();
}
public function getGenreName($genre_id)
{
$query = $this->db->get_where('genres', "id=$genre_id");
return $query->row();
}
public function getSeriesWhereGenre($genre_id)
{
$query = $this->db->select('series.*')
->join('series', 'series_genres.series_id = series.id', 'inner')
->where("genres_id='$genre_id'")
->get('series_genres');
return $query->result();
}
}
?> | true |
212a3657a91146e4e2cae3933282bdf77055787d | PHP | bit2samal/Bit | /Core/Bootstrap.php | UTF-8 | 4,592 | 2.84375 | 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.
*/
namespace Core;
/**
* Description of Bootstrap
*
* @author anil
*/
class Bootstrap
{
private static $instance;
protected static $requestURI;
protected $controller;
protected $action;
protected $slugs;
function __construct()
{
self::$instance = &$this;
self::$requestURI = str_replace(APP_ROOT, '', str_replace('//', '/', $_SERVER['REQUEST_URI']));
}
/**
* Singleton method
* @return object
*/
static function getInstance()
{
return empty(self::$instance) ? (new Bootstrap()) : self::$instance;
}
/**
* Start session if needed
*/
function session()
{
if (!API_MODE) {
session_name('SKELETON');
session_start();
} else {
ini_set('session.use_cookies', '0');
}
}
/**
* Error reporting as per config
*/
function errorReporting()
{
if (ERROR_REPOTING) {
ini_set('display_errors', '1');
error_reporting(E_ALL);
} else {
ini_set('display_errors', '1');
}
}
/**
*
* @return string if path available
* @return boolean if path is empty
*/
function path()
{
if (!empty(self::$requestURI))
return parse_url(self::$requestURI, PHP_URL_PATH);
}
/**
*
* @return string if path available
* @return string fragment #value
*/
function fragment()
{
if (!empty(self::$requestURI))
return parse_url(self::$requestURI, PHP_URL_FRAGMENT);
}
/**
* Find in Routes
*/
function populateRoute()
{
global $routes;
$URI = explode('/', $this->path());
if (empty($URI[0]))
array_shift($URI);
if (empty($URI[0]) && !empty($route['/'])) {
$targetRoute = explode('/', $route['/']);
$this->controller = empty($targetRoute[0]) ? null : $targetRoute[0];
$this->action = empty($targetRoute[1]) ? null : $targetRoute[1];
} else if (!empty($URI) && !empty($routes)) {
foreach ($routes as $request => $route) {
$requestedRoute = explode('/', $request);
if (ucfirst($URI[0]) == $requestedRoute[0] && (empty($URI[1]) || ($URI[1] == $requestedRoute[1] || $requestedRoute[1] == "*"))) {
$targetRoute = explode('/', $route);
$this->controller = empty($targetRoute[0]) ? null : $targetRoute[0];
array_shift($URI);
$this->action = empty($targetRoute[1]) ? null : $targetRoute[1];
if (!empty($URI) && $URI[0] == $requestedRoute[0])
array_shift($URI);
}
}
}
if (!empty($this->controller) && !empty($this->action))
$this->slugs = empty($URI) ? [] : $URI;
}
function populateURI()
{
$URI = explode('/', $this->path());
if (empty($URI[0]))
array_shift($URI);
$this->controller = empty($URI) ? null : ucfirst(array_shift($URI));
$this->action = empty($URI) ? null : array_shift($URI);
$this->slugs = empty($URI) ? [] : $URI;
}
/**
*
* @global array() $route from ./config.php
* @global array() $method from ./config.php
* @return array() parameters to action
*/
function parseUrlPath()
{
$this->populateRoute();
if (empty($this->controller))
$this->populateURI();
// Try to load defaults
if (empty($this->controller))
$this->controller = DEFAULT_CONTROLLER;
if (empty($this->action)) {
global $method;
$this->action = $method[$_SERVER['REQUEST_METHOD']];
}
return empty($this->slugs) ? [] : $this->slugs;
}
/**
*
* @param array() $slugs
* @return null
*/
function app()
{
try {
$controllerName = CONTROLLER_NS . $this->controller;
call_user_func_array(array((new $controllerName()), $this->action), $this->slugs);
} catch (\Exception $e) {
header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
include_once '_pages/404.php';
print_r($e);
return;
}
}
}
| true |
e469dd7a4ac74be44d427d097b1745c52d330c93 | PHP | Kumarjio/accAdda | /login.php | UTF-8 | 1,295 | 2.515625 | 3 | [] | no_license | <?php
include_once('admin/config/config.php');
$user = trim($_POST['user']);
$pass = trim($_POST['pass']);
if(!empty($user) && !empty($pass))
{
$user = $con->real_escape_string($user);
$pass = $con->real_escape_string($pass);
$md5 = md5($pass);
$query = $con->query("select * from user_master where username = '".$user."'");
if($query)
{
$row = $query->num_rows;
if($row == 1)
{
$res = $query->fetch_object();
if($md5 === $res->user_pass)
{
$_SESSION['user'] = $res->username;
$_SESSION['name'] = $res->full_name;
$_SESSION['id'] = $res->user_master_id;
$_SESSION['pass'] = $md5;
$_SESSION['timestamp'] = time();
echo "true";
exit;
}
else
{
echo "Username And Password Not Match.";
exit;
}
}
else
{
echo "Username Not Exists... Try With Different";
exit;
}
}
else
{
echo "Somthing Went Wrong Please Try Again";
exit;
}
}
if(isset($_POST['year']) && isset($_POST['company']))
{
$_SESSION['company_id'] = $_POST['company'];
$_SESSION['year'] = $_POST['year'];
echo "ok";
exit;
}
if(isset($_POST['check']))
{
if(!empty($_SESSION['user']) || !empty($_SESSION['id']))
{
echo "s_ok";
exit;
}else{
echo "notok";
exit;
}
}
?> | true |
4fb9f8a9a43f079b06acd7f7d831b8de0adfb626 | PHP | mokamoto12/oop-practice | /tests/Domain/Model/Product/ProductTest.php | UTF-8 | 759 | 2.703125 | 3 | [] | no_license | <?php
namespace Mokamoto12\OopPractice\Domain\Model\Product;
use PHPUnit\Framework\TestCase;
/**
* Class ProductTest
* @package Mokamoto12\OopPractice\Domain\Model\Product
*/
class ProductTest extends TestCase
{
/**
* @var Product
*/
public $product;
public function setUp()
{
$this->product = new Product(new Name('ABC'), new Price(1000));
}
public function testCliFormat()
{
$this->assertEquals("ABC: 1,000\n", $this->product->cliFormat());
}
public function testSameNameAs()
{
$this->assertTrue($this->product->sameNameAs(new Name('ABC')));
}
public function testSameNameAs2()
{
$this->assertFalse($this->product->sameNameAs(new Name('XXX')));
}
}
| true |
af7a0d00822c1f0b615761298cb0c91932ed206c | PHP | asuslx/f-project | /App/Request.php | UTF-8 | 3,262 | 2.875 | 3 | [] | no_license | <?php
/**
* Author: asuslx (asuslx@gmail.com)
* Date: 4/26/12
*/
class F_App_Request {
private $_host;
private $_path;
private $_sourceData;
public function __construct() {
$this->setSource('get', $_GET);
$this->setSource('post', $_POST);
$this->setSource('request', $_REQUEST);
$this->setSource('cookie', $_COOKIE);
$this->_path = $_SERVER['REQUEST_URI'];
$len = strpos($_SERVER['REQUEST_URI'], '?');
if($len) {
$this->_path = substr(strtolower($_SERVER['REQUEST_URI']), 0, $len);
}
$this->_host = $_SERVER['HTTP_HOST'];
}
public function setSource($name, $data) {
$this->_sourceData[self::_weakName($name)] = $data;
}
public function getHost() {
return $this->_host;
}
public function getPath() {
return $this->_path;
}
public function getParam($param, $source = 'request', $default = null, $type = false, $strict = false) {
if(is_array($param)) {
$source = isset($param['source']) ? $param['source'] : $source;
$default = isset($param['default']) ? $param['default'] : $default;
$type = isset($param['type']) ? $param['type'] : $type;
$strict = isset($param['strict']) ? $param['strict'] : $strict;
if(isset($param['name'])) {
$param = $param['name'];
} else {
throw new F_App_Exception_Controller("param represented as array don't consist \"name\"");
}
}
$result = null;
if(!isset($this->_sourceData[self::_weakName($source)])) {
throw new F_App_Exception_Request("Source named \"$source\" is not set!");
}
if(isset($this->_sourceData[self::_weakName($source)][$param])) {
$result = $this->_sourceData[self::_weakName($source)][$param];
} elseif($strict) {
throw new F_App_Exception_Request("Strict param named \"$param\" is not found!");
} else {
$result = $default;
}
return self::_validate($result, $type, $strict);
}
private static function _weakName($name) {
return strtoupper(trim($name));
}
private static function _validate($value, $type, $strict) {
$result = $value;
if(!$type) return $result;
$result = self::_convert($value, $type);
if($strict && ((string) $result != (string)$value)) throw new F_App_Exception_Request("Type conversion failed for strict parameter!");
return $result;
}
private static function _convert($value, $type) {
switch(self::_weakName($type)) {
case 'STR':
case 'STRING':
$value = (string) $value;
break;
case 'INT':
case 'INTEGER':
$value = (int) $value;
break;
case 'FLOAT':
$value = (float) $value;
break;
case 'BOOL':
case 'BOOLEAN':
$value = (bool) $value;
break;
default: throw new F_App_Exception_Request("Invalid type requested \"$type\"!");
}
return $value;
}
} | true |
4e65c81f9e8ab1f8164c05c2d6b477ada87dcdb5 | PHP | balfour-group/laravel-query-filters | /src/Filters/FilterInterface.php | UTF-8 | 455 | 2.546875 | 3 | [
"MIT"
] | permissive | <?php
namespace Balfour\LaravelQueryFilters\Filters;
interface FilterInterface
{
/**
* @return string
*/
public function getKey();
/**
* @return mixed
*/
public function getDefaultValue();
/**
* @param array $params
* @return mixed
*/
public function getValue(array $params);
/**
* @param mixed $query
* @param mixed $value
*/
public function apply($query, $value);
}
| true |
7416a19f56be5d829c3cc010c0296d14ed9bc25b | PHP | LilianaIvonne/calificacionesLisg | /MVC/modelo/coordinadores_modelo.php | UTF-8 | 642 | 2.84375 | 3 | [] | no_license | <?php
class coordinadores_modelo {
private $db;
private $coordinadores;
public function __construct(){
require_once("../modelo/Conectar.php");
$this->db=Conectar::conexion();
$this->coordinadores=array();
}
public function get_coordinadores(){
if($consulta=$this->db->query("Select * from coordinador")){
// echo "datos cargados"; sólo se usa para comprobar que si se cargaron los datos
};
while($filas=$consulta->fetch_assoc()){
$this->coordinadores[]=$filas;
}
return $this->coordinadores;
}
}
?>
| true |
aa9307fbb623109bfb86abf14661d84e9a2ec0bc | PHP | DEVSENSE/Parsers | /Source/UnitTests/TestData/samples/test9.phpt | UTF-8 | 643 | 3.65625 | 4 | [
"Apache-2.0"
] | permissive | <?php
$juices = array("apple", "orange", "koolaid1" => "purple");
echo "He drank some $juices[0] juice.".PHP_EOL;
echo "He drank some $juices[1] juice.".PHP_EOL;
echo "He drank some $juices[koolaid1] juice.".PHP_EOL;
class people {
public $john = "John Smith";
public $jane = "Jane Smith";
public $robert = "Robert Paulsen";
public $smith = "Smith";
}
$people = new people();
echo "$people->john drank some $juices[0] juice.".PHP_EOL;
echo "$people->john then said hello to $people->jane.".PHP_EOL;
echo "$people->john's wife greeted $people->robert.".PHP_EOL;
echo "$people->robert greeted the two $people->smiths."; // Won't work
?> | true |