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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
9bc18f20c6d14f21d0b6e11bc4abf587ecb35f4e | PHP | yaiza-nt/Curso-PHP | /2-Fundamentos/funciones-arrays.php | UTF-8 | 798 | 3.59375 | 4 | [] | no_license | <?php
/*$amigo = [
'telefono' => 999887766,
'edad' => 22,
'pais' => 'España'
];
// Extrae elementos de arrays asociativos en variables:
extract($amigo);*/
$semana = [
'Lunes', 'Martes', 'Miércoles', 'Jueves',
'Viernes', 'Sábado', 'Domingo'
];
/*echo array_pop($semana).'<br/>'; // quita el último elemento
foreach ($semana as $dia) {
echo $dia.'<br/>';
};*/
# echo join (' - ', $semana); // muestra elementos separados por lo que pasemos como primer parámetro
# echo count($semana); // cuenta los elementos del array
/*sort($semana); // ordena el array
echo join (' - ', $semana);*/
echo join (' - ', array_reverse($semana)); // invierte el orden de los elementos del array
?> | true |
7918a728c6cabefa348fa1ac13a1c544a8557b41 | PHP | github-day-b/test-Repository | /kintai/admin/confEmployee/ajax_changeEmployee.php | UTF-8 | 2,051 | 2.796875 | 3 | [] | no_license | <?php
/*
* @author YukiKawasaki
* FileName ajax_confEmployee.php
* @create 2014/05/01
* Remark 従業員を変更するだけ。
2014/05/16
sql操作をempinfoDBに追い出した。
*/
require_once("../../util/util.php");
require_once("../../database/empinfoDB.php");
session_start();
//CSRF対策
if (empty($_SESSION["token"]) || $_SESSION["token"] != $_POST["token"]
|| !isset($_SESSION["me"]) || !$_SESSION["me"]["admin"]) {
die("不正なアクセスです。");
}else {
;//DoNothing
}
$empId = util::h($_POST["empId"]);
$name = util::h($_POST["name"]);
$email = util::h($_POST["email"]);
$startHour = util::h($_POST["startHour"]);
$startMin = util::h($_POST["startMin"]);
$endHour = util::h($_POST["endHour"]);
$endMin = util::h($_POST["endMin"]);
$startTime = util::makeTime($startHour, $startMin);
$endTime = util::makeTime($endHour, $endMin);
$db = new EmpInfoDB();
//入力チェック
if(empty($name)) {
die("名前が入ってません");
}else if(empty($email)) {
die("emailが入ってません");
}else if(strlen($name) > 30) {
die("名前長くないですか?");
}else if(strlen($email) > 255) {
die("email長くないですか");
}else if(!preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/i", $email)) {
//emailチェック。不勉強で正規表現ができない。
die("それメールアドレスですか?");
}else {
;//DoNothing
}
$password = "";
if (!empty($_POST["pass"])) {
$rawPassword = util::h($_POST["pass"]);
$password = util::makePass($rawPassword);
}
header('Content-type: text/javascript; charset=utf-8');
echo $db->changeEmployee($empId, $name, $email, $password, $startTime, $endTime, $password);//従業員情報の変更
//EOF | true |
87e667721c1c008ee1f75261a1ab47bf9454fbc1 | PHP | nlemaitre/php-connectSession | /login_post.php | UTF-8 | 956 | 3 | 3 | [] | no_license | <?php
session_start();
if (isset($_POST['login']) && isset($_POST['mdp'])) {
require 'connexion.php';
$bdd = pdo_connect_mysql();
$requete = "SELECT * FROM utilis WHERE LoginUtil=? AND PassUtil=?";
$resultat = $bdd->prepare($requete);
$login = $_POST['login'];
$mdp = $_POST['mdp'];
$resultat->execute(array($login, $mdp));
if ($resultat->rowCount() == 1) {
$_SESSION['login'] = $login;
$_SESSION['mdp'] = $mdp;
$authOK = true;
}
}
?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
</head>
<body>
<h1>Résultat de l'authentification</h1>
<?php
if (isset($authOK)) {
echo "<p>Authentification reussi vous êtes " . ($login) . "</p>";
echo '<a href="index.php">Vers accueil</a>';
}
else { ?>
<p>Qui êtes vous ? Information incorrecte </p>
<p><a href="login.php">Try again </p>
<?php } ?>
</body>
</html> | true |
8b4efae834c7398ff572c8c6d2556979ae9903fc | PHP | emilysf/studiowizard | /app/Http/Controllers/FormController.php | UTF-8 | 1,174 | 2.734375 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
class FormController extends Controller
{
public function signup() {
$servername = "127.0.0.1";
$username = "root";
$password = "password321";
$dbname = "Dance_db";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
// if (!$conn) {
// die("Connection failed: " . mysqli_connect_error();
// }
$data = $_POST;
$name = $data['name'];
$age = $data['age'];
$phone = $data['phone'];
$email = $data['email'];
$userpassword = $data['password'];
// print_r($data);
$sql = "INSERT INTO signup (studentName, studentAge, studentPhone, studentEmail, studentPassword)
VALUES ('$name', '$age', '$phone', '$email', '$userpassword')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
//return view('signup');
}
}
| true |
5a26480373d28bda52540d3be054bd2f3ea17fa8 | PHP | thomasdion/bands | /molonlave/lib/Tours.php | UTF-8 | 4,189 | 3.1875 | 3 | [
"MIT"
] | permissive | <?php
/**
* Description of Tours
*
* @author Διονύσης
*/
class Tours {
private $connection;
public $tours;
function __construct(){
$this->connection = null;
$this->tours=null;
}
function unset_con() {
$this->connection = null;
}
function set_data($res){
$this->tours = $res;
}
function get_data(){
return $this->tours;
}
function set_con($con){
$this->connection = $con;
}
function countData() {
try {
$stmt = $this->connection->getDBH()->query('SELECT COUNT(*) as num FROM tours');
if($stmt) {
$count = $stmt->fetchAll(PDO::FETCH_COLUMN,0);
return $count[0];
}else return 0;
}catch(PDOException $e){
throw new PDOException($e,"SELECT ERROR/EXTRACT NEWS");
}
}
function extract_data($start, $limit) {
try {
$stmt = $this->connection->getDBH()->prepare('SELECT * FROM tours ORDER BY tour_date LIMIT ?,?');
$stmt->bindParam(1, $start, PDO::PARAM_INT);
$stmt->bindParam(2, $limit, PDO::PARAM_INT);
if($stmt->execute()) {
$this->tours = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
}catch(PDOException $e){
throw new PDOException($e,"SELECT ERROR/EXTRACT TOURS");
}
}
function extract($id){
try {
$stmt = $this->connection->getDBH()->prepare("SELECT * FROM tours WHERE id=?");
$stmt->bindParam(1, $id, PDO::PARAM_INT);
if ($stmt->execute()) {
$this->tours = $stmt->fetch(PDO::FETCH_ASSOC);
}
}catch(PDOException $e){
throw new PDOException($e,"SELECT ERROR/EXTRACT TOUR");
}
}
function insert(){
try {
$sql = "INSERT INTO tours(tour_date, town, place,type) VALUES
(?,?,?,?)";
$stmt = $this->connection->getDBH()->prepare($sql);
$stmt->bindParam(1, $this->tours['tour_date'], PDO::PARAM_STR);
$stmt->bindParam(2, $this->tours['town'], PDO::PARAM_STR);
$stmt->bindParam(3, $this->tours['place'], PDO::PARAM_STR);
$stmt->bindParam(4, $this->tours['type'], PDO::PARAM_STR);
if($stmt->execute())
return TRUE;
else
return FALSE;
}catch(PDOException $e){
throw new PDOException($e);
}
}
function update(){
try {
$sql = "UPDATE tours SET tour_date=?, town=?, place=?, type=? WHERE id=?";
$stmt = $this->connection->getDBH()->prepare($sql);
$stmt->bindParam(1, $this->tours['tour_date'], PDO::PARAM_STR);
$stmt->bindParam(2, $this->tours['town'], PDO::PARAM_STR);
$stmt->bindParam(3, $this->tours['place'], PDO::PARAM_STR);
$stmt->bindParam(4, $this->tours['type'], PDO::PARAM_STR);
$stmt->bindParam(5, $this->tours['id'], PDO::PARAM_INT);
$stmt->execute();
if($stmt->rowCount())
return TRUE;
else
return FALSE;
}catch(PDOException $e){
throw new PDOException($e,"SELECT ERROR/EXTRACT TOUR");
}
}
function delete($id){
try {
$sql = "DELETE FROM tours WHERE id=?";
$stmt = $this->connection->getDBH()->prepare($sql);
$stmt->bindParam(1, $id, PDO::PARAM_INT);
$stmt->execute();
if($stmt->rowCount())
return TRUE;
else
return FALSE;
}catch(PDOException $e){
throw new PDOException($e,"DELETE ERROR/DELETE TOUR");
}
}
}
?>
| true |
41aa845a4e9a68441d53463f086baf3801b43576 | PHP | ronnyhartenstein/Image-and-Video-Thumbnailer | /src/BaseCommand.php | UTF-8 | 4,133 | 2.671875 | 3 | [] | no_license | <?php
namespace RhFlow\Thumbnailer;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Style\SymfonyStyle;
use \RuntimeException as Exception;
abstract class BaseCommand extends Command
{
/** @var \Monolog\Logger */
protected $log;
/** @var bool */
protected $run_message_showed = false;
public function __construct(\Monolog\Logger $log)
{
$this->log = $log;
parent::__construct();
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->activateLogToOutput($input, $output);
// run in background on Idle
proc_nice(20);
/*
* Fetch parameters
*/
$source_root = strip_last_slash($input->getArgument('source'));
if (!file_exists($source_root)) {
throw new Exception("ERROR: source doesn't exists or is not a directory! $source_root");
}
$target_root = strip_last_slash($input->getArgument('target'));
if (!file_exists($target_root)) {
throw new Exception("ERROR: target doesn't exists or is not a directory! $target_root");
}
$force = $input->hasOption('force') ? $input->getOption('force') : false;
if ($force) {
$this->log->info("Option 'Force overwrite' given");
}
$force_hochkant = $input->hasOption('force-hochkant') ? $input->getOption('force-hochkant') : false;
if ($force_hochkant) {
$this->log->info("Option 'Force-hochkant overwrite' given");
}
$dry = $input->hasOption('dry') ? $input->getOption('dry') : false;
if ($dry) {
$this->log->info("Option 'Dry run' given");
}
/*
* Locking by PID-file, single process
*/
$this->checkLocking();
/*
* Scan source
*/
$successfull = 0;
$this->run_message_showed = false;
// find /Users/ronny/Pictures/2016/* -type f -iname "*.jpg" -or -iname "*.nef" > /tmp/thumbnailer_src.lst
// find /Users/ronny/Movies/2016/* -type f -iname "*.mp4" > /tmp/thumbnailer_src.lst
$source_files = array();
$cmd = $this->shellcommandFindFiles($source_root, $target_root);
exec($cmd, $source_files);
$this->log->debug(count($source_files) . " source files found!");
foreach ($source_files as $source_file) {
if ($this->import($source_root, $source_file, $target_root, $force, $force_hochkant, $dry)) {
$successfull++;
}
}
if ($successfull > 0) {
$this->log->info("DONE! Sucessfully converted $successfull files.");
}
$this->unlock();
}
protected function checkLocking()
{
if (file_exists($this->lockfile)) {
$otherpid = intval(file_get_contents($this->lockfile));
if ($otherpid > 0) {
$output = [];
$return_var = '';
exec('ps -x |grep ' . $otherpid . ' | grep -v grep', $output, $return_var);
if ($return_var == 0 && count($output) == 1) {
throw new \RuntimeException('Other process is still running (' . $otherpid . ')');
}
} else {
throw new \RuntimeException('Lockfile don\'t contain a valid process id. Please check ' . $this->lockfile);
}
}
file_put_contents($this->lockfile, getmypid());
}
protected function unlock()
{
unlink($this->lockfile);
}
protected function activateLogToOutput(InputInterface $input, OutputInterface $output)
{
$this->log->pushHandler(new LogOutputHandler(new SymfonyStyle($input, $output), getLogLevel()));
}
abstract function shellcommandFindFiles(string $source_root, string $target_root);
abstract protected function import(string $source_root, string $source_file, string $target_root, bool $force, bool $force_hochkant, bool $dry): bool;
} | true |
d92b14fc1302b2354086b3a5d05e90b09416266c | PHP | doseonkim/Crypto-Sim | /PHP_SQL/get_user_wallet.php | UTF-8 | 1,775 | 2.765625 | 3 | [] | no_license | <?php
ini_set('display_errors', '1');
error_reporting(E_ALL);
// Connect to the Database
$dsn = 'mysql:host=cssgate.insttech.washington.edu;dbname=doseon';
$username = 'doseon';
$password = 'Getex~';
if (!isset($_GET['name']) || empty($_GET['name'])) {
$result = array(
"code" => 100,
"message" => "name not defined."
);
echo json_encode($result);
exit();
}
$user_name = $_GET['name'];
try {
#make a new DB object to interact with
$db = new PDO($dsn, $username, $password);
#build a SQL statement to query the DB
$q = $db->query("DESCRIBE Wallet");
$table_fields = $q->fetchAll(PDO::FETCH_COLUMN);
$select_sql = "SELECT * FROM Wallet WHERE username = '$user_name'";
#make a query object
$wallet_query = $db->query($select_sql);
$wallet = $wallet_query->fetchAll(PDO::FETCH_ASSOC);
#check to see if the db returned any values
if ($wallet) {
#start an array to hold the results
$result = array("code"=>100, "size"=>count($table_fields) - 1);
$wallet_array = array();
#iterate through the results
if ($table_fields) {
for ($i = 1; $i < count($table_fields); $i++) {
$coin_name = $table_fields[$i];
$coin_amount = $wallet[0][$coin_name];
$wallet_array[$i-1] =
array("coin_name"=>$coin_name,
"coin_amount"=>$coin_amount);
}
$result["wallet_data"] = $wallet_array;
}
} else {
$result = array("code"=>200, "message"=>"No wallet found.");
}
echo json_encode($result);
$db = null;
}
catch (PDOException $e) {
$error_message = $e->getMessage();
$result = array(
"code" => 400,
"message" => "There was an error connecting to
the database: $error_message"
);
echo json_encode($result);
exit();
}
?> | true |
dc9aeaa4e119106b20e92bd18232aa4ffb3baa3f | PHP | yushenxiang/mall-php | /application/common/service/Service.php | UTF-8 | 563 | 2.71875 | 3 | [
"Apache-2.0"
] | permissive | <?php
/**
* @author xialeistudio
* @date 2019-06-13
*/
namespace app\common\service;
/**
* 业务基类
* Class Service
* @package app\common\service
*/
class Service
{
private static $_instances = [];
/**
* @return static|mixed
*/
public static function Factory()
{
$className = get_called_class();
if (isset(self::$_instances[$className])) {
return self::$_instances[$className];
}
self::$_instances[$className] = new static();
return self::$_instances[$className];
}
} | true |
cef6de59b4d0a94e378aa809230ebe5f07c91b13 | PHP | ArielAereal/ClaseUnoPHP | /ejj1prueba.php | UTF-8 | 1,157 | 3.1875 | 3 | [] | no_license | <html>
<head>
<title>Cuevas</title>
</head>
<body>
<h1>Hola Mundo!</h1>
<?php
$vueltas = 10;
$cuentap = 0;
$cuentai = 0;
$i;
$c1 = 0;
$c2 = 0;
$c3 = 0;
$c4 = 0;
$c5 = 0;
$c6 = 0;
$c7 = 0;
$c8 = 0;
$c9 = 0;
$c10 = 0;
for($i = 0; $i<$vueltas;$i++)
{
$numeroR = rand(1,10);
if ($numeroR%2 == 0)
{
$cuentap++;
} else
{
$cuentai++;
}
switch ($numeroR) {
case '1':
$c1++;
break;
case '2':
$c2++;
break;
case '3':
$c3++;
break;
case '4':
$c4++;
break;
case '5':
$c5++;
break;
case '6':
$c6++;
break;
case '7':
if ($c7 == 5*$vueltas/100)
{
continue;
} else
{
$c7++ ;
}
break;
case '8':
$c8++;
break;
case '9':
$c9++;
break;
case '10':
$c10++;
break;
}
}
$r1 = 0;
$r1 = $c1*100/$vueltas;
echo "Pares: $cuentap <br> ";
echo "Impares: $cuentai <br>";
echo "Unos $r1 % <br>";
echo "Doses $c2 <br>";
echo "Treses $c3 <br>";
echo "Cuatros: $c4 <br>";
echo "Cincos: $c5 <br>";
echo "Seises: $c6 <br>";
echo "Sietes: $c7 <br>";
echo "Ochos: $c8 <br>";
echo "Nueves: $c9 <br>";
echo "Dieces: $c10 <br>";
?>
</body>
</html>
| true |
d15736cf1679872ba905418fc348d4527ad174ec | PHP | alifakbarr/Contoh_PHP | /fungsi02.php | UTF-8 | 202 | 3.140625 | 3 | [] | no_license | <?php
function cetak_ganjil($awal,$akhir){
for ($i=$awal; $i<=$akhir;$i++){
if ($i%2==1) {
echo "$i ";
}
}
}
$a=2;
$b=30;
echo "bilangan ganjil dari $a dan $b : <br>";
cetak_ganjil($a,$b);
?>
| true |
e9b5f8e2d4d555f4b51ed8685562382b41d1414f | PHP | gechiui/gechiui-develop | /tests/phpunit/tests/formatting/sanitizeTitle.php | UTF-8 | 518 | 2.578125 | 3 | [] | no_license | <?php
/**
* @group formatting
*/
class Tests_Formatting_SanitizeTitle extends GC_UnitTestCase {
public function test_strips_html() {
$input = 'Captain <strong>Awesome</strong>';
$expected = 'captain-awesome';
$this->assertSame( $expected, sanitize_title( $input ) );
}
public function test_titles_sanitized_to_nothing_are_replaced_with_optional_fallback() {
$input = '<strong></strong>';
$fallback = 'Captain Awesome';
$this->assertSame( $fallback, sanitize_title( $input, $fallback ) );
}
}
| true |
9de6c01797a8a407688cf950a65c1b73834f8764 | PHP | MrRobinMr/randomtools | /zam.php | UTF-8 | 441 | 2.609375 | 3 | [] | no_license | <?php
session_start();
$cena = 0;
require_once "conf.php";
try{
$db = new PDO("mysql:host=".$host.";dbname=".$db_name, $db_user, $db_password);
}
catch (PDOException $e){
die ("Error connecting to database!");
}
foreach ($_SESSION["koszyk"] as $value) {
$sth = $db->prepare('SELECT cena from produkty where id=:id');
$sth->bindValue(':id', $value, PDO::PARAM_STR);
$sth->execute();
$c = $sth->fetch();
echo $c;
}
echo $cena;
?>
| true |
4b0b5079c3a7d87ec321b6c48a63925745cbaf16 | PHP | luispdl/servidor | /Modelos/Auth.php | UTF-8 | 1,869 | 2.8125 | 3 | [] | no_license | <?php namespace Modelos;
require_once 'vendor/autoload.php';
use \Firebase\JWT\JWT;
use \Exception;
use \Firebase\JWT\ExpiredException;
use \Firebase\JWT\SignatureInvalidException;
class Auth
{
private static $clave_secreta = "isft_179_clave";
private static $encriptacion = ['HS256'];
private static $aud = null;
public function __construct(){
}
public static function autenticar($datos){
$time = time();
$token = [
'iat' => $time,
'exp' => $time + (60 * 60),
'aud' => self::Aud(),
'data' => $datos
];
return JWT::encode($token, self::$clave_secreta);
}
public static function verificar($token){
if(empty($token)){
throw new Exception('Token enviado invalido.');
}
try {
$tokenArray = JWT::decode($token, self::$clave_secreta, self::$encriptacion);
}
catch (\Firebase\JWT\ExpiredException $e) {
return ["error" => "El token ha expirado"];
}
catch (\Firebase\JWT\SignatureInvalidException $e){
return ["error" => "Token no verificado"];
}
if($tokenArray->aud !== self::Aud()) {
return ["error" => "Usuario Invalido"];
}
}
public static function obtenerDatos($token){
try {
return JWT::decode(
$token,
self::$clave_secreta,
self::$encriptacion
)->data;
} catch(\UnexpectedValueException $e) {
return $e->getMessage();
} catch(ExpiredException $e) {
return $e->getMessage();
}
}
private static function Aud() {
$aud = '';
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$aud = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$aud = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$aud = $_SERVER['REMOTE_ADDR'];
}
$aud .= @$_SERVER['HTTP_USER_AGENT'];
$aud .= gethostname();
return sha1($aud);
}
}
| true |
b270f3464a5827439a2bb297eec84a94eed7c160 | PHP | Richard-NL/silex-adventure | /src/Rsh/Adventure/Action/ActionStrategy.php | UTF-8 | 578 | 2.796875 | 3 | [] | no_license | <?php
namespace Rsh\Adventure\Action;
class ActionStrategy
{
const actionClasses = [
ExitAction::class,
GoToAction::class,
InventoryAction::class,
// NoAction::class
];
public function getAction($userInputText): Action
{
foreach (self::actionClasses as $actionClass) {
/** @var Action $action */
$action = new $actionClass($userInputText);
if ($action->isMatchOnText()) {
return $action;
}
}
return new NoAction($userInputText);
}
} | true |
5f87eb5ae83a37012d8b238423ae76620fcddc90 | PHP | silver-arrow-software/bg360 | /plugins/sas/social/models/BaseModel.php | UTF-8 | 1,950 | 2.65625 | 3 | [] | no_license | <?php namespace Sas\Social\Models;
use Model;
class BaseModel extends Model
{
protected $isSuperType = false; // set true in super-class model
protected $isSubType = false; // set true in inherited models
protected $typeField = 'type'; //override as needed, only set on the super-class model
public function mapData(array $attributes)
{
if (!$this->isSuperType) {
return $this->newInstance();
}
else {
if (!isset($attributes[$this->typeField])) {
throw new \DomainException($this->typeField . ' not present in the records of a Super Model');
}
else {
$class = $this->getClass($attributes[$this->typeField]);
return new $class;
}
}
}
public function newFromBuilder($attributes = [], $connection = null)
{
$m = $this->mapData((array)$attributes)->newInstance([], true);
$m->setRawAttributes((array)$attributes, true);
return $m;
}
public function newRawQuery()
{
$builder = $this->newEloquentBuilder($this->newBaseQueryBuilder());
$builder->setModel($this)->with($this->with);
return $builder;
}
public function newQuery($excludeDeleted = true)
{
$builder = parent::newQuery($excludeDeleted);
if ($this->isSubType()) {
$builder->where($this->typeField, $this->getClass($this->typeField));
}
return $builder;
}
protected function isSubType()
{
return $this->isSubType;
}
protected function getClass($type)
{
return get_class($type);
}
protected function getType()
{
return get_class($this);
}
public function save(array $options = [], $sessionKey = null)
{
$this->attributes[$this->typeField] = $this->getType();
return parent::save($options, $sessionKey);
}
}
| true |
22338a4686ae4c702e166ec228d00fdc97644be5 | PHP | gilsonmello/aprendanaweb | /app/Repositories/Backend/PackageTeacher/EloquentPackageTeacherRepository.php | UTF-8 | 3,955 | 2.8125 | 3 | [] | no_license | <?php namespace App\Repositories\Backend\PackageTeacher;
use App\Package;
use App\PackageTeacher;
use App\Exceptions\GeneralException;
use App\Repositories\Backend\PackageTeacher\PackageTeacherContract;
use App\User;
/**
* Class EloquentPackageTeacherRepository
* @package App\Repositories\PackageTeacher
*/
class EloquentPackageTeacherRepository implements PackageTeacherContract {
/**
* @param $id
* @return mixed
* @throws GeneralException
*/
public function findOrThrowException($id) {
$packageTeacher = PackageTeacher::withTrashed()->find($id);
if (! is_null($packageTeacher)) return $packageTeacher;
throw new GeneralException('That packageTeacher does not exist.');
}
public function findByPackageAndTeacher($package,$teacher){
$packageTeacher = PackageTeacher::where('package_id',$package)->where('teacher_id',$teacher)->get()->first();
if(! is_null($packageTeacher)) return $packageTeacher;
else return null;
}
/**
* @param $per_page
* @param string $order_by
* @param string $sort
* @return mixed
*/
public function getPackageTeachersPaginated($per_page, $order_by = 'id', $sort = 'asc') {
return PackageTeacher::orderBy($order_by, $sort)->paginate($per_page);
}
/**
* @param $per_page
* @return \Illuminate\Pagination\Paginator
*/
public function getDeletedPackageTeachersPaginated($per_page) {
return PackageTeacher::onlyTrashed()->paginate($per_page);
}
/**
* @param string $order_by
* @param string $sort
* @return mixed
*/
public function getAllPackageTeachers($order_by = 'id', $sort = 'asc') {
return PackageTeacher::orderBy($order_by, $sort)->get();
}
public function getAllPackageTeachersPerPackage($package, $order_by = 'id', $sort = 'asc') {
return PackageTeacher::where('package_id', '=', $package)->orderBy($order_by, $sort)->get();
}
/**
* @param $input
* @return bool
* @throws GeneralException
*/
public function create($teacher,$package,$percentage) {
$packageTeacher = $this->createPackageTeacherStub($percentage);
$packageTeacher->teacher()->associate(User::find($teacher));
$packageTeacher->package()->associate(Package::find($package));
if($packageTeacher->save())
return $packageTeacher;
throw new GeneralException('There was a problem creating this packageTeacher. Please try again.');
}
/**
* @param $id
* @param $input
* @return bool
* @throws GeneralException
*/
public function update($id, $percentage) {
$packageTeacher = $this->findOrThrowException($id);
if ($packageTeacher->update(['percentage' => $percentage])) {
$packageTeacher->save();
return $packageTeacher;
}
throw new GeneralException('There was a problem updating this packageTeacher. Please try again.');
}
/**
* @param $id
* @param $new_file_name
* @return bool
* @throws GeneralException
*/
/**
* @param $id
* @return bool
* @throws GeneralException
*/
public function destroy($id) {
$packageTeacher = $this->findOrThrowException($id);
if ($packageTeacher->delete())
return true;
throw new GeneralException("There was a problem deleting this packageTeacher. Please try again.");
}
/**
* @param $input
* @return mixed
*/
private function createPackageTeacherStub($percentage)
{
$packageTeacher = new PackageTeacher;
$packageTeacher->percentage = $percentage;
return $packageTeacher;
}
public function add($teacher_id, $package_id, $percentage){
$packageteacher = new PackageTeacher;
$packageteacher->teacher_id = $teacher_id;
$packageteacher->package_id = $package_id;
$packageteacher->percentage = $percentage;
$packageteacher->save();
}
} | true |
b9e5b54b8f92cd6e0dc8ffb51984ff92efa6b79d | PHP | ngtrian/bdImage | /library/bdImage/WidgetRenderer/SliderThreads.php | UTF-8 | 1,510 | 2.515625 | 3 | [] | no_license | <?php
class bdImage_WidgetRenderer_SliderThreads extends bdImage_WidgetRenderer_ThreadsBase
{
protected function _getConfiguration()
{
$config = parent::_getConfiguration();
$config['name'] = '[bd] Image: Thread Images Carousel';
$config['options'] += array(
'thumbnail_width' => XenForo_Input::UINT,
'thumbnail_height' => XenForo_Input::UINT,
'title' => XenForo_Input::UINT,
'gap' => XenForo_Input::UINT,
'visible_count' => XenForo_Input::UINT,
);
return $config;
}
protected function _getOptionsTemplate()
{
return 'bdimage_widget_options_slider_threads';
}
protected function _validateOptionValue($optionKey, &$optionValue)
{
if (empty($optionValue)) {
switch ($optionKey) {
case 'thumbnail_width':
case 'thumbnail_height':
$optionValue = 100;
break;
case 'title':
$optionValue = 50;
break;
case 'gap':
$optionValue = 10;
break;
case 'visible_count':
$optionValue = 1;
}
}
return parent::_validateOptionValue($optionKey, $optionValue);
}
protected function _getRenderTemplate(array $widget, $positionCode, array $params)
{
return 'bdimage_widget_slider_threads';
}
}
| true |
38066356e6b6ed9300b2d862ef5162d2d9f5d175 | PHP | iJonKofee/server-API | /app/Model/Feedback/Table.php | UTF-8 | 2,570 | 2.59375 | 3 | [] | no_license | <?php
/**
* @method photo()
* @method taste()
* @method satiety()
* @method quality()
*/
class Feedback_Table extends Core_Db_Table_Abstract
{
use Core_Singleton;
/**
* @var string
*/
protected $_tableName = 'feedback';
/**
* @var integer
*/
private $photo;
/**
* @var integer
*/
private $taste;
/**
* @var integer
*/
private $satiety;
/**
* @var integer
*/
private $quality;
/**
* @var string
*/
private $comment;
/**
* @return number
*/
protected function getPhoto()
{
return $this->photo;
}
/**
* @return number
*/
protected function getTaste()
{
return $this->taste;
}
/**
* @return number
*/
protected function getSatiety()
{
return $this->satiety;
}
/**
* @return number
*/
protected function getQuality()
{
return $this->quality;
}
/**
* @return string
*/
protected function getComment()
{
return $this->comment;
}
/**
* @param integer $id
* @return Feedback_Table
*/
protected function setPhoto($id)
{
$this->photo = $id;
return $this;
}
/**
* @param integer $number
* @return Feedback_Table
*/
protected function setTaste($number)
{
$this->taste = $number;
return $this;
}
/**
* @param integer $number
* @return Feedback_Table
*/
protected function setSatiety($number)
{
$this->satiety = $number;
return $this;
}
/**
* @param integer $number
* @return Feedback_Table
*/
protected function setQuality($number)
{
$this->quality = $number;
return $this;
}
/**
* @param string $str
* @return Feedback_Table
*/
protected function setComment($str)
{
$this->comment = $str;
return $this;
}
public function initialize()
{
$this->hasManyToMany(
"id",
"Feedback_Dish_Table",
"feedback_id", "dish_id",
"Dish_Table",
"id"
);
$this->hasManyToMany(
"id",
"Feedback_Place_Table",
"feedback_id", "place_id",
"Place_Table",
"id"
);
$this->belongsTo("photo", "Media_Table", "id");
}
}
| true |
c5a2582385078f83a999ac07c7ff67eb7fe46c80 | PHP | diondi/contoh-website-pengaduan | /classes/Auth.php | UTF-8 | 1,778 | 3.03125 | 3 | [
"MIT"
] | permissive | <?php
class Auth {
private $connection;
public $table;
// Field table
public $id;
public $jenis;
public $username;
public $nama;
public $nohp;
public $email;
public $password;
public $user_data;
public function __construct($database, $table) {
$this->connection = $database;
$this->table = $table;
}
public function login() {
if ($user_data = $this->checkCredentials()) {
$this->user_data = $user_data;
session_start();
$_SESSION['id'] = $user_data['id'];
$_SESSION['nama'] = $user_data['nama'];
$_SESSION['nohp'] = $user_data['nohp'];
if ($this->table == "admin") {
$_SESSION['username'] = $user_data['username'];
$_SESSION['jenis'] = $user_data['jenis'];
} else {
$_SESSION['email'] = $user_data['email'];
}
$_SESSION['type'] = $this->table;
$_SESSION['is_logged'] = true;
return $user_data['nama'];
}
return false;
}
protected function checkCredentials() {
$field = ($this->table == "admin") ? "username" : "email";
$sql = "SELECT * FROM {$this->table} WHERE {$field}=? AND password=?";
$query = $this->connection->prepare($sql);
$identifier = ($this->table == "admin") ? $this->username : $this->email;
$query->bindParam(1, $identifier);
$query->bindParam(2, $this->password);
$query->execute();
if ($query->rowCount()) {
$data = $query->fetch(PDO::FETCH_ASSOC);
if ($this->password == $data['password']) {
return $data;
}
}
return false;
}
}
| true |
af6b94894ce3bd79bc7f1ac99e8c967083191ae0 | PHP | shreedhar-marasini/beedms | /config/mail.php | UTF-8 | 5,381 | 2.703125 | 3 | [] | no_license | <?php
$dbname = env('DB_DATABASE');
$user = env('DB_USERNAME');
$host = env('DB_HOST');
$pass = env('DB_PASSWORD');
$conn = new mysqli($host, $user, $pass, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT key_name, key_value FROM master_settings";
$result = $conn->query($sql);
if (is_array($result) && $result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
if($row['key_name']=="_EMAIL_ADDRESS_") {
$email = $row['key_value'];
}
if($row['key_name']=="_EMAIL_PASSWORD_") {
$password = $row['key_value'];
}
if($row['key_name']=="_COMPANY_NAME_") {
$companyName = $row['key_value'];
}
if($row['key_name']=="_EMAIL_PORT_") {
$port = $row['key_value'];
}
}
}
else {
$email = env('MAIL_USERNAME');
$password = env('MAIL_PASSWORD');
$companyName = 'BeeDMS';
$port = env('MAIL_PORT');
}
$conn->close();
return [
/*
|--------------------------------------------------------------------------
| Mail Driver
|--------------------------------------------------------------------------
|
| Laravel supports both SMTP and PHP's "mail" function as drivers for the
| sending of e-mail. You may specify which one you're using throughout
| your application here. By default, Laravel is setup for SMTP mail.
|
| Supported: "smtp", "sendmail", "mailgun", "mandrill", "ses",
| "sparkpost", "log", "array"
|
*/
'driver' => env('MAIL_DRIVER', 'smtp'),
/*
|--------------------------------------------------------------------------
| SMTP Host Address
|--------------------------------------------------------------------------
|
| Here you may provide the host address of the SMTP server used by your
| applications. A default option is provided that is compatible with
| the Mailgun mail service which will provide reliable deliveries.
|
*/
'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
/*
|--------------------------------------------------------------------------
| SMTP Host Port
|--------------------------------------------------------------------------
|
| This is the SMTP port used by your application to deliver e-mails to
| users of the application. Like the host we have set this value to
| stay compatible with the Mailgun e-mail application by default.
|
'port' => env('MAIL_PORT', 587),
*/
'port' => env('MAIL_PORT', $port),
/*
|--------------------------------------------------------------------------
| Global "From" Address
|--------------------------------------------------------------------------
|
| You may wish for all e-mails sent by your application to be sent from
| the same address. Here, you may specify a name and address that is
| used globally for all e-mails that are sent by your application.
|
*/
'from' => [
'address' => env('MAIL_FROM_ADDRESS', $email),
'name' => env('MAIL_FROM_NAME', $companyName),
],
/*
|--------------------------------------------------------------------------
| E-Mail Encryption Protocol
|--------------------------------------------------------------------------
|
| Here you may specify the encryption protocol that should be used when
| the application send e-mail messages. A sensible default using the
| transport layer security protocol should provide great security.
|
*/
'encryption' => env('MAIL_ENCRYPTION', 'tls'),
/*
|--------------------------------------------------------------------------
| SMTP Server Username
|--------------------------------------------------------------------------
|
| If your SMTP server requires a username for authentication, you should
| set it here. This will get used to authenticate with your server on
| connection. You may also set the "password" value below this one.
|
*/
/* 'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),*/
'username' => $email,
'password' => $password,
//kxcjezqehngyvftj
/*
|--------------------------------------------------------------------------
| Sendmail System Path
|--------------------------------------------------------------------------
|
| When using the "sendmail" driver to send e-mails, we will need to know
| the path to where Sendmail lives on this server. A default path has
| been provided here, which will work well on most of your systems.
|
*/
'sendmail' => '/usr/sbin/sendmail -bs',
/*
|--------------------------------------------------------------------------
| Markdown Mail Settings
|--------------------------------------------------------------------------
|
| If you are using Markdown based email rendering, you may configure your
| theme and component paths here, allowing you to customize the design
| of the emails. Or, you may simply stick with the Laravel defaults!
|
*/
'markdown' => [
'theme' => 'default',
'paths' => [
resource_path('views/vendor/mail'),
],
],
];
| true |
fcf2602c3ea3a696ef9f6738ab3ea3d44ef1c689 | PHP | artviks/WannabeTinder | /app/Models/User.php | UTF-8 | 1,200 | 3.25 | 3 | [] | no_license | <?php
namespace WTinder\Models;
class User
{
private string $name;
private string $surname;
private string $email;
private string $gender;
private string $password;
private string $id;
public function __construct(
string $name,
string $surname,
string $email,
string $gender,
string $password
)
{
$this->name = $name;
$this->surname = $surname;
$this->email = $email;
$this->gender = $gender;
$this->setPassword($password);
}
public function getName(): string
{
return $this->name;
}
public function getSurname(): string
{
return $this->surname;
}
public function getEmail(): string
{
return $this->email;
}
public function getPassword(): string
{
return $this->password;
}
public function getGender(): string
{
return $this->gender;
}
private function setPassword(string $password): void
{
$passwordEncrypted = password_hash($password, PASSWORD_DEFAULT);
if ($passwordEncrypted) {
$this->password = $passwordEncrypted;
}
}
} | true |
6555cc44a9e7c199055a19bee83db09b42595175 | PHP | tolgadevsec/php | /src/Core/SessionContext.php | UTF-8 | 387 | 2.703125 | 3 | [
"MIT"
] | permissive | <?php
namespace BitSensor\Core;
/**
* Information about the PHP session of the user.
* @package BitSensor\Core
*/
class SessionContext extends Constants
{
/**
* PHP session.
*/
const NAME = 'session';
/**
* Session ID of the connecting user.
*/
const SESSION_ID = 'sessionId';
/**
* Username.
*/
const USERNAME = 'username';
} | true |
013f2652fd8733f0a96b7f41e8b94b3dec25a58a | PHP | 28kayak/BlogEngine_PHP | /config/createDB.php | UTF-8 | 3,056 | 3.09375 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: kaya
* Date: 8/18/16
* Time: 4:07 PM
*/
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "blog";
//create connection
$conn = new mysqli($servername, $username, $password);
//check connection
if($conn->connect_error)
{
echo "Connection Failed: " . $conn->connect_error;
die("Connection Failed: ".$conn->connect_error);
}
else
{
echo "<br>OK to Connect<br>";
echo "<br>Call Create DB<br>";
createDB($conn);
echo "<br>Close DB<br>";
//$conn->close();
echo "<br>Reconnect<br>";
/* change db to world db */
mysqli_select_db($conn, $dbname);
if ($conn->connect_error)
{
echo "Connection Failed: " . $conn->connect_error;
die("Connection Failed: ".$conn->connect_error);
}
else
{
createPost($conn);
createUser($conn);
createCategory($conn);
}
}
echo "<br>Before closing DB<br>";
$conn->close();
function createDB($conn)
{
$sql = "CREATE DATABASE blog";
if(mysqli_query($conn,$sql))
{//query succeed!
echo "<br>query succeed: createDB()<br>";
}
else
{
echo "<br>Error description: " . mysqli_error($conn)."<br>";
}
}
/**
* @param $conn connction with databse
*/
function createPost($conn)
{
$sql = "CREATE TABLE Posts(
post_id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
title VARCHAR(150),
posted_date TIMESTAMP,
body TEXT,
category VARCHAR(150)
)";
if(mysqli_query($conn, $sql))
{
echo "<br>Query Succeed: createPost()<br>";
}
else {
echo "<br>Error description: " . mysqli_error($conn)."<br>";
}
}
function createUser($conn){
$sql = "CREATE TABLE Users(
user_id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(150) NOT NULL,
password VARCHAR (150) NOT NULL
)";
if(mysqli_query($conn,$sql))
{
echo "<br>Query Succeed: createUsers()<br>";
}
else{
echo "<br>Error description: " . mysqli_error($conn)."<br>";
}
}
function createCategory($conn)
{
$sql = "CREATE TABLE Category(
category_id INT AUTO_INCREMENT PRIMARY KEY,
category VARCHAR(150) NOT NULL
)";
if(mysqli_query($conn,$sql))
{
echo "<br>Query Succeed: createCategory()<br>";
}
else{
echo "<br>Error description: " . mysqli_error($conn)."<br>";
}
}
function connectToDB()
{
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error)
{
echo "Connection Failed: " . $conn->connect_error;
die("Connection Failed: ".$conn->connect_error);
}
else {
echo "<br>OK to Connect<br>";
}
return $conn;
}
/**
//Create Table
$conn = new mysqli($servername, $username, $password, $dbname);
//Check Connection
if($conn->connect_error)
{
die("Connection Failed: " . $conn->connect_error);
}
**/
?> | true |
db2033a88a0ec583eb033370652f158cc517684f | PHP | hctom/drubo | /src/Config/Filesystem/FilesystemConfigListInterface.php | UTF-8 | 403 | 2.546875 | 3 | [
"MIT"
] | permissive | <?php
namespace Drubo\Config\Filesystem;
/**
* Interface for drubo filesystem configuration list classes.
*/
interface FilesystemConfigListInterface extends \Iterator, \Countable {
/**
* {@inheritdoc}
*
* @return FilesystemConfigItemInterface
*/
public function current();
/**
* {@inheritdoc}
*
* @return FilesystemConfigItemInterface
*/
public function next();
}
| true |
149777f8dcf6de1c7ac534ce70459c246640927a | PHP | ARCANEDEV/LaravelHtml | /tests/Traits/FormAccessible.php | UTF-8 | 3,527 | 2.65625 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types=1);
namespace Arcanedev\LaravelHtml\Tests\Traits;
use Arcanedev\LaravelHtml\Tests\Stubs\{ModelThatDoesntUseForms, ModelThatUsesForms};
use Arcanedev\LaravelHtml\Tests\TestCase;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
/**
* Class FormAccessible
*
* @author ARCANEDEV <arcanedev.maroc@gmail.com>
*/
class FormAccessible extends TestCase
{
/* -----------------------------------------------------------------
| Properties
| -----------------------------------------------------------------
*/
/**
* The model data.
*
* @var array
*/
protected $modelData = [];
/**
* The Carbon instance.
*
* @var \Carbon\Carbon
*/
protected $now;
/**
* The Form builder instance.
*
* @var \Arcanedev\LaravelHtml\FormBuilder
*/
protected $form;
/* -----------------------------------------------------------------
| Main Methods
| -----------------------------------------------------------------
*/
public function setUp(): void
{
parent::setUp();
$this->migrate();
Model::unguard();
$this->now = Carbon::now();
$this->modelData = [
'string' => 'abcdefghijklmnop',
'email' => 'tj@tjshafer.com',
'address' => [
'street' => 'abcde st'
],
'created_at' => $this->now,
'updated_at' => $this->now,
];
$this->form = $this->getFormBuilder();
}
/* -----------------------------------------------------------------
| Tests
| -----------------------------------------------------------------
*/
/** @test */
public function it_can_mutate_values_for_forms(): void
{
$model = new ModelThatUsesForms($this->modelData);
$this->form->setModel($model);
static::assertSame('ponmlkjihgfedcba', $model->getFormValue('string'));
static::assertSame($this->now->timestamp, $model->getFormValue('created_at'));
}
/** @test */
public function it_can_still_mutate_values_for_views(): void
{
$model = new ModelThatUsesForms($this->modelData);
$this->form->setModel($model);
static::assertSame('ABCDEFGHIJKLMNOP', $model->string);
static::assertSame('1 second ago', $model->created_at);
}
/** @test */
public function it_does_not_require_the_use_of_this_feature(): void
{
$model = new ModelThatDoesntUseForms($this->modelData);
$this->form->setModel($model);
static::assertSame('ABCDEFGHIJKLMNOP', $model->string);
static::assertSame('1 second ago', $model->created_at);
}
/** @test */
public function it_can_get_related_value_for_forms(): void
{
$model = new ModelThatUsesForms($this->modelData);
$this->form->setModel($model);
static::assertSame('abcde st', $model->getFormValue('address.street'));
}
/** @test */
public function it_can_mutate_related_values_for_forms(): void
{
$model = new ModelThatUsesForms($this->modelData);
$model->setRelation(
'related',
new ModelThatUsesForms($this->modelData)
);
$this->form->setModel($model);
static::assertSame($this->form->getValueAttribute('related[string]'), 'ponmlkjihgfedcba');
static::assertSame($this->form->getValueAttribute('related[created_at]'), $this->now->timestamp);
}
}
| true |
55c139cd4cbbe5e22ef9ab47e89801a7fc90bb0f | PHP | donthedeveloper/streamerstats-old | /classes/ValidateInput.php | UTF-8 | 1,097 | 2.984375 | 3 | [] | no_license | <?php
class ValidateInput {
// returns array of passed(true) & failed(false) inputs
public function inputIsNotEmpty($inputArray, $requiredArray) {
$validatedInputArray = array();
foreach($inputArray as $inputName => $inputValue) {
// if the current input being looped through is required
if ($requiredArray[$inputName]) {
if ( empty($inputValue) ) {
$validatedInputArray[$inputName] = FALSE;
}
else {
$validatedInputArray[$inputName] = TRUE;
}
}
}
return $validatedInputArray;
}
public function emailIsValid($inputName) {
$validatedEmail = filter_input(INPUT_POST, $inputName, FILTER_VALIDATE_EMAIL);
if ($validatedEmail) {
return TRUE;
}
else {
return FALSE;
}
}
public function isAlphaNumeric($input) {
$validatedInput = ctype_alnum($input);
if ($validatedInput) {
return TRUE;
}
else {
return FALSE;
}
}
}
| true |
10fc16c20a491c42e98f6b37901d8c8e6435f1c8 | PHP | ikebe094/simple-chat-2020 | /get_typing.php | UTF-8 | 1,151 | 2.84375 | 3 | [] | no_license | <?php
$sql = null;
$res = null;
$dbh = null;
// ホスト名、DB名、サーバーでPHPを実行する際のユーザー名・パスワードを指定する
$host_url = '****';
$db_name = '****';
$php_user = '****';
$php_pass = '****';
date_default_timezone_set('Asia/Tokyo');
$date = array("datenow"=>date("Y-m-d H:i:s"));
// ルーム名をURLの引数で指定し、テーブル名を整形する
$room_id_v = $_GET['room_id'];
if (is_null($room_id_v)) {
exit();
}
$table_name = $room_id_v . "_typing";
$host_dbname = 'pgsql:host=' . $host_url . ';dbname=' . $db_name . ';';
try {
$dbh = new PDO($host_dbname, $php_user, $php_pass);
$sql = "SELECT * FROM $table_name";
$res = $dbh->query($sql);
$typing_data = array();
foreach ($res as $value) {
$typing_data[] = array(
'typing_user_id' => $value['user_id'],
'typing_user_name' => $value['user_name'],
'regist_datetime' => $value['regist_datetime'],
);
}
array_unshift($typing_data, $date);
echo json_encode($typing_data);
} catch (PDOException $e) {
echo $e->getMessage();
die();
}
$dbh = null;
| true |
1d24aa4e78edb7626909dfdeef9a72743a6f0f97 | PHP | nilshollmer/oophp-v5 | /src/Dice100/DicePlayer.php | UTF-8 | 1,803 | 3.734375 | 4 | [] | no_license | <?php
namespace Nihl\Dice100;
/**
* Player class for Dice100 game
*
*/
class DicePlayer
{
/**
* @var string type Type of player
* @var string name Name of player
* @var integer totalPoints Total points
*/
protected $type;
protected $name;
protected $totalPoints;
/**
* Instanciate player with name and 0 points
*
* @param string name Name of player
*/
public function __construct(string $name = null)
{
$this->type = "Player";
$this->name = $name ? $name : $this->type . rand(1000, 9999);
$this->totalPoints = 0;
}
/**
* Get player name
*
* @return string Name of player
*/
public function getName()
{
return $this->name;
}
/**
* Get player type
*
* @return string Type of player
*/
public function getType()
{
return $this->type;
}
/**
* Get player points
*
* @return integer Player points
*/
public function getTotalPoints()
{
return $this->totalPoints;
}
/**
* Set player points
*
* @param integer Player points
*
* @return void
*/
public function setTotalPoints(int $points)
{
$this->totalPoints = $points;
}
/**
* Add player points
*
* @param int $points Points to add
* @return void
*/
public function addPoints(int $points)
{
$this->totalPoints += $points;
}
/**
* Returns true if players total points is greater than or equal to 100
* else false
*
* @return boolean
*/
public function hasWon()
{
return $this->totalPoints >= 100;
}
}
| true |
52439f93fd13b33b28d63823676422983b21415c | PHP | Jasdoge/Djukebox | /scripts/class Tools.php | UTF-8 | 3,310 | 2.765625 | 3 | [
"MIT"
] | permissive | <?php
class Tools{
public static $ERRORS = array();
public static $NOTICES = array();
public static $N_DUMPED = false;
static function addError($text){
self::$ERRORS[] = $text;
}
static function addNotice($text){
self::$NOTICES[] = $text;
}
static function minmax($val, $min = 0, $max = 1){
if($val<$min)return $min;
else if($val>$max)return $max;
return $val;
}
static function dumpNotices(){
if(isset($GLOBALS['errors']))self::$ERRORS = array_merge(self::$ERRORS, $GLOBALS['errors']);
if(isset($GLOBALS['notices']))self::$NOTICES = array_merge(self::$NOTICES, $GLOBALS['notices']);
$GLOBALS['errors'] = array();
$GLOBALS['notices'] = array();
if(!self::$N_DUMPED){
echo '<div class="noticewindow hidden buttonSound" id="noticediv"><p>';
echo '<p class="noticeblue" id="noticetext"></p>';
echo '</div>';
echo '<div class="errorwindow hidden buttonSound" id="errordiv">';
echo '<p class="red" id="errortext"></p>';
echo '</div>';
self::$N_DUMPED = true;
}
if(count(self::$ERRORS) || count(self::$NOTICES)){
echo '<script><!--
';
if(count(self::$ERRORS))
echo 'Tools.addErrors(\''.nl2br(addslashes(implode('<br />', self::$ERRORS))).'\', true);';
if(count(self::$NOTICES))
echo 'Tools.addErrors(\''.nl2br(addslashes(implode('<br />', self::$NOTICES))).'\', false);';
echo '
--></script>';
}
self::$ERRORS = array();
self::$NOTICES = array();
}
public static function postExists(){
$fields = func_get_args();
foreach($fields as $key=>$val)
if(!isset($_POST[$val]))return false;
return true;
}
public static function multiIsset($source, $test){
foreach($test as $key=>$val){
if(!isset($source[$val]))return false;
}
return true;
}
public static function float2fraction($n, $tolerance = 1.e-6) {
$h1=1; $h2=0;
$k1=0; $k2=1;
$b = 1/$n;
do {
$b = 1/$b;
$a = floor($b);
$aux = $h1; $h1 = $a*$h1+$h2; $h2 = $aux;
$aux = $k1; $k1 = $a*$k1+$k2; $k2 = $aux;
$b = $b-$a;
} while (abs($n-$h1/$k1) > $n*$tolerance);
return "$h1/$k1";
}
public static function jasPaginate($startfrom, $ppp, $maxentries, $linkprefix, $nrstoshow){
$totalpages = ceil($maxentries/$ppp);
if($totalpages>1){
$currentpage = round($startfrom/$ppp);
$start = $currentpage-floor($nrstoshow/2);
$end = $currentpage+floor($nrstoshow/2);
if($start<0){
$end -= $start;
$start = 0;
}
if($end>$totalpages){
$start-=($end-$totalpages);
$end=$totalpages;
}
if($start<0)$start = 0;
$prev = $currentpage-1; if($prev<0)$prev=0;
$next = $currentpage+1; if($next>=$totalpages)$next=$totalpages-1;
echo '<p>';
echo '<a class="nav" href="'.$linkprefix.'0'.'"><<</a>';
echo '<a class="nav" href="'.$linkprefix.($prev*$ppp).'"><</a>';
for($i=$start; $i<$end; $i++){
echo '<a class="nav';
if($i==$currentpage)echo ' current';
echo '" href="'.$linkprefix.$i*$ppp.'">'.($i+1).'</a> ';
}
echo '<a class="nav" href="'.$linkprefix.$next*$ppp.'">></a>';
echo '<a class="nav" href="'.$linkprefix.($totalpages-1)*$ppp.'">>></a>';
echo '</p>';
}
}
}
| true |
aa9dd0dd1560f2519c6611eb76bc4392dfb92c24 | PHP | Ahlam97A/test_project | /src/views/Icons/aa.php | UTF-8 | 1,528 | 2.546875 | 3 | [
"MIT"
] | permissive |
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS, DELETE, PUT');
header('Access-Control-Allow-Headers: token, Content-Type');
header('Access-Control-Expose-Headers: *');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Origin: http://localhost:3000');
$db = new mysqli("localhost", "root", "", "project_new");
if (!$db) die("database connection error");
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password, "project_new");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
echo "Connected successfully";
}
$payload = file_get_contents('php://input');
$input = json_decode($payload, true);
$first_name = $input['fname'];
$Mid_name = $input['mname'];
$Last_name = $input['lname'];
$teacherid = $input['id_t'];
$id = $input['id'];
$pass = $input['pwd'];
$date = $input['DateofBirth'];
$subject = $input['sub'];
$address = $input['address'];
$phone = $input['phone'];
// Attempt insert query execution
$sql = "INSERT INTO teacher(fname,mname,lname, id,subject,classid,phone,password ,address,DateBirth) VALUES ('$first_name','$Mid_name','$Last_name','$teacherid','$subject','$id','$phone','$pass','$address','$date')";
echo $sql;
if (mysqli_query($conn, $sql)) {
echo "Records added successfully.";
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn);
}
?>
| true |
5da0ef3e532392f73b7e2c684aed8437a841d5e7 | PHP | florianprechtl/InventoryManager | /InventoryManager/src/login/login-register/uploaduser.php | UTF-8 | 2,920 | 3.078125 | 3 | [] | no_license | <!-- As its name indicates, this code is to place the characteristics of new users into the db-->
<?php
include('../../common/connectDB.php');
include('../../common/basicFunctions.php');
// Connecting to the database
$db = connectToDB();
// Setting up variables
$usernr = null;
// Validation and sanitization
// Firstname
if (isset($_POST['firstname'])) {
$firstname = filter_var($_POST['firstname'], FILTER_SANITIZE_STRING);
} else {
redirect(explode('?', $_SERVER['HTTP_REFERER'])[0] . '?registerSuccessful=false');
}
// Lastname
if (isset($_POST['lastname'])) {
$lastname = filter_var($_POST['lastname'], FILTER_SANITIZE_STRING);
} else {
redirect(explode('?', $_SERVER['HTTP_REFERER'])[0] . '?registerSuccessful=false');
}
// Username
if (isset($_POST['newusername'])) {
$newusername = filter_var($_POST['newusername'], FILTER_SANITIZE_STRING);
} else {
redirect(explode('?', $_SERVER['HTTP_REFERER'])[0] . '?registerSuccessful=false');
}
// Age
if (isset($_POST['age'])) {
$age = filter_var($_POST['age'], FILTER_SANITIZE_NUMBER_INT);
} else {
redirect(explode('?', $_SERVER['HTTP_REFERER'])[0] . '?registerSuccessful=false');
}
// Sex
if (isset($_POST['sex'])) {
$sex = filter_var($_POST['sex'], FILTER_SANITIZE_STRING);
} else {
redirect(explode('?', $_SERVER['HTTP_REFERER'])[0] . '?registerSuccessful=false');
}
// Password
if (isset($_POST['psw'])) {
$psw = filter_var($_POST['psw'], FILTER_SANITIZE_STRING);
} else {
redirect(explode('?', $_SERVER['HTTP_REFERER'])[0] . '?registerSuccessful=false');
}
// Repeated password
if (isset($_POST['repeatedpsw'])) {
$repeatedpsw = filter_var($_POST['repeatedpsw'], FILTER_SANITIZE_STRING);
} else {
redirect(explode('?', $_SERVER['HTTP_REFERER'])[0] . '?registerSuccessful=false');
}
// Get current date
$dateRegister = date("Y-m-d");
// Check if user entered equal passwords
if ($psw == $repeatedpsw) {
$psw = password_hash($psw, PASSWORD_DEFAULT);
$sql= "INSERT INTO user (UserNr, Username, Firstname, Lastname, Password, Age, Sex, MemberSince)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
$stmt = $db->prepare($sql);
$stmt->bind_param('issssiss', $usernr, $newusername, $firstname, $lastname, $psw, $age, $sex, $dateRegister);
print_r($stmt);
echo "<br>";
$stmt->execute();
echo $stmt->get_result();
echo "<br>";
print_r($stmt);
redirect(explode('?', $_SERVER['HTTP_REFERER'])[0] . '?registerSuccessful=true');
} else {
redirect(explode('?', $_SERVER['HTTP_REFERER'])[0] . '?registerSuccessful=false');
}
?>
| true |
68f144951c41af3ffdd7d27f1e2c204ca89b35e1 | PHP | sxeseb/StrasCook | /src/Service/CartService.php | UTF-8 | 2,594 | 2.84375 | 3 | [] | no_license | <?php
namespace App\Service;
class CartService
{
public function addToCart()
{
$errors = [];
$datas = [];
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (!isset($_POST['gridRadios']) || empty($_POST['gridRadios'])) {
$errors['price'] = "Selectionnez une option de prix";
} else {
$price = $this->testInput($_POST['gridRadios']);
$datas['price'] = $price;
}
if (!isset($_POST['menu_q']) || empty($_POST['menu_q'])) {
$errors['quantity'] = "Selectionnez un nombre de couverts";
} else {
$quantity = $this->testInput($_POST['menu_q']);
$datas['quantity'] = $quantity;
}
if (isset($_POST['menu_id']) && !empty($_POST['menu_id'])) {
$menuId = $this->testInput($_POST['menu_id']);
$datas['menuId'] = $menuId;
}
if (isset($_POST['menu_name']) && !empty($_POST['menu_name'])) {
$menuName = $this->testInput($_POST['menu_name']);
$datas['menuName'] = $menuName;
}
}
if (empty($errors)) {
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'][] = $datas;
} else {
$match = 0;
for ($i = 0; $i < count($_SESSION['cart']); $i++) {
if ($_SESSION['cart'][$i]['menuId'] == $datas['menuId']
&& $_SESSION['cart'][$i]['price'] == $datas['price']) {
$_SESSION['cart'][$i]['quantity'] += $datas['quantity'];
$match++;
}
}
if ($match == 0) {
$_SESSION['cart'][] = $datas;
}
}
}
return array($errors, $datas);
}
public function calculTotal($datas) :array
{
$localCount = 0;
$normalCount = 0;
$total = 0;
foreach ($datas as $row) {
if ($row['price'] == 1) {
$normalCount += $row['quantity'];
} else {
$localCount += $row['quantity'];
}
}
$total = $localCount * 30 + $normalCount * 20;
return array('normal' => $normalCount, 'local' => $localCount, 'total' => $total);
}
public function testInput($input)
{
$input = trim($input);
$input = stripcslashes($input);
$input = htmlspecialchars($input);
return $input;
}
}
| true |
42545d9361040b4a3514e1ed4b1ed91997cb055c | PHP | Arshad83/php | /php_examples/array.php | UTF-8 | 745 | 2.90625 | 3 | [] | no_license | <?php
$car['test']=array('first'=>'maruti','suzuki','third'=>'kwid');
var_dump($car['test']);
echo '<br/>';
var_dump($car);
echo '<br/>';
$car=array('first'=>array('m1'=>'maruti_volta',
'm2'=>'maruti_x'
),
'second'=>'suzuki',
'third'=>'kwid');
var_dump($car);
?>
<!-- output
array(3) { ["first"]=> string(6) "maruti" [0]=> string(6) "suzuki" ["third"]=> string(4) "kwid" }
array(1) { ["test"]=> array(3) { ["first"]=> string(6) "maruti" [0]=> string(6) "suzuki" ["third"]=> string(4) "kwid" } }
array(3) { ["first"]=> array(2) { ["m1"]=> string(12) "maruti_volta" ["m2"]=> string(8) "maruti_x" } ["second"]=> string(6) "suzuki" ["third"]=> string(4) "kwid" }
--> | true |
a7c4b3156d69408085e2da561c2122d12ec66ecf | PHP | franzose/kontrolio | /src/Rules/Core/Range.php | UTF-8 | 2,056 | 3.421875 | 3 | [
"MIT"
] | permissive | <?php
namespace Kontrolio\Rules\Core;
use DateTime as PhpDateTime;
use DateTimeInterface;
use InvalidArgumentException;
use LogicException;
use Kontrolio\Rules\AbstractRule;
/**
* Range of values validation rule.
*
* @package Kontrolio\Rules\Core
*/
class Range extends AbstractRule
{
/**
* @var mixed|null
*/
protected $min;
/**
* @var mixed|null
*/
protected $max;
/**
* Range constructor.
*
* @param mixed $min
* @param mixed $max
*/
public function __construct($min = null, $max = null)
{
if ($min === null && $max === null) {
throw new InvalidArgumentException('Either option "min" or "max" must be given.');
}
if ($min !== null && $max !== null && $min > $max) {
throw new LogicException('"Min" option cannot be greater that "max".');
}
if ($max !== null && $max < $min) {
throw new LogicException('"Max" option cannot be less that "min".');
}
$this->min = $min;
$this->max = $max;
}
/**
* Validates input.
*
* @param mixed $input
*
* @return bool
*/
public function isValid($input = null)
{
if ($input === null) {
return false;
}
if (!is_numeric($input) && !$input instanceof DateTimeInterface) {
$this->violations[] = 'numeric';
return false;
}
if ($input instanceof DateTimeInterface) {
if (is_string($this->min)) {
$this->min = new PhpDateTime($this->min);
}
if (is_string($this->max)) {
$this->max = new PhpDateTime($this->max);
}
}
if ($this->max !== null && $input > $this->max) {
$this->violations[] = 'max';
return false;
}
if ($this->min !== null && $input < $this->min) {
$this->violations[] = 'min';
return false;
}
return true;
}
}
| true |
5c3e630aeeb0644c4a35bf07c6676e7a5a2dec5e | PHP | friendica/red | /library/asn1.php | UTF-8 | 8,375 | 2.734375 | 3 | [
"MIT"
] | permissive | <?php
// ASN.1 parsing library
// Attribution: http://www.krisbailey.com
// license: unknown
// modified: Mike Macgrivin mike@macgirvin.com 6-oct-2010 to support Salmon auto-discovery
// from openssl public keys
class ASN_BASE {
public $asnData = null;
private $cursor = 0;
private $parent = null;
public static $ASN_MARKERS = array(
'ASN_UNIVERSAL' => 0x00,
'ASN_APPLICATION' => 0x40,
'ASN_CONTEXT' => 0x80,
'ASN_PRIVATE' => 0xC0,
'ASN_PRIMITIVE' => 0x00,
'ASN_CONSTRUCTOR' => 0x20,
'ASN_LONG_LEN' => 0x80,
'ASN_EXTENSION_ID' => 0x1F,
'ASN_BIT' => 0x80,
);
public static $ASN_TYPES = array(
1 => 'ASN_BOOLEAN',
2 => 'ASN_INTEGER',
3 => 'ASN_BIT_STR',
4 => 'ASN_OCTET_STR',
5 => 'ASN_NULL',
6 => 'ASN_OBJECT_ID',
9 => 'ASN_REAL',
10 => 'ASN_ENUMERATED',
13 => 'ASN_RELATIVE_OID',
48 => 'ASN_SEQUENCE',
49 => 'ASN_SET',
19 => 'ASN_PRINT_STR',
22 => 'ASN_IA5_STR',
23 => 'ASN_UTC_TIME',
24 => 'ASN_GENERAL_TIME',
);
function __construct($v = false)
{
if (false !== $v) {
$this->asnData = $v;
if (is_array($this->asnData)) {
foreach ($this->asnData as $key => $value) {
if (is_object($value)) {
$this->asnData[$key]->setParent($this);
}
}
} else {
if (is_object($this->asnData)) {
$this->asnData->setParent($this);
}
}
}
}
public function setParent($parent)
{
if (false !== $parent) {
$this->parent = $parent;
}
}
/**
* This function will take the markers and types arrays and
* dynamically generate classes that extend this class for each one,
* and also define constants for them.
*/
public static function generateSubclasses()
{
define('ASN_BASE', 0);
foreach (self::$ASN_MARKERS as $name => $bit)
self::makeSubclass($name, $bit);
foreach (self::$ASN_TYPES as $bit => $name)
self::makeSubclass($name, $bit);
}
/**
* Helper function for generateSubclasses()
*/
public static function makeSubclass($name, $bit)
{
define($name, $bit);
eval("class ".$name." extends ASN_BASE {}");
}
/**
* This function reset's the internal cursor used for value iteration.
*/
public function reset()
{
$this->cursor = 0;
}
/**
* This function catches calls to get the value for the type, typeName, value, values, and data
* from the object. For type calls we just return the class name or the value of the constant that
* is named the same as the class.
*/
public function __get($name)
{
if ('type' == $name) {
// int flag of the data type
return constant(get_class($this));
} elseif ('typeName' == $name) {
// name of the data type
return get_class($this);
} elseif ('value' == $name) {
// will always return one value and can be iterated over with:
// while ($v = $obj->value) { ...
// because $this->asnData["invalid key"] will return false
return is_array($this->asnData) ? $this->asnData[$this->cursor++] : $this->asnData;
} elseif ('values' == $name) {
// will always return an array
return is_array($this->asnData) ? $this->asnData : array($this->asnData);
} elseif ('data' == $name) {
// will always return the raw data
return $this->asnData;
}
}
/**
* Parse an ASN.1 binary string.
*
* This function takes a binary ASN.1 string and parses it into it's respective
* pieces and returns it. It can optionally stop at any depth.
*
* @param string $string The binary ASN.1 String
* @param int $level The current parsing depth level
* @param int $maxLevel The max parsing depth level
* @return ASN_BASE The array representation of the ASN.1 data contained in $string
*/
public static function parseASNString($string=false, $level=1, $maxLevels=false){
if (!class_exists('ASN_UNIVERSAL'))
self::generateSubclasses();
if ($level>$maxLevels && $maxLevels)
return array(new ASN_BASE($string));
$parsed = array();
$endLength = strlen($string);
$bigLength = $length = $type = $dtype = $p = 0;
while ($p<$endLength){
$type = ord($string[$p++]);
$dtype = ($type & 192) >> 6;
if ($type==0){ // if we are type 0, just continue
} else {
$length = ord($string[$p++]);
if (($length & ASN_LONG_LEN)==ASN_LONG_LEN){
$tempLength = 0;
for ($x=0; $x<($length & (ASN_LONG_LEN-1)); $x++){
$tempLength = ord($string[$p++]) + ($tempLength * 256);
}
$length = $tempLength;
}
$data = substr($string, $p, $length);
$parsed[] = self::parseASNData($type, $data, $level, $maxLevels);
$p = $p + $length;
}
}
return $parsed;
}
/**
* Parse an ASN.1 field value.
*
* This function takes a binary ASN.1 value and parses it according to it's specified type
*
* @param int $type The type of data being provided
* @param string $data The raw binary data string
* @param int $level The current parsing depth
* @param int $maxLevels The max parsing depth
* @return mixed The data that was parsed from the raw binary data string
*/
public static function parseASNData($type, $data, $level, $maxLevels){
$type = $type%50; // strip out context
switch ($type){
default:
return new ASN_BASE($data);
case ASN_BOOLEAN:
return new ASN_BOOLEAN((bool)$data);
case ASN_INTEGER:
return new ASN_INTEGER(strtr(base64_encode($data),'+/','-_'));
case ASN_BIT_STR:
return new ASN_BIT_STR(self::parseASNString($data, $level+1, $maxLevels));
case ASN_OCTET_STR:
return new ASN_OCTET_STR($data);
case ASN_NULL:
return new ASN_NULL(null);
case ASN_REAL:
return new ASN_REAL($data);
case ASN_ENUMERATED:
return new ASN_ENUMERATED(self::parseASNString($data, $level+1, $maxLevels));
case ASN_RELATIVE_OID: // I don't really know how this works and don't have an example :-)
// so, lets just return it ...
return new ASN_RELATIVE_OID($data);
case ASN_SEQUENCE:
return new ASN_SEQUENCE(self::parseASNString($data, $level+1, $maxLevels));
case ASN_SET:
return new ASN_SET(self::parseASNString($data, $level+1, $maxLevels));
case ASN_PRINT_STR:
return new ASN_PRINT_STR($data);
case ASN_IA5_STR:
return new ASN_IA5_STR($data);
case ASN_UTC_TIME:
return new ASN_UTC_TIME($data);
case ASN_GENERAL_TIME:
return new ASN_GENERAL_TIME($data);
case ASN_OBJECT_ID:
return new ASN_OBJECT_ID(self::parseOID($data));
}
}
/**
* Parse an ASN.1 OID value.
*
* This takes the raw binary string that represents an OID value and parses it into its
* dot notation form. example - 1.2.840.113549.1.1.5
* look up OID's here: http://www.oid-info.com/
* (the multi-byte OID section can be done in a more efficient way, I will fix it later)
*
* @param string $data The raw binary data string
* @return string The OID contained in $data
*/
public static function parseOID($string){
$ret = floor(ord($string[0])/40).".";
$ret .= (ord($string[0]) % 40);
$build = array();
$cs = 0;
for ($i=1; $i<strlen($string); $i++){
$v = ord($string[$i]);
if ($v>127){
$build[] = ord($string[$i])-ASN_BIT;
} elseif ($build){
// do the build here for multibyte values
$build[] = ord($string[$i])-ASN_BIT;
// you know, it seems there should be a better way to do this...
$build = array_reverse($build);
$num = 0;
for ($x=0; $x<count($build); $x++){
$mult = $x==0?1:pow(256, $x);
if ($x+1==count($build)){
$value = ((($build[$x] & (ASN_BIT-1)) >> $x)) * $mult;
} else {
$value = ((($build[$x] & (ASN_BIT-1)) >> $x) ^ ($build[$x+1] << (7 - $x) & 255)) * $mult;
}
$num += $value;
}
$ret .= ".".$num;
$build = array(); // start over
} else {
$ret .= ".".$v;
$build = array();
}
}
return $ret;
}
public static function printASN($x, $indent=''){
if (is_object($x)) {
echo $indent.$x->typeName."\n";
if (ASN_NULL == $x->type) return;
if (is_array($x->data)) {
while ($d = $x->value) {
echo self::printASN($d, $indent.'. ');
}
$x->reset();
} else {
echo self::printASN($x->data, $indent.'. ');
}
} elseif (is_array($x)) {
foreach ($x as $d) {
echo self::printASN($d, $indent);
}
} else {
if (preg_match('/[^[:print:]]/', $x)) // if we have non-printable characters that would
$x = base64_encode($x); // mess up the console, then print the base64 of them...
echo $indent.$x."\n";
}
}
}
| true |
f6ec910b602b4687672e0ec2755be455d78b753e | PHP | hngi/Kymopoleia_bot | /landing.php | UTF-8 | 6,475 | 2.640625 | 3 | [] | no_license | <?php
/**
* A lightweight example script for demonstrating how to
* work with the Slack API.
*/
// Include our Slack interface classes
require_once 'slack-interface/class-slack.php';
require_once 'slack-interface/class-slack-access.php';
require_once 'slack-interface/class-slack-api-exception.php';
use Slack_Interface\Slack;
use Slack_Interface\Slack_API_Exception;
// Define Slack application identifiers
// Even better is to put these in environment variables so you don't risk exposing
// them to the outer world (e.g. by committing to version control)
define( 'SLACK_CLIENT_ID', '774475015110.774931713412' );
define( 'SLACK_CLIENT_SECRET', 'd5320591afa67c006636261d0afe74ca' );
//
// HELPER FUNCTIONS
//
/**
* Initializes the Slack handler object, loading the authentication
* information from a text file. If the text file is not present,
* the Slack handler is initialized in a non-authenticated state.
*
* @return Slack The Slack interface object
*/
function initialize_slack_interface() {
// Read the access data from a text file
if ( file_exists( 'access.txt' ) ) {
$access_string = file_get_contents( 'access.txt' );
} else {
$access_string = '{}';
}
// Decode the access data into a parameter array
$access_data = json_decode( $access_string, true );
$slack = new Slack( $access_data );
return $slack;
}
/**
* Executes an application action (e.g. 'send_notification').
*
* @param Slack $slack The Slack interface object
* @param string $action The id of the action to execute
*
* @return string A result message to show to the user
*/
function do_action( $slack, $action ) {
$result_message = '';
switch ( $action ) {
default:
break;
}
return $result_message;
}
//
// MAIN FUNCTIONALITY
//
// Setup the Slack interface
$slack = initialize_slack_interface();
// If an action was passed, execute it before rendering the page
$result_message = '';
if ( isset( $_REQUEST['action'] ) ) {
$action = $_REQUEST['action'];
$result_message = do_action( $slack, $action );
}
//
// PAGE LAYOUT
//
?>
<!-- <html>
<head>
<title>Slack Integration Example</title>
<style>
body {
font-family: Helvetica, sans-serif;
padding: 20px;
}
.notification {
padding: 20px;
background-color: #fafad2;
}
input {
padding: 10px;
font-size: 1.2em;
width: 100%;
}
</style>
</head>
<body>
<h1>Slack Integration Example</h1>
<form action="" method="post">
<input type="hidden" name="action" value="send_notification"/>
<p>
<input type="text" name="text" placeholder="Type your notification here and press enter to send." />
</p>
</form>
</body>
</html> -->
<!-- <?php if ( $slack->is_authenticated() ) : ?>
<form action="" method="post">
<input type="hidden" name="action" value="send_notification"/>
<p>
<input type="text" name="text" placeholder="Type your notification here and press enter to send." />
</p>
</form>
<?php else : ?>
<p>
<a href="https://slack.com/oauth/authorize?scope=incoming-webhook,commands&client_id=<?php echo $slack->get_client_id(); ?>"><img alt="Add to Slack" height="40" width="139" src="https://platform.slack-edge.com/img/add_to_slack.png" srcset="https://platform.slack-edge.com/img/add_to_slack.png 1x, https://platform.slack-edge.com/img/add_to_slack@2x.png 2x"></a>
</p>
<?php endif; ?> -->
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>KymopoleiaBot</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<link rel='stylesheet' type='text/css' media='screen' href='landingpage.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="path/to/font-awesome/css/font-awesome.min.css">
<link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
</head>
<body>
<header class="header">
<section class="navigation">
<div class="logo"> <i class="fa fa-robot" style="color: white"></i> <span class="logocolor">Kymopoleia</span>Bot</div>
<ul>
<!-- <li><a href="#">Home</a></li> -->
<!-- <li><a href="#">Features</a></li> -->
<!-- <li><a href="signup.php"><span class="loginbutton">Sign Up</span> </a></li> -->
<li><a href="logout.php"><span class="loginbutton">Logout</span></a></li>
</ul>
</section>
<section class="introduction">
<h2>Do Extra With <span class="introspan">KYMOPOLEIA BOT </span> ... In Slack!</h2>
<p class="introp">Join thousands of teams that use KymopoleiaBot to automate storage of Conversations on Slack workspace to an external drive</p>
<br>
<?php if ( $slack->is_authenticated() ) : ?>
<form action="" method="post">
<input type="hidden" name="action" value="send_notification"/>
<p>
<input type="text" name="text" placeholder="Type your notification here and press enter to send." />
</p>
</form>
<?php else : ?>
<p>
<a href="https://slack.com/oauth/authorize?scope=incoming-webhook,commands&client_id=<?php echo $slack->get_client_id(); ?>"><img alt="Add to Slack" height="40" width="139" src="https://platform.slack-edge.com/img/add_to_slack.png" srcset="https://platform.slack-edge.com/img/add_to_slack.png 1x, https://platform.slack-edge.com/img/add_to_slack@2x.png 2x"></a>
</p>
<?php endif; ?>
<br>
<a href="#"><button class="introbutton"> <i class="fa fa-slack" style="color: orangered; font-size: 30px; margin-right: 10px"></i> Add to Slack</button></a>
<br>
<br>
<p class="introp2">Start your free trial today. No credit card required.</p>
</section>
</header>
</body>
</html>
| true |
0f4afaf28f766c8cdd03d37861e240f1a0944d38 | PHP | jetsaus/repeate | /41/41f.php | UTF-8 | 645 | 3.625 | 4 | [] | no_license | <?php
/*
* Модуль функций
*/
function decade(int $dayMonth = 1)
// Возвращает декаду месяца, в зависимости от числа
{
// Число в диапазоне от 1 до 31
if (($dayMonth >= 1) && ($dayMonth <= 31)) {
$decadeNum = $dayMonth / 10;
if ($decadeNum <= 1) {
return 'первая декада';
} elseif ($decadeNum <= 2) {
return 'вторая декада';
} else {
return 'третья декада';
}
} else {
return 'не существующий день месяца';
}
}
| true |
16c82dd0d3869a5a89589a814e7af54760219ec3 | PHP | Windblow99/soultradelaravel | /app/Http/Controllers/Admin/UsersController.php | UTF-8 | 3,628 | 2.609375 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Role;
use App\Models\Category;
use App\Models\Personality;
use PDF;
use Illuminate\Support\Facades\Gate;
use Illuminate\Http\Request;
class UsersController extends Controller
{
/**
* Limiting page view to roles.
*
*
*/
public function __construct()
{
$this->middleware('auth');
}
// Generate PDF
public function createPDF() {
// retreive all records from db
$data = User::all();
// share data to view
view()->share('users',$data);
$pdf = PDF::loadView('adminPDF', $data);
// download PDF file with download method
return $pdf->download('pdf_users.pdf');
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request, User $users)
{
if ($request->term != NULL) {
$users = User::where([
['name', '!=', Null],
[function ($query) use ($request) {
if (($term = $request->term)) {
$query->where('name', 'LIKE', '%' . $term . '%')->get();
}
}]
])
->orderBy('id')
->paginate(10);
} else {
$users = User::all();
}
return view ('admin.users.index', compact('users'))
->with('i', (request()->input('page', 1) -1 ) * 5);
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\User $user
* @return \Illuminate\Http\Response
*/
public function edit(User $user)
{
if (Gate::denies('edit-users')) {
return redirect(route('admin.users.index'));
}
$roles = Role::all();
$categories = Category::all();
$personalities = Personality::all();
return view('admin.users.edit')->with([
'user' => $user,
'roles' => $roles,
'categories' => $categories,
'personalities' => $personalities,
]);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\User $user
* @return \Illuminate\Http\Response
*/
public function update(Request $request, User $user)
{
$user->category()->sync($request->categories);
$user->personality()->sync($request->personalities);
$user->roles()->sync($request->roles);
$user->name = $request->name;
$user->bio = $request->bio;
$user->approved = $request->approved;
$user->price = $request->price;
if ($user->save()){
$request->session()->flash('success', $user->name . ' has been updated');
} else {
$request->session()->flash('error', 'There was an error updating the user');
}
return redirect()->route('admin.users.index');
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\User $user
* @return \Illuminate\Http\Response
*/
public function destroy(User $user)
{
if (Gate::denies('edit-users')) {
return redirect(route('admin.users.index'));
}
$user->roles()->detach();
$user->personality()->detach();
$user->category()->detach();
$user->delete();
return redirect()->route('admin.users.index');
}
}
| true |
233a26fbcfb8fa596e48949c59aa29252cf1d1f6 | PHP | kostadinoval/codeigniter-qa | /application/controllers/guest_search.php | UTF-8 | 3,474 | 2.671875 | 3 | [] | no_license | <?php
class Guest_search extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->model("sessions_model");
$this->load->model("questions_model");
$this->load->model("answers_model");
$this->load->model("user_details_model");
}
public function index(){
$data = $this->sessions_model->get_user_data();
$data["title"] = "Guest Search";
$this->load->view('../includes/header.php', $data);
$this->load->view('guest_search_view');
$this->load->view('../includes/footer.php');
}
/**********************************
* Function that gets the search term submitted through AJAX
* and retrieves all the data as required by the specification.
* Retrieves:
* Question, who posted the question as well as the date
* All the answers with the person who answered and their rating
* All users who answered are ranked based on the rating of the provided answer and not by their total user rating
***********************************/
public function term(){
$search_term = urldecode($this->uri->segment(3));
$data["questions"] = $this->questions_model->search_titles($search_term);
if($data["questions"] != false){
for($i=0;$i<count($data["questions"]);$i++){
$data["questions"][$i]["answers"] = $this->answers_model->get_answers($data["questions"][$i]["question_id"]);
}
$index = 0;
for($i=0; $i<count($data["questions"]); $i++){
foreach($data["questions"][$i]["answers"] as $answer){
$result = $this->user_details_model->get_rating($answer["user_id"]);
$data["questions"][$i]["answers"][$index]["user_rating"] = $result;
$index++;
}
$index = 0;
}
$html = "";
foreach($data["questions"] as $question){
$html .= '<div class="results_table">
<div class="answer_info">
<p class="number_of_answers">';
if(count($question["answers"]) == 0){
$html .= '<span class="guest_search_header"> 0 answers </span>';
}
else if(count($question["answers"]) == 1){
$html .= '<span class="guest_search_header">1 answer </span>';
$html .= '<p class="small_text">Users who answered(rating):</p><p class="small_text">(ordered by their answer rating)</p>';
}
else{
$html .= '<span class="guest_search_header">' . count($question["answers"]) . ' answers </span>';
$html .= '<p class="small_text">Users who answered(rating):</p><p class="small_text">(ordered by their answer rating)</p>';
}
$html .= '</p>';
if(count($question["answers"]) > 0){
$html .= '<ul class="who_answered_list">';
foreach($question["answers"] as $answer){
$html .= '<li><b>' . htmlspecialchars($answer["username"]);
$html .= ' (' . $answer["user_rating"] . ')';
$html .= '</b></li>';
}
$html .= '</ul>';
}
$html .= '</div>';
$html .= '<div class="question_info">
<p class="title">';
$html .= '<a href="https://w1416464.users.ecs.westminster.ac.uk/CI_1/index.php/questions/view_question/' . $question["question_id"] . '">';
$html .= htmlspecialchars($question["title"]) . '</a></p>';
$html .= '<span class="posted_by">Posted by: <b>' . htmlspecialchars($question["username"]) . '</b></span>';
$html .= '<span class="posted_on">Posted on: <b>' . date("d.m.Y", strtotime($question["date_posted"])) . '</b></span>';
$html .= '</div>
</div>';
}
echo $html;
}
else{
echo "";
}
}
}
?> | true |
a70c861ece9cbbde4e696554c30e802e975d6c15 | PHP | tranbachngoc/projectMHDC | /app/app/Console/Commands/DeleteMessageChat.php | UTF-8 | 1,503 | 2.515625 | 3 | [] | no_license | <?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Log;
use Carbon\Carbon;
use App\Models\ChatMessages;
use App\Models\User;
use DB;
use App\Helpers\Commons;
class DeleteMessageChat extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'message_chat:delete';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command Delete Message Chat';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
//
date_default_timezone_set('Asia/Ho_Chi_Minh');
$current_date = date('Y-m-d');
$current_time = date('H:i');
$one_week_ago = Carbon::now()->subWeeks(1);
$messageDeleted = ChatMessages::getListMessageDeleted($one_week_ago);
echo $messageDeleted;
Log::info($messageDeleted);
/*$listUser = User::get();
foreach ( $listUser as $k => $v) {
$address = $v['use_address'];
$infoLatLng = Commons::getLatLng($address);
DB::table('tbtt_user')
->where('use_id', $v['use_id'])
->update(['use_lat' => $infoLatLng['lat'],'use_lng' => $infoLatLng['lng']]);
}
*/
}
}
| true |
44ecc7269a0208fe0fdc793212cae0bd18b0fa67 | PHP | annurkhozin/evotingweb | /application/views/admin/cetak/ttd.php | UTF-8 | 867 | 2.59375 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | <p> </p>
<p> </p>
<table width="100%" border="0">
<tr>
<td width="56%"> </td>
<td width="44%"><br>
<center>Bojonegoro <?php
date_default_timezone_set('Asia/Jakarta'); $jam=date('Y-m-d H:i:s');
/* script menentukan hari */
$array_hr= array(1=>"Senin","Selasa","Rabu","Kamis","Jumat","Sabtu","Minggu");
$hr = $array_hr[date('N')];
/* script menentukan tanggal */
$tgl= date('d');
/* script menentukan bulan */
$array_bln = array(1=>"Januari","Februari","Maret", "April", "Mei","Juni","Juli","Agustus","September","Oktober", "November","Desember");
$bln = $array_bln[date('n')];
/* script menentukan tahun */
$thn = date('Y');
/* script perintah keluaran*/
echo $hr . ", " . $tgl . " " . $bln . " " . $thn;
?> <br />Ttd,<br />
<p> </p>
<p> </p>
(________________)</center>
</td>
</tr>
</table> | true |
dc00b75dda7478130713e94031a5b12ad62d895d | PHP | thomaslu2000/minnowshare | /file.php | UTF-8 | 7,471 | 2.5625 | 3 | [] | no_license | <?php
include("header.php");
if(!isset($_GET['file'], $_GET['share']) or !is_numeric($_GET['file'])){
header("Location: browse.php");
exit();
}
$file_id = $_GET['file'];
switch($_GET['share']){
case 'public': case 'friends': case 'private':
$sharetype = $_GET['share'];
break;
default:
$sharetype = 'public';
}
include_once("./includes/functions.php");
function back($m){
close_connection_and_leave("browse.php", $m);
exit();
}
if($sharetype != 'public' and !$logged_in) back("Not Logged In!");
if(isset($_SESSION['userid'])) $u = $_SESSION['userid'];
require("./includes/connection.php");
$table = $sharetype . "_uploads";
$query = "SELECT owner_id, title, short, description, file_name FROM $table WHERE item_id=$file_id";
$file_data = mysqli_query($con, $query);
if(mysqli_affected_rows($con)!=1){
back('File Not Found');
}
$file_data = mysqli_fetch_assoc($file_data);
$filename = $file_data['file_name'];
$file_type = get_file_type($filename);
$file_info = pathinfo($filename);
$owner_id = $file_data['owner_id'];
$is_owner = $logged_in && $owner_id == $u;
$description = $file_data['description']=="NULL" ? 'No Description Provided' : $file_data['description'];
//Permissions
if($sharetype == 'friends' and !$is_owner){
$query = "SELECT null FROM access_files WHERE user=$u AND item_id=$file_id";
mysqli_query($con, $query);
if(mysqli_affected_rows($con)==0){
back("Please Ask For Permission To Access File");
}
} elseif($sharetype == 'private' and !$is_owner){
back("This File is Private");
}
if(! $owner_name = mysqli_query($con, "SELECT username FROM users WHERE userid=$owner_id")) back("Owner not Found");
$owner_name = mysqli_fetch_assoc($owner_name)['username'];
$path_to_file = "./uploads/$sharetype/$owner_id/";
$img = $path_to_file . $file_info['filename'] . '^@&$' . ".*";
$img = glob($img);
if($img){
$img = $img[0];
} elseif ($file_type == 'image') {
$img = $path_to_file . $filename;
} else {$img = "./images/".$file_type.'.jpg';
}
//delete needs names share and file
?>
<div class="container" align=center>
<a href="<?php echo $img ?>">
<img class="filepic" src="<?php echo $img ?>" alt="<?php echo $file_data['title'];?>">
</a>
<hr>
<form action="scripts/download.php" method="post">
<input type="hidden" name="file_loc" value="<?php echo $path_to_file . $filename; ?>">
<input type="hidden" name="filename" value="<?php echo $filename; ?>">
<button type="submit" class="btn btn-success">Download</button>
</form>
<hr>
<?php if($is_owner){?>
<form action=".\scripts\deleteFile.php" method="post">
<input type="hidden" name="share" value="<?php echo $sharetype ?>">
<input type="hidden" name="file" value="<?php echo $file_id ?>">
<button type="submit" class="btn btn-danger">Delete</button>
</form>
<hr>
<?php } ?>
<div class="container">
<table class="table table-striped table-hover" id="fileInfo">
<thead class="thead-dark">
<tr>
<th colspan="4">File Data</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">Title:</th>
<td colspan="3"><?php echo $file_data['title']; ?></td>
</tr>
<tr>
<th scope="row">Extension:</th>
<td><?php echo ".".$file_info['extension']; ?></td>
<th scope="row">Type:</th>
<td><?php echo $file_type; ?></td>
</tr>
<tr>
<th scope="row">Owner:</th>
<td colspan="3"><a href="profile.php?user=<?php echo $owner_id; ?>"><?php echo $owner_name; ?></a></td>
</tr>
<tr>
<th scope="row">Description:</th>
<td colspan="3"><?php echo $description; ?></td>
</tr>
</tbody>
</table>
<!-- Share if owner-->
<?php if($is_owner and $sharetype=='friends'){?>
<hr>
<h3 id="access">Manage Access To File</h3>
<div class="container">
<h2>Friend List</h2>
<div class="container" style="padding: 0 10% 0 10%;">
<ul class="list-group" id="friend-list-display">
<?php
$run = mysqli_query($con, "SELECT id_2 FROM friends WHERE status='friended' AND id_1=".$_SESSION['userid']);
while($result = mysqli_fetch_assoc($run)){
$friend_id = $result['id_2'];
if($friend_info = mysqli_fetch_assoc(mysqli_query($con, "SELECT username FROM users WHERE userid=$friend_id"))){
mysqli_query($con, "SELECT user FROM access_files WHERE user=$friend_id AND item_id=$file_id");
$access_status = mysqli_affected_rows($con);
?>
<li class="list-group-item d-flex justify-content-between align-items-center"> <?php echo $friend_info['username']; ?>
<form method="post" action="scripts/togglePermission.php">
<input type="hidden" name="item_id" value="<?php echo $file_id; ?>">
<input type="hidden" name="item_title" value="<?php echo $file_data['title']; ?>">
<input type="hidden" name="user_id" value="<?php echo $friend_id; ?>">
<input type="hidden" name="owner_id" value="<?php echo $u; ?>">
<input type="hidden" name="has_access" value="<?php echo $access_status; ?>">
<input type="hidden" name="url" value="<?php
$get = $_GET;
unset($get['message']);
echo $_SERVER['PHP_SELF'] . '?' . http_build_query($get);?>">
<button type="submit" class="btn <?php echo $access_status ? 'btn-success' : 'btn-danger'; ?>">
<?php
if($access_status){
echo 'Has Access';
} else{
echo 'No Access';
}?>
</button>
</form>
</li>
<?php
}
}
?>
</ul>
</div>
</div>
<?php } ?>
</div>
</div>
<?php include("footer.php"); ?> | true |
49e880df36df7a7b6cb3f6fc86589aedad25e5ed | PHP | EugeneErg/SQLPreprocessor | /src/Argument.php | UTF-8 | 1,840 | 3 | 3 | [] | no_license | <?php namespace EugeneErg\SQLPreprocessor;
final class Argument {
const IS_ARRAY = 'array';
const IS_SCALAR = 'scalar';
const IS_VARIABLE = 'variable';
const IS_FUNCTION = 'function';
const IS_FIELD = 'field';
const IS_NULL = 'null';
private $type;
private $value;
public static function byArray($array) {
foreach ($array as $key => $arg) {
$array[$key] = new Argument($arg);
}
return $array;
}
public function getType() {
if (isset($this->type)) {
return $this->type;
}
switch ($type = getType($this->value)) {
case 'array': return $this->type = Self::IS_ARRAY;
case 'NULL': return $this->type = Self::IS_NULL;
case 'object':
if ($this->value instanceof Variable) {
return $this->type = Self::IS_VARIABLE;
}
elseif ($this->value instanceof SQL) {
return $this->type = Self::IS_FUNCTION;
}
elseif ($this->value instanceof Field) {
return $this->type = Self::IS_FIELD;
}
break;
default:
if (is_scalar($this->value)) {
return $this->type = Self::IS_SCALAR;
}
}
throw new \Exception("Invalid function argument type '{$type}'");
}
public function getValue() {
return $this->value;
}
public function setValue($arg) {
$this->value = $arg;
$this->type = null;
if (Self::IS_ARRAY == $this->type = $this->getType()) {
$this->value = Self::byArray($arg);
}
return $this->value;
}
public function __construct($arg) {
$this->setValue($arg);
}
} | true |
80d55971046ac242eacae53f131eb78d8099acb8 | PHP | awagink/AdminSystem | /application/modules/admin/models/UserLevel/Repository.php | UTF-8 | 3,083 | 2.71875 | 3 | [] | no_license | <?php
class Admin_Model_UserLevel_Repository implements Admin_Model_UserLevel_IDAO, Zf_Model_IRepository
{
protected $_dao;
protected $_mapper;
/**
* @param unknown_type $dao
*/
public function setDao($dao) {
if (is_string($dao)) {
$dao = new $dao();
}
if (!$dao instanceof Admin_Model_UserLevel_DAO) {
throw new Admin_Model_UserLevel_Exception('Invalid data access object provided');
}
$this->_dao = $dao;
return $this;
}
/**
* @return Zf_Model_IDAO
*/
public function getDao() {
if (null === $this->_dao) {
$this->setDao('Admin_Model_UserLevel_DAO');
}
return $this->_dao;
}
/**
* @param unknown_type $mapper
*/
public function setMapper($mapper) {
if (is_string($mapper)) {
$mapper = new $mapper();
}
if (!$mapper instanceof Zf_Model_DataMapper) {
throw new Admin_Model_UserLevel_Exception('Invalid data mapper provided');
}
$this->_mapper = $mapper;
return $this;
}
/**
* @return Zf_Model_DataMapper
*/
public function getMapper() {
if (null === $this->_mapper) {
$this->setMapper('Admin_Model_UserLevel_Mapper');
}
return $this->_mapper;
}
/**
* @param unknown_type $id
*/
public function fetchRow($id) {
try {
$row = $this->getDao()->fetchRow($id);
$level = $this->getMapper()->assign(new Admin_Model_UserLevel_Entity(), $row);
return $level;
} catch (Admin_Model_UserLevel_Exception $ex) {
throw $ex;
} catch (Zf_Model_DataMapperException $ex) {
throw new Admin_Model_UserLevel_Exception($ex);
}
}
/**
* @param unknown_type $where
* @param unknown_type $order
* @param unknown_type $count
* @param unknown_type $offset
*/
public function fetchAll($where = null, $order = null, $count = null, $offset = null) {
try {
$rows = $this->getDao()->fetchAll($where, $order, $count, $offset);
$levels = array();
foreach ( $rows as $row ) {
$levels[] = $this->getMapper()->assign(new Admin_Model_UserLevel_Entity(), $row);
}
return $levels;
} catch (Admin_Model_UserLevel_Exception $ex) {
throw $ex;
} catch (Zf_Model_DataMapperException $ex) {
throw new Admin_Model_UserLevel_Exception($ex);
}
return null;
}
/**
* @param unknown_type $data
*/
public function save($data) {
try {
$dataArray = $this->getMapper()->map($data);
$this->getDao()->save($dataArray);
} catch (Admin_Model_UserLevel_Exception $ex) {
throw $ex;
}
return null;
}
/**
* @param unknown_type $data
*/
public function delete($data) {
try {
$dataArray = $this->getMapper()->map($data);
$this->getDao()->delete($dataArray);
} catch (Admin_Model_UserLevel_Exception $ex) {
throw $ex;
}
return null;
}
/**
* @param unknown_type $order
*/
public function select($order = null) {
try {
return $this->getDao()->select($order);
} catch (Admin_Model_UserLevel_Exception $ex) {
throw $ex;
}
return null;
}
}
| true |
00d1f71e9e4cacfc3f50b73a5256b6879ca99581 | PHP | brassbandpl/gestion-frais | /src/Command/ExpenseEventRecalcCommand.php | UTF-8 | 2,078 | 2.71875 | 3 | [] | no_license | <?php
namespace App\Command;
use App\Repository\ExpenseEventRepository;
use App\Service\ExpenseEventCalculator;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
class ExpenseEventRecalcCommand extends Command
{
protected static $defaultName = 'app:expense-event:recalc';
protected static $defaultDescription = 'Recalculate amount of expense events';
private EntityManagerInterface $em;
private ExpenseEventRepository $expenseEventRepository;
private ExpenseEventCalculator $expenseEventCalculator;
public function __construct(
EntityManagerInterface $em,
ExpenseEventRepository $expenseEventRepository,
ExpenseEventCalculator $expenseEventCalculator
) {
parent::__construct();
$this->em = $em;
$this->expenseEventRepository = $expenseEventRepository;
$this->expenseEventCalculator = $expenseEventCalculator;
}
protected function configure(): void
{
$this
->addOption('withClosedEvents', null, InputOption::VALUE_NONE, 'Recalculate all expense events, closed events included')
;
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$qb = $this->expenseEventRepository->createQueryBuilder('exp');
if (!$input->getOption('withClosedEvents')) {
$qb->join('exp.event', 'ev');
$qb->andWhere('ev.closed = 0');
}
$expenseEvents = $qb->getQuery()->getResult();
foreach($expenseEvents as $expenseEvent) {
$this->expenseEventCalculator->calculateRefund($expenseEvent);
}
$this->em->flush();
$io->success(sprintf('%d expense events recalculated', count($expenseEvents)));
return Command::SUCCESS;
}
}
| true |
ba9651585e88a1aaf2ccf66c26e41371a9b941fc | PHP | sadatech/tns_sc | /database/seeds/SalesTableSeeder.php | UTF-8 | 2,134 | 2.5625 | 3 | [
"MIT"
] | permissive | <?php
use Illuminate\Database\Seeder;
use Carbon\Carbon;
use App\EmployeeStore;
use Faker\Factory as Faker;
class SalesTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$faker = Faker::create();
// SALES HEADER
foreach(range(1, 30) as $d){
$employee = 0;
foreach(range(1, 20) as $i){
$employee += 1;
$store_id = EmployeeStore::where('id_employee', ($employee))->first()->id_store;
DB::table('sales')->insert([
'id_employee' => $employee,
'id_store' => $store_id,
'date' => Carbon::parse('2018-11-'.$d),
'week' => Carbon::parse('2018-11-'.$d)->weekOfMonth,
'type' => 'Sell In',
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
]);
DB::table('sales')->insert([
'id_employee' => $employee,
'id_store' => $store_id,
'date' => Carbon::parse('2018-11-'.$d),
'week' => Carbon::parse('2018-11-'.$d)->weekOfMonth,
'type' => 'Sell Out',
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
]);
}
}
$satuan = ['pack', 'karton'];
// SALES DETAIL
foreach(range(1, 600) as $i){
foreach(range(1, 10) as $j){
DB::table('detail_sales')->insert([
'id_sales' => $i,
'id_product' => $j,
'qty' => rand(1, 10),
'qty_actual' => rand(20, 100),
'satuan' => $satuan[rand(0,1)],
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
]);
DB::table('detail_sales')->insert([
'id_sales' => $i,
'id_product' => $j,
'qty' => rand(1, 10),
'qty_actual' => rand(20, 100),
'satuan' => $satuan[rand(0,1)],
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
]);
}
}
}
}
| true |
dbe105f355c1c38f1a608dba7e1c5f4b4c24162c | PHP | YNCBearz/design-pattern | /app/FactoryPattern/Pizza/FounderIngredientFactory.php | UTF-8 | 444 | 2.71875 | 3 | [] | no_license | <?php
namespace App\FactoryPattern\Pizza;
use App\FactoryPattern\Pizza\Dough\GeneralDough;
use App\FactoryPattern\Pizza\Sauce\GeneralSauce;
use App\FactoryPattern\Pizza\Contracts\IngredientFactoryInterface;
class FounderIngredientFactory implements IngredientFactoryInterface
{
public function createDough()
{
return new GeneralDough();
}
public function createSauce()
{
return new GeneralSauce();
}
} | true |
65cda952a212b9021154d89bf64fa2461d03733e | PHP | Gnime/KeaWork | /interfaceDesignExam/views/createUserProfile.php | UTF-8 | 1,337 | 2.734375 | 3 | [] | no_license | <?php
require "views/functions.php";
if (isset($_POST['username'])){
$username= $_POST['username'];
$password = $_POST['password'];
$title = $_POST['title'];
$asUsers = file_get_contents("users.txt");
$ajUsers = json_decode($asUsers);
//
$newUser = new stdClass();
$newUser->id = getGUID();
$newUser->username = $username;
$newUser->password = $password;
$newUser->title = $title;
$newUser->admin = 1;
$newUser->events=[];
array_push($ajUsers , $newUser);
$asUsers = json_encode($ajUsers);
file_put_contents("users.txt", $asUsers);
header("Location: index.php?page=displayUsers");
}
$content = "<div class=\"wdw-createUser\">
<form method='post'>
<div class=\"wdw-createEvent-InputArea\">
<label>Add a new admin account</label>
<input type=\"text\" class=\"createUser form-control\" id=\"lbl-username\" name=\"username\" placeholder='username'>
<input type=\"text\" class=\"createUser form-control\" id=\"lbl-password\" name=\"password\" placeholder='password'>
<input type='text' class='createUser form-control' name='title' placeholder='title'>
<input type=\"submit\" class=\"btn btn-primary\" id=\"btn-submitEvent\" value=\"Add Admin\">
</div>
</form>
"; | true |
9ef4203aee2c0e8ef7ba6ed1f4ec21dfb7740508 | PHP | icevisual/laravel5 | /app/Models/Form/Component.php | UTF-8 | 2,756 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Models\Form;
use App\Models\BaseModel;
class Component extends BaseModel
{
protected $table = 'component';
public $timestamps = false;
public $guarded = [];
protected $createSql = "
DROP TABLE IF EXISTS `op_component`;
CREATE TABLE `op_component` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`component_name` varchar(80) NOT NULL COMMENT '组件名称',
`component_desc` varchar(255) NOT NULL COMMENT '组件描述',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='组件表';
";
public static function updateComponent($data){
\DB::beginTransaction();
self::where('id',$data['id'])->update([
'component_name' => $data['component_name'],
'component_desc' => $data['component_desc']
]);
ComponentAttrs::where('component_id',$data['id'])->delete();
foreach ($data['attrs'] as $v){
ComponentAttrs::addRecord([
'component_id' => $data['id'],//组件ID
'attr_id' => $v['id'],//属性ID
'default_value' => $v['default_value'],//属性默认值
]);
}
\DB::commit();
return true;
}
public static function createNewComponent($data){
\DB::beginTransaction();
$component = self::create([
'component_name' => $data['component_name'],
'component_desc' => $data['component_desc']
]);
foreach ($data['attrs'] as $v){
ComponentAttrs::addRecord([
'component_id' => $component['id'],//组件ID
'attr_id' => $v['id'],//属性ID
'default_value' => $v['default_value'],//属性默认值
]);
}
\DB::commit();
return $component;
}
public static function componentDetail($id){
$component = self::find($id);
return [
'component' => $component->toArray(),
'attrs' => ComponentAttrs::getComponentAttrs($id)
] ;
}
public static function queryComponent($search = [],$page = 1,$pageSize = 10,$order = []){
$handler = self::select([
'component.id',
'component.component_name',
'component.component_desc',
]);
$paginate = $handler->paginate($pageSize, [
'*'
], 'p', $page);
$list = $paginate->toArray();
$data = [
'total' => $list['total'],
'current_page' => $list['current_page'],
'last_page' => $list['last_page'],
'per_page' => $list['per_page'],
'list' => $list['data']
];
return $data;
}
} | true |
9e630e0bc99b6abde77590326719c23e7a6dd062 | PHP | xiaomlove/huanbao | /app/Http/Middleware/ImageToAttachmentKey.php | UTF-8 | 703 | 2.625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Middleware;
use Closure;
class ImageToAttachmentKey
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$method = $request->method();
if (in_array($method, ['POST', 'PUT', 'PATCH']))
{
foreach ($request->all() as $key => $value)
{
if (strpos($key, '_image') !== false)
{
$request->request->set($key, attachmentKey($value));
}
}
}
return $next($request);
}
}
| true |
b092e81c03832d1e5771b2db45fb3077f70b8255 | PHP | HazemFCIH/PodBuilder | /app/Http/Controllers/HomeController.php | UTF-8 | 1,173 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
class HomeController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
return view('home');
}
public function editProfile(){
return view('front_dashboard.users.edit');
}
public function updateProfile(Request $request)
{
if (Hash::check($request->password,auth()->user()->password)) {
$request->validate([
'name' => 'required|min:4|string|max:255',
'email' => 'required|email|string|max:255',
'new_password' => 'confirmed',
]);
$user = auth()->user();
$user->name = $request['name'];
$user->password = Hash::make($request['password']);
$user->email = $request['email'];
$user->save();
return redirect()->route('dashboard.home');
}else{
return view('front_dashboard.users.edit')->withErrors(["password_not_right"=>"Your password is incorrect!"]);;
}
}
}
| true |
87e898237ed9a4932b58bc76a80da13c09f4ee48 | PHP | jasonATindiecentive/coinbase-pro-sdk | /src/Functional/DTO/TimeData.php | UTF-8 | 1,056 | 2.890625 | 3 | [
"MIT"
] | permissive | <?php
/**
* @author Marc MOREAU <moreau.marc.web@gmail.com>
* @license https://github.com/MockingMagician/coinbase-pro-sdk/blob/master/LICENSE.md MIT
* @link https://github.com/MockingMagician/coinbase-pro-sdk/blob/master/README.md
*/
namespace MockingMagician\CoinbaseProSdk\Functional\DTO;
use MockingMagician\CoinbaseProSdk\Contracts\DTO\TimeDataInterface;
use MockingMagician\CoinbaseProSdk\Functional\Misc\Json;
class TimeData extends AbstractCreator implements TimeDataInterface
{
/**
* @var string
*/
private $iso;
/**
* @var float
*/
private $epoch;
public function __construct(string $body)
{
$body = Json::decode($body, true);
$this->iso = $body['iso'];
$this->epoch = (float) $body['epoch'];
}
public function getIso(): string
{
return $this->iso;
}
public function getEpoch(): float
{
return $this->epoch;
}
public static function createFromArray(array $array, ...$extraData)
{
return new static(Json::encode($array));
}
}
| true |
b85e3c9b0906925b7e278285f846ee6663365613 | PHP | SendCloud/sendcloud | /CheckoutCore/Domain/Interfaces/DTOInstantiable.php | UTF-8 | 436 | 2.71875 | 3 | [
"Apache-2.0"
] | permissive | <?php
namespace SendCloud\SendCloud\CheckoutCore\Domain\Interfaces;
use SendCloud\SendCloud\CheckoutCore\DTO\DataTransferObject;
/**
* Interface DTOInstantiable
*
* @package SendCloud\SendCloud\CheckoutCore\Domain\Contracts
*/
interface DTOInstantiable
{
/**
* Makes an instance from dto.
*
* @param DataTransferObject $object
*
* @return mixed
*/
public static function fromDTO($object);
}
| true |
a2ccd984104b5c1b6b4933ff8dfd259c24796732 | PHP | renangtm/rtc | /php/entidades/Usuario.php | UTF-8 | 46,273 | 2.53125 | 3 | [] | no_license | <?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of Fornecedor
*
* @author Renan
*/
class Usuario {
public $id;
public $nome;
public $email;
public $telefones;
public $endereco;
public $cpf;
public $excluido;
public $empresa;
public $login;
public $senha;
public $rg;
public $permissoes;
public $cargo;
public $faixa_salarial;
public $contrato_fornecedor;
function __construct() {
$this->id = 0;
$this->email = null;
$this->telefones = array();
$this->endereco = new Endereco();
$this->excluido = false;
$this->cpf = new CPF("");
$this->rg = new RG("");
$this->email = new Email("");
$this->empresa = null;
$this->permissoes = array();
$this->cargo = null;
$this->faixa_salarial = 0;
$this->contrato_fornecedor = false;
}
public function getSuporte($con,$criar=false){
$suportes = array();
$ps = $con->getConexao()->prepare(
"SELECT s.id,a.id,a.nome,u.id,u.nome,UNIX_TIMESTAMP(s.inicio)*1000 "
. "FROM suporte s "
. "INNER JOIN usuario a ON s.id_atendente=a.id "
. "INNER JOIN usuario u ON s.id_usuario=u.id "
. "WHERE s.fim IS NULL AND (s.id_atendente = $this->id OR s.id_usuario = $this->id)");
$ps->execute();
$ps->bind_result($id,$id_atendente,$nome_atendente,$id_usuario,$nome_usuario,$inicio);
while($ps->fetch()){
$s = new Suporte();
$s->id = $id;
$s->inicio = $inicio;
$a = new Usuario();
$a->id = $id_atendente;
$a->nome = $nome_atendente;
$u = new Usuario();
$u->id = $id_usuario;
$u->nome = $nome_usuario;
$s->usuario = $u;
$s->atendente = $a;
$suportes[] = $s;
}
$ps->close();
if(count($suportes) === 0 && $criar){
$s = new Suporte();
$s->usuario = $this;
$s->atribuir($con);
return array($s);
}
return $suportes;
}
public function setPermissoesAbaixo($con, $permissoes) {
$resultado = array();
foreach ($permissoes as $key => $value) {
if ($value->in) {
$resultado[] = array($value->id, 0);
}
if ($value->del) {
$resultado[] = array($value->id, 1);
}
if ($value->alt) {
$resultado[] = array($value->id, 2);
}
if ($value->cons) {
$resultado[] = array($value->id, 3);
}
}
$ps = $con->getConexao()->prepare("DELETE FROM usuario_permissao_abaixo WHERE id_usuario=$this->id");
$ps->execute();
$ps->close();
foreach ($resultado as $key => $value) {
$ps = $con->getConexao()->prepare("INSERT INTO usuario_permissao_abaixo(id_usuario,id_permissao,tipo) VALUES($this->id,$value[0],$value[1])");
$ps->execute();
$ps->close();
}
}
public function getPermissoesAbaixo($con) {
$permissoes = array();
$ps = $con->getConexao()->prepare("SELECT id_permissao,tipo FROM usuario_permissao_abaixo WHERE id_usuario=$this->id");
$ps->execute();
$ps->bind_result($id_permissao, $tipo);
while ($ps->fetch()) {
if (!isset($permissoes[$id_permissao])) {
$permissoes[$id_permissao] = array();
}
$permissoes[$id_permissao][$tipo] = true;
}
$ps->close();
$todas_permissoes = Sistema::getPermissoes($this->empresa);
$retorno = array();
foreach ($todas_permissoes as $key => $value) {
$cp = Utilidades::copy($value);
if (isset($permissoes[$cp->id][0])) {
$cp->in = true;
}
if (isset($permissoes[$cp->id][1])) {
$cp->del = true;
}
if (isset($permissoes[$cp->id][2])) {
$cp->alt = true;
}
if (isset($permissoes[$cp->id][3])) {
$cp->cons = true;
}
$retorno[] = $cp;
unset($cp);
}
return $retorno;
}
public function getCountClientes($con, $filtro = "") {
$sql = "SELECT COUNT(*) "
. "FROM cliente "
. "INNER JOIN empresa ON cliente.id_empresa=empresa.id "
. "INNER JOIN usuario_cliente ON usuario_cliente.id_usuario=$this->id AND usuario_cliente.id_cliente=cliente.id "
. "WHERE cliente.excluido = false";
if ($filtro !== "") {
$sql .= " AND $filtro";
}
$ps = $con->getConexao()->prepare($sql);
$ps->execute();
$ps->bind_result($qtd);
if ($ps->fetch()) {
$ps->close();
return $qtd;
}
$ps->close();
return 0;
}
public function getTiposTarefaUsuario($con) {
$tipos_tarefa = $this->empresa->getTiposTarefa($con);
$tt = array();
foreach ($tipos_tarefa as $key => $value) {
foreach ($value->cargos as $key2 => $value2) {
if ($value2->id === $this->cargo->id) {
$tt[] = $value;
continue 2;
}
}
}
$retorno = array();
$ps = $con->getConexao()->prepare("SELECT id,id_tipo_tarefa,importancia FROM tipo_tarefa_usuario WHERE id_usuario=$this->id");
$ps->execute();
$ps->bind_result($id, $id_tipo_tarefa, $importancia);
while ($ps->fetch()) {
foreach ($tt as $key => $value) {
if ($value->id === $id_tipo_tarefa) {
$ut = new UsuarioTipoTarefa();
$ut->id = $id;
$ut->importancia = $importancia;
$ut->tipo_tarefa = $value;
$ut->usuario = $this;
$retorno[] = $ut;
unset($tt[$key]);
continue 2;
}
}
}
$ps->close();
foreach ($tt as $key => $value) {
$ut = new UsuarioTipoTarefa();
$ut->importancia = $importancia;
$ut->tipo_tarefa = $value;
$ut->usuario = $this;
$retorno[] = $ut;
}
return $retorno;
}
public function addCliente($con, $cliente, $situacao) {
$uc = new RelacaoUsuarioCliente();
$uc->cliente = $cliente;
$uc->situacao = $situacao;
$uc->merge($con);
$ps = $con->getConexao()->prepare("UPDATE usuario_cliente SET data_inicio=data_inicio,data_fim=data_fim,id_usuario=$this->id WHERE id=$uc->id");
$ps->execute();
$ps->close();
}
public function getEstatisticas($con, $somente_data = false) {
$agora = round(microtime(true));
$repeat = array();
$ps = $con->getConexao()->prepare("SELECT id,intervalos_execucao FROM tarefa WHERE id_usuario=$this->id");
$ps->execute();
$ps->bind_result($id, $interv);
while ($ps->fetch()) {
$i = explode(';', $interv);
foreach ($i as $key => $value) {
if ($value === "") {
continue;
}
$it = explode('@', $interv);
if (isset($repeat[$it[0]][$it[1]])) {
continue;
}
if (!isset($repeat[$it[0]])) {
$repeat[$it[0]] = array();
}
$repeat[$it[0]][$it[1]] = true;
$x1 = doubleval($it[1]);
$x2 = doubleval($it[0]);
$intervalos[] = array($id, min($x1, $x2), max($x1, $x2));
}
}
$ps->close();
for ($i = 1; $i < count($intervalos); $i++) {
for ($j = $i; $j > 0 && $intervalos[$j][2] <= $intervalos[$j - 1][1]; $j--) {
$k = $intervalos[$j];
$intervalos[$j] = $intervalos[$j - 1];
$intervalos[$j - 1] = $k;
}
}
$tmp = array();
foreach ($intervalos as $key => $value) {
$tmp[] = $value[1];
$tmp[] = $value[2];
}
$tmp[] = $agora;
$tipos_tarefa = $this->empresa->getTiposTarefa($con);
$tarefas = array();
$sql = "SELECT tarefa.id,tarefa.id_tipo_tarefa,tarefa.porcentagem_conclusao,UNIX_TIMESTAMP(tarefa.inicio_minimo)*1000,tarefa.intervalos_execucao,tarefa.sucesso "
. "FROM tarefa "
. "LEFT JOIN observacao ON observacao.id_tarefa=tarefa.id "
. "WHERE (" . ($somente_data ? "(DATE(observacao.momento)=DATE(FROM_UNIXTIME($agora)) AND MONTH(observacao.momento)=MONTH(FROM_UNIXTIME($agora)) AND YEAR(observacao.momento)=YEAR(FROM_UNIXTIME($agora)))" : "true")
. ") AND tarefa.id_usuario=$this->id AND tarefa.excluida=false GROUP BY tarefa.id";
$ps = $con->getConexao()->prepare($sql);
$ps->execute();
$ps->bind_result($id, $tipo, $porcentagem, $inicio, $interv, $sucesso);
while ($ps->fetch()) {
$tarefa = new stdClass();
$tarefa->id = $id;
$tarefa->inicio = $inicio;
$tarefa->fim = $inicio;
$tarefa->concluida = ($porcentagem >= 100) ? 2 : ($porcentagem > 0 ? 1 : 0);
$tarefa->tipo_tarefa = null;
$tarefa->sucesso = $sucesso == 1;
foreach ($tipos_tarefa as $key => $value) {
if ($value->id === $tipo) {
$tarefa->tipo_tarefa = $value;
break;
}
}
if ($tarefa->tipo_tarefa === null) {
continue;
}
$tempo_utilizado = 0;
$i = explode(';', $interv);
foreach ($i as $key => $value) {
if ($value === "") {
continue;
}
$it = explode('@', $interv);
$x1 = doubleval($it[1]);
$x2 = doubleval($it[0]);
$tempo_utilizado += abs($x1 - $x2);
$m = max($x1, $x2);
$tarefa->fim = max($tarefa->fim, $m);
}
$tarefa->tempo_utilizado = $tempo_utilizado;
$tarefas[$id] = $tarefa;
}
$ps->close();
$res = array();
foreach ($tarefas as $id_tarefa => $tarefa) {
$tempo = $tarefa->tipo_tarefa->tempo_medio * 60 * 60 * 1000 * 100;
$prox = 0;
while ($prox < count($tmp) && $tmp[$prox] < $tarefa->inicio) {
$prox++;
}
$fora = max(0, $tempo - $tarefa->tempo_utilizado);
$inicio = $tarefa->inicio;
$fim = $tarefa->fim;
if (!$tarefa->concluida) {
$fim = $agora * 1000;
}
while ($inicio < $fim && $fora > 0 && $prox < count($tmp)) {
$dist = min((min($fim, $tmp[$prox]) - $inicio), $fora);
$inicio += $dist;
if ($prox % 2 === 0) {
$fora -= $dist;
if ($prox > 0) {
$tmp[$prox - 1] = $inicio;
} else {
$tmp[$prox] = $inicio - $dist;
}
}
$prox++;
}
$tarefa->fora = $fora == 0;
if (!isset($res[$tarefa->tipo_tarefa->nome])) {
$res[$tarefa->tipo_tarefa->nome] = array();
}
if (!isset($res[$tarefa->tipo_tarefa->nome][$tarefa->concluida])) {
$res[$tarefa->tipo_tarefa->nome][$tarefa->concluida] = array(array(0, 0), array(0, 0));
}
$res[$tarefa->tipo_tarefa->nome][$tarefa->concluida][$tarefa->fora ? 1 : 0][$tarefa->sucesso ? 1 : 0] ++;
}
return $res;
}
public function getClientes($con, $x1, $x2, $filtro = "", $ordem = "") {
$sql = "SELECT "
. "cliente.id,"
. "cliente.codigo_contimatic,"
. "cliente.codigo,"
. "cliente.razao_social, "
. "cliente.nome_fantasia, "
. "cliente.limite_credito, "
. "UNIX_TIMESTAMP(cliente.inicio_limite)*1000, "
. "UNIX_TIMESTAMP(cliente.termino_limite)*1000, "
. "cliente.pessoa_fisica, "
. "cliente.cpf, "
. "cliente.cnpj, "
. "cliente.rg, "
. "cliente.inscricao_estadual, "
. "cliente.suframado, "
. "cliente.inscricao_suframa, "
. "categoria_cliente.id, "
. "categoria_cliente.nome, "
. "endereco_cliente.id, "
. "endereco_cliente.rua, "
. "endereco_cliente.numero, "
. "endereco_cliente.bairro, "
. "endereco_cliente.cep, "
. "cidade_cliente.id, "
. "cidade_cliente.nome, "
. "estado_cliente.id, "
. "estado_cliente.sigla, "
. "email_cliente.id,"
. "email_cliente.endereco,"
. "email_cliente.senha,"
. "empresa.id,"
. "empresa.tipo_empresa,"
. "empresa.nome,"
. "empresa.inscricao_estadual,"
. "empresa.consigna,"
. "empresa.aceitou_contrato,"
. "empresa.juros_mensal,"
. "empresa.cnpj,"
. "endereco_empresa.numero,"
. "endereco_empresa.id,"
. "endereco_empresa.rua,"
. "endereco_empresa.bairro,"
. "endereco_empresa.cep,"
. "cidade_empresa.id,"
. "cidade_empresa.nome,"
. "estado_empresa.id,"
. "estado_empresa.sigla,"
. "email_empresa.id,"
. "email_empresa.endereco,"
. "email_empresa.senha,"
. "telefone_empresa.id,"
. "telefone_empresa.numero,"
. "usuario_cliente.id,"
. "FROM_UNIXTIME(usuario_cliente.data_inicio)*1000,"
. "CASE WHEN usuario_cliente.data_fim IS NULL THEN null ELSE FROM_UNIXTIME(usuario_cliente.data_fim)*1000 END,"
. "usuario_cliente.situacao "
. "FROM cliente "
. "INNER JOIN endereco endereco_cliente ON endereco_cliente.id_entidade=cliente.id AND endereco_cliente.tipo_entidade='CLI' "
. "INNER JOIN cidade cidade_cliente ON endereco_cliente.id_cidade=cidade_cliente.id "
. "INNER JOIN estado estado_cliente ON estado_cliente.id=cidade_cliente.id_estado "
. "INNER JOIN categoria_cliente ON cliente.id_categoria=categoria_cliente.id "
. "INNER JOIN email email_cliente ON email_cliente.id_entidade=cliente.id AND email_cliente.tipo_entidade = 'CLI' "
. "INNER JOIN empresa ON cliente.id_empresa=empresa.id "
. "INNER JOIN endereco endereco_empresa ON endereco_empresa.id_entidade=empresa.id AND endereco_empresa.tipo_entidade='EMP' "
. "INNER JOIN email email_empresa ON email_empresa.id_entidade=empresa.id AND email_empresa.tipo_entidade='EMP' "
. "INNER JOIN telefone telefone_empresa ON telefone_empresa.id_entidade=empresa.id AND telefone_empresa.tipo_entidade='EMP' "
. "INNER JOIN cidade cidade_empresa ON endereco_empresa.id_cidade=cidade_empresa.id "
. "INNER JOIN estado estado_empresa ON cidade_empresa.id_estado = estado_empresa.id "
. "INNER JOIN usuario_cliente ON cliente.id=usuario_cliente.id_cliente AND usuario_cliente.id_usuario=$this->id "
. "WHERE cliente.excluido=false AND usuario_cliente.data_fim IS NULL ";
if ($filtro != "") {
$sql .= "AND $filtro ";
}
if ($ordem != "") {
$sql .= "ORDER BY $ordem ";
}
$sql .= "LIMIT $x1, " . ($x2 - $x1);
$ps = $con->getConexao()->prepare($sql);
$ps->execute();
$ps->bind_result($id_cliente, $cod_ctm, $cod_cli, $nome_cliente, $nome_fantasia_cliente, $limite, $inicio, $fim, $pessoa_fisica, $cpf, $cnpj, $rg, $ie, $suf, $i_suf, $cat_id, $cat_nome, $end_cli_id, $end_cli_rua, $end_cli_numero, $end_cli_bairro, $end_cli_cep, $cid_cli_id, $cid_cli_nome, $est_cli_id, $est_cli_nome, $email_cli_id, $email_cli_end, $email_cli_senha, $id_empresa, $tipo_empresa, $nome_empresa, $inscricao_empresa, $consigna_empresa, $aceitou_contrato_empresa, $juros_mensal_empresa, $cnpj_empresa, $numero_endereco_empresa, $id_endereco_empresa, $rua_empresa, $bairro_empresa, $cep_empresa, $id_cidade_empresa, $nome_cidade_empresa, $id_estado_empresa, $nome_estado_empresa, $id_email_empresa, $endereco_email_empresa, $senha_email_empresa, $id_telefone_empresa, $numero_telefone_empresa, $id_uc, $ini_uc, $fim_uc, $sit_uc);
$clientes = array();
$ucs = array();
while ($ps->fetch()) {
$cliente = new Cliente();
$cliente->id = $id_cliente;
$cliente->codigo_contimatic = $cod_ctm;
$cliente->codigo = $cod_cli;
$cliente->cnpj = new CNPJ($cnpj);
$cliente->cpf = new CPF($cpf);
$cliente->rg = new RG($rg);
$cliente->pessoa_fisica = $pessoa_fisica == 1;
$cliente->nome_fantasia = $nome_fantasia_cliente;
$cliente->razao_social = $nome_cliente;
$cliente->email = new Email($email_cli_end);
$cliente->email->id = $email_cli_id;
$cliente->email->senha = $email_cli_senha;
$cliente->categoria = new CategoriaCliente();
$cliente->categoria->id = $cat_id;
$cliente->categoria->nome = $cat_nome;
$cliente->inicio_limite = $inicio;
$cliente->termino_limite = $fim;
$cliente->limite_credito = $limite;
$cliente->inscricao_suframa = $i_suf;
$cliente->suframado = $suf == 1;
$cliente->inscricao_estadual = $ie;
$end = new Endereco();
$end->id = $end_cli_id;
$end->bairro = $end_cli_bairro;
$end->cep = new CEP($end_cli_cep);
$end->numero = $end_cli_numero;
$end->rua = $end_cli_numero;
$end->cidade = new Cidade();
$end->cidade->id = $cid_cli_id;
$end->cidade->nome = $cid_cli_nome;
$end->cidade->estado = new Estado();
$end->cidade->estado->id = $est_cli_id;
$end->cidade->estado->sigla = $est_cli_nome;
$cliente->endereco = $end;
//empresa
$empresa = Sistema::getEmpresa($tipo_empresa);
$empresa->id = $id_empresa;
$empresa->cnpj = new CNPJ($cnpj_empresa);
$empresa->inscricao_estadual = $inscricao_empresa;
$empresa->nome = $nome_empresa;
$empresa->aceitou_contrato = $aceitou_contrato_empresa;
$empresa->juros_mensal = $juros_mensal_empresa;
$empresa->consigna = $consigna_empresa;
$endereco = new Endereco();
$endereco->id = $id_endereco_empresa;
$endereco->rua = $rua_empresa;
$endereco->bairro = $bairro_empresa;
$endereco->cep = new CEP($cep_empresa);
$endereco->numero = $numero_endereco_empresa;
$cidade = new Cidade();
$cidade->id = $id_cidade_empresa;
$cidade->nome = $nome_cidade_empresa;
$estado = new Estado();
$estado->id = $id_estado_empresa;
$estado->sigla = $nome_estado_empresa;
$cidade->estado = $estado_empresa;
$endereco->cidade = $cidade_empresa;
$empresa->endereco = $endereco_empresa;
$email = new Email($endereco_email_empresa);
$email->id = $id_email_empresa;
$email->senha = $senha_email_empresa;
$empresa->email = $email_empresa;
$telefone = new Telefone($numero_telefone_empresa);
$telefone->id = $id_telefone_empresa;
$empresa->telefone = $telefone_empresa;
$cliente->empresa = $empresa;
//--------------
$clientes[$id_cliente] = $cliente;
$uc = new RelacaoUsuarioCliente();
$uc->id = $id_uc;
$uc->cliente = $cliente;
$uc->data_fim = $fim_uc;
$uc->data_inicio = $ini_uc;
$uc->situacao = $sit_uc;
$ucs[] = $uc;
}
$ps->close();
$in_cli = "-1";
foreach ($clientes as $id => $cliente) {
$in_cli .= ",";
$in_cli .= $id;
}
$ps = $con->getConexao()->prepare("SELECT telefone.id_entidade, telefone.tipo_entidade, telefone.id, telefone.numero FROM telefone WHERE (telefone.id_entidade IN ($in_cli) AND telefone.tipo_entidade='CLI') AND telefone.excluido=false");
$ps->execute();
$ps->bind_result($id_entidade, $tipo_entidade, $id, $numero);
while ($ps->fetch()) {
$v = $clientes;
$telefone = new Telefone($numero);
$telefone->id = $id;
$v[$id_entidade]->telefones[] = $telefone;
}
$ps->close();
$real = array();
foreach ($clientes as $key => $value) {
$real[] = $value;
}
return $ucs;
}
public function getAtividadeUsuarioClienteAtual($con) {
$auc = null;
$ps = $con->getConexao()->prepare("SELECT "
. "id,"
. "data_referente,"
. "pontos_atendimento "
. "FROM usuario_atividade "
. "WHERE "
. "id_usuario=$this->id AND "
. "DATE(data_referente)=DATE(CURRENT_DATE) AND "
. "MONTH(data_referente)=MONTH(CURRENT_DATE) AND "
. "YEAR(data_referente)=YEAR(CURRENT_DATE)");
$ps->execute();
$ps->bind_result($id, $data_referente, $pontos_atendimento);
if ($ps->fetch()) {
$auc = new AtividadeUsuarioCliente();
$auc->id = $id;
$auc->data_referente = $data_referente;
$auc->pontos_atendimento = $pontos_atendimento;
$ps->close();
} else {
$ps->close();
$auc = new AtividadeUsuarioCliente();
$auc->merge($con);
$ps = $con->getConexao()->prepare("UPDATE usuario_atividade SET id_usuario=$this->id WHERE id=$auc->id");
$ps->execute();
$ps->close();
}
$ps = $con->getConexao()->prepare("SELECT SUM(pontos_atendimento) FROM usuario_atividade "
. "WHERE id_usuario=$this->id AND "
. "MONTH(data_referente)=MONTH(FROM_UNIXTIME($auc->data_referente/1000)) AND "
. "YEAR(data_referente)=YEAR(FROM_UNIXTIME($auc->data_referente/1000))");
$ps->execute();
$ps->bind_result($pontos_mes);
if ($ps->fetch()) {
if ($pontos_mes !== null) {
$auc->pontos_mes = $pontos_mes;
}
}
$ps->close();
$auc->calcularMetaDiaria();
return $auc;
}
public function getTarefasSolicitadas($con) {
$cm = new CacheManager(3600000);
$cache = $cm->getCache("tarefas_solicitadas_$this->id", false, true);
if ($cache === null) {
$cache = new stdClass();
$cache->usuarios = "($this->id";
$cache->arr_usuarios = array();
$filiais = $this->empresa->getFiliais($con);
$filiais[] = $this->empresa;
foreach ($filiais as $key => $value) {
$u = $value->getUsuarios($con, 0, 1, "usuario.cpf='" . $this->cpf->valor . "'");
if (count($u) === 1) {
$org = new Organograma($value);
$inf = $org->getInferiores($con, $u[0]);
foreach ($inf as $key2 => $value2) {
$cache->usuarios .= ",$value2->id_usuario";
$cache->arr_usuarios[] = $value2->id_usuario;
}
}
}
$cache->usuarios .= ")";
$cache->arr_associados = array();
$cache->associados = "($this->id";
$cache->tipos_tarefa = array();
$ps = $con->getConexao()->prepare("SELECT empresa.id,usuario.id,empresa.tipo_empresa FROM tarefa "
. "INNER JOIN usuario ON usuario.id=tarefa.id_usuario "
. "INNER JOIN empresa ON empresa.id=usuario.id_empresa "
. "WHERE tarefa.id_usuario IN $cache->usuarios OR tarefa.criada_por=$this->id");
$ps->execute();
$ps->bind_result($id_empresa, $id_usuario, $tipo_empresa);
while ($ps->fetch()) {
$cache->tipos_tarefa[$id_empresa] = $tipo_empresa;
$cache->associados .= ",$id_usuario";
$cache->arr_associados[] = $id_usuario;
}
$ps->close();
$cache->associados .= ")";
foreach ($cache->tipos_tarefa as $key => $value) {
$cache->tipos_tarefa[$key] = Sistema::getEmpresa($value);
$cache->tipos_tarefa[$key]->id = $key;
$cache->tipos_tarefa[$key] = $cache->tipos_tarefa[$key]->getTiposTarefa($con);
}
//--------------------------------------------------------------------
$cache->expedientes = array();
$cache->ausencias = array();
$ps = $con->getConexao()->prepare("SELECT id,UNIX_TIMESTAMP(inicio)*1000,UNIX_TIMESTAMP(fim)*1000,id_usuario FROM ausencia WHERE id_usuario IN $cache->associados AND fim>CURRENT_TIMESTAMP");
$ps->execute();
$ps->bind_result($id, $inicio, $fim, $id_usuario);
while ($ps->fetch()) {
$a = new Ausencia();
$a->id = $id;
$a->inicio = $inicio;
$a->fim = $fim;
if (!isset($cache->usencias[$id_usuario])) {
$cache->ausencias[$id_usuario] = array();
}
$cache->ausencias[$id_usuario][] = $a;
}
$ps->close();
$ps = $con->getConexao()->prepare("SELECT id,inicio,fim,dia_semana,id_usuario FROM expediente WHERE id_usuario IN $cache->associados");
$ps->execute();
$ps->bind_result($id, $inicio, $fim, $dia_semana, $id_usuario);
while ($ps->fetch()) {
$e = new Expediente();
$e->id = $id;
$e->inicio = $inicio;
$e->fim = $fim;
$e->dia_semana = $dia_semana;
if (!isset($cache->expedientes[$id_usuario])) {
$cache->expedientes[$id_usuario] = array();
}
$cache->expedientes[$id_usuario][] = $e;
}
$ps->close();
$cm->setCache("tarefas_solicitadas_$this->id", $cache, false, true);
}
//---------------------------------------
$tarefas = array();
$sql = "SELECT "
. "tarefa.id,"
. "UNIX_TIMESTAMP(tarefa.inicio_minimo)*1000,"
. "tarefa.ordem,"
. "tarefa.porcentagem_conclusao,"
. "tarefa.tipo_entidade_relacionada,"
. "tarefa.id_entidade_relacionada,"
. "tarefa.titulo,"
. "tarefa.descricao,"
. "tarefa.intervalos_execucao,"
. "tarefa.realocavel,"
. "tarefa.id_tipo_tarefa,"
. "tarefa.prioridade,"
. "observacao.id,"
. "observacao.porcentagem,"
. "UNIX_TIMESTAMP(observacao.momento), "
. "observacao.observacao,"
. "usuario.id,"
. "usuario.nome,"
. "empresa.id,"
. "empresa.nome,"
. "CASE WHEN u2.id IS NULL THEN 'CFG' ELSE CONCAT(u2.id,CONCAT('-',u2.nome)) END,"
. "tarefa.criada_por "
. "FROM tarefa "
. "LEFT JOIN (SELECT * FROM observacao WHERE observacao.excluida = false) observacao ON tarefa.id=observacao.id_tarefa "
. "INNER JOIN usuario ON usuario.id=tarefa.id_usuario "
. "INNER JOIN empresa ON empresa.id=usuario.id_empresa "
. "LEFT JOIN usuario u2 ON tarefa.criada_por=u2.id "
. "WHERE tarefa.excluida=false AND (tarefa.id_usuario IN $cache->usuarios OR tarefa.criada_por=$this->id) AND tarefa.porcentagem_conclusao<100 ORDER BY tarefa.id DESC";
$tmp = array();
$ps = $con->getConexao()->prepare($sql);
$ps->execute();
$ps->bind_result($id, $inicio_minimo, $ordem, $porcentagem_conclusao, $tipo_entidade_relacionada, $id_entidade_relacionada, $titulo, $descricao, $intervalos_execucao, $realocavel, $id_tipo_tarefa, $prioridade, $id_observacao, $porcentagem_observacao, $momento_observacao, $observacao, $id_usuario, $nome_usuario, $id_empresa, $nome_empresa, $criada_por, $id_criador);
while ($ps->fetch()) {
if (!isset($tmp[$id])) {
$t = new Tarefa();
$t->id = $id;
$t->inicio_minimo = $inicio_minimo;
$t->ordem = $ordem;
$t->porcentagem_conclusao = $porcentagem_conclusao;
$t->tipo_entidade_relacionada = $tipo_entidade_relacionada;
$t->id_entidade_relacionada = $id_entidade_relacionada;
$t->titulo = $titulo;
$t->descricao = $descricao;
$t->intervalos_execucao = $intervalos_execucao;
$t->realocavel = $realocavel == 1;
$t->id_usuario = $id_usuario;
$t->nome_usuario = $nome_usuario;
$t->id_empresa = $id_empresa;
$t->nome_empresa = $nome_empresa;
$t->usuario = $id_usuario . "-" . $nome_usuario;
$t->empresa = $id_empresa . "-" . $nome_empresa;
$t->assinatura_solicitante = $criada_por;
$t->criada_por = $id_criador;
foreach ($cache->tipos_tarefa[$id_empresa] as $key => $tipo) {
if ($tipo->id === $id_tipo_tarefa) {
$t->tipo_tarefa = $tipo;
break;
}
}
if ($t->tipo_tarefa === null) {
continue;
}
$t->prioridade = $prioridade;
$t->intervalos_execucao = explode(";", $t->intervalos_execucao);
$intervalos = array();
foreach ($t->intervalos_execucao as $key => $intervalo) {
if ($intervalo === "")
continue;
$k = explode('@', $intervalo);
$intervalos[] = array(doubleval($k[0]), doubleval($k[1]));
}
$t->intervalos_execucao = $intervalos;
$tmp[$id] = $t;
if (!isset($tarefas[$id_usuario])) {
$tarefas[$id_usuario] = array();
}
$tarefas[$id_usuario][] = $t;
}
$t = $tmp[$id];
if ($id_observacao !== null) {
$obs = new ObservacaoTarefa();
$obs->id = $id_observacao;
$obs->momento = $momento_observacao;
$obs->porcentagem = $porcentagem_observacao;
$obs->observacao = $observacao;
$t->observacoes[] = $obs;
}
}
$ps->close();
foreach ($tmp as $key => $value) {
if ($value->tipo_tarefa !== null) {
//$value->tipo_tarefa->init($value);
}
}
//--------------------------------------
$retorno = array();
foreach ($tarefas as $key => $value) {
foreach ($value as $key2 => $tarefa) {
if ($tarefa->criada_por === $this->id) {
$retorno[] = $tarefa;
} else {
foreach ($cache->arr_usuarios as $key3 => $value2) {
if ($value2 === $tarefa->id_usuario) {
$retorno[] = new TarefaReduzida($tarefa);
break;
}
}
}
}
}
return $retorno;
}
public function getTarefas($con, $filtro = "", $ordem = "", $agendadas = false) {
$tipos_tarefa = $this->empresa->getTiposTarefa($con);
$sql = "SELECT "
. "tarefa.id,"
. "UNIX_TIMESTAMP(tarefa.inicio_minimo)*1000,"
. "UNIX_TIMESTAMP(tarefa.start_usuario)*1000,"
. "tarefa.ordem,"
. "tarefa.porcentagem_conclusao,"
. "tarefa.tipo_entidade_relacionada,"
. "tarefa.id_entidade_relacionada,"
. "tarefa.titulo,"
. "tarefa.descricao,"
. "tarefa.intervalos_execucao,"
. "tarefa.realocavel,"
. "tarefa.id_tipo_tarefa,"
. "tarefa.prioridade,"
. "observacao.id,"
. "observacao.porcentagem,"
. "UNIX_TIMESTAMP(observacao.momento)*1000, "
. "observacao.observacao,"
. "CASE WHEN u.id IS NULL THEN 'SISTEMA' ELSE CONCAT(u.id,CONCAT('-',u.nome)) END "
. "FROM tarefa "
. "LEFT JOIN (SELECT * FROM observacao WHERE observacao.excluida = false) observacao ON tarefa.id=observacao.id_tarefa "
. "LEFT JOIN usuario u ON u.id=tarefa.criada_por "
. "WHERE tarefa.excluida=false AND " . (!$agendadas ? "(tarefa.agendamento IS NULL OR tarefa.agendamento<CURRENT_TIMESTAMP) AND " : "") . "tarefa.id_usuario=$this->id";
if ($filtro !== "") {
$sql .= " AND $filtro";
}
if ($ordem !== "") {
$sql .= " ORDER BY $ordem";
}
$tarefas = array();
$ps = $con->getConexao()->prepare($sql);
$ps->execute();
$ps->bind_result($id, $inicio_minimo, $start_usuario, $ordem, $porcentagem_conclusao, $tipo_entidade_relacionada, $id_entidade_relacionada, $titulo, $descricao, $intervalos_execucao, $realocavel, $id_tipo_tarefa, $prioridade, $id_observacao, $porcentagem_observacao, $momento_observacao, $observacao, $ass);
while ($ps->fetch()) {
if (!isset($tarefas[$id])) {
$t = new Tarefa();
$t->id = $id;
$t->start = $start_usuario;
$t->assinatura_solicitante = $ass;
$t->inicio_minimo = $inicio_minimo;
$t->ordem = $ordem;
$t->porcentagem_conclusao = $porcentagem_conclusao;
$t->tipo_entidade_relacionada = $tipo_entidade_relacionada;
$t->id_entidade_relacionada = $id_entidade_relacionada;
$t->titulo = $titulo;
$t->descricao = $descricao;
$t->intervalos_execucao = $intervalos_execucao;
$t->realocavel = $realocavel == 1;
foreach ($tipos_tarefa as $key => $tipo) {
if ($tipo->id === $id_tipo_tarefa) {
$t->tipo_tarefa = $tipo;
break;
}
}
if ($t->tipo_tarefa === null) {
continue;
}
$t->prioridade = $prioridade;
$t->intervalos_execucao = explode(";", $t->intervalos_execucao);
$intervalos = array();
foreach ($t->intervalos_execucao as $key => $intervalo) {
if ($intervalo === "")
continue;
$k = explode('@', $intervalo);
$intervalos[] = array($k[0] + 0, $k[1] + 0);
}
$t->intervalos_execucao = $intervalos;
$tarefas[$id] = $t;
}
$t = $tarefas[$id];
if ($id_observacao !== null) {
$obs = new ObservacaoTarefa();
$obs->id = $id_observacao;
$obs->momento = $momento_observacao;
$obs->porcentagem = $porcentagem_observacao;
$obs->observacao = $observacao;
$t->observacoes[] = $obs;
}
}
$retorno = array();
foreach ($tarefas as $key => $value) {
//$value->tipo_tarefa->init($value);
$retorno[] = $value;
}
return $retorno;
}
public function addTarefa($con, $tarefa) {
$tarefa->merge($con);
$ps = $con->getConexao()->prepare("UPDATE tarefa SET id_usuario = $this->id,inicio_minimo=inicio_minimo WHERE id=$tarefa->id");
$ps->execute();
$ps->close();
$tarefa->tipo_tarefa->aoAtribuir($this->id, $tarefa);
}
public function getAusencias($con, $filtro = "") {
$sql = "SELECT id,UNIX_TIMESTAMP(inicio)*1000,UNIX_TIMESTAMP(fim)*1000 FROM ausencia WHERE id_usuario=$this->id";
if ($filtro !== "") {
$sql .= " AND $filtro";
}
$ps = $con->getConexao()->prepare($sql);
$ps->execute();
$ps->bind_result($id, $inicio, $fim);
$ausencias = array();
while ($ps->fetch()) {
$a = new Ausencia();
$a->id = $id;
$a->inicio = $inicio;
$a->fim = $fim;
$ausencias[] = $a;
}
$ps->close();
return $ausencias;
}
public function getExpedientes($con) {
$ps = $con->getConexao()->prepare("SELECT id,inicio,fim,dia_semana FROM expediente WHERE id_usuario=$this->id");
$ps->execute();
$ps->bind_result($id, $inicio, $fim, $dia_semana);
$expedientes = array();
while ($ps->fetch()) {
$e = new Expediente();
$e->id = $id;
$e->inicio = $inicio;
$e->fim = $fim;
$e->dia_semana = $dia_semana;
$expedientes[] = $e;
}
$ps->close();
return $expedientes;
}
public function setExpedientes($con, $expedientes) {
$in = "(-1";
foreach ($expedientes as $key => $value) {
$in .= ",$value->id";
}
$in .= ")";
$ps = $con->getConexao()->prepare("DELETE FROM expediente WHERE id_usuario=$this->id AND id NOT IN $in");
$ps->execute();
$ps->close();
foreach ($expedientes as $key => $value) {
$value->merge($con);
$ps = $con->getConexao()->prepare("UPDATE expediente SET id_usuario=$this->id WHERE id=$value->id");
$ps->execute();
$ps->close();
}
}
public function setAusencias($con, $ausencias) {
$in = "(-1";
foreach ($ausencias as $key => $value) {
$in .= ",$value->id";
}
$in .= ")";
$ps = $con->getConexao()->prepare("DELETE FROM ausencia WHERE id_usuario=$this->id AND id NOT IN $in");
$ps->execute();
$ps->close();
foreach ($ausencias as $key => $value) {
$value->merge($con);
$ps = $con->getConexao()->prepare("UPDATE ausencia SET id_usuario=$this->id WHERE id=$value->id");
$ps->execute();
$ps->close();
}
}
public function merge($con) {
$ps = $con->getConexao()->prepare("SELECT id FROM usuario WHERE (cpf<>'" . $this->cpf->valor . "' AND login='$this->login') AND id <> $this->id AND id_empresa=" . $this->empresa->id);
$ps->execute();
$ps->bind_result($id);
if ($ps->fetch()) {
$ps->close();
throw new Exception("Ja existe um usuario com os mesmos dados $id");
}
$ps->close();
if ($this->id == 0) {
$ps = $con->getConexao()->prepare("INSERT INTO usuario(login,senha,nome,cpf,excluido,id_empresa,rg,faixa_salarial,contrato_fornecedor) VALUES('" . addslashes($this->login) . "','" . addslashes($this->senha) . "','" . addslashes($this->nome) . "','" . $this->cpf->valor . "',false," . $this->empresa->id . ",'" . addslashes($this->rg->valor) . "',$this->faixa_salarial,".($this->contrato_fornecedor?"true":"false").")");
$ps->execute();
$this->id = $ps->insert_id;
$ps->close();
} else {
$ps = $con->getConexao()->prepare("UPDATE usuario SET login='" . addslashes($this->login) . "',senha='" . addslashes($this->senha) . "', nome = '" . addslashes($this->nome) . "', cpf='" . $this->cpf->valor . "',excluido=false, id_empresa=" . $this->empresa->id . ",rg='" . addslashes($this->rg->valor) . "',faixa_salarial=$this->faixa_salarial,contrato_fornecedor=".($this->contrato_fornecedor?"true":"false")." WHERE id = " . $this->id);
$ps->execute();
$ps->close();
}
if ($this->cargo !== null) {
$ps = $con->getConexao()->prepare("UPDATE usuario SET id_cargo=" . $this->cargo->id . " WHERE id=" . $this->id);
$ps->execute();
$ps->close();
}
$this->email->merge($con);
$ps = $con->getConexao()->prepare("UPDATE email SET id_entidade=" . $this->id . ", tipo_entidade='USU' WHERE id = " . $this->email->id);
$ps->execute();
$ps->close();
$this->endereco->merge($con);
$ps = $con->getConexao()->prepare("UPDATE endereco SET id_entidade=" . $this->id . ", tipo_entidade='USU' WHERE id = " . $this->endereco->id);
$ps->execute();
$ps->close();
$ps = $con->getConexao()->prepare("DELETE FROM usuario_permissao WHERE id_usuario=$this->id");
$ps->execute();
$ps->close();
foreach ($this->permissoes as $key => $value) {
$in = ($value->in ? "true" : "false");
$del = ($value->del ? "true" : "false");
$alt = ($value->alt ? "true" : "false");
$cons = ($value->cons ? "true" : "false");
$ps = $con->getConexao()->prepare("INSERT INTO usuario_permissao(id_usuario,id_permissao,incluir,deletar,alterar,consultar) VALUES($this->id,$value->id,$in,$del,$alt,$cons)");
$ps->execute();
$ps->close();
}
$ps = $con->getConexao()->prepare("DELETE FROM usuario_permissao WHERE id_usuario=$this->id AND incluir=false AND deletar=false AND alterar=false AND consultar=false");
$ps->execute();
$ps->close();
$tels = array();
$ps = $con->getConexao()->prepare("SELECT id,numero FROM telefone WHERE tipo_entidade='USU' AND id_entidade=$this->id AND excluido=false");
$ps->execute();
$ps->bind_result($idt, $numerot);
while ($ps->fetch()) {
$t = new Telefone($numerot);
$t->id = $idt;
$tels[] = $t;
}
foreach ($tels as $key => $value) {
foreach ($this->telefones as $key2 => $value2) {
if ($value->id == $value2->id) {
continue 2;
}
}
$value->delete($con);
}
foreach ($this->telefones as $key => $value) {
$value->merge($con);
$ps = $con->getConexao()->prepare("UPDATE telefone SET tipo_entidade='USU', id_entidade=$this->id WHERE id=" . $value->id);
$ps->execute();
$ps->close();
}
}
public function temPermissao($p) {
foreach ($this->permissoes as $key => $value) {
if ($value->nome == $p->nome) {
if ($p->in && !$value->in) {
return false;
} else if ($p->del && !$value->del) {
return false;
} else if ($p->alt && !$value->alt) {
return false;
} else if ($p->cons && !$value->cons) {
return false;
} else {
foreach ($this->empresa->rtc->permissoes as $key2 => $value2) {
if ($value2->id === $value->id) {
return true;
}
}
foreach ($this->empresa->permissoes_especiais as $key3 => $value3) {
if ($key3 >= $this->empresa->rtc->numero) {
continue;
}
foreach ($value3 as $key2 => $value2) {
if ($value2->id === $value->id) {
return true;
}
}
}
return false;
}
}
}
return false;
}
public function delete($con) {
$ps = $con->getConexao()->prepare("UPDATE usuario SET excluido = true WHERE id = " . $this->id);
$ps->execute();
$ps->close();
}
}
| true |
a59c67f549f5d3f1ab8f7febbfb291350e4eafc1 | PHP | bileto/omnipay-payu | /src/Messages/PurchaseResponse.php | UTF-8 | 1,985 | 2.78125 | 3 | [] | no_license | <?php
namespace Omnipay\PayU\Messages;
use Omnipay\Common\Message\AbstractResponse;
use Omnipay\Common\Message\RedirectResponseInterface;
class PurchaseResponse extends AbstractResponse implements RedirectResponseInterface
{
/**
* @return boolean
*/
public function isSuccessful(): bool
{
if ('SUCCESS' !== $this->data->status->statusCode) {
return false;
}
$redirectUrl = $this->getRedirectUrl();
return is_string($redirectUrl);
}
/**
* Gets the redirect target url.
*/
public function getRedirectUrl(): ?string
{
if (isset($this->data->redirectUri) && is_string($this->data->redirectUri)) {
return $this->data->redirectUri;
}
return null;
}
/**
* Get the required redirect method (either GET or POST).
*/
public function getRedirectMethod(): string
{
return 'GET';
}
/**
* Gets the redirect form data array, if the redirect method is POST.
*/
public function getRedirectData(): ?array
{
return null;
}
/**
* @return string|null
*/
public function getTransactionId(): ?string
{
if (isset($this->data->extOrderId) && !empty($this->data->extOrderId)) {
return (string) $this->data->extOrderId;
}
if (isset($this->request->getParameters()['transactionId']) && !empty($this->request->getParameters()['transactionId'])) {
return $this->request->getParameters()['transactionId'];
}
return null;
}
/**
* PayU orderId
* @return null|string
*/
public function getTransactionReference(): ?string
{
if (isset($this->data->orderId) && !empty($this->data->orderId)) {
return (string) $this->data->orderId;
}
return null;
}
public function isRedirect(): bool
{
return is_string($this->data->redirectUri);
}
}
| true |
0e8cab5c95a19b809e62b6cd8f204ac0c136f095 | PHP | Wick/eaa-MVC | /app/src/Source/CSource.php | UTF-8 | 9,060 | 2.765625 | 3 | [
"MIT"
] | permissive | <?php
/**
* Class for display sourcecode.
*
* @author Mikael Roos, me@mikaelroos.se
* @copyright Mikael Roos 2010 - 2014
* @link https://github.com/mosbth/csource
*/
namespace Mos\Source;
class CSource {
/**
* Properties
*/
private $options = array();
/**
* Constructor
*
* @param array $options to alter the default behaviour.
*/
public function __construct($options=array()) {
$default = array(
'image_extensions' => array('png', 'jpg', 'jpeg', 'gif', 'ico'),
'spaces_to_replace_tab' => ' ',
'ignore' => array('.', '..', '.git', '.svn', '.netrc', '.ssh'),
'add_ignore' => null, // add array with additional filenames to ignore
'secure_dir' => '.', // Only display files below this directory
'base_dir' => '.', // Which directory to start look in, defaults to current working directory of the actual script.
'query_dir' => isset($_GET['dir']) ? strip_tags(trim($_GET['dir'])) : null, // Selected directory as ?dir=xxx
'query_file' => isset($_GET['file']) ? strip_tags(trim($_GET['file'])) : null, // Selected directory as ?dir=xxx
'query_path' => isset($_GET['path']) ? strip_tags(trim($_GET['path'])) : null, // Selected directory as ?dir=xxx
);
// Add more files to ignore
if(isset($options['add_ignore'])) {
$default['ignore'] = array_merge($default['ignore'], $options['add_ignore']);
}
$this->options = $options = array_merge($default, $options);
//Backwards compatible with source.php query arguments for ?dir=xxx&file=xxx
if(!isset($this->options['query_path'])) {
$this->options['query_path'] = trim($this->options['query_dir'] . '/' . $this->options['query_file'], '/');
}
$this->validImageExtensions = $options['image_extensions'];
$this->spaces = $options['spaces_to_replace_tab'];
$this->ignore = $options['ignore'];
$this->secureDir = realpath($options['secure_dir']);
$this->baseDir = realpath($options['base_dir']);
$this->queryPath = $options['query_path'];
$this->suggestedPath = $this->baseDir . '/' . $this->queryPath;
$this->realPath = realpath($this->suggestedPath);
$this->pathinfo = pathinfo($this->realPath);
$this->path = null;
// Ensure that extension is always set
if (!isset($this->pathinfo['extension'])) {
$this->pathinfo['extension'] = null;
}
if(is_dir($this->realPath)) {
$this->file = null;
$this->extension = null;
$this->dir = $this->realPath;
$this->path = trim($this->queryPath, '/');
}
else if(is_link($this->suggestedPath)) {
$this->pathinfo = pathinfo($this->suggestedPath);
$this->file = $this->pathinfo['basename'];
$this->extension = strtolower($this->pathinfo['extension']);
$this->dir = $this->pathinfo['dirname'];
$this->path = trim(dirname($this->queryPath), '/');
}
else if(is_readable($this->realPath)) {
$this->file = basename($this->realPath);
$this->extension = strtolower($this->pathinfo['extension']);
$this->dir = dirname($this->realPath);
$this->path = trim(dirname($this->queryPath), '/');
}
else {
$this->file = null;
$this->extension = null;
$this->dir = null;
}
if($this->path == '.') {
$this->path = null;
}
$this->breadcrumb = empty($this->path) ? array() : explode('/', $this->path);
//echo "<pre>" . print_r($this, 1) . "</pre>";
// Check that dir lies below securedir
$this->message = null;
$msg = "<p><i>WARNING: The path you have selected is not a valid path or restricted due to security constraints.</i></p>";
if(substr_compare($this->secureDir, $this->dir, 0, strlen($this->secureDir))) {
$this->file = null;
$this->extension = null;
$this->dir = null;
$this->message = $msg;
}
// Check that all parts of the path is valid items
foreach($this->breadcrumb as $val) {
if(in_array($val, $this->ignore)) {
$this->file = null;
$this->extension = null;
$this->dir = null;
$this->message = $msg;
break;
}
}
}
/**
* List the sourcecode.
*/
public function View() {
return $this->GetBreadcrumbFromPath()
. $this->message . $this->ReadCurrentDir() . $this->GetFileContent();
}
/**
* Create a breadcrumb of the current dir and path.
*/
public function GetBreadcrumbFromPath() {
$html = "<ul class='src-breadcrumb'>\n";
$html .= "<li><a href='?'>" . basename($this->baseDir) . "</a>/</li>";
$path = null;
foreach($this->breadcrumb as $val) {
$path .= "$val/";
$html .= "<li><a href='?path={$path}'>{$val}</a>/</li>";
}
$html .= "</ul>\n";
return $html;
}
/**
* Read all files of the current directory.
*/
public function ReadCurrentDir() {
if(!$this->dir) return;
$html = "<ul class='src-filelist'>";
foreach(glob($this->dir . '/{*,.?*}', GLOB_MARK | GLOB_BRACE) as $val) {
if(in_array(basename($val), $this->ignore)) {
continue;
}
$file = basename($val) . (is_dir($val) ? '/' : null);
$path = (empty($this->path) ? null : $this->path . '/') . $file;
$html .= "<li><a href='?path={$path}'>{$file}</a></li>\n";
}
$html .= "</ul>\n";
return $html;
}
/**
* Get the details such as encoding and line endings from the file.
*/
public function DetectFileDetails() {
$this->encoding = null;
// Detect character encoding
if(function_exists('mb_detect_encoding')) {
if($res = mb_detect_encoding($this->content, "auto, ISO-8859-1", true)) {
$this->encoding = $res;
}
}
// Is it BOM?
if(substr($this->content, 0, 3) == chr(0xEF) . chr(0xBB) . chr(0xBF)) {
$this->encoding .= " BOM";
}
// Checking style of line-endings
$this->lineendings = null;
if(isset($this->encoding)) {
$lines = explode("\n", $this->content);
$l = strlen($lines[0]);
if(substr($lines[0], $l-1, 1) == "\r") {
$this->lineendings = " Windows (CRLF) ";
}
/*elseif(substr($lines[0], $l-1, 1) == "\r") {
$this->lineendings = " Mac (xxxx) ";
} */
else {
$this->lineendings = " Unix (LF) ";
}
}
}
/**
* Remove passwords from known files from all files starting with config*.
*/
public function FilterPasswords() {
$pattern = array(
'/(\'|")(DB_PASSWORD|DB_USER)(.+)/',
'/\$(password|passwd|pwd|pw|user|username)(\s*=\s*)(\'|")(.+)/i',
//'/(\'|")(password|passwd|pwd|pw)(\'|")\s*=>\s*(.+)/i',
'/(\'|")(password|passwd|pwd|pw|user|username)(\'|")(\s*=>\s*)(\'|")(.+)([\'|"].*)/i',
'/(\[[\'|"])(password|passwd|pwd|pw|user|username)([\'|"]\])(\s*=\s*)(\'|")(.+)([\'|"].*)/i',
);
$message = "Intentionally removed by CSource";
$replace = array(
'\1\2\1, "' . $message . '");',
'$\1\2\3' . $message . '\3;',
'\1\2\3\4\5' . $message . '\7',
'\1\2\3\4\5' . $message . '\7',
);
$this->content = preg_replace($pattern, $replace, $this->content);
}
/**
* Get the content of the file and format it.
*/
public function GetFileContent() {
if(!isset($this->file)) {
return;
}
$this->content = file_get_contents($this->realPath);
$this->DetectFileDetails();
$this->FilterPasswords();
// Display svg-image or enable link to display svg-image.
$linkToDisplaySvg = "";
if($this->extension == 'svg') {
if(isset($_GET['displaysvg'])) {
header("Content-type: image/svg+xml");
echo $this->content;
exit;
} else {
$linkToDisplaySvg = "<a href='{$_SERVER['REQUEST_URI']}&displaysvg'>Display as SVG</a>";
}
}
// Display image if a valid image file
if(in_array($this->extension, $this->validImageExtensions)) {
$baseDir = !empty($this->options['base_dir'])
? rtrim($this->options['base_dir'], '/') . '/'
: null;
$this->content = "<div style='overflow:auto;'><img src='{$baseDir}{$this->path}/{$this->file}' alt='[image not found]'></div>";
}
// Display file content and format for a syntax
else {
$this->content = str_replace('\t', $this->spaces, $this->content);
$this->content = highlight_string($this->content, true);
$i=0;
$rownums = "";
$text = "";
$a = explode('<br />', $this->content);
foreach($a as $row) {
$i++;
$rownums .= "<code><a id='L{$i}' href='#L{$i}'>{$i}</a></code><br />";
$text .= $row . '<br />';
}
$this->content = <<< EOD
<div class='src-container'>
<div class='src-header'><code>{$i} lines {$this->encoding} {$this->lineendings} {$linkToDisplaySvg}</code></div>
<div class='src-rows'>{$rownums}</div>
<div class='src-code'>{$text}</div>
</div>
EOD;
}
return "<h3 id='file'><code><a href='#file'>{$this->file}</a></code></h3>{$this->content}";
}
}
| true |
488606c631d960e1e174a03d9c547bc05223d496 | PHP | kraftner/wpstarter | /src/Config/Result.php | UTF-8 | 5,505 | 2.984375 | 3 | [
"MIT"
] | permissive | <?php
/*
* This file is part of the WP Starter package.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace WeCodeMore\WpStarter\Config;
/**
* Value object used as a result for all the validation operation.
*
* Using this object instead of plain values or just throw exception allows a better error handling,
* easy and clean "fallback" in case of error and type uniformity in return type.
*
* Unfortunately, PHP has no generics at this time, so it isn't possible to have type safety for the
* wrapped value.
*/
final class Result
{
/**
* @var mixed
*/
private $value;
/**
* @var \Throwable|null
*/
private $error;
/**
* @var boolean
*/
private $promise = false;
/**
* @param mixed $value
* @return Result
*
* phpcs:disable Inpsyde.CodeQuality.ArgumentTypeDeclaration
*/
public static function ok($value): Result
{
return new static($value);
}
/**
* @return Result
*/
public static function none(): Result
{
return new static();
}
/**
* @param \Throwable|null $error
* @return Result
*/
public static function error(\Throwable $error = null): Result
{
return new static(null, $error ?: new \Error('Error.'));
}
/**
* @param string $message
* @return Result
*/
public static function errored(string $message): Result
{
return static::error(new \Error($message));
}
/**
* @param callable $provider
* @return Result
*/
public static function promise(callable $provider): Result
{
$instance = new static($provider);
$instance->promise = true;
return $instance;
}
/**
* @param mixed|null $value
* @param \Throwable|null $error
*
* phpcs:disable Inpsyde.CodeQuality.ArgumentTypeDeclaration
*/
private function __construct($value = null, \Throwable $error = null)
{
// phpcs:enable Inpsyde.CodeQuality.ArgumentTypeDeclaration
if ($value instanceof Result) {
$this->value = $value->value;
$this->error = $value->error;
return;
}
if ($value instanceof \Throwable && !$error) {
$error = $value;
$value = null;
}
$this->value = $error ? null : $value;
$this->error = $error;
}
/**
* @return bool
*/
public function notEmpty(): bool
{
$this->maybeResolve();
return !$this->error && ($this->value !== null);
}
/**
* @param mixed $compare
* @return bool
*
* phpcs:disable Inpsyde.CodeQuality.ArgumentTypeDeclaration
*/
public function is($compare): bool
{
$this->maybeResolve();
// phpcs:enable
return !$this->error && ($this->value === $compare);
}
/**
* @param mixed $compare
* @return bool
*
* phpcs:disable Inpsyde.CodeQuality.ArgumentTypeDeclaration
*/
public function not($compare): bool
{
$this->maybeResolve();
// phpcs:enable Inpsyde.CodeQuality.ArgumentTypeDeclaration
return !$this->is($compare);
}
/**
* @param mixed $thing
* @param mixed ...$things
* @return bool
*
* phpcs:disable Inpsyde.CodeQuality.ArgumentTypeDeclaration
*/
public function either($thing, ...$things): bool
{
$this->maybeResolve();
// phpcs:enable Inpsyde.CodeQuality.ArgumentTypeDeclaration
array_unshift($things, $thing);
return !$this->error && in_array($this->value, $things, true);
}
/**
* @param mixed $fallback
* @return mixed
*
* phpcs:disable Inpsyde.CodeQuality.ArgumentTypeDeclaration
* phpcs:disable Inpsyde.CodeQuality.ReturnTypeDeclaration
*/
public function unwrapOrFallback($fallback = null)
{
$this->maybeResolve();
// phpcs:enable Inpsyde.CodeQuality.ArgumentTypeDeclaration
// phpcs:enable Inpsyde.CodeQuality.ReturnTypeDeclaration
return $this->notEmpty() ? $this->value : $fallback;
}
/**
* @return mixed
*
* phpcs:disable Inpsyde.CodeQuality.ReturnTypeDeclaration
*/
public function unwrap()
{
// phpcs:enable Inpsyde.CodeQuality.ReturnTypeDeclaration
$this->maybeResolve();
if ($this->error) {
throw $this->error;
}
return $this->value;
}
/**
* @return void
*/
private function maybeResolve()
{
if (!$this->promise) {
return;
}
$this->promise = false;
/** @var callable $resolver */
$resolver = $this->value;
try {
$value = $resolver();
$resolved = $value;
$error = null;
while ($resolved instanceof Result && !$error) {
$resolved->maybeResolve();
$error = $resolved->error;
$resolved = $resolved->value;
}
if ($error) {
$this->error = $error;
$this->value = null;
return;
}
$this->value = $resolved;
} catch (\Throwable $error) {
$this->value = null;
$this->error = $error;
}
}
}
| true |
69e5a575e9a8dfb14977bc480f7966a093291d99 | PHP | masterpuppet/ProjectManager | /module/Application/src/Application/Model/CommentInterface.php | UTF-8 | 293 | 2.921875 | 3 | [] | no_license | <?php
namespace Application\Model;
interface CommentInterface
{
/**
* @return int
*/
public function getId();
/**
* @param string $message
*/
public function setMessage($message);
/**
* @return string
*/
public function getMessage();
} | true |
0e434400000757e8cd58af1e51b0a0e0f98bc722 | PHP | Andrey-SD/billboard | /app/Http/Controllers/Auth/AuthLoginController.php | UTF-8 | 912 | 2.546875 | 3 | [] | no_license | <?php
namespace Billboard\Http\Controllers\Auth;
use Auth;
use Billboard\User;
use Illuminate\Http\Request;
use Billboard\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
class AuthLoginController extends Controller
{
public function login(Request $request)
{
$this->validate($request, [
'name' => 'required|max:32',
'password' => 'required'
]);
$user = User::where('name', $request->name)->first();
if ($user === null) {
User::insert(array(
'name' => $request->name,
'password' => Hash::make($request->password)
));
}
$credentials = $request->only('name', 'password');
if (Auth::attempt($credentials)) {
return redirect()->intended('/');
} else {
return redirect('/')->withInput();
}
}
}
| true |
608aaa93d2b068323ef823d3c756b2579a61298c | PHP | SeppeDev/web-backend-oplossingen | /24-opdracht-classes-begin/opdracht-classes-begin.php | UTF-8 | 776 | 2.859375 | 3 | [] | no_license | <?php
function __autoload( $className )
{
include "classes/" . $className . ".php";
}
$new = 150;
$unit = 100;
$percent = new Percent( $new, $unit );
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>24 | Oplossing classes begin</title>
</head>
<body>
<table>
<caption>Howmuch % is <?php echo( $new ) ?> out off <?php echo( $unit ) ?>?</caption>
<tr>
<td>Absolute</td>
<td><?php echo( $percent->absolute ) ?></td></tr>
<tr>
<td>Relative</td>
<td><?php echo( $percent->relative ) ?></td></tr>
<tr>
<td>Percent</td>
<td><?php echo( $percent->hundred ) ?></td></tr>
<tr>
<td>Nominal</td>
<td><?php echo( $percent->nominal ) ?></td></tr>
</table>
</body>
</html> | true |
4cba7ab9b836e6a6c7b9b33c48a34d3f9de88eb9 | PHP | kennedylinzie/webprojects | /assets/v1/setup.php | UTF-8 | 1,585 | 2.625 | 3 | [] | no_license | <?php require 'assets/v1/connect.php'?>
<?php
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Create database
$sql = "CREATE DATABASE $db";
if (mysqli_query($conn, $sql)) {
// echo "Database created successfully";
} else {
// echo "Error creating database: " . mysqli_error($conn);
}
// Create connection
$conn = mysqli_connect($servername, $username, $password, $db);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "CREATE TABLE $table (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(100) NOT NULL,
sirname VARCHAR(100) NOT NULL,
username VARCHAR(100),
password VARCHAR(255),
email VARCHAR(100),
dob VARCHAR(50),
islocked int(2),
address VARCHAR(50),
trn_date VARCHAR(50),
reg_date TIMESTAMP
)";
if (mysqli_query($conn, $sql)) {
// echo "Table Users created successfully";
} else {
// echo "Error creating table: " . mysqli_error($conn);
}
// Create connection
$conn = mysqli_connect($servername, $username, $password, $db);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// sql to create table
$sql = "CREATE TABLE questions (
id INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(100) NOT NULL,
question VARCHAR(500) NOT NULL
)";
if (mysqli_query($conn, $sql)) {
// echo "Table Users created successfully";
} else {
// echo "Error creating table: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
| true |
cdf2c5f6bca0182f29b11bf7b32299b3d56e51e4 | PHP | bina-antarbudaya/OR14 | /app/components/auth_component.php | UTF-8 | 2,775 | 2.5625 | 3 | [] | no_license | <?php
// auth component
class AuthComponent extends HeliumComponent {
public $prerequisite_components = array('sessions');
public $controller;
public $session;
public $auth_controller_name = 'auth';
public $login_action_name = 'login';
public $logout_action_name = 'logout';
public function init($controller = null) {
$this->controller = $controller;
$this->sessions = $controller->sessions;
$this->session = $controller->session;
$controller->_alias_method(array($this, 'require_authentication'));
$controller->_alias_method(array($this, 'require_role'));
$auth = $this;
$controller->is_logged_in = function() use ($auth) { return $auth->is_logged_in(); };
$controller->require_authentication = function() use ($auth) { return $auth->require_authentication(); };
$controller->require_role = function($role) use ($auth) { return $auth->require_role($role); };
$controller->user = $controller->session->user;
}
public function process_login($username, $password) {
$user = User::find_by_username_and_password($username, $password);
if ($user) {
$this->session->user_password_hash = $user->password_hash;
$this->session->user = $user;
$this->session->save();
return true;
}
else
return false;
}
public function redirect_to_login_page() {
@header('HTTP/1.1 401 Unauthorized');
Gatotkaca::redirect(array('controller' => $this->auth_controller_name, 'action' => $this->login_action_name));
}
public function process_logout() {
$this->controller->sessions->destroy_session();
}
public function is_logged_in() {
return (bool) $this->session->user_id;
}
public function require_authentication() {
if (!$this->is_logged_in()) {
$this->controller->render = false;
$this->session['last_params'] = $this->controller->params;
$this->session->save();
$this->redirect_to_login_page();
}
}
public function require_role($role) {
$this->require_authentication();
if (!$this->session->user->capable_of($role)) {
$this->controller->render = false;
$this->session['last_params'] = $this->controller->params;
$this->session->save();
$this->redirect_to_login_page();
}
}
public function require_role_and_access_to($role, HeliumRecord $object) {
$this->require_role($role);
if (!$this->session->user->has_access_to($object)) {
$this->controller->render = false;
$this->session['last_params'] = $this->controller->params;
$this->session->save();
$this->redirect_to_login_page();
}
}
public function land() {
if ($this->is_logged_in()) {
$user = $this->session->user;
$land = $user->get_landing_page();
PathsComponent::redirect($land);
}
elseif ($lp = $this->session->flash('last_params'))
PathsComponent::redirect($lp);
exit;
}
} | true |
f9338d4bfa26cc5edf1c9a64034162015fdedbd4 | PHP | B3none/prospect-php-client | /src/Response/SearchReportResponse.php | UTF-8 | 477 | 2.5625 | 3 | [] | no_license | <?php
namespace Silktide\ProspectClient\Response;
use Countable;
use Iterator;
use Psr\Http\Message\ResponseInterface;
use Silktide\ProspectClient\Entity\Report;
class SearchReportResponse extends AbstractResponse
{
/**
* @return Report[]
*/
public function getReports() : array
{
$reports = [];
foreach ($this->response["reports"] as $array) {
$reports[] = Report::create($array);
}
return $reports;
}
} | true |
7b1477130581bb96112b28c382c5aeb22c9bd3f4 | PHP | AlexandreGerault/simple-social-network-api | /app/Repositories/BaseRepository.php | UTF-8 | 372 | 2.828125 | 3 | [] | no_license | <?php
namespace App\Repositories;
use Illuminate\Database\Connection;
abstract class BaseRepository
{
protected Connection $connection;
protected string $table;
/**
* BaseRepository constructor.
* @param Connection $connection
*/
public function __construct(Connection $connection)
{
$this->connection = $connection;
}
}
| true |
a35130b0730c9e4d567854c111fadb5a1881336a | PHP | maxbond/allCultureAPI | /src/ApiActions.php | UTF-8 | 1,297 | 2.984375 | 3 | [
"MIT"
] | permissive | <?php
/**
* Class ApiActions.
*
* all.culture.ru API wrapper
*
* @author Maxim Bondarev <macintosh.way@gmail.com>
*
* @link https://all.culture.ru/public/json/howitworks
*/
namespace Maxbond\AllCultureAPI;
abstract class ApiActions
{
/**
* Request object
* Must contain doRequest($url) method.
*
* @var RequestInterface
*/
protected $requester;
/**
* Build and return full request url.
*/
abstract protected function getRequestUrl();
/**
* Do request and return response.
*
* @throws \Exception
*
* @return object
*/
protected function fire(): object
{
$response = null;
try {
$url = $this->getRequestUrl();
} catch (\Exception $e) {
throw new \Exception($e->getMessage());
}
try {
$response = $this->requester->doRequest($url);
} catch (\Exception $e) {
throw new \Exception($e->getMessage());
}
if ($response) {
$jsonResponse = json_decode($response);
if (isset($jsonResponse->error)) {
throw new \Exception('API error: ' . $jsonResponse->error);
}
return $jsonResponse;
}
throw new \Exception('Empty response');
}
}
| true |
5b55c5af4ea6c30ea050abb83e7ca190da553896 | PHP | deusagnis/laravel-microservice | /app/Microservice/Tools/ErrorsGenerator.php | UTF-8 | 2,358 | 2.796875 | 3 | [] | no_license | <?php
namespace App\Microservice\Tools;
use Illuminate\Support\Facades\Response;
class ErrorsGenerator
{
/**
* List of existing errors: code => name
* @var string[]
*/
protected $errors = [
0 => 'Unexpected error',
1 => 'API not found',
2 => 'Basic validation failed',
3 => 'Authentication failed',
4 => 'Method validation failed',
5 => 'Microservice not found',
6 => 'Authentication validation failed',
];
/**
* Creation formatted errors array
* @param mixed $errors
* @return array
*/
protected function genErrors($errors){
if(is_numeric($errors) or empty($errors)){
$errors = $this->getErrorByCode($errors);
}elseif (is_string($errors)){
$errors = [0 => $errors];
}
$formatted = [];
foreach ($errors as $code=>$value){
$formatted[] = [
'code' => $code,
'value' => $value
];
}
return $formatted;
}
/**
* Create array of single error by code
* @param $code
* @return string[]
*/
protected function getErrorByCode($code){
if(!isset($this->errors[$code])){
$code = 0;
}
return [$code => $this->errors[$code]];
}
/**
* Create content array for response
* @param $content
* @param $errors
* @return array|mixed
*/
public function createContent($content,$errors){
if(is_array($content)){
if(!isset($content['errors'])){
$content['errors']=[];
}
}else{
$content = [
'result' => $content,
'errors' => [],
];
}
$generatedErrors = $this->genErrors($errors);
$content['errors'] = array_merge($content['errors'],$generatedErrors);
return $content;
}
/**
* Create JSON response for errors
* @param $response
* @param $errors
* @return \Illuminate\Http\JsonResponse
*/
public function fillResponse($response,$errors){
$content = $response->getOriginalContent();
$content = $this->createContent($content,$errors);
return Response::json($content,$response->status(),$response->headers->all());
}
}
| true |
cc153fad9ff68763174f8c1a11403aa634563564 | PHP | Cloudotron/scholarzone | /dexcode/core/email/email.php | UTF-8 | 2,229 | 2.71875 | 3 | [] | no_license | <?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
//require '../api/phpmailer/autoload.php';
class email{
public $atta;
public $bcc;
public $cc;
public function __construct(){
$this->atta = "";
$this->bcc = "";
$this->cc = "";
}
public function add_cc($c){
$this->cc = $c;
}
public function add_bcc($bc){
$this->bcc = $bc;
}
public function attachment($at){
$this->atta = $at;
}
public function send($sub,$body,$to,$name){
$mail = new PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = 0; //2
$mail->isSMTP();
$mail->Host = EMAIL_SERVER;
$mail->SMTPAuth = true;
$mail->Username = EMAIL_ADDRESS;
$mail->Password = EMAIL_PASSWORD;
$mail->SMTPSecure = 'tls';
$mail->Port = EMAIL_PORT;
$mail->setFrom(EMAIL_ADDRESS, EMAIL_NAME);
$mail->addReplyTo(EMAIL_ADDRESS, EMAIL_NAME);
$mail->addAddress($to, $name);
if($this->cc != ""){
$mail->addCC($this->cc);
}
if($this->bcc != ""){
$mail->addBCC($his->bcc);
}
//Attachments
if($this->atta != ""){
$mail->addAttachment($this->atta); // Add attachments
}
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $sub;
$mail->Body = $body;
//$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
//echo 'Message has been sent';
return true;
} catch (Exception $e) {
//echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
return false;
}
//email code ends
}
}
?> | true |
62d3d0618616ef5da5e88e01818939311480101f | PHP | kaiopessoni/contacts-manager | /app/Http/Controllers/ContactsController.php | UTF-8 | 4,904 | 2.640625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Contact;
use App\User;
class ContactsController extends Controller
{
/**
* Allow only authenticated users
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$user_id = auth()->user()->id;
$user = User::find($user_id);
return view('contacts.index')->with('contacts', $user->contacts()->orderBy('name', 'asc')->get());
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('contacts.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'phone' => 'required',
'email' => 'required',
'zipcode' => 'required',
'state' => 'required',
'city' => 'required',
'neighbourhood' => 'required',
'street' => 'required',
]);
$contact = new Contact;
$contact->name = $request->input('name');
$contact->phone = $request->input('phone');
$contact->email = $request->input('email');
$contact->zipcode = $request->input('zipcode');
$contact->state = $request->input('state');
$contact->city = $request->input('city');
$contact->neighbourhood = $request->input('neighbourhood');
$contact->street = $request->input('street');
$contact->number = $request->input('number') ?? 0;
$contact->user_id = auth()->user()->id;
$contact->save();
$response = [
"success" => true,
"message" => "Contact created successfully."
];
return Response()->json($response);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$contact = Contact::find($id);
if (auth()->user()->id !== $contact->user_id)
return redirect('/');
return view('contacts.show')->with('contact', $contact);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$contact = Contact::find($id);
if (auth()->user()->id !== $contact->user_id)
return redirect('/');
return view('contacts.edit')->with('contact', $contact);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request, [
'name' => 'required',
'phone' => 'required',
'email' => 'required',
'zipcode' => 'required',
'state' => 'required',
'city' => 'required',
'neighbourhood' => 'required',
'street' => 'required',
]);
$contact = Contact::find($id);
if (auth()->user()->id !== $contact->user_id)
return Response()->json(['success' => false, 'message' => 'Access denied!']);
$contact->name = $request->input('name');
$contact->phone = $request->input('phone');
$contact->email = $request->input('email');
$contact->zipcode = $request->input('zipcode');
$contact->state = $request->input('state');
$contact->city = $request->input('city');
$contact->neighbourhood = $request->input('neighbourhood');
$contact->street = $request->input('street');
$contact->number = $request->input('number') ?? 0;
$contact->save();
$response = [
"success" => true,
"message" => "Contact updated successfully."
];
return Response()->json($response);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$contact = Contact::find($id);
if (auth()->user()->id !== $contact->user_id)
return Response()->json(['success' => false, 'message' => 'Access denied!']);
$contact->delete();
$response = [
"success" => true,
"message" => "Contact deleted successfully."
];
return Response()->json($response);
}
}
| true |
9525699d8a76ab6120c84de84ce4fd7ff052f879 | PHP | PubFork/aikq | /app/Console/HtmlStaticCommand/OtherPlayerCommand.php | UTF-8 | 1,119 | 2.6875 | 3 | [] | no_license | <?php
namespace App\Console\HtmlStaticCommand;
use Illuminate\Support\Facades\Storage;
class OtherPlayerCommand extends BaseCommand
{
protected function command_name()
{
return "other_player";
}
protected function description()
{
return "其他播放器";
}
public function handle()
{
$type = $this->argument('type');
$player = "";
switch ($type) {
case "justfun":
$player = $this->getJustFunPlayer();
break;
case "android":
$player = $this->getJustFunAndroidUtil();
break;
}
if (strlen($player) > 0) {
Storage::disk("public")->put("/www/live/otherPlayer/$type.html", $player);
}
}
private function getJustFunPlayer()
{
return view('pc.live.justfun_player', array('cdn' => env('CDN_URL'), 'host' => 'www.aikanqiu.com'));
}
private function getJustFunAndroidUtil()
{
return view('pc.live.justfun_android', array('cdn' => env('CDN_URL'), 'host' => 'www.aikanqiu.com'));
}
} | true |
95eb9fe2f54b0728e17b29f8f3175a69de304450 | PHP | dijiflex/happyland-ventures-LTD | /includes/subscribe.inc.php | UTF-8 | 894 | 2.96875 | 3 | [] | no_license | <?php
include 'dbh.inc.php';
/* Attempt MySQL server connection*/
$link = mysqli_connect("localhost", "root", "", "cudb");
$sql ="";
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$email = mysqli_real_escape_string($link, $_REQUEST['email']);
//$email = "john.doe@example.com";
// Remove all illegal characters from email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
// Validate e-mail
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$sql = "INSERT INTO subscibers (email) VALUES ('$email')";
} else {
echo("$email is not a valid email address");
}
if(mysqli_query($link, $sql)){
header('../index.php');
// echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
| true |
0fb448d152eccfa92a77aab174d10f643d72ff8d | PHP | oelodran/photo_gallery | /public/login.php | UTF-8 | 2,515 | 2.703125 | 3 | [] | no_license | <?php
require_once ('../private/initialize.php');
$errors = [];
$username = '';
$password = '';
if (is_post_request())
{
$username = $_POST['username'] ?? '';
$password = $_POST['password'] ?? '';
$check = $_POST['check'] ?? '';
// validation
if (is_blank($username))
{
$errors[] = "Username cannot be blank.";
}
if (is_blank($password))
{
$errors[] = "Password cannot be blank.";
}
// try to login
if (empty($errors))
{
$user = User::find_by_username($username);
// test if user found and password is correct
if ($user != false && $user->verify_password($password))
{
if ($check === "checked")
{
$username_encrypt = encrypt_cookie($username);
setcookie("rememberme", $username_encrypt, time() + (86400 * 30));
}
// user logged in
$session->login($user);
redirect_to(url_for('/user/users/index.php?id=' . h(u($user->id))));
}
else
{
// username not found or password does not match
$errors[] = "Log in was unsuccessful.";
}
}
}
?>
<?php $page_title = 'Log in'; ?>
<?php include (SHARED_PATH . '/public_header.php'); ?>
<div class="container">
<h1 class="text-center">Log in or <a btn btn-dark href="<?php echo url_for('/user/users/new.php'); ?>">Registration</a></h1>
<?php echo display_errors($errors); ?>
<form action="login.php" method="post">
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control" id="username" aria-describedby="username" name="username"
value="<?php echo h($username); ?>"placeholder="Enter username">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="InputPassword1" name="password" value="" placeholder="Password">
</div>
<div class="form-check">
<input type="checkbox" class="form-check-input" id="Check1" name="check" value="checked">
<label class="form-check-label" for="Check1">Remember my</label>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
<?php include (SHARED_PATH . '/public_footer.php'); ?> | true |
ec13c3cf70db819dc2b408178cd47ed08a2b4bc9 | PHP | maurosarruda/aulas_php | /02_condicionais/01_condicionais.php | UTF-8 | 1,869 | 3.609375 | 4 | [] | no_license | <h1> Estruturas Condicionais </h1>
<?php
$idade = 16;
if ($idade < 18){
echo "Usuário com $idade anos é menor de idade!";
} else if ($idade == 18){
echo "Usuário possui $idade anos!";
} else {
echo "Usuário com $idade anos é um adulto!";
}
?>
<h1> Operadores Lógicos </h1>
<?php
$idade = 15;
if ($idade >= 18 && $idade < 60){
echo "Pessoa na fase adulta!<br>";
}
$cidade = "Campo Grande";
if ($cidade == "Campo Grande" || $cidade == "Dourados"){
echo "Cidade do MS!<br>";
}
if ($idade >= 18 xor $cidade == "Campo Grande"){
echo "Menor campo-grandense ou Adulto de outra cidade!<br>";
}
$status = false;
if (!$status){
echo "Negação!<br>";
}
?>
<h1>Switch</h1>
<?php
// switch ($variable) {
// case 'value':
// # code...
// break;
// default:
// # code...
// break;
// }
// if ($numero == 0){
// } else if ($numero == 1){
// } else if ($numero == 2){
// } else if ($numero == 3){
// } else {
// }
$numero = 5;
switch ($numero) {
case '1':
echo "caso 1";
break;
case '2':
echo "caso 2";
break;
case '3':
echo "caso 3";
break;
default:
echo "Default";
break;
}
?>
<h1>Operador Ternário</h1>
<?php
// if (condicao){
// //executar se for verdadeiro
// expressao1;
// } else {
// //executar se for falso
// expressao2;
// }
// condicao ? expressao1 : expressao2;
$frequencia = 0.6;
$nota = 5;
// echo "A nota inicial é: $nota <br>";
// echo "A frequencia é: $frequencia <br>";
$nota = ($frequencia >= 0.75) ? ($nota + 2) : ($nota - 2);
echo "A nota inicial é: $nota <br>";
// //Implementação na estrutura IF/ELSE
// if ($frequencia >= 0.75){
// $nota = $nota + 2;
// } else {
// $nota = $nota - 2;
// }
?> | true |
d5124271317fbe6ba7b4c8e9b0f8eaa237a4a215 | PHP | eddy983/-open-treasury-api | /app/Imports/TreasuryImport.php | UTF-8 | 3,677 | 2.625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Imports;
use Carbon\Carbon;
use App\TreasuryTemporary;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithChunkReading;
class TreasuryImport implements ToModel, WithChunkReading
{
public $date;
public function __construct(string $date)
{
$this->date = $date;
}
/**
* @return int
*/
public function startRow(): int
{
return 20;
}
public function chunkSize(): int
{
return 100;
}
/**
* @param Collection $collection
*/
public function collection_old_old(Collection $rows)
{
foreach ($rows as $row)
{
Log::info("TreasuryImport(). saving record. Date: $this->date");
$year = explode('-', $this->date)[2];
$month = explode('-', $this->date)[1];
$day = explode('-', $this->date)[0];
$date = Carbon::create($year . "20", $month, $day, 0, 0 ,0, null);
Log::info("Date: $date");
TreasuryTemporary::firstOrCreate(
[
'date' => $date->toDateString(),
'payment_number' => trim($row[0]),
'payer_code' => (int) trim($row[1]),
'amount' => (float) str_replace(',','',$row[4]),
],
[
'day' => $date->day,
'month' => $date->month,
'year' => $date->year,
'mother_ministry' => "",
'organization_name' => (string) trim($row[2]),
'beneficiary_name' => (string) trim($row[3]),
'amount' => (float) str_replace(',','',$row[4]),
'description' => (string) trim($row[5]),
'irregularities' => "",
]
);
}
}
public function model(array $row)
{
Log::info("TreasuryImport() initialized. Date: $this->date");
$year = explode('-', $this->date)[2];
$month = explode('-', $this->date)[1];
$day = explode('-', $this->date)[0];
$date = Carbon::create($year . "20", $month, $day, 0, 0 ,0, null);
Log::info("Date: $date");
/*$day = empty($row[1]) ? '01' : (int) trim($row[1]);
$month = empty($row[1]) ? '01' : (int) trim($row[2]);
$year = empty($row[1]) ? '2021' : (int) trim($row[3]);*/
//$day = empty($this->date) ? '01' : (int) trim($row[1]);
//$month = empty($this->date) ? '01' : (int) trim($row[2]);
//$year = empty($this->date) ? '2021' : (int) trim($row[3]);
return new TreasuryTemporary([
//'date' => trim($row[0]),
//'date' => Carbon::create($year, $month, $day, 0, 0 ,0, null),
'date' => $date->toDateString(),
'day' => $date->day,
'month' => $date->month,
'year' => $date->year,
'payment_number' => trim($row[0]),
'payer_code' => (int) trim($row[1]),
//'mother_ministry' => (string) trim($row[6]),
'mother_ministry' => "",
'organization_name' => (string) trim($row[2]),
'beneficiary_name' => (string) trim($row[3]),
'amount' => (float) str_replace(',','',$row[4]),
'description' => (string) trim($row[5]),
//'irregularities' => empty($row[11]) ? '' : (string) trim($row[11]),
'irregularities' => "",
]);
}
}
| true |
d933962ace21feee7c7968a45c47b3c077198807 | PHP | vasylshyshola/training | /tasks phpbooktrest/oopLesson2.php | UTF-8 | 3,052 | 3.828125 | 4 | [] | no_license | <?php
error_reporting(-1);
class Employee // employee значит «сотрудник»
{
public $name; // имя-фамилия
public $rate; // часовая ставка (сколько он получает тугриков за час работы)
public $hours = array(); // массив, содержащий отработанные часы по неделям
/** Считает общее число отработанных часов */
public function getTotalHoursWorked()
{
// Просто складываем значения часов в массиве
return array_sum($this->hours);
}
/** Считает зарплату */
public function getSalary()
{
// Получаем число отработанных часов
$hours = $this->getTotalHoursWorked();
$overTime = $this->getOvertimeHours(); //плучаем сверхурочные что оплачиваюиться в двойе
$overTimeSalary = $overTime * ($rate * 2);
// и умножаем на часовую ставку
$salary = $hours * $this->rate;
$salary += $overTimeSalary;
return $salary;
}
public function __construct($name, $rate)
{
// задаем имя и часовую ставку
$this->name = $name;
$this->rate = $rate;
}
/* public function getShortName(){ //метод не работает
$division =[];
$division = explode(" ", $this->name);
$division[1] = substr($division[1],0,1);
$newName = implode(" ", $division);
return $division[1];
} */
public function getOvertimeHours(){
$overTime = 0;
foreach ($this->hours as $value) {
if ($value >= 41) {
$overTime += ($value - 40);
}
}
return $overTime;
}
}
$ivan = new Employee("Иванов Иван",10);
$ivan->hours = array(40, 40, 40, 40); // Иван работает по 40 часов в неделю
$peter = new Employee("Петров Петр",8);
$peter->hours = array(40, 10, 40, 50); // Петр взял отгул и потому отработал меньше часов,
// но в последнюю неделю решил поработать побольше
$employees = array($ivan, $peter);
echo "<table border = 1 >";
echo "<tr><td>Работник</td><td>Часы</td><td>Переработка</td><td>Ставка</td><td>Зарплаата</tr>";
// Сама таблица
foreach ($employees as $employee) {
echo "<tr><td>{$employee->name}</td><td>{$employee->getTotalHoursWorked()}</td><td>{$employee->getOvertimeHours()}</td><td>{$employee->rate}</td> <td>{$employee->getSalary()}</td></tr>";
}
echo "</table>"; | true |
8f7fdccb3382f605c6fd6c547488f8590e8ef7f8 | PHP | programmingdog/tinyframe-frame | /src/cache/Cache.php | UTF-8 | 1,200 | 2.84375 | 3 | [
"Apache-2.0"
] | permissive | <?php
// +----------------------------------------------------------------------
// | zibi [ WE CAN DO IT MORE SIMPLE]
// +----------------------------------------------------------------------
// | Copyright (c) 2016-2019 http://xmzibi.com All rights reserved.
// +----------------------------------------------------------------------
// | Author:MrYe <email:55585190@qq.com>
// +----------------------------------------------------------------------
namespace og\cache;
class Cache
{
/**
* 设置缓存
* @param $key
* @param $data
* @param int $expire
* @return array|bool|Memcache|Redis
*/
public function set($key, $data, $expire = 0)
{
if($data === null) {
//删除缓存信息
return $this->del($key);
}
return cache_write($key, $data, $expire);
}
/**
* 获取缓存
* @param $key
* @return array|bool|Memcache|mixed|Redis|string
*/
public function get($key)
{
return cache_read($key);
}
/**
* 删除缓存
* @param $key
* @return array|bool
*/
public function del($key)
{
return cache_delete($key);
}
} | true |
c5ea25707fa1cf19d38230a1ead9acef9657e6ed | PHP | maarekj/netosoft-domain-bundle | /src/Domain/ChainHandler.php | UTF-8 | 1,042 | 2.875 | 3 | [] | no_license | <?php
namespace Netosoft\DomainBundle\Domain;
use Netosoft\DomainBundle\Domain\Exception\UnhandledException;
class ChainHandler implements HandlerInterface
{
/** @var HandlerInterface[]|array */
private $handlers;
/**
* @param HandlerInterface $handler
*
* @return $this
*/
public function addHandler(HandlerInterface $handler)
{
$this->handlers[] = $handler;
return $this;
}
/** {@inheritdoc} */
public function acceptCommand(CommandInterface $command): bool
{
foreach ($this->handlers as $handler) {
if ($handler->acceptCommand($command)) {
return true;
}
}
return false;
}
/** {@inheritdoc} */
public function handle(CommandInterface $command)
{
foreach ($this->handlers as $handler) {
if ($handler->acceptCommand($command)) {
return $handler->handle($command);
}
}
throw new UnhandledException($command);
}
}
| true |
eaeebee74177102db83986fd4832697852c6c875 | PHP | shuxiaoyuan/My-eBookStore | /My-eBookStore/application/models/BookModel.class.php | UTF-8 | 6,110 | 2.84375 | 3 | [] | no_license | <?php
/**
* application/models/BookModel.class.php
* 图书模型
*/
/* 防止 URL 路径访问 */
if(!defined('ENTRY')) {
header("Location:../../index.php");
exit;
}
class BookModel extends Model {
public function __construct() {
parent::__construct(TABLE_BOOK);
}
/**
* 图书添加
*/
public function addNewBook() {
// 检查表单信息是否齐全
if(!(isset($_POST[NEWBOOK_ISBN]) && $_POST[NEWBOOK_ISBN] !== '')) return "ISBN不能为空!";
if(!(isset($_POST[NEWBOOK_AMOUNT]) && $_POST[NEWBOOK_AMOUNT] !== '')) return "上架数量不能为空!";
// 如果 isbn 已经存在,只更新图书数量信息
if($this -> hasInfor(FIELD_BOOK_ISBN, htmlspecialchars($_POST[NEWBOOK_ISBN]))) {
$book[FIELD_BOOK_PK] = $this -> getOneInfor(FIELD_BOOK_PK, FIELD_BOOK_ISBN, htmlspecialchars($_POST[NEWBOOK_ISBN]));
$book[FIELD_BOOK_AMOUNT] = $_POST[NEWBOOK_AMOUNT] + $this -> getOneInfor(FIELD_BOOK_AMOUNT, FIELD_BOOK_ISBN, htmlspecialchars($_POST[NEWBOOK_ISBN]));
return $this -> updateInfor($book);
}
if(!(isset($_POST[NEWBOOK_NAME]) && $_POST[NEWBOOK_NAME] !== '')) return "图书名不能为空!";
if(!(isset($_POST[NEWBOOK_AUTHOR]) && $_POST[NEWBOOK_AUTHOR] !== '')) return "作者名不能为空!";
if(!(isset($_POST[NEWBOOK_TYPE]) && $_POST[NEWBOOK_TYPE] !== '')) return "图书类型不能为空!";
if(!(isset($_POST[NEWBOOK_PUBLISHER]) && $_POST[NEWBOOK_PUBLISHER] !== '')) return "出版社不能为空!";
if(!(isset($_POST[NEWBOOK_DATE]) && $_POST[NEWBOOK_DATE] !== '')) return "出版日期不能为空!";
if(!(isset($_POST[NEWBOOK_INTRO]) && $_POST[NEWBOOK_INTRO] !== '')) return "图书简介不能为空!";
if(!(isset($_POST[NEWBOOK_COST]) && $_POST[NEWBOOK_COST] !== '')) return "图书成本不能为空!";
if(!(isset($_POST[NEWBOOK_PRICE]) && $_POST[NEWBOOK_PRICE] !== '')) return "图书价格不能为空!";
// 封面图片文件上传合法性检测
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES[NEWBOOK_COVER]["name"]);
// 图片扩展名
$extension = end($temp);
if ((($_FILES[NEWBOOK_COVER]["type"] == "image/gif")
|| ($_FILES[NEWBOOK_COVER]["type"] == "image/jpeg")
|| ($_FILES[NEWBOOK_COVER]["type"] == "image/jpg")
|| ($_FILES[NEWBOOK_COVER]["type"] == "image/pjpeg")
|| ($_FILES[NEWBOOK_COVER]["type"] == "image/x-png")
|| ($_FILES[NEWBOOK_COVER]["type"] == "image/png"))
&& ($_FILES[NEWBOOK_COVER]["size"] < 2000000)
&& in_array($extension, $allowedExts))
{
if ($_FILES[NEWBOOK_COVER]["error"] > 0) {
return $_FILES[NEWBOOK_COVER]["error"];
}
}
else {
return "Invalid file";
}
$bookID = $this -> getAutoincrement();
// 图书封面图片重新命名
$bookFullName = $bookID . "." . $extension;
// 将表单信息特殊字符转码并存入数组
$newBookInfor = array(
FIELD_BOOK_ID => $bookID,
FIELD_BOOK_ISBN => htmlspecialchars($_POST[NEWBOOK_ISBN]),
FIELD_BOOK_NAME => htmlspecialchars($_POST[NEWBOOK_NAME]),
FIELD_BOOK_AUTHOR => htmlspecialchars($_POST[NEWBOOK_AUTHOR]),
FIELD_BOOK_TYPE => htmlspecialchars($_POST[NEWBOOK_TYPE]),
FIELD_BOOK_PUBLISHER => htmlspecialchars($_POST[NEWBOOK_PUBLISHER]),
FIELD_BOOK_DATE => htmlspecialchars($_POST[NEWBOOK_DATE]),
FIELD_BOOK_INTRO => htmlspecialchars($_POST[NEWBOOK_INTRO]),
// 封面图片路径用 config 中定义的常量,那是本地 C 盘下目录
FIELD_BOOK_COVER => "public/images/books/" . $bookFullName,
FIELD_BOOK_COST => htmlspecialchars($_POST[NEWBOOK_COST]),
FIELD_BOOK_PRICE => htmlspecialchars($_POST[NEWBOOK_PRICE]),
FIELD_BOOK_AMOUNT => htmlspecialchars($_POST[NEWBOOK_AMOUNT])
);
// 执行上架
$status = $this -> insertInfor($newBookInfor);
if(is_int($status) && $status > 0) { // 上架成功
// 把图片放到网站目录
move_uploaded_file($_FILES[NEWBOOK_COVER]["tmp_name"], IMAGE_BOOK_PATH . $bookFullName);
$status = "上架成功!";
}
// 返回状态信息
return $status;
}
/**
* 根据图书主键修改图书售价
*/
public function editBookPrice() {
// 接收要编辑的图书的参数 isset 函数防构造请求
if(!(isset($_POST[EDIT_BOOK_PK]) && $_POST[EDIT_BOOK_PK] !== '')) return "没有指定要编辑的图书的主键,疑似伪造请求";
if(!(isset($_POST[EDIT_BOOK_PRICE]) && $_POST[EDIT_BOOK_PRICE] !== '')) return "图书售价为必填信息!";
// 信息更新列表
$bookInfor = array(
FIELD_BOOK_PK => htmlspecialchars($_POST[EDIT_BOOK_PK]),
FIELD_BOOK_PRICE => htmlspecialchars($_POST[EDIT_BOOK_PRICE])
);
// 执行更新并返回结果
return $this -> updateInfor($bookInfor);
}
}
| true |
8103b1e7da292e5584c4adaabd06ce619500d7ee | PHP | KossmoHard/test-light-it | /models/User.php | UTF-8 | 3,271 | 3.078125 | 3 | [] | no_license | <?php
/**
* Класс User - модель для работы с пользователями
*/
class User
{
public static function register($name, $email, $password)
{
// Соединение с БД
$db = Db::getConnection();
// Текст запроса к БД
$sql = 'INSERT INTO user (name, email, password) '
. 'VALUES (?, ?, ?)';
// Получение и возврат результатов. Используется подготовленный запрос
$result = $db->prepare($sql);
$result->bind_param('sss', $name, $email, $password);
return $result->execute();
}
/* Проверяем существует ли пользователь с заданными $email и $password */
public static function checkUserData($email, $password)
{
$db = Db::getConnection();
if ($result = $db->prepare(" SELECT id FROM user WHERE email = ? AND password = ? ")) {
$result->bind_param("ss", $email, $password);
$result->execute();
$result->bind_result($id);
$result->fetch();
return $id;
$result->close();
}else{
return false;
}
$db->close();
}
/* Запоминаем пользователя */
public static function auth($userId)
{
session_start();
$_SESSION['user'] = $userId;
}
public static function checkLogged()
{
// Если сессия есть, вернем идентификатор пользователя
session_start();
if (isset($_SESSION['user'])) {
return $_SESSION['user'];
}
header("Location: /user/login");
}
/* Проверяет является ли пользователь гостем */
public static function isGuest()
{
if (isset($_SESSION['user'])) {
return false;
}
return true;
}
/* Проверяет имя: не меньше, чем 2 символа */
public static function checkName($name)
{
if (strlen($name) >= 2) {
return true;
}
return false;
}
/* Проверяет имя: не меньше, чем 6 символов */
public static function checkPassword($password)
{
if (strlen($password) >= 6) {
return true;
}
return false;
}
/* Проверяет email */
public static function checkEmail($email)
{
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
return true;
}
return false;
}
/* Проверяет не занят ли email другим пользователем */
public static function checkEmailExists($email)
{
$db = Db::getConnection();
$sql = 'SELECT * FROM user WHERE email = ? ';
$result = $db->prepare($sql);
$result->bind_param('s', $email);
$result->execute();
$result->store_result();
$result = $result->num_rows;
if ($result == true){
return true;
}else{
return false;
}
}
} | true |
5d4513961b973068326a1d3e91091fac8f04f75b | PHP | urielfs/tesauro | /vistas/v.historico_ajax.php | UTF-8 | 4,703 | 2.65625 | 3 | [] | no_license | <?php
function array_to_json( $array ){
if( !is_array( $array ) ){
return false;
}
$associative = count( array_diff( array_keys($array), array_keys( array_keys( $array )) ));
if( $associative ){
$construct = array();
foreach( $array as $key => $value ){
// We first copy each key/value pair into a staging array,
// formatting each key and value properly as we go.
// Format the key:
if( is_numeric($key) ){
$key = "key_$key";
}
$key = "'".addslashes($key)."'";
// Format the value:
if( is_array( $value )){
$value = array_to_json( $value );
} else if( !is_numeric( $value ) || is_string( $value ) ){
$value = "'".addslashes($value)."'";
}
// Add to staging array:
$construct[] = "$key: $value";
}
// Then we collapse the staging array into the JSON form:
$result = "{ " . implode( ", ", $construct ) . " }";
} else { // If the array is a vector (not associative):
$construct = array();
foreach( $array as $value ){
// Format the value:
if( is_array( $value )){
$value = array_to_json( $value );
} else if( !is_numeric( $value ) || is_string( $value ) ){
$value = "'".addslashes($value)."'";
}
// Add to staging array:
$construct[] = $value;
}
// Then we collapse the staging array into the JSON form:
$result = "[ " . implode( ", ", $construct ) . " ]";
}
return $result;
}
require_once(dirname(dirname(__FILE__))."/iniciar.php");
# Despliego datos en Hostorico
$campos = "tipo_documento,categoria,status,usuario,autor,titulo,id";
$dato_buscado = $_POST["buscaTitulo"];
$datos = $b->consulta_standard($campos,"where deleted=0 && titulo like '%$dato_buscado%'");
$cadena_datos = '<table class="table table-hover"><thead><th>CATEGORIA</th><th>AUTOR</th><th>TITULO</th><th colspan="3"></th></thead><tbody>';
while($row_datos=$datos->fetch()) {
$stmt = $db->prepare("select usuario,status from tesauro where id=:id");
$stmt->execute(array(":id"=>$row_datos['id']));
$row_user = $stmt->fetch();
$cadena_datos .= '<tr>';
$cadena_datos .= '<td>'.$row_datos['categoria'].'</td>';
$cadena_datos .= '<td>'.$row_datos['autor'].'</td>';
$cadena_datos .= '<td>'.htmlspecialchars($row_datos['titulo']).'</td>';
$cadena_datos .= '<td>';
if($row_user[1]!='OK' && $a->decrypt($_POST["usuario"],"dos")==$row_user[0]) {
$cadena_datos .= '<a href="javascript:void(0);" onClick="javascript:';
$cadena_datos .= 'href=\'v.editar_datos_1.php?token='.$a->encrypt($row_datos[6],'tesa').'&usuario='.$_POST["usuario"].'\';">';
$cadena_datos .= '<span class="glyphicon glyphicon-hand-left" aria-hidden="true"></span>';
$cadena_datos .= '</a>';
// Linea para test-BORRAR
#$cadena_datos .= '<a href="#"><span class="glyphicon glyphicon-hand-left" aria-hidden="true"></span></a>';
}
else {
}
$cadena_datos .= '</td><td>';
$cadena_datos .= '<a href="javascript:void(0);" onClick="javascript:';
$cadena_datos .= 'href=\'v.consultas.php?token='.$a->encrypt($row_datos[6],'tesa').'&usuario='.$_POST["usuario"].'\';">';
$cadena_datos .= '<span class="glyphicon glyphicon-search" aria-hidden="true"></span>';
$cadena_datos .= '</a>';
// Linea para test-BORRAR
#$cadena_datos .= '<a><span class="glyphicon glyphicon-search" aria-hidden="true"></span></a>';
$cadena_datos .= '</td><td>';
if($a->decrypt($_POST["usuario"],"dos")==$row_user[0]) {
$cadena_datos .= '<a href="javascript:void(0);" onClick="javascript:if(confirm(\'Esta accion elimina el registro\nDesea continuar?\')) {';
$cadena_datos .= 'href=\'v.historico.php?tokenpt='.$a->encrypt($row_datos[6],'sicpmt').'&usuario='.$_POST["usuario"].'\';';
$cadena_datos .= '} else { return false; }" align="center">';
$cadena_datos .= '<span class="glyphicon glyphicon-trash" aria-hidden="true" align="center"></span></a>';
$cadena_datos .= '</td></tr>';
// Linea para test-BORRAR
#$cadena_datos .= '<a href="#"><span class="glyphicon glyphicon-trash" aria-hidden="true" align="center"></span></a>';
}
$cadena_datos .= '</td></tr>';
}
$cadena_datos .= '</tbody></table>';
$datos = array("accion"=>"historico", "resultado"=>$cadena_datos);
$cadena = array_to_json($datos);
echo $cadena; | true |
39ca69b632582ec934dd90b2b32c7d11e0974a25 | PHP | tradefurniturecompany/site | /app/code/Hotlink/Brightpearl/Model/Interaction/Stock/Realtime/Import/Environment/Instock.php | UTF-8 | 930 | 2.515625 | 3 | [] | no_license | <?php
namespace Hotlink\Brightpearl\Model\Interaction\Stock\Realtime\Import\Environment;
class Instock extends \Hotlink\Brightpearl\Model\Interaction\Stock\Realtime\Import\Environment\YesNo\AbstractYesNo
{
function getDefault()
{
return 1;
}
function getKey()
{
return 'put_back_instock';
}
function getName()
{
return 'Back in stock';
}
function getNote()
{
return "Select Yes to set product back in stock when availability greater than out of stock threshold. Select No to leave product out of stock. Qty is updated in both cases.";
}
function getValue()
{
if ( !$this->_valueInitialised )
{
$storeId = $this->getEnvironment()->getStoreId();
$this->setValue( $this->getEnvironment()->getConfig()->getPutBackInstock( $storeId ) );
}
return $this->_value;
}
} | true |
11cc1d023ab28875772b645753c139daa2ba2f52 | PHP | fivesqrd/hive | /src/Factory.php | UTF-8 | 1,163 | 2.734375 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
namespace Hive;
use Bego;
use Aws\DynamoDb;
class Factory
{
protected $_table;
protected $_name;
public static function instance($config, $name)
{
if (!isset($config['aws']['version'])) {
$config['aws']['version'] = '2012-08-10';
}
$db = new Bego\Database(
new DynamoDb\DynamoDbClient($config['aws']), new DynamoDb\Marshaler()
);
$table = $db->table(
new Model($config['table'])
);
return new static($table, $name);
}
public static function queue($config, $name)
{
return static::instance($config, $name)->createQueueInstance();
}
public static function query($config, $name)
{
return static::instance($config, $name)->createQueryInstance();
}
public function __construct($table, $name)
{
$this->_table = $table;
$this->_name = $name;
}
public function createQueryInstance()
{
return new Query($this->_table, $this->_name);
}
public function createQueueInstance()
{
return new Queue($this->_table, $this->_name);
}
} | true |
5f3c7ac40267921aee14b0035fd639ef8fa36ec5 | PHP | m0n0ph1/php-design-patterns-1 | /src/Nam/Proxy/ShoppingCart.php | UTF-8 | 172 | 2.578125 | 3 | [] | no_license | <?php
namespace Nam\Proxy;
class ShoppingCart implements Cart
{
private $products;
public function getProducts()
{
return $this->products;
}
} | true |
ece7cc55efc5448b13b8bd161085c67643a2b037 | PHP | bakert/compareweather | /classes/location.php | UTF-8 | 2,437 | 2.875 | 3 | [
"MIT"
] | permissive | <?php
require_once __DIR__ . '/../classes/forecastio.php';
require_once __DIR__ . '/../classes/store.php';
require_once __DIR__ . '/../classes/weather.php';
class Location {
public static function init() {
return [
new Location(Config::firstCityName(), Config::firstCityLatitude(), Config::firstCityLongitude()),
new Location(Config::secondCityName(), Config::secondCityLatitude(), Config::secondCityLongitude()),
];
}
public function __construct($name, $latitude, $longitude) {
$this->name = $name;
$this->latitude = $latitude;
$this->longitude = $longitude;
$this->forecastIo = new ForecastIo();
$this->store = new Store();
$this->data = $this->store->load($this);
}
public function name() {
return $this->name;
}
public function latitude() {
return $this->latitude;
}
public function longitude() {
return $this->longitude;
}
public function icon($date = null) {
return $this->property('icon', $date);
}
public function temperature($date = null) {
return $this->property('temperature', $date);
}
public function averageTemperature($beginDate, $endDate) {
$date = $beginDate;
list($n, $total) = [0.0, 0.0];
while ($date <= $endDate) {
$n += 1.0;
$total += $this->temperature($date);
$date = date('Y-m-d', strtotime($date) + (24 * 60 * 60));
}
return $total / $n;
}
protected function retrieve($date) {
$time = $this->middayAtThisLocation($date);
$data = $this->forecastIo->get($this, $time);
$daily = $data['daily']['data'][0];
$weather = new Weather($this, $daily['icon'], $daily['temperatureMax']);
$this->store->save($date, $weather);
$this->data[$date] = $weather;
}
protected function property($property, $date) {
if (!$date) {
$date = date('Y-m-d');
}
if (!isset($this->data[$date])) {
$this->retrieve($date);
}
return $this->data[$date]->$property();
}
protected function middayAtThisLocation($date) {
$hoursAwayFromGreenwich = $this->longitude() / 15.0;
$time = strtotime($date) + (12 * 60 * 60) + (-$hoursAwayFromGreenwich * 60 * 60);
return (int) round($time);
}
}
| true |
81882039bdbf705018a1516462984765ea559f86 | PHP | meza/nestedset | /src/view/Layout.php | UTF-8 | 231 | 2.6875 | 3 | [] | no_license | <?php
/**
* Layout.php
*
* @author meza <meza@meza.hu>
*/
/**
* Common interface for layouts.
*/
interface Layout
{
/**
* Render the layout with the given data.
*
* @return string
*/
public function render($data='');
} | true |
13a183600747208e721be622cc8ba07a6b39ed70 | PHP | BubblestheKhan/MiscIT490Files | /testfiles/register.php | UTF-8 | 4,036 | 3.015625 | 3 | [] | no_license | <?php
require_once 'config.php'; //include config file
//Define variables with empty variables for input
$username = $password = $confirm_password ='';
$username_err = $password_err = $confirm_password_err = "";
//Process form data upon submission
if($_SERVER["REQUEST_METHOD"] == "POST"){
//Validate username
if(empty(trim($_POST["username"]))){
$username_err = "Please enter a username.";
} else{
//Prepare a select statement
$sql = "SELECT Id FROM users WHERE username = ?";
if($stmt = mysqli_prepare($link, $sql)){
//Bind variables to statements to be accepted as parameters
mysqli_stmt_bind_param($stmt, "s", $param_username);
//Set parameters
$param_username = trim($_POST["username"]);
//Attempt to execute statement
if(mysqli_stmt_execute($stmt)){
//Store results
mysqli_stmt_store_result($stmt);
//Check if username is already in database (taken)
if(mysqli_stmt_num_rows($stmt) ==1){
$username_err = "This username is already taken.";
} else{
$username = trim($_POST["username"]);
}
}else{
echo "Ah! The keg spilled! Please try again later!";
}
}
//Close statement
mysqli_stmt_close($stmt);
}
//Validate password
if(empty(trim($_POST['password']))){
$password_err = "Please enter a password.";
} elseif(strlen(trim($_POST['password'])) < 7){
$password_err = "Password must have at least 7 characters.";
} else{
$password = trim($_POST['password']);
}
//Validate confirm password
if(empty(trim($_POST["confirm_password"]))){
$confirm_password_err = 'Please confirm password.';
} else{
$confirm_password = trim($_POST['comfirm_password']);
if($password != $confirm_password){
$confirm_password_err = 'Password did not match.';
}
}
//Check for input errors before inserting in database
if(empty($username_err) && empty($password_err) && empty($confirm_password_err)){
//Prepare an insert statement
$sql = "INSERT INTO users (username, password) VALUES (?,?)";
if($stmt = mysqli_prepare($link, $sql)){
//Bind variables to statements to be accepted as parameters
mysqli_stmt_bind_param($stmt, "ss", $param_username, $param_password);
//Set parameters
$param_username = $username;
$param_password = password_hash($password, PASSWORD_DEFAULT); //Creates a password hash
//Attempt to execute statement
if(mysqli_stmt_execute($stmt)){
//Redirect to login page
header("location: login.php");
} else{
echo "Ah! The keg spilled! Please try again later!";
}
}
//Close statement
mysqli_stmt_close($stmt);
}
//Close conneciton
mysqli_close($link);
}
?>
<!DOCTYPE HTML>
<head>
<meta charset="UTF-8">
<title>HOP Sign Up</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!--/* PUT CSS HERE */-->
<style type="text/css">
</style>
</head>
<body>
<div class="wrapper">
<h2>Sign Up</h2>
<p>Become a drinking buddy! Fill out this form to create an account.</p>
<form method = "post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>">
<label>Username</label>
<input type="text" name="username" class="form-control" value="<?php echo $username; ?>">
<span class="help-block"><?php echo $username_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>">
<label>Password</label>
<input type="password" name="password" class="form-control" value="<?php echo $password;>">
<span class="help-block"><?php echo $pssword_err; ?></span>
</div>
<div clas="form-group <?php echo (!empty($confirm_password_err)) ? 'has-error' : ''; ?>">
<label>Confirm Password</label>
<input type="password" name="confirm_password" class="form-control" value="<!--?php echo $confirm_password; ?-->">
<span class="help-block"><?php echo $confirm_password_err; ?></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Submit">
<input type="reset" class="btn btn-default" value="Reset">
</div>
| true |
1f32569bf309e04b8e66e046c1fa62b48d61b337 | PHP | Eng-RSMY/Leave-Management-System- | /regadmin.php | UTF-8 | 2,238 | 2.796875 | 3 | [] | no_license | <?php
if($_SERVER["REQUEST_METHOD"] == "POST"){
$errors = array();
$email=$_POST['email'];
$name=$_POST['name'];
$pw=$_POST['password'];
//start validation
include 'connection.php';
$sql = "SELECT * FROM admin where email='$email'";
if($result = mysqli_query($conn, $sql)){
$row = mysqli_fetch_array($result);
if($row['email']==$email){
echo "<script>alert('user already exist');</script>";
//header("Location:login_user.php");
//exit();
}
else{
session_start();
$sql="INSERT INTO admin(name,password,email)
VALUES('$name','$pw','$email')";
if(mysqli_query($conn,$sql)){
echo "<script>alert('Success');</script>";
}
else{
echo "Error" . mysqli_error($conn);
}
mysqli_close($conn);
}
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Lab task</title>
<link rel="stylesheet" type="text/css" href="css/reg.css">
</head>
<body>
<div class='reg'>
<fieldset style="width:15%">
<legend> <h3>New Employee Register</h3> </legend>
<form method="POST" action="">
Name <br>
<input type="text" name="name" value="<?php if(isset($_POST['name'])) echo $_POST['name']; ?>" required>
<p><?php if(isset($errors['name'])) echo $errors['name']; ?></p>
Password <br>
<input type="password" name="password" required pattern=".{6,}">
<p><?php if(isset($errors['password1'])) echo $errors['password1']; ?></p>
<p><?php if(isset($errors['password2'])) echo $errors['password2']; ?></p>
<p><?php if(isset($errors['password3'])) echo $errors['password3']; ?></p>
Email <br>
<input type="text" name="email" value="<?php if(isset($_POST['email'])) echo $_POST['email']; ?>" required pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$">
<p><?php if(isset($errors['email'])) echo $errors['email']; ?></p>
<br>
<hr>
<input type="submit" name="Register" value="ok"> <br><hr>
</form>
</fieldset>
</div>
<div class="b">
<a href="login_user.php" target="main">
<input type="submit" name="back" value="Back" target="main"></a>
</div>
</body>
</html> | true |
0d7449ce970484c07ce352873dd6c4e685b61d3f | PHP | tokenly/quotebot | /app/Console/Commands/FetchQuote.php | UTF-8 | 3,141 | 2.65625 | 3 | [] | no_license | <?php namespace Quotebot\Console\Commands;
use Carbon\Carbon;
use DateTimeZone;
use Illuminate\Console\Command;
use Quotebot\Quote\Selector;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Tokenly\CurrencyLib\CurrencyUtil;
class FetchQuote extends Command {
/**
* The console command name.
*
* @var string
*/
protected $name = 'quotebot:fetch';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Select a quote from the database.';
function __construct(Selector $selector) {
$this->selector = $selector;
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function fire()
{
$name = $this->input->getArgument('name');
$base = $this->input->getArgument('base');
$target = $this->input->getArgument('target');
$start = $this->input->getArgument('start');
$end = $this->input->getArgument('end');
$this->comment("Loading $base:$target from $name from $start to $end");
$aggregate_quote = $this->selector->buildAggregateQuoteByTimestampRange($name, "$base:$target", $start->getTimestamp(), $end->getTimestamp());
// $this->line(json_encode($aggregate_quote, 192));
$this->line("################################################################################################\n");
$this->line("Source : ".$aggregate_quote['name']);
$this->line("Currency: ".substr($aggregate_quote['pair'], strpos($aggregate_quote['pair'], ':') + 1));
$this->line("Range : ".$aggregate_quote['start_timestamp']." to ".$aggregate_quote['end_timestamp']);
$this->line('');
$this->line("Low : ".CurrencyUtil::satoshisToFormattedString($aggregate_quote['last_low'], $base == 'USD' ? 2 : 8)." $base");
$this->line("Average : ".CurrencyUtil::satoshisToFormattedString($aggregate_quote['last_avg'], $base == 'USD' ? 2 : 8)." $base");
$this->line("High : ".CurrencyUtil::satoshisToFormattedString($aggregate_quote['last_high'], $base == 'USD' ? 2 : 8)." $base");
$this->line("\n################################################################################################");
$this->comment("done");
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return [
['name', InputArgument::OPTIONAL, 'The driver name.', 'bitcoinAverage'],
['base', InputArgument::OPTIONAL, 'The base currency.', 'USD'],
['target', InputArgument::OPTIONAL, 'The target currency.', 'BTC'],
['start', InputArgument::OPTIONAL, 'Date range start.', Carbon::create()->modify('-24 hours')],
['end', InputArgument::OPTIONAL, 'Date range end.', Carbon::create()],
];
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return [
];
}
}
| true |
cba53e8efce69ad8c1c54c0445729b81e7e56461 | PHP | wildanarifanani/Aplikasi-Bengkel-Surya-Motor-Cimahi | /bengkels/addKendaraan.php | UTF-8 | 613 | 2.8125 | 3 | [] | no_license | <?php
if($_SERVER['REQUEST_METHOD']=='POST'){
//Getting values
error_reporting(0);
$id = $_POST['id'];
$plat = $_POST['plat'];
$merk = $_POST['merk'];
$tahun = $_POST['tahun'];
//Creating an sql query
$sql = "INSERT INTO tbl_kendaraan(id,plat,merk,tahun) VALUES ('$id','$plat','$merk','$tahun')";
//Importing our db connection script
require_once('dbConnect.php');
//Executing query to database
if(mysqli_query($con,$sql)){
echo 'Data Kendaraan Berhasil Disimpan';
}else{
echo 'Data Kendaraan Gagal Disimpan';
}
//Closing the database
mysqli_close($con);
} | true |
164d033281aa9d6dc11a23b3e0124df17c42281d | PHP | HolyLight110/bibc | /app/Models/Passenger.php | UTF-8 | 520 | 2.578125 | 3 | [] | no_license | <?php
namespace App\Models;
use \Illuminate\Database\Eloquent\Model;
class Passenger extends Model
{
protected $table = 'register_user';
protected $primaryKey = 'iUserId';
protected $fillable = ['vName', 'vLastName', 'vEmail', 'vPhone'];
protected $appends = ['fullName'];
public function getFullNameAttribute()
{
return $this->attributes['vName'] . ' ' . $this->attributes['vLastName'];
}
public function setToken($token)
{
$this->apiToken = $token;
}
} | true |
92b11f5641cdfea0daae6fb0a427f5b903ffead6 | PHP | the-cc-dev/PHPJava | /PHPJava/Attributes/JavaLineNumberTableAttribute.php | UTF-8 | 924 | 2.8125 | 3 | [] | no_license | <?php
class JavaLineNumberTableAttribute extends JavaAttribute {
private $LineNumberTableLength = null;
private $LineNumberTables = null;
public function __construct (&$Class) {
parent::__construct($Class);
$this->LineNumberTableLength = $this->Class->getJavaBinaryStream()->readUnsignedShort();
for ($i = 0; $i < $this->LineNumberTableLength; $i++) {
$this->LineNumberTables[$i] = new JavaStructureLineNumberTable($Class);
$this->LineNumberTables[$i]->setStartPc($this->Class->getJavaBinaryStream()->readUnsignedShort());
$this->LineNumberTables[$i]->setLineNumber($this->Class->getJavaBinaryStream()->readUnsignedShort());
}
}
public function getLineNumberTables () {
return $this->LineNumberTables;
}
} | true |
d527d866d3c6c5e89b5a1f18474db4e37ac9712b | PHP | bsm2/laravelProject | /app/Http/Controllers/blogController.php | UTF-8 | 607 | 2.53125 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\blog;
class blogController extends Controller
{
public function createBlog(Request $request){
$data = $this->validate(request(),[
'title'=>'required|max:10|min:2|regex:/^[a-zA-Z]*$/',
'content'=>'required|max:500|min:50'
]);
blog::create($data);
}
public function displayForm(){
return view('createBlog');
}
public function display(){
$data = blog::get();
return view('blogDetails',['data'=>$data]);
}
}
| true |
6576edcf0f2395a4c9fac22eac6d44829e6e6988 | PHP | hughwilly/oioubl | /tests/Unit/DocumentTest.php | UTF-8 | 1,308 | 2.546875 | 3 | [] | no_license | <?php
namespace HughWilly\OioublTests\Unit;
use Carbon\Carbon;
use HughWilly\Oioubl\CreditNote;
use HughWilly\Oioubl\DocumentFactory;
use HughWilly\Oioubl\Invoice;
use HughWilly\Oioubl\UtilityStatement;
use HughWilly\OioublTests\TestCase;
class DocumentTest extends TestCase
{
public function documentTypeProvider()
{
return [
[Invoice::class],
[UtilityStatement::class],
[CreditNote::class],
];
}
/**
* @dataProvider documentTypeProvider
*/
public function testGetReferenceData($documentType)
{
$document = DocumentFactory::make($documentType, [
'ID' => 1,
'IssueDate' => $today = Carbon::today()->toDateString(),
]);
$this->assertEquals(1, $document->getReferenceData()['ID']);
$this->assertNull($document->getReferenceData()['UUID']);
$this->assertEquals($today, $document->getReferenceData()['IssueDate']);
$this->assertEquals(class_basename($documentType), $document->getReferenceData()['DocumentTypeCode']);
}
/**
* @expectedException \HughWilly\Oioubl\Exceptions\InvalidDocumentTypeException
*/
public function testMakeThrowsExceptionIfInvalidDocumentType()
{
DocumentFactory::make('Foo\\Bar');
}
}
| true |
c1b38d5ce6c596ad5183bbcee33e2bc4137e7dd0 | PHP | tedslittlerobot/vi | /src/Core/Scopes/PublishingTrait.php | UTF-8 | 1,903 | 2.78125 | 3 | [
"MIT"
] | permissive | <?php namespace Vi\Core\Scopes;
trait PublishingTrait {
/**
* Boot the publishing trait for a model.
*
* @return void
*/
public static function bootPublishingTrait()
{
static::addGlobalScope( new PublishingScope );
}
// ! Actions and Methods
/**
* Publish the model.
*
* @return void
*/
public function publish()
{
$query = $this->newQuery()->where($this->getKeyName(), $this->getKey());
$this->{$this->getPublishedAtColumn()} = $time = $this->freshTimestamp();
return $query->update(array($this->getPublishedAtColumn() => $this->fromDateTime($time)));
}
/**
* Unpublish the model.
*
* @return void
*/
public function unpublish()
{
$query = $this->newQuery()->where($this->getKeyName(), $this->getKey());
$this->{$this->getPublishedAtColumn()} = null;
return $query->update(array($this->getPublishedAtColumn() => null));
}
// ! Accessors and Mutators
public function getIsPublishedAttribute()
{
return $this->isPublished();
}
// ! Comparators
/**
* Determine if the model instance has been published.
*
* @return bool
*/
public function isPublished()
{
$publishedAt = $this->{$this->getPublishedAtColumn()};
if ( is_null($publishedAt) ) return false;
return $publishedAt->isPast();
}
// ! Helpers
/**
* Get the name of the "published at" column.
*
* @return string
*/
public function getPublishedAtColumn()
{
return defined('static::PUBLISHED_AT') ? static::PUBLISHED_AT : 'published_at';
}
/**
* Get the fully qualified "published at" column.
*
* @return string
*/
public function getQualifiedPublishedAtColumn()
{
return $this->getTable().'.'.$this->getPublishedAtColumn();
}
/**
* Get the attributes that should be converted to dates.
*
* @return array
*/
public function getDates()
{
return array_merge(parent::getDates(), [$this->getPublishedAtColumn()]);
}
}
| true |
b1b6f11c4af5454ff1c1d6973f79a94f1329bf68 | PHP | pgdba/ConsoleApplication | /Hnk/ConsoleApplicationBundle/Symfony/TaskHelper.php | UTF-8 | 2,035 | 2.75 | 3 | [] | no_license | <?php
namespace Hnk\ConsoleApplicationBundle\Symfony;
use Hnk\ConsoleApplicationBundle\Helper\RenderHelper;
use Hnk\ConsoleApplicationBundle\Helper\TaskHelper as BaseTaskHelper;
class TaskHelper extends BaseTaskHelper
{
/**
* Renders bundle choice
*
* @param array $bundles
* @param string $defaultBundle
* @return array|false
*/
public function renderBundleChoice(array $bundles, $defaultBundle = null)
{
$defaultChoice = null;
RenderHelper::println('Available bundles:');
foreach ($bundles as $key => $bundle) {
RenderHelper::println(sprintf(" * %s: %s", $bundle['name'], RenderHelper::decorateText($key, RenderHelper::COLOR_YELLOW)));
if ($bundle['name'] == $defaultBundle) {
$defaultChoice = $key;
}
}
RenderHelper::println();
$choice = RenderHelper::readln("Choose bundle:", $defaultChoice);
RenderHelper::println();
if (array_key_exists($choice, $bundles)) {
return $bundles[$choice];
} else {
return false;
}
}
/**
* @param array $environments
* @param string $defaultEnvironment
*
* @return bool
*/
public function renderEnvironmentChoice(array $environments, $defaultEnvironment = null)
{
$defaultChoice = null;
RenderHelper::println('Available environments:');
foreach ($environments as $key => $env) {
RenderHelper::println(sprintf(" * %s: %s", $env, RenderHelper::decorateText($key, RenderHelper::COLOR_YELLOW)));
if ($env == $defaultEnvironment) {
$defaultChoice = $key;
}
}
RenderHelper::println();
$choice = $this->renderChoice("Choose environment:", $defaultChoice);
RenderHelper::println();
if (array_key_exists($choice, $environments)) {
return $environments[$choice];
} else {
return false;
}
}
}
| true |
c5934ac93628e227e6db0a9825355b11d3fabe72 | PHP | MasahiroHanawa/online_shop | /src/db/migrations/20180423140703_create_products.php | UTF-8 | 871 | 2.71875 | 3 | [
"MIT"
] | permissive | <?php
use Phinx\Migration\AbstractMigration;
class CreateProducts extends AbstractMigration
{
/**
* Migrate Up.
*/
public function up()
{
// create the table
$table = $this->table('products');
$table->addColumn('gross_price', 'integer')
->addColumn('net_price', 'integer')
->addColumn('images_m', 'string', 255)
->addColumn('images_s', 'string', 255)
->addColumn('product_name', 'string', 255)
->addColumn('color_id', 'integer')
->addColumn('created_at', 'datetime')
->addColumn('updated_at', 'datetime', ['null' => true])
->addColumn('deleted_at', 'datetime', ['null' => true])
->create();
}
/**
* Migrate Down.
*/
public function down()
{
$this->dropTable('products');
}
}
| true |
6a5e978bc0707b611ff8dfe830ee87f7bb9f1496 | PHP | jontxust0/proyecto_final | /model/butacaModel.php | UTF-8 | 2,775 | 2.796875 | 3 | [] | no_license | <?php
include_once ('butacaClass.php');
include_once ('connect_data.php');
class butacaModel extends butacaClass{
private $link;
private $lista= array();
public function getLista()
{
return $this->lista;
}
public function listaButacas($idCine)
{
$this->OpenConnect();
$sql = "CALL spMostrarButacasPorCine($idCine)";
$result = $this->link->query($sql);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$nuevo=new butacaClass();
$nuevo->setId($row['id']);
$nuevo->setNumero($row['numero']);
$nuevo->setReservado($row['reservado']);
$nuevo->setId_cine($row['id_cine']);
array_push($this->lista, $nuevo);
}
mysqli_free_result($result);
$this->CloseConnect();
}
public function ocuparButaca(){
$this->OpenConnect();
$butacaOcupar = $this->getId();
$sql = "CALL spOcuparButacas($butacaOcupar)";
$result = $this->link->query($sql);
if ($this->link->query($sql)>=1)
{
return "Se han reservador los asientos elegidos";
} else {
return "Fallo al reservar asientos: (" . $this->link->errno . ") " . $this->link->error;
}
$this->CloseConnect();
}
/*public function contarButacasLibres(){
$this->OpenConnect();
$idCine = $this->getId_cine();
$sql = "CALL spContarButacasLibres($idCine)";
$result = $this->link->query($sql);
if ($this->link->query($sql)>=1)
{
return "El numero de butacas libres es";
} else {
return "Fallo al mostrar: (" . $this->link->errno . ") " . $this->link->error;
}
$this->CloseConnect();
}*/
public function OpenConnect()
{
$konDat=new connect_data();
try
{
$this->link=new mysqli($konDat->host,$konDat->user,$konDat->password,$konDat->bbdd);
}
catch(Exception $e)
{
echo $e->getMessage();
}
$this->link->set_charset("utf8");
}
public function CloseConnect()
{
mysqli_close ($this->link);
}
function getListaButacasJsonString() {
$arr=array();
foreach ($this->lista as $object)
{
$vars = get_object_vars($object);
array_push($arr, $vars);
}
return $arr;
}
}
?> | true |
4746191bbba466f1a2ec00e437b41acb7b7149e2 | PHP | glidepro/automatorm | /src/Orm/Traits/ClosureTree.php | UTF-8 | 4,958 | 2.84375 | 3 | [
"MIT"
] | permissive | <?php
namespace Automatorm\Orm\Traits;
use Automatorm\Database\Query;
use Automatorm\Database\QueryBuilder;
use Automatorm\Orm\Collection;
/**
* Expected closureTable structure:
* Create Table closure (
* id INT NOT NULL AUTO_INCREMENT,
* parent_id INT NOT NULL,
* child_id INT NOT NULL,
* depth INT NOT NULL
* )
*/
trait ClosureTree
{
private $closureTable = null;
protected function setClosureTable($table)
{
$this->closureTable = $table;
// [FIXME] Check Sanity of selected table in Schema:: based on above structure
}
public function createInitialClosure()
{
$query = new Query($this->connection);
$query->sql(QueryBuilder::insert($this->closureTable, ['parent_id' => $this->id, 'child_id' => $this->id, 'depth' => 0]));
$query->execute();
}
public function addParent(self $parent)
{
$table = $this->closureTable;
$query = new Query($this->connection);
$query->sql("
INSERT INTO $table (parent_id, child_id, depth)
SELECT p.parent_id, c.child_id, p.depth+c.depth+1
FROM $table p, $table c
WHERE p.child_id = {$parent->id} AND c.parent_id = {$this->id}
");
$query->execute();
}
public function removeParent(self $parent)
{
$table = $this->closureTable;
$query = new Query($this->connection);
$query->sql("
DELETE FROM $table WHERE id IN(
SELECT a.id FROM (
SELECT rel.id FROM $table p, $table rel, $table c
WHERE p.parent_id = rel.parent_id and c.child_id = rel.child_id
AND p.child_id = {$parent->id} AND c.parent_id = {$this->id}
) as a
);
");
$query->execute();
}
public function getFullTree()
{
$table = $this->closureTable;
// Query to find root node, and all direct child/parent relationships
$query = new Query($this->connection);
$query->sql("
SELECT parent_id as id FROM $table WHERE child_id = {$this->id} ORDER BY depth DESC LIMIT 1;
");
$query->sql("
SELECT parent_id, child_id FROM $table as t WHERE t.parent_id IN (
SELECT child_id FROM $table WHERE parent_id = (
SELECT parent_id FROM $table WHERE child_id = {$this->id} ORDER BY depth DESC LIMIT 1
)
) AND t.depth = 1;
");
list($root, $results) = $query->execute();
// Root Folder Id
$rootid = $root[0]['id'];
// "Find" all nodes in this tree to so all node objects are in instance cache
$ids = [$rootid];
foreach ($results as $row) {
$ids[] = $row['child_id'];
}
// Reset children and parents arrays on all nodes
foreach (static::findAll(['id' => $ids]) as $node) {
$node->children = new Collection();
$node->parents = new Collection();
}
// Foreach child/parent relationship, set the children/parents properties on the relevant objects.
foreach ($results as $row) {
$parent = static::get($row['parent_id']);
$child = static::get($row['child_id']);
$parent->children[] = $child;
$child->parents[] = $parent;
}
// Return the root node
return static::get($rootid);
}
public function changeParent(self $oldparent, self $newparent)
{
$this->removeParent($oldparent);
$this->addParent($newparent);
}
public function getParents()
{
// Find all direct parent/child relationships
$query = new Query($this->connection);
$query->sql(
QueryBuilder::select($this->closureTable, ['parent_id'])->where(['child_id' => $this->id, 'depth' => 1])
);
list($results) = $query->execute();
$parents = [];
foreach ($results as $row) {
$parents[] = $row['parent_id'];
}
return static::findAll(['id' => $parents]);
}
public function getChildren()
{
// Find all direct child/parent relationships
$query = new Query($this->connection);
$query->sql(
QueryBuilder::select($this->closureTable, ['child_id'])->where(['parent_id' => $this->id, 'depth' => 1])
);
list($results) = $query->execute();
$children = [];
foreach ($results as $row) {
$children[] = $row['child_id'];
}
return static::findAll(['id' => $children]);
}
public function _property_parents()
{
return static::getParents();
}
public function _property_children()
{
return static::getChildren();
}
}
| true |
f5ad1f764732f2cede8c8208a5cba4d3c55e07ab | PHP | Paintras/SyliusRichEditorPlugin | /src/Service/FileUploader.php | UTF-8 | 1,959 | 2.71875 | 3 | [
"MIT"
] | permissive | <?php
/*
* This file is part of Monsieur Biz' Rich Editor plugin for Sylius.
*
* (c) Monsieur Biz <sylius@monsieurbiz.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace MonsieurBiz\SyliusRichEditorPlugin\Service;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class FileUploader
{
/**
* @var string
*/
private $targetPath;
/**
* @var string
*/
private $publicDirectory;
/**
* FileUploader constructor.
*
* @param string $targetPath
* @param string $publicDirectory
*/
public function __construct(string $targetPath, string $publicDirectory)
{
$this->targetPath = $targetPath;
$this->publicDirectory = $publicDirectory;
}
/**
* Upload a file and return the path to it.
*
* @param UploadedFile $file
*
* @return mixed|string
*/
public function upload(UploadedFile $file)
{
// See @https://symfony.com/doc/4.4/controller/upload_file.html
$originalFilename = pathinfo($file->getClientOriginalName(), \PATHINFO_FILENAME);
$safeFilename = transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()', $originalFilename);
$fileName = $safeFilename . '-' . uniqid() . '.' . $file->guessExtension();
try {
$file = $file->move($this->getTargetDirectory(), $fileName);
} catch (FileException $e) {
return '';
}
// Generate path from public folder
return str_replace($this->publicDirectory, '', $file->getPathname());
}
/**
* The directory to write the file.
*
* @return string
*/
private function getTargetDirectory()
{
return $this->publicDirectory . $this->targetPath;
}
}
| true |
61b3e0423baac8e7f81604b2cf5abfc6dc415572 | PHP | dinhbachien/WebQuanLy | /ProjectManagement/app/Http/Controllers/Admin/TaskCrudController.php | UTF-8 | 7,243 | 2.53125 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers\Admin;
use App\Http\Requests\TaskRequest;
use App\Models\Task;
use App\User;
use Backpack\CRUD\app\Http\Controllers\CrudController;
use Backpack\CRUD\app\Library\CrudPanel\CrudPanelFacade as CRUD;
/**
* Class TaskCrudController
* @package App\Http\Controllers\Admin
* @property-read \Backpack\CRUD\app\Library\CrudPanel\CrudPanel $crud
*/
class TaskCrudController extends CrudController
{
use \Backpack\CRUD\app\Http\Controllers\Operations\ListOperation;
// use \Backpack\CRUD\app\Http\Controllers\Operations\CreateOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\UpdateOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\DeleteOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\ShowOperation;
public function setup()
{
$this->crud->setModel('App\Models\Task');
$this->crud->setRoute(config('backpack.base.route_prefix') . '/task');
$this->crud->setEntityNameStrings('task', 'tasks');
CRUD::operation('list', function() {
CRUD::removeButton('create');
});
}
protected function setupListOperation()
{
// TODO: remove setFromDb() and manually define Columns, maybe Filters
$this->addColumns();
}
protected function setupCreateOperation()
{
$this->crud->setValidation(TaskRequest::class);
// TODO: remove setFromDb() and manually define Fields
$this->addFields();
}
protected function setupUpdateOperation()
{
$this->setupCreateOperation();
}
private function addColumns(){
$this->crud->addColumn([
"name" => "content",
"label" => "Content",
"type" => "text"
]);
$this->crud->addColumn([
"name" => "priority",
"label" => "Priority",
"type" => "closure",
"function" => function($entry){
return $this->getLabel($entry);
}
]);
$this->crud->addColumn([
"name" => "user",
"label" => "Assignments",
"type" => "closure",
"function" => function($entry){
$name = "";
if ($entry->users->count() > 0){
foreach ($entry->users as $user){
$name .= $user->name . ",";
}
$name = substr($name, 0, -1);
}else{
$name = "";
}
return $name;
},
"limit" => 200
]);
$this->crud->addColumn([
"name" => "started_at",
"label" => "Started at",
"type" => "dateTime"
]);
$this->crud->addColumn([
"name" => "end_at",
"label" => "End at",
"type" => "dateTime"
]);
}
private function getLabel($entry)
{
$label = "";
switch ($entry->priority) {
case config("prioritize.urgent_and_important"):
$label = "<span class='label' style='background-color: " . config("prioritize.urgent_and_important_color") . "'>Urgent and Important</span>";
break;
case config("prioritize.important_not_urgent"):
$label = "<span class='label' style='background-color: " . config("prioritize.important_not_urgent_color") . "'>Important not Urgent</span>";
break;
case config("prioritize.urgent_not_important"):
$label = "<span class='label' style='background-color: " . config("prioritize.urgent_not_important_color") . "'>Urgent not Important</span>";
break;
case config("prioritize.not_important_not_urgent"):
$label = "<span class='label' style='background-color: " . config("prioritize.not_important_not_urgent_color") . "'>not Important not Urgent</span>";
break;
}
return $label;
}
private function addFields(){
$this->crud->addField([
"label" => "Content",
"name" => "content",
"type" => "text"
]);
$this->crud->addField([
"label" => "Priority",
"name" => "priority",
'type' => 'select_from_array',
'options' => [
config("prioritize.urgent_and_important") => "urgent and important",
config("prioritize.important_not_urgent") => "important not urgent",
config("prioritize.urgent_not_important") => "urgent not important",
config("prioritize.not_important_not_urgent") => "not important not urgent"
],
'allows_null' => false,
'default' => 0,
]);
$this->crud->addField([
"label" => "Start at",
"type" => "datetime_picker",
"name" => "started_at"
]);
$this->crud->addField([
"label" => "End at",
"type" => "datetime_picker",
"name" => "end_at"
]);
$this->crud->addField([
"label" => "Assigned to",
'type' => "UserSelect",
'name' => 'user_id',
'entity' => 'users',
'attribute' => "name",
'model' => User::class,
'data_source' => url("api/users/assigned-to"),
'placeholder' => "Select member ",
'minimum_input_length' => 2,
'pivot' => true,
'hint' => "you just choose user who was added to this project"
]);
$this->crud->addField([
"label" => "To do",
"type" => "AddTodo",
'name' => 'task[]',
'suffix' => "<button class=\"btn btn-primary btn-sm\" id='more-task' title=\"add task\"><span class=\"la la-plus\"></span> </button>",
'hint' => "you can add Task for this project or later"
]);
}
/**
* Update the specified resource in the database.
*
* @return Response
*/
public function update()
{
$this->crud->hasAccessOrFail('update');
// execute the FormRequest authorization and validation, if one is required
$request = $this->crud->validateRequest();
$data = $data = $request->except(["_token","_method","http_referrer","save_action"]);
// update the row in the db
$item = Task::find($request->get($this->crud->model->getKeyName()));
$item->update($data);
$this->data['entry'] = $this->crud->entry = $item;
$this->addMember($item, $data["user_id"]);
// show a success message
\Alert::success(trans('backpack::crud.update_success'))->flash();
// save the redirect choice for next time
$this->crud->setSaveAction();
return $this->crud->performSaveAction($item->getKey());
}
private function addMember($item, $users)
{
foreach ($item->users as $user) {
$item->users()->detach($user->id);
}
if (!empty($users)) {
foreach ($users as $user_id) {
$item->users()->attach($user_id);
}
}
}
}
| true |
5bada03ffbd9a1ee2197fa876335908bca35998c | PHP | SafalFrom2050/restaurant-app | /classes/admin/Controllers/CategoryController.php | UTF-8 | 742 | 2.5625 | 3 | [] | no_license | <?php
namespace admin\Controllers;
use admin\Services\CategoryService;
use Models\Category;
class CategoryController {
public $request;
public $view;
private $props;
public function __construct($request)
{
$this->request = $request;
$this->handleRequest();
}
public function index()
{
return loadTemplate($this->view, $this->props);
}
private function handleRequest()
{
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
CategoryService::create(getPDO())->performAction($this->request);
}
$this->props['categories'] = Category::create(getPDO())->findAll();
$this->view = TEMPLATES_PATH_ADMIN.'categories-template.php';
}
} | true |