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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
05deaea04c3aff8c7de68362e6ea6164844342d9 | PHP | IDtholas/LouvreBilleterie | /src/AppBundle/Validator/HolidayValidator.php | UTF-8 | 813 | 2.609375 | 3 | [
"MIT"
] | permissive | <?php
/**
* Created by PhpStorm.
* User: alexa
* Date: 03/11/2017
* Time: 15:12
*/
namespace AppBundle\Validator;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
/**
* Class HolidayValidator
* @package AppBundle\Validator
*/
class HolidayValidator extends ConstraintValidator
{
/**
* @param mixed $value
* @param Constraint $constraint
*/
public function validate($value, Constraint $constraint)
{
$holidayDay = ['01/05', '01/11', '25/12'];
$date = date('d/m', $value->getTimeStamp());
foreach ($holidayDay as $holiday) {
if ($date === $holiday) {
$this->context->buildViolation($constraint->message)
->addViolation();
}
}
}
}
| true |
28e15a909876b2d74d94e9efb85079e87bce494d | PHP | sanch92/Mascotas | /controllers/MascotaController.php | UTF-8 | 6,382 | 2.6875 | 3 | [] | no_license | <?php
// CONTROLADOR UsuarioController
class MascotaController{
// operación por defecto
public function index(){
$this->list(); // listado de mascotas
}
// lista los usuarios
public function list(){
$mascotas = Mascotas::get();
include 'views/mascota/lista.php';
}
// muestra un mascota
public function show(int $id = 0){
// recuperar el usuario
if(!$mascota = Mascotas::getMascota($id))
throw new Exception("No se pudo recuperar la mascota.");
include 'views/mascota/detalles.php';
}
// muestra el formulario de nuevo usuario
public function create(){
$razas = Raza::get();
include 'views/mascota/form_new.php';
}
// guarda el nuevo usuario
public function store(){
// comprueba que llegue el formulario con los datos
if(empty($_POST['guardar']))
throw new Exception('No se recibieron datos');
$mascota = new Mascotas(); //crear el nuevo usuario
$mascota->nombre = DB::escape($_POST['nombre']);
$mascota->sexo = DB::escape($_POST['sexo']);
$mascota->biografia = DB::escape($_POST['biografia']);
$mascota->fechanacimiento = DB::escape($_POST['fechanacimiento']);
$mascota->fechafallecimiento = DB::escape($_POST['fechafallecimiento']);
$mascota->idusuario = Login::get()->id;
$mascota->idraza = intval($_POST['raza']);
if(!$mascota->guardar())
throw new Exception("No se pudo guardar $mascota->nombre");
$mensaje="Guardado la mascota $mascota->nombre";
include 'views/exito.php'; //mostrar éxito
}
//ACTUALIZAR SE HACE EN DOS PASOS
// muestra el formulario de edición de un usuario
public function edit(int $id = 0){
// esta operación solamente la puede hacer el administrador
// o bien el usuario propietario de los datos que se muestran
if(! (Login::isAdmin() || Login::get()->id == $id))
// if(!(Login::getById() || Login::get()))
throw new Exception('No tienes los permisos necesarios');
// recuperar el usuario
if(!$mascota = Mascotas::getMascota($id))
throw new Exception("No se indicó la mascota.");
// mostrar el formulario de edición
include 'views/mascota/actualizar.php';
}
// aplica los cambios de un usuario
public function update(){
// esta operación solamente la puede hacer el administrador
// o bien el usuario propietario de los datos que se muestran
if(!Login::isAdmin() || !Login::get() || Login::get()->id != $id)
throw new Exception('No tienes los permisos necesarios');
// comprueba que llegue el formulario con los datos
if(empty($_POST['actualizar']))
throw new Exception('No se recibieron datos');
$id = intval($_POST['id']); // recuperar el id vía POST
// recuperar el usuario
if(!$mascota = Mascotas::GetMascota($id))
throw new Exception("No existe la mascota $id.");
$mascota->nombre = DB::escape($_POST['nombre']);
$mascota->sexo = DB::escape($_POST['sexo']);
$mascota->biografia = DB::escape($_POST['biografia']);
$mascota->fechanacimiento = DB::escape($_POST['fechanacimiento']);
$mascota->fechafallecimiento = DB::escape($_POST['fechafallecimiento']);
//la clave solamente cambia si se indica una nueva
if(!empty($_POST['clave']))
$mascota->clave = md5($_POST['clave']);
// intenta realizar la actualización de datos
if($mascota->actualizar()===false)
throw new Exception("No se pudo actualizar $mascota->nombre");
// prepara un mensaje
$GLOBALS['mensaje'] = "Actualización de la mascota $mascota->nombre correcta.";
// repite la operación edit, así mantiene la vista de edición.
$this->edit($mascota->id);
}
// muestra el formulario de confirmación de eliminación
public function delete(int $id = 0){
// esta operación solamente la puede hacer el administrador
// o bien el usuario propietario de los datos que se muestran
if(!Login::isAdmin() || !Login::get() || Login::get()->id != $id)
throw new Exception('No tienes los permisos necesarios');
// recupera el usuario para mostrar sus datos en la vista
if(!$mascota = Mascotas::getMascota($id))
throw new Exception("No existe la mascota $id.");
// carga la vista de confirmación de borrado
include 'views/mascota/borrar.php';
}
//elimina el usuario
public function destroy(){
// esta operación solamente la puede hacer el administrador
// o bien el usuario propietario de los datos que se muestran
if(! (Login::isAdmin() || Login::get()->id == $id))
throw new Exception('No tienes los permisos necesarios');
//recuperar el identificador vía POST
$id = empty($_POST['id'])? 0 : intval($_POST['id']);
// borra el usuario de la BDD
if(!Mascotas::borrar($id))
throw new Exception("No se pudo dar de baja la mascota $id");
$mensaje = "La mascota ha sido dado de baja correctamente.";
include 'views/exito.php'; //mostrar éxito
}
}
| true |
d528ec038930374de0d4618e9d05a6a8198a5fc3 | PHP | jim7323/MyScan | /app/Http/Controllers/IndexController.php | UTF-8 | 1,000 | 2.59375 | 3 | [] | no_license | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class IndexController extends Controller
{
private $number = 0;
public function __construct(Request $request){
}
public function index(){
return view('index');
}
public function extractData(Request $request){
if($request->isMethod('post')){
$index = request('index');
$second_index = $index + 1;
$third_index = $second_index + 1;
$fourth_index = $third_index + 1;
$fifth_index = $fourth_index + 1;
//$dataArr = explode("\n", file_get_contents('C:\Users\user\python\result.txt'));
$dataArr = explode("\n", file_get_contents(storage_path('app/result.txt')));
}
echo json_encode(array('0'=>json_encode($dataArr[$index]),'1'=>json_encode($dataArr[$second_index]), '2'=>json_encode($dataArr[$third_index]), '3'=>json_encode($dataArr[$fourth_index]), '4'=>json_encode($dataArr[$fifth_index]) ));
}
}
| true |
cdc2d96af93f7397810fc4747fb0d2e6c649a14d | PHP | x768/uploda | /del.php | UTF-8 | 314 | 2.6875 | 3 | [] | no_license | <?php
define('FILENAME', "/^[^\\.\\/][^\\/]*$/");
$files = explode('/', file_get_contents('php://input'));
foreach ($files as $f)
{
if (preg_match(FILENAME, $f)) {
if (is_file("files/".$f)) {
unlink("files/".$f);
}
if (is_file("thumb/".$f.".png")) {
unlink("thumb/".$f.".png");
}
}
}
echo 'OK';
| true |
da361626cf61d5b1d2fe0cd069cf420ee042bd36 | PHP | Vincebml/PHPatterns | /src/Creational/AbstractFactory/Beer/Budweiser.php | UTF-8 | 460 | 3.1875 | 3 | [
"MIT"
] | permissive | <?php
namespace Phpatterns\Creational\AbstractFactory\Beer;
use Phpatterns\Creational\AbstractFactory\BeerInterface;
class Budweiser implements BeerInterface
{
/** @var string */
private $name;
public function __construct()
{
$this->name = 'Budweiser';
}
/**
* Name of the beer (Heineken, Budweiser, Guinness, etc.)
* @return string
*/
public function getName()
{
return $this->name;
}
}
| true |
f6a832f767ba44673fcf846d5d728f65f490fa52 | PHP | marcvifi10/Programacio-web-PICE | /9 - PHP/BDD/bdd21/dbquery.php | UTF-8 | 2,780 | 2.78125 | 3 | [] | no_license | <!DOCTYPE html>
<html>
<head>
<title>bdd21</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<script src="../jquery-3.4.1.min.js"></script>
<link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.css">
<style>
</style>
</head>
<body>
<?php
$server = "localhost";
$username = "root";
$password = "";
$databse = "proves";
$con = new mysqli($server, $username, $password, $databse);
if ($con->connect_error)
{
die("Error: ".$con->connect_errno." ".$con->connect_error);
}
$con->query("SET NAMES 'utf8'");
$page = 1;
if (isset($_GET["page"]))
{
$page = $_GET["page"];
}
$perPage = 10;
if (isset($_GET["perPage"]))
{
$perPage = $_GET["perPage"];
}
$country = "%";
if (isset($_GET["Country"]))
{
$country = $_GET["Country"];
}
$city = "%";
if (isset($_GET["City"]))
{
$city = $_GET["City"];
}
$query = "SELECT Country FROM customers GROUP BY Country ORDER BY Country";
$result = $con->query($query);
?>
<div class="container">
<select id="selectCities">
<option value="%">Select a city</option>
<?php
$query = "SELECT City FROM customers WHERE Country LIKE '".$country."' AND City Like '".$city."' GROUP BY City ORDER BY City";
$result = $con->query($query);
$numRows = $result->num_rows;
while($nextCity = $result->fetch_assoc())
{
$string = "<option value='".$nextCity["City"]."'>".$nextCity["City"]."</option>\n";
echo $string;
}
?>
</select>
<table class="table table-bordered table-hover table-responsive" id="dbTable">
<?php
$query = "SELECT * FROM customers WHERE Country LIKE '"
.$country."' AND City Like '".$city."'";
$result = $con->query($query);
$numRows = $result->num_rows;
$query .= " LIMIT ".(($page - 1) * $perPage).", ".$perPage;
$result = $con->query($query);
if ($result->num_rows == 0)
{
echo "No data found";
}
else
{
$columns = [];
$infoFields = mysqli_fetch_fields($result);
foreach ($infoFields as $value)
{
$columns[] = $value->name;
}
$string = "<tr>";
foreach ($columns as $column)
{
$string .= "<th>".$column."</th>";
}
$string .= "</tr>";
echo $string;
while($client = $result->fetch_assoc())
{
$string = "<tr>";
foreach ($columns as $column)
{
$string .= "<td>".$client[$column]."</td>";
}
$string .= "</tr>";
echo $string;
}
?>
</table>
</div>
<?php
}
$con->close();
?>
</body>
</html> | true |
6d4964a22360b81d0f9b8d227ec473158952c7e5 | PHP | fdc-antigua/cakephp | /app/Controller/UsersController.php | UTF-8 | 5,826 | 2.5625 | 3 | [] | no_license | <?php
// app/Controller/UsersController.php
App::uses('AppController', 'Controller');
class UsersController extends AppController {
public function beforeFilter() {
parent::beforeFilter();
// Allow users to register and logout.
$this->Auth->allow('add', 'logout','checkemail');
}
public function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
$_today = new DateTime();
$_today->setTimeZone(new DateTimeZone("Asia/Hong_Kong"));
$today = $_today->format('Y-m-d H:i:s');
$id = $this->Auth->user('id');
$data = array('id' => $id, 'last_login_time' => $today);
$this->User->save($data);
return $this->redirect($this->Auth->redirectUrl());
}
$this->Flash->error(__('Invalid username or password, try again'));
}
}
public function logout() {
return $this->redirect($this->Auth->logout());
}
public function index() {
$this->User->recursive = 0;
$this->set('users', $this->paginate());
}
public function view($id = null) {
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException(__('Invalid user'));
}
$this->set('user', $this->User->findById($id));
}
public function add() {
if ($this->request->is('post')) {
$this->User->create();
$this->request->data['User']['created_ip'] = $this->request->clientIp();
if ($this->User->save($this->request->data)) {
$this->Flash->success(__('The user has been saved'));
return $this->redirect(array('action' => 'login'));
}
$this->Flash->error(
__('The user could not be saved. Please, try again.')
);
}
}
public function checkemail(){
$email = $this->request->data['email'];
$this->autoRender = false;
$check = $this->User->find('count', array(
'conditions' => array('User.email' => $email)
));
return $check;
}
public function edit($id = null) {
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException(__('Invalid user'));
}
if ($this->request->is('post') || $this->request->is('put')) {
if ($this->User->save($this->request->data)) {
$this->Flash->success(__('The user has been saved'));
return $this->redirect(array('action' => 'index'));
}
$this->Flash->error(
__('The user could not be saved. Please, try again.')
);
} else {
$this->request->data = $this->User->findById($id);
unset($this->request->data['User']['password']);
}
}
public function update(){
$id = $this->Auth->user('id');
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException(__('Invalid user'));
}
if ($this->request->is('post') || $this->request->is('put')) {
if(isset($this->request->data['old_image'])){
$this->request->data['User']['image'] = $this->request->data['old_image'];
}else{
if(!empty($this->data['User']['image']['name']))
{
$file = $this->data['User']['image']; //put the data into a var for easy use
$ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
$arr_ext = array('jpg', 'jpeg', 'gif'); //set allowed extensions
//only process if the extension is valid
if(in_array($ext, $arr_ext))
{
//do the actual uploading of the file. First arg is the tmp name, second arg is
//where we are putting it
move_uploaded_file($file['tmp_name'], WWW_ROOT . 'img/uploads' . $file['name']);
//prepare the filename for database entry
$this->request->data['User']['image'] = $file['name'];
}
}else{
$this->request->data['User']['image'] = NULL;
}
$this->request->trustProxy = true;
$clientIp = $this->request-> clientIp();
$this->request->data['User']['modified'] = $this->request-> clientIp();
}
if ($this->User->save($this->request->data)) {
$this->Flash->success(__('Your Profile has been updated'));
return $this->redirect(array('controller' => 'posts','action' => 'index'));
}
$this->Flash->error(
__('Your profile could not be updated. Please, try again.')
);
} else {
$this->request->data = $this->User->findById($id);
$this->set('post', $this->User->findById($id));
unset($this->request->data['User']['password']);
}
}
public function delete($id = null) {
// Prior to 2.5 use
// $this->request->onlyAllow('post');
$this->request->allowMethod('post');
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException(__('Invalid user'));
}
if ($this->User->delete()) {
$this->Flash->success(__('User deleted'));
return $this->redirect(array('action' => 'index'));
}
$this->Flash->error(__('User was not deleted'));
return $this->redirect(array('action' => 'index'));
}
} | true |
44642197f2e1b86a68adec6d32788efe92917f93 | PHP | benjisimon/code | /omer-learning-book/lib/book.php | UTF-8 | 4,248 | 2.640625 | 3 | [] | no_license | <?php
define('FPDF_FONTPATH', __DIR__ . '/../fonts/');
/*
* A PHP file for generating books
*/
class Book extends FPDF {
private $styles;
private $current_style;
private $margins = [
'top' => 72,
'bottom' => 72,
'right' => 36,
'left' => 36
];
function __construct() {
parent::__construct('P', 'pt', 'letter');
$this->AddFont('oswald', 'b', 'Oswald-Bold.php');
$this->AddFont('aller', '', 'Aller_Rg.php');
$this->styles = [
'default' => ['helvetica', '', 12, [0, 0, 0]],
'book_title' => ['oswald', 'b', 48, [13, 49, 95]],
'book_subtitle' => ['aller', '', 36, [86, 135, 194]],
'thanks_intro' => ['oswald', 'b', 16, [0, 0, 0]],
'h1' => ['oswald', 'b', 16, [13, 49, 95]],
'h2' => ['aller', '', 10, [0, 0, 0]],
'link' => ['aller', '', 12, [0, 0, 0]]
];
$this->setStyle('default');
$this->AddPage();
$this->SetMargins($this->margins['left'], $this->margins['top'], $this->margins['right']);
$this->SetAutoPageBreak(true, $this->margins['bottom']);
}
public function addTitlePage() {
$this->SetY(72 * 2);
$this->withStyle('book_title', function() {
$this->Cell(0, 55, "49 Days to a Greener and", 0, 2, 'C');
$this->Cell(0, 55, "More Equitable Community", 0, 2, 'C');
});
$this->Ln(72);
$this->withStyle('book_subtitle', function() {
$this->Cell(0, 12, "Omer Learning 2022", 0, 2, 'C');
});
$this->Ln(72 * 3);
$this->Image(__DIR__ . "/../images/logo.png", 72 * 3);
$this->AddPage();
}
public function addThanksPage() {
$this->withStyle('thanks_intro', function() {
$this->Cell(0, 24, "Special thanks to this year's contributors", 0, 1, 'C');
});
$fd = fopen(__DIR__ . '/../data/contributors.csv', 'r');
while($row = fgetcsv($fd)) {
$this->Cell(0, 20, $row[0], 0, 1, 'C');
}
$this->AddPage();
}
public function withSmartBreak($generator) {
$scratchpad = new Book();
$generator($scratchpad);
$height = $scratchpad->GetY();
$remaining = $this->GetPageHeight() - $this->GetY() - $this->margins['bottom'];
if($height > $remaining) {
$this->AddPage();
}
$generator($this);
}
function withIndent($size, $generator) {
$this->SetX($this->margins['left']+ $size);
$generator();
$this->SetX($this->margins['left']);
}
public function addEntry($entry) {
$this->withSmartBreak(function($book) use($entry) {
$book->withStyle('h1', function() use($entry,$book){
$book->Cell(0, 16, $entry['The Count'], 0, 2);
});
$book->withStyle('h2', function() use($entry, $book) {
$book->Cell(0, 20, $entry['Topic'], 0, 2);
});
$y_before = $book->GetY();
$this->withIndent(15, function() use($book, $entry) {
$book->MultiCell(0, 16, $book->scrub($entry['Content']), 0, 'L');
});
$this->Ln();
$this->withIndent(15, function() use ($book, $entry) {
if($url = trim($entry['Learn More'])) {
$short_url = bitly_shrink($url);
$label = str_replace('https://', '', $short_url);
$text = "Read More at $label";
$book->Cell($book->GetStringWidth($text), 14, $text, '', 2, 'C', false, $url);
}
});
$y_after = $book->GetY();
if($y_before < $y_after) {
$book->SetLineWidth(3);
$book->SetDrawColor(200, 200, 200);
$book->Line($this->margins['left'] + 4, $y_before, $this->margins['left'] + 4, $y_after);
}
$book->Ln();
$book->Ln();
});
}
public function setStyle($name) {
$this->current_style = $name;
$this->SetFont($this->styles[$name][0],
$this->styles[$name][1],
$this->styles[$name][2],);
[$r,$g,$b] = $this->styles[$name][3];
$this->SetTextColor($r, $g, $b);
}
public function withStyle($style, $thunk) {
$before = $this->current_style;
$this->setStyle($style);
$thunk();
$this->setStyle($before);
}
private function scrub($text) {
$fixes = [
"’" => "'",
'“' => '"',
'”' => '"',
'–' => '-',
];
return str_replace(array_keys($fixes), array_values($fixes), $text);
}
}
| true |
156bed0397a86335f4059458ee0afdcbd7aa60fa | PHP | jquerygeek/gpweb | /src/Bundle/UserBundle/Dao/UserDao.php | UTF-8 | 460 | 2.765625 | 3 | [
"MIT"
] | permissive | <?php
namespace Bundle\UserBundle\Dao;
interface UserDao
{
/**
* Retrieve User by login and password
*
* @param string $login
* @param string $password
*
* @return Bundle\UserBundle\Entities\User
*/
public function findByLoginAndPassword($data);
/**
* register a new user
*
* @param array $data
* @return Bundle\UserBundle\Entities\User
*/
public function registerUser($data);
}
| true |
d32e36a10b6d4b290a2eb15881d3af603edc741f | PHP | raylison100/Project-WEB-BackEnd | /app/Models/Event.php | UTF-8 | 997 | 2.53125 | 3 | [] | no_license | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;
/**
* Class Ticket.
*
* @package namespace App\Models;
*/
class Event extends Model implements Transformable
{
use TransformableTrait,SoftDeletes;
protected $fillable = [
'subject',
'status_event_id',
'user_id',
];
protected $dates = [
'created_at',
'updated_at',
'deleted_at'
];
public function messages()
{
return $this->hasMany(Message::class);
}
public function users(){
return $this->belongsTo(User::class,'user_id');
}
public function statusEvent(){
return $this->hasOne(StatusEvent::class,'id','status_event_id' );
}
public function participants()
{
return $this->belongsToMany(Participant::class,'event_participants');
}
}
| true |
b74771651acf5b7e5319e888b6b262bf2e0d78a6 | PHP | arkaitzgarro/kreta | /src/Kreta/Bundle/CoreBundle/Event/FormHandlerEvent.php | UTF-8 | 1,843 | 2.765625 | 3 | [
"MIT"
] | permissive | <?php
/**
* This file belongs to Kreta.
* The source code of application includes a LICENSE file
* with all information about license.
*
* @author benatespina <benatespina@gmail.com>
* @author gorkalaucirica <gorka.lauzirika@gmail.com>
*/
namespace Kreta\Bundle\CoreBundle\Event;
use Symfony\Component\EventDispatcher\Event;
/**
* Class FormHandlerEvent.
*
* @package Kreta\Bundle\CoreBundle\Event
*/
class FormHandlerEvent extends Event
{
const NAME = 'kreta_core_event_form_handler';
const TYPE_SUCCESS = 'success';
const TYPE_ERROR = 'error';
/**
* Event type.
*
* @var string
*/
protected $type;
/**
* Event message.
*
* @var string
*/
protected $message;
/**
* Creates a form handler event.
*
* @param string $type Event type, use FormHandlerEvent::TYPE_* constants
* @param string $message Message to be displayed to the user
*/
public function __construct($type, $message)
{
$this->type = $type;
$this->message = $message;
}
/**
* Gets type.
*
* @return string
*/
public function getType()
{
return $this->type;
}
/**
* Sets type. Use FormHandlerEvent::TYPE_* constants
*
* @param string $type The type to be set
*
* @return $this self Object
*/
public function setType($type)
{
$this->type = $type;
return $this;
}
/**
* Returns message.
*
* @return string
*/
public function getMessage()
{
return $this->message;
}
/**
* Sets message.
*
* @param string $message The message to be set
*
* @return $this self Object
*/
public function setMessage($message)
{
$this->message = $message;
return $this;
}
}
| true |
2849677c68c77b198adb9ecdd51971d9b0033e57 | PHP | prezzemolo/logistica | /classes/router.php | UTF-8 | 2,476 | 2.984375 | 3 | [] | no_license | <?php
namespace Logistica\Classes;
require_once join(DIRECTORY_SEPARATOR, [__DIR__, '..', 'tools', 'ex-string.php']);
use Exception;
use Logistica\Tools\ExString;
// error for class Router
class RouterError extends Exception {}
class Router {
private $path;
private $prefix;
private $routes = array();
private function utrim (string $before) {
return trim($before, '/');
}
public function __construct (string $prefix = NULL) {
$this->prefix = utrim($prefix);
$this->path = utrim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
}
public function add_route (string $origin_name, callable $callback) {
$name = utrim($origin_name);
if (isset($this->routes[$name])) throw new RouterError("You can't override exstent route.");
$this->routes[$name] = $callback;
}
public function remove_route (string $origin_name) {
$name = utrim($origin_name);
if (!isset($this->routes[$name])) throw new RouterError("You can't remove non-exstent route.");
unset($this->routes[$name]);
}
public function exec (): bool {
// OK with no prefix, kick!
if (!isset($this->prefix)) return $this->search_and_exec($this->path);
list($prefix, $path) = explode('/', $this->path, 2);
// prefix exists, but prefix not match
if ($prefix !== $this->prefix) return false;
// OK with prefix, kick!
return $this->search_and_exec($path);
}
private function search_and_exec (string $path) {
foreach ($this->routes as $route => $callback) {
$route_factors = trim($route, '/');
$path_match_regexp_pattern = '/^';
$path_match_dynamic_param_names = array();
foreach ($route_factors as $route_factor) {
if (!ExString::startsWith($route_factor, ':')) {
$path_match_regexp_pattern .= $route_factor + '\/';
continue;
}
array_push($path_match_dynamic_param_names, mb_strcut($route_factor, 1));
$path_match_regexp_pattern .= '([^\/]*?)\/';
}
$path_match_dynamic_param_values = array();
$path_match_result = mb_ereg($path_match_regexp_pattern, $path, $path_match_dynamic_param_values);
if ($path_match_result === false) return false;
array_shift($path_match_dynamic_param_values);
$path_match_dynamic_params = array_combine(
$path_match_dynamic_param_names, $path_match_dynamic_param_values);
return call_user_func($callback, [
$path_match_dynamic_params
]);
}
}
}
| true |
4c57fa16f9869a2c6210744786b436e90d7d2710 | PHP | aaxpost/php_form | /formz4.php | UTF-8 | 2,055 | 2.734375 | 3 | [] | no_license | <html>
<head>
<title>Формы_Задача_4</title>
<meta charset="utf-8">
</head>
<body>
<p>Задача №4</p>
<p> Реализуйте заготовку регистрации пользователя. Спросите у него
логин, пароль (в браузере должен быть звездочками) и
подтверждение пароля (тоже звездочками). Сравните пароль и его
подтверждение: если они не совпадают — выведите сообщение об
этом. Проверьте то, что пароль больше 5-ти символов и меньше 9-ти,
а логин больше 3-х и меньше 12-ти символов. Если все правильно —
выведите пользователю сообщение о том, что он успешно
зарегистрирован.</p>
<form action="" method="POST">
<input type="text" placeholder = "логин" name="login"><br><br>
<input type="password" placeholder = "Пароль" name="password_1"><br><br>
<input type="password" placeholder = "Пароль для проверки" name="password_2"><br><br>
<input type="submit" value = "Нажмите для регистрации">
</form>
<?php
//Если форма была отправлена и переменная не пустая:
if (
isset($_REQUEST['login']) and
isset($_REQUEST['password_1']) and
isset($_REQUEST['password_2'])
)
{
$login = trim(strip_tags($_REQUEST['login']));
$pass1 = trim(strip_tags($_REQUEST['password_1']));
$pass2 = trim(strip_tags($_REQUEST['password_2']));
if ($pass1 != $pass2)
{
echo 'Введенные пароли не совпадают! Повторите попытку.';
}
else
{
if (((strlen($pass1)) > 5 and (strlen($pass1)) < 9) and
((strlen($login)) > 3 and (strlen($login)) < 12))
{
echo 'Вы успешно прошли регистрацию';
}
}
}
?>
</body>
</html>
| true |
6a3f6fa1756919897eaa6616ec74ac502d3ca9e1 | PHP | daaner/NovaPoshta | /src/Traits/Limit.php | UTF-8 | 1,002 | 2.859375 | 3 | [
"MIT"
] | permissive | <?php
namespace Daaner\NovaPoshta\Traits;
trait Limit
{
protected $limit;
protected $page;
/**
* Установка лимита записей.
*
* @param int $limit Лимит записей
* @return $this
*/
public function setLimit(int $limit): self
{
$this->limit = $limit;
return $this;
}
/**
* Установка страницы.
*
* @param int $page Номер страницы данных
* @return $this
*/
public function setPage(int $page): self
{
$this->page = $page;
return $this;
}
/**
* @return void
*/
public function getLimit(): void
{
if ($this->limit) {
$this->methodProperties['Limit'] = $this->limit;
}
}
/**
* @return void
*/
public function getPage(): void
{
if ($this->page) {
$this->methodProperties['Page'] = $this->page;
}
}
}
| true |
f3cf59882def36561ebb8bc7a31d30fbf34a9288 | PHP | Mogrenn/mobilaBiblan | /functions/user.php | UTF-8 | 161 | 2.671875 | 3 | [] | no_license | <?php
class User{
private $DB;
function __construct($DB){
$this->DB = $DB;
}
function __destruct(){
$this->DB->closeConnection();
}
}
| true |
21dce8e8b2a31d0a4b0f8aae2e20e24411646b37 | PHP | geldrin/PHP-testing-ground | /libraries/clonefish/validation.string.php | UTF-8 | 11,092 | 2.890625 | 3 | [] | no_license | <?php
/**
* Clonefish form generator class
* (c) phpformclass.com, Dots Amazing
* All rights reserved.
*
* @copyright 2010 Dots Amazing
* @link http://phpformclass.com
* @package clonefish
* @subpackage validation
*/
/*
* Validation
* @package clonefish
* @subpackage validationTypes
*/
class stringValidation extends validation {
var $settings = Array();
// settings coming from the settings array
var $minimum; // minimum length
var $maximum; // maximum length
var $regexp; // regular expression matching
var $regexpnot; // regular expression not matching
var $jsregexp; // regular expression matching for JS
var $jsregexpnot; // regular expression not matching for JS
var $phpregexp; // regular expression matching for PHP
var $phpregexpnot; // regular expression not matching for PHP
var $equals; // fieldname of equal field
var $differs; // fieldname of differing field
var $form; // form
var $required = 1;
// -------------------------------------------------------------------------
function getJSCode( ) {
$code = '';
$fieldvalue = $this->getJSValue();
// EQUALS
if ( strlen( $this->equals ) ) {
$equalfield = $this->form->getElementByName( $this->equals );
if ( !is_object( $equalfield ) )
die(
sprintf(
CF_ERR_STRING_FIELD_NOT_FOUND,
$this->equals,
'equals',
$this->element->getDisplayName()
)
);
$code .=
'errors.addIf( \'' . $this->element->_getHTMLId() . '\', ' .
( $this->required ? '' : '( ' . $fieldvalue . '.length == 0 ) || ' ) .
'( ' . $fieldvalue . ' == ' . $this->getJSValue( $equalfield ) . " ), \"" .
$this->_jsescape( sprintf(
$this->selecthelp( $this->element, CF_STR_STRING_NOT_EQUAL ),
$this->element->getDisplayName(),
$equalfield->getDisplayName()
) ). "\" );\n";
}
// DIFFERS
if ( strlen( $this->differs ) ) {
$differfield = $this->form->getElementByName( $this->differs );
if ( !is_object( $differfield ) )
die(
sprintf(
CF_ERR_STRING_FIELD_NOT_FOUND,
$this->differs,
'differs',
$this->element->getDisplayName()
)
);
$code .=
'errors.addIf( \'' . $this->element->_getHTMLId() . '\', ' .
( $this->required ? '' : '( ' . $fieldvalue . '.length == 0 ) || ' ) .
'( ' . $fieldvalue . ' != ' . $this->getJSValue( $differfield ) . " ), \"" .
$this->_jsescape( sprintf(
$this->selecthelp( $this->element, CF_STR_STRING_NOT_DIFFERENT ),
$this->element->getDisplayName(),
$differfield->getDisplayName()
) ). "\" );\n";
}
// MINIMUM LENGTH
if ( is_numeric( $this->minimum ) )
if ( $this->form->_functionSupported('strlen') )
$code .=
'errors.addIf( \'' . $this->element->_getHTMLId() . '\', ' .
( $this->required ? '' : '( ' . $fieldvalue . '.length == 0 ) || ' ) .
$fieldvalue .
'.length >= ' . $this->minimum . ", \"" .
$this->_jsescape( sprintf(
$this->selecthelp( $this->element, CF_STR_STRING_MINIMUM ),
$this->element->getDisplayName(),
$this->minimum
) ). "\" );\n";
// MAXIMUM LENGTH
if ( is_numeric( $this->maximum ) )
if ( $this->form->_functionSupported('strlen') )
$code .=
'errors.addIf( \'' . $this->element->_getHTMLId() . '\', ' .
( $this->required ? '' : '( ' . $fieldvalue . '.length == 0 ) || ' ) .
$fieldvalue .
'.length <= ' . $this->maximum . ", \"" .
$this->_jsescape( sprintf(
$this->selecthelp( $this->element, CF_STR_STRING_MAXIMUM ),
$this->element->getDisplayName(),
$this->maximum
) ) . "\" );\n";
// MATCHING REGULAR EXPRESSION
if ( strlen( $this->regexp ) || strlen( $this->jsregexp ) ) {
if ( $this->form->_functionSupported('regexp') ) {
$regexp = $this->regexp;
if ( strlen( $this->jsregexp ) )
$regexp = $this->jsregexp;
$code .=
'errors.addIf( \'' . $this->element->_getHTMLId() . '\', ' .
( $this->required ? '' : '( ' . $fieldvalue . '.length == 0 ) || ' ) .
$fieldvalue . ".search( " . $regexp . " ) != -1, \"" .
$this->_jsescape( sprintf(
$this->selecthelp( $this->element, CF_STR_STRING_REGEXP ),
$this->element->getDisplayName(),
$regexp
) ) . "\" );\n";
}
}
// NOT MATCHING REGULAR EXPRESSION
if ( strlen( $this->regexpnot ) || strlen( $this->jsregexpnot ) ) {
if ( $this->form->_functionSupported('regexp') ) {
$regexpnot = $this->regexpnot;
if ( strlen( $this->jsregexpnot ) )
$regexpnot = $this->jsregexpnot;
$code .=
'errors.addIf( \'' . $this->element->_getHTMLId() . '\', ' .
( $this->required ? '' : '( ' . $fieldvalue . '.length == 0 ) || ' ) .
$fieldvalue . ".search( " . $regexpnot . " ) == -1, \"" .
$this->_jsescape( sprintf(
$this->selecthelp( $this->element, CF_STR_STRING_REGEXP_NOT ),
$this->element->getDisplayName(),
$regexpnot
) ) . "\" );\n";
}
}
return $this->injectDependencyJS( $code );
}
// -------------------------------------------------------------------------
function isValid() {
$results = Array();
if ( $this->checkDependencyPHP() ) {
// EQUALS
if ( strlen( $this->equals ) ) {
$equalfield = $this->form->getElementByName( $this->equals );
if ( !is_object( $equalfield ) )
die(
sprintf(
CF_ERR_STRING_FIELD_NOT_FOUND,
$this->equals,
'equals',
$this->element->getDisplayName()
)
);
if (
( $this->required || strlen( $this->element->getValue( 0 ) ) ) &&
( $this->element->getValue( 0 ) != $equalfield->getValue( 0 ) )
) {
$message =
sprintf(
$this->selecthelp( $this->element, CF_STR_STRING_NOT_EQUAL ),
$this->element->getDisplayName(),
$equalfield->getDisplayName()
);
$results[] = $message;
$this->element->addMessage( $message );
}
}
// DIFFERS
if ( strlen( $this->differs ) ) {
$differfield = $this->form->getElementByName( $this->differs );
if ( !is_object( $differfield ) )
die(
sprintf(
CF_ERR_STRING_FIELD_NOT_FOUND,
$this->differs,
'differs',
$this->element->getDisplayName()
)
);
if (
( $this->required || strlen( $this->element->getValue( 0 ) ) ) &&
( $this->element->getValue( 0 ) == $differfield->getValue( 0 ) )
) {
$message =
sprintf(
$this->selecthelp( $this->element, CF_STR_STRING_NOT_DIFFERENT ),
$this->element->getDisplayName(),
$differfield->getDisplayName()
);
$results[] = $message;
$this->element->addMessage( $message );
}
}
// MINIMUM LENGTH
if (
is_numeric( $this->minimum ) &&
( $this->form->_functionSupported('strlen') )
) {
if (
( $this->required || strlen( $this->element->getValue( 0 ) ) ) &&
( $this->form->_handleString( 'strlen', $this->element->getValue( 0 ) ) < $this->minimum )
) {
$message =
sprintf(
$this->selecthelp( $this->element, CF_STR_STRING_MINIMUM ),
$this->element->getDisplayName(),
$this->minimum
);
$results[] = $message;
$this->element->addMessage( $message );
}
}
// MAXIMUM LENGTH
if (
is_numeric( $this->maximum ) &&
( $this->form->_functionSupported('strlen') )
) {
if (
( $this->required || strlen( $this->element->getValue( 0 ) ) ) &&
( $this->form->_handleString( 'strlen', $this->element->getValue( 0 ) ) > $this->maximum )
) {
$message =
sprintf(
$this->selecthelp( $this->element, CF_STR_STRING_MAXIMUM ),
$this->element->getDisplayName(),
$this->maximum
);
$results[] = $message;
$this->element->addMessage( $message );
}
}
// MATCH REGEXP
if ( strlen( $this->regexp ) || strlen( $this->phpregexp ) ) {
if ( $this->form->_functionSupported('regexp') ) {
$regexp = $this->regexp;
if ( strlen( $this->phpregexp ) )
$regexp = $this->phpregexp;
if (
( $this->required || strlen( $this->element->getValue( 0 ) ) ) &&
!$this->form->_handleString( 'regexp', $this->element->getValue( 0 ), $regexp )
) {
$message =
sprintf(
$this->selecthelp( $this->element, CF_STR_STRING_REGEXP),
$this->element->getDisplayName(),
$regexp
);
$results[] = $message;
$this->element->addMessage( $message );
}
}
}
// DON'T MATCH REGEXP
if ( strlen( $this->regexpnot ) || strlen( $this->phpregexpnot ) ) {
if ( $this->form->_functionSupported('regexp') ) {
$regexpnot = $this->regexpnot;
if ( strlen( $this->phpregexpnot ) )
$regexpnot = $this->phpregexpnot;
if (
( $this->required || strlen( $this->element->getValue( 0 ) ) ) &&
$this->form->_handleString( 'regexp', $this->element->getValue( 0 ), $regexpnot )
) {
$message =
sprintf(
$this->selecthelp( $this->element, CF_STR_STRING_REGEXP_NOT),
$this->element->getDisplayName(),
$regexpnot
);
$results[] = $message;
$this->element->addMessage( $message );
}
}
}
}
return $results;
}
}
?> | true |
970e238166335acf283fa7640c290b27438d9ba4 | PHP | daveselinger/greenbase | /Tweet.php | UTF-8 | 3,935 | 2.578125 | 3 | [
"MIT"
] | permissive | <?php
/**
* Created by PhpStorm.
* User: selly
* Date: 5/1/15
* Time: 10:03 AM
*/
namespace greenbase;
include_once 'Database.php';
// Note this works, but could be replaced with the better one found here: https://mathiasbynens.be/demo/url-regex, but needs to be really really tested: _^(?:(?:https?|ftp)://)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)(?:\.(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)*(?:\.(?:[a-z\x{00a1}-\x{ffff}]{2,})))(?::\d{2,5})?(?:/[^\s]*)?$_iuS
define ('URL_REGEX', "{(http|https|ftp)\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&%\$#\=~])*}");
define ('URL_REPLACEMENT', '<a href="$0">$0</a>');
define ('TWITTER_HANDLE_REGEX', "/@([A-Za-z0-9_]{1,15})/");
define ('TWITTER_HANDLE_REPLACEMENT', '<a href="http://twitter.com/$1">$0</a>');
define ('TWITTER_HASHTAG_REGEX', "/#([A-Za-z0-9_]{1,15})/");
define ('TWITTER_HASHTAG_REPLACEMENT', '<a href="http://twitter.com/search?q=%23$1">$0</a>');
class Tweet
{
public $orgId, $createdAt, $text, $userProfileImageUrl, $userDescription, $userUrl;
public function getHtmlIzedText() {
$tempText = preg_replace(URL_REGEX, URL_REPLACEMENT, $this->text);
$tempText = preg_replace(TWITTER_HASHTAG_REGEX, TWITTER_HASHTAG_REPLACEMENT, $tempText);
return preg_replace(TWITTER_HANDLE_REGEX, TWITTER_HANDLE_REPLACEMENT, $tempText);
}
public static function getTweets(\mysqli_stmt $stmt) {
$results = [];
if ($stmt == null || $stmt == false) {
echo "Oops! We had a problem: Null statement";
return $results;
}
$tweet = new Tweet();
if ($stmt->execute()) {
$stmt->bind_result($tweet->orgId, $tweet->createdAt, $tweet->text, $tweet->userProfileImageUrl, $tweet->userDescription, $tweet->userUrl);
} else {
echo "Oops! We had a problem: Query failed";
echo $con->error;
}
while ($stmt->fetch()) {
$results[] = $tweet;
$tweet = new Tweet();
$stmt->bind_result($tweet->orgId, $tweet->createdAt, $tweet->text, $tweet->userProfileImageUrl, $tweet->userDescription, $tweet->userUrl);
}
return $results;
}
public static function getTweetsForOrg($orgId, \mysqli $con)
{
$result = null;
$query = "SELECT org_id, created_at, text, user_profile_image_url, user_description, user_url FROM twitter_feed WHERE org_id = ? ORDER BY created_at DESC";
$stmt = $con->prepare($query);
if ($stmt->bind_param("i", $orgId)) {
$result = Tweet::getTweets($stmt);
} else {
echo "Oops! We had a problem: Failure to bind";
}
$stmt->close();
return $result;
}
public static function getRecentTweets(\mysqli $con)
{
$result = null;
$query = "SELECT org_id, created_at, text, user_profile_image_url, user_description, user_url FROM twitter_feed ORDER BY created_at DESC LIMIT 10";
$stmt = $con->prepare($query);
$result = Tweet::getTweets($stmt);
$stmt->close();
return $result;
}
/**
* Turns an array of tweets into their corresponding HTML.
* @param $tweets
* @return string
*/
public static function htmlizeTweets($tweets) {
$result = '';
$result = $result . "<link rel='stylesheet' type='text/css' href='" . Config::$greenbase_root . "/css/twitter.css'>";
$result = $result . "<UL>";
foreach ($tweets as $tweet) {
$result = $result . "<LI><A HREF='" . $tweet->userUrl . "'><IMG SRC='" . $tweet->userProfileImageUrl . "'></A> Tweeted <blockquote class='twitter-tweet'>". $tweet->getHtmlIzedText() . "</blockquote><BR>" . $tweet->createdAt;
}
$result = $result . "</UL>";
return $result;
}
}
?>
| true |
f9010564c8136276b155586223358c923a7ac26c | PHP | sidazhong/leetcode | /class257/hw4/part2/debug.php | UTF-8 | 1,620 | 2.75 | 3 | [] | no_license | <?php
/**
* @author sida
*
* mysql
* database: EXERCISE
* table: WORK_OUT
* (longitude:float, latitude:float, workout_type:varchar(5), start-year:int, start-month:int, start-day:int, start-hour:int, start-minutes:int duration:int)
* (37.33939,-121.89496, 'swim', 2020, 11, 30, 23, 10, 60)
*
* 20 examples
*
*
*
*/
class debug{
function __construct($action=null,$some_folder=null){
//clear every thing
if($action=="clear"){
exit;
}
}
static function d($data){
print_r($data);
echo "\n";
}
//get all .rss files
function get_all_files($some_folder,$type){
$rs = [];
if ($handle = opendir($some_folder)) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
$pathinfo = pathinfo($entry);
if(!empty($pathinfo['extension'])){
if($pathinfo['extension']==$type){
$rs[]=$some_folder."/".$entry;
}
}
}
}
closedir($handle);
}
return $rs;
}
function toBase($num, $b=62) {
$base='0123456789';
$r = $num % $b ;
$res = $base[$r];
$q = floor($num/$b);
while ($q) {
$r = $q % $b;
$q =floor($q/$b);
$res = $base[$r].$res;
}
return $res;
}
}
$obj=new debug(empty($argv[1])?"":$argv[1]);
?> | true |
58b050e8c125ddb3d3134dccce6bf0f2d66174a4 | PHP | dwipebriani/inventaris_ujikom | /print_id_peminjaman.php | UTF-8 | 1,377 | 2.671875 | 3 | [
"MIT"
] | permissive | <?php
require_once __DIR__ . '/vendor/autoload.php';
include 'config.php';
$id_peminjaman = @$_GET['id_peminjaman'];
$peminjaman=mysqli_query($koneksi, "SELECT * FROM tbl_peminjaman
LEFT JOIN tbl_inventaris ON tbl_peminjaman.kode=tbl_inventaris.kode
LEFT JOIN tbl_ruang ON tbl_inventaris.kode_ruang=tbl_ruang.kode_ruang
LEFT JOIN tbl_pegawai ON tbl_peminjaman.id_pegawai=tbl_pegawai.id_pegawai where tbl_peminjaman.id_peminjaman = '$id_peminjaman'");
$mpdf = new \Mpdf\Mpdf();
$html = '<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Daftar Mahasiswa</title>
<link rel="stylesheet" href="css/print.css">
</head>
<body>
<h1>Daftar Peminjaman</h1>
<table border="1" cellpadding="10" cellspacing="0">
<tr>
<th>No.</th>
<th>Userame</th>
<th>Barang</th>
<th>Ruang</th>
<th>Jumlah</th>
<th>Tanggal</th>
</tr>';
$i = 1;
foreach( $peminjaman as $row ) {
$html .= '<tr>
<td>'. $i++ .'</td>
<td>'. $row["username"] .'</td>
<td>'. $row["nama"] .'</td>
<td>'. $row["nama_ruang"] .'</td>
<td>'. $row["jumlah_pinjam"] .'</td>
<td>'. $row["tanggal_pinjam"] .'</td>
</tr>';
}
$html .= '</table>
</body>
</html>';
$mpdf->WriteHTML($html);
$mpdf->Output('daftar-peminjaman.pdf', \Mpdf\Output\Destination::DOWNLOAD);
?>
| true |
68e1d45e4cb379de33d067662d7e85f8eebf6ab3 | PHP | code0001aaa/ProjectPrimera | /OngekiScoreLog/app/MusicData.php | UTF-8 | 2,008 | 2.671875 | 3 | [
"MIT"
] | permissive | <?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
class MusicData extends Model
{
protected $table = "music_datas";
protected $guarded = ['id'];
function getEstimateExtraLevel(){
$music = MusicData::all();
$keys = [
['basic_level', 'basic_extra_level', 'basic_level_str'],
['advanced_level', 'advanced_extra_level', 'advanced_level_str'],
['expert_level', 'expert_extra_level', 'expert_level_str'],
['master_level', 'master_extra_level', 'master_level_str'],
['lunatic_level', 'lunatic_extra_level', 'lunatic_level_str'],
];
// 表示用データに加工
foreach ($music as $key => $value) {
foreach ($keys as $k) {
// 譜面定数が未定義なら暫定定数を入れる
$music[$key][$k[1]."_estimated"] = false;
if(is_null($value[$k[1]]) && !is_null($value[$k[0]])){
$music[$key][$k[1]] = floor($value[$k[0]]);
if(strpos($value[$k[0]], ".5") !== false){
$music[$key][$k[1]] += 0.7;
}
$music[$key][$k[1]."_estimated"] = true;
}else if(is_null($value[$k[0]])){
$music[$key][$k[0]] = null;
$music[$key][$k[1]] = null;
$music[$key][$k[1]."_estimated"] = false;
}
// レベルのstr版を増やす
if(is_null($value[$k[0]])){
$music[$key][$k[2]] = null;
}else if(strpos($value[$k[0]], ".5") !== false){
$music[$key][$k[2]] = substr($music[$key][$k[0]], 0, strpos($value[$k[0]], ".")) . "+";
}else{
$music[$key][$k[2]] = substr($music[$key][$k[0]], 0, strpos($value[$k[0]], "."));
}
}
}
return $music;
}
}
| true |
dff9761f6a46dd211fd0a5f31d4764c05953ae13 | PHP | deneb3525/chat-program | /views/logout.php | UTF-8 | 321 | 2.515625 | 3 | [] | no_license | <!DOCTYPE html>
<html>
<body>
<?php
session_start();
print_r($_SESSION);
// remove all session variables
session_unset();
// destroy the session
session_destroy();
print_r($_SESSION);
?>
You are logged out.
<a href="<?= 'http://'.$_SERVER['HTTP_HOST'].'/views/main_login.php' ?>">Back to login</a>
</body>
</html> | true |
699aee7eeddc5fad2e895954c8b4b4d50ac135cf | PHP | Yangyang-Cui/FHSU_Map_Management | /include/parseProfile.php | UTF-8 | 3,790 | 2.625 | 3 | [] | no_license | <?php
if((isset($_SESSION['id']) || isset($_GET['user_identity'])) && !isset($_POST['updateProfileBtn'])){
if(isset($_GET['user_identity'])){
$url_encoded_id = $_GET['user_identity'];
$decode_id = base64_decode($url_encoded_id);
$url_id_array = explode("encodeuserid", $decode_id);
$id = $url_id_array[1];
} else {
$id = $_SESSION['id'];
}
$sqlQuery = "SELECT * FROM users WHERE id = :id";
$statement = $db->prepare($sqlQuery);
$statement->execute(array(':id' => $id));
while($rs = $statement->fetch()){
$first_name = $rs['first_name'];
$last_name = $rs['last_name'];
$email = $rs['email'];
$date_joined = strftime("%b %d, %Y", strtotime($rs['join_date']));
}
$user_pic = "img/".$first_name.$last_name.".jpg";
$default = "img/default_profile.jpg";
if(file_exists($user_pic)){
$profile_picture = $user_pic;
} else {
$profile_picture = $default;
}
$encode_id = base64_encode("encodeuserid{$id}");
} else if(isset($_POST['updateProfileBtn'])){
// initialize an array to store any error message from the form
$form_errors = array();
// form validation
$required_fields = array('email', 'first_name', 'last_name');
// call the function to check empty field and merge the return data into form_error array
$form_errors = array_merge($form_errors, check_empty_fields($required_fields));
echo count($form_errors).'-1';
// fields that requires checking for minimum length
// $fields_to_check_length = array('username' => 4);
//$form_errors = array_merge($form_errors, check_pattern('/.{8,16}/',$_POST['password'],'password'));
//echo count($form_errors).'-2';
// call the function to check minimum required length and merge the return data into form_error array
//$form_errors = array_merge($form_errors, check_min_length($fields_to_check_length));
// email validation / merge the return data into form_error array
$form_errors = array_merge($form_errors, check_email($_POST));
echo count($form_errors).'-3';
// validate if file has a valid extension
isset($_FILES['avatar']['name'])? $avatar = $_FILES['avatar']['name'] : $avatar = null;
if($avatar != null) {
$form_errors = array_merge($form_errors, isValidImage($avatar));
}
echo count($form_errors).'-4';
// collect form data and store in variables
$email = $_POST['email'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$hidden_id = $_POST['hidden_id'];
if(empty($form_errors)){
try{
// create SQL update statement
$sqlUpdate = 'UPDATE users SET first_name = :first_name, last_name = :last_name, email =:email WHERE id=:id';
// use PDO prepared to sanitize data
$statement = $db->prepare($sqlUpdate);
// update the record in the database
$statement->execute(array(':first_name' => $first_name, ':last_name' => $last_name, ':email' => $email, ':id' => $hidden_id));
// check if one new row was created
if($statement->rowCount() == 1 || uploadAvatar($first_name,$last_name)) {
$result = flashMessage("Update successfully", true);
} else {
$result = flashMessage("You have not made any changes");
}
} catch (PDOException $ex){
$result = flashMessage(("An error occurred in : " .$ex->getMessage()));
}
} else {
if(count($form_errors) == 1) {
$result = flashMessage("There was 1 error in the form<br>");
} else {
$result = flashMessage('There were '.count($form_errors). ' errors in the form<br>');
}
}
} | true |
ff76be662a56c4a864d2cc31ef4a7dc30b173608 | PHP | zxy787956151/ZxyProject | /www/myphp/Ajax2/service.php | UTF-8 | 479 | 3.1875 | 3 | [] | no_license | <?php
//接受请求参数并根据参数选择操作
if(isset($_POST['action'])&&$_POST['action']!=""){
switch($_POST['action']){
case 'get_all_users': getAllUsers(); break;
default:
}
}
//处理请求:以JSON格式返回所有用户信息
function getAllUsers(){
$users = array(
array("userId"=>1,"userName"=>"Raysmond"),
array("userId"=>2,"userName"=>"雷建坤"),
array("userId"=>3,"userName"=>"Rita")
);
echo json_encode($users);
}
?> | true |
52c8ce0cf2437483aee6883b55e84f289a3b6920 | PHP | alserom/viber-php | /src/Collection/UserCollection.php | UTF-8 | 673 | 2.984375 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types=1);
namespace Alserom\Viber\Collection;
use Alserom\Viber\Entity\User;
/**
* Class UserCollection
* @package Alserom\Viber\Collection
* @author Alexander Romanov <contact@alserom.com>
*/
class UserCollection extends AbstractCollection
{
/**
* @param User $user
* @param User ...$users
*/
public function __construct(User $user, User ...$users)
{
$this->add($user);
foreach ($users as $u) {
$this->add($u);
}
}
/**
* @param User $user
* @return UserCollection
*/
public function add(User $user): self
{
$this->values[] = $user;
return $this;
}
}
| true |
ee4fc44ee96e16bb23480ca70059b1647858e773 | PHP | xdimedrolx/regis | /src/Regis/Application/Event/InspectionStarted.php | UTF-8 | 746 | 2.734375 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types=1);
namespace Regis\Application\Event;
use Regis\Application\Event;
use Regis\Domain\Entity;
use Regis\Domain\Model\Github\PullRequest;
class InspectionStarted implements Event
{
private $inspection;
private $pullRequest;
public function __construct(Entity\Inspection $inspection, PullRequest $pullRequest)
{
$this->inspection = $inspection;
$this->pullRequest = $pullRequest;
}
public function getInspection(): Entity\Inspection
{
return $this->inspection;
}
public function getPullRequest(): PullRequest
{
return $this->pullRequest;
}
public function getEventName(): string
{
return Event::INSPECTION_STARTED;
}
} | true |
f656a10943a1c852a307c738f1653b990280c66b | PHP | grrr-amsterdam/garp3 | /library/Garp/Util/Memory.php | UTF-8 | 1,102 | 2.953125 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
/**
* Garp_Util_Memory
* Shortcut to toggling memory.
*
* @package Garp_Util
* @author Harmen Janssen <harmen@grrr.nl>
*/
class Garp_Util_Memory {
/**
* Raises PHP's RAM limit for extensive operations.
* Takes its value from application.ini if not provided.
*
* @param int $mem In MBs.
* @return Void
*/
public function useHighMemory($mem = null) {
$ini = Zend_Registry::get('config');
if (empty($ini->app->highMemory)) {
return;
}
$highMemory = $ini->app->highMemory;
$currentMemoryLimit = $this->getCurrentMemoryLimit();
if (!empty($currentMemoryLimit)) {
$megs = (int)substr($currentMemoryLimit, 0, -1);
if ($megs < $highMemory) {
ini_set('memory_limit', $highMemory . 'M');
}
} else {
ini_set('memory_limit', $highMemory . 'M');
}
}
/**
* Return current ini setting memory_limit
*
* @return int
*/
public function getCurrentMemoryLimit() {
return ini_get('memory_limit');
}
}
| true |
2d8af63212e60b52b993cc094ea648afbf273396 | PHP | ruzampl/gdpr-bundle | /Serializer/Normalizer/IterableNormalizer.php | UTF-8 | 1,327 | 2.625 | 3 | [
"MIT"
] | permissive | <?php
/**
* This file is part of the GDPR bundle.
*
* @category Bundle
*
* @author SuperBrave <info@superbrave.nl>
* @copyright 2018 SuperBrave <info@superbrave.nl>
* @license https://github.com/superbrave/gdpr-bundle/blob/master/LICENSE MIT
*
* @see https://www.superbrave.nl/
*/
namespace Superbrave\GdprBundle\Serializer\Normalizer;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
/**
* Normalizes data if it's iterable by calling the normalizer chain.
*
* @author Jelle van Oosterbosch <jvo@superbrave.nl>
*/
class IterableNormalizer implements NormalizerInterface, NormalizerAwareInterface
{
use NormalizerAwareTrait;
/**
* {@inheritdoc}
*/
public function supportsNormalization($data, $format = null)
{
if (is_array($data) || $data instanceof \Traversable) {
return true;
}
return false;
}
/**
* {@inheritdoc}
*/
public function normalize($object, $format = null, array $context = [])
{
$normalizedData = [];
foreach ($object as $value) {
$normalizedData[] = $this->normalizer->normalize($value, $format, $context);
}
return $normalizedData;
}
}
| true |
db452b32b2d04e1bdb9e1a4e90c2cb03501fd450 | PHP | TelmaMora/ProyectoPersonal | /app/Repositories/UserRepository.php | UTF-8 | 955 | 2.578125 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: pathao
* Date: 8/19/18
* Time: 3:38 PM
*/
namespace app\Repositories;
use app\Models\Permission;
use app\Models\User;
use Carbon\Carbon;
class UserRepository extends BaseRepository
{
/**
* QueryRepository constructor.
*
*/
public function __construct(User $queries)
{
$this->model = $queries;
}
public function getAllUserWithPagination() {
return $this->model->paginate(env('PAGINATION_LIMIT',20));
}
public function getAllUsers() {
return $this->model->get();
}
public function findById($id) {
return $this->model->find($id);
}
public function saveUser($data) {
$data['created_at'] = Carbon::now();
unset($data['_token']);
unset($data['password_confirmation']);
$data['password'] = \Hash::make($data['password']);
return $this->model->insertGetId($data);
}
} | true |
6c20ea4388aa771621f74b7355d1dfc2e4b32410 | PHP | AlexDardy/projet_evolution | /pages/login.php | UTF-8 | 2,643 | 2.578125 | 3 | [] | no_license | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Application WEB</title>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<?php
include 'theme.php'
?>
<style type="text/css">
.form-signin {
width: 100%;
max-width: 330px;
padding: 15px;
margin: 0 auto;
}
</style>
</head>
<body>
<?php
session_start();
include 'navigation.php';
if (isset($_POST['username'])){
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
$bdd = new PDO('mysql:host=localhost;dbname=evolution;charset=utf8', 'root', '', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$requete = $bdd->prepare("SELECT utilisateurs.ID, utilisateurs.Mot_De_Passe, map_role.Nom
FROM `utilisateurs` INNER JOIN `map_role` ON utilisateurs.ID = map_role.ID
WHERE utilisateurs.ID='$username' and utilisateurs.Mot_De_Passe='".hash('sha256', $password)."'");
$requete->execute();
$data = array();
while($donnees = $requete->fetch()) {
array_push($data,$donnees['Nom']);
}
$requete->closeCursor();
print_r($data);
if(!empty($data)) {
if (in_array("Standard", $data)) {
$_SESSION['role'] = "Standard";
}
if (in_array("Administrateur", $data)) {
$_SESSION['role'] = "Administrateur";
}
echo "<script>window.location.href='index.php';</script>";
exit;
}else{
$message = "Le nom d'utilisateur ou le mot de passe est incorrect.";
}
}
?>
<div class="container mt-5">
<form class="form-signin" action="" method="post" name="login">
<h1 class="h3 mb-3 font-weight-normal">Connectez-vous</h1>
<div class="form-group">
<label for="username">Identifiant</label>
<input type="text" class="form-control" id="username" name="username">
</div>
<div class="form-group">
<label for="password">Mot de passe</label>
<input type="password" class="form-control" id="password" name="password">
</div>
<button type="submit" class="btn btn-lg blue-button btn-block">Se connecter</button>
</form>
</div>
</body>
</html> | true |
d34e10d9b66eb217e8ba24fd0f9ee6060c5ea1a2 | PHP | alicsmn/my_twiiter | /Model/Profile.php | UTF-8 | 1,184 | 2.765625 | 3 | [] | no_license | <?php
require_once ("User.php");
class Profile extends DB {
public function updatemail($updatemail, $mail){
$this->query('UPDATE user SET mail= :updatemail WHERE mail = :mail');
$this->bind(':mail', $mail);
$this->bind(':updatemail', $updatemail);
$this->execute();
}
public function checkmail($updatemail){
$this->query("SELECT COUNT(mail) AS nb_mail FROM user WHERE mail = :updatemail");
$this->bind(':updatemail', $updatemail);
$this->execute();
$result = $this->fetch();
if ($result['nb_mail'] != '0')
{
echo "Email déjà enregistré! Veuillez en choisir un autre ";
return false;
}else{
return true;
}
}
public function updatepassword($updatepassword, $mail){
$this->query('UPDATE user SET password = :updatepassword WHERE mail = :mail');
$this->bind(':updatepassword', $updatepassword);
$this->bind(':mail', $mail);
$this->execute();
}
// public function addAvatar($avatar, $mail){
// $this->query("UPDATE user SET idUrlAvatar = :avatar WHERE mail = :mail");
// $this->bind(':idUrlAvatar', $avatar);
// $this->bind(':mail', $mail);
// $this->execute();
// }
}
?> | true |
e1a53852b6fb12ab7d1a3cde154fa5cc1009c222 | PHP | Damanotra/latihan | /application/models/Activities_model.php | UTF-8 | 2,857 | 2.578125 | 3 | [] | no_license | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Activities_model extends CI_Model {
private $_table = "activities";
public $id;
public $name;
public $email;
public $barang;
public $link_gambar;
public $komentar;
public function rules()
{
return [
['field'=>'name',
'label'=>'Name',
'rules'=>'required'],
['field'=>'email',
'label'=>'Email',
'rules'=>'required'],
['field'=>'barang',
'label'=>'Barang',
'rules'=>'required'],
['field'=>'link_gambar',
'label'=>'gambar'],
['field'=>'komentar',
'label'=>'Comment'],
];
# code...
}
public function getAll()
{
return $this->db->get($this->_table)->result();
# code...
}
public function getById($id)
{
return $this->db->get_where($this->_table,["id"=>$id])->row();
# code...
}
public function save()
{
$post = $this->input->post();
$this->name = $post['name'];
$this->email = $post['email'];
$this->barang = $post['barang'];
$this->link_gambar = $this->_uploadImage();
$this->komentar = $post['comment'];
$this->db->insert($this->_table,$this);
# code...
}
public function update()
{
$post = $this->input->post();
if (!empty($_FILES["image"]["name"])) {
$data = array(
'name' => $post['name'],
'email' => $post['email'],
'link_gambar' =>$this->_uploadImage(),
'barang' => $post['barang'],
'komentar' => $post['comment']
);
} else {
$data = array(
'name' => $post['name'],
'email' => $post['email'],
'barang' => $post['barang'],
'link_gambar'=>$post['old_image'],
'komentar' => $post['comment']
);
}
$this->db->update($this->_table,$data,array('id'=>$post['id']));
# code...
}
public function delete($id)
{
return $this->db->delete($this->_table,array('id'=>$id));
# code...
}
private function _uploadImage()
{
$config['upload_path'] = './upload/activity/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['file_name'] = md5($this->barang.time());
$config['overwrite'] = true;
$config['max_size'] = 1024; // 1MB
//$config['max_width'] = 1024;
//$config['max_height'] = 768;
$this->load->library('upload', $config);
if($this->upload->do_upload('image')) {
return $this->upload->data("file_name");
}
return "default.jpg";
# code...
}
private function _deleteImage($value='')
{
$activity = $this->getById($id);
if ($activity->link_gambar != "default.jpg") {
$filename = explode(".", $activity->link_gambar)[0];
return array_map('unlink', glob(FCPATH."upload/activity/$filename.*"));
}
# code...
}
}
/* End of file Activity_model.php */
/* Location: ./application/models/Activity_model.php */ | true |
da40cdd3a6394be4b6323455f2a70b8892c9e2a7 | PHP | inpresif/laravel-casts | /src/CancelButton.php | UTF-8 | 658 | 2.6875 | 3 | [
"MIT"
] | permissive | <?php namespace GeneaLabs\LaravelCasts;
class CancelButton extends Button
{
public function __construct(string $returnUrl)
{
parent::__construct('');
$this->classes = 'btn btn-cancel pull-right';
$this->returnUrl = $returnUrl;
}
public function getTypeAttribute() : string
{
return 'a';
}
protected function renderBaseControl() : string
{
return '<a href="' . ($this->returnUrl ?: url()->previous()) .
'" class="' . $this->options['class'] . '">Cancel</a>';
}
public function getHtmlAttribute() : string
{
return $this->renderBaseControl();
}
}
| true |
184ad390021a1fd3d8a29ffe01362e45f10bd46f | PHP | ergebnis/phpunit-slow-test-detector | /src/MaximumCount.php | UTF-8 | 818 | 2.84375 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types=1);
/**
* Copyright (c) 2021-2023 Andreas Möller
*
* For the full copyright and license information, please view
* the LICENSE.md file that was distributed with this source code.
*
* @see https://github.com/ergebnis/phpunit-slow-test-detector
*/
namespace Ergebnis\PHPUnit\SlowTestDetector;
/**
* @internal
*
* @psalm-immutable
*/
final class MaximumCount
{
private function __construct(private readonly int $value)
{
}
/**
* @throws Exception\InvalidMaximumCount
*/
public static function fromInt(int $value): self
{
if (0 >= $value) {
throw Exception\InvalidMaximumCount::notGreaterThanZero($value);
}
return new self($value);
}
public function toInt(): int
{
return $this->value;
}
}
| true |
bee49d01e328f192973130a4ee54643c86d671e7 | PHP | fangchaogang/kam-php | /src/Request/Friend/FriendListRequest.php | UTF-8 | 648 | 2.5625 | 3 | [] | no_license | <?php
namespace Kam\Request\Friend;
use Kam\Request\BaseRequest;
use Kam\Response\Response;
/**
* Class FriendListRequest
* @package Kz\Robot\Request
* 好友列表
*/
class FriendListRequest extends BaseRequest
{
const PATH = '/friend/list';
public function request()
{
return new Response(parent::request());
}
/**
* @param int $isRefresh
*/
public function setIsRefresh(int $isRefresh)
{
$this->is_refresh = $isRefresh;
}
/**
* @param int $outRawData
*/
public function setOutRawdata(int $outRawData = 0)
{
$this->out_rawdata = $outRawData;
}
} | true |
17605e07cc0dea53993081ed30c5c3f20b9f3681 | PHP | M-Component/Crontabe | /app/library/Task/ConsoleApp.php | UTF-8 | 3,287 | 2.765625 | 3 | [] | no_license | <?php
namespace Task;
use Phalcon\CLI\Console;
class ConsoleApp extends Console
{
private $options = "hdrmp:s:l:c:";
private $longopts = [
"help",
"daemon",
"reload",
"config:",
"queue:",
"cron:",
"checktime:",
];
private $help = <<<HELP
帮助信息:
Usage: /path/to/php task.php [options] -- [args...]
-h [--help] 显示帮助信息
-s start 启动进程
-s stop 停止进程
-s restart 重启进程
-d [--daemon] 是否后台运行
-r [--reload] 重新载入配置文件
--queue=[true|false] 执行队列
--cron=[true|false] 执行计划任务
--checktime=[true|false] 精确对时,仅对Crontab有效(精确对时,程序则会延时到分钟开始0秒启动)
HELP;
public function __construct()
{
$this->config = $this->di->getConfig();
Process::$pid_path = $this->config->application->logDir;
}
/**
* 2.运行入口
*/
public function run()
{
$opt = getopt($this->options, $this->longopts);// 获取参数
$this->params_help($opt);
$this->params_daemon($opt);
$this->params_queue($opt);
$this->params_cron($opt);
$this->params_checktime($opt);
$this->params_s($opt); // 开启登录
}
/**
* 解析帮助参数
* @param $opt
*/
public function params_help($opt)
{
if (empty($opt) || isset($opt["h"]) || isset($opt["help"])) {
die($this->help);
}
}
/**
* 解析运行模式参数
* @param $opt
*/
public function params_daemon($opt)
{
if (isset($opt["d"]) || isset($opt["daemon"])) {
Process::$daemon = true;
}
}
/**
* 解析精确对时参数
* @param $opt
*/
public function params_checktime($opt)
{
if (isset($opt["checktime"]) && $opt["checktime"] == "false") {
Process::$checktime = false;
}
}
/**
* 解析启动模式参数
* @param $opt
*/
public function params_s($opt)
{
//判断传入了s参数但是值,则提示错误 public/start_cron.sh文件
$allow = array("start", "stop", "restart");
if ((isset($opt["s"]) && !$opt["s"]) || (isset($opt["s"]) && !in_array($opt["s"],$allow))) {
Output::stdout("Please run: path/to/php task.php -s [start|stop|restart]");
}
if (isset($opt["s"]) && in_array($opt["s"], $allow)) {
switch ($opt["s"]) {
case "start":
Process::start();
break;
case "stop":
Process::stop();
break;
case "restart":
Process::restart();
break;
}
}
}
/**
* queue参数
*
* @param $opt
*/
public function params_queue($opt)
{
if (isset($opt["queue"])) {
Process::$queue = true;
}
}
public function params_cron($opt)
{
if (isset($opt["cron"])) {
Process::$cron = true;
}
}
}
| true |
46aa88d455e39d0b90045d71c669e6192484609d | PHP | samokpe2/School-Portal | /pwordrset3.php | UTF-8 | 6,224 | 2.78125 | 3 | [] | no_license | <?php require_once("includes/session.php");?>
<?php require_once("includes/connection.php");?>
<?php require_once("includes/functions.php");?>
<?php //confirm_logged_in_management(); ?>
<?php include("includes/header.php"); ?>
<?php
include_once("includes/form_functions.php");
// START FORM PROCESSING
if(isset($_POST['submit'])){ // Form has been submitted
// initialize an array to hold our errors
$errors = array();
// perform validations on the form data
$required_fields = array('password1', 'password2');
$errors = array_merge($errors, check_required_fields($required_fields));
$fields_with_lengths = array('password1' => 15, 'password2' => 15);
$errors = array_merge($errors, check_max_field_lengths($fields_with_lengths));
// clean up the form data before putting it in the database
$username = $_GET['username'];
$password1 = trim(mysql_prep($_POST['password1']));
$password2 = trim(mysql_prep($_POST['password2']));
$table_users = 'users_student';
// Database submission only proceeds if there were NO errors.
if(empty($errors)){
//confirm password
if($password1 == $password2){
$hashed_password = sha1($password1);
$query = "SELECT * ";
$query .= "FROM users_student ";
$query .= "WHERE username = '$username' LIMIT 1";
$students = mysql_query($query, $connection);
confirm_query($students);
while ($student = mysql_fetch_array($students)) {
$regno = $student['username'];
$qry = "UPDATE users_student SET hashed_password = '$hashed_password' WHERE username = '$regno' ";
$result1 = mysql_query($qry, $connection);
confirm_query($result1);
}
// test to see if the update occurred
if($result1){
// success
?>
<br/><br/><br/><br/><br/><br/>
<div class="col-md-4">
</div>
<article class="col-md-5">
<div class="panel panel-default">
<div class="panel-heading">
<h4>Success !!!</h4>
</div>
<div class="panel-body">
<form action="login_students.php" method="post">
<table>
<tr>
<td><?php echo "Your password reset was successfully"; ?></td>
</tr>
<tr>
<td><?php echo "You can login with your new password"; ?></td>
</tr>
<br/>
<tr>
<td style=text-align:right><br/><input type="submit" name="submit" value="OK " /></td>
</tr>
</table>
</form>
</div>
</div>
</article>
<div class="col-md-3">
</div>
<?php
} else{
// Failed
$message = "The user could not be created.";
$message .= "<br/>" . mysql_error();
}
} else { // confirm password
?>
<br/><br/><br/><br/><br/><br/><br/><br/>
<div class="col-md-4">
</div>
<article class="col-md-5">
<div class="panel panel-default">
<div class="panel-heading">
<h4>Information !!!</h4>
</div>
<div class="panel-body">
<form action="pwordrset1.php" method="post">
<table>
<tr>
<td><?php echo "Password mismatch !"; ?></td>
</tr>
<tr>
<td style=text-align:right><br/><input type="submit" name="submit" value="Try again " /></td>
</tr>
</table>
</form>
</div>
</div>
</article>
<div class="col-md-3">
</div>
<?php
} // ends confirm password
} else { // if(empty($errors))
if(count($errors) == 1){
$message = "There was 1 error in the form.";
} else {
$message = "There were " . count($errors) . " errors in the form.";
}
?>
<br/><br/><br/><br/><br/><br/><br/><br/>
<div class="col-md-4">
</div>
<article class="col-md-5">
<div class="panel panel-default">
<div class="panel-heading">
<h4>Information !!!</h4>
</div>
<div class="panel-body">
<form action="pwordrset1.php" method="post">
<table>
<tr>
<td><?php echo "<p class=\"message\">" . $message . "</p>"; ?></td>
</tr>
<tr>
<td><?php echo "<p> You have to complete the form!</p>"; ?></td>
</tr>
<tr>
<td style=text-align:right><br/><input type="submit" name="submit" value="Try again " /></td>
</tr>
</table>
</form>
</div>
</div>
</article>
<div class="col-md-3">
</div>
<?php
} // ends if(empty($errors))
} else{ //Form has not been submited
?>
<br/><br/><br/><br/><br/><br/><br/><br/>
<div class="col-md-4">
</div>
<article class="col-md-5">
<div class="panel panel-default">
<div class="panel-heading">
<h4>Illegal Entry</h4>
</div>
<div class="panel-body">
<form action="index.php" method="post">
<table>
<tr>
<td>Sorry, you entered into this environment illegally !!!: </td>
</tr>
<tr>
<td style=text-align:right><br/><input type="submit" name="submit" value="OK " /></td>
</tr>
</table>
</form>
</div>
</div>
</article>
<div class="col-md-3">
</div>
<?php
} // ends if(isset($_POST[])) i.e Form has not been submitted
?>
<?php include("includes/footer.php"); ?> | true |
cff2d262b8faa682629563f1aef21fa99c0255f8 | PHP | ChristopherMcKay/homemade-blog | /blog/uploadImgProc.php | UTF-8 | 3,716 | 2.96875 | 3 | [] | no_license | <?php
// image upload proc runs on click of Upload button in Upload Img form in blogCMS.php
session_start();
if($_SESSION['user'] == false) { // not logged in
header('HTTP/1.0 403 Forbidden'); // block
header('Location: blogCMS.php'); // redirect
} else { // are logged in
require_once('../conn/connBlogs.php');
// get the IDmbr from the session
$IDmbr = $_SESSION['IDmbr'];
$user = $_SESSION['user'];
// do the upload:
// 1.) get the data of the file to upload?
$imgAlt = $_POST['img-alt'];
$imgDesc = $_POST['img-desc'];
$imgGallery = $_POST['img-gallery'];
// the multi-part part--the image itself
$fileName = $_FILES['fileToUpload']['name']; // cat.jpg
$fileTemp = $_FILES['fileToUpload']['tmp_name']; // cat.jpgtype
$fileSize = $_FILES['fileToUpload']['size']; // in Bytes
$filePath = '../members/' . $user . '/images/' . $fileName;
$fileType = pathinfo($fileName, PATHINFO_EXTENSION);
// 2.) run a series of tests to see if the image is good to go
// a Boolean-ish var to flip from good (1) to bad (0) if any test fails
$ok = 1;
$msg = "";
// A.) is the image too big? Our limit is 5 MB
if($fileSize > 5*1000*1000) { // 5 million bytes == 5 MB
$ok = 0; // image is too big, so flip the "Boolean"
$msg = "Whoa! Image file size exceeds 5.12MB Max (5120KB)! Your file is " . round($fileSize/1024) . 'KB';
}
// B.) is the file in fact an image..? Image type begins w 'image/'
if($fileType != 'jpg' && $fileType != 'jpeg' && $fileType != 'gif' && $fileType != 'svg' && $fileType != 'png') {
$ok = 0; // image is too big, so flip the "Boolean"
$msg = "Hey! What gives! That's not even an image you're trying to upload!";
}
// C.) is the image already in the user's folder (already been uploaded)
if(file_exists($filePath)) {
$ok = 0; // image is too big, so flip the "Boolean"
$msg = "Oops! That image has already been uploaded to the " . $user . " folder!";
}
// D.) is the image file name already in the database for this user?
$query_img = "SELECT imgName FROM images
WHERE imgName = '$fileName' AND mbrID = '$IDmbr'";
$result_img = mysqli_query($conn, $query_img);
if(mysqli_num_rows($result_img) > 0) { // or mysqli_affected_rows($conn)
$ok = 0; // image is already in the database
$msg = "That's weird! The file name is already in the database, even though the file itself isn't in your folder yet!";
}
if($ok == 1) { // if ok is still 1 after all those tests, save and upload already!!!
// 3.) save img file name to DB
$query = "INSERT INTO images(mbrID, imgName, imgAlt, imgDesc, imgGall) VALUES('$IDmbr', '$fileName', '$imgAlt', '$imgDesc', '$imgGall')";
mysqli_query($conn, $query);
// 4.) upload the image itself to the user's folder
// this method does the actual upload
// path to upload image file into:
move_uploaded_file($fileTemp, $filePath);
$msg = "<h1>Congrats! Image " . $fileName . " uploaded to<br/>" . $filePath . "<br/>File size: " . ($fileSize/1000) . "KB</h1>";
} // end if $ok still == 1
} // end big if-else
echo '<h1 style="margin:2rem 0 0 2rem">' . $msg . '</h1>';
header("Refresh: 3; url=blogCMS.php", true, 303);
?> | true |
5a15be85896adbd7bef7035311fd194ad34bdfd2 | PHP | MaciejKut/PHP-Repos | /PHP-A2-complex-basis/16.php | UTF-8 | 291 | 3.71875 | 4 | [] | no_license | <?php
function powerUp($a, $n) {
$result = 1;
if ($n == 0) {
return 1;
} elseif ($n == 1) {
return $a;
} else {
for ($i = 1; $i <= $n; $i++) {
$result = $a * $result;
}
return $result;
}
}
var_dump(powerUp(2, 1));
| true |
4d1e36e41f886e86cf1238426246f8f3977bd2ec | PHP | josejames/fantastic-tribble | /controller/obtentours.php | UTF-8 | 1,326 | 2.78125 | 3 | [] | no_license | <?php
/* Object Oriented */
// obtenTours.php
$texto = "ERROR: ";
//archivo de configuracion
include '../controller/config.php';
$mysqli = new mysqli($hostdb, $usuariodb, $clavedb, $nombredb);
//$conn = mysql_connect($hostdb, $usuariodb, $clavedb);
/* comprobar la conexión */
if (mysqli_connect_errno()) {
echo $texto . mysqli_connect_error();
/**printf("Falló la conexión: %s\n", mysqli_connect_error());**/
exit();
}
$consulta = "SELECT id_tour, nombre_tour, numero_tour FROM tours ORDER BY numero_tour ASC";
if ($resultado = $mysqli->query($consulta)) {
/* obtener el array de objetos */
while ($fila = $resultado->fetch_row()) {
//printf ("%s (%s)\n", $fila[0], $fila[1]);
if ($fila[2] <= 9) {
$fila[2] = "0".$fila[2];
}
echo "<tr id=".$fila[0].">\n";
echo "<td>".$fila[2]."</td>\n";
echo "<td>".$fila[1]."</td>\n";
echo "<tr>\n";
}
/* liberar el conjunto de resultados */
$resultado->close();
}
/* cerrar la conexión */
$mysqli->close();
?> | true |
0b98fd1bb1c1920038d6e24a0620f216bd40994b | PHP | hyejinpark-dev/phpwithlaravel | /routes/web.php | UTF-8 | 1,330 | 2.625 | 3 | [
"MIT"
] | permissive | <?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
/*
Route::get('/', function () {
return view('welcome');
});
Route::get('/{foo}', function ($foo){
return $foo;
});
Route::pattern('foo', '[0-9a-zA-Z]{3}');
Route::get('/{foo?}', function ($foo='bar'){
return $foo;
})->where('foo','[0-9a-zA-Z]{3}');
*/
/* #리다이렉트
Route::get('/',[
'as' => 'home',
function () {
return 'home page';
}
]);
Route::get('/home', function() {
return redirection(route('home'));
});
*/
/*
Route::get('/', function () {
return view('errors.404');
});
*/
/* #데이터 바인딩
Route::get('/', function () {
return view('welcome')->with('name','Danhee');
});
*/
/*# 여러개 데이터 바인딩
Route::get('/', function () {
return view('welcome')->with([
'name' => 'danhee',
'greeting' => 'hello?',
]);
});
*/
#view() 함수 이용한 바인딩
Route::get('/', function() {
return view('welcome',[
'name' => 'danhee1',
'greeting' => '안녕하세요',
]);
}); | true |
8c411596dd2621d2c78ce8fe41e94d439729c925 | PHP | saddanbimanagantara/PWD-WEEK-1 | /prosesupload.php | UTF-8 | 812 | 2.84375 | 3 | [] | no_license | <?php
//ambil lokasi file diambil diupload
$lokasifile = $_FILES["fileupload"]["tmp_name"];
//ambil nama file dari file yang diupload
$nama_file = $_FILES["fileupload"]["name"];
//ambil data dari deskripsi
$deskripsi = $_POST["deskripsi"];
//set direktori untuk menyimpan file yang diupload beserta dengan nama file pada akhir baris
$direktori = "G:/APP/XAMPP/htdocs/PRAKTIKUM/PWD/WEEK 1/$nama_file";
// cek jika data berhasil dipindah dengan pengecekan fungsi move_upload_file dengan parameter lokasifile asal kelokasi file tujuan, jika file berhasil diupload/pindah maka munculkan pesan nama file dan deskripsi
if(move_uploaded_file($lokasifile, $direktori))
{
echo "Nama File : <b>$nama_file</b>";
echo "Deskripsi File : $deskripsi";
}else{
echo "File Gagal Upload";
}
?> | true |
199fab61c9646dcf99167d07ee27c3251c8e4afb | PHP | morefreeze/11rank | /11rank.php | UTF-8 | 8,260 | 2.734375 | 3 | [] | no_license | <?php
require_once ("DbTools.class.php");
//getCookie();
//$user_info = getUserInfoFrom11('还我K神');
//var_dump($user_info);
//updateUserInfo($user_info);
//updateAllUser();
//get11LastUpdateTime();
// user_info
// id, uname, score, rank, win, lose, update_time
// add a user watched
function watchNewUser($uid, $new_user){
$conn = DbTools::getDBConnect('dota');
$time = time();
$res = $conn->query("SELECT id FROM dota.user_info WHERE uname LIKE '".
$conn->escape_string($new_user)."'");
if (empty($res)){
$user_info = getUserInfoFrom11($new_user);
$ret = updateUserInfo($user_info);
$rank_id = $ret['rank_id'];
}
else{
$rank_id = $res[0]['id'];
}
$res = $conn->query("SELECT ulist FROM dota.user WHERE uid = $uid");
$ulist = array();
if ($res[0]['ulist'] != ""){
$ulist = explode(',', $res[0]['ulist']);
}
if (!in_array($rank_id, $ulist)){
$ulist[] = $rank_id;
$conn->query("UPDATE dota.user SET ulist = '".implode(',', $ulist)."', ".
"update_time = $time WHERE uid = $uid");
}
else{
return false;
}
return true;
}
// update all user 11 score and info
function updateAllUser(){
$conn = DbTools::getDBConnect('dota');
$time = get11LastUpdateTime();
do{
$res = $conn->query("SELECT uname FROM dota.user_info WHERE update_time < $time ".
"LIMIT 100");
if (false === $res){
return false;
}
if (empty($res)){
break;
}
foreach ($res as $user){
$user_info = getUserInfoFrom11($user['uname']);
$ret = updateUserInfo($user_info);
}
//break;
}while(1);
return true;
}
// update A user info with 11 rank (throght getUserInfoFrom11)
// return array('rank_id', 'trend')
function updateUserInfo($user_info){
$conn = DbTools::getDBConnect('dota');
$res = $conn->query("SELECT id,score,rank FROM dota.user_info ".
"WHERE uname LIKE '".$conn->escape_string($user_info['user'])."'");
if (false === $res){
}
extract($user_info);
$rank = $rank == "-" ? 0 : $rank;
$time = time();
// update
if (!empty($res)){
if ($score > $res[0]['score']){
$trend = 1;
}
elseif($score < $res[0]['score']){
$trend = -1;
}
else{
$trend = 0;
}
$conn->query("UPDATE dota.user_info SET score = $score, rank = $rank,".
"win = $win, lose = $lose, user_url = '".$conn->escape_string($user_url)."', ".
"trend = $trend, update_time = $time WHERE id = ". $res[0]['id']);
$rank_id = $res[0]['id'];
}
// insert
else{
$trend = 0;
$sql = "INSERT INTO dota.user_info SET uname = '".$conn->escape_string($user)."', score = $score,".
"rank = $rank, win = $win, lose = $lose, user_url = '".$conn->escape_string($user_url)."', ".
"trend = $trend, update_time = $time";
//var_dump($sql);
$conn->query($sql);
$rank_id = $conn->insert_id;
}
$ret = array('rank_id' => $rank_id,
'score' => $score,
'rank' => $rank,
'win' => $win,
'lose' => $lose,
'trend' => $trend);
return $ret;
}
// get 11 rank from db with local uid
function getUserInfoFromDb($id){
$conn = DbTools::getDBConnect('dota');
if (isset($trend)){
$sql_part = " AND trend = $trend";
}
else{
$sql_part = "";
}
$res = $conn->query("SELECT id,uname,score,rank,win,lose,trend FROM dota.user_info ".
"WHERE id = $id".$sql_part);
if (false === $res){
}
return $res[0];
}
// get 11 rank with A user name
function getUserInfoFrom11($user = 'morefreeze'){
$url = "http://i.5211game.com/rank/search?t=10001&n=$user&login=1";
//$url = "http://www.baidu.com/s?wd=fdsa";
$rank_url = parse_url($url);
//var_dump($rank_url);
$fp = fsockopen($rank_url['host'], 80, $errno, $errstr, 10);
if (!$fp) {
echo "$errstr ($errno)\n";
} else {
$html = "GET ".$rank_url['path']."?".$rank_url['query']." HTTP/1.1\r\n";
$html .= "Host: ".$rank_url['host']."\r\n";
$html .= "Connection: keep-alive\r\n";
$html .= "User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4\r\n";
$html .= "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n";
$html .= "Accept-Encoding: gzip,deflate,sdch\r\n";
$html .= "Accept-Language: en-US,en;q=0.8\r\n";
$html .= "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3\r\n";
//$html .= "Cookie: __utma=1.1935785162.1354122597.1354122597.1354122597.1; __utmc=1; __utmz=1.1354122597.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided); ASP.NET_SessionId=ws0iqjlmhqeexua5fzpw5fee; AsCommunity=D4E99848E3A8B121061280C1C94E9ADCA39D3EF38585703E25C66BB933AC7719A15735415DF3DA58E6F45768F119093528CE9343BF200C2FCD44E3648DFF5DAE99A5F18C75CD36CF09736E7758FF5BFE1C8C3B9BF00972306AA2261EA1D743BC14816FA78A622D3748530BCD4B943F436DEF79427E4DFA3FFC7AE62308366795DC76CC32517A0E5022A424A348BA3607387EA3BD527811DF4227390611BB47E3; lastid=3574433; oldid=3563005; Hm_lvt_f42223235f19a6d82fd2f36f5d7daaab=1354214627,1354299566,1354299621,1354299920; Hm_lpvt_f42223235f19a6d82fd2f36f5d7daaab=1354327754\r\n";
$html .= "\r\n";
fwrite($fp, $html);
$i = 0;
$res = "";
while (!feof($fp)) {
$res .= fgets($fp, 1024);
++$i;
if ($i > 10) break;
}
preg_match("/HTTP\/1.\d (\d{3,3})/", $res, $out);
if ($out[1] != '200'){
var_dump($out[1]);
exit;
}
while (!feof($fp)) {
$res .= fgets($fp, 1024);
++$i;
if ($i > 270) break;
}
fclose($fp);
//var_dump($res);
preg_match("/td\s+class=\"con1\">\s*<strong[^>]*>([\-0-9])[^<]*<\/\s*strong/s", $res, $out);
//preg_match("/div\s+class=\"user\">\s*<a.*>(\w+)\s*<\/a>/", $res, $out);
$ret['rank'] = $out[1];
preg_match("/div\s+class=\"user\">.+?href=\"(.+)\">(.+?)\s+<\/a>/s", $res, $out);
$ret['user_url'] = "http://".$rank_url['host']."/".$out[1];
$ret['user'] = $out[2];
preg_match("/span\s+class=\"red\"[^>]*>(\d+)/", $res, $out);
$ret['score'] = $out[1];
preg_match("/span\s+class=\"orange\"[^>]*>(\d+)/", $res, $out);
$ret['win'] = $out[1];
preg_match("/span\s+class=\"gray\"[^>]>(\d+)/", $res, $out);
$ret['lose'] = $out[1];
preg_match("/td\s*class=\"con6\">([0-9.%]+)/", $res, $out);
$ret['win_rate'] = $out[1];
//var_dump($ret);
return $ret;
}
return false;
}
function get11LastUpdateTime(){
$h = date('H');
if ($h < 6){
$ret = strtotime('yesterday') + 6 * 60 * 60;
}
else{
$ret = strtotime('today') + 6 * 60 * 60;
}
return $ret;
}
function getCookie(){
$url = "http://passport.5211game.com/t/Login.aspx";
$login_url = parse_url($url);
$fp = fsockopen($login_url['host'], 80, $errno, $errstr, 10);
if (!fp){
echo "$errstr ($errno)\n";
}else{
$html = "POST ".$login_url['path']." HTTP/1.1\r\n";
$html .= "Host: ".$login_url['host']."\r\n";
$html .= "Proxy-Connection: keep-alive\r\n";
$html .= "Cache-Control: max-age=0\r\n";
$html .= "Origin: \r\n";
$html .= "http://".$login_url['host']."\r\n";
$html .= "User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4\r\n";
$html .= "Content-Type: application/x-www-form-urlencoded\r\n";
$html .= "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n";
$html .= "Referer: http://passport.5211game.com/t/Login.aspx\r\n";
$html .= "Accept-Encoding: gzip,deflate,sdch\r\n";
$html .= "Accept-Language: en-US,en;q=0.8\r\n";
$html .= "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3\r\n";
$html .= "Cookie: __utma=1.1935785162.1354122597.1354122597.1354122597.1; __utmc=1; __utmz=1.1354122597.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided); ASP.NET_SessionId=jya1z245jcis0ynfwthxifak\r\n";
$post_arr = array('txtUser' => 'iknow963', 'txtPassWord' => 123456, 'butLogin' => '怬',
'__VIEWSTATE' => '/wEPDwULLTEyMzI3ODI2ODBkGAEFHl9fQ29udHJvbHNSZXF1aXJlUG9zdEJhY2tLZXlfXxYBBQxVc2VyQ2hlY2tCb3ihhGZuvwu91lnQxEfvvglIxoUV3w==',
'__EVENTVALIDATION' => '/wEWBQLLvu3fCALB2tiHDgK1qbSWCwL07qXZBgLmwdLFDS8b1h9eACycstvQytmO42OInEvi',);
$post = '';
foreach ($post_arr as $key => $val){
if ($post != ''){
$post .= "&";
}
$post .= $key . "=" . $val;
$length = strlen($post);
}
$html .= "Content-Length: $length\r\n";
$html .= "$post\r\n\r\n";
fwrite($fp, $html);
$i = 0;
$res = "";
while (!feof($fp)) {
$res .= fgets($fp, 1024);
++$i;
if ($i > 1) break;
}
fclose($fp);
}
}
| true |
b8d17016b7fb757470fb28d83da9cd9de8fec58e | PHP | codingandcommunity/Learn-With-Coding-And-Community | /moodle/admin/tool/usertours/classes/cache.php | UTF-8 | 4,452 | 2.59375 | 3 | [
"GPL-1.0-or-later",
"GPL-3.0-only",
"GPL-3.0-or-later",
"MIT"
] | permissive | <?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle 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.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Cache manager.
*
* @package tool_usertours
* @copyright 2016 Andrew Nicols <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace tool_usertours;
defined('MOODLE_INTERNAL') || die();
/**
* Cache manager.
*
* @copyright 2016 Andrew Nicols <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class cache {
/**
* @var CACHENAME_TOUR The name of the cache used for storing tours.
*/
const CACHENAME_TOUR = 'tourdata';
/**
* @var CACHEKEY_TOUR The name of the key used for storing tours.
*/
const CACHEKEY_TOUR = 'tours';
/**
* @var CACHENAME_STEP The name of the cache used for storing steps.
*/
const CACHENAME_STEP = 'stepdata';
/**
* Fetch all enabled tours.
*/
public static function get_enabled_tourdata() {
global $DB;
$cache = \cache::make('tool_usertours', self::CACHENAME_TOUR);
$data = $cache->get(self::CACHEKEY_TOUR);
if ($data === false) {
$sql = <<<EOF
SELECT t.*
FROM {tool_usertours_tours} t
WHERE t.enabled = 1
AND t.id IN (SELECT s.tourid FROM {tool_usertours_steps} s GROUP BY s.tourid)
ORDER BY t.sortorder ASC
EOF;
$data = $DB->get_records_sql($sql);
$cache->set('tours', $data);
}
return $data;
}
/**
* Fetch all enabled tours matching the specified target.
*
* @param moodle_url $targetmatch The URL to match.
*/
public static function get_matching_tourdata(\moodle_url $targetmatch) {
$tours = self::get_enabled_tourdata();
// Attempt to determine whether this is the front page.
// This is a special case because the frontpage uses a shortened page path making it difficult to detect exactly.
$isfrontpage = $targetmatch->compare(new \moodle_url('/'), URL_MATCH_BASE);
$target = $targetmatch->out_as_local_url();
return array_filter($tours, function($tour) use ($isfrontpage, $target) {
if ($isfrontpage && $tour->pathmatch === 'FRONTPAGE') {
return true;
}
$pattern = preg_quote($tour->pathmatch, '@');
$pattern = str_replace('%', '.*', $pattern);
return !!preg_match("@{$pattern}@", $target);
});
}
/**
* Notify of changes to any tour to clear the tour cache.
*/
public static function notify_tour_change() {
$cache = \cache::make('tool_usertours', self::CACHENAME_TOUR);
$cache->delete(self::CACHEKEY_TOUR);
}
/**
* Fetch the tour data for the specified tour.
*
* @param int $tourid The ID of the tour to fetch steps for
*/
public static function get_stepdata($tourid) {
global $DB;
$cache = \cache::make('tool_usertours', self::CACHENAME_STEP);
$data = $cache->get($tourid);
if ($data === false) {
$sql = <<<EOF
SELECT s.*
FROM {tool_usertours_steps} s
WHERE s.tourid = :tourid
ORDER BY s.sortorder ASC
EOF;
$data = $DB->get_records_sql($sql, ['tourid' => $tourid]);
$cache->set($tourid, $data);
}
return $data;
}
/**
* Notify of changes to any step to clear the step cache for that tour.
*
* @param int $tourid The ID of the tour to clear the step cache for
*/
public static function notify_step_change($tourid) {
$cache = \cache::make('tool_usertours', self::CACHENAME_STEP);
$cache->delete($tourid);
}
}
| true |
9d261d637fb0df135ca80d3ebb05dd04f65f8599 | PHP | virgo27/my_work | /lectures/2018_01_27/re_04.php | UTF-8 | 1,367 | 2.546875 | 3 | [] | no_license | <?php
empty re
$reg = "//";
$reg = "/xyz/";
xyz
xyz 123 dsdsjh
xyzsagsah
123 xyz 123
123xyz123dhjd
123fhjgxyz
carrot ^
$reg = "/^xyz/";
xyz
xyz 123 dsdsjh
xyzsagsah
$reg = "/xyz$/";
xyz
123fhjgxyz
$reg = "/^xyz$/";
xyz
$reg = "/^xyza?$/";
xyz
xyza
$reg = "/^xyza*$/";
xyz
xyza
xyzaa
xyzaaaa
xyzaaaaaaaaaaaaaaaaaaaaaa
$reg = "/^xyza+$/";
xyza
xyzaa
xyzaaaa
xyzaaaaaaaaaaaaaaaaaaaaaa
$reg = "/^xyza{2}$/";
xyzaa
$reg = "/^xyza{2,4}$/";
xyzaa
xyzaaa
xyzaaaa
$reg = "/^xyz[10,]$/";
xyz1
xyz0
xyz,
$reg = "/^xyz[0-9a-dA-D\-\?]\?$/";
only alphabtes, atleast 1 character, first letter capital, remianing small
$reg = "/^[A-Z][a-z]*$/";
only alphabtes, atleast 1 character, capital/small all alowed
$reg = "/^[A-Za-z][A-Za-z]*$/";
$reg = "/^[A-Za-z]+$/";
$reg = "/^[a-z]+$/i";
starts with alphabet, contain only alphabtes and digits, min 6 max 20
capital small all alowed
$reg = "/^[a-z][a-z0-9]{5,19}$/i";
starts with alphabet, contain only alphabtes and digits, min 6 max 16
capital small all alowed
$reg = "/^[a-z][a-z0-9]{5,15}$/i";
1-111-1111111
11-111-1111111
111-111-1111111
1111-111-1111111
$reg = "/^[0-9]{1,4}\-[0-9][0-9][0-9]\-[0-9][0-9][0-9][0-9][0-9][0-9][0-9]$/";
$reg = "/^[0-9]{1,4}\-[0-9]{3}\-[0-9]{7}$/";
$reg = "/^\d{1,4}\-\d{3}\-\d{7}$/";
ab-1111-12343
xz-1111-12343
$reg = "/^(ab|xz)\-\d{4}\-\d{5}$/";
?> | true |
00124c72437858af0a96086041955ef69767927e | PHP | akash130013/cannabis_laravel | /app/Imports/AdminAddressImport.php | UTF-8 | 634 | 2.59375 | 3 | [] | no_license | <?php
namespace App\Imports;
use App\AdminDeliveryAddress;
use Maatwebsite\Excel\Concerns\ToModel;
class AdminAddressImport implements ToModel
{
const ACTIVE = 'active';
/**
* @param array $row
*
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
return new AdminDeliveryAddress([
'address' => $row[0],
'city' => $row[1],
'state' => $row[2],
'zipcode' => $row[3],
'country' => $row[4],
'timezone' => $row[5],
'status' => self::ACTIVE
]);
}
}
| true |
e9128144d2f0505136ab8282f4b01e0c1c4c235c | PHP | lbernadskiy/CLI-lib-Test-Task | /src/cli_lib/Entity/Command/CommandBase.php | UTF-8 | 7,334 | 3.015625 | 3 | [] | no_license | <?php
namespace CliLib\Entity\Command;
use CliLib\Entity\Argument;
use CliLib\Entity\Parameter;
use CliLib\IO\Output\CommonOutputInterface;
use CliLib\ConsoleApp;
use CliLib\Entity\Command\Config;
use CliLib\Exception\{UnlinkedApplicationException, ArgumentException, ParameterException};
/**
* Абстрактный класс реализующий общие методы присущие всем командам
* а также определяющий методы обязательные для реализации дочерними классами.
*
* Class CommandBase
* @package CliLib\Entity\Command
*/
abstract class CommandBase
{
/**
* @var Название команды
*/
private $name;
/**
* @var Описание команды
*/
private $description;
/**
* @var Набор описания аргументов команды.
*/
private $arguments;
/**
* @var Набор описания параметров команды.
*/
private $parameters;
/**
* @var Свойство для хранения объекта приложения.
*/
private $application;
/**
* @var Является ли стандартной командой.
*/
protected $isDefault;
/**
* Вызывает инициализацию в рамках которой должны быть установлены название, описание
* и доступные наборы аргументов и параметров.
*
* CommandBase constructor.
* @param string|null $name
*/
public function __construct(string $name = null)
{
if ($name) {
$this->setName($name);
}
$this->initConfig();
}
/**
* Возвращает название команды.
*
* @return mixed Название команды.
*/
public function getName()
{
return $this->name;
}
/**
* Устанавливает название команды.
*
* @param string $name Название команды.
*/
public function setName(string $name)
{
$this->name = $name;
}
/**
* Возвращает описание команды.
*
* @return mixed Описание команды.
*/
public function getDescription()
{
return $this->description;
}
/**
* Устанавливает описание команды.
*
* @param string $description Описание команды.
*/
public function setDescription(string $description)
{
$this->description = $description;
}
/**
* Сохраняет объект приложения для взаимодействия.
*
* @param ConsoleApp $app Объект основного приложения.
*/
public function linkApplication(ConsoleApp $app)
{
$this->application = $app;
}
/**
* Возвращает привязанное приложение.
*
* @throws UnlinkedApplicationException Выбрасывается если приложение не привязано в момент вызова метода.
* @return mixed
*/
public function getApplication()
{
if ($this->application) {
return $this->application;
}
throw new UnlinkedApplicationException('Application was not linked to current command');
}
/**
* Сохраняет аргумент если он ещё не был сохранен,
* в противном случае выбрасывает исключение.
*
* @throws ArgumentException Выбрасывает если аргумент уже был задан.
* @param Argument $arg Объект аргумента.
*/
public function addArgument(Argument $arg)
{
$argName = $arg->getName();
if (!$this->arguments[$argName]) {
$this->arguments[$argName] = $arg;
} else {
throw new ArgumentException(sprintf('Argument "%s" was already set.', $argName));
}
}
/**
* Метод для сохранения несколько аргументов сразу.
*
* @param array $arguments Массив объектов аргументов.
*/
public function addArguments($arguments = [])
{
if ($arguments) {
foreach ($arguments as $arg) {
$this->addArgument($arg);
}
}
}
/**
* Метод возвращает сохраненный набор аргументов.
*
* @return mixed Набор аргументов.
*/
public function getArguments()
{
return $this->arguments;
}
/**
* Сохраняет параметр если он ещё не был сохранен,
* в противном случае выбрасывает исключение.
*
* @throws ParameterException Выбрасывает если параметр уже был задан.
* @param Parameter $param Объект параметра.
*/
public function addParameter(Parameter $param)
{
$paramName = $param->getName();
if (!$this->options[$paramName]) {
$this->parameters[$paramName] = $param;
} else {
throw new ParameterException(sprintf('Parameter "%s" was already set.', $paramName));
}
}
/**
* Метод для сохранения несколько аргументов сразу.
*
* @param array $parameters Массив объектов параметров.
*/
public function addParameters($parameters = [])
{
if ($parameters) {
foreach ($parameters as $param) {
$this->addParameter($param);
}
}
}
/**
* Метод для получения сохраненных параметров.
*
* @return mixed Набор сохраненных параметров.
*/
public function getParameters()
{
return $this->parameters;
}
/**
* Метод определяет является ли команда стандартной (предустановленной).
*
* @return mixed
*/
public function isDefault()
{
return $this->isDefault;
}
/**
* Метод для реализации дочерними классами.
* Отвечает за непосредственное выполнение действий.
*
* @param CommonOutputInterface $output Объект вывода
* @param \CliLib\Entity\Command\Config $config Объект обработанных входящих параметров и аргументов.
*/
abstract function performAction(CommonOutputInterface $output, Config $config);
}
| true |
36df7f150a64fa8f259cabc9d85e3a474cdb2ab8 | PHP | luanjinlong/pay | /Repository/PayOrderRepository.php | UTF-8 | 2,864 | 3.078125 | 3 | [] | no_license | <?php
namespace Repository;
/**
* 支付订单对应的数据处理
* Class PayOrderRepository
* @package Repository
*/
class PayOrderRepository extends \Controller
{
const ORDER_CREATE = -1;
const ORDER_LOCK = -2;
const ORDER_REQUEST_FAIL = -3;
const ORDER_FAIL = -4;
const ORDER_SUCCESS = 1;
/**
* 订单状态对应的意义
*/
const STATUS_ORDER = [
self::ORDER_CREATE => '新订单', // 支付之前创建订单
self::ORDER_LOCK => '锁定中(正在支付)', // 发送请求成功,等待回掉
self::ORDER_REQUEST_FAIL => '请求支付失败', // 请求支付失败,request 请求出现问题
self::ORDER_FAIL => '支付失败', // 回掉支付失败
self::ORDER_SUCCESS => '订单支付成功', // 回掉支付成功
];
/**
* 根据订单状态获取状态对应的状态名
* @param $status
* @return mixed|string
*/
public function getStatusNameByStatus($status)
{
if (!array_key_exists($status, self::STATUS_ORDER)) {
return '未知状态';
}
return self::STATUS_ORDER[$status];
}
/**
* todo 根据订单号获取对应的状态名
* @param $order
* @return mixed|string
*/
public function getStatusNameByOrderNum($order)
{
$sql = [];
return $this->getStatusNameByStatus($sql[PayDataRepository::ORDER_NUM]);
}
/**
* 创建订单
* @param $arr
* @return bool
*/
public function createOrder($arr)
{
$order = $arr[PayDataRepository::ORDER_NUM];
// todo 订单入库 self::ORDER_CREATE
return true;
}
/**
* 根据订单号更新订单状态为锁定 已经发送请求成功 等待回掉
* @param $order_num int
* @return bool
*/
public function updateToLockByOrder($order_num)
{
// todo sql 更新状态为锁定
return true;
}
/**
* 订单号更新为请求支付失败
* @param $order_num int
* @return bool
*/
public function updateToRequestFailByOrder($order_num)
{
// todo sql 更新状态为锁定 self::ORDER_REQUEST_FAIL
return true;
}
/**
* 根据订单号更新订单状态为支付失败
* @param $order_num int
* @return bool
*/
public function updateToFailByOrder($order_num)
{
// todo sql 更新状态为支付失败
return true;
}
/**
* 根据订单号更新订单状态为支付成功
* @param $order_num int
* @return bool
*/
public function updateToSuccessByOrder($order_num)
{
// todo sql 更新状态为支付成功
return true;
}
} | true |
a99bc8eca9010833cf35915c2e10a0cf9afa67dc | PHP | nourhene15/nourheneprojet | /core/clientfidelesF.php | UTF-8 | 2,551 | 2.734375 | 3 | [] | no_license | <?PHP
include "../config.php";
class clientfidelesF {
function afficherclientfideles ($clientfideles){
echo "idClient: ".$clientfideles->getidClient()."<br>";
echo "PointsFidelite: ".$clientfideles->getPointsFidelite()."<br>";
}
function ajouterclientfideles($clientfideles){
$sql="insert into clientfideles (idClient,PointsFidelite) values (:idClient,:PointsFidelite)";
$db = config::getConnexion();
try{
$req=$db->prepare($sql);
$idClient=$clientfideles->getidClient();
$PointsFidelite=$clientfideles->getPointsFidelite();
$req->bindValue(':idClient',$idClient);
$req->bindValue(':PointsFidelite',$PointsFidelite);
$req->execute();
}
catch (Exception $e){
echo 'Erreur: '.$e->getMessage();
}
}
function afficherclientfideless(){
//$sql="SElECT * From clientfideles e inner join formationphp.clientfideles a on e.idClient= a.idClient";
$sql="SElECT * From clientfideles";
$db = config::getConnexion();
try{
$liste=$db->query($sql);
return $liste;
}
catch (Exception $e){
die('Erreur: '.$e->getMessage());
}
}
function supprimerclientfideles($id){
$sql="DELETE FROM clientfideles where id= :id";
$db = config::getConnexion();
$req=$db->prepare($sql);
$req->bindValue(':idClient',$idClient);
try{
$req->execute();
// header('Location: index.php');
}
catch (Exception $e){
die('Erreur: '.$e->getMessage());
}
}
function modifierclientfideles($clientfideles,$id){
$sql="UPDATE clientfideles SET idClient=:idClient, PointsFidelite=:PointsFidelite WHERE id=:id";
$db = config::getConnexion();
//$db->setAttribute(PDO::ATTR_EMULATE_PREPARES,false);
try{
$req=$db->prepare($sql);
$idClientn=$clientfideles->getidClient();
$PointsFidelite=$clientfideles->getPointsFidelite();
$req->bindValue(':idClient',$idClient);
$req->bindValue(':PointsFidelite',$PointsFidelite);
$s=$req->execute();
// header('Location: index.php');
}
catch (Exception $e){
echo " Erreur ! ".$e->getMessage();
}
}
function rechercherListeclientfideless($idClient){
$sql="SELECT * from clientfideles where idClient=$idClient";
$db = config::getConnexion();
try{
$liste=$db->query($sql);
return $liste;
}
catch (Exception $e){
die('Erreur: '.$e->getMessage());
}
}
}
?> | true |
0940d7e16589c8e4de5b71c884102b5f299d56a5 | PHP | m1/form-manager | /src/Attributes/Max.php | UTF-8 | 3,255 | 3.109375 | 3 | [
"MIT"
] | permissive | <?php
namespace FormManager\Attributes;
use FormManager\InputInterface;
class Max
{
public static $error_message = 'The max value allowed is %s';
/**
* Callback used on add this attribute to an input
*
* @param InputInterface $input The input in which the attribute will be added
* @param mixed $value The value of this attribute
*
* @return mixed $value The value sanitized
*/
public static function onAdd($input, $value)
{
switch ($input->attr('type')) {
case 'datetime':
case 'datetime-local':
case 'date':
case 'time':
case 'month':
case 'week':
return self::checkDatetimeAttribute($input, $value);
default:
return self::checkAttribute($input, $value);
}
}
/**
* Callback used on add this attribute to an input
*
* @param InputInterface $input The input in which the attribute will be added
* @param mixed $value The value of this attribute
*
* @return mixed The value sanitized
*/
protected static function checkAttribute($input, $value)
{
if (!is_float($value) && !is_int($value)) {
throw new \InvalidArgumentException('The max value must be a float number');
}
$input->addValidator('max', array(__CLASS__, 'validate'));
return $value;
}
/**
* Callback used on add this attribute to a datetime input
*
* @param InputInterface $input The input in which the attribute will be added
* @param mixed $value The value of this attribute
*
* @return mixed The value sanitized
*/
protected static function checkDatetimeAttribute($input, $value)
{
if (!date_create($value)) {
throw new \InvalidArgumentException('The max value must be a valid datetime');
}
$input->addValidator('max', array(__CLASS__, 'validateDatetime'));
return $value;
}
/**
* Callback used on remove this attribute from an input
*
* @param InputInterface $input The input from the attribute will be removed
*/
public static function onRemove($input)
{
$input->removeValidator('max');
}
/**
* Validates the input value according to this attribute
*
* @param InputInterface $input The input to validate
*
* @return string|true True if its valid, string with the error if not
*/
public static function validate($input)
{
$value = $input->val();
$attr = $input->attr('max');
return (empty($attr) || ($value <= $attr)) ? true : sprintf(static::$error_message, $attr);
}
/**
* Validates the datetime input value according to this attribute
*
* @param InputInterface $input The input to validate
*
* @return string|true True if its valid, string with the error if not
*/
public static function validateDatetime($input)
{
$value = $input->val();
$attr = $input->attr('max');
return (empty($attr) || (strtotime($value) <= strtotime($attr))) ? true : sprintf(static::$error_message, $attr);
}
}
| true |
19012bbeb6bbfd1e63d47680db95970fd97046dc | PHP | aUsABuisnessman/php-linode-api | /src/foundation/ApiRequestTrait.php | UTF-8 | 2,419 | 2.828125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | <?php
namespace HnhDigital\LinodeApi\Foundation;
/*
* This file is part of the PHP Linode API.
*
* (c) H&H|Digital <hello@hnh.digital>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use GuzzleHttp\Client as Guzzle;
/**
* This is the API Request class.
*
* @author Rocco Howard <rocco@hnh.digital>
*/
trait ApiRequestTrait
{
/**
* Guzzle client.
*
* @var Guzzle
*/
private $client;
/**
* Make an api call.
*
* @param string $method The method to be used. One of GET, PUT, POST, DELETE.
* @param string $uri
* @param string $payload
* @param string $settings
* - headers An array of headers to be sent with this request.
*
* @return mixed
*/
protected function makeApiCall($method, $uri = '', $payload = [], $settings = [])
{
if (is_null($this->client)) {
$this->client = new Guzzle([
'base_uri' => Auth::getBaseEndpoint(),
]);
}
// Get the headers from the settings.
$headers = isset($settings['headers']) ? $settings['headers'] : [];
// Authorization.
Auth::getHeader($headers);
// Add headers to the payload.
$payload['headers'] = $headers;
try {
// Add the placeholders.
$endpoint_url = sprintf($this->endpoint.$uri, ...$this->endpoint_placeholders);
// Request to the given endpoint, and process the response.
return $this->processResponse($method, $this->client->request(
$method,
$endpoint_url,
$payload
));
} catch (\Exception $exception) {
// Throw an error if the request fails
throw new LinodeApiException($exception->getMessage());
}
}
/**
* Process the response.
*
* @param string $method
* @param string $response
*
* @return bool|array
*/
private function processResponse($method, $response)
{
$contents = $response->getBody()->getContents();
$decoded_contents = json_decode($contents, true);
if (json_last_error() === JSON_ERROR_NONE) {
return $decoded_contents;
}
throw new LinodeApiException('Could not decode response. '.$contents);
}
}
| true |
d389de780902780eb8dd12aecfedd60e85c7e62c | PHP | jfroehlich/coreSite | /site/myapp/models.php | UTF-8 | 198 | 2.890625 | 3 | [
"BSD-2-Clause"
] | permissive | <?php
// the models of this app.
class MyAppItem {
var $name = "";
var $created = "";
function __construct($name="demo") {
$this->name = $name;
$this->created = date("F jS, Y, G:i");
}
} | true |
f83110e414fd79051be9db0b28eced8ffdd360a7 | PHP | codememory1/database | /Builders/Compilers/Configs/TableConfig.php | UTF-8 | 1,862 | 3.015625 | 3 | [
"MIT"
] | permissive | <?php
namespace Codememory\Components\Database\Builders\Compilers\Configs;
/**
* Class TableConfig
*
* @package Codememory\Components\Database\Builders\Compilers\Configs
*
* @author Codememory
*/
class TableConfig
{
/**
* @var array
*/
private array $columns = [];
/**
* @var string
*/
private string $engine = 'innoDB';
/**
* @var string|null
*/
private ?string $charset = null;
/**
* @param string $name
* @param string $type
* @param int|null $length
* @param bool $ai
* @param bool $nullable
* @param string|null $default
* @param string|null $collation
*
* @return TableConfig
*/
public function addColumn(string $name, string $type, ?int $length = null, bool $ai = false, bool $nullable = false, ?string $default = null, ?string $collation = null): TableConfig
{
$this->columns[] = compact('name', 'type', 'length', 'ai', 'nullable', 'default', 'collation');
return $this;
}
/**
* @return array
*/
public function getColumns(): array
{
return $this->columns;
}
/**
* @param string $engine
*
* @return TableConfig
*/
public function setEngine(string $engine): TableConfig
{
$this->engine = $engine;
return $this;
}
/**
* @return string
*/
public function getEngine(): string
{
return $this->engine;
}
/**
* @param string $charset
*
* @return TableConfig
*/
public function setCharset(string $charset): TableConfig
{
$this->charset = $charset;
return $this;
}
/**
* @return string|null
*/
public function getCharset(): ?string
{
return $this->charset;
}
} | true |
a72e8b632b19a1d91a0d77739e89811d15e16ec7 | PHP | andreytech/mary-framework | /application/models/home.php | UTF-8 | 349 | 2.65625 | 3 | [] | no_license | <?php
class HomeModel extends CoreModel {
function getHomePageData() {
// Simple call to database using active record:
// $data = $this->db->from('some_table')->getObjects(); // returns array of objects
// Simple regular call to database:
// $data = $this->db->setQuery($sql)->getObjects(); // returns array of objects
return array();
}
} | true |
01bac72e29344c92a3623bb3122f80bdba206a8f | PHP | leafpoda/topsdk | /src/top/request/XhotelConfirmRequest.php | UTF-8 | 1,105 | 2.515625 | 3 | [] | no_license | <?php
/**
* TOP API: taobao.xhotel.confirm request
*
* @author auto create
* @since 1.0, 2013-12-05 12:50:25
*/
class XhotelConfirmRequest
{
/**
* 1:认可淘宝匹配的结果
2:不认可淘宝匹配的结果
**/
private $confirm;
/**
* hid
**/
private $hid;
private $apiParas = array();
public function setConfirm($confirm)
{
$this->confirm = $confirm;
$this->apiParas["confirm"] = $confirm;
}
public function getConfirm()
{
return $this->confirm;
}
public function setHid($hid)
{
$this->hid = $hid;
$this->apiParas["hid"] = $hid;
}
public function getHid()
{
return $this->hid;
}
public function getApiMethodName()
{
return "taobao.xhotel.confirm";
}
public function getApiParas()
{
return $this->apiParas;
}
public function check()
{
RequestCheckUtil::checkNotNull($this->confirm,"confirm");
RequestCheckUtil::checkNotNull($this->hid,"hid");
}
public function putOtherTextParam($key, $value) {
$this->apiParas[$key] = $value;
$this->$key = $value;
}
}
| true |
a46b8a723c90fa32de7bb8aa07d19cec59230197 | PHP | efhafidezet/e-asset-web | /database/migrations/2021_03_18_033825_create_assignment_table.php | UTF-8 | 1,005 | 2.5625 | 3 | [
"MIT"
] | permissive | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateAssignmentTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('assignment', function (Blueprint $table) {
$table->increments('assignment_id');
$table->string('assignment_name');
$table->dateTime('assignment_date');
$table->longText('assignment_details');
$table->integer('location_id');
$table->integer('radius');
$table->integer('assignment_status'); //0 Belum Tersedia, 1 Selesai, 2 Berjalan
$table->tinyInteger('is_active')->default('1');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('assignment');
}
}
| true |
0f8b62a8858233b8de014776b2c478ef1f98fc65 | PHP | hardcoded74/elliott-forum | /src/addons/ThemeHouse/Monetize/Listener/CriteriaUser.php | UTF-8 | 1,325 | 2.578125 | 3 | [] | no_license | <?php
namespace ThemeHouse\Monetize\Listener;
use ThemeHouse\Monetize\XF\Entity\UserProfile;
use XF\Entity\User;
/**
* Class CriteriaUser
* @package ThemeHouse\Monetize\Listener
*/
class CriteriaUser
{
/**
* @param $rule
* @param array $data
* @param User $user
* @param $returnValue
*/
public static function criteriaUser($rule, array $data, User $user, &$returnValue)
{
/** @var UserProfile $profile */
$profile = $user->Profile;
switch ($rule) {
case 'thmonetize_active_upgrades_count':
if ($profile->getThMonetizeActiveUpgradesCount() >= $data['upgrades']) {
$returnValue = true;
}
break;
case 'thmonetize_active_upgrades_maximum':
if ($profile->getThMonetizeActiveUpgradesCount() <= $data['upgrades']) {
$returnValue = true;
}
break;
case 'thmonetize_active_upgrades_expiry':
$cutOff = \XF::$time + ($data['days'] * 86400);
$expiryDate = $profile->getThMonetizeActiveUpgradesEndDate();
if ($expiryDate && $expiryDate < $cutOff) {
$returnValue = true;
}
break;
}
}
}
| true |
2f5217c1d25075dbda07ec3eb76f63541c8f6b72 | PHP | saulhoward/haddock-cms | /core/tags/20080221/haddock-project-organisation/classes/HaddockProjectOrganisation_PHPIncFile.inc.php | UTF-8 | 2,089 | 2.90625 | 3 | [] | no_license | <?php
/**
* HaddockProjectOrganisation_PHPIncFile
*
* @copyright Clear Line Web Design, 2007-08-27
*/
class
HaddockProjectOrganisation_PHPIncFile
extends
FileSystem_PHPIncFile
{
private $title_line;
private $copyright_holder;
private $date;
private $body;
public function
get_title_line()
{
return $this->title_line;
}
public function
set_title_line($title_line)
{
$this->title_line = $title_line;
}
public function
get_copyright_holder()
{
return $this->copyright_holder;
}
public function
set_copyright_holder($copyright_holder)
{
$this->copyright_holder = $copyright_holder;
}
public function
get_date()
{
if (!isset($this->date)) {
$this->date = date('Y-m-d');
}
return $this->date;
}
public function
set_date($date)
{
$this->date = $date;
}
public function
get_body()
{
return $this->body;
}
public function
set_body($body)
{
$this->body = $body;
}
public function
get_as_string()
{
if (is_file($this->get_name())) {
#echo $this->get_name() . " already exists, returning contents.\n";
return $this->get_contents();
} else {
#echo $this->get_name() . " doesn't exist, generating contents.\n";
$str = '';
$str .= "<?php\n";
$str .= "/**\n";
$str .= ' * ' . $this->get_title_line() . "\n";
$str .= " *\n";
$date = $this->get_date();
$str .= ' * @copyright ' . $this->get_copyright_holder() . ", $date\n";
$str .= " */\n";
$str .= "\n";
$str .= $this->get_body();
$str .= "\n";
$str .= "?>\n";
return $str;
}
}
}
?>
| true |
d76470fe092f6ba601b6b600d186162cf7a5a15e | PHP | aybbou/patent-scraper | /src/Rayak/PatentsScraper.php | UTF-8 | 2,884 | 3.015625 | 3 | [] | no_license | <?php
namespace Rayak;
use Goutte\Client;
/**
* @author Ayyoub
*/
class PatentsScraper {
private $client;
private $config = array();
private static $patentScraper = NULL;
private function __construct(Client $client, array $config = null, $path) {
$this->client = $client;
$this->config = $config;
$this->createPatentsFiles($path);
}
static function createPatentScraper(Client $client, array $config = null, $path) {
self::$patentScraper = new PatentsScraper($client, $config, $path);
return self::$patentScraper;
}
private function getFullPageLink($pageNumber) {
$website = isset($this->config['website']) ? $this->config['website'] : '';
$searchPage = isset($this->config['searchPage']) ? $this->config['searchPage'] : '';
$queryParam = isset($this->config['queryParam']) ? $this->config['queryParam'] : '';
$pageParam = isset($this->config['pageParam']) ? $this->config['pageParam'] : '';
$query = isset($this->config['query']) ? $this->config['query'] : '';
$fullPageLink = $website . $searchPage . '&' . $queryParam . '=' . $query . '&' . $pageParam . '=' . $pageNumber;
return $fullPageLink;
}
private function getPatentLink($patent) {
$website = isset($this->config['website']) ? $this->config['website'] : '';
$link = $patent->getAttribute('href');
$patentLink = $website . $link;
return $patentLink;
}
private function createPatentFile($filePath, $patentContent) {
$file = fopen($filePath, 'w');
fputs($file, $patentContent);
fclose($file);
}
private function createPatentsFiles($path) {
$patentLinkFilter = isset($this->config['patentLinkFilter']) ? $this->config['patentLinkFilter'] : '';
$patentContentFilter = isset($this->config['patentContentFilter']) ? $this->config['patentContentFilter'] : '';
$nbPatents = 1;
for ($page = 1;; $page++) {
$fullPageLink = $this->getFullPageLink($page);
$patentsCrawler = $this->client->request('GET', $fullPageLink);
$patents = $patentsCrawler->filter($patentLinkFilter);
if ($patents->count() == 0) {
echo "\nDone !";
break;
}
foreach ($patents as $patent) {
$patentLink = $this->getPatentLink($patent);
$crawler = $this->client->request('GET', $patentLink);
$patentCrawler = $crawler->filter($patentContentFilter);
$patentContent = $patentCrawler->html();
$filePath = $path . '/' . $nbPatents . '.html';
$this->createPatentFile($filePath, $patentContent);
echo "$nbPatents.html Created.\n";
$nbPatents++;
}
}
}
}
| true |
b3d6af83fa2240b08a2764eebf5123e98b3a2a9b | PHP | xingziye/steampunked-project2 | /lib/Steampunked/CreateGameView.php | UTF-8 | 1,231 | 2.890625 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: Santoro
* Date: 4/8/16
* Time: 3:20 PM
*/
namespace Steampunked;
class CreateGameView
{
/**
* Constructor
* Sets the page title and any other settings.
*/
public function __construct(Site $site)
{
$this->site = $site;
}
public function present(){
$html = <<<HTML
<div class="screen">
<p><img src="images/title.png" alt="Steampunked Logo"></p>
<form method="post" action="post/create-game-post.php">
<fieldset>
<legend>Game Size</legend>
<br>
<p>
<label for="6x6">6x6</label>
<input type="radio" name="gamesize" id="6x6" value="6" checked="checked" >
<label for="10x10">10x10</label>
<input type="radio" name="gamesize" id="10x10" value="10">
<label for="20x20">20x20</label>
<input type="radio" name="gamesize" id="20x20" value="20">
</p>
<br>
<p>
<input type="submit" value="Submit">
</p>
</fieldset>
</form>
</div>
HTML;
return $html;
}
private $site; ///< The Site object
} | true |
3497fba36ddccada0ed100ff390e8992dc79c061 | PHP | zachbrowne/phpODP | /testscript.php | UTF-8 | 768 | 2.59375 | 3 | [
"CC-BY-3.0"
] | permissive | <?
/**
* You do not need to upload this script to your server if you don't experience any problems! :)
*
* testscript.php - will check to see if you can access the dmoz server from your host/server.
*
* If you experience any problems with odp.php, please run this script to see what errors are shown. Search for these errors in the phpODP forum
* at http://www.bie.no/forum/ - and remember to refer to the error messages if you need to ask a question in the forum.
*
*/
function error_handler($severity, $msg, $filename, $linenum) {
echo $severity . " " . $msg . " ($filename:$linenum)<br>";
}
error_reporting(E_ALL);
set_error_handler("error_handler");
if($fp = fopen("http://www.dmoz.org", "r")) {
echo "Congrats! Everything seems to be working";
}
?> | true |
acb344976dcbedcf3634b4f7f6f95f18b0996bb1 | PHP | edjenkins/xmovement | /app/Jobs/SendContactEmail.php | UTF-8 | 1,018 | 2.53125 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Jobs;
use App\Jobs\Job;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Lang;
use Mail;
use App\Message;
use App\User;
class SendContactEmail extends Job implements ShouldQueue
{
use InteractsWithQueue, SerializesModels;
protected $name;
protected $email;
protected $text;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($name, $email, $text)
{
$this->name = $name;
$this->email = $email;
$this->text = $text;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
Mail::send('emails.contact-email', ['name' => $this->name, 'email' => $this->email, 'text' => $this->text], function ($message) {
$message->to(getenv('APP_CONTACT_EMAIL'))->subject(Lang::get('emails.contact_email_subject', ['name' => $this->name]));
});
}
}
| true |
374b627162050deb414104e31549ff636cb40bd7 | PHP | DilipKumarR14/All | /codeigniter/application/controllers/Archived.php | UTF-8 | 4,446 | 2.734375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | <?php
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Authorization");
include_once "NoteStoreConfig.php";
/**
* @description api for the archive the notes
*/
class Archived
{
/**
* @method isArchive()
* to check whether it is archived
* @var id which store the id of the archive card
* @return jsondata
*/
public function isArchive()
{
$id = $_POST['id'];
$conf = new NoteStoreConfig();
$conn = $conf->configs();
$stmt = $conn->prepare("UPDATE note SET isArchive = 'true' where id = '$id' ");
$stmt->execute();
$stmt = $conn->prepare("SELECT * FROM note where isArchive = 'false' ");
$stmt->execute();
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
$jsondata = json_encode($row);
print($jsondata);
}
/**
* @method unArchive()
* @description to check whether it is archived
* @var id which store the id of the unarchive card
* @return jsondata
*/
public function unArchive()
{
$id = $_POST['id'];
$conf = new NoteStoreConfig();
$conn = $conf->configs();
$stmt = $conn->prepare("UPDATE note SET isArchive = 'false' where id = '$id' ");
$stmt->execute();
$stmt = $conn->prepare("SELECT * FROM note where isArchive = 'true' ");
$stmt->execute();
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
$jsondata = json_encode($row);
print($jsondata);
}
/**
* @method receiveArchive()
* to store the archive the cards into the database
* @return jsondata
*/
public function receiveArchive()
{
$headers = apache_request_headers();
$jwt = $headers['Authorization'];
$jwttoken = explode(" ", $jwt); // bearer
require "Account.php";
$validate = new Account();
if ($validate->verify($jwttoken[1])) {
if ($_POST['email'] != null) {
$email = $_POST['email'];
$title = $_POST['title'];
$note = $_POST['note'];
$date = $_POST['date'];
$color = $_POST['color'];
$arch = $_POST['archive'];
$conf = new NoteStoreConfig();
$conn = $conf->configs();
/**
* insert the title and note into databse based on the emailid
*/
$stm = $conn->prepare("INSERT INTO note(title,note,email,date,colorcode,isArchive) VALUES('$title','$note','$email','$date','$color','$arch')");
$stm->execute();
/**
* fetch all the values from the database based on the email
*/
$stmt = $conn->prepare("select * from note where email = '$email' and isArchive = 'true' order by id desc ");
$stmt->execute();
/**
* return the array of all the field like note,title,email etc
*/
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
$res = json_encode($row);
print($res);
} else {
/**
* email not found (content-not found)
*/
$res = '{"status":"204"}';
print $res;
}
} else {
$res = json_encode(array(
"status" => "404",
));
print $res;
}
}
/**
* @method storearchive()
* for the store the archive card
* @return jsondata
*/
public function storearchive()
{
$res = apache_request_headers();
/**
* @var email holds the title entered by the user and stored in cookie while login
*/
$email = $_POST['email'];
$conf = new NoteStoreConfig();
$conn = $conf->configs();
/**
* fetch all the values from the database based on the email
*/
$stmt = $conn->prepare("select * from note where email = '$email' and isArchive = 'true' order by id desc ");
$stmt->execute();
/**
* return the array of all the field like note,title,email etc
*/
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
$res = json_encode($row);
/**
* return the result response
*/
print($res);
}
}
| true |
e21522a4ef0e4fa701793d6ddb0e255ab1ffccd1 | PHP | riuson/eaaphp2 | /classes/router.php | UTF-8 | 1,210 | 2.765625 | 3 | [] | no_license | <?php
/*
* Check, find and load controller.
*/
Class Router {
private $registry;
function __construct($registry) {
$this->registry = $registry;
}
function delegate() {
// Analize call
$this->getController($controllerClassName);
// Create controller (__autoload)
$controller = new $controllerClassName($this->registry);
// additional control: some modes require logged user
if ($controller->loginRequired()) {
if (!$this->registry['user']->isLogged()) {
$controllerError = new controller_sys_error($this->registry);
return $controllerError->process();
}
}
// get data
return $controller->process();
}
private function getController(&$controller) {
$call = (empty($_POST['call'])) ? '' : $_POST['call'];
// if no incoming data, set default mode
if (empty($call)) {
$call = 'mode_about';
}
// check for invalid symbols
if (preg_match("/[^a-zA-Z_\d]/", $call) > 0) {
$call = "sys_error";
}
// check user access rights to mode
if (preg_match("/mode_/", $call) > 0) {
$modes = $this->registry['modes'];
if (!in_array($call, $modes->getAvailableModes()))
$call = "sys_error";
}
$controller = "controller_" . $call;
}
}
?>
| true |
26c48d8a5918d1bbbec064c873aff221be61c64b | PHP | dtabirca/design-patterns | /tests/VisitorTest.php | UTF-8 | 1,081 | 3.125 | 3 | [] | no_license | <?php declare(strict_types=1);
/**
* Visitor Test
*
* @category Design_Patterns
* @package Behavioral
* @author AltTab
* @license WTFPL https://en.wikipedia.org/wiki/WTFPL
* @link https://github.com
*/
use DesignPatterns\Behavioral\Visitor;
use PHPUnit\Framework\TestCase;
/**
* Testing Visitor Pattern
*/
class VisitorTest extends TestCase
{
/**
* test visitor interface
*/
public function testVisitor1(): void
{
$this->expectOutputString(
"A + ConcreteVisitor1\n" .
"B + ConcreteVisitor1\n"
);
$visitor1 = new Visitor\ConcreteVisitor1();
(new Visitor\ConcreteComponentA())->accept($visitor1);
(new Visitor\ConcreteComponentB())->accept($visitor1);
}
/**
*
*/
public function testVisitor2(): void
{
$this->expectOutputString(
"A + ConcreteVisitor2\n" .
"B + ConcreteVisitor2\n"
);
$visitor2 = new Visitor\ConcreteVisitor2();
(new Visitor\ConcreteComponentA())->accept($visitor2);
(new Visitor\ConcreteComponentB())->accept($visitor2);
}
}
| true |
a616e040c7554b6a85b669df51dfee6e7eaed44b | PHP | tlaffoon/freezy-octo | /app/database/migrations/2014_12_02_171450_AddUsersTable.php | UTF-8 | 1,867 | 2.65625 | 3 | [] | no_license | <?php
use Illuminate\Database\Migrations\Migration;
class AddUsersTable extends Migration
{
/**
* Run the migrations.
*/
public function up()
{
// Creates the users table
Schema::create('users', function ($table) {
$table->increments('id');
$table->string('email')->unique();
$table->string('password');
$table->string('first');
$table->string('last');
$table->string('fullname');
$table->string('phone');
$table->string('gender');
$table->date('dob');
$table->integer('age');
$table->string('img_path');
$table->string('street');
$table->string('city');
$table->string('state');
$table->string('zip');
$table->string('address');
$table->string('role')->default('student');
$table->string('status')->default('unassigned');
$table->integer('assigned_course_id')->unsigned();
$table->boolean('financing')->default(0);
$table->boolean('application_completed')->default(0);
$table->boolean('scholarship_recipient')->default(0);
$table->string('confirmation_code');
$table->string('remember_token')->nullable();
$table->boolean('confirmed')->default(false);
$table->timestamps();
});
// Creates password reminders table
Schema::create('password_reminders', function ($table) {
$table->string('email');
$table->string('token');
$table->timestamp('created_at');
});
}
/**
* Reverse the migrations.
*/
public function down()
{
Schema::drop('password_reminders');
Schema::drop('users');
}
}
| true |
bce75291dc930c4c8276d1c46102290b61a7343f | PHP | gdhaison/pure_php_mvc | /PostManager/src/Controller/Manager/ManagerController.php | UTF-8 | 2,756 | 2.6875 | 3 | [] | no_license | <?php
use Model\Provider;
require_once(__DIR__ . '/../../Model/Provider.php');
class ManagerController
{
private static $instance;
public static function getInstance()
{
if (is_null(self::$instance)) {
self::$instance = new ManagerController();
}
return self::$instance;
}
public function index()
{
(is_null($_POST['per_page']) ? $per_page = 5 : $per_page = $_POST['per_page']);
$query = 'SELECT * FROM posts LIMIT ' . $per_page;
echo $per_page;
$posts = Provider::getInstance()->excuteQuery($query);
require_once(__DIR__ . '/../../View/Manager/index.php');
}
public function create()
{
require_once(__DIR__ . '/../../View/Manager/create.php');
}
public function store()
{
$target_dir = "/home/vuhaison/Desktop/PostManager/public/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$image = "";
if(move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)){
$image = $target_file;
}
$query = 'INSERT INTO posts(title, description, image, status) VALUES(?, ?, ?, ?)';
$provider = Provider::getInstance()->excuteNonQuery($query, [
$_POST['title'],
$_POST['description'],
$image,
$_POST['status'],
]);
if ($provider) {
header('Location: ?controller=manager&action=index');
} else {
echo 'Stored incorret';
}
}
function show()
{
echo 'show';
}
public function edit()
{
$id = $_GET['id'];
$query = "Select * from posts where id = " . $id;
$posts = Provider::getInstance()->excuteQuery($query);
$post = $posts[0];
require_once(__DIR__ . '/../../View/Manager/edit.php');
}
public function update($id)
{
$query = 'Update posts set title=?, description=?, image=?, status=? where id=?';
$provider = Provider::getInstance()->excuteNonQuery($query, [
$_POST['title'],
$_POST['description'],
$_POST['image'],
$_POST['status'],
$id,
]);
if ($provider) {
header('Location: ?controller=manager&action=index');
} else {
echo 'Stored incorret';
}
}
public function destroy($id)
{
$query = 'Delete from posts where id = ?';
$provider = Provider::getInstance()->excuteNonQuery($query, [
$id
]);
if ($provider) {
header('Location: ?controller=manager&action=index');
} else {
echo 'Stored incorret';
}
}
} | true |
d684b7aacc90a609efb053e2230958ea101c66bf | PHP | fakhrishahab/csi_web | /app/Http/Controllers/ContactController.php | UTF-8 | 892 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
namespace csi\Http\Controllers;
use csi\Message;
use Illuminate\Http\Request;
use csi\Http\Requests;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Response;
class ContactController extends Controller
{
protected $messages;
public function __construct(Message $message)
{
$this->messages = $message;
}
public function index(){
$messages = $this->messages->paginate(10);
return view('backend.messages.index', compact('messages'));
}
public function create(Requests\StoreMessageRequest $request){
$attr = [
'name' => $request->input('name'),
'email' => $request->input('email'),
'message' => $request->input('message')
];
if($this->messages->create($attr)){
return Response::json(array(
'code' => 200,
'message' => 'Save Message Successfull'
), 200);
}
}
}
| true |
8e3e357cf04a12464359cca09029a3a7dba342a5 | PHP | EduardCherkashyn/codingTask | /src/Entity/Task.php | UTF-8 | 2,035 | 2.609375 | 3 | [] | no_license | <?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\Table(name="task")
*/
class Task
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue
* @var int
*/
private $id;
/**
* @ORM\Column(type="string")
* @var string
*/
private $user_name;
/**
* @ORM\Column(type="string")
* @var string
*/
private $email;
/**
* @ORM\Column(type="text")
* @var string
*/
private $text;
/**
* @ORM\Column(type="boolean")
* @var boolean
*/
private $completed;
/**
* @ORM\Column(type="boolean")
* @var boolean
*/
private $edited;
/**
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* @return string
*/
public function getUserName()
{
return $this->user_name;
}
/**
* @param string $user_name
*/
public function setUserName($user_name)
{
$this->user_name = $user_name;
}
/**
* @return string
*/
public function getEmail()
{
return $this->email;
}
/**
* @param string $email
*/
public function setEmail($email)
{
$this->email = $email;
}
/**
* @return string
*/
public function getText()
{
return $this->text;
}
/**
* @param string $text
*/
public function setText($text)
{
$this->text = $text;
}
/**
* @return bool
*/
public function isCompleted()
{
return $this->completed;
}
/**
* @param bool $completed
*/
public function setCompleted($completed)
{
$this->completed = $completed;
}
/**
* @return bool
*/
public function isEdited()
{
return $this->edited;
}
/**
* @param bool $edited
*/
public function setEdited($edited)
{
$this->edited = $edited;
}
}
| true |
4bc50085bc2bee4911653f9e1c5197d0e37f7911 | PHP | chrgu000/gongnangwang | /gongnangconsole/Apps/Home/Mapper/ProjectAuditMapper.class.php | UTF-8 | 684 | 2.640625 | 3 | [] | no_license | <?php
namespace Home\Mapper;
final class ProjectAuditMapper implements IMapper {
public function tranlate(array $rows, $isArray) {
if (! empty ( $rows )) {
if ($isArray) {
foreach ( $rows as $k => $v ) {
$rows [$k] ['old_publish_status_txt'] = _getProPublishStatusById ( $v ['old_publish_status'] );
$rows [$k] ['new_publish_status_txt'] = _getProPublishStatusById ( $v ['new_publish_status'] );
}
} else {
$rows ['old_publish_status_txt'] = _getProPublishStatusById ( $rows ['old_publish_status'] );
$rows ['new_publish_status_txt'] = _getProPublishStatusById ( $rows ['new_publish_status'] );
}
}
return $rows;
}
} | true |
9daf90eb3e7f7e37104602e05f023506bf22c83d | PHP | ztavruz/server-site | /app/Service/User/UserService.php | UTF-8 | 1,184 | 2.890625 | 3 | [] | no_license | <?php
namespace App\Service\User;
use App\Entity\User;
use App\Repository\UserRepository;
use App\Security\Token\Token;
use App\Storage\SessionStorage;
class UserService
{
private $repository;
/**
* @var SessionStorage
*/
private $jwt;
public function __construct(UserRepository $repository, SessionStorage $storage)
{
$this->repository = $repository;
$this->jwt = new Token();
}
//testable
public function signup(SignupDto $dto): User
{
$user = new User();
$user->setEmail($dto->email);
$user->setPassword($dto->password);
$user->setName($dto->name);
$user = $this->repository->create($user);
return $user;
}
public function login(LoginDto $dto)
{
$user = new User();
$user->setLogin($dto->login);
$user->setPassword($dto->password);
$user = $this->repository->login($user);
if ($user != null) {
return $user;
}
if (!$user) {
throw new \DomainException("Пользователь с таким логином не найден!(User not found) ");
}
}
} | true |
b32070b33beecf5ef7a5a126ffe5b386f4f57935 | PHP | lipevieira/selo | /app/Models/Document.php | UTF-8 | 1,030 | 2.609375 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Document extends Model
{
protected $fillable = ['doc_name', 'description',];
protected $dates = [
'created_id',
'created_at',
];
/**
* Relacionamento de morphTo
*
* @return Institution
* @return InstitutionRecognition
*/
public function institution()
{
return $this->belongsTo(Institution::class);
}
public function downloandAnexoOne()
{
return response()->download(storage_path("app/public/models/anexo01.doc"));
}
/**
* Baixando o modelo do Anexo 06
*
* @return void
*/
public function downloandAnexoSix()
{
return response()->download(storage_path("app/public/models/anexo06.doc"));
}
/**
* Baixando o modelo do Anexo 07
* @return void
*/
public function downloandAnexoServen()
{
return response()->download(storage_path("app/public/models/anexo07.doc"));
}
}
| true |
4e47902abe0ea95a1c184e57cd8cb0878161cace | PHP | carlosjonas/aprendiz_back_end | /home.php | UTF-8 | 2,552 | 2.765625 | 3 | [] | no_license | <?php
//Linkando minha conexao com o banco
require_once 'acao/conexao.php'
?>
<!DOCTYPE html>
<html>
<head>
<title>CRUD</title>
<meta charset="utf-8"/>
<link rel="shortcut icon" href="assets/img/favicon.ico" />
<!--Adicionando minha linkagem externa de css,js e de icones do font-awesome-->
<link rel="stylesheet" type="text/css" href="assets/css/style.css"/>
<meta id="viewport" name="viewport" content="width=device-width" />
<script src="https://kit.fontawesome.com/7b2c34bc68.js" crossorigin="anonymous"></script>
</head>
<body>
<!--Iniciando meu crud básico-->
<h1>CRUD - Aprendiz de Back End</h1>
<table>
<thead>
<tr>
<!--Colocando os campos de cabeçalho-->
<th>Nome:</th>
<th>RG:</th>
<th>CPF:</th>
<th>Email:</th>
<th>Endereço:</th>
<th>Telefone 1:</th>
<th>Telefone 2:</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<?php
//Aqui eu estou selecionando as linhas do meu banco pra exibir em tempo real as informações e estou passando os dados em um loop
$sql= "SELECT * FROM usuarios";
$result = mysqli_query($conexao, $sql);
while ($dados = mysqli_fetch_array($result)) {
?>
<tr>
<td><?php echo $dados['nome']; ?></td>
<td><?php echo $dados['rg']; ?></td>
<td><?php echo $dados['cpf']; ?></td>
<td><?php echo $dados['email']; ?></td>
<td><?php echo $dados['endereco']; ?></td>
<td><?php echo $dados['telefone1']; ?></td>
<td><?php echo $dados['telefone2']; ?></td>
<td>
<!--Meu botão de Editar-->
<button class="icone-editar">
<a href="editar.php?id=<?php echo $dados['id'];?>"><i class="fas fa-pencil-alt"></i></a>
</button>
</td>
<td>
<form action="acao/deletar.php" method="POST">
<!--input escondido para apontar pro meu deletar e saber qual registro estou pegando-->
<input type="hidden" name="id" value="<?php echo $dados['id']; ?>">
<!--Meu botão de Deletar, só confirmo com um return pra não acontecer de clicarem sem querer-->
<button class="icone-deletar" type="submit" onclick="return confirm('Tem certeza que deseja excluir este registro?')" name="btn-deletar">
<i class="fas fa-trash-alt"></i>
</button>
</form>
</td>
</tr>
<?php
//Fim do loop que faço pra exibir os dados
}
?>
</tbody>
</table>
<br/><br/>
<!--Meu botão para adicionar um novo usuário-->
<div class="btn-adicionar">
<a href="adicionar.php">Adicionar Usuário</a>
</div>
</body>
</html> | true |
2054db460ee93145fc70ec38ff9cda9d5eef8292 | PHP | dellsala/ESys-Framework | /lib/library/ESys/PHPUnit/TestSuiteBuilder.php | UTF-8 | 2,718 | 2.84375 | 3 | [] | no_license | <?php
/**
* @package ESys
*/
/**
*
*/
class ESys_PHPUnit_TestSuiteBuilder {
public function build ($suiteClass, $targetDirectory)
{
$suite = new $suiteClass();
$suite->setName($suiteClass);
$testFiles = $this->findTestFiles($targetDirectory, true);
foreach ($testFiles as $testFile) {
require_once $testFile;
}
$classNameCalculator =
new ESys_PHPUnit_TestSuiteBuilder_ClassNameCalculator($suiteClass, $targetDirectory);
foreach ($testFiles as $testFile) {
$className = $classNameCalculator->className($testFile);
if (substr($className, 0 - strlen('Suite')) == 'Suite') {
$suite->addTestSuite(call_user_func(array($className, 'suite')));
} else {
$suite->addTestSuite($className);
}
}
return $suite;
}
private function findTestFiles ($targetDirectory, $skipSuiteSearch = false)
{
if (! $skipSuiteSearch) {
$suiteList = glob($targetDirectory.'/*Suite.php');
if (count($suiteList)) {
return array($suiteList[0]);
}
}
$fileList = glob($targetDirectory.'/*');
$testFileList = array();
foreach ($fileList as $file) {
if (substr($file, 0 - strlen('Test.php')) == 'Test.php') {
$testFileList[] = $file;
} else if (is_dir($file)) {
$testFileList = array_merge($testFileList, $this->findTestFiles($file));
}
}
return $testFileList;
}
}
class ESys_PHPUnit_TestSuiteBuilder_ClassNameCalculator {
private $suiteClass;
private $targetDirectory;
private $classRootDirectory;
public function __construct ($suiteClass, $targetDirectory)
{
$this->suiteClass = $suiteClass;
$this->targetDirectory = $targetDirectory;
}
private function classRootDirectory ()
{
if (! isset($this->classRootDirectory)) {
$packageDepth = count(explode('_', $this->suiteClass));
$this->classRootDirectory = $this->targetDirectory;
for ($i=0; $i < $packageDepth -1; $i++) {
$this->classRootDirectory = dirname($this->classRootDirectory);
}
}
return $this->classRootDirectory;
}
public function className ($classFile)
{
$classRootDirectory = $this->classRootDirectory().'/';
$className = substr($classFile, strlen($classRootDirectory));
$className = substr($className, 0, - strlen('.php'));
$className = str_replace('/', '_', $className);
return $className;
}
}
| true |
f51dd303cdd0620a7d78a0055e8319bf9d9c7aa8 | PHP | chameleon-system/chameleon-base | /src/CoreBundle/private/library/classes/TViewParser/TViewParser.class.php | UTF-8 | 8,214 | 2.625 | 3 | [
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-2.0-only",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-unknown-license-reference",
"GPL-1.0-or-later",
"Apache-2.0",
"LGPL-2.1-or-later",
"CC0-1.0",
"CC-BY-2.5",
"MPL-2.0",
"MPL-1.0",
"LGPL-2.1-only",
"... | permissive | <?php
/*
* This file is part of the Chameleon System (https://www.chameleonsystem.com).
*
* (c) ESONO AG (https://www.esono.de)
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use ChameleonSystem\CoreBundle\ServiceLocator;
/**
* used to render module views. makes data as $data and under the key name available in the view.
/**/
class TViewParser
{
/**
* the template data.
*
* @var array
*/
protected $aTemplateData = array();
/**
* shows a comment hint block with the template path.
*
* @var bool - default true
*/
public $bShowTemplatePathAsHTMLHint = true;
/**
* add a variable to the system. the variable will be accessible in the view
* under $data[$key], and the key name.
*
* @param string $key
* @param mixed $var
*/
public function AddVar($key, $var)
{
$this->aTemplateData[$key] = $var;
}
/**
* adds an array of variables to the template system
* the variable will be accessible in the view under $data[$key],
* and the key name.
*
* @param array $aData
*/
public function AddVarArray($aData)
{
$this->aTemplateData = array_merge($this->aTemplateData, $aData);
}
/**
* render content.
*
* @param string $sModuleName - module name
* @param string $sViewName - view name
*
* @return string -rendert view
*/
public function Render($sModuleName, $sViewName)
{
$sTemplatePath = $this->getViewPathManager()->getModuleViewPath($sModuleName, $sViewName);
return $this->GetContent($sTemplatePath);
}
/**
* Render current data using sViewName in sSubType for either Core, Custom, or Customer.
*
* @param string $sViewName - name of the view (do not include .view.php)
* @param string $sSubType - path relative to objectviews
* @param string $sType - Core, Custom, Customer
*
* @example RenderObjectView('metadata','dbobjects/TCMSActivePage','Core')
*
* @return string
*/
public function RenderObjectView($sViewName, $sSubType = '', $sType = 'Core')
{
$sTemplatePath = $this->getViewPathManager()->getObjectViewPath($sViewName, $sSubType, $sType);
return $this->GetContent($sTemplatePath);
}
/**
* Render current data using sViewName in sSubType for either Core, Custom, or Customer.
*
* @param string $sViewName - name of the view (do not include .view.php)
* @param string $sModuleName - name of the CMS backend module
* @param string $sType - Core, Custom, Customer
*
* @return string
*/
public function RenderBackendModuleView($sViewName, $sModuleName = '', $sType = 'Core')
{
$sTemplatePath = $this->getViewPathManager()->getBackendModuleViewPath($sViewName, $sModuleName, $sType);
return $this->GetContent($sTemplatePath);
}
/**
* render current data using view.
*
* @param string $sPath - full path to view
*
* @return string
*/
public function RenderBackendModuleViewByFullPath($sPath)
{
$sTemplatePath = $this->getViewPathManager()->getBackendModuleViewFromFullPath($sPath);
return $this->GetContent($sTemplatePath);
}
/**
* @param string $sViewName - name of the view (do not include .view.php, include subdirs if neccessary)
* @param string $sModuleName - name of the web module
* @param string $sType - Core, Custom, Customer
*
* @example RenderWebModuleView('includes/atom','MTBlogPostList','Customer')
*
* @return string
*/
public function RenderWebModuleView($sViewName, $sModuleName, $sType = 'Customer')
{
$sTemplatePath = $this->getViewPathManager()->getWebModuleViewPath($sViewName, $sModuleName, $sType);
return $this->GetContent($sTemplatePath);
}
/**
* Render current data using sViewName in sSubType for either Core, Custom, or Customer
* but assumes that the path is in ./classes.
*
*
* @param string $sViewName - name of the view (do not include .view.php)
* @param string $sSubType - path relative to objectviews
* @param string $sType - Core, Custom, Customer
*
* @example RenderObjectPackageView('metadata','pkgShop/dbobjects/TCMSActivePage','Core')
*
* @return string
*/
public function RenderObjectPackageView($sViewName, $sSubType = '', $sType = 'Core')
{
$sTemplatePath = $this->getViewPathManager()->getObjectPackageViewPath($sViewName, $sSubType, $sType);
return $this->GetContent($sTemplatePath);
}
/**
* renders the module/object view
* outputs an error in html if view was not found.
*
* @param string $sTemplatePath - path to view
*
* @return string
*/
protected function GetContent($sTemplatePath)
{
$content = '';
$orgPath = $sTemplatePath;
$sTemplatePath = realpath($sTemplatePath);
if (false === $sTemplatePath) {
if (_DEVELOPMENT_MODE) {
$content = '<div style="background-color: #ffcccc; color: #900; border: 2px solid #c00; padding-left: 10px; margin-bottom: 8px; padding-right: 10px; padding-top: 5px; padding-bottom: 5px; font-weight: bold; font-size: 11px; min-height: 40px; display: block;">Error! view is missing: '.TGlobal::OutHTML($orgPath).'</div>';
} else {
$content = '<!-- MISSING VIEW - see log for details -->';
TTools::WriteLogEntry('Error! view is missing: '.$orgPath, 1, __FILE__, __LINE__);
}
} else {
if (file_exists($sTemplatePath) && is_file($sTemplatePath)) {
unset($orgPath);
if (!array_key_exists('data', $this->aTemplateData)) {
$data = $this->aTemplateData;
}
extract($this->aTemplateData, EXTR_REFS || EXTR_SKIP);
ob_start();
require TGlobal::ProtectedPath($sTemplatePath);
$content = ob_get_contents();
ob_end_clean();
} else {
if (_DEVELOPMENT_MODE) {
$content = '<div style="background-color: #ffcccc; color: #900; border: 2px solid #c00; padding-left: 10px; margin-bottom: 8px; padding-right: 10px; padding-top: 5px; padding-bottom: 5px; font-weight: bold; font-size: 11px; min-height: 40px; display: block;">Error! view is missing: '.TGlobal::OutHTML($orgPath).'</div>';
} else {
$content = '<!-- MISSING VIEW - see log for details -->';
TTools::WriteLogEntry("Error! view is missing: {$sTemplatePath} [org: {$orgPath}]", 1, __FILE__, __LINE__);
}
}
}
$bAllowHint = false;
$showViewSourceHtmlHints = \ChameleonSystem\CoreBundle\ServiceLocator::getParameter('chameleon_system_core.debug.show_view_source_html_hints');
if ($showViewSourceHtmlHints && !empty($content) && _DEVELOPMENT_MODE) {
$bAllowHint = true;
}
if ($bAllowHint && $this->bShowTemplatePathAsHTMLHint && !TGlobal::IsCMSMode()) {
$sTemplatePath = $this->TransformHTMLHintPath($sTemplatePath);
$content = "<!--\nSTART VIEW: {$sTemplatePath}\n-->{$content}<!--\nEND VIEW: {$sTemplatePath}\n-->";
}
return $content;
}
/**
* overwrite this method to transform the view path hint to a more usable format
* use this for example to convert the path to your local dev environment and IDE
* (samba shares, FTP paths or whatever), this reduces your effort finding the right files.
*
* @param string $sTemplatePath
*
* @return string
*/
protected function TransformHTMLHintPath($sTemplatePath)
{
return $sTemplatePath;
}
/**
* @return IViewPathManager
*/
private function getViewPathManager()
{
return ServiceLocator::get('chameleon_system_core.viewPathManager');
}
}
| true |
2ea224d4f74894941a6b75fc4463b90aa588505e | PHP | filipha/web-backend-oplossingen | /opdracht-conditional-statements-switch/opdracht_conditional_statements_switch.php | UTF-8 | 623 | 3.125 | 3 | [] | no_license | <?php
$getal = 5;
switch ( $getal )
{
case 1:
$antwoord = "maandag";
break;
case "2":
$antwoord = "dinsdag";
break;
case "3":
$antwoord = "woensdag";
break;
case "4":
$antwoord = "donderdag";
break;
case "5":
$antwoord = "vrijdag";
break;
case "6":
$antwoord = "zaterdag";
break;
case "7":
$antwoord = "zondag";
break;
default:
$antwoord = "geen dag overeenkomstig een getal";
}
?>
<!doctype HTML>
<html>
<head>
<title>Dit is de titel</title>
</head>
<body>
<p>De <?php echo $getal?>de dag van de week is <?php echo $antwoord?></p>
</body>
</html> | true |
f69dda072de253429d4cfaeb24f52aeebf4b1f98 | PHP | OgaBoss/algoexpert-php | /src/Implementations/DoublyLinkedList/ListNode.php | UTF-8 | 324 | 3.359375 | 3 | [] | no_license | <?php
namespace Src\Implementation\DoublyLinkedList;
class ListNode
{
public ?ListNode $next = null;
public ?ListNode $prev = null;
public int $value;
/**
* ListNode constructor.
* @param int $value
*/
public function __construct(int $value)
{
$this->value = $value;
}
} | true |
c550bf7be6c4f76cde7a35dc37abde1d00b79e6f | PHP | chewam/ExtMyAdmin | /php/json/error.php | UTF-8 | 979 | 3.234375 | 3 | [] | no_license | <?php
/**
* JSON error class
*
* @class JsonError
*/
class JsonError {
/**
* Error(s) store
*
* @property array $_error
*/
protected $_error = array();
/**
* Check if error were generated
*
* @method get_error
* @param string $msg Error message
* @param string $attr Error key attribute (default to error)
* @return string Json encoded error
*/
public function get_error($msg, $attr='msg') {
$class_name = get_class($this);
$error = array($attr => 'From "'.$class_name.'" error: "'.$msg.'"',
'success' => false);
$this->_error[] = $error;
return ($error);
}
/**
* Format error to JSON, show to stdout and exit.
*
* @method _show_error
* @param string $msg Error message
* @param string $attr Error key attribute (default to error)
*/
protected function _show_error($msg, $attr='msg') {
$json = $this->get_error($msg, $attr);
exit(JsonParser::encode($json));
}
}
| true |
365457f3d49e793352fd514953742d0e93fdebc3 | PHP | ambient-amber/docs | /symfony_twig.php | UTF-8 | 3,112 | 2.65625 | 3 | [] | no_license | <?
// ---------------------------------------------
// Inheritance
// parent
{% block stylesheets %}
<link href="{{ asset('css/main.css') }}" rel="stylesheet" />
{% endblock %}
// child
{% block stylesheets %}
{{ parent() }}
<link href="{{ asset('css/contact.css') }}" rel="stylesheet" />
{% endblock %}
// ---------------------------------------------
/* Будет искать у сущности свойство title.
* Свойства, как правило, private, но сработает метод getTitle()
*
* Если выводится свойство типа boolean, например published, то будет поиск методов isPublished(), hasPublished()
*
* Если article не объект, а массив, то твиг выведет элемент массива
* */
{{ article.title }}
// -------------------------------------------------
// Twig Extensions
// https://symfonycasts.com/screencast/symfony-doctrine/twig-extension
/* Одна из практик создавать 1 класс AppExtension, в к-м будут все кастомные функции и фильтры твига на весь проект
*
* */
> php bin/console make:twig-extension
// -------------------------------------------------
// Тернарный оператор с функцией
{{ article.publishedAt ? article.publishedAt|date('Y-m-d') : 'unpublished' }}
// -------------------------------------------------
// KnpTimeBundle - вместо даты выводит five minutes ago, two weeks ago
> composer require knplabs/knp-time-bundle
// -------------------------------------------------
/* Контейнер симфони не создает экземпляры сервисов пока они не используются.
* Если использоват hit-type в конструкторе твига
* public function __construct(MarkdownHelper $markdownHelper)
* то инстанцирование будет происходить всегда
*
* Во избежание этого создается Service Subscriber
* https://symfonycasts.com/screencast/symfony-doctrine/service-subscriber
* */
use Symfony\Component\DependencyInjection\ServiceSubscriberInterface;
use Psr\Container\ContainerInterface;
class AppExtension extends AbstractExtension implements ServiceSubscriberInterface
{
private $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public function processMarkdown($value)
{
return $this->container
->get(MarkdownHelper::class)
->parse($value);
}
public static function getSubscribedServices()
{
return [
MarkdownHelper::class,
];
}
}
// -------------------------------------------------
// Вывод списка из бд в шаблоне https://symfonycasts.com/screencast/symfony-doctrine/repository
// Экшен homepage в котроллере
// -------------------------------------------------
| true |
185a091e0a233551e617355c5974e8ed323c2c03 | PHP | allflame/vain-core | /src/Exception/ConnectionFactoryException.php | UTF-8 | 1,310 | 2.75 | 3 | [] | no_license | <?php
/**
* Vain Framework
*
* PHP Version 7
*
* @package vain-connection
* @license https://opensource.org/licenses/MIT MIT License
* @link https://github.com/allflame/vain-connection
*/
declare(strict_types = 1);
namespace Vain\Core\Exception;
use Vain\Core\Connection\Factory\ConnectionFactoryInterface;
use Vain\Core\Exception\AbstractCoreException;
/**
* Class ConnectionFactoryException
*
* @author Taras P. Girnyk <taras.p.gyrnik@gmail.com>
*/
class ConnectionFactoryException extends AbstractCoreException
{
private $connectionFactory;
/**
* ConnectionFactoryException constructor.
*
* @param ConnectionFactoryInterface $connectionFactory
* @param string $message
* @param int $code
* @param \Exception|null $previous
*/
public function __construct(
ConnectionFactoryInterface $connectionFactory,
string $message,
int $code = 500,
\Exception $previous = null
) {
$this->connectionFactory = $connectionFactory;
parent::__construct($message, $code, $previous);
}
/**
* @return ConnectionFactoryInterface
*/
public function getConnectionFactory(): ConnectionFactoryInterface
{
return $this->connectionFactory;
}
}
| true |
6ff923cb7034e4c5a89a365e5d8884fd82efc24b | PHP | dredix84/UCC_Project | /views/group_rights.php | UTF-8 | 1,594 | 2.546875 | 3 | [] | no_license | <?php
session_checkstart();
if(isset($_REQUEST["rtoken"]) && isset($_SESSION["rtoken"]) && $_SESSION["rtoken"] == $_REQUEST["rtoken"]){
$nowcat = "";
$db->query("SELECT rights FROM user_groups WHERE id = ".$_REQUEST["id"]);
$grights = $db->fetch_assoc();
if(isset($grights)){
$grights = json_decode($grights["rights"]);
}else{
$grights = array("empty", "empty");
}
//print_r($grights);
//die();
$db->query("SELECT DISTINCT category FROM rights");
?>
<form action="index.php" method="post">
<input type="submit" value="Save Rights" />
<input type="hidden" name="id" value="<?=$_REQUEST["id"]?>" />
<input type="hidden" name="action" value="save_rights" />
<input type="hidden" name="route" value="user_groups" />
<div id="accordion">
<?php
foreach($db->fetch_assoc_all() as $rcats){
//while ($rcats = $db->fetch_assoc()) {
?>
<h3><?=$rcats["category"]?></h3>
<div>
<ul>
<?php
$db->query("SELECT * FROM rights WHERE category = '".$rcats["category"]."'");
while ($right = $db->fetch_assoc()) {
$rname = $right["rname"]."_".$right["category"];
if(is_array($grights)){
$checked = (in_array($rname, $grights)?'checked="checked"':"");
}else{
$checked = "";
}
//$checked = (in_array($rname, $grights)?'checked="checked"':"");
echo "<li><input type=\"checkbox\" name=\"right[]\" value=\"".$rname."\" ".$checked." /> - ".$right["title"]."</li>";
}
?>
</ul>
</div>
<?php
}
?>
</div>
</form>
<?php }else{ ?>
<h1 style="text-align:center; color:red ">Access Denied</h1>
<?php } ?> | true |
13d283f858a33c9b5b93db074f95d562d688b97e | PHP | thrasyvoulos/doc_manager | /models/Role.php | UTF-8 | 760 | 2.65625 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
namespace app\models;
use Yii;
/**
* This is the model class for table "role".
*
* @property integer $roleid
* @property string $description
*/
class Role extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
const ROLE_ADMIN = 1;
const ROLE_USER = 2;
public static function tableName()
{
return 'role';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['description'], 'required'],
[['description'], 'string', 'max' => 50],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'roleid' => 'Roleid',
'description' => 'Description',
];
}
}
| true |
6f287f69d84ba3a1e60e47cb4c75e112ff95731f | PHP | redlinx/PHP-Web-Development | /unit06/home.php | UTF-8 | 1,766 | 2.65625 | 3 | [] | no_license | <?php
require_once("class/class_voter.php");
$voter = new voter();
$voters_list = $voter->display_voters_list();
echo "<div class ='alert alert-dark'>";
echo '<div class="row">';
echo '<div class="col-sm-12">';
echo '<h1 align="center">Account Records</h1>' ;
echo "</div>";
echo "</div>";
echo "</div>";
echo "<div align = 'center'>";
echo "<table border = 1 >";
echo "<tr>";
echo "<td> Account ID</td>";
echo "<td>Account Username</td>";
echo "<td>Lastname</td>";
echo "<td>Firstname</td>";
echo "<td>Middlename</td>";
echo "<td>Email Address</td>";
echo "<td>Year_Month</td>";
echo "<td>Update</td>";
echo "</tr>";
$total_count_number = 0;
for ($ctr=0; $ctr < count($voters_list) ; $ctr++)
{
echo "<tr>";
echo "<td align = 'Center'>".$voters_list[$ctr][0]."</td>";
echo "<td align = 'Center'>".$voters_list[$ctr][1]."</td>";
echo "<td align = 'Center'>".$voters_list[$ctr][2]."</td>";
echo "<td align = 'Center'>".$voters_list[$ctr][3]."</td>";
echo "<td align = 'Center'>".$voters_list[$ctr][4]."</td>";
echo "<td align = 'Center'>".$voters_list[$ctr][5]."</td>";
echo "<td align = 'Center'>".$voters_list[$ctr][6]."</td>";
echo '<td align = "Center"><a href="update_form.php?id='.$voters_list[$ctr][0].'
&username='.$voters_list[$ctr][1].'
&lastname='.$voters_list[$ctr][2].'
&firstname='.$voters_list[$ctr][3].'
&middlename='.$voters_list[$ctr][4].'
&email='.$voters_list[$ctr][5].'">Update</a></td>';
echo "</tr>";
$total_count_number += $voters_list[$ctr][0];
}
echo "<tr>
<td>".$total_count_number."</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>";
echo "</table>";
?> | true |
fb201004b3d76630a3631607f73960c6f1966b81 | PHP | Konzertheld/Portfolio | /theme.php | UTF-8 | 5,932 | 2.578125 | 3 | [] | no_license | <?php
/**
* Portfolio Habari Theme
* by Konzertheld
* http://konzertheld.de
*/
class Portfolio extends Theme
{
/**
* Execute on theme init to apply these filters to output
*/
public function action_init_theme()
{
$this->add_template('block.photoset_randomphotos', dirname(__FILE__) . '/block.photoset_randomphotos.php');
$this->add_template('block.singlepage_content', dirname(__FILE__) . '/block.singlepage_content.php');
Format::apply('autop', 'comment_content_out');
Format::apply('autop', 'post_content_excerpt');
$this->assign( 'multipleview', false);
$action = Controller::get_action();
if ($action == 'display_home' || $action == 'display_entries' || $action == 'search' || $action == 'display_tag' || $action == 'display_date') {
$this->assign('multipleview', true);
}
}
/**
* Create theme options
*/
public function action_theme_ui( $theme )
{
}
public function action_template_header($theme)
{
Stack::add('template_header_javascript', Site::get_url('scripts') . '/jquery.js', 'jquery');
if(!$this->multipleview && array_key_exists('photoset', Post::list_active_post_types())) {
Stack::add('template_header_javascript', $theme->get_url() . '/photoset.js', 'photoset-js', 'jquery');
}
if($this->multipleview && array_key_exists('photo', Post::list_active_post_types())) {
Stack::add('template_footer_javascript', $theme->get_url() . 'photo.js', 'photo-js', 'jquery');
}
}
/**
* Provide some blocks that make using the theme as an actual portfolio easier
*/
public function filter_block_list($blocklist = array())
{
$blocklist['singlepage_content'] = _t("Statische Seite", __CLASS__);
if(Post::type('photoset')) {
$blocklist['photoset_randomphotos'] = _t("Zufällige Fotoauswahl", __CLASS__);
}
return $blocklist;
}
/**
* Configuration for the singlepage block
*/
public function action_block_form_singlepage_content($form, $block)
{
$pageposts = Posts::get(array('content_type' => Post::type('page'), 'status' => Post::status('published')));
$pages = array();
foreach($pageposts as $page) {
$pages[$page->id] = $page->title;
}
$form->append( 'select', 'pages', __CLASS__ . '__pageblock_page', _t("Page to display:", __CLASS__));
$form->pages->size = (count($pages) > 6) ? 6 : count($pages);
$form->pages->options = $pages;
}
/**
* Configuration for the randomphotos block for the photoset content type
* The output will be done in the same style the output for the photo content type
*/
public function action_block_form_photoset_randomphotos($form, $block)
{
$form->append('text', 'photocount', __CLASS__ . '__randomphotosblock_count', _t("Number of photos to display:", __CLASS__));
}
/**
* Put the selected page into the singlepage block
*/
public function action_block_content_singlepage_content($block)
{
$block->page = Post::get(array('id' => Options::get(__CLASS__ . '__pageblock_page')));
}
/**
* Get photos from sets and supply them to the block
*/
public function action_block_content_photoset_randomphotos($block)
{
$assets = array();
$posts = Posts::get(array('content_type' => Post::type('photoset'), 'status' => Post::status('published')));
foreach($posts as $post) {
foreach(explode("\n", $post->content_media) as $asset) {
$assets[] = $asset;
}
}
$photos = array();
$photocount = Options::get(__CLASS__ . '__randomphotosblock_count', 8);
if(count($assets) >= $photocount) {
while(count($photos) < $photocount) {
// By using the output as index duplicates are impossible
$random = $assets[array_rand($assets)];
$photos[$random] = $random;
}
}
$block->photos = $photos;
}
/**
* Convert a post's tags ArrayObject into a usable list of links
* @todo this should be done with TermFormat now
* @param array $array The Tags object from a Post object
* @return string The HTML of the linked tags
*/
public function filter_post_tags_out($array)
{
foreach($array as $tag) $array_out[] = "<li><a href='" . URL::get("display_entries_by_tag", array( "tag" => $tag->term) ) . "' rel='tag'>" . $tag->term_display . "</a></li>\n";
$out = '<ul>' . implode('', $array_out) . '</ul>';
return $out;
}
/**
* Provide excerpts to avoid cutting off text when no summary is provided
**/
public function filter_post_content_excerpt($text)
{
if(strlen($text) > 280) {
// cut off everything after the word at position 280. Don't use \W so we don't cut HTML tags
$rest = preg_replace('/[ .\-]+.*/', '', substr($text, 280));
return substr($text, 0, 280) . $rest;
}
return $text;
// Alternative method: Return match[0] from /(\w+\W+){50}/ for the first 50 words
}
/**
* Get a single photo for the multiple photoset view
**/
public function filter_post_content_singlesetphoto($content, $post)
{
$assets = $post->content_media;
if(isset($assets)) {
// Revert what the plugin did
$assetarray = explode("\n", $assets);
return $assetarray[array_rand($assetarray)];
}
return '';
}
/**
* Add photosets to the output (0.9 method)
*/
public function filter_template_user_filters( $filters )
{
// Cater for the home page which uses presets as of d918a831
if ( isset( $filters['preset'] ) ) {
if(isset($filters['content_type'])) {
$filters['content_type'] = Utils::single_array( $filters['content_type'] );
}
$filters['content_type'][] = Post::type( 'photosets' );
$filters['content_type'][] = Post::type( 'entry' );
$filters['content_type'][] = Post::type( 'quote' );
} else {
// Cater for other pages like /page/1 which don't use presets yet
if ( isset( $filters['content_type'] ) ) {
$filters['content_type'] = Utils::single_array( $filters['content_type'] );
$filters['content_type'][] = Post::type( 'photoset' );
$filters['content_type'][] = Post::type( 'quote' );
}
}
return $filters;
}
}
?> | true |
685cecb3c9bd34003e259211c514e8a625c6559c | PHP | sheikhjahid/itobuz-plus | /app/Http/Controllers/RoleController.php | UTF-8 | 1,739 | 2.609375 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\RoleRequest;
use App\Contracts\RoleInterface;
class RoleController extends Controller
{
protected $roleInterface;
public function __construct(RoleInterface $roleInterface)
{
$this->roleInterface = $roleInterface;
}
public function getAllRoles()
{
$roleData = $this->roleInterface->getRoleData();
return view('Role.allRole')->with('roledata',$roleData);
}
public function getRoleById($id)
{
$roleData = $this->roleInterface->getRoleDataById($id);
return view('Role.singleRole')->with('roledata',$roleData);
}
public function createRole(RoleRequest $request)
{
$requestData = $request->all();
$checkCreatedData = $this->roleInterface->createRoleData($requestData);
if($checkCreatedData)
{
return redirect('roles')->with('create_success','Role data created successfully!!');
}
else
{
return redirect('roles')->with('create_failure','Unbale to create role data!!');
}
}
public function searchRoleUser(Request $request)
{
try
{
if($request->ajax())
{
$id = $request->get('id');
$name = $request->get('name');
$userdata = $this->roleInterface->getRoleUser($id,$name);
if(count($userdata) >= 1)
{
return $userdata;
}
else
{
return "No data found!!";
}
}
}
catch(\Exception $e)
{
return $e->getMessage();
}
}
}
| true |
7d835bb4a080f8b4a7e2543da19d65de5b01a2fe | PHP | adminlii/yt | /application/models/Service/AutomaticLetterTemplate.php | UTF-8 | 5,840 | 2.703125 | 3 | [] | no_license | <?php
class Service_AutomaticLetterTemplate extends Common_Service
{
/**
* @var null
*/
public static $_modelClass = null;
/**
* @return Table_AutomaticLetterTemplate|null
*/
public static function getModelInstance()
{
if (is_null(self::$_modelClass)) {
self::$_modelClass = new Table_AutomaticLetterTemplate();
}
return self::$_modelClass;
}
/**
* @param $row
* @return mixed
*/
public static function add($row)
{
$model = self::getModelInstance();
return $model->add($row);
}
/**
* 添加自动发信模板
* @param unknown_type $alt_row
* @param unknown_type $altc_rows
*/
public static function addTemplate($alt_row, $altc_rows){
$result = array(
"ask" => 1,
"message" => 'Create Template Success',
'errorCode' => ''
);
$db = Common_Common::getAdapter();
$db->beginTransaction();
try {
$alt_row['create_time'] = date('Y-m-d H:i:s');
$alt_id = Service_AutomaticLetterTemplate::add($alt_row);
foreach ($altc_rows as $key => $value) {
$value['alt_id'] = $alt_id;
Service_AutomaticLetterTemplateContent::add($value);
}
$db->commit();
} catch (Exception $e) {
$db->rollback();
$result = array (
"ask" => 0,
"message" => $e->getMessage (),
'errorCode' => $e->getCode ()
);
}
return $result;
}
/**
* 修改自动发信模板
* @param unknown_type $alt_id
* @param unknown_type $alt_row
* @param unknown_type $altc_rows
*/
public static function editTemplate($alt_id, $alt_row, $altc_rows){
$result = array(
"ask" => 1,
"message" => 'Update Template Success',
'errorCode' => ''
);
$db = Common_Common::getAdapter();
$db->beginTransaction();
try {
Service_AutomaticLetterTemplate::update($alt_row,$alt_id);
Service_AutomaticLetterTemplateContent::delete($alt_id,'alt_id');
foreach ($altc_rows as $key => $value) {
$value['alt_id'] = $alt_id;
Service_AutomaticLetterTemplateContent::add($value);
}
$db->commit();
} catch (Exception $e) {
$db->rollback();
$result = array (
"ask" => 0,
"message" => $e->getMessage (),
'errorCode' => $e->getCode ()
);
}
return $result;
}
/**
* @param $row
* @param $value
* @param string $field
* @return mixed
*/
public static function update($row, $value, $field = "alt_id")
{
$model = self::getModelInstance();
return $model->update($row, $value, $field);
}
/**
* @param $value
* @param string $field
* @return mixed
*/
public static function delete($value, $field = "alt_id")
{
$model = self::getModelInstance();
return $model->delete($value, $field);
}
/**
* @param $value
* @param string $field
* @param string $colums
* @return mixed
*/
public static function getByField($value, $field = 'alt_id', $colums = "*")
{
$model = self::getModelInstance();
return $model->getByField($value, $field, $colums);
}
/**
* @return mixed
*/
public static function getAll()
{
$model = self::getModelInstance();
return $model->getAll();
}
/**
* @param array $condition
* @param string $type
* @param int $pageSize
* @param int $page
* @param string $order
* @return mixed
*/
public static function getByCondition($condition = array(), $type = '*', $pageSize = 0, $page = 1, $order = "")
{
$model = self::getModelInstance();
return $model->getByCondition($condition, $type, $pageSize, $page, $order);
}
/**
* @param $val
* @return array
*/
public static function validator($val)
{
$validateArr = $error = array();
$validateArr[] = array("name" =>EC::Lang('模板名称'), "value" =>$val["template_name"], "regex" => array("require",));
$validateArr[] = array("name" =>EC::Lang('模板简称'), "value" =>$val["template_short_name"], "regex" => array("require",));
$validateArr[] = array("name" =>EC::Lang('平台'), "value" =>$val["platform"], "regex" => array("require",));
$validateArr[] = array("name" =>EC::Lang('修改人'), "value" =>$val["user_id"], "regex" => array("require","integer",));
$validateArr[] = array("name" =>EC::Lang('状态'), "value" =>$val["status"], "regex" => array("require",));
// $validateArr[] = array("name" =>EC::Lang('创建时间'), "value" =>$val["create_time"], "regex" => array("require",));
$validateArr[] = array("name" =>EC::Lang('修改时间'), "value" =>$val["lastupdate"], "regex" => array("require",));
return Common_Validator::formValidator($validateArr);
}
/**
* 获得模板相关的插入变量
*/
public static function getTemplateOperate(){
$con = array(
'operate_key'=>'letter',
);
$result = Service_MessageTemplateOperate::getByCondition($con);
return $result;
}
/**
* @param array $params
* @return array
*/
public function getFields()
{
$row = array(
'E0'=>'alt_id',
'E1'=>'template_name',
'E2'=>'template_short_name',
'E3'=>'company_code',
'E4'=>'platform',
'E5'=>'user_id',
'E6'=>'status',
'E7'=>'create_time',
'E8'=>'lastupdate',
'E9'=>'language',
);
return $row;
}
} | true |
39bec04f2c07188c3ecbb754a04a548f0f6e64f3 | PHP | sketchytech/json-book | /php/indexing_in_progress/chapter-parser.php | UTF-8 | 3,807 | 2.546875 | 3 | [] | no_license | <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
// Currently shows all notes and references
// TODO: show one box that swipes to reveal notes, refs, user notes
// TODO: reveal only notes and references for single paragraph by using this.id
$(document).ready(function(){
$a=0;
$(".paragraph").click(function(){
if ($a==0) {
$(".notehidden").slideDown(600,'linear');
$(".refhidden").slideDown(600,'linear');
$(".anchorhidden").slideDown(600,'linear');
$a=1;}
else {
$(".notehidden").slideUp(600,'linear');
$(".refhidden").slideUp(600,'linear');
$(".anchorhidden").slideUp(600,'linear');
$a=0;}
});
});
</script>
<div style="margin-top:100px">
<?php
// TODO: Add listening and storage side of user notes
include_once('readjson.php');
global $itemNumber;
$itemNumber=1;
$linkedItemNumber=6;
global $para;
$para=new paragraph; // create new paragraph object from
// Chapter
$chapter_json = file_get_contents("burn.json");
$chapter = json_decode($chapter_json);
processObject($chapter,$linkedItemNumber);
// After chapter has been processed create note list and print
global $notes; // makes notes globally available to all functions
$notes=$para->returnNotes(); // create the array of notes by importing the one created in readjson.php
printNotes(); // notes are printed
function processObject($chapter,$linkedItemNumber) {
global $itemNumber;
if(is_object($chapter)){
foreach($chapter as $key=>$value)
{
// if($itemNumber==$linkedItemNumber) echo "<a id='".$itemNumber."'></a>";
$title_tags = array("h1","h2","h3","h4","h5");
if(in_array($key, $title_tags)){
echo "<".$key.">".$value."</".$key.">";
echo "<div id='".$itemNumber."' style='display:none; background-color:lightyellow; color:red; padding:10px;' class='anchorhidden'><p>".$itemNumber." | <span style='color:black;' contenteditable='true'>Tap to write notes here.</span></p></div>";
}
if($key=="blockquote") {
echo "<".$key.">";
// make sure blockquotes handle italics and citations correctly
}
// Confirm that chapter is array
if (is_array($value)) {
global $itemNumber;
$numberOfItems=count($value);
$i=0;
while ($i<$numberOfItems){
//arrayProcess($value);
if(is_string($value[$i])) {
echo $value[$i];
}// Part of the error testing
elseif(is_array($value[$i])) arrayProcess($value[$i],$linkedItemNumber);
elseif(is_object($value[$i])) bounceObject($value[$i],$linkedItemNumber);
$i++;
}
}
if($key=="blockquote") {echo "</".$key.">"; // this handles blockquotes that come between paragraphs but blockquotes within paragraphs must also be handled, because those are correct
// Add user notes
addUserNotes();
}
}
}
}
function arrayProcess($array,$linkedItemNumber){
global $itemNumber;
global $notes;
global $para;
$para->returnParagraph($array,$itemNumber);
//else processObject($array,$linkedItemNumber);
// Add user notes
addUserNotes();
$itemNumber++;
}
function bounceObject($object,$linkedItemNumber) {
global $itemNumber;
processObject($object,$linkedItemNumber);
$itemNumber++;
}
function printNotes(){
global $notes;
if (count($notes)>0){
if (count($notes)==1) echo "<h2>Note</h2>";
else echo "<h2>Notes</h2>";
echo "<ol>";
$i=0;
while($i<count($notes)){
$note_number=$i+1;
echo "<li id='note".$note_number."'>".$notes[$i]." <a href='#ref".$note_number."'>[^]</a></li>";
$i++;
}
echo "</ol>";
}
}
function addUserNotes() {
// Adds user notes
global $itemNumber;
echo "<div id='user".$itemNumber."' style='display:none; background-color:lightyellow; color:red; padding:10px;' class='anchorhidden'><p>".$itemNumber." | <span style='color:black;' contenteditable='true'>Tap to write notes here.</span></p></div>";
}
?>
</div>
<script type="text/javascript">
//window.location.hash="20";
</script>
| true |
8929a0569948305c051271bfed4a8fcc4990a979 | PHP | sky8652/laravel-cms | /app/Model/Admin/Admin.php | UTF-8 | 3,106 | 2.546875 | 3 | [] | no_license | <?php
namespace App\Model\Admin;
use App\Traits\ModelTrait;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;
class Admin extends Authenticatable
{
use Notifiable;
use ModelTrait;
use SoftDeletes;
protected $dates=['deleted_at'];
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* Notes:添加管理员(事物)
* User: 你猜呢
* Date: 2019/5/25
* Time: 10:36
* @param $data
* @param $role
* @return bool
*/
public function addAdminAndRole($data,$role)
{
DB::beginTransaction();
try{
$addAdminResult = $this->create($data);
if (!$addAdminResult) {
DB::rollback();
return false;
}
$id = DB::getPdo()->lastInsertId();
$roles = array();
foreach ($role as $v)
{
$roles[]=array('admin_id'=>$id,'role_id'=>$v);
}
$addAdminRoleResult = RoleAdmin::insert($roles);
if(!$addAdminRoleResult){
DB::rollback();
return false;
}
DB::commit();
return true;
} catch (\Exception $e){
DB::rollback();
return false;
}
}
/**
* Notes:管理员修改
* User: 你猜呢
* Date: 2019/5/25
* Time: 14:03
* @param $id
* @param $data
* @param $role
* @return bool
*/
public function updateAdminAndRole($id,$data,$role)
{
DB::beginTransaction();
try{
$where[]=['id','=',$id];
$updateAdminResult = $this->where($where)->update($data);
if (!$updateAdminResult) {
DB::rollback();
return false;
}
//删除用户角色
$delAdminRoles = RoleAdmin::where('admin_id','=',$id)->delete();
if (!$delAdminRoles) {
DB::rollback();
return false;
}
//重新添加角色
$roles = array();
foreach ($role as $v)
{
$roles[]=array('admin_id'=>$id,'role_id'=>$v);
}
$addAdminRoleResult = RoleAdmin::insert($roles);
if(!$addAdminRoleResult){
DB::rollback();
return false;
}
DB::commit();
return true;
} catch (\Exception $e){
DB::rollback();
return false;
}
}
public function getListByPage($where=[],$num=10)
{
return $this->withTrashed()->where($where)->paginate($num);
}
public function restoreOne($where)
{
return $this->withTrashed()->where($where)->first()->restore();
}
}
| true |
464b71fa62ecac558f2734430cf71b341a897d88 | PHP | pmill/php-plesk | /src/pmill/Plesk/DeleteEmailAddress.php | UTF-8 | 1,373 | 2.59375 | 3 | [
"BSD-2-Clause"
] | permissive | <?php
namespace pmill\Plesk;
class DeleteEmailAddress extends BaseRequest
{
/**
* @var string
*/
public $xml_packet = <<<EOT
<?xml version="1.0"?>
<packet version="1.6.3.0">
<mail>
<remove>
<filter>
<site-id>{SITE_ID}</site-id>
<name>{USERNAME}</name>
</filter>
</remove>
</mail>
</packet>
EOT;
/**
* @var array
*/
protected $default_params = [
'email' => null,
];
/**
* @param array $config
* @param array $params
* @throws ApiRequestException
*/
public function __construct($config, $params)
{
parent::__construct($config, $params);
if (!filter_var($this->params['email'], FILTER_VALIDATE_EMAIL)) {
throw new ApiRequestException("Invalid email submitted");
}
list($username, $domain) = explode("@", $this->params['email']);
$request = new GetSite($config, ['domain' => $domain]);
$info = $request->process();
$this->params['site_id'] = $info['id'];
$this->params['username'] = $username;
}
/**
* @param $xml
* @return bool
*/
protected function processResponse($xml)
{
if ($xml->mail->remove->result->status == 'error') {
return false;
}
return true;
}
}
| true |
e80577bd8c1c539f8a85d367a69c11df6ce03325 | PHP | tomaz/PieCrust | /tests/libs/PHPUnitWebReport/PHPUnit/WebReport/Dashboard.php | UTF-8 | 7,662 | 2.828125 | 3 | [
"Apache-2.0"
] | permissive | <?php
/**
* The main file for PHPUnit-WebReport.
*/
require_once 'Report.php';
/**
* The dashboard for a PHPUnit test run.
*/
class PHPUnit_WebReport_Dashboard
{
public $report;
public $errors;
/**
* Runs PHPUnit on the given directory.
*/
public static function run($testsDir, $logFile)
{
$phpUnitExe = self::getPhpUnitExe();
$logFile = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $logFile);
$command = $phpUnitExe . ' --log-junit "' . $logFile . '" "' . $testsDir . '"';
$output = array();
exec($command, $output);
return $output;
}
protected static function findExe($exeName)
{
$envPaths = explode(PATH_SEPARATOR, getenv('PATH'));
foreach ($envPaths as $p)
{
$tentative = rtrim($p, '/\\') . DIRECTORY_SEPARATOR . $exeName;
if (file_exists($tentative))
return $tentative;
}
return false;
}
protected static function getPhpUnitExe()
{
// Find 'phpunit' in the PATH.
$phpUnitExe = self::findExe('phpunit'); // on Windows, this should be 'phpunit.bat' but since both exist,
// and Windows runs .bat without extension, it's all good.
if (!$phpUnitExe)
{
// Can't find phpunit. Use our own runner (which is a copy of phpunit's short code.).
// ...but we still have to find the PHP executable.
$phpExeName = 'php';
if (strpos(PHP_OS, 'Windows') == 0)
$phpExeName = 'php.exe';
$phpExe = self::findExe($phpExeName);
if (!$phpExe and isset($_SERVER['PHPRC']))
{
$tentative = $_SERVER['PHPRC'] . DIRECTORY_SEPARATOR . $phpExeName;
if (file_exists($tentative))
$phpExe = $tentative;
}
if (!$phpExe and strpos(PHP_OS, 'Windows') === false)
{
$tentative = '/usr/bin/php';
if (file_exists($tentative))
$phpExe = $tentative;
}
if (!$phpExe)
{
throw new Exception("Can't find the PHP executable anywhere!");
}
try
{
$runnerCode = '<?php'.PHP_EOL.
'set_include_path("'.addcslashes(get_include_path(), '\\"').'");'.PHP_EOL.
<<<'EOD'
if (strpos('/usr/bin/php', '@php_bin') === 0) {
set_include_path(dirname(__FILE__) . PATH_SEPARATOR . get_include_path());
}
require 'PHPUnit/Autoload.php';
PHPUnit_TextUI_Command::main();
EOD;
$phpUnitExe = tempnam(sys_get_temp_dir(), 'phpunit');
file_put_contents($phpUnitExe, $runnerCode);
$phpUnitExe = '"'.$phpExe .'" "'.$phpUnitExe.'"';
}
catch (Exception $e)
{
throw new Exception("Couldn't find PHPUnit executable ".PHPUNIT." and failed to create our own: ".$e->getMessage());
}
}
return $phpUnitExe;
}
/**
* Creates a new instance of PHPUnit_WebReport_Dashboard.
*/
public function __construct($logFile, $format = 'xml')
{
$logFile = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $logFile);
switch ($format)
{
case 'xml':
$this->report = $this->parseXmlLog($logFile);
break;
default:
throw new Exception('Not implemented.');
}
}
/**
* Gets the CSS code for the report, for including in a page's <head> section.
*/
public function getReportCss()
{
return file_get_contents(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'phpunit_report.css');
}
/**
* Displays the test run report.
*/
public function display($headerLevel = 2)
{
if ($this->errors === null)
{
echo '<div class="test-report">';
// Summary of the test run.
echo '<div class="test-report-summary">';
$this->displayStats($this->report);
echo '</div>';
// Details on test suites that failed.
foreach ($this->report->testSuites as $testsuite)
{
$this->displayTestSuite($testsuite, true, $headerLevel);
}
echo '</div>';
}
else
{
echo '<div class="test-report">';
echo '<h' . $headerLevel . '>Error reading PHPUnit log</h' . $headerLevel . '>';
foreach ($this->errors as $error)
{
echo '<p>' . $error . '</p>';
}
echo '</div>';
}
}
protected function displayStats($stats)
{
echo '<div class="stats';
if ($stats->hasErrors() or $stats->hasFailures()) echo ' fail';
else echo ' success';
echo '">';
$passCount = $stats->testCount() - $stats->errorCount() - $stats->failureCount();
echo $passCount . '/' . $stats->testCount() . ' test cases complete: ' .
'<strong>' . $passCount . '</strong> passes, ' .
'<strong>' . $stats->failureCount() . '</strong> fails and ' .
'<strong>' . $stats->errorCount() . '</strong> errors.';
echo '</div>';
}
protected function displayTestSuite($testsuite, $skipSuccessful, $headerLevel)
{
if ($skipSuccessful and !$testsuite->hasErrors() and !$testsuite->hasFailures())
{
return;
}
echo '<div class="test-suite">';
echo '<h' . $headerLevel . '>' . $testsuite->name . '</h' . $headerLevel . '>';
if (!$skipSuccessful)
{
echo '<div class="test-suite-stats">';
$this->displayStats($testsuite);
echo '</div>';
}
foreach ($testsuite->testSuites as $subTestsuite)
{
$this->displayTestSuite($subTestsuite, $skipSuccessful, $headerLevel + 1);
}
foreach ($testsuite->testCases as $testcase)
{
if ($skipSuccessful and !$testcase->hasFailures() and !$testcase->hasErrors())
{
continue;
}
echo '<div class="test-case">';
if ($testcase->hasErrors() or $testcase->hasFailures())
{
echo '<span class="fail">Fail</span>: ' . $testcase->name;
if (count($testcase->failures) > 0)
{
echo '<div class="failures">';
foreach ($testcase->failures as $failure)
{
echo '<pre>' . htmlentities($failure) . '</pre>';
}
echo '</div>';
}
if (count($testcase->errors) > 0)
{
echo '<div class="errors">';
foreach ($testcase->errors as $error)
{
echo '<pre>' . htmlentities($error) . '</pre>';
}
echo '</div>';
}
}
else
{
echo '<span class="success">Success</span>: ' . $testcase->name;
}
echo '</div>';
}
echo '</div>';
}
protected function parseXmlLog($logFile)
{
$report = new PHPUnit_WebReport_Report();
libxml_use_internal_errors(true);
$results = simplexml_load_file($logFile);
if (!$results)
{
$this->errors = array();
foreach (libxml_get_errors() as $error)
{
$this->errors[] = $error->message . " (in '" . $error->file . "', line " . $error->line . ", column " . $error->column . ")";
}
libxml_clear_errors();
}
else
{
foreach ($results->testsuite as $ts)
{
$report->testSuites[] = $this->parseXmlTestSuite($ts);
}
}
return $report;
}
protected function parseXmlTestSuite($ts)
{
$testsuite = new PHPUnit_WebReport_TestSuite();
$testsuite->name = $ts['name'];
$testsuite->stats['tests'] = intval($ts['tests']);
$testsuite->stats['assertions'] = intval($ts['assertions']);
$testsuite->stats['failures'] = intval($ts['failures']);
$testsuite->stats['errors'] = intval($ts['errors']);
$testsuite->stats['time'] = floatval($ts['time']);
foreach ($ts->testsuite as $subTs)
{
$testsuite->testSuites[] = $this->parseXmlTestSuite($subTs);
}
foreach ($ts->testcase as $tc)
{
$testcase = new PHPUnit_WebReport_TestCase();
$testcase->name = $tc['name'];
foreach ($tc->failure as $f)
{
$testcase->failures[] = strval($f);
}
foreach ($tc->error as $e)
{
$testcase->errors[] = strval($e);
}
$testsuite->testCases[] = $testcase;
}
return $testsuite;
}
}
| true |
33bcd11d98d87ff4a3b98d60e53b3072465d3fbb | PHP | cyrnne/Magiting | /adminHats.php | UTF-8 | 22,775 | 2.59375 | 3 | [] | no_license | <?php
include('includes/session.php');
if($_REQUEST['action']=="Add")
{
try {
include('includes/indexdb.php');
$prodID = rand(1000,10000);
$prodName = $_POST['prodName'];
$prodDesc = $_POST['prodDesc'];
$prodPrice = $_POST['prodPrice'];
$prodStk = $_POST['prodStk'];
$target_dir = "products/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
$getImgName = basename($_FILES["fileToUpload"]["name"]);
$nameImg = "products/".$getImgName;
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
// echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
$sql = "INSERT INTO tblproducts (prodID, prodName ,prodDesc, prodPrice, prodStk,prodCat, prodImg) VALUES ('$prodID','$prodName','$prodDesc','$prodPrice','$prodStk','Hats','$nameImg')";
if($conn->query($sql) === TRUE) {
// echo "Evaluation Submitted";
echo "<script>alert('Product added')</script>";
}
else{
echo "<script>alert('Product not added')</script>";
}
}
else {
echo "Sorry, there was an error uploading your file.";
}
}
}//catch exception
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
}
else if ($_REQUEST['action']=="Save"){
include('includes/indexdb.php');
$prodID = $_POST['prodID'];
$prodName = $_POST['prodName'];
$prodDesc = $_POST['prodDesc'];
$prodPrice = $_POST['prodPrice'];
$prodStk = $_POST['prodStk'];
$sql = "UPDATE tblproducts SET prodName='$prodName',prodDesc='$prodDesc',prodPrice='$prodPrice',prodStk='$prodStk' WHERE prodID='$prodID'";
if($conn->query($sql) === TRUE) {
echo "<script>alert('Item Updated')</script>";
}
else{
echo "<script>alert('Item not Updated')</script>";
}
}
else if ($_REQUEST['action']=="Delete"){
$prodID = $_POST['prodID'];
$sql = "Delete From tblproducts where prodID ='$prodID'";
if($conn->query($sql) === TRUE) {
echo "<script>alert('Item Deleted')</script>";
}
else{
echo "<script>alert('Item not Deleted')</script>";
}
}
?>
<html>
<head>
<link rel="shortcut icon" href="assets/img/logowhite.png" />
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
<title>Magiting | Home</title>
<link rel="stylesheet" href="assets/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="assets/css/STYLES.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body style="color: rgb(255,255,255);">
<h1 class="home-heading" style="color: rgb(255,255,255);"><span class="text-center home-heading-upper" style="color: rgb(116,116,116);font-size: 30px;">A Baybayin Movement</span><span class="text-center home-heading-lower" style="font-size: 120px;">MAGITING</span></h1>
<nav class="navbar navbar-light navbar-expand-lg bg-white"
id="mainNav" style="background-color: #ffffff;">
<div class="container-fluid"><button data-toggle="collapse" data-target="#navcol-1" class="navbar-toggler"><span class="navbar-toggler-icon"></span></button>
<div class="collapse navbar-collapse" id="navcol-1" style="margin-left: 210px;">
<ul class="nav navbar-nav mx-auto" style="margin: 0px;padding: 0px;margin-left: 210px;">
<li role="presentation" class="nav-item" style="margin-left: 0px;"><a href="Home.html" class="nav-link">MANAGE PRODUCTS</a></li>
<li role="presentation" class="nav-item"><a href="AboutUs.html" class="nav-link">ACCOUNTS</a></li>
</ul><?php echo $menuBar; ?></div>
</div>
</nav>
<section class="page-section about-heading">
<div class="about-heading-content">
<div class="row" style="margin-right: 0px;margin-left: 0px;">
<div class="col-9 text-center mx-auto" style="background-color: #ffffff;color: rgb(0,0,0);opacity: 1;padding-bottom:20px; margin-top: 50px;margin-bottom: 50px;">
<h1 class="admin-heading" style="margin-top: 25px;margin-bottom: 25px;">MANAGE PRODUCTS</h1>
<div class="dropdown"><button class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-expanded="false" type="button" style="margin-right: 0px;">PRODUCTS</button>
<div role="menu" class="dropdown-menu"><a role="presentation" href="ADMIN.php" class="dropdown-item">Tees</a><a role="presentation" href="adminHats.php" class="dropdown-item">Hats</a></div>
</div>
<!-- Table Dynamic -->
<div class="col-md-12" style="padding-left: 80px;padding-right: 80px;padding-top:30px;">
<!-- Website Overview-->
<div class="panel panel-default">
<div class="panel-heading main-color-bg">
<h3 class="panel-title">Hats</h3>
<button class="btn btn-light action-button" id="addBtn" style="color: white; background-color: black; border: none; float: left; margin-bottom: 10px;" data-toggle="modal" data-target="#addUser" onclick="showAddBtn();">Add Item</button>
</div>
<div class="panel-body">
<br>
<div class="table-responsive">
<table class="table table-striped table-hover" id="prodTbl">
<thead class="thead-dark" style="color: black; text-align: center;">
<tr>
<td>Product ID</td>
<td>Name</td>
<td>Description</td>
<td>Price</td>
<td>Stock</td>
<td>Category</td>
<td>Image</td>
</tr>
</thead>
<?php
include("includes/indexdb.php");
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT * FROM tblproducts where prodCat like 'Hats'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
?>
<tr style="text-align: center; color: black;">
<td data-label="ID"><?php echo $row['prodID']?></td>
<td data-label="Name"><?php echo $row['prodName']?></td>
<td data-label="Description"><?php echo $row['prodDesc']?></td>
<td data-label="Price"><?php echo $row['prodPrice']?></td>
<td data-label="Stock"><?php echo $row['prodStk']?></td>
<td data-label="Category"><?php echo $row['prodCat']?></td>
<td data-label="Image"><img src="<?php echo $row['prodImg']?>" style="height: 50px; width: 60px;"></td>
</tr>
<?php
}
}
?>
</table>
</div>
</div>
</div>
</div>
<!-- End of Table -->
</div>
</div>
</div>
</section>
<!--FOOTER-->
<div class="footer-dark" style="padding-top: 40px;padding-bottom: 30px;background-color: #000000;">
<footer>
<div class="container">
<div class="row">
<div class="col-sm-6 col-md-3 text-left item">
<h3>CUSTOMER SERVICE</h3>
<ul>
<li><a href="#" data-toggle="modal" data-target="#myModalsize">Size Guide<br /></a></li>
<!--SIZE GUIDE MODAL-->
<!-- The Modal -->
<div class="modal" id="myModalsize">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header" style="color: black;">
<h4 class="modal-title">Size Guide</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="sizemodal-body" style="color: black;">
<p style="color: black; text-align: justify;">
<center><img class="size-guide" src="assets/img/size chart.jpg" style="width: 400px;"/></center>
</p>
</div>
</div>
</div>
</div>
<li><a href="#" data-toggle="modal" data-target="#myModalchart">Color Chart<br /></a></li>
<!--COLOR CHART MODAL-->
<!-- The Modal -->
<div class="modal" id="myModalchart">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header" style="color: black;">
<h4 class="modal-title">Color Chart</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="chartmodal-body" style="color: black;">
<p style="color: black; text-align: justify;">
<center><img class="chart-guide" src="assets/img/color.jpg" style="width: 400px;"/></center>
</p>
</div>
</div>
</div>
</div>
<li><a href="#" data-toggle="modal" data-target="#myModalcontact">Contact Us<br /></a></li>
<!--CONTACT MODAL-->
<!-- The Modal -->
<div class="modal" id="myModalcontact">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header" style="color: black;">
<h4 class="modal-title">Contact Us</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="contactmodal-body" style="color: black; font-family: century gothic; margin-top:80px; font-size:15px; height:2.5in;">
<div class="row text-center m-auto icon-features" style="width: 380px;">
<div class="col-4 icon-feature"><i class="fa fa-map-marker"></i>
<p><b>Location</b></p>
<p>Bazaars are To Be Announced</p>
</div>
<div class="col-4 icon-feature"><i class="fa fa-phone"></i>
<p><b>Call Us</b></p>
<p>+63 956 153 8775<br /></p>
</div>
<div class="col-4 icon-feature"><i class="fa fa-envelope"></i>
<p><b>Email Us</b></p>
<p>magitingph @gmail.com<br /></p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-sm-6 col-md-3 text-left item">
<h3>ABOUT US</h3>
<ul>
<li><a href="ABOUTUS.php">Mission Vision</a></li>
<li><a href="ABOUTUS.php">Owners</a></li>
<li></li>
</ul>
</div>
<div class="col-md-6 text-left item text">
<h3>MAGITING PH</h3>
<p>A Baybayin movement that aims to parttake in the co-creation <br />of a generation of Active Participation and Appreciation for the <br />Filipino Identity.<br /><br /></p>
</div>
<div class="col item social"><p style="color: grey; padding-bottom: 5px;">CHECK US OUT ON<br></p><a href="https://www.facebook.com/MagitingPH" target="_blank"><img src="assets/img/icofb.png" style="width: 30px">
<i class="icon ion-social-facebook"></i></a><a href="https://twitter.com/Magitingph" target="_blank"><img src="assets/img/icotwit.png" style="width: 30px">
<i class="icon ion-social-twitter"></i></a><a href="https://www.instagram.com/magitingph" target="_blank"><img src="assets/img/icoig.png" style="width: 30px">
<i class="icon ion-social-instagram"></i></a></div>
</div><img src="assets/img/logowhite.png" class="d-flex d-xl-flex justify-content-center mx-auto justify-content-xl-center" style="width: 50px;padding-top: 30px;" />
<p class="copyright" style="padding-top: 10px;">Magiting PH © 2017</p>
</div>
</footer>
</div>
</body>
</header>
<!-- Modals -->
<!-- Add Page -->
<div class="modal fade" id="addUser" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content" style="color: black; text-align: center;">
<form name="myform" id="myform" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" enctype="multipart/form-data">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Add Item</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close" onclick="clearText();"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<div class="form-group">
<label>Product ID</label>
<input type="text" id="prodID" name="prodID" class="form-control" form="myform" readonly>
</div>
<div class="form-group">
<label>Product Name</label>
<input type="text" id="prodName" name="prodName" class="form-control" form="myform" required>
</div>
<div class="form-group">
<label>Description</label>
<input type="text" id="prodDesc" name="prodDesc" class="form-control" form="myform" required>
</div>
<div class="form-group">
<label>Price</label>
<input type="text" id="prodPrice" name="prodPrice" class="form-control" form="myform" required>
</div>
<div class="form-group">
<label>Stock</label>
<input type="text" id="prodStk" name="prodStk" class="form-control" form="myform" required>
</div>
<div class="form-group">
<label>Select image to upload</label>
<input type="file" name="fileToUpload" id="fileToUpload">
</div>
<div class="form-group">
<label>Category</label>
<input type="text" id="prodCat" name="prodCat" class="form-control" form="myform" value="Hats" readonly>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" id="closeBtn" onclick="clearText();" data-dismiss="modal" style=" float: right;" >Close</button>
<button type="submit" class="btn btn-light action-button" value="Save" id="saveBtn" name="action" style=" float: right; margin-right: 5px; display: none;">Save changes</button>
<button type="submit" class="btn btn-light action-button" value="Add" id="addbtn" name="action" style=" float: right; margin-right: 5px; display: none;">Add Item</button>
<button type="button" class="btn btn-light action-button" id="delBtn" onclick="clickDel()" style=" float: right;">Delete</button>
<p id="confirmationTag" style="margin-right: 5px; display: none; float: right;">Are you sure?</p>
<button type="submit" class="btn btn-light action-button" id="yesBtn" name="action" value="Delete" style="display: none; float: right; margin-right: 5px;">Yes</button>
<button type="button" onclick="clickNo();" class="btn btn-light action-button" id="noBtn" style="display: none; float: right; margin-right: 5px;">No</button>
</div>
</form>
</div>
</div>
</div>
<script>
$('#upload').on('click', function() {
var file_data = $('#sortpicture').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
$.ajax({
url: 'includes/upload.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
alert(php_script_response); // display response from the PHP script, if any
}
});
});
</script>
<script>
function clickDel(){
var delBtn = document.getElementById('delBtn');
var saveBtn = document.getElementById('saveBtn');
var clearBtn = document.getElementById('closeBtn');
delBtn.style.display = "none";
saveBtn.style.display = "none";
clearBtn.style.display = "none";
var yesBtn = document.getElementById('yesBtn');
var noBtn = document.getElementById('noBtn');
var confirmationTag = document.getElementById('confirmationTag');
noBtn.style.display = "block";
yesBtn.style.display = "block";
confirmationTag.style.display = "block";
}
function clickNo(){
var delBtn = document.getElementById('delBtn');
var saveBtn = document.getElementById('saveBtn');
var clearBtn = document.getElementById('closeBtn');
delBtn.style.display = "block";
saveBtn.style.display = "block";
clearBtn.style.display = "block";
delBtn.style.float = "right";
saveBtn.style.float = "right";
clearBtn.style.float = "right";
var yesBtn = document.getElementById('yesBtn');
var noBtn = document.getElementById('noBtn');
var confirmationTag = document.getElementById('confirmationTag');
noBtn.style.display = "none";
yesBtn.style.display = "none";
confirmationTag.style.display = "none";
}
</script>
<script>
var table = document.getElementById('prodTbl');
for(var i = 1; i < table.rows.length; i++)
{
table.rows[i].onclick = function()
{
//rIndex = this.rowIndex;
var addBtn = document.getElementById('addBtn');
addBtn.click();
hideAddBtn();
showSaveBtn();
document.getElementById("prodID").value = this.cells[0].innerHTML;
document.getElementById("prodName").value = this.cells[1].innerHTML;
document.getElementById("prodDesc").value = this.cells[2].innerHTML;
document.getElementById("prodPrice").value = this.cells[3].innerHTML;
document.getElementById("prodStk").value = this.cells[4].innerHTML;
};
}
</script>
<script>
function clearText(){
document.getElementById("prodID").value = "";
document.getElementById("prodName").value = "";
document.getElementById("prodDesc").value = "";
document.getElementById("prodPrice").value = "";
document.getElementById("prodStk").value = "";
clickNo();
}
</script>
<script type="text/javascript">
function showAddBtn(){
hideSaveBtn();
var x = document.getElementById("addbtn");
x.style.display = "block";
}
function hideAddBtn(){
var x = document.getElementById("addbtn");
x.style.display = "none";
}
function showSaveBtn(){
var x = document.getElementById("saveBtn");
x.style.display = "block";
}
function hideSaveBtn(){
var x = document.getElementById("saveBtn");
x.style.display = "none";
}
</script>
</body>
</html> | true |
dd114049bc1ee2b50dfc090246f25566e8fb35f0 | PHP | benrowe/formatter | /tests/FormatterProviderTest.php | UTF-8 | 1,681 | 2.546875 | 3 | [
"MIT"
] | permissive | <?php
use Benrowe\Formatter\Formatter;
use Benrowe\Formatter\Tests\Examples\NumberSampleProvider;
use Benrowe\Formatter\Tests\Examples\SampleProvider;
// use stdObject;
/**
* Test sample providers
*/
class FormatterProviderTest extends PHPUnit_Framework_TestCase
{
/**
* @var Formatter
*/
private $formatter;
public function setUp()
{
$this->formatter = new Formatter([
'number' => new NumberSampleProvider,
'sample' => 'Benrowe\Formatter\Tests\Examples\SampleProvider'
]);
}
public function testConstructor()
{
$formatter = new Formatter([
'number' => new NumberSampleProvider,
'sample' => 'Benrowe\Formatter\Tests\Examples\SampleProvider'
]);
$this->assertSame([
'number.number',
'number.unsigned',
'sample.return',
'sample.rot',
'sample.case'
], $formatter->formats());
$this->assertTrue($formatter->hasFormat('number.unsigned'));
}
public function testInvalidFormatter()
{
$this->setExpectedException('InvalidArgumentException');
$formatter = new Formatter([
'fake' => new stdClass,
]);
}
public function testInvalidFormatArray()
{
$this->setExpectedException('InvalidArgumentException');
$this->formatter->format('value', 'number.');
}
public function testFormat()
{
$this->assertSame($this->formatter->format('foo', 'sample.return'), 'foo');
// $this->assertSame($this->formatter->format('foo', ['sample.case', SampleProvider::CASE_UPPER]), 'FOO');
}
}
| true |
d5092eac399f2d81ffd1d21a8265ba0b48caa852 | PHP | dukekn/clpngs | /core/factory/DataFactory.php | UTF-8 | 2,862 | 2.796875 | 3 | [] | no_license | <?php
namespace App\Core\Factory;
abstract class DataFactory
{
public static function getData(array $file): array
{
$values = array_map('str_getcsv', file($file['tmp_name']));
$keys = ['cust_id', 'vat_id', 'doc_id', 'type', 'parent_doc_id', 'currency', 'amount'];
$result = array();
foreach ($values as $value) {
if ((isset($result[$value[0]]))) {
array_push($result[$value[0]], array_combine($keys, $value));
} else {
$result[$value[0]] = [array_combine($keys, $value)];
}
}
return $result;
}
public static function setException($ex)
{
print('<span class="exception"><b>Exception:</b> ' . $ex->getMessage()."</span>");
}
public static function getCurrencie(array $post): array
{
$pair_codes = json_decode($post['pair_code'], true);
$pair_rates = json_decode($post['pair_rate'], true);
return [
"default" => [filter_var(strtoupper($post['currency_main']), FILTER_SANITIZE_STRING) => 1],
'output' => filter_var(strtoupper($post['currency_output']), FILTER_SANITIZE_STRING),
'rates' => array_combine(array_map('strtoupper', $pair_codes), $pair_rates)
];
}
public static function exchange(array $rates, float $amount, string $currency_from): string
{
$currency_output = $rates['output'];
try {
//is default currency from?
if ($currency_from == array_keys($rates['default'])[0]) {
if (in_array($currency_output, array_keys($rates['rates']))) {
$rate = $rates['rates'][$currency_output];
return round($amount * $rate, 2) ;
}
} else {
if (in_array($currency_from, array_keys($rates['rates']))) {
$rate_default = array_values($rates['default'])[0];
$rate_current = $rates['rates'][$currency_from]?? null;
$rate_output = $rates['rates'][$currency_output]?? null;
if(!isset($rate_current))
{
throw new \Exception($currency_from . ' is not defined or unsupported!');
}
if(!isset($rate_output))
{
throw new \Exception($currency_output . ' is not defined or unsupported!');
}
return round(($amount / $rate_current) * $rate_output, 2);
} else {
// return $currency_from.' is not defined!';
throw new \Exception($currency_from . ' is not defined!');
}
}
} catch (\Exception $e) {
throw new\Exception($e->getMessage());
}
}
} | true |
6a3f5756c5f7c03a541582f116a610b3291b959f | PHP | Kwadz/poker-hand-evaluator | /app/src/Controller/DefaultController.php | UTF-8 | 2,403 | 2.5625 | 3 | [] | no_license | <?php
namespace App\Controller;
use App\Form\FileUploadType;
use App\Service\Counter;
use App\Service\FileParser;
use App\Service\FileUploader;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class DefaultController extends AbstractController
{
private FileParser $fileParser;
private Counter $playerWinsCounter;
/**
* DefaultController constructor.
*
* @param FileParser $fileParser
* @param Counter $playerWinsCounter
*/
public function __construct(FileParser $fileParser, Counter $playerWinsCounter)
{
$this->fileParser = $fileParser;
$this->playerWinsCounter = $playerWinsCounter;
}
/**
* @Route("/", name="app_file_upload")
* @param Request $request
* @param FileUploader $file_uploader
* @param EntityManagerInterface $entityManager
* @return Response
*/
public function indexAction(Request $request, FileUploader $file_uploader, EntityManagerInterface $entityManager
) {
$form = $this->createForm(FileUploadType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$file = $form['upload_file']->getData();
if ($file) {
$file_name = $file_uploader->upload($file);
if (null !== $file_name) // for example
{
$directory = $file_uploader->getTargetDirectory();
$fullPath = $directory.'/'.$file_name;
$game = $this->fileParser->parse($fullPath);
$game->setGameFilename($fullPath);
$entityManager->persist($game);
return $this->render('result.html.twig', [
'player1WinsCount' => $this->playerWinsCounter->countPlayer1Wins($game->getRounds())
]);
} else {
$this->addFlash('error', 'The file could\'nt be uploaded!');
}
}
}
return $this->render(
'upload.html.twig',
[
'form' => $form->createView(),
]
);
}
}
| true |
015fc7da0a182ca663bc40fdf8c4a63e86c85530 | PHP | crysalead/net | /src/Mime/Address.php | UTF-8 | 3,663 | 3.0625 | 3 | [
"MIT"
] | permissive | <?php
namespace Lead\Net\Mime;
use InvalidArgumentException;
/**
* Email/name address container (support UTF-8 charset only).
*/
class Address
{
/**
* Email address
*
* @var string
*/
protected $_email;
/**
* Name
*
* @var string
*/
protected $_name;
/**
* Constructor
*
* @param string $address An email address or a simple email string
* @param null|string $name An optionnal name
*/
public function __construct($address, $name = null)
{
if (!$address || !is_string($address)) {
throw new InvalidArgumentException("Email can't be empty.");
}
if (!$name && preg_match('~^(.+) +<(.*)>\z~', $address, $matches)) {
$email = $matches[2];
$name = $matches[1];
} else {
$name = $name ?: '';
$email = $address;
}
$email = trim(str_replace(["\r", "\n"], '', $email));
if (!static::isValid(Mime::encodeEmail($email))) {
throw new InvalidArgumentException("Invalid email `'{$address}'`, can't be parsed.");
}
$this->_email = $email;
$name = trim(str_replace(["\r", "\n"], '', $name));
if (!$name) {
return;
}
if (!is_string($name)) {
throw new InvalidArgumentException('Name must be a string');
}
$this->_name = $name;
}
/**
* Retrieve email
*
* @return string
*/
public function email()
{
return $this->_email;
}
/**
* Retrieve name
*
* @return string
*/
public function name()
{
return $this->_name;
}
/**
* Return the encoded representation of the address
*
* @return string
*/
public function toString()
{
$email = '<' . Mime::encodeEmail($this->email()) . '>';
$name = $this->name();
return $name ? Mime::encodeValue($name) . ' ' . $email : $email;
}
/**
* Return the encoded representation of the address
*
* @return string
*/
public function __toString()
{
return $this->toString();
}
/**
* Check if an email is valid.
*
* Uses the same RFC5322 regex on which FILTER_VALIDATE_EMAIL is based, but allows dotless domains.
* @link http://squiloople.com/2009/12/20/email-address-validation/
* @copyright 2009-2010 Michael Rushton
* Feel free to use and redistribute this code. But please keep this copyright notice.
*
* @param string $text The text
* @return string
*/
public static function isValid($email)
{
return (boolean) preg_match(
'/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)' .
'((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' .
'(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' .
'([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' .
'(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' .
'(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' .
'|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' .
'|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
'|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD',
$email ?: ''
);
}
}
| true |
e5bb0beeaa7ad930d2b3d3fd767a7d403b4ff553 | PHP | lossendae/Previously-on | /src/models/TvShow.php | UTF-8 | 3,508 | 2.53125 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | <?php
/*
* This file is part of the Lossendae\PreviouslyOn.
*
* (c) Stephane Boulard <lossendae@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Lossendae\PreviouslyOn\Models;
use DB;
use Eloquent;
/**
* Class TvShow
*
* @package Lossendae\PreviouslyOn\Models
*/
class TvShow extends Eloquent
{
/**
* Defining fillable attributes on the model
*
* @var array
*/
protected $fillable = [
'name',
'overview',
'network',
'first_aired',
'banner_url',
'poster_url',
'fanart_url',
'thetvdb_id',
'imdb_id',
'zap2it_id',
];
/**
* The attributes that aren't mass assignable.
*
* @var array
*/
protected $guarded = ['id'];
public static function boot()
{
parent::boot();
static::deleting(function ($tvShow)
{
$tvShow->episodes()
->delete();
});
}
/**
* @return mixed
*/
public function episodes()
{
return $this->hasMany(__NAMESPACE__ . '\\' . 'Episode');
}
/**
* @return mixed
*/
public function assigned()
{
return $this->belongsToMany(__NAMESPACE__ . '\\' . 'User', 'assigned_tv_shows')
->withPivot('user_id');
}
/**
* @param $query
* @return mixed
*/
public function scopeSeasons($query)
{
return $query->select(DB::raw('COUNT(DISTINCT season_number) as seasons'))
->leftJoin('episodes', 'tv_shows.id', '=', 'episodes.tv_show_id')
->where('season_number', '>', 0);
}
/**
* @param $query
* @param $userId
* @return mixed
*/
public function scopeAssignedTo($query, $userId)
{
$query->join('assigned_tv_shows', function ($join) use ($userId)
{
$join->on('tv_shows.id', '=', 'assigned_tv_shows.tv_show_id')
->where('assigned_tv_shows.user_id', '=', (int)$userId);
});
return $query;
}
/**
* @param $query
* @param $userId
* @return mixed
*/
public function scopeAllWithRemaining($query, $userId)
{
$remainingEpisodes = 'COUNT(CASE WHEN IF(' . DB::getTablePrefix() . 'watched_episodes.user_id, 1, 0) = 0 AND ';
$remainingEpisodes .= DB::getTablePrefix() . 'episodes.first_aired < NOW() THEN 1 END) as remaining';
$query->addSelect(DB::raw($remainingEpisodes))
->leftJoin('episodes', 'tv_shows.id', '=', 'episodes.tv_show_id')
->leftJoin('watched_episodes', function ($join) use ($userId)
{
$join->on('episodes.id', '=', 'watched_episodes.episode_id')
->where('watched_episodes.user_id', '=', (int)$userId);
})
->where('episodes.season_number', '>', (int)0);
return $query;
}
/**
* @param $query
* @param int $id
* @param $userId
* @param bool $returnResult
* @return mixed
*/
public function scopeOneWithRemaining($query, $id = 0, $userId, $returnResult = false)
{
$query->allWithRemaining($userId, $returnResult)
->where('tv_shows.id', '=', $id);
if($returnResult)
{
return $query->first();
}
return $query;
}
}
| true |
e0ce90613edbbf33ce76f15ba10c9e767807dfeb | PHP | mankidal19/RentIt | /web/php/checkUserLogin.php | UTF-8 | 1,683 | 2.65625 | 3 | [] | no_license | <?php
// Start up your PHP Session
session_start();
include('config.php');
?>
<?php
// username and password sent from form
$myusername=$_POST['username'];
$mypassword=$_POST['password'];
$sql="SELECT * FROM user WHERE username='$myusername' and password='$mypassword'";
$result=mysqli_query($conn,$sql);
$rows=mysql_fetch_array($result);
$user_name=$rows['username'];
$user_id=$rows['password'];
$user_level=$rows['level'];
$userID = $rows['userID'];
// mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
$_SESSION["Login"] = "YES";
// Add user information to the session (global session variables)
$_SESSION['USER'] = $user_name;
$_SESSION['ID'] = $user_id;
$_SESSION['LEVEL'] =$user_level;
$expire = time()+60*60*24*30;
setcookie("userID", $userID, $expire);
if($_SESSION["LEVEL"] == "Admin"){
header("Location: admin.php");
}
else if($_SESSION["LEVEL"] == "Staff"){
header("Location: staff.php");
}
else if($_SESSION["LEVEL"] == "Manager"){
header("Location: manager.php");
}
// echo "<h1>You are now correctly logged in</h1>";
// echo "<p><a href='document.php'>Proceed to site</a></p>";
}
//if wrong username and password
else {
$_SESSION["Login"] = "NO";
echo "<h1>You are NOT correctly logged in </h1>";
echo "<p><a href='document.php'>Link to protected file</a></p>";
}
?>
| true |
54acc05883ed657885182763f272cca4b1b2ba2c | PHP | kkesidis/currencies | /app/Eloquent/Repository.php | UTF-8 | 2,829 | 3.28125 | 3 | [] | no_license | <?php
namespace App\Eloquent;
use App\Interfaces\RepositoryInterface;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Container\Container as App;
abstract class Repository implements RepositoryInterface
{
private $app;
protected $model;
public function __construct(App $app)
{
$this->app = $app;
$this->makeModel();
}
// Model Initialization Process
abstract function model();
/**
* Register model
*/
public function makeModel()
{
$model = $this->app->make($this->model());
if (!$model instanceof Model){
throw new RepositoryException("Class {$this->model()} must be an instance of Illuminate\\Database\\Eloquent\\Model");
}
return $this->model = $model;
}
/**
* Find by ID
* @param id
* @param columns
*
* @return model
*/
public function find($id, $columns=['*'])
{
return $this->model->findOrFail($id, $columns);
}
/**
* Find by attribute
* @param attribute
* @param value
* @param columns
*
* @return model
*/
public function findBy($attribute, $value, $columns=['*'])
{
return $this->model->where($attribute, '=', $value)->firstOrFail($columns);
}
/**
* Get all
* @param columns
*
* @return collection
*/
public function all($columns=['*'])
{
return $this->model->get($columns);
}
/**
* Get all, order by attribute
* @param attribute
* @param value
* @param columns
*
* @return collection
*/
public function allBy($attribute, $value, $columns=['*'])
{
return $this->model->orderBy($attribute, $value)->get($columns);
}
/**
* All, filtered by where and order by
* @param attribute
* @param value
* @param orderBy
* @param order
* @param columns
*
* @return collection
*/
public function allByOrdered($attribute, $value, $orderBy, $order, $columns=['*'])
{
return $this->model->where($attribute, '=', $value)->orderBy($orderBy, $order)->get($columns);
}
/**
* Paginate
* @param perPage
* @param columns
*
* @return collection
*/
public function paginate($perPage=15, $columns=['*'])
{
return $this->model->paginate($perPage, $columns);
}
/**
* Create
* @param data
*
* @return integer
*/
public function create(array $data)
{
return $this->model->create($data);
}
/**
* Update a set of data
* @param data
* @param id
* @param attribute, in case we do not want to update by Id
*
* @return integer (number of rows affected)
*/
public function update(array $data, $id, $attribute='id')
{
return $this->model->where($attribute, '=', $id)->update($data);
}
/**
* Delete by Id
* @param id
*/
public function delete($id)
{
return $this->model->destroy($id);
}
/**
* Delete by Attribute
* @param attribute
* @param value
*/
public function deleteBy($attribute, $value)
{
return $this->model->where($attribute, '=', $value)->delete();
}
}
?> | true |
f488aed0ee56bfdd7a5aefcfada32a9d8add18ea | PHP | OksanaZakharovaIP-31/RGZ | /connect.php | UTF-8 | 460 | 2.578125 | 3 | [] | no_license | <?php
$server = 'localhost'; // имя сервера
$username = 'root'; // имя пользователя
$database = 'king';
$password = 'h.5r3rJYwia7BGk';
$con=mysqli_connect($server, $username,$password, $database) //функция открытия соединения с севером базы данных
or die (mysqli_error()); // если подключение не открылось, отобразить описание ошибки
?> | true |
5c35fec57038b075e141baa8f4137d04f1360b4e | PHP | urm123/white_lable_restaurant | /app/Repository/AddressRepository.php | UTF-8 | 856 | 2.828125 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: janaka
* Date: 28/02/19
* Time: 11:10 AM
*/
namespace App\Repository;
use App\Address;
/**
* Class AddressRepository
* @package App\Repository
*/
class AddressRepository
{
/**
* @param array $request
* @return Address
*/
public function create(array $request)
{
$address = new Address($request);
$address->save();
return $address;
}
/**
* @param array $address
* @return mixed
*/
public function update(array $address)
{
return Address::whereId($address['id'])->update([
'address' => $address['address'],
'street' => $address['street'],
'city' => $address['city'],
'county' => $address['county'],
'postcode' => $address['postcode'],
]);
}
} | true |
fb896d4d45f2d7a5b4de51f495990242137a630d | PHP | AnhThi/Syslytic | /application/models/Captcha_model.php | UTF-8 | 1,031 | 2.546875 | 3 | [
"MIT"
] | permissive | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Captcha_model extends CI_Model {
public $variable;
public function __construct()
{
parent::__construct();
}
public function insert_capt($time,$ip,$word)
{
$data = array(
'captcha_time' => $time,
'ip_address' => $ip,
'word' => $word
);
$this->db->insert('captcha',$data);
}
public function check_captcha()
{
$expiration = time() - 7200; // Two hour limit
$this->db->where('captcha_time < ', $expiration)
->delete('captcha');
$sql = 'SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip_address = ? AND captcha_time > ?';
$binds = array($_POST['captcha'], $this->input->ip_address(), $expiration);
$query = $this->db->query($sql, $binds);
$row = $query->row();
if ($row->count == 0)
{
return false; // phai nhap capt
}
else
{
return true;
}
}
}
/* End of file Captcha_model.php */
/* Location: ./application/models/Captcha_model.php */ | true |