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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
2a82fac8d66071bc7669bf004dc709cfb97f2189 | PHP | ngadzheva/ElectivesManagement | /exam_final/php/registerValidation.php | UTF-8 | 7,173 | 2.515625 | 3 | [] | no_license | <?php
require_once 'student.php';
require_once 'lecturer.php';
session_start();
$database = new DataBase();
$user = modifyInput($_POST['user']);
$pass = modifyInput($_POST['password']);
$confirmPass = modifyInput($_POST['confirmPassword']);
$names = modifyInput($_POST['names']);
$email = modifyInput($_POST['email']);
$userType = modifyInput($_POST['userType']);
$fn = $_POST['fn'];
$year = $_POST['year'];
$bachelorPrograme = $_POST['bachelorPrograme'];
$department = modifyInput($_POST['department']);
$telephone = modifyInput($_POST['telephone']);
$visitingHours = modifyInput($_POST['visitingHours']);
$office = modifyInput($_POST['office']);
$personalPage = modifyInput($_POST['personalPage']);
$_SESSION['names'] = $names;
$_SESSION['user'] = $user;
$_SESSION['email'] = $email;
$_SESSION['fn'] = $fn;
$_SESSION['year'] = $year;
$_SESSION['department'] = $department;
$_SESSION['telephone'] = $telephone;
$_SESSION['visitingHours'] = $visitingHours;
$_SESSION['office'] = $office;
$_SESSION['personalPage'] = $personalPage;
setcookie('userType', $userType, time() + 240, '/');
setcookie('bachelorPrograme', $bachelorPrograme, time() + 240, '/');
if(!$names || !$user || !$email || !$pass){
$_SESSION['registrationError'] = 'Моля, попълнете всички задължителни полета.';
header('Location: ./register.php');
} else {
if(mb_strlen($names) > 200){
$_SESSION['registrationError'] = 'Трите имена трябва да са най-много 200 символа.';
header('Location: ./register.php');
} else if(mb_strlen($user) > 200){
$_SESSION['registrationError'] = 'Потребителското име трябва да е най-много 200 символа.';
header('Location: ./register.php');
} else if(mb_strlen($email) > 200){
$_SESSION['registrationError'] = 'Email-ът трябва да е най-много 200 символа.';
header('Location: ./register.php');
} else if(mb_strlen($pass) > 200){
$_SESSION['registrationError'] = 'Паролата трябва да е най-много 200 символа.';
header('Location: ./register.php');
} else if($pass != $confirmPass){
$_SESSION['registrationError'] = 'Двете пароли не съвпадат.';
header('Location: ./register.php');
} else {
$sql = "SELECT * FROM users WHERE userName='$user' || email= '$email'";
$query = $database->executeQuery($sql, "Failed finding $user!");
$exist = $query->fetch(PDO::FETCH_ASSOC);
if($exist){
$_SESSION['registrationError'] = 'Съществува потребител с въведеното потребителско име / парола.';
header('Location: ./register.php');
} else {
if($userType == '-'){
$_SESSION['registrationError'] = 'Моля, попълнете всички задължителни полета.';
header('Location: ./register.php');
} else if($userType == 'student'){
if(!$fn || !$year || !$bachelorPrograme){
$_SESSION['registrationError'] = 'Моля, попълнете всички задължителни полета.';
header('Location: ./register.php');
}
if(mb_strlen($bachelorPrograme) > 200){
$_SESSION['registrationError'] = 'Името на бакалавърската програма трябва да е най-много 200 символа.';
header('Location: ./register.php');
}
$student = new Student($user, $fn);
$student->insertStudent($user, hash('sha256', $pass), $email, $fn, $names, $year, $bachelorPrograme);
$database->closeConnection();
session_destroy();
setcookie('userType', $userType, time() - 240, '/');
setcookie('bachelorPrograme', $bachelorPrograme, time() - 240, '/');
header('Location: ./login.php');
} else {
if(!$department){
$_SESSION['registrationError'] = 'Моля, попълнете всички задължителни полета.';
header('Location: ./register.php');
} else if(mb_strlen($department) > 100){
$_SESSION['registrationError'] = 'Името на катедрата трябва да е най-много 100 символа.';
header('Location: ./register.php');
} else if(strlen($telephone) > 20){
$_SESSION['registrationError'] = 'Телефонният номер трябва да е най-много 20 символа.';
header('Location: ./register.php');
} else if (!preg_match ('/\+359 [0-9]{1,4} [0-9]{2} [0-9]{2} [0-9]{2,3}/', $telephone)){
$_SESSION['registrationError'] = 'Телефонният номер не е валиден.';
header('Location: ./register.php');
} else if(mb_strlen($visitingHours) > 50){
$_SESSION['registrationError'] = 'Приемното време трябва да е обозначено в най-много 50 символа.';
header('Location: ./register.php');
} else if(mb_strlen($office) > 100){
$_SESSION['registrationError'] = 'Името на кабинета трябва да е най-много 100 символа.';
header('Location: ./register.php');
} else if(strlen($personalPage) > 200){
$_SESSION['registrationError'] = 'Адресът на личната страница трябва да е най-много 200 символа.';
header('Location: ./register.php');
}
$lecturer = new Lecturer($user, '');
$lecturer->insertLecturer($user, hash('sha256', $pass), $email, $names, $department, $telephone, $visitingHours, $office, $personalPage);
$database->closeConnection();
session_destroy();
setcookie('userType', $userType, time() - 240, '/');
header('Location: ./login.php');
}
}
}
}
function modifyInput($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
| true |
2691b83a66b2fe4d05027584794d3919ad73e6fb | PHP | erodrimora/team-superman-hngi7 | /scripts/internemmanuel(scripts).php | UTF-8 | 307 | 3.171875 | 3 | [] | no_license | <?php
/*
*Just trying to keep things simple *
*but still avoid being accused of *
*plagiarism because this task doesn't *
*have many unique solutions *
*/
$output = 'Hello World, this is Emmanuel Menyaga with HNGi7 ID HNG-02898 using PHP for stage 2 task.sparklinsparky@gmail.com';
echo $output; | true |
629efa6cf722c1a5d6d1ef5d81b00dcf7e14a040 | PHP | sumeetshahani108/Housing-Management-System | /app/Owner.php | UTF-8 | 1,201 | 2.671875 | 3 | [
"MIT"
] | permissive | <?php
//In models we define out business logic .
namespace App;
use App\Like;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Zizaco\Entrust\Traits\EntrustUserTrait;
class Owner extends Model implements AuthenticatableContract, CanResetPasswordContract
{
//define in the model, what is the name of the table
use Authenticatable,CanResetPassword, EntrustUserTrait;
protected $table = 'owner';
protected $primaryKey = 'owner_id';
//if we don't write the timestamp, it gives the error : column not found
public $timestamps = false;
public function getAuthIdentifier(){
return $this->getKey();
}
public function apartment(){
return $this->hasMany('Apartment','apt_id');
}
public function getAuthPassword(){
return $this->password;
}
public function getReminderEmail(){
return $this->email;
}
public function likes()
{
return $this->hasMany('App\Like');
}
}
| true |
146b948d92bf29560cc62f8c862c28b35f7ce3ce | PHP | pawelfuta/Grupa | /src/Grupa/ProjektBundle/Entity/FilmGatunek.php | UTF-8 | 1,261 | 2.59375 | 3 | [
"MIT",
"BSD-3-Clause"
] | permissive | <?php
namespace Grupa\ProjektBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Grupa\ProjektBundle\Entity\Film as Film;
use Doctrine\Common\Collections\ArrayCollection;
/**
* @ORM\Entity
* @ORM\Table()
*/
class FilmGatunek
{
/**
* @ORM\Id
* @ORM\Column(type="string")
*/
protected $name;
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @ORM\OneToMany(targetEntity="Film", mappedBy="gatunek")
*/
protected $filmy;
public function __construct()
{
$this->filmy = new ArrayCollection();
}
/**
* Set name
*
* @param string $name
* @return FilmGatunek
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Add filmy
*
* @param \Grupa\ProjektBundle\Entity\Film $filmy
* @return FilmGatunek
*/
public function addFilmy(\Grupa\ProjektBundle\Entity\Film $filmy)
{
$this->filmy[] = $filmy;
return $this;
}
/**
* Remove filmy
*
* @param \Grupa\ProjektBundle\Entity\Film $filmy
*/
public function removeFilmy(\Grupa\ProjektBundle\Entity\Film $filmy)
{
$this->filmy->removeElement($filmy);
}
/**
* Get filmy
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getFilmy()
{
return $this->filmy;
}
}
| true |
1fc3eab3392632969baa890994657648bca82f70 | PHP | kwda1002/PHP_test | /touch restaurants_searche.php | UTF-8 | 491 | 2.671875 | 3 | [] | no_license | # restaurants_seasher.php
<?php
function write_data_to_csv(){
$restaurants = [];
$response = "hogehoge";
if(isset($response["results"]["error"])){
return print("エラーが発生しました!");
}
if(isset($response["results"]["shop"])){
foreach($response["shop"] as &$i){
$restaurant_name = $i["name"];
$restaurants[] = $restaurant_name;
}
}
return print_r($restaurants);
}
write_data_to_csv()
?>
| true |
ae5f8275a748f35491c342121474f1f703fab54f | PHP | nguyenky/shophoa | /app/Http/Middleware/RoleMiddleware.php | UTF-8 | 719 | 2.703125 | 3 | [] | no_license | <?php
namespace App\Http\Middleware;
use Closure;
use Auth;
class RoleMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next,$role)
{
$arUser = Auth::user();
if($arUser['roles']==1){
$ss = 'Admin';
}elseif ($arUser['roles']==2) {
$ss = 'Mod';
}else{
$ss = 'User';
}
//-----
//----
if(strpos($role,$ss) === false){
return redirect()->route('admin.auth.error');
}
return $next($request);
}
}
| true |
1572b6144846df8c3b2110391eb5b49a29df0c4a | PHP | Guillermo-l/Bucket-list-van-je-vrienden-1b700f72 | /bucket_list_friends.php | UTF-8 | 600 | 3.65625 | 4 | [] | no_license | <?php
$vrienden = [];
echo "Hoeveel vrienden zal ik vragen om hun droom?" . PHP_EOL;
$aantalVrienden = readline(">");
if (is_numeric($aantalVrienden)) {
for ($i = 0; $i < $aantalVrienden; $i++) {
echo "Wat is jouw naam?" . PHP_EOL;
$namen = readline(">");
echo "Wat is jouw droom?" . PHP_EOL;
$vrienden[$namen] = readline(">");
}
foreach ($vrienden as $naam => $droom) {
echo $naam . "heeft dit als droom: " . $droom . PHP_EOL;
}
} else {
echo "'$aantalVrienden' is geen geldig getal, probeer het opnieuw!" . PHP_EOL;
exit();
}
?> | true |
4643899fd78529db31f1cd62cea63b9e190ae534 | PHP | BGCX067/f1n4l-pr0j3c7-f0r-t3h-0n35-wh0-n33d-17-svn-to-git | /trunk/application/forms/Esqueci.php | UTF-8 | 1,314 | 2.53125 | 3 | [] | no_license | <?php
class Application_Form_Esqueci extends Zend_Form {
public function init() {
$validate = new Zend_Validate_Callback('userExists');
$validate->setMessage('Usuario inexistente!');
$this->addElement(
'text',
'usuario',
array(
'label' => 'CPF (usuario / somente numeros)*',
'required' => true,
'class' => 'campo-txt',
'validators' => array(
new Zend_Validate_Int(),
$validate
)
)
);
$this->addElement(
'submit',
'submit_button',
array(
'label' => 'Enviar',
'class' => 'bt-enviar',
'ignore' => true
)
);
}
}
function userExists($user) {
$usuarioModel = new Application_Model_Usuario();
$exists = $usuarioModel->fetchRow(
$usuarioModel->select()
->where('usuario = :usuario')
->bind(array(
'usuario' => $user
))
);
if ($exists != null) {
return true;
}
return false;
}
| true |
0d8a18bdc1309bc2b53d28e719280b268c947953 | PHP | kilofox/ftwcm-shop | /src/Event/StoreSaved.php | UTF-8 | 308 | 2.609375 | 3 | [
"MIT"
] | permissive | <?php
namespace Ftwcm\Shop\Event;
/**
* 商店保存完成事件。
*/
class StoreSaved
{
/** @var object $store */
public $store;
/**
* Constructor.
*
* @param object $store
*/
public function __construct(object $store)
{
$this->store = $store;
}
}
| true |
9985d0e91ad055872fefc389b0e6cbaecf085129 | PHP | m75687/stu3 | /src/Lib/YRow.php | UTF-8 | 1,017 | 2.90625 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types=1);
class YRow
{
protected $row = null;
protected $minx = null;
protected $maxx = null;
protected $systemId = null;
function __construct($cury, $minx, $maxx, $systemId = 0)
{
$this->row = $cury;
$this->minx = $minx;
$this->maxx = $maxx;
$this->systemId = $systemId;
}
protected $fields = null;
function getFields()
{
if ($this->fields === null) {
for ($i = $this->minx; $i <= $this->maxx; $i++) {
$this->fields[] = MapField::getFieldByCoords($i, $this->row);
}
}
return $this->fields;
}
function getSystemFields()
{
if ($this->fields === null) {
for ($i = $this->minx; $i <= $this->maxx; $i++) {
$this->fields[] = SystemMap::getFieldByCoords($this->systemId, $i, $this->row);
}
}
return $this->fields;
}
function getRow()
{
return $this->row;
}
} | true |
b7b027f0d17b10ad32bc53f77455b4d05fab4203 | PHP | devDzign/sf52-ddd-code-challenge | /domain/src/Security/Gateway/ParticipantGateway.php | UTF-8 | 494 | 2.796875 | 3 | [] | no_license | <?php
namespace Chabour\Domain\Security\Gateway;
use Chabour\Domain\Security\Model\Participant;
interface ParticipantGateway
{
/**
* @param string|null $email
* @return bool
*/
public function isEmailUnique(?string $email): bool;
/**
* @param string|null $pseudo
* @return bool
*/
public function isPseudoUnique(?string $pseudo): bool;
/**
* @param Participant $user
*/
public function register(Participant $user): void;
}
| true |
9bb8f4af44c40f12eab53eb8a2f7799fecde4114 | PHP | quadrowin/icengine | /Class/Query/Command/From.php | UTF-8 | 1,491 | 2.703125 | 3 | [] | no_license | <?php
/**
* Часть запроса from
*
* @author morph
*/
class Query_Command_From extends Query_Command_Abstract
{
/**
* @inheritdoc
*/
protected $mergeStrategy = Query::MERGE;
/**
* @inheritdoc
*/
protected $part = Query::FROM;
/**
* Помощник для операции join
*
* @var Helper_Query_Command_Join
*/
protected static $helper;
/**
* @inheritdoc
*/
public function create($data)
{
$this->data = $this->helper()->join(
!empty($data[1]) ? $data : $data[0], Query::FROM
);
return $this;
}
/**
* Получить хелпер
*
* @return Helper_Query_Command_Join
*/
public function getHelper()
{
return self::$helper;
}
/**
* Получить (инициализировать) хелпер
*/
protected function helper()
{
if (is_null(self::$helper)) {
$serviceLocator = IcEngine::serviceLocator();
self::$helper = $serviceLocator->getService(
'helperQueryCommandJoin'
);
}
return self::$helper;
}
/**
* Изменить хелпер
*
* @param Helper_Query_Command_Join $helper
*/
public function setHelper($helper)
{
self::$helper = $helper;
}
} | true |
aef5fcfcf1b393d4e94ba3a974f25e1dfd0af607 | PHP | sfnt/ms | /protected/modules/articles/controllers/ColumnController.php | UTF-8 | 8,418 | 2.71875 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
class ColumnController extends ArticlesController
{
/**
* Displays a particular model.
* @param integer $id the ID of the model to be displayed
*/
public function actionView($id)
{
$this->render('view',array(
'model'=>$this->loadModel($id),
));
}
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
*/
public function actionCreate($parentid = 0)
{
$model=new Column;
// AJAX 表单验证
$this->performAjaxValidation($model);
if(isset($_POST['Column']))
{
$model->attributes=$_POST['Column'];
$time = time();
$model->creattime = $time;
$model->updatetime = $time;
$model->publishtime = $time;
if(isset($_POST['publishtime']) && $_POST['publishtime']){
$model->publishtime = strtotime($_POST['publishtime']);
}
if($model->parentid>0){
$parent = Column::model()->findByPk($model->parentid);
if($parent)
{
$model->level = $parent->level + 1;
if($parent->level==0){
$model->rootid = $parent->id;
}
else{
$model->rootid = $parent->rootid;
}
}
else
{
$model->parentid = 0;
$model->level = 0;
$model->rootid = 0;
}
}
else{
$model->parentid = 0;
$model->level = 0;
$model->rootid = 0;
}
if($model->save())
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
}
if ($parentid)
$model->parentid = $parentid;
$model->template = 'column';
$model->content_template = 'article';
$this->render('create',array(
'model'=>$model,
));
}
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id the ID of the model to be updated
*/
public function actionUpdate($id)
{
$model=$this->loadModel($id);
//AJAX 表单验证
$this->performAjaxValidation($model);
if(isset($_POST['Column']))
{
$model->attributes=$_POST['Column'];
$time = time();
//$model->creattime = $time;
$model->updatetime = $time;
//$model->publishtime = $time;
if(isset($_POST['publishtime']) && $_POST['publishtime']){
$model->publishtime = strtotime($_POST['publishtime']);
}
if($model->parentid>0){
$parent = Column::model()->findByPk($model->parentid);
if($parent)
{
$model->level = $parent->level + 1;
if($parent->level==0){
$model->rootid = $parent->id;
}
else{
$model->rootid = $parent->rootid;
}
}
else
{
$model->parentid = 0;
$model->level = 0;
$model->rootid = 0;
}
}
else{
$model->parentid = 0;
$model->level = 0;
$model->rootid = 0;
}
if($model->save())
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
}
$this->render('update',array(
'model'=>$model,
));
}
/**
* Deletes a particular model.
* If deletion is successful, the browser will be redirected to the 'admin' page.
* @param integer $id the ID of the model to be deleted
*/
public function actionDelete($id)
{
if(Yii::app()->request->isPostRequest)
{
// we only allow deletion via POST request
$this->loadModel($id)->delete();
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if(!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
else
throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
}
/**
* Lists all models.
*/
public function actionIndex()
{
$menus = Column::getTreeDATA('*', false);
$tree = new Tree();
$tree->icon = array(' │ ', ' ├─ ', ' └─ ');
$tree->nbsp = ' ';
$array = array();
$enum_display = EnumHelper::IsDisplay();
$enum_template = EnumHelper::ColumnTemplate();
$enum_contentTemplate = EnumHelper::ContentTemplate();
foreach ($menus as $r) {
$r['str_manage'] = CHtml::link('<i class="icon-plus icon-white"></i>'.Yii::t('articles','Add subcategory'), array('create', 'parentid'=>$r['id']),array('class'=>'btn btn-info')).' '.
CHtml::link('<i class="icon-edit icon-white"></i>'.Yii::t('system','modify'), array('update', 'id'=>$r['id']),array('class'=>'btn btn-info'))
.' '.
CHtml::link('<i class="icon-trash icon-white"></i>'.Yii::t('system','delete'), array('delete', 'id'=>$r['id']),array('class'=>'btn btn-info btn-del')).' ';
$r['publish_status'] = $enum_display[$r['publish_status']];
$r['template'] = $enum_template[$r['template']];
$r['content_template'] = $enum_contentTemplate[$r['content_template']];
$array[] = $r;
}
$str = "<tr>
<td><input name='listorders[\$id]' type='text' size='3' value='\$listorder' class='input-text-c'></td>
<td >\$spacer\$name</td>
<td >\$template</td>
<td >\$content_template</td>
<td >\$publish_status</td>
<td >\$str_manage</td>
</tr>";
$tree->init($array);
$this->render('index', array(
'menuTree' => $tree->get_tree('0', $str)
));
}
/**
* Returns the data model based on the primary key given in the GET variable.
* If the data model is not found, an HTTP exception will be raised.
* @param integer the ID of the model to be loaded
*/
public function loadModel($id)
{
$model=Column::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
/**
* Performs the AJAX validation.
* @param CModel the model to be validated
*/
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='column-form')
{
if(isset($_POST['publishtime']) && $_POST['publishtime']){
$model->publishtime = strtotime($_POST['publishtime']);
}
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
public function actionListorder(){
$listorders = $_POST['listorders'];
$connection=Yii::app()->db;
$transaction=$connection->beginTransaction();
$success = true;
$sql="UPDATE ".Column::model()->tableName()." SET listorder=:listorder WHERE id=:id";
$command=$connection->createCommand($sql);
try
{
foreach($listorders as $key=>$value)
{
$command->bindParam(":listorder",$value,PDO::PARAM_INT);
$command->bindParam(":id",$key,PDO::PARAM_INT);
$command->execute();
}
$transaction->commit();
}
catch(Exception $e) // 如果有一条查询失败,则会抛出异常
{
$transaction->rollBack();
$success = FALSE;
}
if($success){
if (Yii::app()->request->isAjaxRequest) {
$this->success(Yii::t('system','Successfully set new order!'));
} else {
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
}
}
else{
if (Yii::app()->getRequest()->isAjaxRequest) {
$result = array();
$result['status'] = 0;
$result['info'] = Yii::t('system','Set new order failed.');
$result['data'] = null;
header('Content-Type:text/html; charset=utf-8');
exit(json_encode($result));
} else {
throw new CHttpException(505, Yii::t('system','Set new order failed.'));
}
}
}
}
| true |
07f8d0f15c3c93a1844fb39b3f256c47e7292e74 | PHP | eliezerfot123/addons_send_email_backend | /index.php | UTF-8 | 2,224 | 2.625 | 3 | [
"Apache-2.0"
] | permissive | <?php
header("Access-Control-Allow-Origin: *");
error_reporting(E_ALL);
ini_set('display_errors', '1');
require_once 'PHPMailer/PHPMailerAutoload.php';
if (isset($_POST['inputName']) && isset($_POST['inputEmail']) && isset($_POST['inputPhone']) && isset($_POST['inputMessage'])) {
//check if any of the inputs are empty
if (empty($_POST['inputName']) || empty($_POST['inputEmail']) || empty($_POST['inputPhone']) || empty($_POST['inputMessage'])) {
$data = array('success' => false, 'message' => 'Por favor complete todos los campos');
echo json_encode($data);
exit;
}
//create an instance of PHPMailer
$mail = new PHPMailer();
// incluimos los datos de conexión
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'usuario@gmail.com'; // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465;
//datos para el envio
$mail->From = $_POST['inputEmail'];
$mail->FromName = $_POST['inputName'];
$mail->AddAddress('usuario@gmail.com'); //recipient
$mail->Subject = "Reporte de Incidentes - Vía addons para firefox";
$mail->Body = "Nombre: " . $_POST['inputName'] . "\r\n\r\nDescripción: " . stripslashes($_POST['inputMessage']). "\r\n\r\nTeléfono: " .$_POST['inputPhone']. "\r\n\r\nCorreo: " .$_POST['inputEmail'];
if (isset($_POST['ref'])) {
$mail->Body .= "\r\n\r\nRef: " . $_POST['ref'];
}
if(!$mail->send()) {
$data = array('success' => false, 'message' => 'Su mensaje no pudo ser enviado. ' . $mail->ErrorInfo);
echo json_encode($data);
exit;
}
$data = array('success' => true, 'message' => 'Muchas gracias. Hemos recibido su mensaje');
echo json_encode($data);
} else {
$data = array('success' => false, 'message' => 'POr favor rellene todos los campos correctamente;
echo json_encode($data);
}
| true |
7afc3c9c1f5180569efb40b9c8502690b3d0992c | PHP | lihaoliangGz/PhpArray | /PhpArray_ar_as.php | UTF-8 | 3,916 | 3.53125 | 4 | [] | 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.
*/
echo "array_rand — 从数组中随机取出一个或多个单元 :" . "\n";
$input = array(1, 2, 3, 4, 5, 6);
$array = array("frist", "second", "three", "four");
$array2 = array("a" => "banana", "b" => "yellow", "c" => "gray", "d" => "blue");
print_r(array_rand($input, 3));
print_r(array_rand($input, 1));
echo "\n";
print_r(array_rand($array, 2));
print_r(array_rand($array, 1));
echo "\n";
print_r(array_rand($array2, 2));
print_r(array_rand($array2, 1));
echo "\n\n";
echo "array_reduce — 用回调函数迭代地将数组简化为单一的值:" . "\n";
function sum($array, $item) {
$array += $item;
return $array;
}
function product($array, $item) {
$array *= $item;
return $array;
}
$a = array(1, 2, 3, 4, 5);
$x=array();
echo array_reduce($a, "sum")."\n";
echo array_reduce($a, "product",1)."\n";//如果不指定第三个参数,开始值为0,乘积0
echo array_reduce($x, "sum","空数组");
echo "array_replace_recursive — 使用传递的数组递归替换第一个数组的元素:"."\n";
$base = array('citrus' => array("orange"), 'berries' => array("blackberry", "raspberry"),);
$replacements = array('citrus' => array('pineapple'), 'berries' => array('blueberry'));
print_r(array_replace_recursive($base, $replacements));
echo "array_replace — 使用传递的数组替换第一个数组的元素:"."\n";
$base = array("orange", "banana", "apple", "raspberry");
$replacements = array(0 => "pineapple", 4 => "cherry");
$replacements2 = array(0 => "grape");
print_r(array_replace($base, $replacements,$replacements2));
echo "array_reverse — 返回单元顺序相反的数组 :"."\n";
$input = array("php", 4.0, array("green", "red"));
print_r(array_reverse($input));
print_r(array_reverse($input,TRUE));
echo "array_search — 在数组中搜索给定的值,如果成功则返回首个相应的键名 :"."\n";
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$array2 = array(0 => '2', 1 => '154', 2 => 654, 3 => 63);
echo var_dump(array_search("green",$array));
echo var_dump(array_search("gray",$array));
echo var_dump(array_search(654, $array2));
echo var_dump(array_search("654", $array2));
echo var_dump(array_search("654", $array2, TRUE))."\n\n";
echo "array_shift — 将数组开头的单元移出数组:"."\n";
$stack = array("orange", "banana", "apple", "raspberry");
$stack2 = array("orange"=>"12", "banana"=>"15", "apple"=>"65", "raspberry"=>"32");
echo array_shift($stack)."\n";
echo array_shift($stack2)."\n";
echo "array_slice — 从数组中取出一段:"."\n";
$input = array("a", "b", "c", "d", "e");
print_r(array_slice($input, 1));;
print_r(array_slice($input, 1,3));;
print_r(array_slice($input, -4,3));;
print_r(array_slice($input, 1,-3,TRUE));;
print_r(array_slice($input, -4,-3));;
print_r(array_slice($input, 5));;
echo "array_splice — 去掉数组中的某一部分并用其它值取代 :"."\n";
$input = array("red", "green", "blue", "yellow");
print_r(array_splice($input, 1));
print_r($input);
echo "---------------------------------------\n";
$input = array("red", "green", "blue", "yellow");
print_r(array_splice($input, 1, count($input),"org"));
print_r($input);
echo "---------------------------------------\n";
$input = array("red", "green", "blue", "yellow");
array_splice($input, -1, 1, array("black", "maroon"));
print_r($input);
echo "---------------------------------------\n";
$input = array("red", "green", "blue", "yellow");
array_splice($input, 3, 0, "purple");
print_r($input);
echo "array_sum — 对数组中所有值求和 :"."\n";
$a = array(2, 4, 6, 8);
echo array_sum($a),"\n";
echo array_sum(array()),"\n";
$b = array("a" => 1.2, "b" => 2.3, "c" => 3.4);
echo array_sum($b), "\n\n";
?>
| true |
ae13ef466d24266c11a60c1da6bd3df72293d14d | PHP | sumitguptamca/test | /admin-common/ldap.php | UTF-8 | 7,273 | 2.6875 | 3 | [] | no_license | <?php
/*
Inroads Control Panel/Shopping Cart - LDAP Authentication Functions
Written 2018-2019 by Randall Severy
Copyright 2018-2019 Inroads, LLC
*/
require_once 'config.php';
define(LDAP_OPT_DIAGNOSTIC_MESSAGE,0x0032);
function get_ldap_error($ldap)
{
if (ldap_get_option($ldap,LDAP_OPT_DIAGNOSTIC_MESSAGE,$error))
return $error;
return null;
}
function get_data_code($error)
{
$start_pos = strpos($error,'data ');
if ($start_pos === false) return null;
$start_pos += 5;
$end_pos = strpos($error,',',$start_pos);
if ($end_pos === false) return null;
return substr($error,$start_pos,$end_pos - $start_pos);
}
function connect_ldap_host(&$error)
{
global $ldap_host;
putenv('LDAPTLS_REQCERT=never');
$url_info = parse_url($ldap_host);
$fp = @fsockopen($url_info['host'],$url_info['port'],$errno,
$error_string,1);
if (! $fp) {
if (! $error_string) {
$last_error = error_get_last();
$error_string = $last_error['message'];
}
$error = 'Unable to connect to LDAP Server: '.$error_string .
' ('.$errno.')';
return null;
}
$ldap = @ldap_connect($ldap_host);
if (! $ldap) {
$error = 'Unable to connect to LDAP Server'; return null;
}
return $ldap;
}
function validate_ldap_user($username,$password,&$error)
{
$ldap = connect_ldap_host($error);
if (! $ldap) return false;
$bind = @ldap_bind($ldap,$username,$password);
if (! $bind) {
$error = get_ldap_error($ldap);
$data_code = get_data_code($error);
if ($data_code == '52e')
$error = 'Invalid LDAP Username/Password for User '.$username;
else $error = 'LDAP Bind Failed = '.$error;
return false;
}
return $ldap;
}
function convert_ldap_date($date)
{
$y = substr($date,0,4);
$m = substr($date,4,2);
$d = substr($date,6,2);
$h = substr($date,8,2);
$i = substr($date,10,2);
$s = substr($date,12,2);
$timestamp = mktime($h,$i,$s,$m,$d,$y);
return $timestamp;
}
function get_ldap_users($ldap,&$error)
{
global $ldap_dn;
$search_filter = '(objectCategory=person)';
$ldap_result = ldap_search($ldap,$ldap_dn,$search_filter);
if (! $ldap_result) {
$error = 'LDAP Search Failed = '.get_ldap_error($ldap);
return null;
}
$entries = ldap_get_entries($ldap,$ldap_result);
$users = array();
foreach ($entries as $index => $entry) {
if (! is_numeric($index)) continue;
$username = $entry['userprincipalname'][0];
$fname = $entry['givenname'][0];
$lname = $entry['sn'][0];
$email = $entry['mail'][0];
$phone = $entry['telephonenumber'][0];
$created = convert_ldap_date($entry['whencreated'][0]);
$modified = convert_ldap_date($entry['whenchanged'][0]);
$users[] = array('username'=>$username,'fname'=>$fname,'lname'=>$lname,
'email'=>$email,'phone'=>$phone,'created'=>$created,
'modified'=>$modified);
}
return $users;
}
function get_ldap_user($ldap,$username,&$error)
{
global $ldap_dn;
$search_filter = '(userprincipalname='.$username.')';
$ldap_result = ldap_search($ldap,$ldap_dn,$search_filter);
if (! $ldap_result) {
$error = 'LDAP Search Failed = '.get_ldap_error($ldap);
return null;
}
$entries = ldap_get_entries($ldap,$ldap_result);
if (! isset($entries[0])) {
$error = 'LDAP User '.$username.' Not Found'; return null;
}
$username = $entries[0]['userprincipalname'][0];
if (isset($entries[0]['givenname'][0]))
$fname = $entries[0]['givenname'][0];
else $fname = '';
if (isset($entries[0]['sn'][0])) $lname = $entries[0]['sn'][0];
else if (isset($entries[0]['name'][0])) $lname = $entries[0]['name'][0];
else $lname = '';
if (isset($entries[0]['mail'][0])) $email = $entries[0]['mail'][0];
else $email = $username;
if (isset($entries[0]['telephonenumber'][0]))
$phone = $entries[0]['telephonenumber'][0];
else $phone = '';
$created = convert_ldap_date($entries[0]['whencreated'][0]);
$modified = convert_ldap_date($entries[0]['whenchanged'][0]);
$user_info = array('username'=>$username,'fname'=>$fname,'lname'=>$lname,
'email'=>$email,'phone'=>$phone,'created'=>$created,
'modified'=>$modified);
return $user_info;
}
function lookup_ldap_user($username,$password)
{
global $user_pref_names,$ldap_user_info;
require_once 'adminusers-common.php';
$username = trim($username); $password = trim($password);
$ldap = validate_ldap_user($username,$password,$error);
if (! $ldap) {
log_error($error); return null;
}
$user_info = get_ldap_user($ldap,$username,$error);
if (! $user_info) {
log_error($error); return null;
}
$db = new DB;
$query = 'select * from users where username="default"';
$default_info = $db->get_record($query);
if (! $default_info) {
log_error('Default User not found'); return null;
}
$query = 'select * from user_prefs where username="default"';
$default_prefs = $db->get_records($query,'pref_name','pref_value');
if (! $default_prefs) {
log_error('Default User Preferences not found'); return null;
}
$user_record = user_record_definition();
$user_record['username']['value'] = $username;
$user_record['password']['value'] = $password;
$user_record['firstname']['value'] = $user_info['fname'];
$user_record['lastname']['value'] = $user_info['lname'];
$user_record['email']['value'] = $user_info['email'];
$user_record['office_phone']['value'] = $user_info['phone'];
$user_record['perms']['value'] = $default_info['perms'];
$user_record['module_perms']['value'] = $default_info['module_perms'];
$user_record['custom_perms']['value'] = $default_info['custom_perms'];
$user_record['creation_date']['value'] = $user_info['created'];
$user_record['modified_date']['value'] = $user_info['modified'];
if (! empty($ldap_user_info)) {
foreach ($ldap_user_info as $field_name => $field_value)
$user_record[$field_name]['value'] = $field_value;
}
if (function_exists('custom_update_user')) {
if (! custom_update_user($db,$user_record,ADDRECORD)) return null;
}
require_once '../engine/modules.php';
if (module_attached('add_user')) {
$user_info = $db->convert_record_to_array($user_record);
if (! call_module_event('add_user',array($db,$user_info))) {
call_module_event('delete_user',array($db,$user_info));
log_error(get_module_errors()); return null;
}
}
if (! $db->insert('users',$user_record)) return null;
$error_msg = null;
if (! save_user_prefs($db,$user_record,ADDRECORD,$error_msg,
$default_prefs)) {
log_error($error_msg); return null;
}
if (function_exists('custom_save_user')) {
if (! custom_save_user($db,$user_record,ADDRECORD)) return null;
}
log_activity('Added LDAP User '.$username);
return $user_info;
}
?>
| true |
eb08135eb8867eb9d786efa43182316368fb7456 | PHP | Avaaren/minsk_attractions | /backend/api/authApi.php | UTF-8 | 1,839 | 2.734375 | 3 | [] | no_license | <?php
require_once 'baseApi.php';
require_once($_SERVER['DOCUMENT_ROOT'].'/services/db_layer/db_query_builder.php');
require_once($_SERVER['DOCUMENT_ROOT'].'/services/auth/login.php');
require_once($_SERVER['DOCUMENT_ROOT'].'/services/auth/registration.php');
require_once($_SERVER['DOCUMENT_ROOT'].'/services/auth/AuthClass.php');
class authApi extends baseApi
{
public $apiName = 'auth';
public $urlTemplates = [
'login' => 'loginHandler',
'logout' => 'logoutHandler',
'registration' => 'registrationHandler',
];
/**
* Метод POST
* http://ДОМЕН/auth/login/
* @return string
*/
public function loginHandler()
{
if ($this->method === "POST"){
$log = new Login();
$isSuccess = $log->loginRequestHandler();
return $this->response(['errors' => $log->errors, 'success' => $isSuccess], 200);
}
return $this->response('Wrong method', 405);
}
/**
* Метод POST
* http://ДОМЕН/auth/logout/
* @return string
*/
public function logoutHandler()
{
if (Auth\AuthClass::isAuthorized()){
unset($_SESSION['is_auth']);
unset($_SESSION['username']);
return $this->response(['success' => $true], 200);
}
return $this->response('Not authorized', 404);
}
/**
* Метод POST
* http://ДОМЕН/auth/registration/
* @return string
*/
public function registrationHandler()
{
if ($this->method === "POST"){
$reg = new Registration();
$isSuccess = $reg->registrationRequestHandler();
return $this->response(['errors' => $reg->errors, 'success' => $isSuccess], 200);
}
return $this->response('Wrong method', 405);
}
} | true |
8c97b85ae0a9743b2644519d1176db25038960ff | PHP | Aleksandr0611/work | /task_6.php | UTF-8 | 422 | 3.03125 | 3 | [] | no_license | <?php
declare(strict_types=1);
$cities = ['moscow', 'london', 'berlin', 'porto'];
/**
* @param array $a
* @param int $b
* @param null $c
*/
function get(array $a, int $b, $c = null)
{
if (($a[$b] == false) && ($c == null)) {
$a[$b] = $c;
echo $a[$b] = $c;
} elseif ($a[$b] == false) {
$a[$b] = $c;
echo $a[$b] = $c;
} else {
echo $a[$b];
}
}
get($cities, 1); | true |
87bce8eddc43b1bd9bbcef046b7b668a72199651 | PHP | pcardona34/exercices_divers | /troisieme/homophones_32/scores.php | UTF-8 | 2,188 | 2.75 | 3 | [] | no_license | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Scores</title>
<link rel="stylesheet" href="style.css">
<script>
// Page affichée pour le mode évaluation 1
ch=[];
note=[];
// Fonctions appelées par le fichier "textes.js"
function titre() {}
function bouton() {}
function fenetre() {}
function mot() {}
function score(a) { ch[ch.length]=a; }
// Valeur de la note
function valeur(n) {
if (n.charAt(0)=="-") return -1;
else return eval(n);
}
<?php
// Récupération et enregistrement du score dans le fichier "scores.txt"
if (isset($_GET['enr'])) {
$score=$_GET['enr'];
if (strlen($score)!=0) {
$fichier=fopen("scores.txt","a+");
$entree=$score."\n";
fputs($fichier,$entree);
fclose($fichier);
}
}
// Lecture du fichier "scores.txt" et création du tableau à deux entrées $note[$i][$j]
$ligne=file("scores.txt");
$note=array();
$verif=array();
$ind=0;
for($i=0; $i<count($ligne); $i++) {
$verif[$i]=split("§", $ligne[$i]);
if (count($verif[$i])==5) {
$note[$ind]=split("§", $ligne[$i]);
$note[$ind][4]=rtrim($note[$ind][4]);
$ind++;
}
}
// Conversion du tableau PHP en tableau JS
for ($i=0; $i<count($note); $i++) {
echo "note[".$i."]=[];\n";
for ($j=0;$j<5;$j++) { echo "note[".$i."][".$j."]='".$note[$i][$j]."';\n"; }
}
?>
// Ordonnancement du tableau à deux entrées note[i][j] selon les notes obtenues
for (i=0; i<note.length; i++) {
var sauv=[];
var max=i;
for (var j=i; j<note.length; j++) { if (valeur(note[j][4])>valeur(note[max][4])) max=j; }
if (max!=i) {
for (var k=0; k<5; k++) {
sauv[k]=note[i][k];
note[i][k]=note[max][k];
note[max][k]=sauv[k];
}
}
}
onload=function() {
var i,j, txt='<table>';
txt+='<tr><th>'+ch[0]+'</th><th>'+ch[1]+'</th><th>'+ch[2]+'</th><th>'+ch[3]+'</th><th>'+ch[4]+'</th></tr>';
for (i=0; i<note.length; i++) {
txt+='<tr>';
for (j=0; j<5; j++) { txt+='<td>'+note[i][j]+'</td>'; }
txt+='</tr>';
}
txt+='</table><div id="menu"><button type="button" onclick="effacer();">'+ch[6]+'</button>';
txt+='<button type="button" onclick="self.close();">'+ch[5]+'</button></div>';
document.body.innerHTML=txt;
};
</script>
<script src="textes.js"></script>
</head>
<body></body>
</html>
| true |
bdd3e6751292ca8b9287cb5ac9b40dfc8714a813 | PHP | bakicdj/EmailReplyExtractor | /src/ActiveCollab/EmailReplyExtractor/Extractor/OutlookExtractor.php | UTF-8 | 682 | 2.765625 | 3 | [
"MIT"
] | permissive | <?php
namespace ActiveCollab\EmailReplyExtractor\Extractor;
/**
* @package ActiveCollab\EmailReplyExtractor\Extractor
*/
final class OutlookExtractor extends Extractor
{
/**
* @param string $html
*
* @return string
*/
static function toPlainText($html)
{
$html = str_replace('div', 'p', $html);
return parent::toPlainText($html);
}
/**
* Return original message splitters
*
* @todo
* @return array
*/
protected function getOriginalMessageSplitters()
{
return array_merge(parent::getOriginalMessageSplitters(), [
'/\-------------------------/is',
]);
}
} | true |
40c4973e7c8ea9e6d1b99013dd4b5d207530915a | PHP | IsmaelBIT/My-first-class-e527375b | /MyLogger.class.php | UTF-8 | 141 | 3.375 | 3 | [] | no_license | <?php
class MyLogger
{
public function log($message) {
echo $message;
}
}
$logger = new MyLogger();
$logger->log('Hey! :)'); | true |
bb9846e0acb4e2e45516f77c35e4eb5db4fb6ce9 | PHP | xpmozong/wavephp2 | /framework/cache/WaveRedisCluster.php | UTF-8 | 11,929 | 2.96875 | 3 | [] | no_license | <?php
/**
* PHP 5.0 以上
*
* @package Wavephp
* @author 许萍
* @copyright Copyright (c) 2016
* @link https://github.com/xpmozong/wavephp2
* @since Version 2.0
*
*/
/**
* Wavephp Application RedisCluster Class
*
* Redis 操作,支持 Master/Slave 的负载集群
*
* @package Wavephp
* @subpackage cache
* @author 许萍
*
*/
class WaveRedisCluster
{
// 是否使用 M/S 的读写集群方案
private $_isUseCluster = false;
// Slave 句柄标记
private $_sn = 0;
// 服务器连接句柄
private $_linkHandle = array(
'master'=>null,// 只支持一台 Master
'slave'=>array(),// 可以有多台 Slave
);
/**
* 构造函数
*
* @param boolean $isUseCluster 是否采用 M/S 方案
*
*/
public function __construct($isUseCluster = false)
{
$this->_isUseCluster = $isUseCluster;
}
/**
* 连接服务器,注意:这里使用长连接,提高效率,但不会自动关闭
*
* @param array $config Redis服务器配置
* @param boolean $isMaster 当前添加的服务器是否为 Master 服务器
* @param int $db 数据库
* @return boolean
*
*/
public function connect($config, $isMaster = true, $db = 0)
{
// default port
if (!isset($config['port'])) {
$config['port'] = 6379;
}
// 设置 Master 连接
if ($isMaster) {
$this->_linkHandle['master'] = new Redis();
$ret = $this->_linkHandle['master']
->connect($config['host'],$config['port'], 3);
if ($ret && $db) {
$this->_linkHandle['master']->select($db);
}
} else {
// 多个 Slave 连接
$this->_linkHandle['slave'][$this->_sn] = new Redis();
$ret = $this->_linkHandle['slave'][$this->_sn]
->connect($config['host'],$config['port'], 3);
if ($ret && $db) {
$this->_linkHandle['slave'][$this->_sn]->select($db);
}
++$this->_sn;
}
return $ret;
}
/**
* 关闭连接
*
* @param int $flag 关闭选择 0:关闭 Master 1:关闭 Slave 2:关闭所有
* @return boolean
*
*/
public function close($flag = 2)
{
switch ($flag) {
// 关闭 Master
case 0:
$this->getRedis()->close();
break;
// 关闭 Slave
case 1:
for ($i = 0; $i < $this->_sn; ++$i) {
$this->_linkHandle['slave'][$i]->close();
}
break;
// 关闭所有
case 2:
$this->getRedis()->close();
for ($i = 0 ; $i < $this->_sn; ++$i) {
$this->_linkHandle['slave'][$i]->close();
}
break;
}
return true;
}
/**
* 得到 Redis 原始对象可以有更多的操作
*
* @param boolean $isMaster 返回服务器的类型 true:返回Master false:返回Slave
* @return redis object
*
*/
public function getRedis($isMaster = true)
{
if ($isMaster) {
return $this->_linkHandle['master'];
} else {
if ($this->_isUseCluster) {
return $this->_getSlaveRedis();
} else {
return $this->_linkHandle['master'];
}
}
}
/**
* 写缓存
*
* @param string $key 组存KEY
* @param string $value 缓存值
* @param int $expire 过期时间, 0:表示无过期时间
*
*/
public function set($key, $value, $expire = 0)
{
// 永不超时
if ($expire == 0) {
$ret = $this->getRedis()->set($key, $value);
} else {
$ret = $this->getRedis()->setex($key, $expire, $value);
}
return $ret;
}
/**
* 读缓存
*
* @param string $key 缓存KEY,支持一次取多个 $key = array('key1','key2')
* @return string || boolean 失败返回 false, 成功返回字符串
*
*/
public function get($key)
{
// 是否一次取多个值
$func = is_array($key) ? 'mGet' : 'get';
return $this->getRedis(false)->{$func}($key);
}
/**
* 删除缓存
*
* @param string || array $key 缓存KEY,支持单个健:"key1" 或多个健:array('key1','key2')
* @return int 删除的健的数量
*
*/
public function delete($key)
{
// $key => "key1" || array('key1','key2')
return $this->getRedis()->delete($key);
}
/**
* 值加加操作,类似 ++$i ,如果 key 不存在时自动设置为 0 后进行加加操作
*
* @param string $key 缓存KEY
* @param int $default 操作时的默认值
* @return int 操作后的值
*
*/
public function incr($key, $default = 1)
{
if ($default == 1) {
return $this->getRedis()->incr($key);
} else {
return $this->getRedis()->incrBy($key, $default);
}
}
/**
* 值减减操作,类似 --$i ,如果 key 不存在时自动设置为 0 后进行减减操作
*
* @param string $key 缓存KEY
* @param int $default 操作时的默认值
* @return int 操作后的值
*
*/
public function decr($key, $default = 1)
{
if ($default == 1) {
return $this->getRedis()->decr($key);
} else {
return $this->getRedis()->decrBy($key, $default);
}
}
/**
* 插入一个值到列表中,如果列表不存在,新建一个列表
* @param string $key
* @param string $value
*
*/
public function lpush($key, $value)
{
return $this->getRedis()->lPush($key, $value);
}
/**
* 删除列表的第一个值并返回它
*
* @param string $key
* @return string
*
*/
public function lpop($key)
{
return $this->getRedis()->lPop($key);
}
/**
* 删除列表的某个值
*/
public function lrem($key, $value, $count)
{
return $this->getRedis()->lRem($key, $value, $count);
}
/**
* 插入一个值到列表中,如果列表不存在,新建一个列表
*
* @param string $key
* @param string $value
* @return boolean
*
*/
public function rpush($key, $value)
{
return $this->getRedis()->rPush($key, $value);
}
/**
* 删除并返回列表的最后一个值
*
* @param string $key
* @return string
*
*/
public function rpop($key)
{
return $this->getRedis()->rPop($key);
}
/**
* 从列表中返回指定位置的值
*
* @param string $key
* @param int $index
* @return string
*
*/
public function lget($key, $index = 0)
{
$func = 'lGet';
return $this->getRedis(false)->{$func}($key, $index);
}
/**
* 获得列表的长度
*
* @param string $key
* @return int
*
*/
public function llen($key)
{
$func = 'lLen';
return $this->getRedis(false)->{$func}($key);
}
/**
* 成员添加
*
* @param string $key
* @param string $value
* @return boolean
*
*/
public function sadd($key, $value)
{
return $this->getRedis()->sAdd($key, $value);
}
/**
* 成员列表
*
* @param string $key
* @return array
*
*/
public function smembers($key)
{
$func = 'sMembers';
return $this->getRedis(false)->{$func}($key);
}
/**
* 移除成员
*
* @param string $key
* @param string $value
* @return boolean
*
*/
public function sremove($key, $value)
{
return $this->getRedis()->sRemove($key, $value);
}
/**
* 添空当前数据库
*
* @return boolean
*
*/
public function clear()
{
return $this->getRedis()->flushDB();
}
/* =================== 哈希操作 ========================*/
/**
* 将key->value写入hash表中
*
* @param $hash string 哈希表名
* @param $data array 要写入的数据 array('key'=>'value')
* @return boolean
*
*/
public function hashSet($hash, $key, $data)
{
$return = null;
if (is_array($data) && !empty($data)) {
$return = $this->getRedis()->hSet($hash, $key, $data);
}
return $return;
}
/**
* 获取hash表的数据
*
* @param $hash string 哈希表名
* @param $key mixed 表中要存储的key名 默认为null 返回所有key>value
* @param $type int 要获取的数据类型 0:返回所有key 1:返回所有value 2:返回所有key->value
* @return array
*
*/
public function hashGet($hash, $key = array(), $type = 0)
{
$return = null;
if (!empty($key)) {
if (is_array($key)) {
$func = 'hMGet';
} else {
$func = 'hGet';
}
$return = $this->getRedis(false)->{$func}($hash, $key);
} else {
switch ($type) {
case 0:
$func = 'hKeys';
break;
case 1:
$func = 'hVals';
break;
case 2:
$func = 'hGetAll';
break;
default:
$return = false;
break;
}
$return = $this->getRedis(false)->{$func}($hash);
}
return $return;
}
/**
* 获取hash表中元素个数
*
* @param $hash string 哈希表名
*
*/
public function hashLen($hash)
{
$return = null;
$func = 'hLen';
$return = $this->getRedis(false)->{$func}($hash);
return $return;
}
/**
* 删除hash表中的key
*
* @param $hash string 哈希表名
* @param $key mixed 表中存储的key名
*
*/
public function hashDel($hash, $key)
{
return $this->getRedis()->hDel($hash, $key);
}
/**
* 查询hash表中某个key是否存在
*
* @param $hash string 哈希表名
* @param $key mixed 表中存储的key名
*
*/
public function hashExists($hash, $key)
{
$return = null;
$func = 'hExists';
$return = $this->getRedis(false)->{$func}($hash, $key);
return $return;
}
/* =================== 以下私有方法 =================== */
/**
* 随机 HASH 得到 Redis Slave 服务器句柄
*
* @return redis object
*
*/
private function _getSlaveRedis()
{
// 就一台 Slave 机直接返回
if ($this->_sn <= 1) {
return $this->_linkHandle['slave'][0];
}
// 随机 Hash 得到 Slave 的句柄
$hash = $this->_hashId(mt_rand(), $this->_sn);
return $this->_linkHandle['slave'][$hash];
}
/**
* 根据ID得到 hash 后 0~m-1 之间的值
*
* @param string $id
* @param int $m
* @return int
*
*/
private function _hashId($id, $m=10)
{
//把字符串K转换为 0~m-1 之间的一个值作为对应记录的散列地址
$k = md5($id);
$l = strlen($k);
$b = bin2hex($k);
$h = 0;
for ($i = 0; $i < $l; $i++) {
//相加模式HASH
$h += substr($b, $i*2, 2);
}
$hash = ($h * 1) % $m;
return $hash;
}
}
?>
| true |
351078ebf56781b214d8f6db8fa1970669db813a | PHP | KatterinaM/experience-work | /dataprocessor/src/app/Entity/Entity/Cian/Traits/ShareAmount.php | UTF-8 | 2,176 | 2.65625 | 3 | [] | no_license | <?php
namespace App\Entity\Cian\Traits;
use App\Entity\Cian\Base\AbstractObject;
use App\Entity\Cian\Base\CategoryInterface;
use JMS\Serializer\Annotation as Serializer;
use Symfony\Component\Validator\Constraints;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
/**
* Trait ShareAmount
* @package App\Entity\Cian\Traits
*/
trait ShareAmount
{
/**
* @var string
* @Serializer\SerializedName("ShareAmount")
* @Serializer\XmlElement(cdata=false)
* @Serializer\SkipWhenEmpty
* @Constraints\Callback({ "App\Entity\Cian\Traits\ShareAmount", "validateShareAmount" })
*/
private $shareAmount;
/**
* @return string
*/
public function getShareAmount(): string
{
return $this->shareAmount;
}
/**
* @param string $shareAmount
*/
public function setShareAmount(string $shareAmount): void
{
$this->shareAmount = $shareAmount;
}
/**
* @param $shareAmount
* @param ExecutionContextInterface $context
* @param $payload
*/
public static function validateShareAmount(
$shareAmount,
ExecutionContextInterface $context,
/** @noinspection PhpUnusedParameterInspection */
$payload
) {
/** @var AbstractObject $object */
$object = $context->getObject();
if ((is_null($shareAmount) && in_array($object->getCategory(), [
CategoryInterface::COUNTRY_CATEGORY_HOUSE_SHARE_RENT,
CategoryInterface::COUNTRY_CATEGORY_HOUSE_SHARE_SALE
]))
|| (!is_null($shareAmount) && !in_array($object->getCategory(), [
CategoryInterface::CITY_CATEGORY_FLAT_SHARE_SALE,
CategoryInterface::COUNTRY_CATEGORY_HOUSE_SHARE_RENT,
CategoryInterface::COUNTRY_CATEGORY_HOUSE_SHARE_SALE
]))
) {
$context->buildViolation(
'Данное поле заполняется только для категорий:'
. '"Часть дома", "Доля в квартире"'
)->addViolation();
}
}
} | true |
045d0a62e9b42827ae8574467839c04bd7d86cbd | PHP | tbajorek/doctrine-file-fixtures | /src/Model/Entity/FieldNameResolver.php | UTF-8 | 1,092 | 2.546875 | 3 | [
"MIT"
] | permissive | <?php
namespace Tbajorek\DoctrineFileFixturesBundle\Model\Entity;
use Tbajorek\DoctrineFileFixturesBundle\Model\Config\BundleConfig;
use Tbajorek\DoctrineFileFixturesBundle\Model\Config\Metadata\FieldInterface;
use Tbajorek\DoctrineFileFixturesBundle\Model\FixturesException;
class FieldNameResolver
{
/**
* @var BundleConfig
*/
private $bundleConfig;
public function __construct(BundleConfig $bundleConfig)
{
$this->bundleConfig = $bundleConfig;
}
/**
* @param FieldInterface $field
* @return string
* @throws FixturesException
*/
public function resolveFileColumn(FieldInterface $field): string
{
$namesType = $this->bundleConfig->getNamesType();
switch ($namesType) {
case BundleConfig::NAMES_TYPE_COLUMN:
return $field->getColumnName();
case BundleConfig::NAMES_TYPE_FIELD:
return $field->getFieldName();
default:
throw new FixturesException("Wrong value in config for source name type is set");
}
}
} | true |
ea2d71ba04725e4914912e0a1a4aef9743abfa08 | PHP | vomoir/rubricon | /rubric_get_list.php | UTF-8 | 1,165 | 2.546875 | 3 | [
"MIT"
] | permissive | <?PHP
require_once("dbconnector.php");
//require_once("check_session.php");
error_log("In project_get_list.php\nChecking Session...");
if(!isset($_POST['submit'])){
/*
if (!checkSession()){
error_log("Session Time out.");
echo "error: Session has timed out. Please login again...";
return false;
exit;
} else {
GetProjectsList();
}
*/
GetRubricsList();
}
function GetRubricsList(){
/*
if($_SESSION['admin'] == "false"){
error_log("In project_get_list.php: NOT and admin!");
echo "error: not authorised.";
return false;
}
*/
$project_id = $_GET['project_id'];
$task_id = $_GET['task_id'];
//Return metadata about the columns in each table for a given database (table_schema)
$qry = "SELECT id, p_name, p_details FROM tb_projects order by id";
$dbConn = opendatabase();
$result = mysqli_query($dbConn, $qry);
if(!$result || mysqli_num_rows($result) <= 0){
echo("Could not obtain metadata information.");
return false;
}
$options = "";
while($row = mysqli_fetch_array($result)) {
$options .= "<option value='" . $row['id'] . "'>";
$options .= $row['p_name'] . "</option>";
}
echo $options;
//return $options;
}
?> | true |
93180ba88e6d123cd43ceb7d6e49c527e8e3896b | PHP | Jonesyei/modelphp | /includes/project/member.php | UTF-8 | 3,997 | 2.5625 | 3 | [] | no_license | <?php
include_once("../main_inc.php");
/*
$member["id"] = X; //--會員資料 參數
$member["other_account"] = 'x'; //其他榜定欄位 名稱
$member["other_type"] = 'x'; //其他榜定帳戶類型 欄位名稱
$member["data"] = $_SESSION["member_info"]["login"]; //登入資料源
$member["file_url"] = 'upload/'; //檔案上傳目錄
*/
$member["data"] = $_SESSION["member_info"]["login"];
if ($member["table"]==NULL) $member["table"] = PREFIX.'member';
if ($member["id"]==NULL) $member["id"] = $_GET["id"];
if ($member["file_url"]==NULL) $member["file_url"] = 'upload/';
if ($_GET && !$_POST){
///----使用id拉資料
if ($_GET["id"]!=NULL){
if ($member["data"]["id"]!=NULL && $member["data"]["id"]==$_GET["id"]){
$sql = "select * from ".$member["table"]." where id=".$member["id"];
$data["one"] = $conn->GetRow($sql);
}else{
//--本身沒有ID資料卻拉ID資料 表示來源不合法
linkto(-1);
}
}
//---使用帳戶登入
if ($_GET["account"]!=NULL){
$sql = "select * from ".$member["table"]." where account='".strtolower(quotes($_GET["account"]))."' and password='".md5($_GET["password"])."'";
$data["one"] = $conn->GetRow($sql);
}
//---使用綁定登入方式
if ($_GET["other_account"]!=NULL){
$sql = "select * from ".$member["table"]." where ".$member["other_account"]."='".quotes($_GET["other_account"])."' and ".$member["other_type"]."='".$_GET["other_type"]."'";
$data["one"] = $conn->GetRow($sql);
}
//---使用email登入方式
if ($_GET["email"]!=NULL){
$sql = "select * from ".$member["table"]." where email='".quotes($_GET["email"])."' and password='".md5($_GET["password"])."'";
$data["one"] = $conn->GetRow($sql);
}
if ($data["one"]){
$member_data = $data["one"];
$_SESSION["member_info"]["login"] = $data["one"];
if ($_GET["ajax"]!=NULL){
echo json_encode($data["one"]);
exit;
}else{
linkto(-1); //反回;
}
}else{
//---無資料處理方式
linkto(-1); //反回;
}
}
if ($_POST){
//---------檔案上傳 直接一起寫入post
foreach ($_FILES as $k=>$v){
if (is_array($_FILES[$k]["name"])){ //---判斷為陣列名稱相同物件上傳
foreach ($_FILES[$k]["name"] as $n1=>$n2){
$temp_file_name = explode('.',$n2);
$temp_file_name = strtotime(date('Y-m-d H:i:s')).$k.rand(10,99).'.'.$temp_file_name[count($temp_file_name)-1];
move_uploaded_file($_FILES[$k]["tmp_name"][$n1],$member["file_url"].$temp_file_name);
$_POST[$k][] = $temp_file_name;
}
}else{
$temp_file_name = explode('.',$_FILES[$k]["name"]);
$temp_file_name = strtotime(date('Y-m-d H:i:s')).$k.rand(10,99).'.'.$temp_file_name[count($temp_file_name)-1];
move_uploaded_file($_FILES[$k]["tmp_name"],$member["file_url"].$temp_file_name);
$_POST[$k] = $temp_file_name;
}
}
//----判斷陣列資料組合字串
foreach ($_POST as $k=>$v){
if (is_array($_POST[$k])){
$_POST[$k] = implode("|__|",$_POST[$k]);
}
}
//---判斷有否 account 值,否者表示更新,有者表示帳戶註冊
if ($_POST["account"]==NULL || $_POST["account"]==''){
if ($member["data"]["id"]!=NULL){
$are = $_POST;
if ($_POST["password"]==''||$_POST["password"]==NULL) unset($are["password"]); else $are["password"] = md5($_POST["password"]);
$ar = $conn->AutoExecute($member["table"], $are, "UPDATE","id=".$member["data"]["id"]);
}else{
alert('請確認您是否為登入狀態',-1);
}
}else{
$sql = "select * from ".$member["table"]." where account='".quotes(strtolower($_POST["account"]))."' or email='".quotes($_POST["email"])."'";
$member_create = $conn->GetRow($sql);
if ($member_create){
if ($member_create["account"] == quotes(strtolower($_POST["account"]))){
alert('該帳戶已申請過了',-1);
}else{
alert('信箱資料重複',-1);
}
}else{
$are = $_POST;
$are["account"] = strtolower($_POST["account"]);
$are["password"] = md5($_POST["password"]);
$ar = $conn->AutoExecute($member["table"], $are, "INSERT");
}
}
}
?> | true |
fdf81b556f209f7b34832d60f1a86d82434338b7 | PHP | kweku360/rotaapi | /templates/clubs/index.php | UTF-8 | 1,278 | 2.546875 | 3 | [] | no_license | <?php
/**
* User: kweku
* Date: 9/18/2016
* Time: 4:42 PM
*/
error_reporting(-1); // reports all errors
ini_set("display_errors", "1"); // shows all errors
ini_set("log_errors", 1);
ini_set("error_log", "/tmp/php-error.log");
// setup the autoloading
//require_once 'vendor/autoload.php';
// setup Propel
require_once 'config/config.php';
$resultArray = Array();
//means we can add new suit
$newDefendant = new Clubinfo();
try{$newDefendant->setClubname("moses");}catch (Exception $x){}
try{$newDefendant->setPresident("moses");}catch (Exception $x){}
try{$newDefendant->setCountry("moses");}catch (Exception $x){}
try{$newDefendant->setCity("moses");}catch (Exception $x){}
try{$newDefendant->setDistrict("moses");}catch (Exception $x){}
try{$newDefendant->setContact1(34);}catch (Exception $x){}
try{$newDefendant->setSponsor("moses");}catch (Exception $x){}
try{$newDefendant->setCountrycode("moses");}catch (Exception $x){}
try{$newDefendant->setCreated(time());}catch (Exception $x){}
try{$newDefendant->setModified(time());}catch (Exception $x){}
$newDefendant->save();
$item = Array();
$item["message"] = "Save Successfull";
$resultArray["meta"] = $item;
echo json_encode($resultArray,JSON_PRETTY_PRINT);
//echo json_encode($resultArray,JSON_PRETTY_PRINT);
| true |
0f23ffada9008f3f16943763504f6def231063c7 | PHP | gongasvic/Naval-Territory-Devision | /inscrever.php | UTF-8 | 1,326 | 2.734375 | 3 | [] | no_license | <?php
// inicia sessão para passar variaveis entre ficheiros php
session_start();
include('comum.php');
// Carregamento das variáveis username e pin do form HTML através do metodo POST;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$lid = test_input($_POST["lid"]);
}
if(!isset($_SESSION['validado']) || $_SESSION['validado'] == False) {
echo("Utilizador não logado! Dentro de 3 sec irá para a página de login.");
header("refresh:3;url=login.php");
} else {
if(isset($lid)) {
// Conexão à BD
include('ligacao.php');
$username = $_SESSION['username'];
$nif = $_SESSION['nif'];
//regista a pessoa no leilão. Exemplificativo apenas.....
$sql = "INSERT INTO concorrente (pessoa,leilao) VALUES ($nif,$lid)";
$result = $connection->query($sql);
if (!$result) {
echo("<p> Pessoa nao registada: Erro na Query:($sql) <p>");
header("refresh:3;url=inscrever.php");
exit();
}
echo("<p> Pessoa ($username), nif ($nif) Registada no leilao ($lid)</p>\n");
header("refresh:3;url=listar.php");
} else {
?>
<form action="" method="post">
<h2>Escolha o ID do leilão que pretende concorrer</h2>
<p>ID : <input type="text" name="lid" /></p>
<p><input type="submit" /></p>
</form>
<?php
}
//termina a ligacao
$connection = null;
}
?> | true |
74e38986ff35d5760f276c0a51c442030a5ced2f | PHP | Mariana730/MarbeUrban | /modelo/FormaPagamentoModelo.php | UTF-8 | 1,665 | 2.8125 | 3 | [] | no_license | <?php
function adicionarPagamento ($descricao) {
$sql = "INSERT INTO FormaPagamento (descricao) VALUES ('$descricao')";
$resultado = mysqli_query ($cnx = conn(), $sql);
if(!$resultado) { die('Erro ao cadastrar forma de pagamento'.mysqli_error($cnx));}
return 'Forma de Pagamento cadastrada com sucesso! <br> <a href="./FormaPagamento/adicionar/" class="btn btn-primary">Voltar</a>';
}
function pegarTodosPagamentos (){
$sql = "SELECT * FROM FormaPagamento";
$resultado = mysqli_query(conn(), $sql);
$pagamentos = array();
while ($linha = mysqli_fetch_assoc($resultado)){
$pagamentos[] = $linha;
}
return $pagamentos;
}
function pegarPagamentoPorId ($idFormaPagamento) {
$sql = "SELECT * FROM FormaPagamento WHERE idFormaPagamento = $idFormaPagamento";
$resultado = mysqli_query(conn(), $sql);
$pagamentos = mysqli_fetch_assoc($resultado);
return $pagamentos;
}
function deletarPagamento ($idFormaPagamento) {
$sql = "DELETE FROM FormaPagamento WHERE idFormaPagamento = $idFormaPagamento";
$resultado = mysqli_query($cnx = conn(), $sql);
if (!$resultado) {
die ('Erro ao deletar forma de pagamento' . mysqli_error($cnx));
}
return 'Forma de Pagamento deletada com sucesso!';
}
function editarPagamento ($idFormaPagamento, $descricao){
$sql = "UPDATE FormaPagamento SET descricao = '$descricao' WHERE idFormaPagamento = '$idFormaPagamento'";
$resultado = mysqli_query($cnx = conn(), $sql);
if (!$resultado) {
die ('Erro ao alterar forma de pagamento' . mysqli_error($cnx));
}
return 'Forma de pagamento alterada com sucesso!';
}
| true |
6e78a45e5f0f59515c3cc069c44b6ab8ad01ea5f | PHP | xqmsg/phpsdk-core | /src/com/xqmsg/sdk/v2/services/Exchange.php | UTF-8 | 2,176 | 2.65625 | 3 | [] | no_license | <?php namespace com\xqmsg\sdk\v2\services;
use com\xqmsg\sdk\v2\exceptions\StatusCodeException;
use Config;
use com\xqmsg\sdk\v2\enums\CallMethod;
use com\xqmsg\sdk\v2\ServerResponse;
use com\xqmsg\sdk\v2\XQModule;
use com\xqmsg\sdk\v2\XQSDK;
/**
* Class Exchange
* @package com\xqmsg\sdk\v2\services
*/
class Exchange extends XQModule {
public const FOR_DEFAULT = "xq";
public const FOR_DASHBOARD = "dashboard";
public const REQUEST = 'request';
public const REQUIRED = array( self::REQUEST );
/**
* @param XQSDK $sdk
* @return static
*/
public static function with(XQSDK $sdk) : self {
return new self($sdk);
}
/**
* @inheritDoc
*/
public function name(): string
{
return "exchange";
}
/**
* @inheritDoc
*/
public function run( array $args = [ self::REQUEST => self::FOR_DEFAULT ] ): ServerResponse
{
$this->validateInput( $args, self::REQUIRED );
$cache = $this->sdk()->getCache();
// Ensure that there is an active profile.
$activeProfile = $cache->getActiveProfile( true );
if ( $args[self::REQUEST] === self::FOR_DASHBOARD ) {
$authorization = $cache->getXQAccess($activeProfile);
}
else {
$authorization = $cache->getXQPreauth($activeProfile);
}
if (!$authorization || empty($authorization)) {
throw new StatusCodeException("No authorization token available" );
}
$response = $this->sdk()->call(
Config::SubscriptionHost(),
$this->name(), $args,
'',
CallMethod::Get,
Config::ApiKey(), $authorization , $args['_lang'] ?? Config::DEFAULT_LANGUAGE
);
if ($response->succeeded()) {
if ( $args[self::REQUEST] === self::FOR_DASHBOARD ) {
$cache->addDashboardAccess( $activeProfile, $response->raw() );
}
else {
$cache->addXQAccess( $activeProfile, $response->raw());
$cache->clearXQPreauth($activeProfile);
}
}
return $response;
}
} | true |
0c3629c6c222b59b2d08b5f02547eec03107b178 | PHP | JLdevprog/RPG_object | /object.php | UTF-8 | 6,320 | 3.125 | 3 | [] | no_license | <?php
/*
Imaginons un jeu de rôle.
Il existe plusieurs type de personnages : les Humains les Orques et les Elfes.
Chaque personnage possède :
> Un nom
> Des points de vie (par défaut 100)
> Des points d'attaque (par défaut 10)
> Des points de défense (par défaut 5)
> Un cri de guerre (par exemple "A l'attaqqquuue !")
Chaque type de personnage possède des caractéristiques particulières :
> Les Humains ont un bonus de +1 sur tous type d'arme.
> Les Orques ont +2 en attaque et défense mais -10 de vie.
Ils commencent donc avec 90 PV, 12 Atk et 7 dfs.
> Les Elfes ont -3 en défense. Ils commencent donc avec 2 de défense.
Les Elfes peuvent fuir n'importe quel combat en sacrifiant 20 point de vie.
Quand un Elfe gagne un combat, il gagne 2 de défense et de 2 de vie.
-- Première étape :
Créer une classe Personnage.
Cette classe implémentera tous les attributs et méthodes communes aux personnages.
Mettre en place les différents type de personnage. Vous devez pouvoir créer des Elfes, des Orques ou des Humains.
-- Deuxième étape :
Les Orques ne sont compris de personne.
Leur cri de guerre est dorénavant : "mlll wwouogrouroulou !!"
-- Troisième étape :
Il existe plusieurs types d'équipements : Armure, épée, autres (vous pouvez en rajouter autant que vous voulez).
Chaque équipement est désigné par un nom et une description de l'objet.
Un équipement confère un bonus bien particulier.
Par exemple : une armure peut conférer +5 en défense, une épée +3 en attaque.
Il y'a même certains objet qui confère +10 en attaque mais baisse de 5 la défense.
Créer une classe Equipement.
Cette classe implémentera tous les attributs et méthodes communes aux équipements.
Mettre en place les différents type d'équipements. Vous devez pouvoir créer plusieurs équipements.
(Je vous laisse libre cours à votre imagination pour la création d'arme et de pouvoir spécifique....)
-- Quatrième étape :
Un personnage peut posséder plusieurs équipements mais :
- Il ne peut être équipé que de 4 objet au total.
- Il ne peut être équipé que de 2 épée a la fois.
- Il ne peut porter qu'une seule armure.
Implémenter donc le fait qu'un personnage possède (ou non) un inventaire.
-- Cinquième étape :
Organiser des combats entre vos personnages !!
Rajouter des méthodes qui permettent de se battre entre vos personnages.
Décomptez les points de vies en fonction des attaques etc...
*/
/*
class race{
private $type;
private $bonus;
public function __toString(){
return "Type : ".$this->type."<br>"."Bonus : ".$this->bonus."<br>";
}
public function __construct($type,$bonus){
$this->type=$type;
$this->bonus=$bonus;
}
public function get_type(){
return $this->type;
}
public function set_type($type){
$this->type=$type;
}
public function get_bonus(){
return $this->bonus;
}
public function set_bonus($bonus){
$this->bonus=$bonus;
}
}*/
class character {
private $race;
private $name;
private $life_p = 100;
private $attack_p = 10;
private $defend_p = 5;
private $shout = "A l'attaqqquuue !";
private $equipment;
public function __toString(){
return "Profil : <br>".$this->name."<br>".$this->life_p."<br>".
$this->attack_p."<br>".$this->defend_p."<br>".$this->shout."<br>";
}
public function __construct($name, $race, $shout){
//parent::__construct();
$this->name=$name;
$this->set_Race($race);
$this->shout = $shout;
}
public function get_name(){
return $this->name;
}
public function set_name($name){
$this->name=$name;
}
public function get_life(){
return $this->life_p;
}
public function set_life($life_p){
$this->life_p=$life_p;
}
public function get_attack(){
return $this->attack_p;
}
public function set_attack($attack_p){
$this->attack_p=$attack_p;
}
public function get_defend(){
return $this->defend_p;
}
public function set_defend($defend_p){
$this->defend_p=$defend_p;
}
public function get_shout(){
return $this->shout;
}
public function set_shout($shout){
$this->shout=$shout;
}
public function set_Race($race){
//selon la $race, tu change les bonus
$this->race=$race;
if($race=="Ork"){
$this->life_p -= 10;
$this->attack_p += 2;
$this->defend_p += 2;
echo "Ork power";
}
elseif($race=="Human"){
echo "Human Armory";
}
elseif($race=="Elf"){
$this->defend_p -= 2;
echo 'Elf Vivacity';
}
}
public function set_equipment($equipment){
$this->equipment=$equipment;
if($this->race=="Human"){
$this->attack_p += 1;
}
}
public function get_equipment(){
return $this->equipment;
}
}
class equipment {
private $category;
private $life_p;
private $attack_p;
private $defend_p;
public function __construct($category, $life_p, $attack_p, $defend_p){
//parent::__construct();
$this->category = $category;
$this->life_p = $life_p;
$this->attack_p = $attack_p;
$this->defend_p = $defend_p;
}
public function get_category(){
$this->category=$category;
}
public function set_category($category){
return $this->category=$category;
}
public function set_life_p($life_p){
$this->life_p=$life_p;
}
public function get_life_p(){
return $this->life_p;
}
public function set_attack_p($attack_p){
$this->attack_p=$attack_p;
if($race=="Human"){
$attack_p = $attack_p += 1;
}
}
public function get_attack_p(){
return $this->attack_p;
}
public function set_defend_p($defend_p){
$this->defend_p=$defend_p;
}
public function get_defend_p(){
return $this->defend_p;
}
}
echo "<hr>";
$johann = new character("Johann L","Human", "Hoha?!");
?><pre><?php
//var_dump($johann);
?><pre><?php
//echo $johann;
$sword = new equipment("sword", 0 , 10, 5);
?><pre><?php
//var_dump($sword);
?><pre><?php
$johann->set_equipment($sword);
$johann->get_equipment();
?><pre><?php
var_dump($johann);
?><pre><?php
//echo $johann;
//$johann->equipment=$sword;
echo "<hr>";
$simon = new character("Simon B","Elf", "Poah?!");
$bow = new equipment("bow", 1 , 8 , 1);
$simon->set_equipment($bow);
var_dump($simon);
echo "<hr>";
$roger = new character("Roger","Ork", "Groah?!");
$axe = new equipment("axe", 0 , 12 , 2);
$roger->set_equipment($axe);
var_dump($roger);
echo "<hr>";
echo $johann ."<br><br>". $simon ."<br><br>". $roger;
?> | true |
a9cad07fa8861776bf78a72541faefeadd0ec81e | PHP | alexjaboatao/ProjetoDAInscricao | /tratamento_v3.php | UTF-8 | 2,534 | 2.5625 | 3 | [] | no_license | <!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Sistema de Análise da Dívida Ativa</title>
</head>
<body>
<?php
require_once "conexao.php";
require_once "crud.php";
$nomearquivo = $_FILES["arquivo"]["tmp_name"];
$tipo = $_POST["tipo"];
if (!empty($nomearquivo)){
$localizacao = substr($_FILES["arquivo"]["name"], strlen($_FILES["arquivo"]["name"])-7,3);
$objeto = fopen ($nomearquivo, 'r');
$arquivo = fgetcsv($objeto, 0, ";");
if($localizacao == "EAN" or $localizacao == "DAT"){
$natureza = utf8_encode(substr ($arquivo[0], 9, 11));
}elseif(substr($_FILES["arquivo"]["name"], 0, 16) == "ListCerAINFRACAO"){
$natureza = "autoConfDat";
}
$pdo = conectar();
if($localizacao == "EAN" && $tipo == "Inscrição"){
carregarTabelaInscricao($natureza, $pdo, $arquivo, $objeto);
} elseif($localizacao == "DAT" && $tipo == "Remessa"){
carregarTabelaRemessa($natureza, $pdo, $arquivo, $objeto);
} elseif(substr($_FILES["arquivo"]["name"], 0, 16) == "ListCerAINFRACAO" && $tipo == "Remessa"){
carregarTabelaRemessaAutoConf($natureza, $pdo, $arquivo, $objeto);
}else {
if($tipo == "Inscrição"){
echo "<script>window.location='TelaEnviarArquivo_v2.php?tipo=Inscrição';alert('Selecione o arquivo correto!');</script>" ;
}elseif($tipo == "Remessa"){
echo "<script>window.location='TelaEnviarArquivo_v2.php?tipo=Remessa';alert('Selecione o arquivo correto!');</script>" ;
}
}
desconectar($pdo);
fclose($objeto);
}else{
echo "<script>window.location='TelaEnviarArquivo_v2.php';alert('Não foi enviado arquivo!');</script>" ;
}
function carregarTabelaInscricao($natureza, $pdo, $arquivo, $objeto){
deletarTabelaBaseAcompInsc($natureza, $pdo);
criarTabelaBaseAcompInsc($arquivo, $natureza, $pdo);
incluirDadosBaseAcompInsc($arquivo, $natureza, $objeto, $pdo);
}
function carregarTabelaRemessa($natureza, $pdo, $arquivo, $objeto){
deletarTabelaBaseAcompRemessa($natureza, $pdo);
criarTabelaBaseAcompRemessa($arquivo, $natureza, $pdo);
incluirDadosBaseAcompRemessa($arquivo, $natureza, $objeto, $pdo);
}
function carregarTabelaRemessaAutoConf($natureza, $pdo, $arquivo, $objeto){
criarTabelaAutoConf($arquivo, $natureza, $pdo);
incluirDadosAutoConfRemessa ($arquivo, $natureza, $objeto, $pdo);
}
?>
</body>
</html> | true |
ebfaaf677e2be34d55740f9a4ae44da2976eb9a3 | PHP | stanislas-m/Scolarite | /share/model/Role.class.php | UTF-8 | 755 | 3.09375 | 3 | [] | no_license | <?php
/**
* Role
*
* @author Stanislas Michalak <stanislas.michalak@gmail.com>
*/
class RoleModel extends Model {
protected $_datasourceName = 'Role';
//Champs
protected $_idRole;
protected $_libelle;
//Erreurs
const BAD_ID_ROLE_ERROR = 1;
const BAD_LIBELLE_ERROR = 2;
public function setIdRole($idRole) {
if (is_numeric($idRole) && (int) $idRole > 0) {
$this->_idRole = (int) $idRole;
} else if (!empty($idRole)) {
$this->_errors[] = self::BAD_ID_ROLE_ERROR;
}
}
public function setLibelle($libelle) {
if (!empty($libelle) && is_string($libelle) && !is_numeric($libelle)) {
$this->_libelle = $libelle;
} else {
$this->_errors[] = self::BAD_LIBELLE_ERROR;
}
}
} | true |
80135c59ade19ab629ddf9355a1dbcd424cdec33 | PHP | doncem/homepage-php | /src/cdcollection/models/cdArtist.php | UTF-8 | 3,076 | 3.0625 | 3 | [] | no_license | <?php
namespace cdcollection\models;
/**
* Artist model
* @Entity
* @Table(name="cd_artist")
* @package cdcollection_models
*/
class cdArtist {
/**
* Autoincrement table ID
* @var int
* @Id
* @GeneratedValue
* @Column(type="integer")
*/
protected $id;
/**
* Name of artist
* @var string
* @Column(type="string")
* @Column(length=255)
*/
protected $name;
/**
* Year formed
* @var int
* @Column(type="smallint")
* @Column(length=4)
*/
protected $formed_in;
/**
* Info about artist
* @var string|null
* @Column(type="text")
* @Column(nullable=true)
*/
protected $info;
/**
* Info source
* @var string|null
* @Column(type="string")
* @Column(length=255)
* @Column(nullable=true)
*/
protected $src;
/**
* Last time updated
* @var string YYYY-MM-DD HH:II:SS
* @Column(type="datetime")
*/
protected $last_update;
/**
* Model of genre of this artist
* @var cdGenre
* @ManyToOne(targetEntity="cdGenre", inversedBy="artists")
* @JoinColumn(name="genre_id", referencedColumnName="id")
*/
private $genre;
/**
* Model of country of this artist
* @var cdCountry
* @ManyToOne(targetEntity="cdCountry", inversedBy="artists")
* @JoinColumn(name="country_id", referencedColumnName="id")
*/
private $country;
/**
* Collection of albums of this artist
* @var \Doctrine\Common\Collections\ArrayCollection
* @OneToMany(targetEntity="cdAlbum", mappedBy="artist")
*/
private $albums;
/**
* Initiate collection
*/
public function __construct() {
$this->albums = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get it
* @return cdGenre
*/
public function getGenre() {
return $this->genre;
}
/**
* Get it
* @return cdCountry
*/
public function getCountry() {
return $this->country;
}
/**
* List of albums
* @return array
*/
public function getAlbums() {
return $this->albums->getValues();
}
/**
* Get it
* @return string
*/
public function getName() {
return $this->name;
}
/**
* Get it
* @return int
*/
public function getFormedIn() {
return $this->formed_in;
}
/**
* Get it
* @return string|null
*/
public function getInfo() {
return $this->info;
}
/**
* Get it
* @return string|null
*/
public function getSrc() {
return $this->src;
}
/**
* Get it
* @return string
*/
public function getLastUpdate() {
return $this->last_update;
}
/**
* Get encoded url for this artist
* @return string
*/
public function getUrl() {
return urlencode($this->name);
}
}
| true |
7beb72d6c869a88a692af33c428a6a7c3ebbc789 | PHP | Bruno-Esteban-Martinez-Millan/Proyect | /php/pago.php | UTF-8 | 497 | 2.609375 | 3 | [] | no_license | <?php
require_once("conexion.php");
class Pago extends Conexion{
public function alta($sal1,$fecha_dep1,$met_pag1,$des1){
$this->sentencia = "INSERT INTO pago VALUES (null,1,'$sal1','$fecha_dep1','$met_pag1','$des1')";
$this->ejecutarSentencia();
}
public function consulta(){
$this->sentencia = "SELECT * FROM pago";
return $this->obtenerSentencia();
}
public function eliminar($id){
$this->sentencia = "DELETE FROM pago WHERE IDpago = $id";
$this->ejecutarSentencia();
}
}
?> | true |
d98a9d6aa5f71e93a2161545d51e3fc580a8fe3e | PHP | chimerarocks/tag | /src/ChimeraRocks/Tag/Models/Tag.php | UTF-8 | 752 | 2.6875 | 3 | [] | no_license | <?php
namespace ChimeraRocks\Tag\Models;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Database\Eloquent\Model;
class Tag extends Model
{
protected $table = "chimerarocks_tags";
private $validator;
protected $fillable = [
'name',
];
public function taggable()
{
return $this->morphTo();
}
public function setValidator(Validator $validator)
{
$this->validator = $validator;
}
public function getValidator()
{
return $this->validator;
}
public function isValid()
{
$validator = $this->validator;
$validator->setRules(['name' => 'required|max:255']);
$validator->setData($this->attributes);
if ($validator->fails()) {
$this->errors = $validator->errors();
return false;
}
return true;
}
} | true |
cfcbd02ca348385dfac6c5df8ae6ed2bb8d425ae | PHP | amm4yv/WebPL | /assignment1/newuser.php | UTF-8 | 1,329 | 2.5625 | 3 | [] | no_license | <?php session_start() ?>
<!DOCTYPE html>
<html>
<head>
<title>Quiz of the Day</title>
<link type="text/css" rel="stylesheet" href="style.css" media="screen" />
</head>
<body>
<header>
<h1>Quiz of the Day</h1>
</header>
<section class="container">
<div class="login">
<h1>Create an Account</h1>
<?php
if(isset($_SESSION['error'])){
$error = $_SESSION['error'];
if (strcmp($error, "passwordMatch") == 0){
echo "<p style='color:RED;'>Passwords didn't match. Please try again.</p><br/>";
}
if (strcmp($error, "userExists") == 0){
echo "<p style='color:RED;'>Invalid user or user already exists. Please try again.</p><br/>";
}
unset($_SESSION['error']);
}
?>
<form method="post" action="index.php">
<p><input type="text" name="newUser" value="" placeholder="Username"></p>
<p><input type="password" name="newPass1" value="" placeholder="Password"></p>
<p><input type="password" name="newPass2" value="" placeholder="Confirm Password"></p>
<p class="submit"><input type="submit" name="submit" value="Create Account"></p>
</form>
</div>
<div class="login-help">
<p>Already have a username? <a href="index.php">Click here to login</a>.</p>
</div>
</section>
</body>
</html>
| true |
46d58e354801e552cee53370ca7ec60c263baef1 | PHP | AlfredoMarino/SistemaVotacion | /modelo/conection.php | UTF-8 | 1,484 | 3.40625 | 3 | [] | no_license | <?php
//CLASE QUE PROVEE LA CONEXION
class conexion
{
public $conexion;
public $HostName = 'localhost';
public $dbPort = '5432';
public $dbName = 'electionDB';
public $dbUser = 'postgres';
public $dbPassword = 'aamv';
//Propiedad estática, inicializada a nulo, donde guardaremos la instancia de la propia clase
static private $instance = null;
//Definimoms el método constructor como privado
private function __construct()
{
$this->conexion = pg_connect(
'host='.$this->HostName
.' port='.$this->dbPort
.' dbname='.$this->dbName
.' user='.$this->dbUser
.' password='.$this->dbPassword)
or die('Falló al conectarse');
}
//Método estatico que sirve como punto de acceso global
public static function getInstance() {
if (self::$instance == null) {
//Si no hay instancia creada, lo hace. Si la hay tira p'alante
self::$instance = new conexion();
}
//Al final devuelve la instancia
return self::$instance;
}
//DEVUELVE LA CONEXION
public function getConexion(){
return $this->conexion;
}
public function __clone()
{
trigger_error("No puede clonar una instancia de ". get_class($this) ." class.", E_USER_ERROR );
}
public function __wakeup()
{
trigger_error("No puede deserializar una instancia de ". get_class($this) ." class.", E_USER_ERROR );
}
}
?> | true |
ad4f2721d1b63205b010f429a538656e22cf7533 | PHP | Efrat19/why-work-twice | /backend/app/Http/Controllers/AdminHomeworkController.php | UTF-8 | 3,002 | 2.53125 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers;
use App\DTO\Homework\StoreHomeworkDto;
use App\Homework;
use App\Http\Requests\Homework\HomeworkRequest;
use App\Repositories\HomeworkRepositoryInterface;
use App\School;
use App\Subject;
use Illuminate\Http\Request;
class AdminHomeworkController extends Controller
{
protected $homeworkRepository;
public function __construct(HomeworkRepositoryInterface $homeworkRepository)
{
$this->homeworkRepository = $homeworkRepository;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return 'index';
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('admin.homework.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(HomeworkRequest $request)
{
$school = School::firstOrCreate(['name' => $request['school']]);
$subject = Subject::firstOrCreate(['name' => $request['subject']]);
$homework = $this->homeworkRepository->create(new StoreHomeworkDto(
$request->input('description'),
$request->input('source'),
$school,
$subject,
auth()->user()
));
return redirect('/admin/search/homeworks')->with('msg' , 'homework '.$homework['id'].' successfully created');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
return view('admin.homework.show')->withHomework(Homework::findOrFail($id));
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
return view('admin.homework.edit')->with(['homework' => Homework::findOrFail($id)]);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(HomeworkRequest $request, Homework $homework)
{
$homework = $this->homeworkRepository->update($request, $homework);
return redirect('/admin/search/homeworks')->with('msg' , 'homework '.$homework['id'].' successfully updated');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy(Homework $homework)
{
$homework = $this->homeworkRepository->delete($homework);
return redirect('/admin/search/homeworks')->with('msg' , 'homework '.$homework['id'].' successfully deleted');
}
}
| true |
e708907c1bcd6a9399079081b5c2267913cba9cd | PHP | arout77/diamondphp | /app/plugins/Geoip.php | UTF-8 | 4,404 | 3.078125 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Plugin;
use GeoIp2\Database\Reader;
/*
* DOCUMENTATION:
* https://github.com/maxmind/GeoIP2-php
*/
class Geoip extends \GeoIp2\Database\Reader {
# Database access needed for some calculations
/**
* @var mixed
*/
private $db;
# Search radius properties
/**
* @var array
*/
public $radius = [];
# Use MaxMind GeoIP data to determine user location
/**
* @var mixed
*/
private $record;
/**
* @var mixed
*/
public $ip_address;
/**
* @var mixed
*/
public $latitude;
/**
* @var mixed
*/
public $longitude;
/**
* @var mixed
*/
public $city;
/**
* @var mixed
*/
public $state;
/**
* @var mixed
*/
public $state_abbr;
/**
* @var mixed
*/
public $zipcode;
/**
* @var mixed
*/
public $country;
/**
* @var mixed
*/
public $country_abbr;
/**
* @param $geo_db_file
* @param $db
*/
public function __construct($geo_db_file, $db) {
$this->db = $db;
$reader = new Reader($geo_db_file);
$ip = MY_IP4;
$this->ip_address = $ip;
$record = $reader->city($ip);
$this->record = $reader->city($ip);
// City name
$this->city = $this->record->city->name;
// State name
$this->state = $this->record->mostSpecificSubdivision->name;
// Two letter abbreviation for state
$this->state_abbr = $this->record->mostSpecificSubdivision->isoCode;
// Five digit zip code
$this->zipcode = $this->record->postal->code;
// Country name
$this->country = $record->country->name;
// Two letter abbreviation for country
$this->country_abbr = $record->country->isoCode;
// Latitude and longitude
$this->latitude = $this->record->location->latitude;
$this->longitude = $this->record->location->longitude;
}
/**
* @return mixed
*/
public function ip() {
return $this->ip_address;
}
/**
* @param $lat1
* @param $lon1
* @param $lat2
* @param $lon2
* @param $unit
* @return mixed
*/
public function distance($lat1, $lon1, $lat2, $lon2, $unit = "M") {
$theta = $lon1 - $lon2;
$dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
$dist = acos($dist);
$dist = rad2deg($dist);
$miles = $dist * 60 * 1.1515;
$unit = strtoupper($unit);
if ($unit == "K") {
return ($miles * 1.609344);
} else if ($unit == "N") {
return ($miles * 0.8684);
} else {
if ($miles < 10) {
$miles = number_format($miles, 1, '.', '');
} else {
$miles = number_format($miles);
}
return $miles;
}
}
/**
* @param $miles
* @return mixed
*/
public function search_radius($miles): \PDOStatement{
# This function will try to find all cities within a given radius based on
# the current visitor's location
$query = "SELECT citycode, statecode, code,
(
3959 * acos( cos( radians( ? ) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians( ? ) ) + sin( radians( ? ) ) * sin( radians( latitude ) ) )
)
AS distance
FROM zips
GROUP BY distance
HAVING distance <= $miles;
";
$cities_in_radius = $this->db->prepare($query);
$cities_in_radius->execute([$this->latitude, $this->longitude, $this->latitude]);
return $cities_in_radius;
}
/**
* @param $zip
* @return mixed
*/
public function cities($zip) {
# Return a list of cities for the specified state or zip code
if (strlen($zip) === 5) {
# Search by zip code
$q = "SELECT citycode, statecode FROM zips WHERE code = ? ";
$s = $this->db->prepare($q);
$s->execute([$zip]);
} else {
# Search by state
$q = "SELECT citycode FROM zips WHERE statecode = ? ";
$s = $this->db->prepare($q);
$s->execute([$zip]);
}
if ($s) {
return $s;
}
return false;
}
/**
* @param $zip
* @return mixed
*/
public function states($zip) {
$q = "SELECT statecode FROM zips WHERE code = ? ";
$s = $this->db->prepare($q);
$s->execute([$zip]);
return $s;
}
/**
* @param $city
* @param $state
* @return mixed
*/
public function zipcode($city, $state) {
$q = "SELECT code FROM zips WHERE citycode = ? AND statecode = ? ";
$s = $this->db->prepare($q);
$s->execute([$city, $state]);
return $s['code'];
}
}
| true |
89465dc47de9ca73a271d77420216257da8626e1 | PHP | Stuskoski/Achieve-Life | /achieve/achieve/WebContent/models/GetFriends.class.php | UTF-8 | 1,953 | 2.859375 | 3 | [] | no_license | <?php
include_once("Database.class.php");
class GetFriends{
public function getAll($user){
if(!is_null($user)){
try{
//echo $user;
/*** connect to the database ***/
$dbh = Database::getDB();
/*** The sql statement ***/
$stmt = $dbh->prepare("SELECT user2 FROM Friends WHERE user1=:user
UNION
Select user1 FROM Friends WHERE user2=:user");
/*** Bind params ***/
$stmt->bindParam ( ':user', $user, PDO::PARAM_STR );
/*** exceute the query ***/
$stmt->execute();
/*** set the fetch mode to associative array ***/
$stmt->setFetchMode(PDO::FETCH_NUM);
/*** set the header for the image ***/
//$array = $stmt->fetch();
/***Parse through the list***/
while ($row = $stmt->fetch()) {
//echo $row[0] . "\n";
$ary[]=$row[0];
}
/***Clear the connection to the database***/
Database::clearDB();
if(empty($ary)){
$ary='';
}
return $ary;
}catch(Exception $e){
echo $e->getMessage();
}
}
}
public function getAllUsers(){
if(isset($_SESSION['user_session'])){
try{
//echo $user;
/*** connect to the database ***/
$dbh = Database::getDB();
/*** The sql statement ***/
$stmt = $dbh->prepare("SELECT userName
FROM Users");
/*** Bind params ***/
$stmt->bindParam ( ':user', $_SESSION['user_session'], PDO::PARAM_STR );
/*** exceute the query ***/
$stmt->execute();
/*** set the fetch mode to associative array ***/
$stmt->setFetchMode(PDO::FETCH_NUM);
/*** set the header for the image ***/
//$array = $stmt->fetch();
/***Parse through the list***/
while ($row = $stmt->fetch()) {
$a[] = $row[0];
}
/***Clear the connection to the database***/
Database::clearDB();
return $a;
}catch(Exception $e){
echo $e->getMessage();
}
}
}
} | true |
2bce04bc586baacd2a7636e4501faf7c51f23321 | PHP | appers-platform/platform | /solutions/user/controller/oauth_mailru.php | UTF-8 | 1,790 | 2.515625 | 3 | [
"MIT"
] | permissive | <?
use ohmy\Auth2;
if(\solutions\user::isAuthorized()) {
\response::redirect(self::getConfig('afterAuthUrl'));
}
// @TOOD: url of this page
$redirect = \helper::fullUrl(self::getUrl().'?afterAuthUrl='.urlencode(\solutions\user::getAfterAuthUrl()));
# initialize 3-legged oauth
$auth = Auth2::legs(3)
->set('id', $this->getConfig('oauth_mail_ru')['id'])
->set('secret', $this->getConfig('oauth_mail_ru')['secret_key'])
->set('redirect', $redirect)
# oauth flow
->authorize('https://connect.mail.ru/oauth/authorize')
->access('https://connect.mail.ru/oauth/token')
# save access token
->finally(function($data) use(&$access_token) {
$access_token = $data['access_token'];
});
// get user data
$params = [
'method' => 'users.getInfo',
'session_key' => $access_token,
'app_id' => '722752',
'format' => 'json',
'secure' => 1
];
// sign query
ksort($params);
$params_str = '';
foreach($params as $key => $value) {
$params_str .= "$key=$value";
}
$params['sig'] = md5($params_str.$this->getConfig('oauth_mail_ru')['secret_key']);
// execute: get user data
$auth->GET('http://www.appsmail.ru/platform/api', $params)->then(function($response) {
$data = $response->json();
if(!count($data) || !$data[0]) {
parentController::oauth(new userModel());
return;
}
$prepared = new userModel();
$data = $data[0];
$prepared->email = $data['email'];
$prepared->social_id = $data['uid'];
$prepared->social_auth_id = userModel::OAUTH_MAILRU;
$prepared->is_confirmed = true;
$prepared->birthday = strtotime($data['birthday']);
$prepared->photo_url = $data['pic_big'];
$prepared->is_male = $data['sex'] ? userModel::GENDER_FEMALE : userModel::GENDER_MALE;
$prepared->url = $data['link'];
$prepared->name = $data['nick'];
parentController::oauth($prepared);
});
| true |
161e13f720582ec2b05c14a1a94950739c398200 | PHP | magazord-plataforma/madeira-madeira-marketplace | /MadeiraMadeira/Marketplace/Dominio/Lote.php | UTF-8 | 994 | 2.90625 | 3 | [] | no_license | <?php
namespace MadeiraMadeira\Marketplace\Dominio;
/**
* Description of Lote
*
* @author Maicon Sasse
*/
class Lote extends AbstractModel
{
/**
* @var AbstractModel[]
*/
protected $_lista;
public function getLista()
{
return $this->_lista;
}
public function setLista(array $lista = null)
{
$this->_lista = $lista;
}
public function add($item)
{
$lista = $this->getLista() ? $this->getLista() : array();
$lista[] = $item;
$this->setLista($lista);
}
public function serialize()
{
$result = null;
if ($lista = $this->getLista()) {
$result = array();
foreach ($lista as $index => $value) {
if ($value instanceof AbstractModel) {
$result[$index] = $value->serialize();
} else {
$result[$index] = $value;
}
}
}
return $result;
}
}
| true |
49eefad7f2a62cde539671dff792093af3126b62 | PHP | InHale1/test | /auth.php | UTF-8 | 2,195 | 2.578125 | 3 | [] | no_license | <br/>
<br/>
<br/>
<br/>
<br/>
<?php
include "config.php";
$db_table_to_show = 'Client';
session_start();
$_SESSION['name'] = $_POST['name'];
$_SESSION['pass'] = md5($_POST['pass']);
if (isset($_POST['exit_btn'])){
session_unset();
header("Location: http://sql-chiibip.rhcloud.com" );
}
if (($_SESSION['name']) && ($_SESSION['pass'])){
session_start();
$query = "SELECT * FROM `users` WHERE `name` = '".$_SESSION['name']."' ";
$sql = sprintf($query,
mysql_real_escape_string($_SESSION['name']='%s' && '%d'),
mysql_real_escape_string($_SESSION['pass']='%s' && '%d'));
$res = mysql_query ($query);
$row = mysql_fetch_array ($res);
if (($_SESSION['name'] == $row['name']) && ($_SESSION['pass'] == $row ['password'])){
$qr_result = mysql_query("SELECT * FROM " . $db_table_to_show)
or die(mysql_error());
// выводим на страницу сайта заголовки HTML-таблицы
echo '<table border="1">';
echo '<thead>';
echo '<tr>';
echo '<th>Personal identification number</th>';
echo '<th>Name</th>';
echo '<th>Telephone</th>';
echo '<th>Credit Summ</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
// выводим в HTML-таблицу все данные клиентов из таблицы MySQL
while($data = mysql_fetch_array($qr_result)){
echo '<tr>';
echo '<td>' . $data['PID'] . '</td>';
echo '<td>' . $data['Name'] . '</td>';
echo '<td>' . $data['Phone'] . '</td>';
echo '<td>' . $data['Credit'] . '</td>';
echo '</tr>';
}
echo '</tbody>';
echo '</table>';
} else { echo "Неверно указано имя пользователя или пароль. Повторите попытку ешё раз."; };
}
?>
<div class="exit" style="float:left" >
<form id="exit_form", action ="auth.php", method = "POST" >
</br>
<label for = "Exit"> </label>
<input type="submit" value="Exit" name="exit_btn">
</form>
</div>
| true |
103aed2b81c96a31526c1f8fb05c7089e720a1b4 | PHP | peludomania/cursosUdemy | /SOLID/5 DPI/LocalUserRepository.php | UTF-8 | 247 | 2.828125 | 3 | [] | no_license | <?php
class LocalUserRepository implements UserRepository
{
public function getUser(int $id): User
{
// logica para leer usuario de la base de datos
$user = new User(1, 'Alberto', 'a@a.com');
return $user;
}
} | true |
149d0b69b2531c59395f830a9b0b67f3d93ed687 | PHP | wydhit/phalcon | /common/Services/ComService.php | UTF-8 | 1,791 | 2.609375 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: wyd
* Date: 2017-08-02
* Time: 14:17
*/
namespace Common\Services;
use Bizer\Search\ComSearch;
use Common\Exception\LogicException;
use Common\Exception\ModelNotFindException;
use Common\Models\WeCom;
use Common\Models\WeOrder;
use Common\Services\BaseService;
/**
* Class ComService
* @package Common\Services
* @property
*/
class ComService extends BaseService
{
protected $modelCLass = WeCom::class;
public function add($data)
{
/**
* @var $model WeCom
*/
$model = $this->findModel();
$model->title = $data['title'];
}
public function edit($data, $id)
{
/**
* @var $model WeCom
*/
$model = $this->findModel($id);
$model->title = "asdfaf";
}
public function editByAgent($data, $id, $agentId)
{
/**
* @var
*/
$model = $this->findModel($id);
}
public function addByAgent($data = [], $agentId = 0)
{
}
public function addByCom($data = [], $comid = 0)
{
}
/**
* 检查店铺是否属于某个商家用户
* @param $comid
* @param $bizerId
* @return bool
* @throws LogicException
*/
public function checkComidBelongToBizer($comid, $bizerId)
{
return WeCom::count(['id=:comid: and uid=:uid:', 'bind' => ['comid' => $comid, 'uid' => $bizerId]]);
}
/**
* 检查店铺是否属于某个商家用户
* @param $comid
* @param $bizerId
* @return bool
* @throws LogicException
*/
public function checkComidBelongToAgent($comid, $agentId)
{
return WeCom::count(['id=:comid: and uid=:uid:', 'bind' => ['comid' => $comid, 'uid' => $agentId]]);
}
} | true |
697e21b8f6a96a50c611896b71ae6fa170ae5b06 | PHP | TatAnt/FinalProjectPHP | /classes/Recipe.php | UTF-8 | 8,430 | 3.03125 | 3 | [] | no_license | <?php
require_once "PDO_Database.php";
require_once "Rating.php";
class Recipe{
private $Id;
private $CategoryId;
private $MealTypeId;
private $Name;
private $Ingridients;
private $PrepSteps;
private $PreparationTime;
private $CookingTime;
private $Servings;
private $RecipeDate;
private $Image;
private $Comment;
/* ========================================================================*/
function __construct($recipe_Id, $categoryId, $mealTypeId, $name, $ingridients, $prepSteps, $preparationTime, $cookingTime, $servings, $recipeDate, $image, $comment)
{
$this->Id = $recipe_Id;
$this->CategoryId = $categoryId;
$this->MealTypeId = $mealTypeId;
$this->Name = $name;
$this->Ingridients = $ingridients;
$this->PrepSteps = $prepSteps;
$this->PreparationTime = $preparationTime;
$this->CookingTime = $cookingTime;
$this->Servings = $servings;
$this->RecipeDate = $recipeDate;
$this->Image = $image;
$this->Comment = $comment;
}
/* ========================================================================*/
public static function ReadAllRecipeFromDB(){
try
{
$database = PDO_Database::Get_Instance();
$query = "SELECT * FROM recipes";
$statement = $database->Connection->prepare($query);
$statement->execute();
$total=$statement->rowCount();
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
return $result;
}catch(PDOException $e)
{
echo "Query Failed: ".$e->getMessage();
}
}
/* ========================================================================*/
public static function Search_By_Name($name){
$database = PDO_Database::Get_Instance();
$query = "SELECT * FROM `recipes` WHERE Name LIKE '%$name%'";
$statement = $database->Connection->prepare($query);
$statement->bindValue(1,"%$name%");
$statement->execute();
//$result = $statement->fetch(PDO::FETCH_ASSOC);
if(!$statement->rowCount() == 0){
while($result = $statement->fetch(PDO::FETCH_ASSOC)){
//foreach($result as $Element){
$i=0;
echo '<table border="0" cellpadding="10">';
if($i%3==0){
echo "<tr>";
echo "<td>";
echo "<a href='recipe_details.php?Id=" .$result['Id']."'>"."<img src = \"images/".$result['Image']." \" height='auto' width='350px' />"."</a>";
echo "</td>";
echo "</tr>";
echo "<tr>";
echo "<td><b>";
echo "<h3>";
echo "<a href='recipe_details.php?Id=" .$result['Id']."'>".$result['Name']."</a>";
echo "</h3>";
echo "</b></td>";
echo "</tr>";
echo "<tr>";
echo "<td>";
echo "Cooking time: ".$result['CookingTime'];
echo "</td>";
echo "</tr>";
echo "<br>";
echo "<tr>";
echo "<td>";
echo "Servings: ".$result['Servings'];
echo "</td>";
echo "</tr>";
echo "<br>";
echo "<tr>";
echo "<td>";
$averageRating = self::Calculate_Rating($result['Id']);
Rating::Dispaly_Stars($averageRating);
echo "</td>";
echo "</tr>";
echo "<br><br><br>";
}else{
echo "<td>";
echo "<a href='recipe_details.php?Id=" .$result['Id']."'>".$result['Name']."</a>";
echo "</h3>";
echo "</b></td>";
}
$i++;
echo "</table>";}
}
//echo $result['Name'];
//echo $result['Servings'];
}
//====================================================================
public static function Calculate_Rating($recipe_Id, $user_Id = null){
try{
$query = "";
if(empty($user_Id)){
$query = "SELECT AVG(Rating) FROM ratings WHERE RecipeId= $recipe_Id ";
}else{
$query = "SELECT AVG(Rating) FROM ratings WHERE RecipeId = $recipe_Id AND UserId = $user_Id";
}
$database = PDO_Database::Get_Instance();
$statement = $database->Connection->prepare($query);
$statement->execute();
$result = $statement->fetch(PDO::FETCH_ASSOC);
return $result['AVG(Rating)'];
}catch(PDOException $e){
echo "Query Failed: ". $e->getMessage();
}
}
//============================================================================
public static function Display(&$recipes){
foreach($recipes as $Element){
$i=0;
echo '<table border="0" cellpadding="10">';
if($i%3==0){
echo "<tr>";
echo "<td>";
echo "<a href='recipe_details.php?Id=" .$Element['Id']."'>"."<img src = \"images/".$Element['Image']." \" height='auto' width='350px' />"."</a>";
echo "</td>";
echo "</tr>";
echo "<tr>";
echo "<td><b>";
echo "<h3>";
echo "<a href='recipe_details.php?Id=" .$Element['Id']."'>".$Element['Name']."</a>";
echo "</h3>";
echo "</b></td>";
echo "</tr>";
echo "<tr>";
echo "<td>";
echo "Cooking time: ".$Element['CookingTime'];
echo "</td>";
echo "</tr>";
echo "<br>";
echo "<tr>";
echo "<td>";
echo "Servings: ".$Element['Servings'];
echo "</td>";
echo "</tr>";
echo "<br>";
echo "<tr>";
echo "<td>";
$averageRating = self::Calculate_Rating($Element['Id']);
Rating::Dispaly_Stars($averageRating);
echo "</td>";
echo "</tr>";
echo "<br><br><br>";
}else{
echo "<td>";
echo "<a href='recipe_details.php?Id=" .$Element['Id']."'>".$Element['Name']."</a>";
echo "</h3>";
echo "</b></td>";
}
$i++;
echo "</table>";
}
}
public static function Search_By_Id($recipe_Id){
try
{
$database = PDO_Database::Get_Instance();
$query = "SELECT * FROM recipes WHERE Id = $recipe_Id";
$statement = $database->Connection->prepare($query);
$statement->execute();
$result = $statement->fetch(PDO::FETCH_ASSOC);
return $result;
}catch(PDOException $e)
{
echo "Query Failed: ".$e->getMessage();
}
}
public static function Display_Details($recipe_Id, $user_Id = null){
$recipe = self::Search_By_Id($recipe_Id);
echo '<div class="card w-100">';
// Card body
echo '<div class="row">';
echo '<div class="m-3 pb-3 col-md-5">';
echo "<img src='images/".$recipe['Image'] ."' height='auto' width='400px' >";
echo '</div>';//end of column1
echo '<div class="col-md-6">';
echo '<span class="highlight"><h3><b>'.$recipe['Name'].'</b></h3></span><br><br>';
echo '<h5 style="display: inline;"><b>Preparation Time: </b></h5>'.'<h6 style="display: inline;">'.$recipe['PreparationTime'].'</h6><hr style="clear: both;" />';
echo '<h5 style="display: inline;"><b>Cooking Time: </b></h5>'.'<h6 style="display: inline;">' .$recipe['CookingTime'].'</h6><hr style="clear: both;" />';
echo '<h5 style="display: inline;"><b>Servings: </b></h5>'.'<h6 style="display: inline;">' .$recipe['Servings'].'</h6><hr style="clear: both;" />';
echo '<h5 style="display: inline;"><b>Recipe Date: </b></h5>'.'<h6 style="display: inline;">' .$recipe['RecipeDate'].'</h6><hr style="clear: both;" />';
echo '<h5 style="display: inline;"><b>Ingridients: </b></h5>'.'<h6 style="display: inline;">'.$recipe['Ingridients'].'</h6><hr style="clear: both;" />';
echo '<h5><b>Preparation Steps: </b></h5>'.'<h6>'.$recipe['PrepSteps'].'</h6>';
echo '<form>';
echo '<div class="form-outline">';
echo '<textarea name="Comment" class="form-control" id="textAreaExample" rows="4"></textarea>';
echo'<label class="form-label" for="textAreaExample">Your Comment</label>';
echo '<input type="submit" name="add" class="btn" value="Add"/>';
echo '</div>';
echo '</form>';
echo '</div>';//end of column2
echo '</div>'; //end of row
echo '<div class="col-md-1">';
echo'<a href="index.php">';
echo "<button class='btn btn-success'>". '<span class="fa fa-angle-double-left" style="font-size:24px"></span></button>';
echo'</a>';
echo '</div>';//end of column4
echo '</div>';//end of body
echo '<div class="card-footer">';
//Card footer
echo '<div class="row">';
echo '<div class="col-md-4">';
$avgerageRating = self::Calculate_Rating($recipe_Id);
Rating::Dispaly_Stars($avgerageRating);//display average rating
echo '</div>';//end of col1
echo '<div class="col-md-4">';
if(!empty($user_Id)){
echo "<div><h5><b>Rate This Recipe: </b></h5></div>";
$rating = self::Calculate_Rating($recipe_Id, $user_Id);
Rating::Display_Form($rating);
}
echo '</div>';//end of col2
echo '<div class="col-md-4">';
echo '</div>';
echo '</div>';//end of row2
echo '</div>';//end of footer
}
}
?> | true |
ba946f6bcfc3064446902cd7619c5917305f096c | PHP | norja25/16._julijs | /app/Http/Controllers/Auth/AuthController.php | UTF-8 | 2,933 | 2.609375 | 3 | [] | no_license | <?php namespace Modelbook\Http\Controllers\Auth;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Input;
use Laracasts\Flash\Flash;
use Modelbook\Http\Controllers\Controller;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Contracts\Auth\Registrar;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Modelbook\User;
use Modelbook\Http\Requests\UserRequest;
use Modelbook\Commands\RegisterUserCommand;
use Modelbook\Http\Requests;
use Illuminate\Http\Request;
use GuzzleHttp\Client as Guzzle;
class AuthController extends Controller {
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers;
/**
* Create a new authentication controller instance.
*
* @param \Illuminate\Contracts\Auth\Guard $auth
* @param \Illuminate\Contracts\Auth\Registrar $registrar
* @return void
*/
public function __construct(Guard $auth, Registrar $registrar)
{
$this->auth = $auth;
$this->registrar = $registrar;
$this->middleware('guest', ['except' => 'getLogout']);
}
/**
* Show a form to register the user
*
* @return \Illuminate\View\View
* @return Response
*/
public function create() {
return view('auth.register');
}
/**
*Creating a new Modelbook user
*
* @param UserRequest $request
* UserRequest is where register form is validated
* ***Modelbook/Http/Requests/UserRequest
* If validation successful form data is passed to DTO(DataTransferObject) UserRegistredCommand
* ***Modelbook/Commands/UserRegistred
* After that to do the registration logic inside UserRegistredCommandHandler
* ***Modelbook/Handlers/Commands
* @return \Illuminate\View\View
*/
public function store(UserRequest $request)
{
$user = $this->dispatch(new RegisterUserCommand(
$user_firstname = $request->input('user_firstname'),
$user_lastname = $request->input('user_lastname'),
$email = $request->input('email'),
$user_phone = $request->input('user_phone'),
$password = $request->input('password')
));
// Flash::success('You have registred! Your login credentials will be sent to your mobile phone number');
return redirect('login');
}
public function destroy($id)
{
$userid = $id;
User::destroy($userid);
return 'User ' . $userid . ' deleted';
}
/**
* @return mixed
*/
public function all()
{
return User::all();
}
}
| true |
2052d6f23db68e4406a7a8c64483bcb67c9425d3 | PHP | cvuorinen/symfony-legacy-example | /legacy/classes/info.php | UTF-8 | 246 | 2.640625 | 3 | [
"MIT"
] | permissive | <?php
class Info
{
function getUsername($id)
{
global $container;
$userRepository = $container->get('acme.demo.repository.user');
$user = $userRepository->find($id);
return $user->getUsername();
}
}
| true |
424e78f20bc1dae9fa652e8303460123266b8145 | PHP | michalsen/rearrange | /includes/admin/class-rearrange-admin.php | UTF-8 | 2,647 | 2.65625 | 3 | [] | no_license | <?php
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
class RearrangeAdmin {
public function __construct() {
add_action('admin_init', array($this, 'wp_rearrange_admin_init'));
add_action('admin_menu', array($this, 'admin_menu'));
}
public function admin_menu() {
$page = add_management_page('Rearrange', 'Rearrange ', 'manage_options', 'rearrange', array( $this,'wp_rearrange_settings_page'));
}
function wp_rearrange_admin_init() {
if(is_admin()){
if ($_REQUEST['action'] == 'forward' ||
$_REQUEST['action'] == 'back') {
include(WP_PLUGIN_DIR. '/rearrange/includes/simple_html_dom.php');
$posts = getPosts();
foreach ($posts as $key => $value) {
if (preg_match('/(<img .*?>)/', $value->post_content)) {
$content = str_get_html($value->post_content);
foreach($content->find('img') as $element) {
$newOrderImage = 'css="' . $element->attr['class'] . '" ';
$newOrderImage .= 'src="' . $element->attr['src'] . '" ';
$newOrderImage .= 'alt="' . $element->attr['alt'] . '" ';
$newOrderImage .= 'width="' . $element->attr['width'] . '" ';
$newOrderImage .= 'height="' . $element->attr['height'] . '" ';
}
// $strippedContent = strip_tags($value->post_content, '<img>');
$strippedContent = preg_replace("/<img[^>]+\>/i", " ", $value->post_content);
//$cleanedstrippedContent = str_replace(" ", '', $strippedContent);
if ($_REQUEST['action'] == 'forward') {
$newOrder = '<img ';
$newOrder .= $newOrderImage;
$newOrder .= '>';
$newOrder .= $strippedContent;
}
if ($_REQUEST['action'] == 'back') {
$newOrder = $strippedContent;
$newOrder .= '<img ';
$newOrder .= $newOrderImage;
$newOrder .= '>';
}
global $wpdb;
$wpdb->update(
$wpdb->prefix . 'posts',
array(
'post_content' => $newOrder,
),
array( 'ID' => $value->ID)
);
}
}
}
}
}
public function wp_rearrange_settings_page(){
include('functions.php');
include('rearrange_admin.tpl.php');
}
}
return new RearrangeAdmin();
function getPosts() {
global $wpdb;
$sql = 'SELECT ID, post_content FROM ' . $wpdb->prefix . 'posts WHERE post_status = "publish"';
$posts = $wpdb->get_results($sql);
return $posts;
}
| true |
83be061e1cd449232dc249e4f6b651cc99bdcba3 | PHP | RakeshRoy1995/cart | /admin-panel.php | UTF-8 | 1,436 | 2.578125 | 3 | [] | no_license | <?php
include('header.php');
?>
<?php
include('db.php');
if(isset($_POST['upload'])){
$name = $_POST['name'];
$code = $_POST['code'];
$price = $_POST['price'];
$target = "product-images/".basename($_FILES['image']['name']);
//product-images is the folder name to save picture inthat particular filder
$sql = "INSERT INTO tblproduct(name, code, image, price)
VALUES ('$name','$code','$target','$price')";
$run = mysqli_query($conn , $sql);
if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
$msg = "Image Upload successfully";
} else {
$msg = "Image Not Upload successfully";
}
echo "<script>window.open('index.php','_self')</script>";
}
?>
<form class="form-group" action='admin-panel.php' method='post' enctype='multipart/form-data' ></br><br>
Name :<input type="text" name="name" class="form-control" required ><br><br>
Code :<input type="text" name="code" class="form-control" required ><br><br>
Image :<input type='file' name= 'image' class="btn btn-outline-primary" required ><br><br>
Price :<input type="text" name="price" class="form-control" required ><br><br>
<input type="submit" name="upload" value="Image Upload" class="btn btn-outline-primary" />
</form>
<?php
include('footer.php');
?>
| true |
8db1de1e09537d64d242520ad5c6f9750215f516 | PHP | SuddenKey/PHPtext | /db/PHP面向对象程序设计之魔术方法/自动加载类.php | UTF-8 | 651 | 2.84375 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: haohao
* Date: 2017/8/22
* Time: 下午1:52
*/
//__autoload 是在实例化对象时,如果累不存在就会被自动调用
//参数:实例化的类名
//作用:可以用于自动引入类文件
function __autoload($classname) {
//注意:类文件名要有规律
// 类文件名要统一
// 类文件的路径要有规律
$file = $classname.".php";
$path = "./class/".$file;
if (file_exists($path)) {
include ($path);
} else {
die("你所使用的{$classname}.php文件不存在");
}
}
$demo = new demo();
var_dump($demo);
$demo = new demo1();
| true |
887e2f8885fafd2025c3b825fc5297ce1ee327db | PHP | Kenlock/microfinance | /app/Listeners/ClientPendingApprovalTaskListener.php | UTF-8 | 769 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Listeners;
use App\Events\ClientCreatedEvent;
use App\Task;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
class ClientPendingApprovalTaskListener
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param ClientCreatedEvent $event
* @return void
*/
public function handle(ClientCreatedEvent $event)
{
$task = new Task();
$task->name = 'client pending approval';
$task->user_id = $event->user_id;
$task->branch_id = $event->branch_id;
$task->status = 'pending';
$event->client->task()->save($task);
}
}
| true |
06aad1aa3183612f3c97764caee3e725e2d58892 | PHP | JamersonWalderson/challenge-mesha | /app/Http/Controllers/Api/SpecialityController.php | UTF-8 | 1,779 | 2.5625 | 3 | [] | no_license | <?php
namespace App\Http\Controllers\Api;
use App\Models\Speciality;
use App\Http\Resources\SpecialityResource;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class SpecialityController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
$speciality = Speciality::All();
return SpecialityResource::collection($speciality);
}
/**
* Store a newly created resource in storage.
*
*/
public function store(Request $request)
{
$speciality = new Speciality;
$speciality->name = $request->input('name');
// Existe um mutator que transforma doctor_id no nome do doutor
$speciality->doctor_id = $request->input('doctor_id');
$speciality->price = $request->input('price');
if($speciality->save()){
return new SpecialityResource($speciality);
}
}
/**
* Display the specified resource.
*
*/
public function show($id)
{
$speciality = Speciality::find($id);
return new SpecialityResource($speciality);
}
/**
* Update the specified resource in storage.
*
*/
public function update(Request $request)
{
$speciality = Speciality::find($request->id);
$speciality->name = $request->input('name');
if($speciality->save()){
return new SpecialityResource($speciality);
}
}
/**
* Remove the specified resource from storage.
*
*/
public function destroy($id)
{
$speciality = Speciality::find($id);
if ($speciality->delete()){
return new SpecialityResource($speciality);
}
}
}
| true |
00b1c75c1ddde97a64e45e18fc4bac9d72e4d627 | PHP | nitsuzxz/Online-Booking-Ticket | /Admin-Side/hall/manageHall.php | UTF-8 | 2,081 | 2.5625 | 3 | [] | no_license | <?php
$cinemaID = '';
$hallName = '';
$hallType = '';
$hallPrice = '';
$hallRow = '';
$hallSeatsPerRow = '';
$query = 'SELECT * FROM hall
INNER JOIN cinema ON hall.hall_cinema_id = cinema.cinema_id
ORDER BY hall_cinema_id ASC';
$res = mysqli_query($conn, $query);
$hallList = mysqli_fetch_all($res, MYSQLI_ASSOC);
if (isset($_POST['addHall'])) {
//echo $_POST['cineID'];
$cinemaID = $_POST['cinemaID'];
$hallName = $_POST['hallName'];
$hallType = $_POST['hallType'];
$hallPrice = $_POST['hallPrice'];
$hallRow = $_POST['hallRow'];
$hallSeatsPerRow = $_POST['hallSeatsPerRow'];
$query = "INSERT INTO hall(hall_name, hall_cinema_id, hall_type, hall_price, seat_row, seat_number) VALUES ('$hallName', '$cinemaID', '$hallType', '$hallPrice', '$hallRow', '$hallSeatsPerRow')";
if (mysqli_query($conn, $query)) {
header('Location: hall.php');
}
else{
echo "Query x jadi";
}
}
if (isset($_GET['delete'])){
$query = "DELETE FROM hall WHERE hall_id = {$_GET['delete']}";
mysqli_query($conn, $query);
header('Location: hall.php');
}
if (isset($_GET['edit'])){
$query = "SELECT * FROM hall WHERE hall_id = {$_GET['edit']}";
$res = mysqli_query($conn, $query);
$hallInst = mysqli_fetch_array($res);
$cinemaID = $hallInst['hall_cinema_id'];
$hallName = $hallInst['hall_name'];
$hallType = $hallInst['hall_type'];
$hallPrice = $hallInst['hall_price'];
$hallRow = $hallInst['seat_row'];
$hallSeatsPerRow = $hallInst['seat_number'];
}
if (isset($_POST['editHall'])){
$hallID = $_POST['hallID'];
$cinemaID = $_POST['cinemaID'];
$hallName = $_POST['hallName'];
$hallType = $_POST['hallType'];
$hallPrice = $_POST['hallPrice'];
$hallRow = $_POST['hallRow'];
$hallSeatsPerRow = $_POST['hallSeatsPerRow'];
$query = "UPDATE hall SET hall_cinema_id = '$cinemaID', hall_name = '$hallName', hall_type = '$hallType', hall_price = '$hallPrice', seat_row = '$hallRow', seat_number = '$hallSeatsPerRow' WHERE hall_id = '$hallID'";
mysqli_query($conn, $query);
header('Location: hall.php');
}
?> | true |
2cfdf632dd6e2eaf87af21ff8f40d92558eacac2 | PHP | asim-altayb/retrofit-server-side | /login.php | UTF-8 | 794 | 2.765625 | 3 | [] | no_license |
<?php
//getting user values
$username=$_POST['username'];
$password=$_POST['password'];
//an array of response
$output = array();
//requires database connection
require_once('db.php');
//checking if email exit
$conn=$dbh->prepare("SELECT * FROM users WHERE username=? and password=?");
$pass=$password;
$conn->bindParam(1,$username);
$conn->bindParam(2,$pass);
$conn->execute();
if($conn->rowCount() == 0){
$output['isSuccess'] = 0;
$output['message'] = "Wrong username or Password";
}
//get the username
if($conn->rowCount() !==0){
$results=$conn->fetch(PDO::FETCH_OBJ);
//we get both the username and password
$username=$results->username;
$output['isSuccess'] = 1;
$output['message'] = "login sucessful";
$output['username'] = $username;
}
echo json_encode($output);
?>
| true |
03dd848e3a70348055905a7e0f4955cdd083bf5a | PHP | JosueMOsunaG12/CubeSummation | /tests/CubeControllerTest.php | UTF-8 | 3,275 | 2.578125 | 3 | [
"MIT"
] | permissive | <?php
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class CubeControllerTest extends TestCase
{
/**
* A functional test for index.
*
* @return void
*/
public function testIndex()
{
$this->visit('/cube')
->see('Choose a Cube')
->see('Add a Cube')
->see('Upload Cube')
->see('This is an application just to show how the Cube Summation')
->dontSee('Update Cube')
->dontSee('Query Cube')
->dontSee('Blocks for');
}
/**
* Two functional tests for storage.
*
* @return void
*/
public function testStorage()
{
// Test with correct field name
$this->visit('/cube')
->type('First Cube', 'name')
->press('submit-add')
->see('created successfully');
// Test with incorrect field name
$this->visit('/cube')
->press('submit-add')
->see('is required');
}
/**
* A functional test for show.
*
* @return void
*/
public function testShow()
{
$this->visit('/cube/1')
->see('Update Cube')
->see('Query Cube')
->see('Blocks for');
}
/**
* Four functional tests for update.
*
* @return void
*/
public function testUpdate()
{
// Test with correct field name
$this->visit('/cube/1')
->type('3', 'x')
->type('3', 'y')
->type('3', 'z')
->type('1', 'value')
->press('submit-update')
->see('updated successfully');
/*
* Tests with incorrect fields
*/
// Field required
$this->visit('/cube/1')
->press('submit-update')
->see('is required');
// Field must be integer
$this->visit('/cube/1')
->type('1a', 'x')
->press('submit-update')
->see('integer');
// Field value very great
$this->visit('/cube/1')
->type('1000000000', 'y')
->press('submit-update')
->see('greater');
}
/**
* Four functional tests for query.
*
* @return void
*/
public function testQuery()
{
// Test with correct field name
$this->visit('/cube/1')
->type('1', 'x1')
->type('1', 'y1')
->type('1', 'z1')
->type('2', 'x2')
->type('2', 'y2')
->type('2', 'z2')
->press('submit-query')
->see('the sum of: 27');
/*
* Tests with incorrect fields
*/
// Field required
$this->visit('/cube/1')
->press('submit-query')
->see('is required');
// Field must be integer
$this->visit('/cube/1')
->type('1a', 'z1')
->press('submit-query')
->see('integer');
// Field value very great
$this->visit('/cube/1')
->type('10000000', 'z2')
->press('submit-query')
->see('greater');
}
}
| true |
b90b72d8b4657757aa84e258b60c9f435858be4f | PHP | takumi-okada8817/portfolio | /index.php | UTF-8 | 8,603 | 2.5625 | 3 | [] | no_license | <?php
//ログイン画面
//エラー表示(開発時のみ)
ini_set('display_errors',1);
error_reporting(E_ALL);
require_once('function.php');
if(isset($_POST['login'])){
//セッションスタート
session_start();
//入力値のサニタイズ
$clean = array();
if(isset($_POST)){
foreach($_POST as $key => $value){
$clean[$key] = htmlspecialchars($value,ENT_QUOTES);
}
}
$useridentify = $clean['useridentify'];
$loginpassword = $clean['loginpassword'];
//有効なメールアドレスかどうかのフィルター
$clean_email = $useridentify;
if($_POST['useridentify'] === $clean_email && filter_var($clean_email,FILTER_VALIDATE_EMAIL)){
$valid_identify = $useridentify;
}else if($_POST['useridentify'] === '' || !preg_match("/[^\s ]/", $_POST['useridentify'])){
$error_message = '未入力または空白を除いて入力してください';
}else{
$error_message = "このメールアドレスは有効ではありません";
}
try{
$dbh = new PDO('データベース情報');
$dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
$error_message = 'データベースに接続失敗'.PHP_EOL;
return $e->getMessage();
}
if(isset($valid_identify)){
try{
$sql = 'select * from users where identify = :valid_identify';
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':valid_identify',$valid_identify);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
}catch(Exception $e){
return $e->getMessage().PHP_EOL;
}
}
//DBにメールアドレスがあるかの確認
if(!isset($result['identify'])){
$error_message = 'メールアドレスが間違っている可能性があります';
$result['password'] = null;
}
//パスワードの認証
if(password_verify($loginpassword,$result['password'])){
session_regenerate_id(true);
$_SESSION['name'] = $result['username'];
$_SESSION['email'] = $result['identify'];
setcookie('useridentify',$result['identify'],time()+60*60*24*7); //HttpOnlyを属性に追加してIDを盗まれる危険性を減らす
header('Location: http://localhost:8000/timeline.php'); //普通は直書きしない
exit();
}else if($_POST['useridentify'] === '' || !preg_match("/[^\s ]/", $_POST['useridentify'])){
$error_message = '未入力または空白を除いて入力してください';
}else{
$error_message = 'メールアドレスまたはパスワードが間違っています';
}
}
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Find a small happiness</title>
<link rel="stylesheet" href="css/style.css">
<link rel="icon" type="image/x-icon" href="images/round_flight_takeoff_black_24dp.png">
<link href="https://fonts.googleapis.com/css2?family=M+PLUS+Rounded+1c:wght@300&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Courier+Prime:ital@1&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=M+PLUS+Rounded+1c:wght@300&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Sawarabi+Mincho&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Work+Sans&display=swap" rel="stylesheet">
</head>
<body>
<header>
<a id="title">
<h1>Find a small happiness</h1>
</a>
</header>
<div class="wrapper">
<main id="main">
<div id="contents">
<div id="registration">
<h1>Find a small happiness</h1>
<div id="contentsform">
<form action="index.php" method="POST" name="loginform">
<div id="form">
<div id="useridentify">
<label>メールアドレス<br>
<input type="text" name="useridentify">
<span style="display: none; color: rgb(255, 82, 82);"></span>
<span class="e-msg"><?php if(isset($error_message)){echo $error_message;} ?></span>
</label>
</div>
<div id="password">
<label>パスワード<br>
<input type="password" name="loginpassword" required>
<span style="display: none; color: rgb(255, 82, 82);"></span>
<span class="e-msg"><?php if(isset($error_message)){echo $error_message;}?></span>
</label>
</div>
</div>
<div id="submit">
<button type="submit" name="login" disabled="disabled">ログイン</button>
</div>
</form>
</div>
</div>
<div id="tosignIn">
<p>アカウントを登録されますか?<a href="signIn.php" >新規登録する</a></p>
</div>
</div>
<br>
<br>
<br>
</main>
</div>
<footer class="footer">
<div>
<div class="footerrow">
<div class="footernav">
<a href="">
<div>Find a small happinessについて</div>
</a>
</div>
<div class="footernav">
<a href="">
<div>利用規約</div>
</a>
</div>
<div class="footernav">
<a href="">
<div>データに関するポリシー</div>
</a>
</div>
<div class="footernav">
<a href="">
<div>ヘルプ</div>
</a>
</div>
</div>
<div id="borderline"></div>
<div class="footerrow">
<div id="language">
<span>
<select>
<option value="jp">日本語</option>
<option value="en">English</option>
</select>
</span>
</div>
<div id="copyright">©Find a small happiness. All rights reserved. </div>
</div>
</div>
</footer>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="javascript/logincheck.js"></script>
<script>
$('input[name="useridentify"],input[name="loginpassword"]').on('keyup',()=>{
var value = $('input[name="useridentify"],input[name="loginpassword"]').val();
if($('input[name="useridentify"]').val() === "" || $('input[name="loginpassword"]').val() === "" || !value.match(/[^\s\t]/)){
$('button[name="login"]').prop("disabled",true);
}else{
$('button[name="login"]').removeAttr('disabled');
}
});
</script>
</body>
</html> | true |
c0b404962d03d92180b6ee930c77abb2f19e4a06 | PHP | cravler/CravlerRemoteBundle | /Service/RoomsChain.php | UTF-8 | 653 | 2.796875 | 3 | [
"MIT"
] | permissive | <?php
namespace Cravler\RemoteBundle\Service;
use Cravler\RemoteBundle\Room\RoomInterface;
/**
* @author Sergei Vizel <sergei.vizel@gmail.com>
*/
class RoomsChain
{
/**
* @var array
*/
private $rooms = array();
/**
* @param $room
*/
public function addRoom($room)
{
if ($room instanceof RoomInterface) {
$this->rooms[$room->getId()] = $room;
}
}
/**
* @param $key
* @return mixed
*/
public function getRoom($key)
{
return $this->rooms[$key];
}
/**
* @return array
*/
public function getRooms()
{
return $this->rooms;
}
}
| true |
09a3b8972fde6a01cab5725001481e93deae3b41 | PHP | iamandrewluca/psms | /app/Handlers/FakeGuzzleHandler.php | UTF-8 | 5,122 | 2.546875 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: andreiluca
* Date: 1/15/18
* Time: 01:45
*/
namespace App\Handlers;
use GuzzleHttp\Promise\Promise;
use GuzzleHttp\Psr7\Response;
use Illuminate\Http\JsonResponse;
use Psr\Http\Message\RequestInterface;
class FakeGuzzleHandler
{
/**
* @param RequestInterface $request
* @param $options
* @return Promise
*/
public function __invoke(RequestInterface $request, $options)
{
$promise = new Promise(function () use ($request, &$promise) {
$promise->resolve($this->getResponse($request));
});
return $promise;
}
/**
* @param RequestInterface $request
* @return Response|string
*/
private function getResponse(RequestInterface $request)
{
$path = $request->getUri()->getPath();
switch ($path)
{
// WEB
case '/webAuthorize': return $this->webAuthorize();
case '/smsAuthorize': return $this->smsAuthorize();
case '/webValidatePin': return $this->webValidatePin();
// MOBILE
case '/wapIdentifyUser': return $this->wapIdentifyUser();
case '/getUser': return $this->getUser();
case '/wapAuthorize': return $this->wapAuthorize();
// SOME COUNTRIES
case '/paymentAuthorize': return $this->paymentAuthorize();
// COMMON
case '/checkStatus': return $this->checkStatus();
case '/preparePayment': return $this->preparePayment();
case '/commitPayment': return $this->commitPayment();
case '/getSubscription': return $this->getSubscription();
case '/closeSubscription': return $this->closeSubscription();
default: return JsonResponse::create(["Nothing to see here"]);
}
}
// WEB
private function webAuthorize() {
return JsonResponse::create([
'resultCode' => 100,
'resultText' => '',
'sessionId' => '123',
'redirectURL' => '/webhooks/redirect',
'operatorCode' => ''
]);
}
private function smsAuthorize() {
return JsonResponse::create([
'resultCode' => 100,
'resultText' => '',
'sessionId' => '123',
'redirectURL' => '/webhooks/redirect',
'operatorCode' => ''
]);
}
private function webValidatePin() {
return JsonResponse::create([
'resultCode' => 100,
'resultText' => '',
]);
}
// MOBILE
private function wapIdentifyUser() {
return JsonResponse::create([
'resultCode' => 100,
'resultText' => '',
'uid' => 1,
'redirectURL' => '/webhooks/redirect',
'operatorCode' => ''
]);
}
private function wapAuthorize() {
return JsonResponse::create([
'resultCode' => 100,
'resultText' => '',
'sessionId' => '123',
'redirectURL' => '/webhooks/redirect',
'operatorCode' => ''
]);
}
private function getUser() {
return JsonResponse::create([
'resultCode' => 100,
'resultText' => '',
'user' => [
'status' => '',
'userIP' => '',
'msisdn' => '',
'operatorCode' => '',
]
]);
}
// SOME
private function paymentAuthorize() {
return JsonResponse::create([
'resultCode' => 100,
'resultText' => '',
'sessionId' => '123',
'redirectURL' => '/webhooks/redirect',
'operatorCode' => ''
]);
}
// COMMON
private function checkStatus() {
return JsonResponse::create([
'resultCode' => 100,
'resultText' => '',
'statusNumber' => 1,
'statusText' => ''
]);
}
private function preparePayment() {
return JsonResponse::create([
'resultCode' => 100,
'resultText' => '',
'trid' => 1,
]);
}
private function commitPayment() {
return JsonResponse::create([
'resultCode' => 100,
'resultText' => '',
'msisdn' => '1234',
]);
}
private function getSubscription() {
return JsonResponse::create([
'resultCode' => 100,
'resultText' => '',
'subscription' => [
'subscriptionId' => '',
'msisdn' => '',
'operatorCode' => '',
'statusNumber' => 100,
'statusText' => '',
'recurrent' => 1,
'paymentType' => '',
'timeOpen' => 123,
'timeAuthorized' => 123,
'timeRenewal' => 123,
],
]);
}
private function closeSubscription() {
return JsonResponse::create([
'resultCode' => 100,
'resultText' => '',
]);
}
}
| true |
aabaa2a6fcf3b65c50eb2d365b73296204e11ca8 | PHP | dcods22/ElectricAthletics | /php/search.php | UTF-8 | 2,598 | 2.890625 | 3 | [] | no_license | <?php
class SearchController
{
private $dbconn;
private $table;
function __construct($tablename, $dbname = 'blogdatabase', $dblogin = 'dancody', $dbpass = 'tino24', $url = 'electricathleticscom.ipagemysql.com')
{
$this->dbconn = new PDO("mysql:host=$url;dbname=$dbname", "$dblogin", "$dbpass");
$this->tablename = $tablename;
}
function searchArticles($search){
$search = '%' . $search . '%';
$sql = "SELECT `id`, `typeID`, `pic`, `title` FROM `blogs` WHERE `title` LIKE :search";
$statement = $this->dbconn->prepare($sql);
$statement->bindValue(':search', $search);
$statement->execute();
$entry = $statement->fetchall(PDO::FETCH_ASSOC);
echo json_encode($entry);
}
function searchTags($search){
$articles = array();
$articlesFinal = array();
$search = '%' . $search . '%';
$sql = "SELECT `tagID` FROM `tagList` WHERE `tag` LIKE :search";
$statement = $this->dbconn->prepare($sql);
$statement->bindValue(':search', $search);
$statement->execute();
$IDs = $statement->fetchall(PDO::FETCH_ASSOC);
foreach($IDs as $ID){
$sql2 = "SELECT `articleID` FROM `tags` WHERE tagID=:ID";
$stmt = $this->dbconn->prepare($sql2);
$stmt->bindValue(':ID', $ID[tagID]);
$stmt->execute();
$entry = $stmt->fetchall(PDO::FETCH_ASSOC);
$articles = array_merge($articles, $entry);
}
foreach($articles as $artID){
$sql3 = "SELECT `id`, `typeID`,`pic`, `title` FROM `blogs` WHERE id=:artID";
$stmt2 = $this->dbconn->prepare($sql3);
$stmt2->bindValue(':artID', $artID[articleID]);
$stmt2->execute();
$art = $stmt2->fetchall(PDO::FETCH_ASSOC);
$articlesFinal = array_merge($articlesFinal, $art);
}
echo json_encode($articlesFinal);
}
function searchUsers($search){
$search = '%' . $search . '%';
$sql = "SELECT `id`, `email`, `username`, `avatar` FROM `Users` WHERE `username` LIKE :search";
$statement = $this->dbconn->prepare($sql);
$statement->bindValue(':search', $search);
$statement->execute();
$entry = $statement->fetchall(PDO::FETCH_ASSOC);
echo json_encode($entry);
}
}
$type = $_GET['type'];
$query = $_GET['query'];
$searchController = new SearchController('Users');
if($type == "article"){
$searchController->searchArticles($query);
}else if($type == "tag"){
$searchController->searchTags($query);
}else if($type == "user"){
$searchController->searchUsers($query);
}
| true |
b7ae0db1fc2155bb526c7604fbc621a3333caa12 | PHP | zyl6868/bh | /common/clients/UserService.php | UTF-8 | 2,927 | 2.609375 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
declare(strict_types = 1);
/**
* Created by PhpStorm.
* User: liuxing
* Date: 17-10-16
* Time: 下午4:00
*/
namespace common\clients;
use common\components\MicroServiceRequest;
use common\components\WebDataKey;
use Httpful\Mime;
use Yii;
use yii\db\Exception;
class UserService
{
/**
* @var null
*/
private $uri = null;
private $microServiceRequest = null;
private $host = null;
/**
* TestMicroService constructor.
*/
public function __construct()
{
$this->uri = Yii::$app->params['microService'];
$this->host = 'user-base-service';
$this->microServiceRequest = new MicroServiceRequest($this->host);
}
/**
* 获取用户默认的版本信息
* @param integer $userId
* @return array|object|string
* @throws \Httpful\Exception\ConnectionErrorException
*/
public function getTeacherBookVersion(int $userId)
{
$result = $this->microServiceRequest->get($this->uri . '/v1/teacher/' . $userId . '/book/version')
->sendsType(Mime::JSON)
->expectsType(Mime::JSON)
->send();
return $result;
}
/**
* 保存用户默认的版本信息
* @param int $userId
* @param int $subjectId
* @param int $versionId
* @param int $departmentId
* @param int $tomeId
* @return \Httpful\associative|string
* @throws \Httpful\Exception\ConnectionErrorException
*/
public function saveTeacherBookVersion(int $userId, int $subjectId, int $versionId, int $departmentId, int $tomeId)
{
$result = $this->microServiceRequest->post($this->uri . '/v1/teacher/book/version')
->body(http_build_query(['user-id' => $userId, 'subject-id' => $subjectId, 'version' => $versionId, 'department' => $departmentId, 'tome' => $tomeId]))
->sendsType(Mime::FORM)
->send();
return $result;
}
/**
* 根据用户名查询用户信息
* @param string $userName
* @return \Httpful\associative|string
* @throws \Httpful\Exception\ConnectionErrorException
*/
public function getUserInfoByUserName(string $userName)
{
$result = $this->microServiceRequest->get($this->uri . '/v1/user/info/user-name?'. http_build_query(['user-name' => $userName]))
->sendsType(Mime::JSON)
->send();
return $result;
}
/**
*验证用户访问权限 id和token是否匹配
* @param int $userId
* @param string $token
* @return \Httpful\associative|string
* @throws \Httpful\Exception\ConnectionErrorException
*/
public function verifyUserToken(int $userId,string $token)
{
$result = $this->microServiceRequest->get($this->uri . '/v1/'.$userId.'/token/'.$token.'/verify')
->sendsType(Mime::JSON)
->send();
return $result;
}
} | true |
ee2715e0ba2119811d65cb7fff1e92abc968e20a | PHP | loovien/shangjialian | /app/Utils/WxUtils.php | UTF-8 | 2,681 | 2.640625 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: luowen
* Date: 2017/3/20
* Time: 22:05
*/
namespace App\Utils;
final class WxUtils
{
use SingletonTrait;
/*
* wechat app id
*/
const WX_APPID = "wx41680155348354c9";
/*
* wechat secret
*/
const WX_SECRET = "4bd4ceaaeaab5b46c2e2a020c48f1119";
/*
* base scope
*/
const WX_SNSAPI_BASE_SCOPE = "snsapi_base";
/*
* userinfo scope
*/
const WX_SNSAPI_USERINFO_SCOPE = "snsapi_userinfo";
/*
* get wechat access_token api
*/
const WX_CLIENT_ACCESS_TOKEN = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s';
/*
* wechat ask user to authenticate uri
*/
const WX_AUTH_URI = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&response_type=code&scope=%s&state=STATE";
/*
* wechat js ticket url
*/
const WX_JSTICKET_URL = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi';
/*
* wechat get access token uri
*/
const WX_ACCESS_TOKEN_URI = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code';
const WX_JS_API_URL = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi';
public static function getInstance() { }
/**
* get wechat redirect url
*
* @return string
*/
public static function getRedirectUri()
{
return sprintf(self::WX_AUTH_URI, self::WX_APPID, self::WX_SNSAPI_BASE_SCOPE);
}
/**
* use wechat server callback's code to get visitor's openid
*
* @param string $code
* @return null
*/
public static function getWxOpenId($code = '')
{
$accessTokenUrl = sprintf(self::WX_ACCESS_TOKEN_URI, self::WX_APPID, self::WX_SECRET, $code);
$resultSet = json_decode(HttpUtil::get($accessTokenUrl), true);
if(!isset($resultSet['openid']))
return null;
return $resultSet;
}
/**
* obtain access_token url
*
* @return string
*/
public static function getAccessTokenUrl()
{
return sprintf(self::WX_CLIENT_ACCESS_TOKEN, self::WX_APPID, self::WX_SECRET);
}
/**
* acquire wechat javascript ticket url
*
* @param string $accessToken
* @return string
*/
public static function getJsTicketUrl($accessToken = '')
{
return sprintf(self::WX_JSTICKET_URL, $accessToken);
}
/**
* acquire wechat appId
*
* @return string
*/
public static function getAppId()
{
return self::WX_APPID;
}
} | true |
4eb12a560e336926ec0a3129e69d935ba6fc3587 | PHP | spryker/git-hook | /src/GitHook/Command/FileCommand/PreCommit/ArchitectureSniff/ArchitectureSniffConfiguration.php | UTF-8 | 740 | 2.625 | 3 | [
"MIT"
] | permissive | <?php
/**
* MIT License
* For full license information, please view the LICENSE file that was distributed with this source code.
*/
namespace GitHook\Command\FileCommand\PreCommit\ArchitectureSniff;
class ArchitectureSniffConfiguration
{
/**
* @var array
*/
protected $config;
/**
* @param array $config
*/
public function __construct(array $config)
{
$this->config = $config;
}
/**
* @return int
*/
public function getMinimumPriority(): int
{
$defaultPriority = 2;
if (!$this->config) {
return $defaultPriority;
}
return (isset($this->config['priority'])) ? $this->config['priority'] : $defaultPriority;
}
}
| true |
bc577ba52d9006f19a6b0c7bbf596e6f94b6bf51 | PHP | tiagofrancafernandes/teste-api-enderecos | /docker-php7.4_laravel-pgsql-mysql/public/pdo_test.php | UTF-8 | 1,343 | 2.75 | 3 | [] | no_license | <?php
$type = 'mysql'; //mysql/postgres
$pdo_config = [
'pgsql' => [
'driver' => 'pgsql',
'host' => '127.0.0.1',
'port' => 5432,
'user' => 'postgres',
'password' => 'postgres',
'database' => 'postgres',
'more' => '',
],
'mysql' => [
'driver' => 'mysql',
'host' => 'mysql',
'port' => 3306,
'user' => 'root',
'password' => 'mysql',
'database' => 'mysql',
'more' => '',
],
];
$driver = $pdo_config[$type]['driver'] ?? '';
$host = $pdo_config[$type]['host'] ?? '';
$port = $pdo_config[$type]['port'] ?? '';
$database = $pdo_config[$type]['database'] ?? '';
$user = $pdo_config[$type]['user'] ?? '';
$password = $pdo_config[$type]['password'] ?? '';
$more = $pdo_config[$type]['more'] ?? '';
try {
$dsn = "$driver:host=$host;port=$port;dbname=$database;$more";
// make a database connection
$pdo = new PDO(
$dsn,
$user,
$password,
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);
if ($pdo)
echo "<pre>\nConnected to the $database database successfully!</pre>";
} catch (PDOException $e)
{
die($e->getMessage());
}
| true |
2d85a1bdccc18800325f5642c124df0423ab1ce5 | PHP | sitedata/panel | /tests/Integration/Api/Client/ClientControllerTest.php | UTF-8 | 5,805 | 2.515625 | 3 | [
"MIT",
"Apache-2.0"
] | permissive | <?php
namespace Pterodactyl\Tests\Integration\Api\Client;
use Pterodactyl\Models\User;
use Pterodactyl\Models\Server;
use Pterodactyl\Models\Subuser;
use Pterodactyl\Models\Permission;
class ClientControllerTest extends ClientApiIntegrationTestCase
{
/**
* Test that only the servers a logged in user is assigned to are returned by the
* API endpoint. Obviously there are cases such as being an administrator or being
* a subuser, but for this test we just want to test a basic scenario and pretend
* subusers do not exist at all.
*/
public function testOnlyLoggedInUsersServersAreReturned()
{
/** @var \Pterodactyl\Models\User[] $users */
$users = factory(User::class)->times(3)->create();
/** @var \Pterodactyl\Models\Server[] $servers */
$servers = [
$this->createServerModel(['user_id' => $users[0]->id]),
$this->createServerModel(['user_id' => $users[1]->id]),
$this->createServerModel(['user_id' => $users[2]->id]),
];
$response = $this->actingAs($users[0])->getJson('/api/client');
$response->assertOk();
$response->assertJsonPath('object', 'list');
$response->assertJsonPath('data.0.object', Server::RESOURCE_NAME);
$response->assertJsonPath('data.0.attributes.identifier', $servers[0]->uuidShort);
$response->assertJsonPath('data.0.attributes.server_owner', true);
$response->assertJsonPath('meta.pagination.total', 1);
$response->assertJsonPath('meta.pagination.per_page', config('pterodactyl.paginate.frontend.servers'));
}
/**
* Tests that all of the servers on the system are returned when making the request as an
* administrator and including the ?filter=all parameter in the URL.
*/
public function testFilterIncludeAllServersWhenAdministrator()
{
/** @var \Pterodactyl\Models\User[] $users */
$users = factory(User::class)->times(3)->create();
$users[0]->root_admin = true;
$servers = [
$this->createServerModel(['user_id' => $users[0]->id]),
$this->createServerModel(['user_id' => $users[1]->id]),
$this->createServerModel(['user_id' => $users[2]->id]),
];
$response = $this->actingAs($users[0])->getJson('/api/client?filter=all');
$response->assertOk();
$response->assertJsonCount(3, 'data');
for ($i = 0; $i < 3; $i++) {
$response->assertJsonPath("data.{$i}.attributes.server_owner", $i === 0);
$response->assertJsonPath("data.{$i}.attributes.identifier", $servers[$i]->uuidShort);
}
}
/**
* Test that servers where the user is a subuser are returned by default in the API call.
*/
public function testServersUserIsASubuserOfAreReturned()
{
/** @var \Pterodactyl\Models\User[] $users */
$users = factory(User::class)->times(3)->create();
$servers = [
$this->createServerModel(['user_id' => $users[0]->id]),
$this->createServerModel(['user_id' => $users[1]->id]),
$this->createServerModel(['user_id' => $users[2]->id]),
];
// Set user 0 as a subuser of server 1. Thus, we should get two servers
// back in the response when making the API call as user 0.
Subuser::query()->create([
'user_id' => $users[0]->id,
'server_id' => $servers[1]->id,
'permissions' => [Permission::ACTION_WEBSOCKET_CONNECT],
]);
$response = $this->actingAs($users[0])->getJson('/api/client');
$response->assertOk();
$response->assertJsonCount(2, 'data');
$response->assertJsonPath('data.0.attributes.server_owner', true);
$response->assertJsonPath('data.0.attributes.identifier', $servers[0]->uuidShort);
$response->assertJsonPath('data.1.attributes.server_owner', false);
$response->assertJsonPath('data.1.attributes.identifier', $servers[1]->uuidShort);
}
/**
* Returns only servers that the user owns, not servers they are a subuser of.
*/
public function testFilterOnlyOwnerServers()
{
/** @var \Pterodactyl\Models\User[] $users */
$users = factory(User::class)->times(3)->create();
$servers = [
$this->createServerModel(['user_id' => $users[0]->id]),
$this->createServerModel(['user_id' => $users[1]->id]),
$this->createServerModel(['user_id' => $users[2]->id]),
];
// Set user 0 as a subuser of server 1. Thus, we should get two servers
// back in the response when making the API call as user 0.
Subuser::query()->create([
'user_id' => $users[0]->id,
'server_id' => $servers[1]->id,
'permissions' => [Permission::ACTION_WEBSOCKET_CONNECT],
]);
$response = $this->actingAs($users[0])->getJson('/api/client?filter=owner');
$response->assertOk();
$response->assertJsonCount(1, 'data');
$response->assertJsonPath('data.0.attributes.server_owner', true);
$response->assertJsonPath('data.0.attributes.identifier', $servers[0]->uuidShort);
}
/**
* Tests that the permissions from the Panel are returned correctly.
*/
public function testPermissionsAreReturned()
{
/** @var \Pterodactyl\Models\User $user */
$user = factory(User::class)->create();
$this->actingAs($user)
->getJson('/api/client/permissions')
->assertOk()
->assertJson([
'object' => 'system_permissions',
'attributes' => [
'permissions' => Permission::permissions()->toArray(),
],
]);
}
}
| true |
4fe4de47bf2f306532ffcef13f0986ad748e7d65 | PHP | trailburning/tb-api | /src/AppBundle/Repository/UserRepository.php | UTF-8 | 975 | 2.515625 | 3 | [] | no_license | <?php
namespace AppBundle\Repository;
use AppBundle\Entity\User;
class UserRepository extends BaseRepository
{
/**
* @param int $limit
*
* @return User[]
*/
public function findLatestActiveWithAvatar($limit = 10): array
{
$clientId = 'race_base';
$qb = $this->getQB();
$qb->andWhere('u.client = :client_id');
$qb->setParameter('client_id', $clientId);
$qb->andWhere('u.enabled = true');
$qb->addOrderBy('u.registeredAt', 'DESC');
$qb->setMaxResults($limit);
$result = $qb->getQuery()->getResult();
return $result;
}
/**
* @return int
*/
public function getUserCount()
{
$qb = $this->getQB()
->select('count(u.id)')
->andWhere('u.client = :client')
->setParameter('client', 'race_base')
->andWhere('u.enabled = true');
return $qb->getQuery()->getSingleScalarResult();
}
}
| true |
b96272de4d0195faceee9a967686ab253a9a4a3c | PHP | kikipermana17/latihan-git | /rekursif/latihan/latihan1.php | UTF-8 | 1,004 | 3.109375 | 3 | [] | no_license | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<fieldset>
<legend>Perhitungsn</legend>
<form action=" " method="post">
<tr>
<th>Masukan Bilangan</th>
<td>: <input type="text" name="bil"></td>
</tr>
<tr>
<th>Masukan Pangkat</th>
<td>: <input type="text" name="pangkat"></td>
</tr><br>
<input type="submit" name="save">
</form>
</fieldset>
</body>
</html>
<?php
if (isset($_POST['save'])){
$a = $_POST['bil'];
$b = $_POST['pangkat'];
}
function faktorial(){
if ($a > 2) {
return $a * faktorial($a - 1);
}else{
return $a;
}
}
$hasil = faktorial(5);
echo $hasil;
?> | true |
86894760201e0f19d6b3ed9b67baeb1addaa47c0 | PHP | kvu-luong/data_web2 | /model/CategoryModel.php | UTF-8 | 604 | 3.03125 | 3 | [] | no_license | <?php
class CategoryModel{
var $category_id ;
var $categoryName;
function __construct($category_id, $categoryName) {
$this->category_id = $category_id;
$this->categoryName = $categoryName;
}
function getCategory_id() {
return $this->category_id;
}
function getCategoryName() {
return $this->categoryName;
}
function setCategory_id($category_id) {
$this->category_id = $category_id;
}
function setCategoryName($categoryName) {
$this->categoryName = $categoryName;
}
}
| true |
9d8035ed6f0e981c7385f8b91feb906b2d4f263f | PHP | algo26-matthias/phlymail | /phlymail/shared/lib/phlyDAV/Locks.php | UTF-8 | 4,352 | 2.765625 | 3 | [] | no_license | <?php
/**
* extending functionality for SabreDAV
* @package phlyMail Nahariya 4.0+ Default branch
* @subpackage WebDAV server
* @copyright 2009-2015 phlyLabs, Berlin (http://phlylabs.de)
* @version 0.0.3 2015-03-12
*/
class phlyDAV_Locks extends Sabre_DAV_Locks_Backend_Abstract {
/**
* The DB connection object
*
* @var $DB
*/
protected $DB;
public function __construct()
{
$this->DB = &$GLOBALS['DB'];
$this->DB->Tbl['core_lock'] = '`'.$this->DB->DB['database'].'`.`'.$this->DB->DB['prefix'].'_core_lock`';
}
/**
* Returns a list of Sabre_DAV_Locks_LockInfo objects
*
* This method should return all the locks for a particular uri, including
* locks that might be set on a parent uri.
*
* If returnChildLocks is set to true, this method should also look for
* any locks in the subtree of the uri for locks.
*
* @param string $uri
* @param bool $returnChildLocks
* @return array
*/
public function getLocks($uri, $returnChildLocks)
{
$query = 'SELECT `owner`,`token`,`timeout`,`created`,`scope`,`depth`,`uri` FROM '. $this->DB->Tbl['core_lock']
.' WHERE ((`created` + `timeout`) > CAST('.time().' AS UNSIGNED INTEGER)) AND ((`uri`="'.$this->DB->esc($uri).'")';
// We need to check locks for every part in the uri.
$uriParts = explode('/', $uri);
// We already covered the last part of the uri
array_pop($uriParts);
$currentPath = '';
foreach ($uriParts as $part) {
if ($currentPath) {
$currentPath .= '/';
}
$currentPath .= $part;
$query.=' OR (`depth`!=0 AND `uri`="'.$this->DB->esc($currentPath).'")';
}
if ($returnChildLocks) {
$query .= ' OR (`uri` LIKE "'.$this->DB->esc($uri).'/%")';
}
$query .= ')';
$qid = $this->DB->query($query);
$lockList = array();
while ($row = $this->DB->fetchassoc($qid)) {
$lockInfo = new Sabre_DAV_Locks_LockInfo();
foreach ($row as $k => $v) {
$lockInfo->$k = $v;
}
$lockList[] = $lockInfo;
}
return $lockList;
}
/**
* Locks a uri
*
* @param string $uri
* @param Sabre_DAV_Locks_LockInfo $lockInfo
* @return bool
*/
public function lock($uri, Sabre_DAV_Locks_LockInfo $lockInfo)
{
// We're making the lock timeout 30 minutes
$lockInfo->timeout = 30*60;
$lockInfo->created = time();
$lockInfo->uri = $uri;
$locks = $this->getLocks($uri, false);
$exists = false;
foreach ($locks as $lock) {
if ($lock->token == $lockInfo->token) {
$exists = true;
}
}
if ($exists) {
$query = 'UPDATE '. $this->DB->Tbl['core_lock']
.' SET `owner`="'.$this->DB->esc($lockInfo->owner).'"'
.',`timeout`='.intval($lockInfo->timeout)
.',`scope`='.intval($lockInfo->scope)
.',`depth`='.intval($lockInfo->depth)
.',`uri`="'.$this->DB->esc($uri).'"'
.',`created`='.intval($lockInfo->created)
.' WHERE `token`="'.$this->DB->esc($lockInfo->token).'"';
} else {
$query = 'INSERT INTO '. $this->DB->Tbl['core_lock']
.' SET `owner`="'.$this->DB->esc($lockInfo->owner).'"'
.',`timeout`='.intval($lockInfo->timeout)
.',`scope`='.intval($lockInfo->scope)
.',`depth`='.intval($lockInfo->depth)
.',`uri`="'.$this->DB->esc($uri).'"'
.',`created`='.intval($lockInfo->created)
.',`token`="'.$this->DB->esc($lockInfo->token).'"';
}
return $this->DB->query($query);
}
/**
* Removes a lock from a uri
*
* @param string $uri
* @param Sabre_DAV_Locks_LockInfo $lockInfo
* @return bool
*/
public function unlock($uri, Sabre_DAV_Locks_LockInfo $lockInfo)
{
$query = 'DELETE FROM '. $this->DB->Tbl['core_lock'].' WHERE `uri`="'.$this->DB->esc($uri).'" AND `token`="'.$this->DB->esc($lockInfo->token).'"';
return $this->DB->query($query);
}
}
| true |
c11af192a5c19d673f69fc214b0cab0a915f2544 | PHP | nilsenj/storecamp | /app/Core/Transformers/LayoutTransformer.php | UTF-8 | 641 | 2.59375 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Core\Transformers;
use League\Fractal\TransformerAbstract;
use App\Core\Models\Layout;
/**
* Class LayoutTransformer
* @package namespace App\Core\Transformers;
*/
class LayoutTransformer extends TransformerAbstract
{
/**
* Transform the \Layout entity
* @param \Layout $model
*
* @return array
*/
public function transform(Layout $model)
{
return [
'id' => (int) $model->id,
/* place your other model properties here */
'created_at' => $model->created_at,
'updated_at' => $model->updated_at
];
}
}
| true |
6325fe2c063502b6d8f74284d51ce6802905f579 | PHP | nguaki/PHP | /PHPUNIT/jeffreyway/tips-tricks-pitfalls/tests/MockTest.php | UTF-8 | 942 | 3.3125 | 3 | [] | no_license | <?php
class MockTest extends PHPUnit_Framework_TestCase
{
public function test_mockery()
{
//Nov 12, 2018
//Mocking is a way to fake calling.
//This is not a good example of mocking.
//A good example is as follows:Lets say you need to test
//a method which inserts a row of a new user and send an
//email to the user. We don't want to sent an email to a new user.
//But we still need to test the function.
//So we can actually call the function and skip sending an email line.
$mock = Mockery::mock('acme\Bar');
//Run once and let it return a string.
//This example doesn't test the real code.
//So I think this is a waste of testing but for the sake of learning mocking, it is here.
$mock->shouldReceive('run')->once()->andReturn('mocked');
$this->assertEquals( 'mocked', $mock->run() );
//This is the actual source code.
$this->assertEquals( 'running from Bar', (new acme\Bar)->run());
}
}
?> | true |
59ea1bca94040b36246db5e57168a3d6aab2e6e9 | PHP | anthony39100/cinema | /src/Entity/Acteur.php | UTF-8 | 2,488 | 2.59375 | 3 | [] | no_license | <?php
namespace App\Entity;
use App\Repository\ActeurRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass=ActeurRepository::class)
*/
class Acteur
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
*/
private $name;
/**
* @ORM\Column(type="string", length=255)
*/
private $description;
/**
* @ORM\Column(type="string", length=255)
*/
private $photo;
/**
* @ORM\Column(type="datetime")
*/
private $dateAnniversaire;
/**
* @ORM\ManyToMany(targetEntity=Films::class, mappedBy="Acteurs")
*/
private $Acteurs;
public function __construct()
{
$this->Acteurs = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(string $description): self
{
$this->description = $description;
return $this;
}
public function getPhoto(): ?string
{
return $this->photo;
}
public function setPhoto(string $photo): self
{
$this->photo = $photo;
return $this;
}
public function getDateAnniversaire(): ?\DateTimeInterface
{
return $this->dateAnniversaire;
}
public function setDateAnniversaire(\DateTimeInterface $dateAnniversaire): self
{
$this->dateAnniversaire = $dateAnniversaire;
return $this;
}
/**
* @return Collection|Films[]
*/
public function getActeurs(): Collection
{
return $this->Acteurs;
}
public function addActeur(Films $acteur): self
{
if (!$this->Acteurs->contains($acteur)) {
$this->Acteurs[] = $acteur;
$acteur->addActeur($this);
}
return $this;
}
public function removeActeur(Films $acteur): self
{
if ($this->Acteurs->removeElement($acteur)) {
$acteur->removeActeur($this);
}
return $this;
}
}
| true |
cc931e593057c35f0cd4d8ef5040c86dc5dc625d | PHP | SergSad/prize | /models/UserPrizes.php | UTF-8 | 2,021 | 2.6875 | 3 | [] | permissive | <?php
declare(strict_types=1);
namespace app\models;
use Yii;
use yii\db\ActiveQuery;
/**
* This is the model class for table "user_prizes".
*
* @property int $id
* @property int $user_id
* @property string $prize_type
* @property boolean $is_send
*
* @property ActiveQuery $prize
* @property User $user
*/
class UserPrizes extends \yii\db\ActiveRecord {
const ATTR_ID = 'id';
const ATTR_USER_ID = 'user_id';
const ATTR_PRIZE_TYPE = 'prize_type';
const ATTR_IS_SEND = 'is_send';
/**
* {@inheritdoc}
*/
public static function tableName() {
return 'user_prizes';
}
/**
* {@inheritdoc}
*/
public function rules() {
return [
// Сюда надо константы подставить
[['user_id','prize_type'],'required'],
[['user_id'],'integer'],
[['prize_type'],'string','max' => 255],
[['user_id'],'exist','skipOnError' => true, 'targetClass' => User::className(),
'targetAttribute' => ['user_id' => 'id']
],
['is_send','boolean'],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels() {
// Сюда тоже константы
return [
'id' => 'ID',
'user_id' => 'User ID',
'prize_type' => 'Prize Type',
'is_send' => 'Is Send',
];
}
/**
* @return ActiveQuery
* @throws \Exception
*
* @author Sergey Sadovin <sadovin.serj@gmail.com>
*/
public function getPrize() {
switch ($this->prize_type) {
case PrizeBonus::TYPE:
return $this->hasOne(PrizeBonus::class, ['user_prize_id' => 'id']);
break;
case PrizeMoney::TYPE:
return $this->hasOne(PrizeMoney::class, ['user_prize_id' => 'id']);
break;
case PrizePhysical::TYPE:
return $this->hasOne(PrizePhysical::class, ['user_prize_id' => 'id']);
break;
}
throw new \Exception('Неизвестный тип приза');
}
/**
* Gets query for [[User]].
*
* @return ActiveQuery
*/
public function getUser() {
return $this->hasOne(User::className(), ['id' => 'user_id']);
}
}
| true |
ac78d31d88cf7012378b9d86378141042f1dab78 | PHP | Oskitaa/Velazquez | /Servidor/php/ddbb/login/creaAlumnos/muestraAlumnos.php | UTF-8 | 824 | 2.59375 | 3 | [] | no_license | <?php
require_once('../conexion.php');
print (compareHas("123456","10$614b8e510efc167704a728634b1a7f5f"));
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Muestra Alumnos</title>
</head>
<body>
<?php
$resultado = $conexion->query('SELECT a.nombre,a.apellidos,a.email, c.nombre FROM alumnos a INNER JOIN cursos c ON a.codigo_curso = c.codigo');
while ($registro = $resultado->fetch()) {
print "<p>".$registro[0]. " ".$registro[1]." ".$registro[2]." ".$registro[3]."</p>";
}
?>
<form action="./creaAlumnoForm.php" method="post">
<button type="submit" name="agregarAlumno">Agregar Alumno</button>
</form>
</body>
</html>
<?php
?> | true |
5971a00d124b8db5ca0497d72e7beb4fbfeb59c8 | PHP | 2dq2t/FSMProject | /backend/components/Logger.php | UTF-8 | 7,103 | 2.953125 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
namespace backend\components;
use Yii;
use DateTime;
use RuntimeException;
use yii\helpers;
use yii\helpers\FileHelper;
/**
* Class Logger is contain attributes and functions correlate log
*/
class Logger {
const INFO = 'INFO';
const ERROR = 'ERROR';
const WARNING = 'WARNING';
/**
* This holds the instance's logger
* @var
*/
private static $instance;
/**
* Directory to the logs
* @var string
*/
private $logDirectory;
/**
* Path to the log file
* @var string
*/
private $logFilePath;
/**
* This holds the file handle for this instance's log file
* @var resource
*/
private static $fileHandle;
private $config = [
'extension' => 'txt',
'dateFormat' => 'Y-m-d G:i:s.u',
'prefix' => 'log_'
];
/**
* The construct class logger
*/
public function __construct()
{
if (!$this->logDirectory) {
$this->logDirectory = Yii::getAlias('@backend').DIRECTORY_SEPARATOR. 'logs'.DIRECTORY_SEPARATOR;
if (!file_exists($this->logDirectory)) {
FileHelper::createDirectory($this->logDirectory, 0777);
}
}
// $this->config = array_merge($this->config, $config);
// $this->setLogFilePath($this->logDirectory);
// if(file_exists($this->logFilePath) && !is_writable($this->logFilePath)) {
// throw new RuntimeException(Yii::t('app', 'The file could not be written to. Check that appropriate permissions have been set.'));
// }
// $this->setFileHandle('a');
//
// if ( ! self::$fileHandle) {
// throw new RuntimeException(Yii::t('app', 'The file could not be opened. Check permissions.'));
// }
}
public static function getInstance()
{
if (!self::$instance)
{
self::$instance = new Logger();
}
return self::$instance;
}
/**
* @param string $logDirectory
*/
public function setLogFilePath($logDirectory) {
$this->logFilePath = $logDirectory.DIRECTORY_SEPARATOR.$this->config['prefix'].date('Y-m-d').'.'.$this->config['extension'];
}
public function getLogDirectory(){
return $this->logDirectory;
}
public function setConfig(array $config) {
$this->config = array_merge($this->config, $config);
}
public function getConfig(){
return $this->config;
}
/**
* @param $writeMode
*
* @internal param resource $fileHandle
*/
public function setFileHandle($writeMode) {
self::$fileHandle = fopen($this->logFilePath, $writeMode);
}
/**
* Class destructor
*/
public function __destruct()
{
if (self::$fileHandle) {
fclose(self::$fileHandle);
}
}
/**
* Logs with an arbitrary level.
*
* @param mixed $level
* @param string $message
* @param array $beforeValues
* @param array $afterValues
* @param int $userId
* @return null
*/
public static function log($level, $message, $userId, array $beforeValues = [], array $afterValues = [])
{
self::getInstance()->setLogFilePath(self::getInstance()->logDirectory);
if(file_exists(self::getInstance()->logFilePath) && !is_writable(self::getInstance()->logFilePath)) {
throw new RuntimeException(Yii::t('app', 'The file could not be written to. Check that appropriate permissions have been set.'));
}
self::getInstance()->setFileHandle('a');
if ( ! self::$fileHandle) {
throw new RuntimeException(Yii::t('app', 'The file could not be opened. Check permissions.'));
}
$changeValues = !empty($beforeValues) && !empty($afterValues) ? self::getInstance()->changeValues($beforeValues, $afterValues) : [];
$message = self::getInstance()->formatMessage($level, $message, $userId, $changeValues);
self::write($message);
}
/**
* Writes a line to the log
*
* @param string $message Line to write to the log
* @return void
*/
private function write($message)
{
if (null !== self::$fileHandle) {
if (fwrite(self::$fileHandle, $message) === false) {
throw new RuntimeException(Yii::t('app', 'The file could not be written to. Check that appropriate permissions have been set.'));
} else {
fflush(self::$fileHandle);
}
}
}
private function formatMessage($level, $message, $userId, array $changeValues = [])
{
$message = "[{$this->getTimestamp()}][{$level}]: {$message}, " . Yii::t('app', 'Employee Id: ') . "{$userId}";
if (!empty($changeValues)) {
$message .=", " . Yii::t('app','Changed values: ') . PHP_EOL . $this->indent($this->contextToString($changeValues));
}
return $message.PHP_EOL;
}
/**
* Gets the correctly formatted Date/Time for the log entry.
*
* PHP DateTime is dump, and you have to resort to trickery to get microseconds
* to work correctly, so here it is.
*
* @return string
*/
private function getTimestamp()
{
$originalTime = microtime(true);
$micro = sprintf("%06d", ($originalTime - floor($originalTime)) * 1000000);
$date = new DateTime(date('Y-m-d H:i:s.'.$micro, $originalTime));
return $date->format($this->config['dateFormat']);
}
/**
* Takes the given context and coverts it to a string.
*
* @param array $context The Context
* @return string
*/
private function contextToString($context)
{
$export = '';
foreach ($context as $key => $value) {
$export .= "{$key}: ";
$export .= preg_replace(array(
'/=>\s+([a-zA-Z])/im',
'/array\(\s+\)/im',
'/^ |\G /m'
), array(
'=> $1',
'array()',
' '
), str_replace('array (', '(', var_export($value, true)));
$export .= PHP_EOL;
}
return str_replace(array('\\\\', '\\\''), array('\\', '\''), rtrim($export));
}
/**
* Indents the given string with the given indent.
*
* @param string $string The string to indent
* @param string $indent What to use as the indent.
* @return string
*/
private function indent($string, $indent = ' ')
{
return $indent.str_replace("\n", "\n".$indent, $string);
}
/**
* Gets the change value
*
* @param array $beforeValues
* @param array $afterValues
* @return array
*/
private function changeValues(array $beforeValues, array $afterValues)
{
$different = array_diff_assoc($beforeValues, $afterValues);
$arr = [];
foreach($different as $key => $value) {
$arr[$key] = [$beforeValues[$key] => $afterValues[$key]];
}
return $arr;
}
}
| true |
3742797073e6ab280aae7763fc29d13acda53be3 | PHP | mindXtension/civicracy | /civi-php/protected/views/vote/_path.php | UTF-8 | 1,436 | 2.859375 | 3 | [] | no_license | <?php
/**
* Graphical display of vote path - shows where the user's vote is being delegated to
*
* @param array $votePath array of vote elements, each with realname, slogan, candidate_id, reason
* @param boolean $noSloganChange optional to hide slogan-change button
*/
foreach($votePath as $vote)
{ ?>
<div class="vp-row">
<div class="vp-left">
<img src="<?php echo Yii::app()->request->baseUrl; ?>/img/user_arrows.png" alt="User" />
</div>
<div class="vp-right">
<h5><?php echo CHtml::encode($vote->realname); ?></h5>
<p>
<?php
echo $vote->slogan == '' ? Yii::t('app', 'vote.noslogan') : CHtml::encode($vote->slogan);
echo " ";
if ($vote->candidate_id == Yii::app()->user->id && (!isset($noSloganChange) || $noSloganChange === false))
{
echo "<a class='label label-info' href=".$this->createUrl('user/settings').">".Yii::t('app','vote.changeslogan.button')."</a>";
}
?>
</p>
<?php /* display reason why user votes for him/herself. No nice formatting yet, and slogan fits nicely anyway. */ /* if($vote == end($votePath)) { ?>
<p><?php echo $vote->reason; ?></p>
<?php } */ ?>
</div>
</div>
<?php if($vote !== end($votePath))
{ ?>
<div class="vp-row vp-row-arrow">
<div class="vp-left">
<img src="<?php echo Yii::app()->request->baseUrl; ?>/img/arrow.png" alt="delegiert" />
</div>
<div class="vp-right"><?php echo CHtml::encode($vote->reason); ?></div>
</div>
<?php
} } ?> | true |
0b876e3345fe7bc90a056247777e1492cb830920 | PHP | Boyche/shortenUrlFix | /backend_tests/url_shortener/openUrl.php | UTF-8 | 1,092 | 2.78125 | 3 | [] | no_license | <?php
if(isset($_GET['shortUrl'])){
$url = $_GET['shortUrl'];
require_once('functions.php');
$conn = connectToDatabase();
//preparing query that will find real url hidding behind short url if it exists
$query = "SELECT *
FROM `requests`
WHERE SHORTURL = ?";
$stmt = $conn->prepare($query);
if(!$stmt->bind_param('s', $url)){
//if there is any error it will be displayed with 404 respond
header("404 Not Found", true, 404);
die( 'Error in query: '.$conn->error);
}
if(!$stmt->execute()){
//if there is any error it will be displayed with 404 respond
header("404 Not Found", true, 404);
die( 'Error in query: '.$conn->error);
}
$result = $stmt->get_result();
if ($row = $result->fetch_assoc()) {
// with htmlentities we prevent any kind of cross site scripting attack.
header("Location: ".htmlentities($row['FULLURL']),TRUE,301);
}else{
//if there is no shorten link, we return 404 not found
header("404 Not Found", TRUE, 404);
}
}else{
header("404 Not Found", TRUE, 404);
}
?>
| true |
a2dafd47dc69c6c53ea99c8beca9e83a1a6cd2b5 | PHP | mineirim/observer | /application/modules/data/models/Projetos.php | UTF-8 | 4,974 | 2.734375 | 3 | [] | no_license | <?php
class Data_Model_Projetos {
private $_db_table;
/**
*
* @param int $projeto_id
* @return Data_Model_DbTable_Rowset_Organizacoes
*/
public function getFinanciadores($projeto_id) {
$projetosTable = new Data_Model_DbTable_Projetos();
/* @var $projeto Data_Model_DbTable_Row_Projeto */
$projeto = $projetosTable->fetchRow('id=' . $projeto_id);
return $projeto->getFinanciadores();
}
/**
*
* @return Data_Model_DbTable_Projetos
*/
public function getProjetosDBTable() {
if (!$this->_db_table) {
$this->_db_table = new Data_Model_DbTable_Projetos();
}
return $this->_db_table;
}
/**
* @param $formData
* @return mixed
*/
public function insert($formData) {
unset($formData['id']);
if (isset($formData['financiadores_ids'])) {
$financiadores_ids = split(',', $formData['financiadores_ids']);
unset($formData['financiadores_ids']);
} else {
$financiadores_ids = [];
}
$formData['data_inicio'] = $this->formatDate($formData['data_inicio']);
$formData['data_fim'] = $this->formatDate($formData['data_fim']);
foreach ($formData as $key => $value) {
if ($value == '') {
unset($formData[$key]);
}
}
$id = $this->getProjetosDBTable()->insert($formData);
$this->updateFinanciadores($id, $financiadores_ids);
$row = $this->getProjetosDBTable()->fetchRow("id=$id");
return $row;
}
/**
* verifica o formato de entrada da data e devolve no formato para salvar no banco
*/
private function formatDate($date) {
if ($date === '' || !$date) {
return;
}
if (DateTime::createFromFormat('Y-m-d', $date)) {
$formatedDate = $date;
}elseif (\Zend_Date::isDate($date, \Zend_Date::ISO_8601)) {
$tmpDt = new \Zend_Date($date, \Zend_Date::ISO_8601);
$formatedDate = $tmpDt->toString('Y-MM-dd');
} else {
$tmpDt = DateTime::createFromFormat('d/m/Y', $date);
$formatedDate = $tmpDt->format('Y-m-d');
}
return $formatedDate;
}
/**
* @param $formData
* @return mixed
*/
public function update($formData) {
$fields = ['nome', 'data_inicio', 'data_fim', 'coordenador_usuario_id', 'apresentacao', 'metas', 'objetivos', 'codigo','objetivos_adm','propriedades', 'objetivos_fiotec'];
$params = [];
foreach ($fields as $field) {
if (isset($formData[$field])) {
$params[$field] = $formData[$field];
}
}
foreach ($params as &$value) {
if ($value == '') {
$value = null;
}
}
$id = $formData['id'];
unset($formData['id']);
if (isset($formData['financiadores_ids'])) {
$financiadores_ids = split(',', $formData['financiadores_ids']);
unset($formData['financiadores_ids']);
} else {
$financiadores_ids = [];
}
$this->getProjetosDBTable()->getAdapter()->beginTransaction();
// $this->getProjetosDBTable()->update($params, ["id=?"=>$id]);
$row = $this->getProjetosDBTable()->fetchRow(["id=?"=>$id]);
$row->setFromArray($formData);
$row->save();
$this->getProjetosDBTable()->getAdapter()->commit();
$this->updateFinanciadores($id, $financiadores_ids);
return $row;
}
/**
* @param $projeto_id
* @param $organizacoes_ids
*/
public function updateFinanciadores($projeto_id, $organizacoes_ids) {
$financiadoresTable = new Data_Model_DbTable_ProjetosFinanciadores;
if (count($organizacoes_ids) == 0) {
$financiadoresTable->delete('projeto_id=' . $projeto_id);
} else {
$financiadoresTable->delete('projeto_id=' . $projeto_id . ' AND organizacao_id NOT IN (' . implode(',', $organizacoes_ids) . ')');
}
foreach ($organizacoes_ids as $organizacao_id) {
if (!$financiadoresTable->fetchRow('projeto_id=' . $projeto_id . ' AND organizacao_id =' . $organizacao_id)) {
$financiadoresTable->insert(['projeto_id' => $projeto_id, 'organizacao_id' => $organizacao_id]);
}
}
}
/**
* @param $where
*/
public function getProjetos($where = null) {
$projetosTable = new Data_Model_DbTable_Projetos();
$rows = $projetosTable->fetchAll($where, 'nome');
return $rows;
}
/**
* @param $projeto
* @return mixed
*/
public function totalPorSistema($projetoId) {
$total = 0.0;
$sistema = \Zend_Registry::get('sistema');
$financeiroDbTable = new Data_Model_DbTable_Financeiro();
$where = ' programacao_id IN (SELECT p.id
FROM programacoes p INNER JOIN programacao_sistemas ps on p.id=ps.programacao_id
WHERE ps.sistema_id=' . $sistema->id . ' AND projeto_id=' . $projetoId . ') ';
$rowset = $financeiroDbTable->fetchAll($where);
foreach ($rowset as $key => $financeiro) {
$total = $total + $financeiro->valor;
}
return $total;
}
/**
* @param $id
* @return array
*/
public function getProjeto($id) {
$projetosTable = new Data_Model_DbTable_Projetos();
$projetoRow = $projetosTable->find($id);
return $projetoRow->current()->toArray();
}
}
| true |
d3891d9481abee189056f659bb82d6e5711fa4ea | PHP | dimitar1024/Telerik | /PHP web development Gatakka/Telerik - 05. ExtensionBooksCataloge/register.php | UTF-8 | 2,775 | 2.671875 | 3 | [] | no_license | <?php
ob_start();
$title = 'Регистрация';
include 'includes/header.php';
include 'includes/functions.php';
?>
<nav>
<ul>
<li>
<a href="login.php">Вход</a>
</li>
<li>
<a href="index.php">Книги</a>
</li>
<li>
<a href="book.php">Нова Книга</a>
</li>
<li>
<a href="author.php">Нов Автор</a>
</li>
</ul>
</nav>
<form id="register" class="insert" method="post">
<br/>
<label for="name">Потребителско име</label>
<input id="name" type="text" name="username" placeholder="username" required="required" />
<br />
<label for="pass">Парола</label>
<input id="pass" type="password" name="pass" placeholder="password" required="required"/>
<br />
<label for="email">Е-майл</label>
<input id="email" type="email" name="email" placeholder="email" required="required"/>
<br />
<input type="submit" name="submit" value="Регистрация" />
<br />
</form>
<?php
if (isset($_POST['submit'])) {
$name = trim($_POST['username']);
$name_esc = mysqli_real_escape_string($db,$name);
$password = htmlspecialchars(trim($_POST['pass']));
$pass_esc = mysqli_real_escape_string($db, $password);
$email = trim($_POST['email']);
$email_esc = mysqli_real_escape_string($db, $email);
$error = false;
$sql = "SELECT * FROM users WHERE username = '$name_esc' ";
$q = mysqli_query($db, $sql);
$row_count = mysqli_num_rows($q);
if ($row_count > 0) {
echo "<p>Вече съществува потребител с това потребителско име. Опитайте отново! </p>";
$error = true;
}
if (mb_strlen($name_esc) < 5) {
echo "<p>Името е по-малко от 5 символа. Опитайте отново! </p>";
$error = true;
}
if (mb_strlen($password) < 5) {
echo "<p>Паролата е прекалено къса от 5 символа. Моля опитайте отново!</p>";
$error = true;
}
if (mb_strlen($password) > 32) {
echo "<p>Паролата е прекалено дълга от 32 символа. Моля опитайте отново!</p>";
$error = true;
}
if (!$error) {
$timeNow = date("Y-m-d H:i:s");
$sql = "INSERT INTO users(username,password,email,date) VALUES ('" . mysqli_real_escape_string($db,$name) . "','" . mysqli_real_escape_string($db,$password) . "','" . mysqli_real_escape_string($db,$email) . "','" .$timeNow . "')";
echo $sql;
$q = mysqli_query($db, $sql);
if (mysqli_error($db)) {
echo "<p>Error</p>";
}
echo "<p>Регистрирахте се успешно успешно!</p>";
header('Location: login.php');
exit;
}
}
?>
<?php
include 'includes/footer.php';
?>
| true |
fa647d1fd5f07aacf9cdff0dc6a4d61922530539 | PHP | jefftocco21/LearningPHP | /LearningPHP/Chaper_3/arithmetic_operators.php | UTF-8 | 181 | 3.6875 | 4 | [] | no_license | <?php
//standard across most languages, following pemdas
echo 5 * 6 + 3 - 1 . '<br>';
echo (5 * 6) + 3 - 1;
echo '<br>';
//Square of a number
echo 5**2;
?> | true |
758d26d9f7e05ea5963f4fe35756288370091f4d | PHP | dengchunhui/classlib | /PHP_常用类class/class/checklogin.class.php | UTF-8 | 806 | 2.609375 | 3 | [] | no_license | <?php
class checklogin {
var $name;
var $pwd;
function __construct($username, $password) {
$this->name = $username;
$this->pwd = $password;
}
function checkinput() {
global $db;
$sql = "select * from tb_manager where name='$this->name' and pwd='$this->pwd'";
$res = $db->query($sql);
$info = $db->fetch_array($res);
if ($info['name'] == $this->name and $info['pwd'] == $this->pwd) {
$_SESSION[admin_name] = $info[name];
$_SESSION[pwd] = $info[pwd];
echo "<script>alert('登录成功!);window.location.href='index.php';</script>";
} else {
echo "<script language='javascript'>alert('登录失败!');history.back();</script>";
exit;
}
}
}
?>
| true |
06e9226a6900e00f4c14a2306ec930d53a56185d | PHP | shardulrane/Web-Development-Using-PHP | /MIS/jhc_mis/admin/addsession2.php | UTF-8 | 857 | 2.546875 | 3 | [] | no_license | <?php
session_start();
$q=$_GET["q"];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "MIS";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql="SELECT * FROM Department WHERE Dept_Name = '".$q."'";
$result = $conn->query($sql);
while ($row = $result->fetch_array(MYSQLI_ASSOC))
{
$q1 = $row['Dept_ID'];
$_SESSION["dep"] = $q1;
}
$sql1="SELECT distinct Class FROM weeklyplan WHERE Dept_ID = '".$q1."' order by Class asc";
$result1 = $conn->query($sql1);
echo"<option value='0'>Select Class</option>";
while ($row1 = $result1->fetch_array(MYSQLI_ASSOC))
{
echo "<option value='".$row1['Class']."'>".$row1['Class']."</option>";
}
?>
<select>
| true |
a498ed1ce79caa025cd7e89c4983dcb02c907b2e | PHP | phpstan/phpstan-src | /tests/PHPStan/Rules/DummyCollector.php | UTF-8 | 519 | 2.71875 | 3 | [
"MIT"
] | permissive | <?php declare(strict_types = 1);
namespace PHPStan\Rules;
use PhpParser\Node;
use PhpParser\Node\Expr\MethodCall;
use PHPStan\Analyser\Scope;
use PHPStan\Collectors\Collector;
/**
* @implements Collector<MethodCall, string>
*/
class DummyCollector implements Collector
{
public function getNodeType(): string
{
return MethodCall::class;
}
public function processNode(Node $node, Scope $scope)
{
if (!$node->name instanceof Node\Identifier) {
return null;
}
return $node->name->toString();
}
}
| true |
f7b2c6df54ffb13313cebfed16e6640bb2f39cb3 | PHP | andrey-silivanov/Geonames | /src/Repositories/Admin1CodeRepository.php | UTF-8 | 920 | 2.78125 | 3 | [
"MIT"
] | permissive | <?php
namespace MichaelDrennen\Geonames\Repositories;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use MichaelDrennen\Geonames\Models\Admin1Code;
class Admin1CodeRepository {
/**
* @param string $countryCode
* @param string $admin1Code
* @return Admin1Code
*/
public function getByCompositeKey ( string $countryCode, string $admin1Code ): Admin1Code {
$admin1CodeModel = Admin1Code::on( env( 'DB_GEONAMES_CONNECTION' ) )
->where( 'country_code', $countryCode )
->where( 'admin1_code', $admin1Code )
->first();
if ( is_null( $admin1CodeModel ) ) {
throw new ModelNotFoundException( "Unable to find an admin1_code model with country of $countryCode and admin1_code of $admin1Code" );
}
return $admin1CodeModel;
}
} | true |
5786d6d794d9e47e91bcdbac3445a9a90df746c2 | PHP | maciejslawik/otomoto-scrapper | /src/App/Manufacturer/Scrapper/ManufacturerHtmlScrapperInterface.php | UTF-8 | 571 | 2.71875 | 3 | [
"MIT"
] | permissive | <?php
/**
* File: ManufacturerHtmlScrapperInterface.php
*
* @author Maciej Sławik <maciekslawik@gmail.com>
* Github: https://github.com/maciejslawik
*/
namespace MSlwk\Otomoto\App\Manufacturer\Scrapper;
use MSlwk\Otomoto\App\Manufacturer\Data\ManufacturerDTOArray;
/**
* Interface ManufacturerHtmlScrapperInterface
* @package MSlwk\Otomoto\App\Manufacturer\Scrapper
*/
interface ManufacturerHtmlScrapperInterface
{
/**
* @param string $html
* @return ManufacturerDTOArray
*/
public function scrapManufacturers(string $html): ManufacturerDTOArray;
}
| true |
e4fb8a6c106c6da4d39ffa020df45d5e412ee51a | PHP | hongha1997/Lbstory_Laravel | /app/Http/Controllers/Admin/CatController.php | UTF-8 | 3,666 | 2.640625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers\Admin;
use App\Cat;
use App\Story;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class CatController extends Controller
{
public function __construct(Cat $mcat, Story $mstory){
$this->mcat = $mcat;
$this->mstory = $mstory;
}
public function index(){
$cats = $this->mcat->getList();
return view('admin.cat.index', compact('cats'));
}
public function getAdd(){
$cats = $this->mcat->getList();
return view('admin.cat.add', compact('cats'));
}
public function postAdd(Request $request){
$request->validate(
[
'name' => 'required|min:6|max:32',
],
[
'name.required'=>'Yều cầu nhập',
'name.min'=>'Yều cầu nhập lớn hơn 6 ký tự',
'name.max'=>'Yều cầu nhập nhơ hơn 32 ký tự',
]
);
$name = trim($request->name);
$nameparent = $request->nameparent;
$item = [
'name' => $name,
'parent' => $nameparent,
];
$result = $this->mcat->addItem($item);
if($result) {
return redirect()
->route('admin.cat.index')
->with('msg', 'Thêm thành công');
} else {
return redirect()
->route('admin.cat.index')
->with('msg', 'Lỗi');
}
}
public function del($id) {
//xóa tin trước khi xóa thư mục
$objStorys = $this->mstory->getItemByCat($id);
foreach ($objStorys as $objStory) {
$oldPicture = $objStory->picture;
if ($oldPicture !="" && file_exists('templates/bstory/hinhanh/'.$oldPicture)) {
unlink('templates/bstory/hinhanh/'.$oldPicture);
}
$this->mstory->delItem($objStory->story_id);
}
// xóa danh mục con
// $resultCon = $this->mcat->getItemCon($id); // all 38
// if(isset($resultCon)){
// $haha2 = $this->mcat->delItemCon($resultCon->parent);
// if($haha2)
// {
// del($resultCon->parent);
// }
// }
$this->mcat->delItemCon($id);
$result = $this->mcat->delItem($id);
if($result) {
return redirect()
->route('admin.cat.index')
->with('msg', 'Xóa thành công');
} else {
return redirect()
->route('admin.cat.index')
->with('msg', 'Lỗi');
}
}
public function getEdit($id) {
$cat = $this->mcat->getItem($id);
$cats = $this->mcat->getList();
return view('admin.cat.edit', compact('id', 'cat','cats'));
}
public function postEdit(Request $request, $id){
$request->validate(
[
'name' => 'required|min:6|max:32',
],
[
'name.required'=>'Yều cầu nhập tên truy cập',
'name.min'=>'Yều cầu nhập lớn hơn 6 ký tự',
'name.max'=>'Yều cầu nhập nhơ hơn 32 ký tự',
]
);
$name = trim($request->name);
$nameparent = $request->nameparent;
$item = [
'name' => $name,
'parent' => $nameparent,
];
$result = $this->mcat->editItem($id, $item);
if($result) {
return redirect()
->route('admin.cat.index')
->with('msg', 'Sửa thành công');
} else {
return redirect()
->route('admin.cat.index')
->with('msg', 'Lỗi');
}
}
}
| true |
f4c95489c08a70b4099a020a00277c1d74e4d91f | PHP | leopires/billion-dollar-app | /brand-actions.php | UTF-8 | 696 | 2.59375 | 3 | [] | no_license | <?php
if (!$_POST)
header("Location: index.html");
$brandName = $_POST['txtBrand'];
if ($brandName) {
$errorMessage = NULL;
$db = NULL;
try {
$db = new PDO("sqlite:db/db-billion-dollar-app.sqlite");
$query = $db->prepare("INSERT INTO CAR_BRANDS (BRAND) VALUES (?)");
if (!$query->execute(array("{$brandName}"))) {
$errorMessage = $query->errorInfo()[2];
}
} catch (PDOException $ex) {
$errorMessage = $ex->getMessage();
} finally {
$db = NULL;
}
if ($errorMessage) {
header("Location: brands.php?error=" . $errorMessage);
} else {
header("Location: brands.php");
}
}
?> | true |
ff31792fc50213df93f31e9263d78c46dca2a0db | PHP | yzawudi/food_web | /login.php | UTF-8 | 981 | 2.75 | 3 | [] | no_license | <?php
/*开启会话*/
//session_start();
$data=$_POST;
/*获取登录表单提交过来的数据*/
$user=$data['Username'];
$pwd=$data['Password'];
// 创建连接
$conn = new mysqli('localhost', 'root', 'root', 'test');
// Check connection
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
$sql = "select * from `user` where username='$user' and password='$pwd'";
$result = $conn->query($sql);
/*如果数据存在,即用户登录成功*/
if ($result) {
/*将用户名和昵称存在服务器,可以多个页面使用*/
$row = $result->fetch_assoc();
$_SESSION['username'] = $row['username'];
// 判断是否正确
$res['code'] = '200';
$res['status'] = 'success';
$res['msg'] = 'ok';
echo json_encode($res);
}else{/*用户名或密码错误*/
$res['code'] = '400';
$res['status'] = 'error';
$res['msg'] = '用户名或密码错误';
echo json_encode($res);
} | true |
6f738db3b0e98f78b6f4983b8792aa72aeb80545 | PHP | itstructure/yii2-template-multilanguage | /models/AboutQuality.php | UTF-8 | 2,288 | 2.65625 | 3 | [] | permissive | <?php
namespace app\models;
/**
* This is the model class for table "about_qualities".
*
* @property int $about_id
* @property int $qualities_id
*
* @property About $about
* @property Quality $quality
*/
class AboutQuality extends \yii\db\ActiveRecord
{
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'about_qualities';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[
[
'about_id',
'qualities_id'
],
'required'
],
[
[
'about_id',
'qualities_id'
],
'integer'
],
[
[
'about_id',
'qualities_id'
],
'unique',
'targetAttribute' => [
'about_id',
'qualities_id'
]
],
[
[
'about_id'
],
'exist',
'skipOnError' => true,
'targetClass' => About::class,
'targetAttribute' => [
'about_id' => 'id'
]
],
[
[
'qualities_id'
],
'exist',
'skipOnError' => true,
'targetClass' => Quality::class,
'targetAttribute' => [
'qualities_id' => 'id'
]
],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'about_id' => 'About ID',
'qualities_id' => 'Qualities ID',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getAbout()
{
return $this->hasOne(About::class, [
'id' => 'about_id'
]);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getQuality()
{
return $this->hasOne(Quality::class, [
'id' => 'qualities_id'
]);
}
}
| true |
1a370dd05a0d4ae9c6a7ad00e1d73f6aa5657948 | PHP | CindyLilianaDiaz/ContentManagementSystem | /edit-admin.php | UTF-8 | 2,021 | 2.75 | 3 | [] | no_license | <?php ob_start();
require_once('auth.php');
//set the page title
$title = 'Edit Administrator';
require_once('header.php');
//check if we have an user ID in the querystring
//isset means does this value has something or it is null
if(isset($_GET['user_id'])) {
//if we do, store in a variable
$user_id = base64_decode($_GET['user_id']);
try{
//connect
require_once('db.php');
//select all the data for the selected subscriber
$sql = "SELECT * FROM administrators WHERE user_id = :user_id";
//store each value from the database into a variable
$cmd = $conn->prepare($sql);
$cmd->bindParam(':user_id', $user_id , PDO::PARAM_INT);
$cmd->execute();
$result = $cmd->fetchAll();
foreach( $result as $row){
$email = $row['email'];
}
//disconnect
$conn = null;
}
catch(exception $e){
//email ourselves error details
mail('cindy.liliana.diaz@gmail.com','Edit Admin Error', $e);
//load generic error page
header('location:error.php');
}
}
?>
<div class="jumbotron">
<div class="container">
<h1>EDIT INFORMATION</h1>
<form method="post" action="save-admin.php" class="form-horizontal">
<h4>* Required Information</h4>
<div class="form-group">
<label for="email" class="col-sm-2">*Email:*</label>
<input name="email" type="email" required value="<?php echo $email; ?>" />
</div>
<div class="form-group">
<label for="password" class="col-sm-2">*Password:*</label>
<input name="password" type="password" required/>
</div>
<div class="form-group">
<label for="confirm"class="col-sm-2">*Confirm Password:</label>
<input type="password" name="confirm" required />
</div>
<input type="hidden" name="user_id" value="<?php echo $user_id;?>" />
<input type="submit" value="Save" class="btn btn-primary"/>
</form>
</div>
</div>
<?php
require_once('footer.php');
ob_flush(); ?>
| true |
144bfdffcc574ef09d2c645e748b6d3a09e00dad | PHP | usg2010/usg | /mail.php | UTF-8 | 627 | 2.734375 | 3 | [] | no_license | <?php
if(isset($_POST['submit'])){
$name = $_POST['name'];
$email= $_POST['email'];
$phone= $_POST['phone'];
$msg=$_POST['msg'];
$to = "usg.lu.21@gmail.com";
$subject = "From submission";
$message="Name: ".$name."\n".$phone."\n"."wrote the following: "."\n\n".$msg;
$headers="from: ".$email;
if(mail($to,$subject,$headers)){
echo"<h1>sent successfully! Thank you"." ".$name.",we will cintact you later!<h1>";
}
else{
echo "Somthing went wrong! please check your email or password";
}
}
?> | true |
64eb39fa32b819025ba442fb347a49a9e0b044e8 | PHP | FrittenKeeZ/laravel-vouchers | /tests/HasVouchersTest.php | UTF-8 | 3,478 | 2.546875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | <?php
declare(strict_types=1);
namespace FrittenKeeZ\Vouchers\Tests;
use FrittenKeeZ\Vouchers\Tests\Models\Color;
use FrittenKeeZ\Vouchers\Tests\Models\User;
use FrittenKeeZ\Vouchers\Vouchers;
/**
* @internal
*/
class HasVouchersTest extends TestCase
{
/**
* Test HasVouchers::createVoucher().
*
* @return void
*/
public function testCreateVoucher(): void
{
$user = $this->factory(User::class)->create();
$voucher = $user->createVoucher();
// Check user voucher relation.
$this->assertTrue($user->is($voucher->owner));
$this->assertTrue($voucher->is($user->vouchers->first()));
}
/**
* Test HasVouchers::createVoucher() with callback.
*
* @return void
*/
public function testCreateVoucherWithCallback(): void
{
$user = $this->factory(User::class)->create();
$color = $this->factory(Color::class)->create();
$voucher = $user->createVoucher(function (Vouchers $vouchers) use ($color) {
$vouchers->withEntities($color);
});
// Check user voucher relation.
$this->assertTrue($user->is($voucher->owner));
$this->assertTrue($voucher->is($user->vouchers->first()));
$this->assertTrue($color->is($voucher->getEntities(Color::class)->first()));
}
/**
* Test HasVouchers::createVoucher() with associated entities.
*
* @return void
*/
public function testCreateVoucherWithAssociated(): void
{
$user = $this->factory(User::class)->create();
$other = $this->factory(User::class)->create();
$voucher = $user->createVoucher(function (Vouchers $vouchers) use ($other) {
$vouchers->withEntities($other);
});
// Check user voucher relation.
$this->assertTrue($user->is($voucher->owner));
$this->assertTrue($voucher->is($user->vouchers->first()));
$this->assertFalse($other->is($voucher->owner));
$this->assertTrue($other->is($voucher->getEntities(User::class)->first()));
$this->assertTrue($voucher->is($other->voucherEntities->first()->voucher));
$this->assertTrue($voucher->is($other->associatedVouchers->first()));
}
/**
* Test HasVouchers::createVouchers().
*
* @return void
*/
public function testCreateVouchers(): void
{
$user = $this->factory(User::class)->create();
$vouchers = $user->createVouchers(3);
foreach ($vouchers as $index => $voucher) {
// Check user voucher relation.
$this->assertTrue($user->is($voucher->owner));
$this->assertTrue($voucher->is($user->vouchers[$index]));
}
}
/**
* Test HasVouchers::createVouchers() with callback.
*
* @return void
*/
public function testCreateVouchersWithCallback(): void
{
$user = $this->factory(User::class)->create();
$color = $this->factory(Color::class)->create();
$vouchers = $user->createVouchers(3, function (Vouchers $vouchers) use ($color) {
$vouchers->withEntities($color);
});
foreach ($vouchers as $index => $voucher) {
// Check user voucher relation.
$this->assertTrue($user->is($voucher->owner));
$this->assertTrue($voucher->is($user->vouchers[$index]));
$this->assertTrue($color->is($voucher->getEntities(Color::class)->first()));
}
}
}
| true |
c62e112688d2e7e258822a353b4f01c329b0a0c2 | PHP | kdrdmr/dhl-sdk-api-express | /src/Webservice/Soap/Type/Tracking/ShipperReference.php | UTF-8 | 1,044 | 2.6875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | <?php
/**
* See LICENSE.md for license details.
*/
namespace Dhl\Express\Webservice\Soap\Type\Tracking;
/**
* ShipperReference class.
*
* @api
* @author Ronny Gertler <ronny.gertler@netresearch.de>
* @link https://www.netresearch.de/
*/
class ShipperReference
{
/**
* @var string
*/
protected $ReferenceID;
/**
* @var string
*/
protected $ReferenceType;
/**
* @return string
*/
public function getReferenceID()
{
return $this->ReferenceID;
}
/**
* @param string $ReferenceID
*
* @return self
*/
public function setReferenceID($ReferenceID)
{
$this->ReferenceID = $ReferenceID;
return $this;
}
/**
* @return string
*/
public function getReferenceType()
{
return $this->ReferenceType;
}
/**
* @param string $ReferenceType
* @return self
*/
public function setReferenceType($ReferenceType)
{
$this->ReferenceType = $ReferenceType;
return $this;
}
}
| true |
109cad23c64c23333e02edf54cfd007da3ffb6b0 | PHP | jezzaluzande/thisproject | /odll/application/base.php | UTF-8 | 2,963 | 2.734375 | 3 | [] | no_license | <?php
class Application
{
var $uri;
var $model;
var $db;
function __construct($uri)
{
$this->uri = $uri;
}
function loadDatabase()
{
$this->db = new Database;
//connect to database
$this->db->connect();
}
function loadController($class)
{
$file = "application/controller/".$this->uri['controller'].".php";
if(!file_exists($file)) die();
require_once($file);
$controller = new $class();
if(method_exists($controller, $this->uri['method']))
{
$controller->{$this->uri['method']}($this->uri['var']);
} else {
$controller->index();
}
}
function loadView($view,$vars)
{
if(is_array($vars) && count($vars) > 0)
extract($vars, EXTR_PREFIX_SAME, "wddx");
require_once('view/'.$view.'.php');
}
function loadModel($model)
{
require_once('model/'.$model.'.php');
$this->$model = new $model;
}
function uploadImg($a, $b)
{
//define ("MAX_SIZE","400");
$errors=0;
$image = $a;
$uploadedfile = $b;
if ($image)
{
$filename = stripslashes($a);
$extension = $this->getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "jpe") && ($extension != "jfif")
&& ($extension != "png") && ($extension != "gif") && ($extension != "tif") && ($extension != "tiff"))
{
//echo '<script type=\'text/javascript\'>alert(\'Unknown image extension. Photo not uploaded.\')</script>';
$errors=1;
} else {
$size=filesize($b);
if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $b;
$src = imagecreatefromjpeg($uploadedfile);
} else if($extension=="png") {
$uploadedfile = $b;
$src = imagecreatefrompng($uploadedfile);
} else {
$src = imagecreatefromgif($uploadedfile);
}
list($width,$height)=getimagesize($uploadedfile);
//$newwidth=400;
//$newheight=($height/$width)*$newwidth;
//$tmp=imagecreatetruecolor($newwidth,$newheight);
//imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
//$u = "1000";
$locate = $a;
$filename = "application/img/". $locate;
imagejpeg($src,$filename,100);
imagedestroy($src);
//imagedestroy($tmp);
return true;
}
}
}
function uploadFiles($a,$b)
{
if($a)
{
$filename = stripslashes($a);
$extension = $this->getExtension($filename);
$extension = strtolower($extension);
//if($extension=="doc" || $extension=="docx" || $extension=="pdf" || $extension=="xls" || $extension=="xlsx" || $extension == "txt")
if($extension=="xls" || $extension=="xlsx")
{
$target = "application/database/";
$target = $target .$a;
move_uploaded_file($b, $target);
return true;
} else {
return false;
}
}
}
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
}
?> | true |
6c6de91be03bdc913f64aa7e1eb1a179db342462 | PHP | aLuckyfellow/agileSwoole | /src/Kernel/Core/Route/IRoute.php | UTF-8 | 159 | 2.703125 | 3 | [
"MIT"
] | permissive | <?php
namespace Kernel\Core\Route;
interface IRoute
{
public function add(string $method, string $path, $closure) : IRoute;
public function getRouter();
} | true |
5c570dc0ad45806d89e705d98c48495b4352f85d | PHP | Aviyajeet/PHPProject_CE140_CE077 | /MobileShop/EditMobile.php | UTF-8 | 5,457 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
error_reporting(E_ALL ^ E_DEPRECATED);
require_once('User.php');
require_once('DataBase.php');
require_once('Mobile.php');
session_start();
$mobile = null;
$DB = new DataBase();
if(
(isset($_SESSION['AdminID']) && !empty($_SESSION['AdminID']))
&& ((!empty($_POST['ID']))&& (isset($_POST['ID'])))
&& (isset($_FILES['image']) && !empty($_FILES['image']))
&& (isset($_FILES['features']) && !empty($_FILES['features']))
){
$id = $_POST['id'];
$model = $_POST['model'];
$brand = $_POST['brand'];
$price = $_POST['price'];
$tmp_name = $_FILES['image']['tmp_name'];
$camera = $_POST['camera'];
$memory = $_POST['memory'];
$network = $_POST['network'];
$platform = $_POST['platform'];
$cpu = $_POST['cpu'];
$features = $_POST['features'];
$mobile = new Mobile($id, $model, $brand, $price, $ImageURL, $camera, $memory, $network, $platform, $cpu, $features);
$location = "MobilesPictures/";
if(move_uploaded_file($tmp_name,$location.$brand.$model.".jpg")){
$ImageURL =$location.$brand.$model.".jpg";
$mobile = new Mobile($id, $model, $brand, $price, $ImageURL, $camera, $memory, $network, $platform, $cpu, $features);
$DB->editMobile($mobile);
header('Location: AdminPage.php');
}
}
elseif((isset($_SESSION['AdminID']) && !empty($_SESSION['AdminID'])) && (isset($_POST['ID']) && !empty($_POST['ID']))) {
$DB = new DataBase();
$id = $_POST['ID'];
$mobile = $DB->getMobileById($id);
}else{
header('Location: AdminPage.php');
}
?>
<html>
<head>
<link rel="stylesheet" href="bootstrap-theme.css">
<link rel="stylesheet" href="bootstrap-theme.min.css">
<link rel="stylesheet" href="bootstrap.css">
<link rel="stylesheet" href="bootstrap.min.css">
</head>
<body>
<form class="form-horizontal" action="EditMobile.php" method="post">
<fieldset>
<!-- Form Name -->
<legend>Edit Mobile</legend>
<input type="hidden" value="<?php echo $mobile->ID?>" name="ID">
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="name">Model</label>
<div class="col-md-4">
<input name="model" type="text" placeholder="Model" class="form-control input-md" value="<?php echo $mobile->Model?>" required="">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" for="name">Brand</label>
<div class="col-md-4">
<select name="brand" class="form-control">
<option value="<?php echo $mobile->BrandID?>"><?php echo $DB->getBrandById($mobile->BrandID)->Name;?></option>
</select>
</div>
</div>
<br/>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label">Price</label>
<div class="col-md-4">
<input name="price" type="text" placeholder="Price" class="form-control input-md" value="<?php echo $mobile->Price?>" required="">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" >Image</label>
<div class="col-md-4">
<input name="image" type="file" class="form-control" required="">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" >Camera Specs</label>
<div class="col-md-6">
<input name="camera" type="text" placeholder="Camera Specs" value="<?php echo $mobile->CameraSpecs?>" class="form-control input-md" required="">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" >Memory Specs</label>
<div class="col-md-6">
<input name="memory" type="text" placeholder="Memory Specs" value="<?php echo $mobile->MemorySpecs?>" class="form-control input-md" required="">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" >Network Specs</label>
<div class="col-md-6">
<input name="network" type="text" placeholder="Network Specs" value="<?php echo $mobile->NetworkSpecs?>" class="form-control input-md" required="">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label">Platform</label>
<div class="col-md-6">
<input name="platform" type="text" placeholder="Platform" value="<?php echo $mobile->Platform?>" class="form-control input-md" required="">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" >CPU</label>
<div class="col-md-6">
<input name="cpu" type="text" placeholder="CPU" value="<?php echo $mobile->CPU?>" class="form-control input-md" required="">
</div>
</div>
<!-- Textarea -->
<div class="form-group">
<label class="col-md-4 control-label" >Features</label>
<div class="col-md-4">
<textarea class="form-control" id="anschrift" placeholder="Features" name="features" required=""></textarea>
</div>
</div>
<!-- Button (Double) -->
<div class="form-group">
<div class="col-md-8">
<input type="submit" value="Save" class="btn btn-success">
<a class="btn btn-success" href="AdminPage.php">Back</a>
</div>
</div>
</fieldset>
</form>
</body>
</html> | true |
d7afdc8733a0d326416fbeb933ffc1506a74ab1d | PHP | luobobaozi/HC | /Server/GameServer/server2/DbModule/SysPlayerConnectionInfo.php | UTF-8 | 19,606 | 2.515625 | 3 | [] | no_license | <?php
require_once ($GLOBALS ['GAME_ROOT'] . "CMySQL.php");
require_once ("SQLUtil.php");
/**
* [The generated files]
*/
class SysPlayerConnectionInfo {
private /*string*/ $id; //PRIMARY KEY
private /*string*/ $user_id;
private /*int*/ $server_id;
private /*string*/ $account;
private /*string*/ $proxy_id;
private /*string*/ $socket_id;
private /*int*/ $type;
private /*int*/ $state;
private /*string*/ $address;
private /*string*/ $create_time;
private $this_table_status_field = false;
private $id_status_field = false;
private $user_id_status_field = false;
private $server_id_status_field = false;
private $account_status_field = false;
private $proxy_id_status_field = false;
private $socket_id_status_field = false;
private $type_status_field = false;
private $state_status_field = false;
private $address_status_field = false;
private $create_time_status_field = false;
public static function loadedTable( $fields=NULL,$condition=NULL)
{
$result = array();
$p = "*";
if(!empty($fields))
{
$p = SQLUtil::parseFields($fields);
}
if (empty($condition))
{
$sql = "SELECT {$p} FROM `player_connection_info`";
}
else
{
$sql = "SELECT {$p} FROM `player_connection_info` WHERE ".SQLUtil::parseCondition($condition);
}
$qr = MySQL::getInstance()->RunQuery($sql);
if(empty($qr)){
return $result;
}
$ar = MySQL::getInstance()->FetchAllRows($qr);
if (empty($ar) || count($ar) == 0)
{
return $result;
}
foreach($ar as $row)
{
$tb = new SysPlayerConnectionInfo();
if (isset($row['id'])) $tb->id = $row['id'];
if (isset($row['user_id'])) $tb->user_id = $row['user_id'];
if (isset($row['server_id'])) $tb->server_id = intval($row['server_id']);
if (isset($row['account'])) $tb->account = $row['account'];
if (isset($row['proxy_id'])) $tb->proxy_id = $row['proxy_id'];
if (isset($row['socket_id'])) $tb->socket_id = $row['socket_id'];
if (isset($row['type'])) $tb->type = intval($row['type']);
if (isset($row['state'])) $tb->state = intval($row['state']);
if (isset($row['address'])) $tb->address = $row['address'];
if (isset($row['create_time'])) $tb->create_time = $row['create_time'];
$result[] = $tb;
}
return $result;
}
public static function insertSqlHeader($fields=NULL)
{
$result = array();
if(!empty($fields)){
$where = SQLUtil::parseFields($fields);
$result[0] = "INSERT INTO `player_connection_info` ({$where}) VALUES ";
$ar = array();
foreach($fields as $key){
$ar[$key]=1;
}
$result[1] = $ar;
}else{
$result[0]="INSERT INTO `player_connection_info` (`id`,`user_id`,`server_id`,`account`,`proxy_id`,`socket_id`,`type`,`state`,`address`,`create_time`) VALUES ";
$result[1] = array('id'=>1,'user_id'=>1,'server_id'=>1,'account'=>1,'proxy_id'=>1,'socket_id'=>1,'type'=>1,'state'=>1,'address'=>1,'create_time'=>1);
}
return $result;
}
public function loaded( $fields=NULL,$condition=NULL)
{
if (empty($condition) && empty($this->id))
{
return false;
}
$p = "*";
$where = "`id` = '{$this->id}'";
if(!empty($fields))
{
$p = SQLUtil::parseFields($fields);
}
if (!empty($condition))
{
$where =SQLUtil::parseCondition($condition);
}
$sql = "SELECT {$p} FROM `player_connection_info` WHERE {$where}";
if(isset($this->user_id)){MySQL::selectDbForUser($this->user_id);}else{MySQL::selectDbForUser($GLOBALS['USER_ID']);}
$qr = MySQL::getInstance()->RunQuery($sql);
$ar = MySQL::getInstance()->FetchArray($qr);
if (!$ar || count($ar)==0)
{
return false;
}
if (isset($ar['id'])) $this->id = $ar['id'];
if (isset($ar['user_id'])) $this->user_id = $ar['user_id'];
if (isset($ar['server_id'])) $this->server_id = intval($ar['server_id']);
if (isset($ar['account'])) $this->account = $ar['account'];
if (isset($ar['proxy_id'])) $this->proxy_id = $ar['proxy_id'];
if (isset($ar['socket_id'])) $this->socket_id = $ar['socket_id'];
if (isset($ar['type'])) $this->type = intval($ar['type']);
if (isset($ar['state'])) $this->state = intval($ar['state']);
if (isset($ar['address'])) $this->address = $ar['address'];
if (isset($ar['create_time'])) $this->create_time = $ar['create_time'];
$this->clean();
return true;
}
public function loadedCount( $fields=NULL,$condition=NULL)
{
if (empty($condition) && empty($this->id))
{
return false;
}
$p = "*";
$where = "`id` = '{$this->id}'";
if(!empty($fields))
{
$p = SQLUtil::parseFields($fields);
}
if (!empty($condition))
{
$where =SQLUtil::parseCondition($condition);
}
$sql = "SELECT {$p} FROM `player_connection_info` WHERE {$where}";
if(isset($this->user_id)){MySQL::selectDbForUser($this->user_id);}else{MySQL::selectDbForUser($GLOBALS['USER_ID']);}
$qr = MySQL::getInstance()->RunQuery($sql);
$ar = MySQL::getInstance()->FetchArray($qr);
if (!$ar || count($ar)==0)
{
return false;
}
return $ar;
}
public function loadedExistFields()
{
$emptyCondition = true;
$emptyFields = true;
$fields = array();
$condition = array();
if (!isset($this->id)){
$emptyFields = false;
$fields[] = 'id';
}else{
$emptyCondition = false;
$condition['id']=$this->id;
}
if (!isset($this->user_id)){
$emptyFields = false;
$fields[] = 'user_id';
}else{
$emptyCondition = false;
$condition['user_id']=$this->user_id;
}
if (!isset($this->server_id)){
$emptyFields = false;
$fields[] = 'server_id';
}else{
$emptyCondition = false;
$condition['server_id']=$this->server_id;
}
if (!isset($this->account)){
$emptyFields = false;
$fields[] = 'account';
}else{
$emptyCondition = false;
$condition['account']=$this->account;
}
if (!isset($this->proxy_id)){
$emptyFields = false;
$fields[] = 'proxy_id';
}else{
$emptyCondition = false;
$condition['proxy_id']=$this->proxy_id;
}
if (!isset($this->socket_id)){
$emptyFields = false;
$fields[] = 'socket_id';
}else{
$emptyCondition = false;
$condition['socket_id']=$this->socket_id;
}
if (!isset($this->type)){
$emptyFields = false;
$fields[] = 'type';
}else{
$emptyCondition = false;
$condition['type']=$this->type;
}
if (!isset($this->state)){
$emptyFields = false;
$fields[] = 'state';
}else{
$emptyCondition = false;
$condition['state']=$this->state;
}
if (!isset($this->address)){
$emptyFields = false;
$fields[] = 'address';
}else{
$emptyCondition = false;
$condition['address']=$this->address;
}
if (!isset($this->create_time)){
$emptyFields = false;
$fields[] = 'create_time';
}else{
$emptyCondition = false;
$condition['create_time']=$this->create_time;
}
if ($emptyFields)
{
unset($fields);
}
if ($emptyCondition)
{
unset($condition);
}
return $this->loaded($fields,$condition);
}
public function inOrUp()
{
$sql = $this->getInSQL();
if (empty($sql))
{
return false;
}
$sql .= " ON DUPLICATE KEY UPDATE ";
$sql .= $this->getUpFields();
if(isset($this->user_id)){MySQL::selectDbForUser($this->user_id);}else{MySQL::selectDbForUser($GLOBALS['USER_ID']);}
$qr = MySQL::getInstance()->RunQuery($sql);
if (!$qr)
{
return false;
}
if (empty($this->id))
{
$this->id = MySQL::getInstance()->GetInsertId();
}
$this->clean();
return true;
}
public function save($condition=NULL)
{
if (empty($condition))
{
$uc = "`id`='{$this->id}'";
}
else
{
$uc = SQLUtil::parseCondition($condition);
}
$sql = $this->getUpSQL($uc);
if(empty($sql)){
return true;
}
if(isset($this->user_id)){MySQL::selectDbForUser($this->user_id);}else{MySQL::selectDbForUser($GLOBALS['USER_ID']);}
$qr = MySQL::getInstance()->RunQuery($sql);
$this->clean();
return (boolean)$qr;
}
public static function sql_delete($condition=NULL)
{
if (empty($condition))
{
return false;
}
$sql = "DELETE FROM `player_connection_info` WHERE ".SQLUtil::parseCondition($condition);
$qr = MySQL::getInstance()->RunQuery($sql);
return (boolean)$qr;
}
public function delete()
{
if (!isset($this->id))
{
return false;
}
$sql = "DELETE FROM `player_connection_info` WHERE `id`='{$this->id}'";
if(isset($this->user_id)){MySQL::selectDbForUser($this->user_id);}else{MySQL::selectDbForUser($GLOBALS['USER_ID']);}
$qr = MySQL::getInstance()->RunQuery($sql);
return (boolean)$qr;
}
public function getInsertValue($fields)
{
$values = "(";
foreach($fields as $f => $k){
if($f == 'id'){
$values .= "'{$this->id}',";
}else if($f == 'user_id'){
$values .= "'{$this->user_id}',";
}else if($f == 'server_id'){
$values .= "'{$this->server_id}',";
}else if($f == 'account'){
$values .= "'{$this->account}',";
}else if($f == 'proxy_id'){
$values .= "'{$this->proxy_id}',";
}else if($f == 'socket_id'){
$values .= "'{$this->socket_id}',";
}else if($f == 'type'){
$values .= "'{$this->type}',";
}else if($f == 'state'){
$values .= "'{$this->state}',";
}else if($f == 'address'){
$values .= "'{$this->address}',";
}else if($f == 'create_time'){
$values .= "'{$this->create_time}',";
}
}
$values .= ")";
return str_replace(",)",")",$values);
}
private function getInSQL()
{
if (!$this->this_table_status_field)
{
return;
}
$fields = "(";
$values = " VALUES(";
if (isset($this->id))
{
$fields .= "`id`,";
$values .= "'{$this->id}',";
}
if (isset($this->user_id))
{
$fields .= "`user_id`,";
$values .= "'{$this->user_id}',";
}
if (isset($this->server_id))
{
$fields .= "`server_id`,";
$values .= "'{$this->server_id}',";
}
if (isset($this->account))
{
$fields .= "`account`,";
$values .= "'{$this->account}',";
}
if (isset($this->proxy_id))
{
$fields .= "`proxy_id`,";
$values .= "'{$this->proxy_id}',";
}
if (isset($this->socket_id))
{
$fields .= "`socket_id`,";
$values .= "'{$this->socket_id}',";
}
if (isset($this->type))
{
$fields .= "`type`,";
$values .= "'{$this->type}',";
}
if (isset($this->state))
{
$fields .= "`state`,";
$values .= "'{$this->state}',";
}
if (isset($this->address))
{
$fields .= "`address`,";
$values .= "'{$this->address}',";
}
if (isset($this->create_time))
{
$fields .= "`create_time`,";
$values .= "'{$this->create_time}',";
}
$fields .= ")";
$values .= ")";
$sql = "INSERT INTO `player_connection_info` ".$fields.$values;
return str_replace(",)",")",$sql);
}
private function getUpFields()
{
$update = "";
if ($this->user_id_status_field)
{
if (!isset($this->user_id))
{
$update .= ("`user_id`=null,");
}
else
{
$update .= ("`user_id`='{$this->user_id}',");
}
}
if ($this->server_id_status_field)
{
if (!isset($this->server_id))
{
$update .= ("`server_id`=null,");
}
else
{
$update .= ("`server_id`='{$this->server_id}',");
}
}
if ($this->account_status_field)
{
if (!isset($this->account))
{
$update .= ("`account`=null,");
}
else
{
$update .= ("`account`='{$this->account}',");
}
}
if ($this->proxy_id_status_field)
{
if (!isset($this->proxy_id))
{
$update .= ("`proxy_id`=null,");
}
else
{
$update .= ("`proxy_id`='{$this->proxy_id}',");
}
}
if ($this->socket_id_status_field)
{
if (!isset($this->socket_id))
{
$update .= ("`socket_id`=null,");
}
else
{
$update .= ("`socket_id`='{$this->socket_id}',");
}
}
if ($this->type_status_field)
{
if (!isset($this->type))
{
$update .= ("`type`=null,");
}
else
{
$update .= ("`type`='{$this->type}',");
}
}
if ($this->state_status_field)
{
if (!isset($this->state))
{
$update .= ("`state`=null,");
}
else
{
$update .= ("`state`='{$this->state}',");
}
}
if ($this->address_status_field)
{
if (!isset($this->address))
{
$update .= ("`address`=null,");
}
else
{
$update .= ("`address`='{$this->address}',");
}
}
if ($this->create_time_status_field)
{
if (!isset($this->create_time))
{
$update .= ("`create_time`=null,");
}
else
{
$update .= ("`create_time`='{$this->create_time}',");
}
}
if (empty($update) || strlen($update) < 1)
{
return;
}
$i = strrpos($update,",");
if (!is_bool($i))
{
$update = substr($update,0,$i);
}
return $update;
}
private function getUpSQL($condition)
{
if (!$this->this_table_status_field)
{
return null;
}
$update = $this->getUpFields();
if (empty($update))
{
return;
}
$sql = "UPDATE `player_connection_info` SET {$update} WHERE {$condition}";
return $sql;
}
public function add($fieldsValue,$condition=NULL)
{
if (empty($condition))
{
$uc = "`id`='{$this->id}'";
}
else
{
$uc = SQLUtil::parseCondition($condition);
}
$update = SQLUtil::parseASFieldValues($fieldsValue);
$sql = "UPDATE `player_connection_info` SET {$update} WHERE {$uc}";
if(isset($this->user_id)){MySQL::selectDbForUser($this->user_id);}else{MySQL::selectDbForUser($GLOBALS['USER_ID']);}
$qr = MySQL::getInstance()->RunQuery($sql);
return (boolean)$qr;
}
public function sub($fieldsVal,$condition=NULL)
{
if (empty($condition))
{
$uc = "`id`='{$this->id}'";
}
else
{
$uc = SQLUtil::parseCondition($condition);
}
$update = SQLUtil::parseASFieldValues($fieldsVal,false);
$sql = "UPDATE `player_connection_info` SET {$update} WHERE {$uc}";
if(isset($this->user_id)){MySQL::selectDbForUser($this->user_id);}else{MySQL::selectDbForUser($GLOBALS['USER_ID']);}
$qr = MySQL::getInstance()->RunQuery($sql);
return (boolean)$qr;
}
private function /*void*/ clean()
{
$this->this_table_status_field = false;
$this->id_status_field = false;
$this->user_id_status_field = false;
$this->server_id_status_field = false;
$this->account_status_field = false;
$this->proxy_id_status_field = false;
$this->socket_id_status_field = false;
$this->type_status_field = false;
$this->state_status_field = false;
$this->address_status_field = false;
$this->create_time_status_field = false;
}
public function /*string*/ getId()
{
return $this->id;
}
public function /*void*/ setId(/*string*/ $id)
{
$this->id = SQLUtil::toSafeSQLString($id);
$this->id_status_field = true;
$this->this_table_status_field = true;
}
public function /*void*/ setIdNull()
{
$this->id = null;
$this->id_status_field = true;
$this->this_table_status_field = true;
}
public function /*string*/ getUserId()
{
return $this->user_id;
}
public function /*void*/ setUserId(/*string*/ $user_id)
{
$this->user_id = SQLUtil::toSafeSQLString($user_id);
$this->user_id_status_field = true;
$this->this_table_status_field = true;
}
public function /*void*/ setUserIdNull()
{
$this->user_id = null;
$this->user_id_status_field = true;
$this->this_table_status_field = true;
}
public function /*int*/ getServerId()
{
return $this->server_id;
}
public function /*void*/ setServerId(/*int*/ $server_id)
{
$this->server_id = intval($server_id);
$this->server_id_status_field = true;
$this->this_table_status_field = true;
}
public function /*void*/ setServerIdNull()
{
$this->server_id = null;
$this->server_id_status_field = true;
$this->this_table_status_field = true;
}
public function /*string*/ getAccount()
{
return $this->account;
}
public function /*void*/ setAccount(/*string*/ $account)
{
$this->account = SQLUtil::toSafeSQLString($account);
$this->account_status_field = true;
$this->this_table_status_field = true;
}
public function /*void*/ setAccountNull()
{
$this->account = null;
$this->account_status_field = true;
$this->this_table_status_field = true;
}
public function /*string*/ getProxyId()
{
return $this->proxy_id;
}
public function /*void*/ setProxyId(/*string*/ $proxy_id)
{
$this->proxy_id = SQLUtil::toSafeSQLString($proxy_id);
$this->proxy_id_status_field = true;
$this->this_table_status_field = true;
}
public function /*void*/ setProxyIdNull()
{
$this->proxy_id = null;
$this->proxy_id_status_field = true;
$this->this_table_status_field = true;
}
public function /*string*/ getSocketId()
{
return $this->socket_id;
}
public function /*void*/ setSocketId(/*string*/ $socket_id)
{
$this->socket_id = SQLUtil::toSafeSQLString($socket_id);
$this->socket_id_status_field = true;
$this->this_table_status_field = true;
}
public function /*void*/ setSocketIdNull()
{
$this->socket_id = null;
$this->socket_id_status_field = true;
$this->this_table_status_field = true;
}
public function /*int*/ getType()
{
return $this->type;
}
public function /*void*/ setType(/*int*/ $type)
{
$this->type = intval($type);
$this->type_status_field = true;
$this->this_table_status_field = true;
}
public function /*void*/ setTypeNull()
{
$this->type = null;
$this->type_status_field = true;
$this->this_table_status_field = true;
}
public function /*int*/ getState()
{
return $this->state;
}
public function /*void*/ setState(/*int*/ $state)
{
$this->state = intval($state);
$this->state_status_field = true;
$this->this_table_status_field = true;
}
public function /*void*/ setStateNull()
{
$this->state = null;
$this->state_status_field = true;
$this->this_table_status_field = true;
}
public function /*string*/ getAddress()
{
return $this->address;
}
public function /*void*/ setAddress(/*string*/ $address)
{
$this->address = SQLUtil::toSafeSQLString($address);
$this->address_status_field = true;
$this->this_table_status_field = true;
}
public function /*void*/ setAddressNull()
{
$this->address = null;
$this->address_status_field = true;
$this->this_table_status_field = true;
}
public function /*string*/ getCreateTime()
{
return $this->create_time;
}
public function /*void*/ setCreateTime(/*string*/ $create_time)
{
$this->create_time = SQLUtil::toSafeSQLString($create_time);
$this->create_time_status_field = true;
$this->this_table_status_field = true;
}
public function /*void*/ setCreateTimeNull()
{
$this->create_time = null;
$this->create_time_status_field = true;
$this->this_table_status_field = true;
}
public function /*string*/ toDebugString()
{
$dbg = "(";
$dbg .= ("id={$this->id},");
$dbg .= ("user_id={$this->user_id},");
$dbg .= ("server_id={$this->server_id},");
$dbg .= ("account={$this->account},");
$dbg .= ("proxy_id={$this->proxy_id},");
$dbg .= ("socket_id={$this->socket_id},");
$dbg .= ("type={$this->type},");
$dbg .= ("state={$this->state},");
$dbg .= ("address={$this->address},");
$dbg .= ("create_time={$this->create_time},");
$dbg .= ")";
return str_replace(",)",")",$dbg);
}
}
?>
| true |
278570662e5c68e767979631de6da4f9d9c5f6e4 | PHP | kamguir/garagelavage | /lib/model/TblFacture.php | UTF-8 | 5,557 | 2.671875 | 3 | [] | no_license | <?php
/**
* Skeleton subclass for representing a row from the 'tbl_facture' table.
*
*
*
* This class was autogenerated by Propel 1.6.6-dev on:
*
* 10/12/13 18:14:04
*
* You should add additional methods to this class to meet the
* application requirements. This class will only be generated as
* long as it does not already exist in the output directory.
*
* @package propel.generator.lib.model
*/
class TblFacture extends BaseTblFacture {
public function __toString() {
return $this->getIdFacture();
}
public function getLibelle() {
return 'rrrr';
// return $this->getRefTypeLavage()->getLibelle();
}
public function getMontantTotalParDate($date) {
$jour = date('d');
$mois = date('m');
$annee = date('Y');
if ($date == $jour) {
$jourCourant = 'DAY(' . TblFacturePeer::DATE_REGLEMENT . ')=' . $jour;
$moisCourant = 'MONTH(' . TblFacturePeer::DATE_REGLEMENT . ')=' . $mois;
$anneeCourante = 'YEAR(' . TblFacturePeer::DATE_REGLEMENT . ')=' . $annee;
}
if ($date == $mois) {
$jourCourant = 'DAY(' . TblFacturePeer::DATE_REGLEMENT . ')between 1 and 31';
$moisCourant = 'MONTH(' . TblFacturePeer::DATE_REGLEMENT . ')=' . $mois;
$anneeCourante = 'YEAR(' . TblFacturePeer::DATE_REGLEMENT . ')=' . $annee;
}
if ($date == $annee) {
$jourCourant = 'DAY(' . TblFacturePeer::DATE_REGLEMENT . ')between 1 and 31';
$moisCourant = 'MONTH(' . TblFacturePeer::DATE_REGLEMENT . ')between 1 and 12';
$anneeCourante = 'YEAR(' . TblFacturePeer::DATE_REGLEMENT . ')=' . $annee;
}
return (double) TblFactureQuery::create()
->addAnd(TblFacturePeer::DATE_REGLEMENT, $jourCourant, Criteria::CUSTOM)
->addAnd(TblFacturePeer::DATE_REGLEMENT, $moisCourant, Criteria::CUSTOM)
->addAnd(TblFacturePeer::DATE_REGLEMENT, $anneeCourante, Criteria::CUSTOM)
// ->useRefTypeLavageQuery()
// ->withColumn('SUM(' . RefTypeLavagePeer::MONTANT_LAVAGE . ')', "montantTotal")
// ->endUse()
->withColumn('SUM(' . TblFacturePeer::PRIX_LAVAGE . ')', "montantTotal")
->select('montantTotal')
->findOne();
echo Propel::getConnection()->getLastExecutedQuery();
die;
}
public function getMontantTotalParWeek() {
$weekAcctuel = 'WEEK(' . TblFacturePeer::DATE_REGLEMENT . ')=WEEK(CURDATE())';
$anneeAcctuelle = 'YEAR(' . TblFacturePeer::DATE_REGLEMENT . ')=' . date('Y');
return (double) TblFactureQuery::create()
->addAnd(TblFacturePeer::DATE_REGLEMENT, $weekAcctuel, Criteria::CUSTOM)
->addAnd(TblFacturePeer::DATE_REGLEMENT, $anneeAcctuelle, Criteria::CUSTOM)
// ->useRefTypeLavageQuery()
// ->withColumn('SUM(' . RefTypeLavagePeer::MONTANT_LAVAGE . ')', "montantTotal")
// ->endUse()
->withColumn('SUM(' . TblFacturePeer::PRIX_LAVAGE . ')', "montantTotal")
->select('montantTotal')
->findOne();
echo Propel::getConnection()->getLastExecutedQuery();
die;
}
function getMontantReglement($mois) {
return (double) TblFactureQuery::create()
->addAnd(TblFacturePeer::DATE_REGLEMENT, 'MONTH(' . TblFacturePeer::DATE_REGLEMENT . ')=' . $mois, Criteria::CUSTOM)
->addAnd(TblFacturePeer::DATE_REGLEMENT, 'YEAR(' . TblFacturePeer::DATE_REGLEMENT . ')=' . date('Y'), Criteria::CUSTOM)
->useLnkTypeLavageFactureQuery()
->useRefTypeLavageQuery()
->withColumn('SUM(' . RefTypeLavagePeer::MONTANT_LAVAGE . ')', "montantTotal")
->endUse()
->endUse()
// ->useRefTypeLavageQuery()
// ->withColumn('SUM(' . RefTypeLavagePeer::MONTANT_LAVAGE . ')', "montantTotal")
// ->endUse()
->select('montantTotal')
->findOne();
echo Propel::getConnection()->getLastExecutedQuery();
die;
}
public function toArrayString() {
$nomEmploye = ' -- ';
if ($this->getTblClient()) {
$nomEmploye = $this->getTblClient()->getLibelle();
}
if ($this->getTblVoiture()) {
$pieces = explode("/", $this->getTblVoiture()->getImmatriculation());
$marqueVoiture = $this->getTblVoiture()->getRefMarque()->getMarqueLibelle();
}else{
$imat = '0000/0/00';
$pieces = explode("/", $imat);
$marqueVoiture = '--';
}
return array(
// $this->getIdFacture(),
$marqueVoiture,
'<p dir=\'rtl\' lang=\'ar\'>'.$pieces[2].'/'.$pieces[1].'/'.$pieces[0].'</p>',
$nomEmploye,
$this->getPrixLavage(),
$this->getDateReglement(),
"DT_RowId" => "row_" . $this->getIdFacture()
);
}
function getNrbVoituresparEmploye($idEmploye) {
return (int) TblFactureQuery::create()
->filterByIdEmploye($idEmploye)
->count();
}
}
// TblFacture
| true |
5b26591d7f2684062ae3eef4907331086fb53858 | PHP | balihoo/scrumboard | /RestClient.php | UTF-8 | 6,448 | 2.890625 | 3 | [] | no_license | <?php
/*
Copyright (c) 2012 Balihoo, Inc.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
// ========================================================================
// ensure Curl is installed
if (!extension_loaded("curl")) {
throw(new Exception(
"Curl extension is required"));
}
/*
if(!class_exists("RemoteService", false)) {
interface RemoteService
{
public function init($url);
public function set($name, $value);
public function execute();
public function getInfo($name);
public function lastError();
public function close();
}
}
*/
class CurlRemoteService /*implements RemoteService*/
{
private $handle = null;
public function init($url) {
$this->handle = curl_init($url);
}
public function set($name, $value) {
curl_setopt($this->handle, $name, $value);
}
public function execute() {
return curl_exec($this->handle);
}
public function getInfo($name) {
return curl_getinfo($this->handle, $name);
}
public function lastError() {
return curl_error($this->handle);
}
public function close() {
curl_close($this->handle);
}
}
/*
* RestResponse holds all the REST response data
* Before using the reponse, check IsError to see if an exception
* occurred with the data sent to Balihoo
* ResponseJSON will contain a JSON text
* ResponseText contains the raw string response
* Url and QueryString are from the request
* HttpStatus is the response code of the request
*/
class RestResponse
{
public $ResponseText;
public $ResponseJSON;
public $HttpStatus;
public $Url;
public $QueryString;
public $IsError;
public $ErrorMessage;
public function __construct($url, $text, $status)
{
preg_match('/([^?]+)\??(.*)/', $url, $matches);
$this->Url = $matches[1];
$this->QueryString = $matches[2];
$this->ResponseText = $text;
$this->HttpStatus = $status;
if ($this->HttpStatus != 204) {
// $this->ResponseJSON = json_decode($text);
}
if (($this->IsError = ($status >= 400)) && is_object($this->ResponseJSON)) {
$this->ResponseJSON = json_decode($text);
$this->ErrorMessage =
(string)$this->ResponseJSON->Message;
}
}
}
/* throws RestException on error
* Useful to catch this exception separately from general PHP
* exceptions, if you want
*/
class RestException extends Exception
{
}
class RestClient
{
protected $endpoint;
protected $user;
protected $password;
protected $serviceClass;
/** @var CurlRemoteService */
protected $service;
public function __construct($username, $password, $restUrl, $service = "CurlRemoteService")
{
$this->user = $username;
$this->password = $password;
$this->endpoint = "https://$restUrl";
$this->serviceClass = $service;
}
public function getFullUrl($path)
{
return "{$this->endpoint}/$path";
}
public function post($path, $params = array())
{
return $this->request($path, 'POST', $params);
}
public function get($path, $params = array())
{
return $this->request($path, 'GET', $params);
}
public function request($path, $method = 'GET', $vars = array())
{
return $this->requestInner($path, $method, $vars);
}
private function encodeVars(&$vars)
{
$encoded = "";
foreach ($vars as $key => $value)
{
$encoded .= "$key=" . urlencode($value) . "&";
}
return substr($encoded, 0, -1);
}
private function joinToken($path)
{
return FALSE === strpos($path, '?') ? "?" : "&";
}
private function makeUrl($path, $method, $encodedVars)
{
// construct full url
$url = "{$this->endpoint}/$path";
// if GET and vars, append them
if (strtoupper($method) == "GET") {
$url .= $this->joinToken($path) . $encodedVars;
}
return $url;
}
public function requestInner($path, $method = "GET", $vars = array())
{
$fp = null;
$tmpfile = "";
$encoded = $this->encodeVars($vars);
// construct full url
$url = $this->makeUrl($path, $method, $encoded);
// initialize a new curl object
$this->service = new $this->serviceClass();
$this->service->init($url);
$this->service->set(CURLOPT_SSL_VERIFYPEER, false);
$this->service->set(CURLOPT_RETURNTRANSFER, true);
switch (strtoupper($method)) {
case "GET":
$this->service->set(CURLOPT_HTTPGET, true);
break;
case "POST":
$this->service->set(CURLOPT_POST, true);
$this->service->set(CURLOPT_POSTFIELDS, $encoded);
break;
case "PUT":
$this->service->set(CURLOPT_POSTFIELDS, $encoded);
$this->service->set(CURLOPT_CUSTOMREQUEST, "PUT");
file_put_contents(
$tmpfile = tempnam("/tmp", "put_"),
$encoded);
$this->service->set(CURLOPT_INFILE, $fp = fopen(
$tmpfile,
'r'));
$this->service->set(CURLOPT_INFILESIZE, filesize($tmpfile));
break;
case "DELETE":
$this->service->set(CURLOPT_CUSTOMREQUEST, "DELETE");
break;
default:
throw(new RestException("Unknown method $method"));
break;
}
// send credentials
if(isset($this->user))
{
$this->service->set(CURLOPT_USERPWD, "{$this->user}:{$this->password}");
}
if (FALSE === ($result = $this->service->execute())) {
throw(new RestException(
"Curl failed with error " . $this->service->lastError()));
}
// get result code
$responseCode = $this->service->getInfo(CURLINFO_HTTP_CODE);
// unlink tmpfiles
if ($fp) {
fclose($fp);
}
if (strlen($tmpfile)) {
unlink($tmpfile);
}
return new RestResponse($url, $result, $responseCode);
}
}
| true |