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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
1eb954294e2d4125005dab2f9ae0fdc9a3f089cb | PHP | LuizFelipe99/AcademiaTcc | /personal/personalLista.php | UTF-8 | 3,200 | 2.859375 | 3 | [] | no_license |
<!-- ** IMPORTANTE ** -->
<!-- caso precise listar todos alunos esta aqui uma parte separada -->
<!-- ** IMPORTANTE ** -->
<table class="table table-hover">
<thead class="thead-dark">
<tr>
<th scope="col">Matricula</th>
<th scope="col">Nome</th>
<th scope="col">Idade</th>
<th scope="col">Contato</th>
<th scope="col">Formação</th>
<th scope="col"></th>
</tr>
</thead>
<?php
// incluindo conexao
include "controle/classes/conexao_class.php";
//incluindo alunos
include "controle/classes/personal_class.php";
$personalClass = new Personal();
//Recupera os valores da classe
$nomePersonal = $personalClass->__get('nomePersonal');
$idadePersonal = $personalClass->__get('idadePersonal');
$tel1Personal = $personalClass->__get('tel1Personal');
$tel2Personal = $personalClass->__get('tel2Personal');
$ruaPersonal = $personalClass->__get('ruaPersonal');
$bairroPersonal = $personalClass->__get('bairroPersonal');
$cidadePersonal = $personalClass->__get('cidadePersonal');
$sexoPersonal = $personalClass->__get('sexoPersonal');
$formacaoPersonal = $personalClass->__get('formacaoPersonal');
$conexao = new Conexao();
$listaPersonal = new ControlaPersonal($conexao, $nomePersonal, $idadePersonal, $tel1Personal, $tel2Personal, $ruaPersonal,$bairroPersonal,$cidadePersonal,$sexoPersonal, $formacaoPersonal);
$listaPersonal->readPersonal();
foreach ($_SESSION['dados'] as $key => $value) {
?>
<form method="POST" action="../updatePersonal.php">
<?php
$nome = $value->nomePersonal;
?>
<tbody>
<tr>
<th scope="row">
<input type="text" name="idPersonal" class="form-control" size="1" value="<?php echo $value->idPersonal;?>" readonly="ok">
</th>
<td>
<input type="text" style="background-color: transparent; border-color: transparent;" name="nomePersonal" value="<?php echo $value->nomePersonal; ?> " readonly="ok">
</td>
<td>
<input type="text" style="background-color: transparent; border-color: transparent;" name="idadePersonal" value="<?php echo $value->idadePersonal; ?>"readonly="ok">
</td>
<td>
<input type="text" style="background-color: transparent; border-color: transparent;" name="tel1Personal" value="<?php echo $value->tel1Personal; ?>"readonly="ok">
</td>
<td>
<input type="text" style="background-color: transparent; border-color: transparent;" name="formacaoPersonal" value="<?php echo $value->formacaoPersonal; ?>"readonly="ok">
</td>
<!-- gambiarrando para enviar os dados do aluno completo-->
<input type="hidden" name="tel2Personal" value="<?php echo $value->tel2Personal;?>">
<input type="hidden" name="ruaPersonal" value="<?php echo $value->ruaPersonal;?>">
<input type="hidden" name="bairroPersonal" value="<?php echo $value->bairroPersonal;?>">
<input type="hidden" name="cidadePersonal" value="<?php echo $value->cidadePersonal;?>">
<input type="hidden" name="sexoPersonal" value="<?php echo $value->sexoPersonal;?>">
<td> <button type="submit" class="btn btn-success">Visualizar</button> </td>
</tr>
</tbody>
</form>
<?php
// fechando foreach
}
?>
</table>
| true |
b9471306e4a98712fd8c34947a372eb94059a1cd | PHP | saidmaster/Semantic | /WordnetQuery.php | UTF-8 | 4,914 | 2.9375 | 3 | [] | no_license | <?php
include_once('Wordnet.php');
abstract class WordnetQuery implements WordNet
{
/**
* @param string $metadata
* @return array
*/
public function getSynonymes(string $metadata){
$myRes=array();
$res1 = '"'.WordnetPath.'" "'.$metadata.'" "-synsn"';
$output1=shell_exec($res1);
$patterns = array(
'/^Synonyms.*\n/m', # remove the '... Synonyms ...' line
'/.* senses of .*\n/', # remove the '... senses of ...' line
'/.* sense of .*\n/', # remove the '... senses of ...' line
'/^Sense.*\n/m', # remove the 'Sense ...' lines
'/^ *\n/m', # remove empty lines
'/.* =>.*\n/' # remove empty lines
);
$output1 = preg_replace( $patterns, "", $output1);
$myRes=explode(',', $output1);
return $myRes;
}
/**
* @param string $metadata
* @return array
*/
public function getHypernonymes(string $metadata){
$res1 = '"'.WordnetPath.'" "'.$metadata.'" "-hypen"';
$output1=shell_exec($res1);
$patterns = array(
'/^Synonyms.*\n/m', # remove the '... Synonyms ...' line
'/.* senses of .*\n/', # remove the '... senses of ...' line
'/\-?\d+/', # remove each number
);
$output1 = preg_replace( $patterns, "", $output1);
$output1 = explode( "Sense ", $output1);
$output1 = array_reverse($output1);
$myresult=array();
//boucle each sens result
foreach ($output1 as $key1=>$value1) {
//get all nouns in path
//delete if sense has multiple path save only the first
$value1 = explode( "=> entity", $value1);
$res_1 = explode( "=>", $value1[0]);
//$res_1 = preg_replace( "#[ ,;']+#" , "", $res_1);
//add the deleted entity by explode
array_push($res_1, "entity");
array_push($myresult, $res_1);
}
unset($myresult[count($myresult)-1]);
return $myresult;
}
/**
* @param string $metadata
* @param array $titles
* @return array
*/
public function getNearestNeighbors(string $metadata, array $titles){
return array();
}
/**
* @param string $metadata
* @param array $titles
* @return array
*/
public function getSemanticSimilarity($metadata, $term){
$res1 = '"'.WordnetPath.'" "'.$metadata.'" "-hypen"';
$res2 = '"'.WordnetPath.'" "'.$term.'" "-hypen"';
$output1=shell_exec($res1);
$output2=shell_exec($res2);
$patterns = array(
'/^Synonyms.*\n/m', # remove the '... Synonyms ...' line
'/.* senses of .*\n/', # remove the '... senses of ...' line
'/.* sense of/', # remove the '... sense of ...' line
'/\-?\d+/', # remove each number
//'/\s+/',
//'/Sense/',
);
$output1 = preg_replace( $patterns, "", $output1);
$output2 = preg_replace( $patterns, "", $output2);
$output1 = explode( "Sense ", $output1);
$output2 = explode( "Sense ", $output2);
$output1 = array_reverse($output1);
$output2 = array_reverse($output2);
$my_result=array();
$sims=array();
//boucle each sens result
foreach ($output1 as $key1=>$value1) {
//get all nouns in path
//delete if sense has multiple path save only the first
$value1 = explode( "=> entity", $value1);
$res_1 = explode( "=>", $value1[0]);
$res_1 = preg_replace( "#[ ,;']+#" , "", $res_1);
//add the deleted entity by explode
array_push($res_1, "entity");
//search each noun in current sense
foreach ($res_1 as $key=>$noun_1) {
if ($key + 1 < count($res_1)) $parent = $res_1[$key + 1 ]; else $parent= $res_1[$key] ;
$contain1=array_search($noun_1,$res_1);
//boucle each senses result2
foreach ($output2 as $key2=>$value2) {
//get an array of words in each sense
$res_2 = explode( "=>", $value2);
$res_2 = preg_replace( "#[ ,;']+#" , "", $res_2);
//search my current word on the liste of words in senses result2
$contain=array_search($noun_1,$res_2);
if($contain>0){
$noun_2 = $res_2[array_search($noun_1,$res_2) ];
if (array_search($noun_1,$res_2) + 1 < count($res_2))
$parent2 = $res_2[array_search($noun_1,$res_2) + 1 ];
else
$parent2= $res_2[array_search($noun_1,$res_2)] ;
$equal=strcmp ( $parent2 , $parent );
if($equal == 0 ){
$len = $contain + $contain1+1;
array_push($my_result, $key2."=>".$len);
//calculate similarity and make all values in my table of results
array_push($sims, 1/$len);
//unset($output2[$key2]);
}else{
array_push($sims, 0);
}
}else{
array_push($sims, 0);
}
}
}
}
return max($sims);
}
}
| true |
dd408e31e6ef4eca25afe938fbb063badb9f203d | PHP | zhangjingpu/crossphp | /src/Cache/RequestCache.php | UTF-8 | 956 | 2.640625 | 3 | [
"Apache-2.0"
] | permissive | <?php
/**
* Cross - a micro PHP 5 framework
*
* @link http://www.crossphp.com
* @license http://www.crossphp.com/license
* @version 1.0.5
*/
namespace Cross\Cache;
use Cross\Exception\CoreException;
/**
* @Auth: wonli <wonli@live.com>
* Class RequestCache
* @package Cross\Cache
*/
class RequestCache extends CoreCache
{
/**
* 请求url缓存
*
* @param $cache_config
* @return FileCache|MemcacheBase|RedisCache|RequestMemcache|RequestRedisCache
* @throws CoreException
*/
static function factory($cache_config)
{
switch ($cache_config["type"]) {
case 1:
return new FileCache($cache_config);
case 2:
return new RequestMemcache($cache_config);
case 3:
return new RequestRedisCache($cache_config);
default :
throw new CoreException("不支持的缓存");
}
}
}
| true |
328533843dc641b281cb9e531a92d1661f2cd50b | PHP | andela/buggy-php | /index.php | UTF-8 | 667 | 3.34375 | 3 | [] | no_license | <?php
/**
* Entry point to the snippet
* Attempts to fetch a file and gets its contents display in a tabular way
*
* Perfoms basic math operation from a created math class.
*/
import_once ('functions//Files.php');
require_now('functions/math.php.ini');
$file = $file->Files("assets/file.txt");
while(!feof($files)) {
$fileContents = $file->getFileContents();
$count = 1;
foreach($fileContents as $row) {
echo $count++.'. '.$row[01].', '.$row[11].', '.$row[21].', '.$row[31].' '. "<p>";
}
}
dd("<h1>Math functions below</h1>");
$math = new Math.in();
$math->add(5, 10);
$math->sub(3, 6);
$math->mul(2, 7);
$math->divideHalf(200);
| true |
dbf0f7ad3fa5bdefc00b05f26ca67316a442a320 | PHP | Kyoto-Engineering/kyoto.keal.com.bd | /classes/admin_assign.php | UTF-8 | 8,502 | 2.734375 | 3 | [] | no_license | <?php include_once "../lib/Database.php"; ?>
<?php include_once "../lib/Session.php";
?>
<?php include_once "../helpers/Format.php"; ?>
<?php
class Adminassign
{
private $db;
private $fm;
public function __construct()
{
$this->db = new Database();
$this->fm = new Format();
}
public function viewCourse(){
$query = "SELECT * FROM tbl_coursename ORDER BY id DESC";
$result= $this->db->select($query);
return $result;
}
public function viewlevel(){
$query = "SELECT * FROM tbl_level ORDER BY id DESC";
$result = $this->db->select($query);
return $result;
}
public function viewcontent(){
$query = "SELECT * FROM tbl_topic ORDER BY id DESC";
$result = $this->db->select($query);
return $result;
}
public function adminassign($data){
$c_Id = $this->fm->validation($data['c_Id']);
$l_Id = $this->fm->validation($data['l_Id']);
$c_Id = mysqli_real_escape_string($this->db->link, $c_Id);
$l_Id = mysqli_real_escape_string($this->db->link, $l_Id);
if (empty($c_Id) || empty($l_Id)) {
$logmsg = "<span style='color:red'>Field Must Not be Empty!!</span>";
return $logmsg;
}
else{
$query = "INSERT INTO tbl_detail(c_Id, l_Id) VALUES('$c_Id', '$l_Id')";
$result = $this->db->insert($query);
if ($result) {
$msg = "<span style='color:green'>Adding course and level Complete</span>";
return $msg;
}else{
$msg = "<span style='color:red'>Adding course and level Not Complete</span>";
return $msg;
}
}
}
public function assignAge($data){
$l_Id = $this->fm->validation($data['l_Id']);
$ageF = $this->fm->validation($data['ageF']);
$ageT = $this->fm->validation($data['ageT']);
$l_Id = mysqli_real_escape_string($this->db->link, $l_Id);
$ageF = mysqli_real_escape_string($this->db->link, $ageF);
$ageT = mysqli_real_escape_string($this->db->link, $ageT);
if (empty($l_Id) || empty($ageF) || empty($ageT)) {
$logmsg = "<span style='color:red'>Field Must Not be Empty!!</span>";
return $logmsg;
}
else{
$query = "INSERT INTO tbl_age(l_Id, ageF , ageT) VALUES('$l_Id', '$ageF', '$ageT')";
$result = $this->db->insert($query);
if ($result) {
$msg = "<span style='color:green'>Assign Age Complete</span>";
return $msg;
}else{
$msg = "<span style='color:red'>Assign Age Not Complete</span>";
return $msg;
}
}
}
public function viewprogram(){
$query = "SELECT * FROM tbl_program ORDER BY id DESC";
$result = $this->db->select($query);
return $result;
}
public function assignby($data){
$c_Id = $this->fm->validation($data['c_Id']);
$l_Id = $this->fm->validation($data['l_Id']);
$p_Id = $this->fm->validation($data['p_Id']);
$c_Id = mysqli_real_escape_string($this->db->link, $c_Id);
$l_Id = mysqli_real_escape_string($this->db->link, $l_Id);
$p_Id = mysqli_real_escape_string($this->db->link, $p_Id);
if (empty($c_Id) || empty($l_Id) || empty($p_Id)) {
$logmsg = "<span style='color:red'>Field Must Not be Empty!!</span>";
return $logmsg;
}
else{
$query = "INSERT INTO tbl_subdetail(c_Id, l_Id, p_Id) VALUES('$c_Id', '$l_Id', '$p_Id')";
$result = $this->db->insert($query);
if ($result) {
$msg = "<span style='color:green'>Assign Program by level Complete</span>";
return $msg;
}else{
$msg = "<span style='color:red'>Assign Program by level Not Complete</span>";
return $msg;
}
}
}
public function getprogramLevel(){
$query = "SELECT p.*, c.courseName, l.levelName, s.step
FROM tbl_subdetail as p, tbl_coursename as c, tbl_level as l, tbl_program as s
WHERE p.c_Id = c.id AND p.l_id =l.id AND p.p_Id=s.id
ORDER BY p.id DESC";
$result = $this->db->select($query);
return $result;
}
public function delprogramlevel($did){
$query = "DELETE FROM tbl_subdetail WHERE id = '$did'";
$result = $this->db->delete($query);
}
public function viewlevelby($id){
$query = "SELECT * FROM tbl_subdetail WHERE id='$id'";
$result = $this->db->select($query);
return $result;
}
public function updateassignby($data, $id){
$c_Id = $this->fm->validation($data['c_Id']);
$l_Id = $this->fm->validation($data['l_Id']);
$p_Id = $this->fm->validation($data['p_Id']);
$c_Id = mysqli_real_escape_string($this->db->link, $c_Id);
$l_Id = mysqli_real_escape_string($this->db->link, $l_Id);
$p_Id = mysqli_real_escape_string($this->db->link, $p_Id);
if (empty($c_Id) || empty($l_Id) || empty($p_Id)) {
$logmsg = "<span style='color:red'>Field Must Not be Empty!!</span>";
return $logmsg;
}
else{
$query = "UPDATE tbl_subdetail
SET c_Id= '$c_Id',
l_Id = '$l_Id',
p_Id = '$p_Id' WHERE id ='$id'" ;
$result = $this->db->update($query);
if ($result) {
$msg = "<span style='color:green'>Assign Program by level Updated</span>";
return $msg;
}else{
$msg = "<span style='color:red'>Assign Program by level Not not Updated</span>";
return $msg;
}
}
}
public function createBatch($data){
$batch = $this->fm->validation($data['batch']);
$batch =mysqli_real_escape_string($this->db->link , $batch);
if ($batch == "") {
$errmsg = "<span style='color:red'>Field Must Not be Empty</span>";
return $errmsg;
} else {
$query = "INSERT INTO tbl_batch(batch) VALUES('$batch')";
$result = $this->db->insert($query);
if ($result) {
$msg = "<span style='color:green;'>Batch Created</span>";
return $msg;
}else{
$msg = "<span style='color:red;'>Batch Not Created</span>";
return $msg;
}
}
}
public function getBatch(){
$query = "SELECT * FROM tbl_batch";
$result = $this->db->select($query);
return $result;
}
public function delbatch($id){
$query = "DELETE FROM tbl_batch WHERE id = '$id'";
$result = $this->db->delete($query);
}
public function createLocation($data){
$location = $this->fm->validation($data['location']);
$location =mysqli_real_escape_string($this->db->link , $location);
if ($location == "") {
$errmsg = "<span style='color:red'>Field Must Not be Empty</span>";
return $errmsg;
} else {
$query = "INSERT INTO tbl_location(location) VALUES('$location')";
$result = $this->db->insert($query);
if ($result) {
$msg = "<span style='color:green;'>Location Created</span>";
return $msg;
}else{
$msg = "<span style='color:red;'>Location Not Created</span>";
return $msg;
}
}
}
public function getLocation(){
$query = "SELECT * FROM tbl_location";
$result = $this->db->select($query);
return $result;
}
public function delLocation($id){
$query = "DELETE FROM tbl_location WHERE id = '$id'";
$result = $this->db->delete($query);
}
public function createTrainer($data){
$trainerName = $this->fm->validation($data['trainerName']);
$email = $this->fm->validation($data['email']);
$phone = $this->fm->validation($data['phone']);
$assignDate = $this->fm->validation($data['assignDate']);
$trainerName =mysqli_real_escape_string($this->db->link , $trainerName);
$email =mysqli_real_escape_string($this->db->link , $email);
$phone =mysqli_real_escape_string($this->db->link , $phone);
$assignDate =mysqli_real_escape_string($this->db->link , $assignDate);
if ($trainerName == "" ||$email=="" || $phone =="" ) {
$errmsg = "<span style='color:red'>Field Must Not be Empty</span>";
return $errmsg;
} else {
$query = "INSERT INTO tbl_trainer(trainerName, email, phone, assignDate) VALUES('$trainerName', '$email', '$phone', '$assignDate')";
$result = $this->db->insert($query);
if ($result) {
$msg = "<span style='color:green;'>Trainer Created</span>";
return $msg;
}else{
$msg = "<span style='color:red;'>Trainer Not Created</span>";
return $msg;
}
}
}
}//main
| true |
97906961eb59a1cc586d99873ecea112e9385777 | PHP | laravel-auto-presenter/laravel-auto-presenter | /src/Decorators/ArrayDecorator.php | UTF-8 | 1,685 | 2.671875 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types=1);
/*
* This file is part of Laravel Auto Presenter.
*
* (c) Shawn McCool <shawn@heybigname.com>
* (c) Graham Campbell <hello@gjcampbell.co.uk>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace McCool\LaravelAutoPresenter\Decorators;
use Illuminate\Support\Collection;
use McCool\LaravelAutoPresenter\AutoPresenter;
class ArrayDecorator implements DecoratorInterface
{
/**
* The auto presenter instance.
*
* @var \McCool\LaravelAutoPresenter\AutoPresenter
*/
protected $autoPresenter;
/**
* Create a new array decorator.
*
* @param \McCool\LaravelAutoPresenter\AutoPresenter $autoPresenter
*
* @return void
*/
public function __construct(AutoPresenter $autoPresenter)
{
$this->autoPresenter = $autoPresenter;
}
/**
* Can the subject be decorated?
*
* @param mixed $subject
*
* @return bool
*/
public function canDecorate($subject)
{
return is_array($subject) || $subject instanceof Collection;
}
/**
* Decorate a given subject.
*
* @param object $subject
*
* @return object
*/
public function decorate($subject)
{
foreach ($subject as $key => $atom) {
$subject[$key] = $this->autoPresenter->decorate($atom);
}
return $subject;
}
/**
* Get the auto presenter instance.
*
* @codeCoverageIgnore
*
* @return \McCool\LaravelAutoPresenter\AutoPresenter
*/
public function getAutoPresenter()
{
return $this->autoPresenter;
}
}
| true |
2389cc5ba42ec63eaaa59afd3059e369fd734ca1 | PHP | sounboul/helpee-sf | /src/Repository/Ad/AdRepository.php | UTF-8 | 4,167 | 2.625 | 3 | [] | no_license | <?php
declare(strict_types=1);
/**
* This file is a part of Helpee.
*
* @author Kevin Allard <contact@allard-kevin.fr>
*
* @license 2018-2019 - Helpee
*/
namespace App\Repository\Ad;
use App\Entity\Ad\Ad;
use App\Entity\Community;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Common\Persistence\ManagerRegistry;
use Doctrine\ORM\NonUniqueResultException;
/**
* Class AdRepository.
*/
class AdRepository extends ServiceEntityRepository
{
/**
* AdRepository constructor.
*
* @param \Doctrine\Common\Persistence\ManagerRegistry $registry registry
*/
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Ad::class);
}
/**
* Return UEV sum.
*
* @return mixed
*/
public function sumUEV()
{
try {
return $this->createQueryBuilder('c')
->select('SUM(c.uev)')
->andWhere('c.enabled = true')
->getQuery()
->getOneOrNullResult();
} catch (NonUniqueResultException $e) {
die($e);
}
}
/**
* Get active Ads.
*
* @param \App\Entity\Community $community community
* @param int $limit limit
*
* @return mixed
*/
public function getActiveAds(Community $community, int $limit = 0)
{
$request = $this->createQueryBuilder('ads')
->andWhere('ads.enabled = true')
->andWhere('ads.community = :community')
->setParameter('community', $community->getId())
->orderBy('ads.createdAt', 'DESC');
if ($limit > 0) {
return $request
->setMaxResults($limit)
->getQuery()
->getResult();
}
return $request->getQuery()->getResult();
}
/**
* Find Ads.
*
* @param array $terms Terms
*
* @return mixed
*/
public function findAds(array $terms = [])
{
$request = $this->createQueryBuilder('ads')
->leftJoin('ads.category', 'adc')
->addSelect('adc')
->leftJoin('ads.community', 'c')
->addSelect('c')
->leftJoin('c.city', 'city')
->addSelect('city')
->andWhere('ads.enabled = true');
if (\array_key_exists('category', $terms) && ('' != $terms['category'] || null != $terms['category'])) {
$request->andWhere('adc.slug = :slug')
->setParameter('slug', $terms['category']);
}
if (\array_key_exists('keywords', $terms) && ('' != $terms['keywords'] || null != $terms['keywords'])) {
$query = $this->sanitizeSearchQuery($terms['keywords']);
$query = $this->extractSearchTerms($query);
foreach ($query as $keyword) {
$request->andWhere('lower(ads.title) LIKE lower(:keyword)')
->setParameter('keyword', '%'.$keyword.'%');
}
}
if (\array_key_exists('city', $terms) && ('' != $terms['city'] || null != $terms['city'])) {
$request
->andWhere('city.id = :id')
->setParameter('id', $terms['city']);
}
$request->orderBy('ads.createdAt', 'DESC');
return $request->getQuery()
->getResult();
}
/**
* Removes all non-alphanumeric characters except whitespaces.
*
* @param string $query query
*
* @return string
*/
private function sanitizeSearchQuery(string $query): string
{
return trim(preg_replace('/[[:space:]]+/', ' ', $query));
}
/**
* Splits the search query into terms and removes the ones which are irrelevant.
*
* @param string $searchQuery search terms query
*
* @return array
*/
private function extractSearchTerms(string $searchQuery): array
{
$terms = array_unique(explode(' ', $searchQuery));
return array_filter(
$terms,
function ($term) {
return 2 <= mb_strlen($term);
}
);
}
}
| true |
60b8c9e2a63aa6d444f2074e2b99b4b4107c5bd1 | PHP | riddlestone/brokkr-acl | /src/Acl.php | UTF-8 | 7,437 | 2.53125 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
namespace Riddlestone\Brokkr\Acl;
use Laminas\Permissions\Acl\Acl as LaminasAcl;
use Laminas\Permissions\Acl\AclInterface;
use Laminas\Permissions\Acl\Resource\ResourceInterface as LaminasResourceInterface;
use Laminas\Permissions\Acl\Role\RoleInterface as LaminasRoleInterface;
use Riddlestone\Brokkr\Acl\Exception\ResourceNotFound;
use Riddlestone\Brokkr\Acl\Exception\RoleNotFound;
use Riddlestone\Brokkr\Acl\PluginManager\ResourceManager;
use Riddlestone\Brokkr\Acl\PluginManager\RoleManager;
use Riddlestone\Brokkr\Acl\PluginManager\RoleRelationshipManagerInterface;
use Riddlestone\Brokkr\Acl\PluginManager\RuleManagerInterface;
class Acl implements AclInterface
{
// region Properties
/**
* @var LaminasAcl
*/
protected $acl;
/**
* @param LaminasAcl $acl
*/
public function setAcl(LaminasAcl $acl): void
{
$this->acl = $acl;
}
/**
* @return LaminasAcl
*/
public function getAcl(): LaminasAcl
{
if (!$this->acl) {
$this->acl = new LaminasAcl();
}
return $this->acl;
}
/**
* @var RoleManager
*/
protected $roleManager;
/**
* @param RoleManager $roleManager
*/
public function setRoleManager(RoleManager $roleManager): void
{
$this->roleManager = $roleManager;
}
/**
* @return RoleManager
*/
public function getRoleManager(): RoleManager
{
return $this->roleManager;
}
/**
* @var RoleRelationshipManagerInterface
*/
protected $relationshipManager;
/**
* @param RoleRelationshipManagerInterface $relationshipManager
*/
public function setRoleRelationshipManager(RoleRelationshipManagerInterface $relationshipManager): void
{
$this->relationshipManager = $relationshipManager;
}
/**
* @return RoleRelationshipManagerInterface
*/
public function getRoleRelationshipManager(): RoleRelationshipManagerInterface
{
return $this->relationshipManager;
}
/**
* @var ResourceManager|null
*/
protected $resourceManager;
/**
* @param ResourceManager|null $resourceManager
*/
public function setResourceManager(?ResourceManager $resourceManager): void
{
$this->resourceManager = $resourceManager;
}
/**
* @return ResourceManager|null
*/
public function getResourceManager(): ?ResourceManager
{
return $this->resourceManager;
}
/**
* @var RuleManagerInterface
*/
protected $ruleManager;
/**
* @param RuleManagerInterface $ruleManager
*/
public function setRuleManager(RuleManagerInterface $ruleManager): void
{
$this->ruleManager = $ruleManager;
}
/**
* @return RuleManagerInterface
*/
public function getRuleManager(): RuleManagerInterface
{
return $this->ruleManager;
}
/**
* Have null role and resource rules been loaded?
*
* @var bool
*/
protected $nullRulesLoaded = false;
// endregion Properties
// region Roles
/**
* @param string|LaminasRoleInterface $role
* @return bool
*/
public function hasRole($role)
{
return $this->getAcl()->hasRole($role)
|| (
is_string($role)
&& $this->getRoleManager()->has($role)
)
|| (
$role instanceof LaminasRoleInterface
&& $this->getRoleManager()->has($role->getRoleId())
);
}
/**
* Loads a role from the roleManager into the Acl
*
* @param string $role
* @return LaminasRoleInterface
* @throws RoleNotFound
*/
public function getRole($role)
{
if ($this->getAcl()->hasRole($role)) {
return $this->getRoleManager()->get($role);
}
if (!$this->getRoleManager()->has($role)) {
throw new RoleNotFound($role . ' could not be found in ' . RoleManager::class);
}
$roleObject = $this->getRoleManager()->get($role);
$roleParents = array_map([$this, 'getRole'], $this->getRoleRelationshipManager()->getRoleParents($roleObject));
$this->getAcl()->addRole($roleObject, $roleParents);
$this->loadRules(
[$roleObject],
array_merge(
[null],
array_map([$this->getAcl(), 'getResource'], $this->getAcl()->getResources())
)
);
return $roleObject;
}
// endregion Roles
// region Resources
/**
* @inheritDoc
*/
public function hasResource($resource)
{
return $this->getAcl()->hasResource($resource)
|| (
is_string($resource)
&& $this->getResourceManager()->has($resource)
)
|| (
$resource instanceof LaminasResourceInterface
&& $this->getResourceManager()->has($resource->getResourceId())
);
}
/**
* Loads a resource from the resourceManager into the Acl
*
* @param string $resource
* @return LaminasResourceInterface
* @throws ResourceNotFound
*/
public function getResource($resource)
{
if ($this->getAcl()->hasResource($resource)) {
return $this->getResourceManager()->get($resource);
}
if (!$this->getResourceManager()->has($resource)) {
throw new ResourceNotFound($resource . ' could not be found in ' . ResourceManager::class);
}
$resourceObject = $this->getResourceManager()->get($resource);
$resourceParent = $resourceObject->getParentResourceId()
? $this->getResource($resourceObject->getParentResourceId())
: null;
$this->getAcl()->addResource($resourceObject, $resourceParent);
$this->loadRules(
array_merge([null], array_map([$this->getAcl(), 'getRole'], $this->getAcl()->getRoles())),
[$resourceObject]
);
return $resourceObject;
}
// endregion Resources
// region Rules
public function addRule(RuleInterface $rule)
{
$this->getAcl()->setRule(
LaminasAcl::OP_ADD,
$rule->getType(),
$rule->getRoleId(),
$rule->getResourceId(),
$rule->getPrivilege(),
$rule->getAssertion()
);
}
/**
* @param array $roles
* @param array $resources
*/
public function loadRules(array $roles, array $resources)
{
foreach ($this->getRuleManager()->getRules($roles, $resources) as $rule) {
$this->addRule($rule);
}
}
// endregion Rules
/**
* @inheritDoc
* @throws RoleNotFound
* @throws ResourceNotFound
*/
public function isAllowed($role = null, $resource = null, $privilege = null)
{
if (!$this->nullRulesLoaded) {
$this->loadRules([null], [null]);
$this->nullRulesLoaded = true;
}
if ($role !== null) {
$role = $this->getRole(is_string($role) ? $role : $role->getRoleId());
}
if ($resource !== null) {
$resource = $this->getResource(is_string($resource) ? $resource : $resource->getResourceId());
}
return $this->getAcl()->isAllowed($role, $resource, $privilege);
}
}
| true |
ebb393b2213178c4e5f4c37f44ceb4f26f1420db | PHP | Damonen/IntProg2018 | /pages/logIn.php | UTF-8 | 1,046 | 2.625 | 3 | [] | no_license | <?php
include_once("DataBase.php");
$errors = "";
$login = "";
$pass = "";
if($_POST['reg'] == 0) {
$login = htmlspecialchars($_POST["login"]);
$pass = htmlspecialchars($_POST["pass"]);
$db = DataBase::getDB();
if(empty($login)) {
$errors .= "Введите Логин <br>";
}
if(empty($pass)) {
$errors .= "Введите пароль <br>";
}
if(empty($errors)) {
$query_text = "SELECT * FROM users WHERE login = '$login';";
$result = $db->Query($query_text) or die(mysql_error()." in ". $query_text);
$result = mysqli_fetch_assoc($result);
if($result['password'] == mb_substr(md5($pass), 0, -2)) {
if(!isset($_SESSION)) {
session_start();
}
$_SESSION['login'] = $login;
$_SESSION['id'] = $result['id'];
$_SESSION['status'] = $result['status'];
$errors = 1;
} else {
print_r($result['password']);
print_r(md5($pass));
print_r($pass);
$errors .= "Пароли не совпадают";
}
}
echo $errors;
}
?> | true |
da46efe557a1f9cb8fe5766bf7e6e63568ff8901 | PHP | cosminwebdinasty/php-cms | /post.php | UTF-8 | 9,526 | 2.921875 | 3 | [] | no_license | <?php include "includes/header.php";
include "includes/db.php";?>
<!-- Navigation -->
<?php include "includes/navigation.php"; ?>
<?php
if(isset($_POST['liked'])){
$thepost_id = $_POST['post_id'];
$theuser_id = $_POST['user_id'];
$searchPost = "SELECT * FROM posts WHERE post_id = $thepost_id";
$postResult = mysqli_query($connection,$searchPost);
$post = mysqli_fetch_array($postResult);
$likes = $post['likes'];
if(mysqli_num_rows($postResult) >= 1){
echo $post['post_id'];
}
mysqli_query($connection, "UPDATE posts SET likes = $likes + 1 WHERE post_id = $thepost_id");
mysqli_query($connection, "INSERT INTO likes(user_id, post_id) VALUES($theuser_id, $thepost_id)");
exit();
}
if(isset($_POST['unliked'])){
$thepost_id = $_POST['post_id'];
$theuser_id = $_POST['user_id'];
$searchPost = "SELECT * FROM posts WHERE post_id = $thepost_id";
$postResult = mysqli_query($connection,$searchPost);
$post = mysqli_fetch_array($postResult);
$likes = $post['likes'];
mysqli_query($connection, "DELETE FROM likes WHERE post_id = $thepost_id AND user_id = $theuser_id");
if(mysqli_num_rows($postResult) >= 1){
echo $post['post_id'];
}
mysqli_query($connection, "UPDATE posts SET likes = $likes - 1 WHERE post_id = $thepost_id");
exit();
}
?>
<!-- Page Content -->
<div class="container">
<div class="row">
<!-- Blog Entries Column -->
<div class="col-md-8">
<h1 class="page-header">
Page Heading
<small>Secondary Text</small>
</h1>
<?php
if(isset($_GET['p_id'])){
$post_id = $_GET['p_id'];
$view_query = "UPDATE posts SET post_views = post_views + 1 WHERE post_id = {$post_id}";
$views_result = mysqli_query($connection, $view_query);
$query = "SELECT * FROM posts WHERE post_id = '$post_id' ";
$result = mysqli_query($connection,$query);
while($row = mysqli_fetch_assoc($result)){
$title = $row['post_title'];
$author = $row['post_author'];
$date = $row['post_date'];
$image = $row['post_image'];
$content = $row['post_content'];
$tags = $row['post_tags'];
?>
<!-- First Blog Post -->
<h2>
<a href="#"> <?php echo $title; ?></a>
</h2>
<p class="lead">
by <a href="index.php"><?php echo $author; ?></a>
</p>
<p><span class="glyphicon glyphicon-time"></span> Posted on <?php echo $date; ?></p>
<hr>
<img class="img-responsive" src="images/<?php echo $image; ?>" alt="">
<hr>
<p><?php echo $content; ?></p>
<a class="btn btn-primary" href="#">Read More <span class="glyphicon glyphicon-chevron-right"></span></a>
<hr>
<?php
$likes_query = "SELECT * FROM likes WHERE post_id = $post_id ";
$likes_result = mysqli_query($connection,$likes_query);
if(mysqli_num_rows($likes_result) < 1) {
?>
<div class="row">
<p class="pull-right"><a class="like" href="#"><span class="glyphicon glyphicon-thumbs-up"></span> Like</a> </p>
</div>
<?php } else{ ?>
<div class="row">
<p class="pull-right"><a class="unlike" href="#"><span class="glyphicon glyphicon-thumbs-down"></span> Unlike</a> </p>
</div>
<?php } ?>
<?php
$likes_query = "SELECT * FROM likes WHERE post_id = $post_id ";
$likes_result = mysqli_query($connection,$likes_query);
?>
<div class="row">
<p class="pull-right"><?php echo mysqli_num_rows($likes_result); ?></a> </p>
</div>
<div class="clearfix"></div>
<?php } }
else {
header("Location: index.php");
}
?>
<!-- Blog Comments -->
<?php
if(isset($_POST['add_comment'])){
$post_id = $_GET['p_id'];
$author = $_POST['comment_author'];
$email = $_POST['comment_email'];
$content = $_POST['comment_content'];
$query = "INSERT INTO comments (comment_post_id, comment_author, comment_email, comment_content, comment_status, comment_date)";
$query .= "VALUES('$post_id', '$author' ,'$email', '$content' , 'unapproved', now() )";
$result = mysqli_query($connection, $query);
if(!$result){
die("error" . mysqli_error());
}
$query = "UPDATE posts SET post_comment_count = post_comment_count + 1 ";
$query .= "WHERE post_id = $post_id";
$result2 = mysqli_query($connection,$query);
if(!$result){
die("error" . mysqli_error());
}
}
?>
<!-- Comments Form -->
<div class="well">
<h4>Leave a Comment:</h4>
<form role="form" action="" method="post">
<div class="form-group">
<label for="comment_author">Author</label>
<input type="text" name="comment_author" class="form-control" rows="3" required>
</div>
<div class="form-group">
<label for="comment_email">Email</label>
<input type="email" name="comment_email" class="form-control" rows="3" required>
</div>
<div class="form-group">
<label for="comment_content">Your Comment</label>
<textarea name="comment_content" class="form-control" rows="3" required></textarea>
</div>
<button type="submit" name="add_comment" class="btn btn-primary">Submit</button>
</form>
</div>
<hr>
<!-- Posted Comments -->
<?php
$query_comments = "SELECT * FROM comments WHERE comment_post_id = {$post_id} ";
$query_comments .= "AND comment_status = 'approved' ";
$query_comments .= "ORDER BY comment_id DESC";
$comments_result = mysqli_query($connection,$query_comments);
while($row = mysqli_fetch_assoc($comments_result)){
$id = $row['comment_id'];
$post_id = $row['comment_post_id'];
$author= $row['comment_author'];
$email= $row['comment_email'];
$content= $row['comment_content'];
$status= $row['comment_status'];
$date= $row['comment_date'];
?>
<!-- Comment -->
<div class="media">
<a class="pull-left" href="#">
<img class="media-object" src="http://placehold.it/64x64" alt="">
</a>
<div class="media-body">
<h4 class="media-heading"><?php echo $author; ?>
<small><?php echo $date; ?> </small>
</h4>
<?php echo $content; ?>
</div>
</div>
<?php } ?>
</div>
<!-- Blog Sidebar Widgets Column -->
<?php include "includes/sidebar.php"; ?>
</div>
<!-- /.row -->
<hr>
<?php include "includes/footer.php" ?>
<script>
$(document).ready(function(){
var post_id = <?php echo $post_id; ?>
var user_id = 20;
//like
$('.like').click(function(){
$.ajax({
url: "/cms/post.php?p_id=<?php echo $post_id; ?>",
type:'post',
data:{
'liked': 1,
'post_id': post_id,
'user_id': user_id
}
});
});
//unlike
$('.unlike').click(function(){
$.ajax({
url: "/cms/post.php?p_id=<?php echo $post_id; ?>",
type:'post',
data:{
'unliked': 1,
'post_id': post_id,
'user_id': user_id
}
});
});
});
</script> | true |
11fb990a1d1a6a392a4b1693942ed251f1216e5c | PHP | ixnode/php-branch-diagram-builder | /src/Branch.php | UTF-8 | 6,218 | 3.046875 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types=1);
/**
* MIT License
*
* Copyright (c) 2021 Björn Hempel <bjoern@hempel.li>
*
* 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.
*/
namespace Ixnode\PHPBranchDiagramBuilder;
use Exception;
/**
* Class Branch
*
* @author Björn Hempel <bjoern@hempel.li>
* @version 1.0 <2021-10-16>
* @license https://opensource.org/licenses/MIT MIT License
* @link https://github.com/ixnode/php-branch-diagram-builder
* @category Main
* @package Ixnode\PHPBranchDiagramBuilder
*/
class Branch
{
protected string $name;
protected ?string $title;
protected ?string $targetSystem;
protected int $row;
protected string $fillColor;
protected string $strokeColor;
/**
* The stroke dash array.
*
* @var int[]
*/
protected array $strokeDashArray = [5, 5];
protected int $strokeOpacity = 1;
protected int $strokeWidth = 1;
protected ?string $textColor;
protected int $textSize = 20;
protected ?int $lastStepPosition = null;
/**
* Branch constructor.
*
* @param string $colorFill The color fill.
* @param string $colorStroke The color stroke.
* @param string|null $colorText The color text.
*/
public function __construct(
string $colorFill,
string $colorStroke,
string $colorText = null
) {
$this->fillColor = $colorFill;
$this->strokeColor = $colorStroke;
$this->textColor = $colorText;
$this->title = null;
$this->targetSystem = null;
}
/**
* Sets the name of this branch.
*
* @param string $name The name.
*
* @return void
*/
public function setName(string $name): void
{
$this->name = $name;
}
/**
* Returns the name of this branch.
*
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* Sets the title of this branch.
*
* @param string $title The title.
*
* @return void
*/
public function setTitle(string $title): void
{
$this->title = $title;
}
/**
* Returns the title of this branch.
*
* @return string
*/
public function getTitle(): string
{
return $this->title ?? $this->name;
}
/**
* Sets the target system.
*
* @param string|null $targetSystem The target system.
*
* @return void.
*/
public function setTargetSystem(?string $targetSystem): void
{
$this->targetSystem = $targetSystem;
}
/**
* Returns the target system.
*
* @return string|null
*/
public function getTargetSystem(): ?string
{
return $this->targetSystem;
}
/**
* Sets the row of this branch.
*
* @param int $row The row.
*
* @return void
*/
public function setRow(int $row): void
{
$this->row = $row;
}
/**
* Returns the row of this branch.
*
* @return int
*/
public function getRow(): int
{
return $this->row;
}
/**
* Returns the color fill.
*
* @return string
*/
public function getFillColor(): string
{
return $this->fillColor;
}
/**
* Returns the color stroke.
*
* @return string
*/
public function getStrokeColor(): string
{
return $this->strokeColor;
}
/**
* Returns the dash array stroke.
*
* @return int[]
*/
public function getStrokeDashArray(): array
{
return $this->strokeDashArray;
}
/**
* Returns the stroke opacity.
*
* @return int
*/
public function getStrokeOpacity(): int
{
return $this->strokeOpacity;
}
/**
* Returns the stroke width.
*
* @return int
*/
public function getStrokeWidth(): int
{
return $this->strokeWidth;
}
/**
* Returns the color text.
*
* @return string
*/
public function getTextColor(): string
{
return $this->textColor ?? $this->strokeColor;
}
/**
* Returns the text size.
*
* @return int
*/
public function getTextSize(): int
{
return $this->textSize;
}
/**
* Sets the last step number of this branch.
*
* @param int $lastStepPosition The last step position.
*
* @throws Exception
* @return void
*/
public function setLastStepPosition(int $lastStepPosition): void
{
if ($lastStepPosition < $this->lastStepPosition) {
throw new Exception(
sprintf(
<<<TEXT
The new last step number "%d" must be greater or equal than the last one %s.
TEXT,
$lastStepPosition,
$this->lastStepPosition
)
);
}
$this->lastStepPosition = $lastStepPosition;
}
/**
* Returns the last step number of this branch.
*
* @return ?int
*/
public function getLastStepPosition(): ?int
{
return $this->lastStepPosition;
}
}
| true |
bede2fc5bd407791e4922875d69d299edb3e205a | PHP | febriantho/laravel-form-builder | /src/Gustiawan/FormBuilder/Commands/CreateForm.php | UTF-8 | 1,961 | 2.84375 | 3 | [
"MIT"
] | permissive | <?php
namespace Gustiawan\FormBuilder\Commands;
use Illuminate\Support\Str;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
class CreateForm extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'make:form {name : The Name of the Form}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create Form';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$file = File::get(__DIR__."/form.stub");
$name_argument = $this->argument('name');
$name_arguments = explode("/", $name_argument);
$name = $name_arguments[count($name_arguments) - 1];
unset($name_arguments[count($name_arguments) - 1]);
$str = Str::of($file)->replaceFirst("{name}", $name);
if (count($name_arguments) > 0) {
$str = Str::of($str)->replaceFirst("{namespace}", "\\".implode("\\", $name_arguments));
} else {
$str = Str::of($str)->replaceFirst("{namespace}", "");
}
$path = base_path("app/Form");
$folders = explode("/", $name_argument);
unset($folders[count($folders) - 1]);
$folder = implode("/", $folders);
if(!File::exists($path."/".$folder)) {
File::makeDirectory($path."/".$folder, $mode = 0755, true, true);
}
if (File::exists($path."/".$name_argument.".php")) {
$this->info("File already exists!");
return;
}
File::put($path."/".$name_argument.".php", $str);
$this->info('Form was created!');
}
}
| true |
374c0201a3c829e0db80d28e68d95c05637bc83f | PHP | MotanyaIsaack/Fashion-and-Design | /application/modules/website/views/sections/cards.php | UTF-8 | 4,879 | 2.671875 | 3 | [
"MIT"
] | permissive | <?php
if (count($cards) > 0) {
switch ($folder) {
case "event":
showEventCards($folder, $cards);
break;
case "collection":
showCollectionCards($folder, $cards);
break;
}
} else {
displayNone($folder);
}
function displayNone($folder)
{
echo '
<center class="display-4">No ' . $folder . ' to show. Our homepage isn\'t empty though :)
<p><a href="' . base_url('website/home') . '" class="blue-text">Go to homepage?</a></p>
<center>
';
}
function showEventCards($folder, $cards)
{
foreach ($cards as $event) {
//Get the event details
$id = $event['event_id'];
$url = 'website/event/';
$today = date("Y-m-d");
$event_date = $event['date'];
$filter = ($event_date > $today) ? "upcoming" : "past";
$img = $event['landing_page_image'];
$name = $event['short_name'];
$subfolder = "event_".$id;
$full_name = $event['full_name'];
$location = $event['location'];
$item_summary = $event['item_summary'];
$event_link = base_url($url . $id);
echo '
<div class="portfolio-item" data-groups=\'["all", "' . $filter . '"]\'>
<div class="card event">
<div class="card-image waves-effect waves-block waves-light">
<img class="activator"
src="' . images_url($folder . '/' . $subfolder . "/" . $img) . '" alt="image" height="450px">
</div>
<div class="card-content activator">
<span class="card-title">
<a href="' . $event_link . '" class="grey-text text-darken-2">
' . $name . '<br>
<span class="text-capitalize grey-text">' . $location . '</span>
</a>
<i class="material-icons right">info_outline</i>
</span>
</div>
<div class="card-reveal">
<span class="card-title">' . $full_name . '
<i class="material-icons right"></i>
</span>
<p>' . $item_summary . '</p>
<a href="' . $event_link . '" class="readmore">Learn more</a>
</div>
<!--<div class="card-action">
<a href="' . $event_link . '" class="blue-text">View event</a>
</div>-->
</div><!-- /.card -->
</div><!-- /.portfolio-item -->
';
}
}
function showCollectionCards($folder, $cards)
{
foreach ($cards as $collection) {
//Get the event details
$id = $collection['collection_id'];
$url = 'website/subcollections/';
$filter = $collection['category_name'];
$img = $collection['landing_page_image'];
$subfolder = "collection_".$id;
$name = $collection['short_name'];
$full_name = $collection['full_name'];
$location = null;
$item_summary = $collection['item_summary'];
$collection_url = base_url($url . $id);
echo '
<div class="portfolio-item" data-groups=\'["all", "' . $filter . '"]\'>
<div class="card collection">
<div class="card-image waves-effect waves-block waves-light">
<a href="' . $collection_url . '">
<img class="activator" src="' . images_url($folder . '/' . $subfolder . "/" . $img) . '" alt="image" height="470px">
</a>
</div>
<a href="' . $collection_url . '" class="grey-text text-darken-2">
<div class="card-content activator">
<span class="card-title">
' . $name . '
<i class="material-icons right hide">info_outline</i>
</span>
</div>
</a>
<div class="card-action">
<a href="' . $collection_url . '" class="blue-text">View collection</a>
</div>
<div class="card-reveal hide">
<span class="card-title">' . $full_name . '
<i class="material-icons right"></i>
</span>
<p>' . $item_summary . '</p>
<a href="' . base_url($url . $id) . '" class="readmore">Learn more</a>
</div>
</div><!-- /.card -->
</div><!-- /.portfolio-item -->
';
}
}
| true |
7a910ac8c16d90773ea62de17add9b2f33dbd71a | PHP | Dario19999/Proyecto-de-titulacion | /php/mailer.php | UTF-8 | 1,670 | 2.625 | 3 | [] | no_license | <?php
require __DIR__ . '/../vendor/autoload.php';
include 'conexion.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
function mailer ($correo, $nombre_usuario_receta, $asunto, $cuerpo)
{
$mail = new PHPMailer(true);
//Server settings
// $mail->SMTPDebug = 2; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.hostinger.mx'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'lacuisine@lacousine.com'; // SMTP username
$mail->Password = '#BEgwTy`77jnhwj17k'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom('lacuisine@lacousine.com', 'La Cuisine');
$mail->addAddress($correo, $nombre_usuario_receta); // Add a recipient
// // Attachments
// $mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
// $mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $asunto;
$mail->Body = $cuerpo;
$mail->AltBody = $cuerpo;
$mail->send();
}
?> | true |
92b9ff31cae1468065461b7c762d05e7b603abd7 | PHP | SpencerBelleau/DOC_HardwareServiceRequestDatabase | /DOC/ajax/saveTimeSheet.php | UTF-8 | 917 | 2.546875 | 3 | [] | no_license | <?php
require "../snippets/dbConn.php";
require "../snippets/SQLTools.php";
require "../snippets/utils.php";
session_start();
$com0 = "UPDATE DOC_Timestamps SET timeOut = :timeOut WHERE timestampId=:id";
executeSQL_Safe_U($com0, $dbConn, ":timeOut", date("Y-m-d H:i:s"), ":id", $_SESSION['sessionId']);
$com1 = "SELECT timestampId, timeIn, timeOut, finished, TIMESTAMPDIFF(HOUR, timeIn, timeOut) as hours, TIMESTAMPDIFF(MINUTE, timeIn, timeOut) as minutes, TIMESTAMPDIFF(SECOND, timeIn, timeOut) as seconds FROM DOC_Timestamps WHERE userId = :id ORDER BY timeIn ASC";
$ret = executeSQL_Safe($com1, $dbConn, ":id", $_SESSION['userID']);
function valid($time)
{
if($time['finished'] == 1)
{
return "Finished";
}else{
return "In Progress";
}
}
foreach($ret as $time)
{
echo $time['timeIn'] . "," . $time['timeOut'] . "," . gmdate("H:i:s", $time['seconds']) . "," . valid($time) . "\n";
}
?> | true |
b2643420b8c616e133d9ca320de90c04023c7210 | PHP | HyeonsikCho/front | /com/nexmotion/html/common/MakeCommonHtml.php | UTF-8 | 3,125 | 2.703125 | 3 | [] | no_license | <?
/**
* @brief option html 공통사용함수
*
* @param $val = option 실제 값
* @param $dvs = option 화면 출력값
* @param $attr = option에 추가로 입력할 attribute
*
* @return option html
*/
function option($val, $dvs, $attr = '') {
$option_form = "<option %s value=\"%s\">%s</option>";
$ret = sprintf($option_form, $attr, $val, $dvs);
return $ret;
}
/**
* @brief 옵션 html 생성
*
* @param $rs = 검색결과
* @param $arr["flag"] = "기본 값 존재여부"
* @param $arr["def"] = "기본 값(ex:전체)"
* @param $arr["def_val"] = "기본 값의 option value"
* @param $arr["val"] = "option value에 들어갈 필드 값"
* @param $arr["dvs"] = "option에 표시할 필드 값"
* @param $arr["dvs_tail"] = "option 값 뒤에 붙일 단어"
* @param $arr["dvs_tail"] = "option 값 뒤에 붙일 단어"
* @param $arr["sel"] = "selected할 val값" -> value랑 비교
* @param $arr["sel_dvs"] = "selected할 val값" -> dvs랑 비교
* @param $arr["except_arr"] = 예외처리사항, 해당 사항 외적으로 처리할 때 사용
*
* @return option html
*/
function makeOptionHtml($rs, $arr) {
$html = "";
if ($arr["flag"] === true) {
$html = option($arr["def_val"], $arr["def"], "selected=\"selected\"");
}
$except_arr = $arr["except_arr"];
$dvs_tail = $arr["dvs_tail"];
$sel_val = $arr["sel"];
$sel_dvs = $arr["sel_dvs"];
$val = $arr["val"];
$dvs = $arr["dvs"];
while ($rs && !$rs->EOF) {
$opt_dvs = $rs->fields[$dvs];
$opt_val = null;
//필드 값 뒤에 붙일 단어
if ($dvs_tail !== null) {
$opt_dvs = $opt_dvs . $dvs_tail;
}
//만약 $val 빈값이 아니면
if ($val !== null) {
$opt_val = $rs->fields[$val];
if (empty($opt_val) === true) {
$opt_val = $opt_dvs;
}
} else {
$opt_val = $opt_dvs;
}
$selected = "";
if ($sel_val === true ||
$opt_val === $sel_val ||
$opt_dvs === $sel_dvs) {
$selected = "selected=\"selected\"";
$sel_val = false;
$sel_dvs = false;
}
// 예외사항 1 -> 후공정 처리예외
if (!empty($except_arr["after_name"])) {
if ($except_arr["after_name"] === "접지" &&
$opt_dvs === "비중앙") {
$selected .= " class=\"_custom\"";
}
}
$html .= option($opt_val, $opt_dvs, $selected);
$rs->MoveNext();
}
return $html;
}
function noLoginPop() {
$html = <<<HTML
<header>
<h2>선입금 결제하기</h2>
<button class="close" title="닫기"><img src="/design_template/images/common/btn_circle_x_white.png" alt="X"></button>
</header>
<article>
<h3>로그인 상태가 아닙니다.</h3>
<div class="function center">
<strong><button type="button" onclick="location.replace('/member/login.html');">로그인</button></strong>
</div>
</article>
HTML;
return $html;
}
?>
| true |
8e1913bc3f287e820d6af63949158c0ab10a4c73 | PHP | rifkyalamsyah/PHP-OOP | /C5/20.php | UTF-8 | 1,373 | 4.03125 | 4 | [] | no_license | <?php
// Type Check & Casts
// data/Programmer.php
// Example
class Programmer
{
public string $name;
public function __construct(string $name)
{
$this->name = $name;
}
}
class BackendProgrammer extends Programmer
{
}
class FrontendProgrammer extends Programmer
{
}
class Company
{
public Programmer $programmer;
}
// Type Check & Casts
function sayHelloProgrammer(Programmer $programmer)
{
if ($programmer instanceof BackendProgrammer) {
echo "Hello Backend Programmer $programmer->name" . PHP_EOL;
} else if ($programmer instanceof FrontendProgrammer) {
echo "Hello Frontend Programmer $programmer->name" . PHP_EOL;
} else if ($programmer instanceof Programmer) {
echo "Hello Programmer $programmer->name" . PHP_EOL;
}
}
// Mengakses Type Check & Casts
// Polymorphism.php
// Example
/*
require_once "data/Programmer.php";
$company = new Company();
$company->programmer = new Programmer("Rifky");
var_dump($company);
$company->programmer = new BackendProgrammer("Rifky");
var_dump($company);
$company->programmer = new FrontendProgrammer("Rifky");
var_dump($company);
sayHelloProgrammer(new Programmer("Rifky"));
sayHelloProgrammer(new BackendProgrammer("Rifky"));
sayHelloProgrammer(new FrontendProgrammer("Rifky"));
*/ | true |
6d5aadd5b6cfffa9d449a7579262245e9f3d6133 | PHP | sam-lopata/epgimporter | /src/Tests/XMLStreamFileLoaderTest.php | UTF-8 | 2,273 | 2.59375 | 3 | [] | no_license | <?php
namespace EPGImporter\Tests;
use EPGImporter\Loader\LoaderException;
use EPGImporter\Loader\XMLStreamFileLoader;
use PHPUnit\Framework\TestCase;
class XMLStreamFileLoaderTest extends TestCase
{
private const SOURCE = "src/Tests/data/test_data.xml";
private const BROKEN_SOURCE = "src/Tests/data/test_data_broken.xml";
/** @var XMLStreamFileLoader */
private $fl;
public function setUp()
{
$this->fl = new XMLStreamFileLoader();
}
public function testInitFileNotExists()
{
$this->expectException(LoaderException::class);
$this->fl->init('/some/file/here/which/not/exist');
}
public function testInitSuccess()
{
$this->fl->init(self::SOURCE);
$reflector = new \ReflectionClass($this->fl);
$loaderProperty = $reflector->getProperty('source');
$loaderProperty->setAccessible(true);
$this->assertEquals(self::SOURCE, $loaderProperty->getValue($this->fl));
$this->assertEquals(\XMLReader::ELEMENT, $this->fl->nodeType);
}
public function testReadLine()
{
$this->fl->init(self::SOURCE);
$this->fl->readLine();
$reflector = new \ReflectionClass($this->fl);
$lsp = $reflector->getProperty('lastStatus');
$lsp->setAccessible(true);
$lastStatus = $lsp->getValue($this->fl);
$this->assertTrue($lastStatus);
}
public function testReadLineBroken()
{
$this->expectException(LoaderException::class);
$this->fl->init(self::BROKEN_SOURCE);
}
public function testExpandNode()
{
$this->fl->init(self::SOURCE);
/** @var \DOMNode $node */
$node = $this->fl->readLine()->expandNode()->getLastOperationStatus();
$this->assertInstanceOf(\DOMElement::class, $node);
$this->assertEquals("network", $node->tagName);
$node = $this->fl->readLine()->expandNode()->getLastOperationStatus();
$this->assertInstanceOf(\DOMElement::class, $node);
$this->assertEquals("service", $node->tagName);
$node = $this->fl->readLine()->expandNode()->getLastOperationStatus();
$this->assertInstanceOf(\DOMElement::class, $node);
$this->assertEquals("event", $node->tagName);
}
}
| true |
9f2bb74bcf3c360fb63e1aba5ae769ebfc9ff2e7 | PHP | ekyna/Commerce | /Shipment/Entity/AbstractShipmentItem.php | UTF-8 | 2,850 | 2.8125 | 3 | [
"MIT"
] | permissive | <?php
namespace Ekyna\Component\Commerce\Shipment\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Ekyna\Component\Commerce\Shipment\Model;
/**
* Class ShipmentItem
* @package Ekyna\Component\Commerce\Shipment\Entity
* @author Etienne Dauvergne <contact@ekyna.com>
*/
abstract class AbstractShipmentItem implements Model\ShipmentItemInterface
{
/**
* @var int
*/
protected $id;
/**
* @var Model\ShipmentInterface
*/
protected $shipment;
/**
* @var float
*/
protected $quantity = 0;
/**
* @var ArrayCollection
*/
protected $children;
/**
* @var float
*/
protected $expected;
/**
* @var float
*/
protected $available;
/**
* Constructor.
*/
public function __construct()
{
$this->clearChildren();
}
/**
* @inheritdoc
*/
public function getId()
{
return $this->id;
}
/**
* @inheritdoc
*/
public function getShipment()
{
return $this->shipment;
}
/**
* @inheritdoc
*/
public function setShipment(Model\ShipmentInterface $shipment = null)
{
if ($this->shipment !== $shipment) {
if ($previous = $this->shipment) {
$this->shipment = null;
$previous->removeItem($this);
}
if ($this->shipment = $shipment) {
$this->shipment->addItem($this);
}
}
return $this;
}
/**
* @inheritdoc
*/
public function getQuantity()
{
return $this->quantity;
}
/**
* @inheritdoc
*/
public function setQuantity($quantity)
{
$this->quantity = $quantity;
return $this;
}
/**
* @inheritdoc
*/
public function setChildren(array $children)
{
$this->clearChildren();
foreach ($children as $child) {
$this->children->add($child);
}
return $this;
}
/**
* @inheritdoc
*/
public function getChildren()
{
return $this->children;
}
/**
* @inheritdoc
*/
public function clearChildren()
{
$this->children = new ArrayCollection();
return $this;
}
/**
* @inheritdoc
*/
public function getExpected()
{
return $this->expected;
}
/**
* @inheritdoc
*/
public function setExpected($expected)
{
$this->expected = (float)$expected;
return $this;
}
/**
* @inheritdoc
*/
public function getAvailable()
{
return $this->available;
}
/**
* @inheritdoc
*/
public function setAvailable($available)
{
$this->available = (float)$available;
return $this;
}
}
| true |
9ebf1f77b229c3457190032f110b925dd5ec8f78 | PHP | tingren/php_test_pro | /app/base/querybuilder.php | UTF-8 | 5,652 | 2.734375 | 3 | [] | no_license | <?php
class QueryBuilder {
protected $conn;
protected $select;
protected $update;
protected $from;
protected $cond;
protected $cond_not = array();
protected $cond_and = array();
protected $cond_or = array();
protected $cond_in = array();
protected $cond_not_in = array();
protected $groupby;
protected $joind = false;
protected $orderby = array();
protected $limit;
public function __construct($conn=null){
$this->conn = $conn;
}
public function condition($keys){
$this->cond = $keys;
return $this;
}
public function where_not($keys){
$this->cond_not = array_merge($this->cond_not,$keys);
return $this;
}
public function where_in($keys){
$this->cond_in = array_merge($this->cond_in,$keys);
return $this;
}
public function where_not_in($keys){
$this->cond_not_in = array_merge($this->cond_not_in,$keys);
return $this;
}
public function select($keys){
$this->select = $keys;
return $this;
}
public function from($keys){
$this->from = $keys;
return $this;
}
public function leftjoin($keys){
$this->from.=" LEFT JOIN ${keys} ";
return $this;
}
public function rightjoin($keys){
$this->from.=" RIGHT JOIN ${keys} ";
return $this;
}
public function innerjoin($keys){
$this->from.=" INNER JOIN ${keys} ";
return $this;
}
public function on($keys){
$str = implode("=",$keys);
$this->from.= " ON $str ";
return $this;
}
public function where($keys){
$this->cond_and= array_merge($this->cond_and,$keys);
return $this;
}
public function where_or($keys){
$this->cond_or = array_merge($this->cond_or,$keys);
return $this;
}
public function groupby($keys){
$this->groupby = $keys;
return $this;
}
public function orderby($keys){
$this->orderby = array_merge($this->orderby,$keys);
return $this;
}
public function limit($val1=null,$val2=null){
if(is_numeric($val1) && is_numeric($val2)){
$this->limit="LIMIT ${val1},${val2}";
}elseif(is_numeric($val1)){
$this->limit="LIMIT ${val1}";
}
return $this;
}
public function sql(){
$select = "";
$where = "";
$not = "";
$and = "";
$or = "";
$in = "";
$not_in = "";
$cond = "";
$filter = array();
$groupby = "";
$orderby = "";
if(is_array($this->select)){
$select.=" SELECT ".implode(",",$this->select);
}else if(!empty($this->select)){
$select.=" SELECT ".$this->select;
}else {
$select.=" SELECT *";
}
/**条件叠加**/
if(!empty($this->cond_and)){
if(is_array($this->cond_and)){
$arr_and = array();
foreach($this->cond_and as $key=>$value){
$arr_and[] = " ${key}='${value}' ";
}
$and=implode(" AND ",$arr_and);
}else{
$and=$this->cond_and;
}
if(!empty($and)){
$filter[]=$and;
}
}
if(is_array($this->cond_or)){
if(is_array($this->cond_or)){
$arr_or = array();
foreach($this->cond_or as $key=>$value){
$arr_or[] = " ${key}='${value}' ";
}
$or = implode(" OR ", $arr_or);
}else{
$or = $this->cond_or;
}
if(!empty($or)){
$filter[]=$or;
}
}
//in 条件
if(!empty($this->cond_in)){
$arr_in = array();
foreach($this->cond_in as $key=>$val){
$arr_in[] = "${key} IN('".implode("','",$val)."')";
}
if(!empty($arr_in)){
$in= implode(" AND ",$arr_in);
}
if(!empty($arr_in)){
$filter[]=$in;
}
}
//not in 条件
if(!empty($this->cond_not_in)){
$arr_not_in = array();
foreach($this->cond_not_in as $key=>$val){
$arr_not_in[] = "$key NOT IN('".implode("','",$val)."')";
}
if(!empty($arr_not_in)){
$not_in= implode(" AND ",$arr_not_in);
}
if(!empty($arr_in)){
$filter[]=$not_in;
}
}
if(!empty($this->cond_not) && is_array($this->cond_not)){
if(is_array($this->cond_and)){
$arr_not = array();
foreach($this->cond_not as $key=>$value){
$arr_not[] = " ${key}!='${value}' ";
}
$not=implode(" AND ",$arr_not);
}else{
$not=$this->cond_not;
}
if(!empty($not)){
$filter[]=$not;
}
}
if(!empty($this->cond)){
$filter[]=$this->cond;
}
if(!empty($filter)){
$where .= implode(" AND ",$filter);
}
/*
if(!empty($and) && !empty($or)){
$where.=$and." AND ".$or;
}else{
$where.=(!empty($and))?$and:"";
$where.=(!empty($or))?$or:"";
}*/
/*
* groupby
*/
if(!empty($this->groupby)){
$groupby.=$this->groupby;
}
/*
* orderby
*/
if(!empty($this->orderby) && is_array($this->orderby)){
$arr=array();
foreach($this->orderby as $key=>$value){
$arr[]="${key} ${value}";
}
if(!empty($arr)){
$orderby = implode(",",$arr);
}
}
//combine sql
if(!empty($select)){
$sql = "";
$sql .= $select;
if(!empty($this->from)){
$sql .= " FROM ".$this->from;
}
if(!empty($where)){
$sql .= " WHERE ".$where;
}
if(!empty($groupby)){
$sql .= " GROUP BY ".$groupby;
}
if(!empty($orderby)){
$sql .= " ORDER BY ".$orderby;
}
if(!empty($this->limit)){
$sql .=" ".$this->limit;
}
return $sql;
}
return false;
}
public function query($param=null){
if(empty($this->conn))
return false;
$sql = $this->sql();
if(empty($sql))
return false;
$statm = $this->conn->prepare ($sql);
$statm->setFetchMode ( PDO::FETCH_NAMED );
if (is_array ($param) && !empty($param)) {
foreach ( $param as $key => $value ) {
$$key = $value;
$statm->bindParam ( $key, $$key );
}
}
$rs = $statm->execute ();
$this->info = $statm->errorInfo ();
if ($rs) {
$data = $statm->fetchAll ();
return $data;
}
return false;
}
}
| true |
f3841a3c44e6337a0b9ec11dccf5be96fd1cb434 | PHP | khakanali/OpenMAll | /master3/app/Http/Controllers/DirectoryController.php | UTF-8 | 4,407 | 2.65625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Http\Repository\DirectoryRepo;
use App\Http\Repository\OccupationRepo;
use App\Http\Requests\DirectoryRequest;
use Illuminate\Http\Request;
use Validator;
class DirectoryController extends Controller {
protected $repo;
protected $orepo;
function __construct(DirectoryRepo $repo, OccupationRepo $orepo) {
$this->repo = $repo;
$this->orepo = $orepo;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index() {
$object = $this->repo->index();
$professional = $this->orepo->lists()->toArray();
\View::share("directories", $this->createIndex($object));
\View::share("professional", $professional);
return view('directory.directory');
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create() {
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(DirectoryRequest $request) {
$input = $request->except("_token");
$messages = array(
'occupation_id.required' => 'The professional field is required.',
'occupation_id.numeric' => 'The professional field is must be a numeric.',
);
$validator = Validator::make($input, [
'company' => 'required',
'business_reg_no' => 'required|integer|min:0',
'email' => 'required|email',
'phone' => 'required',
'address' => 'required',
'occupation_id' => 'required|numeric',
], $messages);
if ($validator->fails()) {
return redirect('directory')
->withErrors($validator)
->withInput();
}
$status = $this->repo->create($input);
return redirect('directory')->with('success', "Thank You We Will Contact You.");
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id) {
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id) {
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(DirectoryRequest $request, $id) {
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id) {
//
}
public function createIndex($object) {
$final = array();
foreach ($object->toArray() as $key => $value) {
if (isset($value['occupation_name'])) {
if (strtolower($value['occupation_name'][0]) == "a" ||
strtolower($value['occupation_name'][0]) == "b" ||
strtolower($value['occupation_name'][0]) == "c" ||
strtolower($value['occupation_name'][0]) == "d") {
$final['A-D'][] = $value;
} else if (strtolower($value['occupation_name'][0]) == "e" || strtolower($value['occupation_name'][0]) == "f" || strtolower($value['occupation_name'][0]) == "g" || strtolower($value['occupation_name'][0]) == "h") {
$final['E-H'][] = $value;
} else if (strtolower($value['occupation_name'][0]) == "i" || strtolower($value['occupation_name'][0]) == "j" || strtolower($value['occupation_name'][0]) == "k" || strtolower($value['occupation_name'][0]) == "l") {
$final['I-L'][] = $value;
} else if (strtolower($value['occupation_name'][0]) == "m" || strtolower($value['occupation_name'][0]) == "n" || strtolower($value['occupation_name'][0]) == "o" || strtolower($value['occupation_name'][0]) == "p") {
$final['M-P'][] = $value;
} else if (strtolower($value['occupation_name'][0]) == "q" || strtolower($value['occupation_name'][0]) == "r" || strtolower($value['occupation_name'][0]) == "s" || strtolower($value['occupation_name'][0]) == "t") {
$final['Q-T'][] = $value;
} else if (strtolower($value['occupation_name'][0]) == "u" || strtolower($value['occupation_name'][0]) == "v" || strtolower($value['occupation_name'][0]) == "w" || strtolower($value['occupation_name'][0]) == "x") {
$final['U-X'][] = $value;
} else if (strtolower($value['occupation_name'][0]) == "y" || strtolower($value['occupation_name'][0]) == "z") {
$final['Y-Z'][] = $value;
}
}
}
return $final;
}
}
| true |
93d9f7608b85100d6169b1d0cf361bc8537b642c | PHP | PatrickMurphy/EAF-Auction | /classes/eaf_error_exception.php | UTF-8 | 899 | 3.109375 | 3 | [] | no_license | <?php // This class handles page errors, can be passed as an array to show multiple errors at once.
class eaf_error_exception extends eaf_exception {
private $errors = Array();
private $array = true;
public function __construct($messages){
if(is_array($messages)){
$this->errors = $messages;
$m = 'Eaf_error_exception';
} else if(is_string($messages)){
$this->array = false;
$m = $messages;
}
parent::__construct($m);
}
public function displayErrors(){
$display = '<span class="column" style="width:660px;">';
if($this->array)
foreach($this->errors as $code => $text)
$display .= $this->error($text);
else
$display .= $this->error($this->getMessage());
return $display . '</span><br />';
}
}
?> | true |
433c578cbded733d6a547b2c38abd5268ebc1290 | PHP | yttiktak/SharedPano | /redirector.php | UTF-8 | 1,512 | 2.640625 | 3 | [] | no_license | <?php
$trigger = "ready/";
//session_start();
//$sesNonce = $_SESSION['nonce'];
//if (strlen($sesNonce)!=6) {
// echo "NONCE ERROR"; // lazy lazy. Just, ok, so I got a session, must be my user calling, right?
// exit(); not while testing. 'sides, tests are not via page, so errereror allways.
//}
//$skinBase = $_SESSION['skinBase'];
$uri = $_SERVER['REQUEST_URI'];
$pos = strpos($uri,$trigger);
$tailURI = substr($uri,$pos+strlen($trigger));
//$filteredURI = filter_var($tailURI,FILTER_SANITIZE_URL);
//skinBase will save me!! No need for tedious local file searching, and might interfere with testing.
/**
if (file_exists($filteredURI)) {
exit();// should I return 404 or something? Anyway, this prevents grabbing local files.
}
if (0!=strpos($filteredURI,$skinBase) {
exit(); // Reject requests not going to my proxied intent.
}
**/
$lastDot = strrpos($tailURI,'.');
$ext = substr($tailURI,$lastDot+1);
// error_log("uri: ".$uri);
switch ($ext) {
case 'png':
case 'PNG':
header('Content-Type: image/png');
break;
case 'tif':
case 'TIF':
header('Content-Type: image/tif');
break;
case 'jpg':
case 'JPG':
default:
error_log("this is considered an image/jpeg: ".$ext);
header('Content-Type: image/jpeg');
}
header('Cache-Control: max-age=60000'); // 6000000 about a month
header('Expires: '.gmdate('D, d M Y H:i:s \G\M\T', time() + (60 * 60 * 24 * 30)));
// error_log("readfile: ".$tailURI);
if (!@readfile($tailURI)) {
header('HTTP/1.0 404 Not Found');
}
?>
| true |
8d58ea09908f74ae9ed9f0b7b18a475e912fc93c | PHP | artsites/nova-seo | /src/Rules/NovaSeoRule.php | UTF-8 | 803 | 2.765625 | 3 | [] | no_license | <?php
namespace Artsites\NovaSeo\Rules;
use Illuminate\Contracts\Validation\Rule;
class NovaSeoRule implements Rule
{
private string $message;
public function __construct()
{
//
}
public function passes($attribute, $value)
{
$data = json_decode($value);
if(mb_strlen($data?->title ?? '') > 191) {
$this->message = 'Максимальная длина поля "Title" - 191 символ';
return false;
}
if(mb_strlen($data?->description ?? '') > 500) {
$this->message = 'Максимальная длина поля "Description" - 500 символов';
return false;
}
return true;
}
public function message()
{
return $this->message;
}
}
| true |
cc8d9d45be11f37d88eb76a89f037f2744633070 | PHP | dicrtarasov/yii2-telegram | /src/entity/Voice.php | UTF-8 | 972 | 2.765625 | 3 | [] | no_license | <?php
/*
* @copyright 2019-2022 Dicr http://dicr.org
* @author Igor A Tarasov <develop@dicr.org>
* @license MIT
* @version 23.01.22 04:16:54
*/
declare(strict_types=1);
namespace dicr\telegram\entity;
use dicr\telegram\TelegramEntity;
/**
* This object represents a voice note.
*
* @link https://core.telegram.org/bots/api#voice
*/
class Voice extends TelegramEntity
{
/** Identifier for this file, which can be used to download or reuse the file */
public ?string $fileId = null;
/**
* Unique identifier for this file, which is supposed to be the same over time and for
* different bots. Can't be used to download or reuse the file.
*/
public ?string $fileUniqueId = null;
/** Duration of the audio in seconds as defined by sender */
public ?int $duration = null;
/** Optional. MIME type of the file as defined by sender */
public ?string $mimeType = null;
/** Optional. File size */
public ?int $fileSize = null;
}
| true |
6e828c9ebc4174d14e1272d758e19a32b3dd2453 | PHP | MohannadElemary2/fleet-management | /app/Services/ReservationService.php | UTF-8 | 1,607 | 2.75 | 3 | [] | no_license | <?php
namespace App\Services;
use App\Repositories\ReservationRepository;
use App\Repositories\TripRepository;
use App\Resources\Base\FailureResource;
use App\Services\Base\BaseService;
use Illuminate\Http\Response;
class ReservationService extends BaseService
{
public function __construct(ReservationRepository $repository)
{
parent::__construct($repository);
}
/**
* Validate & Store New Trip Reservation
* 1) Trip Is Available To Receive New Reservations
* 2) Chosen Seat is Available To Be Reserved
*
* @param array $data
* @return JsonResource
* @author Mohannad Elemary
*/
public function store($data)
{
// Get The Trip If Available To Have New Reservations
$trip = app(TripRepository::class)->getSingleAvailableTrip($data);
// Check If The Trip Is Available
if (!$trip) {
return abort(
new FailureResource(
[],
__('reservations/messages.unavailable_trip_to_reserve'),
Response::HTTP_BAD_REQUEST
)
);
}
// Check If The Chosen Seat Is Available
if (!$trip->isAvailableForReservations($data['seat_number'])) {
return abort(
new FailureResource(
[],
__('reservations/messages.unavailable_seat_to_reserve'),
Response::HTTP_BAD_REQUEST
)
);
}
// Create New Reservation
return $this->repository->store($data, $trip);
}
}
| true |
4a552d0dd708a7112ce99d429032fa586de8cd3b | PHP | rostiknaz/magento2-modules | /Training/Repository/Controller/Repository/Example.php | UTF-8 | 2,739 | 2.53125 | 3 | [] | no_license | <?php
namespace Training\Repository\Controller\Repository;
use Magento\Framework\Api\FilterBuilder;
use Magento\Framework\Api\Search\FilterGroupBuilder;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Training\Repository\Api\ExampleRepositoryInterface;
class Example extends Action
{
/**
* @var ExampleRepositoryInterface
*/
private $exampleRepository;
/**
* @var SearchCriteriaBuilder
*/
private $searchCriteriaBuilder;
/**
* @var FilterBuilder
*/
private $_filterBuilder;
/**
* @var FilterGroupBuilder
*/
private $_filterGroupBuilder;
public function __construct(
Context $context,
ExampleRepositoryInterface $exampleRepository,
SearchCriteriaBuilder $searchCriteriaBuilder,
FilterGroupBuilder $filterGroupBuilder,
FilterBuilder $filterBuilder
) {
$this->exampleRepository = $exampleRepository;
$this->searchCriteriaBuilder = $searchCriteriaBuilder;
$this->_filterBuilder = $filterBuilder;
$this->_filterGroupBuilder = $filterGroupBuilder;
parent::__construct($context);
}
public function execute()
{
$this->getResponse()->setHeader('content-type', 'text/plain');
$examples = $this->_getExamplesByFilter();
foreach ($examples as $example) {
$this->getResponse()->appendBody(
sprintf(
"%s (%d)\n",
$example->getName(),
$example->getId()
)
);
}
}
private function _getExamplesByFilter()
{
$filters = [
'name eq Foo',
'name eq Qux'
];
$this->_addFilters($filters);
$this->searchCriteriaBuilder->setFilterGroups(
[$this->_filterGroupBuilder->create()]
);
$examples = $this->exampleRepository->getList(
$this->searchCriteriaBuilder->create()
)->getItems();
return $examples;
}
private function _addFilters($filters)
{
foreach ($filters as $filter) {
if (is_string($filter) && preg_match('/[a-z]/', $filter)) {
$filterParts = explode(' ', $filter);
$filter = $this->_filterBuilder
->setField($filterParts[0])
->setValue($filterParts[2])
->setConditionType($filterParts[1])
->create();
$this->_filterGroupBuilder->addFilter($filter);
}
}
$this->_filterGroupBuilder;
}
} | true |
f591243e56c23b4c61112ecddb07d302d59d1151 | PHP | oleksiyserb/comfort-heat | /models/Project.php | UTF-8 | 1,841 | 2.765625 | 3 | [] | no_license | <?php
namespace app\models;
use Yii;
use yii\data\Pagination;
/**
* This is the model class for table "project".
*
* @property int $id
* @property string $title
* @property string|null $picture
* @property string|null $text
*/
class Project extends \yii\db\ActiveRecord
{
const SHOW_LIMIT_PROJECT = 8;
const STATUS_SEE = 1;
const LIMIT_PROPOSITION_PROJECTS = 2;
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'project';
}
/**
* @return string
*/
public function getImage()
{
if ($this->picture) {
return Yii::$app->params['storage'] . $this->picture;
} else {
return '/no-image.png';
}
}
/**
* @param $id
* @return mixed
*/
public static function getPojects()
{
$query = Project::find()
->where(['status' => self::STATUS_SEE]);
$countProjects = $query->count();
$pages = new Pagination(['totalCount' => $countProjects, 'pageSize' => self::SHOW_LIMIT_PROJECT]);
$projects = $query->offset($pages->offset)
->limit($pages->limit)
->all();
$data['projects'] = $projects;
$data['pages'] = $pages;
return $data;
}
/**
* @return array|\yii\db\ActiveRecord[]
*/
public static function getAll()
{
return Project::find()
->where(['status' => Project::STATUS_SEE])
->orderBy('id DESC')
->limit(Project::SHOW_LIMIT_PROJECT)
->all();
}
public static function getPropositions()
{
return Project::find()
->where(['status' => Project::STATUS_SEE])
->orderBy('id DESC')
->limit(Project::LIMIT_PROPOSITION_PROJECTS)
->all();
}
}
| true |
9ef04ba38da97fbafe1ff56dd2ebd240a0fa252e | PHP | temilolakutelu/Smartpropertyhub-website | /cron_jobs/property_alert.php | UTF-8 | 2,721 | 2.609375 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | <?php
function config()
{
$servername = "propertyhub.com.ng";
$username = "property_user";
$password = "H8iml16@";
$database = "propertyhub_db";
$conn = mysqli_connect($servername, $username, $password, $database);
if (!$conn) {
echo 'error in conection';
}
return $conn;
}
function send_notification($id, $pid, $uid)
{
$conn = config();
$query1 = "SELECT * FROM tbl_properties WHERE property_ID='$pid' LIMIT 1 ";
$result = mysqli_query($conn, $query1);
$row1 = mysqli_fetch_assoc($result);
$prop = $row1['property_Name'];
$message1 = 'Property Alert Match!!! Your property, ' . $prop . ' matches a property Alert Request';
$message2 = 'Property Alert Match!!! Property Alert submitted with id-' . $id .
' have got a match. The Property name is ' . $prop . '';
$date = date("Y-m-d H:i:s");
$query2 = "INSERT INTO tbl_agent_messages(agent_ID, message,date)
VALUES ('$uid','$message1','$date')";
mysqli_query($conn, $query2);
$query3 = "INSERT INTO tbl_admin_messages(message,date)
VALUES ('$message2','$date')";
mysqli_query($conn, $query3);
}
function alert()
{
$conn = config();
$query = "SELECT * FROM tbl_property_alert";
$result = mysqli_query($conn, $query);
if (!empty($result) && mysqli_num_rows($result) > 0) {
$x = 1;
// output data of each row
while ($data = mysqli_fetch_assoc($result)) {
$query2 = "SELECT * FROM tbl_properties JOIN tbl_prt_facilities
ON tbl_properties.property_ID=tbl_prt_facilities.property_ID
WHERE (tbl_properties.delete='0' AND tbl_properties.status_Details='published'
AND tbl_properties.stat='unsold'
AND tbl_properties.category_ID='" . $data["category"] . "'
)";
$result2 = mysqli_query($conn, $query2);
if (!empty($result2) && mysqli_num_rows($result2) > 0) {
while ($prop = mysqli_fetch_assoc($result2)) {
$query2 = "UPDATE tbl_property_alert SET matchID ='" . $prop["property_ID"] . "' WHERE id='" . $data["id"] . "' ";
mysqli_query($conn, $query2);
send_notification($data['id'], $prop['property_ID'], $prop['user_ID']);
}
}
}
}
}
alert();
// AND tbl_properties.subtype='" . $data["subtype"] . "'
// AND tbl_properties.country='" . $data["country"] . "'
// AND tbl_properties.state='" . $data["state"] . "'
// AND tbl_properties.price >= '" . $data["max-price"] . "'
// AND tbl_prt_facilities.bedroom='" . $data["beds_no"] . "'
| true |
4fa6f588b1bfd416e5892ed973ccd8a287332232 | PHP | donataskriauciunas/Palanga | /solid/OpenClose/Objects/Triangle.php | UTF-8 | 1,118 | 3.671875 | 4 | [] | no_license | <?php
namespace solid\OpenClose\Objects;
class Triangle implements FigureInterface
{
/** @var float */
private $lenght1, $length2, $length3;
/**
* Triangle constructor.
* @param float $length1
* @param float $length2
* @param float $length3
*/
public function __construct($length1, $length2, $length3)
{
$this->lenght1 = $length1;
$this->length2 = $length2;
$this->length3 = $length3;
}
/**
* @return float
*/
public function countArea()
{
return sqrt(
$this->getHalfPerimeter()*($this->getHalfPerimeter() - $this->lenght1)
* $this->getHalfPerimeter()*($this->getHalfPerimeter() - $this->length2)
* $this->getHalfPerimeter()*($this->getHalfPerimeter() - $this->length3)
);
}
/**
* @return float
*/
public function countPerimeter()
{
return $this->lenght1 + $this->length2 + $this->length3;
}
/**
* @return float
*/
private function getHalfPerimeter()
{
return $this->countPerimeter() / 2;
}
} | true |
23b2f448cce4d47dbc059c5af17d088ef24542f6 | PHP | rabiulkhan/news_graphics | /live_on_v2.php | UTF-8 | 1,141 | 2.5625 | 3 | [] | no_license | <?php
error_reporting(E_ALL);
/* Allow the script to hang around waiting for connections. */
set_time_limit(0);
/* Turn on implicit output flushing so we see what we're getting
* as it comes in. */
ob_implicit_flush();
$address = 'localhost';
$port = 5250;
if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
}
if (socket_bind($sock, $address, $port) === false) {
echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}
if (socket_listen($sock, 5) === false) {
echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}
do {
if (($msgsock = socket_accept($sock)) === false) {
echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
break;
}
/* Send instructions. */
$msg = "loadbg 1-10 amb auto \r\n";
socket_write($msgsock, $msg, strlen($msg));
socket_close($msgsock);
} while (true);
socket_close($sock);
//header("Location : news_graphics_control.php");
?> | true |
cf7528715596bdf98acc2d5373bae565474e4c14 | PHP | adawongframework/project | /system/classes/Ada/Database/Driver/Mysqli.php | UTF-8 | 4,851 | 2.734375 | 3 | [] | no_license | <?php if (!defined('ADAPATH')) die ('Access failure');
/**
* Mysqli扩展实现类
*+--------------------------
* @package Core
* @category Base
* @author zjie 2014/01/05
*/
class Ada_Database_Driver_Mysqli extends Ada_Database_Driver {
/**
* 数据库配置信息
* @var Array
*/
private $config;
/**
* 链接句柄
* @var Object
*/
private $identity;
/**
* 查询结果句柄
* @var Resource
*/
private $resource;
/**
* 设置debug模式
* @var Boolean
*/
private $debug = FALSE;
/**
* 保存错误信息
* @var String
*/
private $error = '';
/**
* 构造方法
*+-------------------------------
* @param Array $config 数据库配置
*/
public function __construct($config) {
if (!extension_loaded('mysqli')) {
throw new Ada_Exception('Mysqli Expansion is not enabled');
}
$this->config = $config;
$this->debug = $config['debug'];
}
/**
* 执行一条查询语句
*+-----------------------------------------
* @param String $sql
* @return Ada_Database_Driver_Mysqli_Result
*/
public function select($sql) {
$this->query($sql);
return new Ada_Database_Driver_Mysqli_Result($this->resource);
}
/**
* 执行一条插入语句
*+-------------------------------------------------
* @param String $table 表名
* @param Aarry $params 插入数据,数组key作为表字段名
* @return Boolean
*/
public function insert($table, $params) {
return $this->query(Ada_Database_Query::insertString($table, $params));
}
/**
* 执行一条更新语句
*+-------------------------------------------------
* @param String $table 表名
* @param Aarry $params 更新数据,数组key作为表字段名
* @param String $wehre 条件
* @return Boolean
*/
public function update($table, $params, $where='') {
return $this->query(Ada_Database_Query::updateString($table, $params, $where));
}
/**
* 执行一条删除语句
*+-------------------------
* @param String $table 表名
* @param String $where 条件
* @return Boolean
*/
public function delete($table, $where='') {
return $this->query(Ada_Database_Query::deleteString($table, $where));
}
/**
* 开启事物
*+------------
* @param Void
* @return Void
*/
public function start() {
$this->dblink();
$this->choose();
return mysqli_autocommit($this->identity, FALSE);
}
/**
* 提交事物
*+------------
* @param Void
* @return Void
*/
public function commit() {
$this->dblink();
$this->choose();
return mysqli_commit($this->identity);
}
/**
* 回滚事物
*+------------
* @param Void
* @return Void
*/
public function rollback() {
$this->dblink();
$this->choose();
return mysqli_rollback($this->identity);
}
/**
* 获取数据库插入id
*+----------------
* @param Void
* @return Void
*/
public function lastId() {
return mysqli_insert_id($this->identity);
}
/**
* 获取影响行数
*+------------
* @param Void
* @return Void
*/
public function affect() {
return mysqli_affected_rows($this->identity);
}
/**
* 获取错误信息
*+--------------
* @param Void
* @return String
*/
public function error() {
return $this->error;
}
/**
* 执行一条sql语句
*+------------------
* @param String $sql
* @return Boolean
*/
private function query($sql) {
$this->dblink();
$this->choose();
mysqli_query($this->identity, "SET NAMES '{$this->config['charset']}'");
if (($this->resource = mysqli_query($this->identity, $sql)) == FALSE) {
throw new Ada_Exception(mysqli_error($this->identity));
}
return TRUE;
}
/**
* 连接数据库
*+---------------
* @param Void
* @return Boolean
*/
private function dblink() {
if (is_object($this->identity)) {
return TRUE;
}
if(!($this->identity = @mysqli_connect($this->config['hostname'], $this->config['username'], $this->config['password']))) {
throw new Ada_Exception(mysqli_connect_error(),mysqli_connect_errno());
}
return TRUE;
}
/**
* 选择数据库
*+---------------
* @param Void
* @return Boolean
*/
private function choose() {
if(!(mysqli_select_db($this->identity, $this->config['database']))) {
$this->debug();
}
return TRUE;
}
/**
* 设置或者捕获错误信息
*+--------------------
* @param Void
* @return Void
*/
private function debug() {
if (is_object($this->identity)) {
if ($this->debug) {
throw new Ada_Exception(mysqli_error($this->identity), mysqli_errno($this->identity));
} else {
$this->error = mysqli_error($this->identity);
}
}
}
/**
* 析构函数
*+------------
* 释放资源
*+------------
* @param Void
* @return Void
*/
public function __destruct() {
if (is_resource($this->identity)) {
mysqli_close($this->identity);
}
if (is_resource($this->resource)) {
mysqli_free_result($this->resource);
}
unset($this->config);
}
} | true |
c2881a69c72dd8be9bd3e3cced63e0f7858944bb | PHP | satpreetsingh/183project | /NoteShare/htdocs/model/dbcon.php | UTF-8 | 2,461 | 2.890625 | 3 | [] | no_license | <?php
// Author: Joseph Trapani
// Date: 10/27/2009
// General concept found on: http://www.killersites.com/forums/topic/1843/oops-mysql-connecting-and-fetching-data/
// Base class which acts as an ancestor class.
// Instanciation example: include '/var/www/localhost/htdocs/model/dbcon.php';
// $dbData = new DBData("localhost","root","b4n4n4s","NoteShareSEP);
class DBConnect {
protected $hostname,$username,$password,$db_name;
/**
* Constructor
* @param String $hostname,$username,$password,$db_name.
* All information we need to provide whenever we connect to a database.
*/
public function __construct($hostname,$username,$password,$db_name){
$this->hostname = $hostname;
$this->username = $username;
$this->password = $password;
$this->db_name = $db_name;
}
/**
* Connect to MySQL.
* @return void
*/
public function connectToMySQL(){
$this->con = mysql_connect($this->hostname,$this->username,$this->password);
if (!$this->con){
die( "<br>Could not connect to MySQL" . mysql_error() . ".<br />");
}
}
}
/**
* Disconnect from MySQL.
* @return void
*/
function closeConnection(){
mysql_close();
}
/*
* DBData class extends DBConnect
*/
class DBData extends DBConnect{
/**
* Constructor
* @param String $hostname,$username,$password,$db_name.
* All information we need to provide whenever we connect to a database.
*/
public function __construct($hostname = "localhost",$username = "root",$password = "b4n4n4s",$db_name = "NoteShareSEP"){
// Call the parent constructor to set up the protected data fields.
parent::__construct($hostname,$username,$password,$db_name);
// Connect to the MySQL Server.
$this -> connectToMySQL();
// Select the database.
$this -> selectDB();
}
public function selectDB(){
$result = mysql_select_db($this->db_name,$this->con);
if (!$result){
die( "<br>Could not connect to database ' ". $this->db_name. " ' ".mysql_error() . ".<br />");
}
}
}
?> | true |
8dc8d7a682f19273f9ecf0d51e6c9ed7e622b387 | PHP | neosumit/demo | /assignment_3/test/delete.php | UTF-8 | 584 | 2.703125 | 3 | [] | no_license | <?php
$_GET['id'];
$ids=$_GET['id'];
echo $ids;
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "training";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$dele = "DELETE FROM `customer` WHERE `id`='$ids'";
// echo "hello";
if ($conn->query($dele) === TRUE) {
header("Location:main.php");
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
?> | true |
50b23373b0e8f816d73e7a27b046177482cd8fae | PHP | evalor/ClickTask | /Core/Curl/Cookie.php | UTF-8 | 2,420 | 3.09375 | 3 | [
"Apache-2.0"
] | permissive | <?php
namespace eValor\cronTask\Core\Curl;
/**
* HTTP Cookie Class
* Class Cookie
* @author : evalor <master@evalor.cn>
* @package eValor\cronTask\Core\Curl
*/
class Cookie
{
private $name;
private $value;
private $expire = 0;
private $path = '/';
private $domain = null;
private $secure = false;
private $httpOnly = false;
/**
* @return mixed
*/
public function getName()
{
return $this->name;
}
/**
* @param mixed $name
* @return Cookie
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* @return mixed
*/
public function getValue()
{
return $this->value;
}
/**
* @param mixed $value
* @return Cookie
*/
public function setValue($value)
{
$this->value = $value;
return $this;
}
/**
* @return int
*/
public function getExpire()
{
return $this->expire;
}
/**
* @param int $expire
* @return Cookie
*/
public function setExpire($expire)
{
$this->expire = $expire;
return $this;
}
/**
* @return string
*/
public function getPath()
{
return $this->path;
}
/**
* @param string $path
* @return Cookie
*/
public function setPath($path)
{
$this->path = $path;
return $this;
}
/**
* @return null
*/
public function getDomain()
{
return $this->domain;
}
/**
* @param null $domain
* @return Cookie
*/
public function setDomain($domain)
{
$this->domain = $domain;
return $this;
}
/**
* @return bool
*/
public function isSecure()
{
return $this->secure;
}
/**
* @param bool $secure
* @return Cookie
*/
public function setSecure($secure)
{
$this->secure = $secure;
return $this;
}
/**
* @return bool
*/
public function isHttpOnly()
{
return $this->httpOnly;
}
/**
* @param bool $httpOnly
* @return Cookie
*/
public function setHttpOnly($httpOnly)
{
$this->httpOnly = $httpOnly;
return $this;
}
public function __toString()
{
return "{$this->name}={$this->value};";
}
} | true |
876d1630a513f89a49dccd737924946df133722c | PHP | JKetelaar/Switchboo | /src/Controller/SwitchController.php | UTF-8 | 6,784 | 2.515625 | 3 | [] | no_license | <?php
namespace App\Controller;
use App\Entity\API\Supplier;
use App\Entity\PersonalInformation;
use App\Entity\Quote;
use App\Form\QuoteStepFourType;
use App\Service\SwitchException;
use App\Service\SwitchManager;
use NumberFormatter;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
/**
* Class SwitchController
* @package App\Controller
*
* @Route("/switch/step")
*/
class SwitchController extends AbstractController
{
/**
* @param Request $request
* @return RedirectResponse|Response
*
* @Route("/5", name="switch_step_5")
*/
public function switchStepFive(Request $request)
{
return $this->render(
'switch/step_5.html.twig'
);
}
/**
* @param Request $request
* @return RedirectResponse|Response
*
* @Route("/4", name="switch_step_4")
*/
public function switchStepFour(Request $request)
{
if (($quote = $this->getQuote($request)) === null) {
return $this->redirectToHome();
}
if (($personalInformation = $quote->getPersonalInformation()) === null) {
$personalInformation = new PersonalInformation();
}
$form = $this->createForm(QuoteStepFourType::class, $personalInformation);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$personalInformation = $form->getData();
$quote->setPersonalInformation($personalInformation);
$this->getDoctrine()->getManager()->persist($personalInformation);
$this->getDoctrine()->getManager()->persist($quote);
$this->getDoctrine()->getManager()->flush();
return $this->redirectToRoute('switch_step_5');
}
return $this->render(
'switch/step_4.html.twig',
[
'form' => $form->createView(),
]
);
}
/**
* @param Request $request
* @return Quote|null
*/
private function getQuote(Request $request): ?Quote
{
$id = $request->getSession()->get('quote');
if ($id === null) {
return null;
}
return $this->getDoctrine()->getRepository(Quote::class)->find($id);
}
/**
* @param array|null $errors
* @return RedirectResponse
*/
private function redirectToHome(?array $errors = null): RedirectResponse
{
return $this->redirectToRoute('home', ['errors' => $errors]);
}
/**
* @param int $step
* @param Request $request
* @param SwitchManager $switchManager
* @return RedirectResponse|Response
*
* @Route("/{step}", name="switch_step")
*/
public function switchStep(int $step, Request $request, SwitchManager $switchManager)
{
$numberFormatter = new NumberFormatter('en', NumberFormatter::SPELLOUT);
$stepFormType = 'App\Form\QuoteStep'.ucfirst($numberFormatter->format($step)).'Type';
return $this->nextStep($request, $step, $step + 1, $stepFormType, $switchManager);
}
/**
* @param Request $request
* @param int $currentStep
* @param int $nextStep
* @param string $formClass
* @param SwitchManager $switchManager
* @return RedirectResponse|Response
*/
private function nextStep(Request $request, int $currentStep, int $nextStep, string $formClass, SwitchManager $switchManager)
{
if (($quote = $this->getQuote($request)) === null) {
return $this->redirectToHome();
}
$switchManager->setQuote($quote);
$suppliers = null;
$options = [];
if ($currentStep === 1) {
$suppliers = [];
$plans = [];
/** @var Supplier $supplier */
try {
foreach ($switchManager->getSuppliers() as $supplier) {
$suppliers[$supplier->getName()] = $supplier->getId();
foreach ($supplier->getPlans() as $plan) {
$plans[$plan->getName()] = $plan->getId();
}
}
} catch (SwitchException $e) {
return $this->redirectToHome($e->getErrors());
}
ksort($suppliers);
$options['suppliers'] = $suppliers;
$options['plans'] = $plans;
} elseif ($currentStep === 2) {
$options['payment_methods'] = $switchManager->getPaymentMethods();
} elseif ($currentStep === 3) {
$suppliers = $switchManager->getFutureSupplies();
$options['suppliers'] = $suppliers;
}
$form = $this->createForm($formClass, $quote, $options);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
/** @var Quote $quote */
$quote = $form->getData();
if ($currentStep === 2) {
if ($request->request->get('quote_step_two')['selectedGasSpend'] == '1') {
$quote->setSelectedGasSpend(true);
$quote->setGasUseKWH(null);
} else {
$quote->setSelectedGasSpend(false);
$quote->setGasMoneyPerType(null);
$quote->setGasMoneySpend(null);
}
if ($request->request->get('quote_step_two')['selectedElecSpend'] == '1') {
$quote->setSelectedElecSpend(true);
$quote->setElecUseKWH(null);
} else {
$quote->setSelectedElecSpend(false);
$quote->setElecMoneyPerType(null);
$quote->setElecMoneySpend(null);
}
}
if ($request->request->get('quote_step_one') !== null && $request->request->get(
'quote_step_one'
)['sameSupplier'] == '0') {
$quote->setSameSupplier(false);
}
$this->getDoctrine()->getManager()->persist($quote);
$this->getDoctrine()->getManager()->flush();
return $this->redirectToRoute('switch_step', ['step' => $nextStep]);
}
return $this->render(
'switch/step_'.$currentStep.'.html.twig',
[
'form' => $form->createView(),
'suppliers' => $suppliers,
'payment_methods' => ($currentStep === 3 ? $switchManager->getPaymentMethods(
true
) : null),
'quote' => $quote
]
);
}
}
| true |
83c7a4125658498af4acfab3df56826518abab6f | PHP | awaiskhalil/PHP-and-mysql | /server.php | UTF-8 | 3,601 | 2.796875 | 3 | [] | no_license | <?php
SESSION_start();
$name = "";
$email = "";
$errors = array();
$Name = "";
$phone_no="";
//connect to the database
$db = mysqli_connect('localhost', 'root', '', 'mydb');
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//if the registration button is clicked
if (isset($_POST['register'])) {
$name = mysqli_real_escape_string($db, $_POST['name']);
$email = mysqli_real_escape_string($db, $_POST['email']);
$password_1 = mysqli_real_escape_string($db, $_POST['password_1']);
$password_2 = mysqli_real_escape_string($db, $_POST['password_2']);
// ensure that form fields are filled properly
if (empty($name)){
array_push($errors, "Name is required");
}
if (empty($email)){
array_push($errors, "Email is required");
}
if (empty($password_1)){
array_push($errors, "Password is required");
}
if ($password_1 != $password_2){
array_push($errors, "Password and Confirm Passowrd do not match");
}
//if there are no errors, save user to database
if (count($errors) == 0){
$password = md5($password_1); //encypt password before storing in database
$sql = "INSERT INTO registration (name, email, password)
VALUES ('$name', '$email', '$password')";
mysqli_query($db,$sql);
$_SESSION['email'] = $email;
$_SESSION['success'] = "You are now logged in";
header('location: index.php'); // redirect to home page
}
}
// login user from login page
if (isset($_POST['login'])) {
$email = mysqli_real_escape_string($db, $_POST['email']);
$password= mysqli_real_escape_string($db, $_POST['password']);
// ensure that form fields are filled properly
if (empty($email)) {
array_push($errors, "Email is required");
}
if (empty($password)) {
array_push($errors, "Password is required");
}
if (count($errors) == 0) {
$password= md5($password); //encypt the password
$query = "SELECT * FROM registration WHERE email='$email' AND password='$password'";
$result = mysqli_query($db, $query);
if (mysqli_num_rows($result) == 1) {
// user log in
$_SESSION['email'] = $email;
$_SESSION['success'] = "You are now logged in";
header('location: index.php'); // redirect to home page
}
else{
array_push($errors, "wrong username or password");
// header('location: login.php');
}
}
}
if (isset($_POST['add_phone'])) {
$Name = mysqli_real_escape_string($db, $_POST['Name']);
$phone_no = mysqli_real_escape_string($db, $_POST['phone_no']);
if (empty($Name)){
array_push($errors, "Name is required");
}
if (empty($phone_no)){
array_push($errors, "Phone Number is required");
}
//if there are no errors, save user to database
if (count($errors) == 0){
$sql = "INSERT INTO phone (Name, phone_no)
VALUES ('$Name', '$phone_no')";
mysqli_query($db,$sql);
header('location: index.php');
}
}
// logout session
if (isset($_GET['logout'])) {
session_destroy();
unset($_SESSION['email']);
header('location: login.php');
}
?> | true |
bd8b64b0bc1d5dca67912c9b99c04dae12940439 | PHP | baconwaffles/ukfn | /app/User.php | UTF-8 | 11,376 | 2.84375 | 3 | [
"MIT"
] | permissive | <?php
namespace App;
use DB;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'surname', 'email', 'password', 'title_id', 'group_id',
'department_id', 'orcidid', 'url', 'researcher'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* Compare old and new tags to determine which ones we are deleting
* (in old but not in new) and which ones we are adding
* (in new but not in old)
*
* @param array $tags Multidimensional array containing an array per tagtype
* @return void
*/
public function updateTags($tags)
{
$tagtypes = ['disciplines' => 1, 'applications' => 2,
'techniques' => 3, 'facilities' => 4];
$currentTags = $this->getTagIds();
if (!empty($currentTags)) {
// merge all input tags for comparison
$inputTags = [];
foreach ($tagtypes as $type) {
if (!empty($tags[$type]) && is_array($tags[$type])) {
array_merge($inputTags, $tags[$type]);
}
}
// detach all tags that were not input
foreach ($currentTags as $curTag) {
if (!in_array($curTag, $inputTags)) {
$this->tags()->detach($curTag);
}
}
}
foreach ($tagtypes as $type => $key) {
if (!empty($tags[$type])) {
foreach ($tags[$type] as $element) {
$id = is_numeric($element)
? $element
: Tag::create(['name' => $element,
'category' => 'Other', 'tagtype_id' => $key]);
$this->tags()->attach($id);
}
}
}
}
/**
* Compare old and new institutions to determine which ones
* we are deleting (in old but not in new) and which ones
* we are adding (in new but not in old)
*
* @param array $institutions
* @return void
*/
public function updateInstitutions($institutions)
{
$currentInstitutions = $this->getInstitutionIds();
if (!empty($currentInstitutions)) {
foreach ($currentInstitutions as $curInstitution) {
if (!in_array($curInstitution, $institutions)) {
$this->institutions()->detach($curInstitution);
}
}
}
if (!empty($institutions)) {
foreach ($institutions as $inputInstitution) {
if (!in_array($inputInstitution, $currentInstitutions)) {
$id = is_numeric($inputInstitution)
? $inputInstitution
: Institution::create(['name' => $inputInstitution]);
$this->institutions()->attach($id);
}
}
}
}
/**
* Get the institutions associated with the given user
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function institutions()
{
return $this->belongsToMany('App\Institution', 'institution_users')
->withTimestamps();
}
/**
* Get the sigs associated with the given user
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function sigs()
{
return $this->belongsToMany('App\Sig', 'sig_users')
->withPivot('main')->withTimestamps();
}
/**
* Get the tags associated with the given user
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function tags()
{
return $this->belongsToMany('App\Tag', 'user_tags')->withTimestamps();
}
/**
* Get the disciplines associated with the given user
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function disciplines()
{
return $this->belongsToMany('App\Tag', 'user_tags')
->where('tagtype_id', 1)
->withTimestamps();
}
/**
* Get the title associated with the user
*
* @return \Illuminate\Database\Eloquent\Relations\belongsTo
*/
public function title()
{
return $this->belongsTo('App\Title');
}
/**
* Get the group associated with the user
*
* @return \Illuminate\Database\Eloquent\Relations\belongsTo
*/
public function group()
{
return $this->belongsTo('App\Group');
}
/**
* Get the group associated with the user
*
* @return \Illuminate\Database\Eloquent\Relations\belongsTo
*/
public function department()
{
return $this->belongsTo('App\Department');
}
/**
* Get the subscription associated with the user
*
* @return \Illuminate\Database\Eloquent\Relations\HasOne
*/
public function subscription()
{
return $this->hasOne('App\Subscription');
}
/**
* Get the news associated with the user
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function news()
{
return $this->hasMany('App\News');
}
/**
* Get the events associated with the user
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function events()
{
return $this->hasMany('App\Event');
}
/**
* Get the list of tag ids associated with the user
*
* @return array
*/
public function getTagIds()
{
return $this->tags->lists('id')->toArray();
}
/**
* Get the list of institution ids associated with the user
*
* @return array
*/
public function getInstitutionIds()
{
return $this->institutions->lists('id')->toArray();
}
/**
* Determine if the user is allowed to edit the sig given by $sigId
*
* @param int $sigId
* @return boolean
*/
public function canEditSig($sigId)
{
return $this->isAdmin() || $this->isSigEditorOf($sigId);
}
/**
* Determine if the user can edit a sig AND is NOT an admin
*
* @param int $sigId
* @return boolean
*/
public function isSigEditorOf($sigId)
{
return $this->isLeaderOfSig($sigId)
|| $this->isColeaderOfSig($sigId)
|| $this->isKeyPersonnelOfSig($sigId);
}
/**
* Determine if the user can edit SIG pages (in general)
*
* @param int $sigId
* @return boolean
*/
public function isSigEditor()
{
return $this->isSigLeader()
|| $this->isSigCoLeader()
|| $this->isSigKeyPersonnel();
}
/**
* Determine if the user is a leader of the sig given by $sigId
*
* @param int $sigId
* @return boolean
*/
public function isLeaderOfSig($sigId)
{
return $this->sigs()->where('sigs.id', $sigId)
->where('main', 1)->count() > 0;
}
/**
* Determine if the user is a coleader of the sig given by $sigId
*
* @param int $sigId
* @return boolean
*/
public function isColeaderOfSig($sigId)
{
return $this->sigs()->where('sigs.id', $sigId)
->where('main', 2)->count() > 0;
}
/**
* Determine if the user is a key member of the sig given by $sigId
*
* @param int $sigId
* @return boolean
*/
public function isKeyPersonnelOfSig($sigId)
{
return $this->sigs()->where('sigs.id', $sigId)
->where('main', 3)->count() > 0;
}
/**
* Determine if the user is asscociated with the sig given by $sigId
*
* @param int $sigId
* @return boolean
*/
public function belongsToSig($sigId)
{
return $this->sigs()->where('sigs.id', $sigId)->count() > 0;
}
/**
* Determine if the user is an administrator.
*
* @return boolean
*/
public function isAdmin()
{
return $this->group_id === 1;
}
/**
* Determine if the user is the leader of at least one sig.
*
* @return boolean
*/
public function isSigLeader()
{
return $this->sigs()->where('main', 1)->count() > 0;
}
/**
* Determine if the user is the co-leader of at least one sig.
*
* @return boolean
*/
public function isSigCoLeader()
{
return $this->sigs()->where('main', 2)->count() > 0;
}
/**
* Determine if the user is the key personnel of at least one sig.
*
* @return boolean
*/
public function isSigKeyPersonnel()
{
return $this->sigs()->where('main', 3)->count() > 0;
}
/**
* Determine if the user is the member of at least one sig.
*
* @return boolean
*/
public function isSigMember()
{
return $this->sigs()->where('main', 0)->count() > 0;
}
/**
* Get the SIG for which the user is a leader
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function sigLeaderships()
{
return $this->sigs()->where('main', 1)->get();
}
/**
* Get the IDs of the SIG for which the user is a leader
*
* @return array
*/
public function sigLeadershipsIds()
{
return $this->sigs()->where('main', 1)->lists('id')->toArray();
}
/**
* Get the SIGs that this user can edit
*
* @return array
*/
public function editableSigs()
{
$editable = [];
foreach ($this->sigs as $sig) {
if ($this->canEditSig($sig->id)) {
$editable[] = $sig;
}
}
return $editable;
}
/**
* Get the value of the sig_users.main attribute for the user
* and a given $sigId
*
* @param int $sigId
* @return int
*/
public function sigStatusId($sigId)
{
if (!$this->belongsToSig($sigId)) {
return null;
}
return $this->sigs()->where('sigs.id', $sigId)->first()->pivot->main;
}
/**
* Get the membership status of the user for a given $sigId
*
* @param int $sigId
* @return string
*/
public function sigStatus($sigId)
{
switch ($this->sigStatusId($sigId)) {
case 0: return "Member";
case 1: return "Leader";
case 2: return "Co-leader";
case 3: return "Key personnel";
}
return null;
}
/**
* Get the list of institutions linked to users
*
* @return array
*/
public static function userInstitutions()
{
return DB::table('institution_users')
->select(DB::raw('DISTINCT(`institution_id`) as id, name'))
->join('institutions','institution_users.institution_id',
'=','institutions.id')
->orderBy('name')
->get();
}
}
| true |
220067a5789ec1d65192121e06018343db22d47d | PHP | eltortuganegra/medieval-jousting-tournaments | /application/protected/models/SigninForm.php | UTF-8 | 1,322 | 2.921875 | 3 | [
"MIT"
] | permissive | <?php
/**
* SigninForm class.
* LoginForm is the data structure for keeping
* user login form data. It is used by the 'login' action of 'SiteController'.
*/
class SiginForm extends CFormModel
{
public $email;
public $password;
public $knight_name;
private $_identity;
/**
* Declares the validation rules.
* The rules state that username and password are required,
* and password needs to be authenticated.
*/
public function rules()
{
return array(
// username and password are required
array('email, password, knight_name', 'required'),
// check email format
array('email', 'email'),
// check max length
array('email', 'length', 'max'=>255),
array('password', 'length', 'max'=>60),
//Check min length knight name
array( 'knight_name', 'length', 'min'=>4)
);
}
/**
* Declares attribute labels.
*/
public function attributeLabels()
{
return array(
'email'=>'email',
'password'=>'password',
'knight_name'=>'name',
);
}
/**
* Sigin user
* @return boolean whether login is successful
*/
public function existEmail( $email ){
//Check if user and mail is used
$user = Users::model()->findByAttributes( array(
'select'=>'*',
'condition'=>'email=:email',
'params'=>array(':email'=>$email )
));
var_dump($user);
}
}
| true |
4590c0153c6bf6b9fa737d3fdf262654dfc1ad31 | PHP | Victorien95/phpoo | /bibliotheque/App/Cnx.php | UTF-8 | 817 | 3.078125 | 3 | [] | no_license | <?php
namespace App;
class Cnx
{
/**
* @var \PDO
*/
private static $instance;
/**
* Constructeur privé pour êmpecher d'instancier la classe
*/
private function __construct()
{
}
/**
* @return \PDO
*/
public static function getInstance(): \PDO
{
if (is_null(self::$instance))
{
self::$instance = new \PDO(
'mysql:dbname=bibliotheque;host=localhost',
'root',
'',
[
\PDO::MYSQL_ATTR_INIT_COMMAND =>'SET names utf8',
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION
]
);
}
return self::$instance;
}
} | true |
e83f9ca7b114bea2b7034772811ced65f2f0d7d7 | PHP | ai310/codecamp | /htdocs/home/codecamp_18989/htdocs/php/07/if.php | UTF-8 | 321 | 3.296875 | 3 | [] | no_license | <!DOCTYPE html>
<html lang="ja">
<head>
<title></title>
<meta charset="utf-8">
</head>
<body>
<?php
// 0〜1のランダムな数字を取得
$rand = mt_rand(1, 10);
// 6以上の場合
if ($rand >= 6) {
print '当たり';
// 6未満の場合
} else {
print 'はずれ';
}
?>
</body>
</html> | true |
92fc87ad58c1440f2588539353a230a2d0b9c915 | PHP | fgaudenzi/webERP-bootstrap | /Z_ImportPriceList.php | UTF-8 | 6,327 | 2.65625 | 3 | [] | no_license | <?php
include('includes/session.inc');
$Title = _('Import Sales Price List');
include('includes/header.inc');
echo '<p class="page_title_text"><img alt="" src="' . $RootPath . '/css/' . $Theme .
'/images/maintenance.png" title="' .
_('Import Price List from CSV file') . '" />' . ' ' .
_('Import Price List from CSV file') . '</p>';
$FieldHeadings = array(
'StockID', // 0 'STOCKID',
'SalesType', // 1 'Price list id',
'CurrencyCode', // 2 'Currency Code',
'Price' // 3 'Price'
);
if (isset($_FILES['PriceListFile']) and $_FILES['PriceListFile']['name']) { //start file processing
//check file info
$FileName = $_FILES['PriceListFile']['name'];
$TempName = $_FILES['PriceListFile']['tmp_name'];
$FileSize = $_FILES['PriceListFile']['size'];
$FieldTarget = 4;
$InputError = 0;
//get file handle
$FileHandle = fopen($TempName, 'r');
//get the header row
$HeadRow = fgetcsv($FileHandle, 10000, ',');
//check for correct number of fields
if ( count($HeadRow) != count($FieldHeadings) ) {
prnMsg (_('File contains') . ' '. count($HeadRow). ' ' . _('columns, expected') . ' '. count($FieldHeadings). '. ' . _('Download the template to see the expected columns.'),'error');
fclose($FileHandle);
include('includes/footer.inc');
exit;
}
//test header row field name and sequence
$HeadingColumnNumber = 0;
foreach ($HeadRow as $HeadField) {
if ( trim(mb_strtoupper($HeadField)) != trim(mb_strtoupper($FieldHeadings[$HeadingColumnNumber]))) {
prnMsg (_('The file to import the price list from contains incorrect column headings') . ' '. mb_strtoupper($HeadField). ' != '. mb_strtoupper($FieldHeadings[$HeadingColumnNumber]). '<br />' . _('The column headings must be') . ' StockID, SalesType, CurrencyCode, Price','error');
fclose($FileHandle);
include('includes/footer.inc');
exit;
}
$HeadingColumnNumber++;
}
//start database transaction
DB_Txn_Begin();
//loop through file rows
$LineNumber = 1;
while ( ($myrow = fgetcsv($FileHandle, 10000, ',')) !== FALSE ) {
//check for correct number of fields
$FieldCount = count($myrow);
if ($FieldCount != $FieldTarget){
prnMsg ($FieldTarget . ' ' . _('fields required') . ', '. $FieldCount. ' ' . _('fields received'),'error');
fclose($FileHandle);
include('includes/footer.inc');
exit;
}
// cleanup the data (csv files often import with empty strings and such)
$StockID = mb_strtoupper($myrow[0]);
foreach ($myrow as &$value) {
$value = trim($value);
$value = str_replace('"', '', $value);
}
//first off check that the item actually exist
$sql = "SELECT COUNT(stockid) FROM stockmaster WHERE stockid='" . $StockID . "'";
$result = DB_query($sql);
$testrow = DB_fetch_row($result);
if ($testrow[0] == 0) {
$InputError = 1;
prnMsg (_('Stock item') . ' "'. $myrow[0]. '" ' . _('does not exist'),'error');
}
//Then check that the price list actually exists
$sql = "SELECT COUNT(typeabbrev) FROM salestypes WHERE typeabbrev='" . $myrow[1] . "'";
$result = DB_query($sql);
$testrow = DB_fetch_row($result);
if ($testrow[0] == 0) {
$InputError = 1;
prnMsg (_('SalesType/Price List') . ' "' . $myrow[1]. '" ' . _('does not exist'),'error');
}
//Then check that the currency code actually exists
$sql = "SELECT COUNT(currabrev) FROM currencies WHERE currabrev='" . $myrow[2] . "'";
$result = DB_query($sql);
$testrow = DB_fetch_row($result);
if ($testrow[0] == 0) {
$InputError = 1;
prnMsg (_('Currency') . ' "' . $myrow[2] . '" ' . _('does not exist'),'error');
}
//Finally force the price to be a double
$myrow[3] = (double)$myrow[3];
if ($InputError !=1){
//Firstly close any open prices for this item
$sql = "UPDATE prices
SET enddate='" . FormatDateForSQL($_POST['StartDate']) . "'
WHERE stockid='" . $StockID . "'
AND enddate>'" . date('Y-m-d') . "'
AND typeabbrev='" . $myrow[1] . "'";
$result = DB_query($sql);
//Insert the price
$sql = "INSERT INTO prices (stockid,
typeabbrev,
currabrev,
price,
startdate
) VALUES (
'" . $myrow[0] . "',
'" . $myrow[1] . "',
'" . $myrow[2] . "',
'" . $myrow[3] . "',
'" . FormatDateForSQL($_POST['StartDate']) . "')";
$ErrMsg = _('The price could not be added because');
$DbgMsg = _('The SQL that was used to add the price failed was');
$result = DB_query($sql, $ErrMsg, $DbgMsg);
}
if ($InputError == 1) { //this row failed so exit loop
break;
}
$LineNumber++;
}
if ($InputError == 1) { //exited loop with errors so rollback
prnMsg(_('Failed on row '. $LineNumber. '. Batch import has been rolled back.'),'error');
DB_Txn_Rollback();
} else { //all good so commit data transaction
DB_Txn_Commit();
prnMsg( _('Batch Import of') .' ' . $FileName . ' '. _('has been completed. All transactions committed to the database.'),'success');
}
fclose($FileHandle);
} else { //show file upload form
echo '<form action="' . htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8') . '" method="post" class="noPrint" enctype="multipart/form-data">';
echo '<div class="centre">';
echo '<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />';
echo '<div class="page_help_text">' .
_('This function loads a new sales price list from a comma separated variable (csv) file.') . '<br />' .
_('The file must contain four columns, and the first row should be the following headers:') . '<br />StockID, SalesType, CurrencyCode, Price<br />' .
_('followed by rows containing these four fields for each price to be uploaded.') . '<br />' .
_('The StockID, SalesType, and CurrencyCode fields must have a corresponding entry in the stockmaster, salestypes, and currencies tables.') . '</div>';
echo '<br /><input type="hidden" name="MAX_FILE_SIZE" value="1000000" />' .
_('Prices effective from') . ': <input type="text" name="StartDate" size="10" class="date" alt="' . $_SESSION['DefaultDateFormat'] . '" value="' . date($_SESSION['DefaultDateFormat']) . '" /> ' .
_('Upload file') . ': <input name="PriceListFile" type="file" />
<input type="submit" name="submit" value="' . _('Send File') . '" />
</div>
</form>';
}
include('includes/footer.inc');
?>
| true |
3191570264558ed25763cee191415b2c216dd08c | PHP | ooglek/php-bandwidth-iris | /tests/OtherTest.php | UTF-8 | 2,599 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Middleware;
class OtherTest extends PHPUnit_Framework_TestCase {
public static $container;
public static $client;
public static $index = 0;
public static function setUpBeforeClass() {
$mock = new MockHandler([
new Response(200, [], "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><CityResponse> <ResultCount>618</ResultCount> <Cities> <City> <RcAbbreviation>PINEHURST</RcAbbreviation> <Name>ABERDEEN</Name> </City> <City> <RcAbbreviation>JULIAN</RcAbbreviation> <Name>ADVANCE</Name> </City> </Cities></CityResponse>"),
new Response(200, [], "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><RateCenters> <ResultCount>652</ResultCount> <RateCenters> <RateCenter> <Abbreviation>AGOURA</Abbreviation> <Name>AGOURA</Name> </RateCenter> <RateCenter> <Abbreviation>ALAMITOS</Abbreviation> <Name>ALAMITOS</Name> </RateCenter> </RateCenters></RateCenters>"),
]);
self::$container = [];
$history = Middleware::history(self::$container);
$handler = HandlerStack::create($mock);
$handler->push($history);
self::$client = new Iris\Client("test", "test", Array('url' => 'https://api.test.inetwork.com/v1.0', 'handler' => $handler));
}
public function testCitiesGet() {
$c = new \Iris\Cities(self::$client);
$cities = $c->getList(["state" => "NC"]);
$json = '{"RcAbbreviation":"PINEHURST","Name":"ABERDEEN"}';
$this->assertEquals($json, json_encode($cities[0]->to_array()));
$this->assertEquals("GET", self::$container[self::$index]['request']->getMethod());
$this->assertEquals("https://api.test.inetwork.com/v1.0/cities?state=NC", self::$container[self::$index]['request']->getUri());
self::$index++;
}
public function testRC() {
$c = new \Iris\RateCenter(self::$client);
$cities = $c->getList(["state" => "CA"]);
$json = '{"Name":"AGOURA","Abbreviation":"AGOURA"}';
$this->assertEquals($json, json_encode($cities[0]->to_array()));
$this->assertEquals("GET", self::$container[self::$index]['request']->getMethod());
$this->assertEquals("https://api.test.inetwork.com/v1.0/rateCenters?state=CA", self::$container[self::$index]['request']->getUri());
self::$index++;
}
}
| true |
020c53a2bcf5e4f2ac049e801a061b1bf820f229 | PHP | ebuildy/ebuildy | /src/eBuildy/DataBinder/Form.php | UTF-8 | 2,301 | 2.8125 | 3 | [] | no_license | <?php
namespace eBuildy\DataBinder;
class Form extends DataBinder
{
protected $children = array();
public function __construct($name = '', $options = array())
{
parent::__construct($name, $options);
$this->preTransforms = array();
}
public function addChild(DataBinder $value)
{
$this->children[$value->name] = $value;
}
public function getChild($childName)
{
return $this->children[$childName];
}
public function getChildData($childName)
{
return $this->getChild($childName)->getData();
}
public function getChildDataNormed($childName)
{
return $this->getChild($childName)->getDataNormed();
}
public function getChildren()
{
return $this->children;
}
/**
* 1. Set data of children
* 2. Merge children norm validation error
* 3. Set form data
*
* @param array $value
*/
public function setData($value)
{
foreach($this->children as $child)
{
if (isset($value[$child->name]))
{
$child->setData($value[$child->name]);
}
else
{
$child->setData(null);
}
}
foreach($this->children as $child)
{
if ($child->isValid() === false)
{
foreach($child->getErrors() as $errorName => $error)
{
$this->errors[$child->name] = $error;
}
}
}
parent::setData($value);
}
public function setDataNormed($value)
{
foreach($this->children as $child)
{
if (isset($value[$child->name]))
{
$child->setDataNormed($value[$child->name]);
}
}
parent::setDataNormed($value);
}
protected function reverseTransform()
{
}
protected function transform()
{
$dataNormed = array();
foreach($this->children as $child)
{
$dataNormed[$child->name] = $child->getDataNormed();
}
$this->dataNormed = $dataNormed;
}
} | true |
8dce80647b7cf7de232efbe0e321285af31b90d1 | PHP | HectorGlez4/FaceMOOC | /php/model/MComment.php | UTF-8 | 2,023 | 2.6875 | 3 | [] | no_license | <?php
require_once("Model.php");
class MComment extends Model
{
function SelectComment($idFormation)
{
$this->Connect();
$sql = "SELECT * FROM comment WHERE id_formation = :idFormation";
$stmt = $this->PDO->prepare($sql);
$stmt->bindParam(":idFormation", $idFormation, PDO::PARAM_INT);
return $this->Select($stmt);
}
function InsertComment($idFormation, $idUser, $mark,$description, $date_comment)
{
$this->Connect();
$sql = "INSERT INTO comment(id_formation, id_user, mark, description, date_comment)
VALUES (:idFormation, :idUser ,:mark, :description , :date_comment);";
$stmt = $this->PDO->prepare($sql);
$description = htmlspecialchars($description);
$stmt->bindParam(":idFormation", $idFormation, PDO::PARAM_INT);
$stmt->bindParam(":idUser", $idUser, PDO::PARAM_INT);
$stmt->bindParam(":mark", $mark, PDO::PARAM_STR);
$stmt->bindParam(":description", $description, PDO::PARAM_STR);
$stmt->bindParam(":date_comment", $date_comment, PDO::PARAM_STR);
return $this->Insert($stmt);
}
function DeleteComment($idComment)
{
$this->Connect();
$sql = "DELETE FROM comment WHERE id_comment = :idComment ";
$stmt = $this->PDO->prepare($sql);
$stmt->bindParam(":idComment", $idComment, PDO::PARAM_INT);
return $this->Delete($stmt);
}
function UpdateComment($mark, $description, $date_comment, $idComment)
{
$this->Connect();
$sql = "UPDATE comment SET mark = :mark, description = :description, $date_comment = :date_comment
WHERE id_comment = idComment ";
$stmt = $this->PDO->prepare($sql);
$description = htmlspecialchars($description);
$stmt->bindParam(":idComment", $idComment, PDO::PARAM_INT);
$stmt->bindParam(":mark", $mark, PDO::PARAM_STR);
$stmt->bindParam(":description", $description, PDO::PARAM_STR);
$stmt->bindParam(":date_comment", $date_comment, PDO::PARAM_STR);
return$this->Update($stmt);
}
}
//$mes = new MExpert();
//echo "\n";
//var_dump($mes->SelectExpertsALL()); | true |
b54e12add6ac80e23cfa9af06d69f608758c34d8 | PHP | AlexeyKonstantinov78/apfy-All-Presents-For-You | /basic/models/Users.Old.php | UTF-8 | 5,625 | 2.578125 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
namespace app\models;
use Yii;
use yii\web\IdentityInterface;
/**
* This is the model class for table "users".
*
* @property integer $id
* @property string $user_name
* @property string $user_password
* @property string $domain
* @property double $balance
*/
class Users extends \yii\db\ActiveRecord implements IdentityInterface
{
private static $root = [
'id' => 0,
'name' => 'mouse',
'password' => 'XJ4Bk7ppbSuHuadYEby5',
];
public $auth_key;
public static function tableName()
{
return 'users';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['mail', 'password', 'phone', 'name'], 'required'],
[['status'], 'integer'],
[['data_create', 'date_last_visit'], 'safe'],
[['mail'], 'string', 'max' => 128],
['mail', 'email', 'message' => 'Проверть написание почты.'],
[['password'], 'string', 'max' => 64],
[['name', 'lastname', 'surname'], 'string', 'max' => 32],
[['phone'], 'string', 'max' => 18],
[['mail'], 'unique'],
];
}
/**
* @inheritdoc
*/
public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
if ($this->isNewRecord) {
$this->password = $this->hashPassword($this);
} else {
$this->password = $this->password != '' && $this->password != $this->oldAttributes['password'] ? $this->hashPassword($this) : $this->oldAttributes['password'];
}
return true;
} else {
return false;
}
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'mail' => 'Почта',
'password' => 'Пароль',
'name' => 'Имя',
'lastname' => 'Фамилия',
'surname' => 'Отчество',
'phone' => 'Телефон',
'status' => 'Статус',
'data_create' => 'Дата создания',
'date_last_visit' => 'Дата последнего визита',
];
}
public function is_root(){
if(\Yii::$app->user->identity->id == self::$root['id'])
return true;
return false;
}
public function is_user(){
if(findIdentity(\Yii::$app->user->identity->id) !== null && \Yii::$app->user->identity->id !== 0)
return true;
return false;
}
public static function findIdentity($id)
{
if($id === 0) return new static(self::$root);
return static::findOne($id);
//return $result;
}
public static function findByName($u)
{
if($u->name == 'mouse' && $u->password == self::$root['password']) return new static(self::$root);
return false;
}
public static function findByMail($mail)
{
$password = self::hashPassword($mail);
//var_dump(static::find()->where(['mail' => $mail->mail, 'password' => $password])->one());
//var_dump($password);
// var_dump(static::find()->where(['mail' => $mail->mail, 'password' => 'pfqrj2008gjghsu3md'])->one());
//var_dump(static::find()->where(['id' => $mail->id,'password' => self::hashPassword($u)])->one());
//exit;
return static::find()->where(['mail' => $mail->mail, 'password' => $password])->one();
}
public static function findUserByMail($mail){
//b114ebdbd2746e44e427e4613cfbb89ce3f0bb5a
//$u = self::findByMail($mail);
//echo $password;
//var_dump(static::find()->where(['mail' => $mail->mail, 'password' => $password])->one());
//var_dump($u);
// var_dump(static::find()->where(['mail' => $mail->mail, 'password' => 'pfqrj2008gjghsu3md'])->one());
//var_dump(static::find()->where(['id' => $u->id,'password' => self::hashPassword($u)])->one());
//exit;
// if($u->name == 'root' && $u->password == self::$root['password']) return new static(self::$root);
$password = self::hashPassword($mail);
return static::find()->where(['mail' => $mail->mail, 'password' => $password])->one();
//return static::find()->where(['id' => $u->id, 'password' => 'pfqrj2008gjghsu3md'])->one();
}
public static function findByUserPhone($u)
{
return static::find()->where(['phone' => $u])->one();
}
public function getId()
{
return $this->id;
}
public function validatePassword($data)
{
return $this->password === $this->hashPassword($data);
}
public function getAuthKey()
{
return '';
}
public function validateAuthKey($authKey)
{
return $this->getAuthKey() === $authKey;
}
private function generateAuthKey()
{
return Yii::$app->security->generateRandomString();
}
public static function findIdentityByAccessToken($token, $type = null)
{
return Yii::$app->session['auth_token'] == $token;
}
public function hashPassword($p)
{
/*
var_dump($p->mail);
var_dump($p->password);
var_dump(Yii::$app->params['solt']);
var_dump(sha1(Yii::$app->params['solt'].$p->password.$p->mail));
exit;
*/
$r = sha1(Yii::$app->params['solt'].$p->password.$p->mail);
return $r;
}
}
| true |
0a3153efa5bf27a711b3eb1a0c23106a8321db47 | PHP | charmonds/Cascadeo | /LRMDS/process_registration.php | UTF-8 | 4,185 | 2.640625 | 3 | [] | no_license | <?php
require_once("db_connect.g");
$myConnection = mysql_connect("$db", "$db_user", "$db_password");
$connection = mysql_select_db("$database", $myConnection);
if (!$myConnection)
{
die("Failed to connect: ". mysql_error());
}
else
{
function newSalt()
{
return chr(rand(0,255)).chr(rand(0,255)).chr(rand(0,255)).chr(rand(0,255));
}
$username = $_POST['username'];
$group_id = $_GET['group_id'];
if($group_id == 13)
{
$ctype_id = $_POST['curriculum_area_type'];
$grade_type = $_POST['grade_type'];
}
$lname = $_POST['lname'];
$fname = $_POST['fname'];
$mname = $_POST['mname'];
$password1 = $_POST['password1'];
$password2 = $_POST['password2'];
$school_id = $_POST['school_id'];
$errors = 0;
$empty = 0;
if($password1=="")
{
$empty++;
}
if($password2=="")
{
$empty++;
}
if($password1!="" && $password2 !="")
{
if($_POST['password1'] != $_POST['password2'])
{
$errors++;
}
}
//check if is blank
if($username=="")
{
$empty++;
}
else
{
$checker = '/^[^\W][a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\@[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\.[a-zA-Z]{2,4}$/';
if(preg_match($checker, $username))
{
$test = mysql_query("SELECT verifyAccount('$username') as username", $myConnection);
$fetch = mysql_fetch_array($test);
if($fetch['username']!=NULL)
{
$errors++;
}
}
else
{
$errors++;
}
}
//check name if it has no numbers
$checker = '/^[a-zA-Z]+[(-|\' )a-zA-Z]*[a-zA-Z]$/';
if($lname=="")
{
$empty++;
}
else
{
if(!preg_match($checker, $lname)) { $errors++; }
}
if($fname=="")
{
$empty++;
}
else
{
if(!preg_match($checker, $fname)) { $errors++; }
}
if($mname=="")
{
$empty++;
}
else
{
if(!preg_match($checker, $mname)) { $errors++; }
}
if($school_id=="")
{
$empty++;
}
if($group_id == 13)
{
if($ctype_id == 0 && ($grade_type != 7 && $grade_type != 8))
{
$empty++;
$errors++;
}
if($grade_type == 0)
{
$empty++;
$errors++;
}
}
if($empty)
{
echo "";
}
if(!$empty)
{
if($errors <= 0)
{
//IF EVERYTHING IS VALID
$salt = sha1(newSalt());
$encrypt_password = sha1($salt . $_POST['password1']);
$created_at = date('Y-m-d H:i:s', time());
//insert into sf_guard_user
mysql_query("INSERT INTO sf_guard_user(username, algorithm, salt, password, created_at, last_login, is_active, is_super_admin) VALUES ('$username', 'sha1', '$salt', '$encrypt_password', '$created_at', NULL, 1, 0)", $myConnection);
//get the sf_guard_user_id
$additionalInfo1 = mysql_query("
SELECT account('s', '$username', 'null') as sf_guard_user_id
", $myConnection);
$temp = mysql_fetch_array($additionalInfo1);
$sf_guard_user_id = $temp['sf_guard_user_id'];
//insert into the users table
if($group_id == 13){
if($grade_type == 7 || $grade_type == 8)
{
mysql_query("INSERT INTO users (last_name, first_name, middle_name, sf_guard_user_id, email_address, school_id, curriculum_area_type_id, created_at) VALUES('$lname', '$fname', '$mname', $sf_guard_user_id, '$username', $school_id, NULL, '$created_at')", $myConnection);
}
else mysql_query("INSERT INTO users (last_name, first_name, middle_name, sf_guard_user_id, email_address, school_id, curriculum_area_type_id, created_at) VALUES('$lname', '$fname', '$mname', $sf_guard_user_id, '$username', $school_id, $ctype_id, '$created_at')", $myConnection);
}
else
mysql_query("INSERT INTO users (last_name, first_name, middle_name, sf_guard_user_id, email_address, school_id, created_at) VALUES('$lname', '$fname', '$mname', $sf_guard_user_id, '$username', $school_id, '$created_at')", $myConnection);
//insert into sf_guard_user_group
mysql_query("INSERT INTO sf_guard_user_group VALUES($sf_guard_user_id, $group_id)", $myConnection);
header('Location: enter_login.php?action=success');
mysql_close($myConnection);
}
else
header('Location: register.php?action=error');
}
}
?> | true |
0b1a6b59ca9124f6653088bfd16cfb7fe3760ced | PHP | Sumit-Sahu/StudentPortal | /user-verification/students_info.php | UTF-8 | 1,299 | 2.578125 | 3 | [] | no_license |
<?php
//Start the session to see if the user is authencticated user.
session_start();
//Check if the user is authenticated first. Or else redirect to login page
//if(isset($_SESSION['IS_AUTHENTICATED']) && $_SESSION['IS_AUTHENTICATED'] == 1){
//require('menu.php');
/*Connect to mysql server*/
// require 'config/db.php';
$link = mysqli_connect('localhost', 'root', '');
if(!$link)
{
die('Failed to connect to server: ' . mysqli_error());
}
$db = mysqli_select_db($link,'user-verification');
if(!$db)
{
die("Unable to select database");
}
$qry = 'SELECT * FROM student';
$result = mysqli_query($link,$qry);
echo '<h1>The Students Profile are - </h1>';
/*Draw the table for Players*/
echo '<table border="1">
<th> Email </th>
<th> Roll no. </th>
<th> Name </th>
<th> Batch </th>
<th> Branch </th>
<th> DOB </th>';
/*Show the rows in the fetched result set one by one*/
while ($row = mysqli_fetch_assoc($result))
{
echo '<tr>
<td>'.$row['email'].'</td>
<td>'.$row['roll_no'].'</td>
<td>'.$row['name'].'</td>
<td>'.$row['batch'].'</td>
<td>'.$row['branch'].'</td>
<td>'.$row['dateOfBirth'].'</td>
</tr>';
}
echo '</table>';
//else{
//header('location:login_form.php');
//exit();
//}
?>
| true |
09781d8eb3832e17359697f8cb4f9cd48d55aeb8 | PHP | wolflingorg/Simple-Silex-Blog-Backend | /src/Blog/CommandBus/Middleware/Validation/CommandValidationMiddleware.php | UTF-8 | 1,340 | 2.625 | 3 | [] | no_license | <?php
namespace Blog\CommandBus\Middleware\Validation;
use Blog\Exception\ValidationException;
use SimpleBus\Message\Bus\Middleware\MessageBusMiddleware;
use Symfony\Component\Validator\ConstraintViolationList;
use Symfony\Component\Validator\Validator\ValidatorInterface;
class CommandValidationMiddleware implements MessageBusMiddleware
{
private $validator;
/**
* @param ValidatorInterface $validator
*/
public function __construct(ValidatorInterface $validator)
{
$this->validator = $validator;
}
/**
* @param object $message
* @param callable $next
*/
public function handle($message, callable $next)
{
if (is_object($message) && method_exists($message, 'loadValidatorMetadata')) {
$this->validate($message);
}
$next($message);
}
/**
* @param object $message
*/
private function validate($message)
{
/** @var ConstraintViolationList $violations */
$violations = $this->validator->validate($message);
if (count($violations) != 0) {
$errors = [];
foreach ($violations as $violation) {
$errors[$violation->getPropertyPath()] = $violation->getMessage();
}
throw new ValidationException($errors);
}
}
}
| true |
4db43c5c9f75d2eed1bb279d3e8713fd237e480e | PHP | DungBuiDeveloper/laravel_new_blog | /app/Repositories/Backend/TagRepository.php | UTF-8 | 5,180 | 2.5625 | 3 | [] | no_license | <?php
namespace App\Repositories\Backend;
use Cache;
use DataTables;
use App\Models\BackEnd\Tag;
use App\Repositories\BaseRepository;
/**
* Class PermissionRepository.
*/
class TagRepository extends BaseRepository
{
/**
* UserRepository constructor.
*
* @param Tag $model
*/
public function __construct(Tag $model)
{
$this->model = $model;
}
public function getAjaxDataTable($search)
{
$tag = $this->model->get();
return Datatables::of($tag)
->editColumn('action', function ($tag) {
$editButton = '<div class="btn-group btn-group-sm"><a
title="'.__('buttons.general.crud.edit').'"
href="'.route('admin.tags.showFormEdit', $tag->slug).'"
class="btn btn-xs btn-primary"><i class="fas fa-edit"></i></a>';
$viewButton = '<a
title="'.__('buttons.general.crud.view').'"
href="'.route('admin.tags.detail', $tag->slug).'"
class="btn btn-xs btn-warning"><i class="fas fa-eye"></i></a>';
$deleteButton = '<a
data-method="delete"
data-trans-button-cancel="'.__('buttons.general.cancel').'"
data-placement="top"
data-toggle="tooltip"
href="'.route('admin.tags.destroy', ['id' => $tag->id]).'"
data-id="'.$tag->id.'"
title="'.__('buttons.general.crud.delete').'"
data-original-title="'.__('buttons.general.crud.delete').'"
class="btn btn-xs btn-danger btn-delete"><i class="fa fa-trash"></i> </a></div>';
return $editButton.$viewButton.$deleteButton;
})
->rawColumns(['action'])
->toJson();
}
/**
* [storeCategory Save Category].
* @param [type] $data [Post Category Data]
* @return [type] [true / false Status Save Model]
*/
public function storeTag($data)
{
try {
$cacheTag = Cache::get('tags', $this->model::all());
$tagNew = $this->model::create($data);
$cacheTag[] = $tagNew;
Cache::forever('tags', $cacheTag);
return $tagNew;
} catch (\Exception $e) {
return $e->getMessage();
}
}
/**
* [getRelatedSlugs Relate Slug].
* @param [type] $slug [Condition]
* @param int $id [Use when edit]
* @return [string] [unique slug]
*/
public function getRelatedSlugs($slug, $id = 0)
{
try {
return $this->model::select('slug')->where('slug', 'like', $slug.'%')
->where('id', '<>', $id)
->get();
} catch (\Exception $e) {
return $e->getMessage();
}
}
/**
* [getAlltags].
* @return [array] [All Category ]
*/
public function getAlltags()
{
try {
$tag = Cache::rememberForever('tags', function () {
return $this->model::all();
});
return $tag;
} catch (\Exception $e) {
return $e->getMessage();
}
}
/**
* [DELETE Tag].
*/
public function destroy($id)
{
try {
$deleteTag = $this->model::find($id);
$cacheTag = Cache::get('tags', null);
if ($deleteTag) {
if ($cacheTag) {
foreach ($cacheTag as $key => $tag) {
if ($tag->id == $id) {
unset($cacheTag[$key]);
Cache::forever('tags', $cacheTag);
}
}
}
return $deleteTag->delete();
}
return false;
} catch (\Exception $e) {
return $e->getMessage();
}
}
/**
* [getTagBySlug get Detail Tag By Slug].
* @param string $slug [description]
* @return array
*/
public function getTagBySlug($slug = '')
{
try {
return $this->model::where('slug', $slug)->first();
} catch (\Exception $e) {
return $e->getMessage();
}
}
/**
* [editTag Edit Tag].
* @param array $data [data for edit Tag]
* @return array
*/
public function editTag($data)
{
try {
$tagEdit = $this->model::find($data['id']);
$update = $tagEdit->update($data);
if ($update) {
$cacheTag = Cache::get('tags', null);
if ($cacheTag) {
foreach ($cacheTag as $key => $tag) {
if ($tag->id == $data['id']) {
$cacheTag[$key] = $tagEdit;
Cache::forever('tags', $cacheTag);
}
}
}
return $tagEdit;
}
return false;
} catch (\Exception $e) {
return $e->getMessage();
}
}
}
| true |
789a84db0a2375d82c3581df792e32876ce3bee3 | PHP | prack/php-rack | /lib/prack/cascade.php | UTF-8 | 1,684 | 2.828125 | 3 | [
"MIT"
] | permissive | <?php
// TODO: Document!
# Rack::Cascade tries an request on several middleware_apps, and returns the
# first response that is not 404 (or in a list of configurable
# status codes).
class Prack_Cascade
implements Prack_I_MiddlewareApp
{
private $middleware_apps;
private $has_app;
private $catch;
// TODO: Document!
static function notFound()
{
static $not_found = null;
if ( is_null( $not_found ) )
$not_found = array( 404, array(), array() );
return $not_found;
}
// TODO: Document!
static function with( $middleware_apps, $catch = array( 404 ) )
{
return new Prack_Cascade( $middleware_apps, $catch );
}
// TODO: Document!
public function __construct( $middleware_apps, $catch = array( 404 ) )
{
$this->middleware_apps = array();
$this->has_app = array();
foreach ( $middleware_apps as $middleware_app )
$this->add( $middleware_app );
$this->catch = array();
foreach ( $catch as $status )
$this->catch[ $status ] = true;
}
// TODO: Document!
public function call( &$env )
{
$result = self::notFound();
foreach ( $this->middleware_apps as $middleware_app )
{
$result = $middleware_app->call( $env );
if ( !@$this->catch[ $result[ 0 ] ] )
break;
}
return $result;
}
// TODO: Document!
public function add( $middleware_app )
{
$this->has_app[ spl_object_hash( $middleware_app ) ] = true;
array_push( $this->middleware_apps, $middleware_app );
}
public function concat( $middleware_app ) { return $this->add( $middleware_app ); }
// TODO: Document!
public function contains( $middleware_app )
{
return @$this->has_app[ spl_object_hash( $middleware_app ) ];
}
}
| true |
4bf6cd4d16c1f9196653391c91994b6b902e1c1d | PHP | ccook5/Coombe_registration | /admin/functions.inc.php | UTF-8 | 1,375 | 2.875 | 3 | [] | no_license | <?php
/*** print a complete error page in html.
*
* @param $msg The error message as a text string
* @paran $redirect_to Specify a url to redirect to automatically.
* @param $redirect_time How long to wait before redirecting (in seconds).
*/
function error_page($msg, $redirect_to = "", $redirect_time = 0)
{
page_header($redirect_to, $redirect_time);
echo ' <div class="error">'.$msg.'</div>';
page_footer();
exit;
}
/*** print a complete warning page in html.
*
* @param $msg The warning message as a text string
* @paran $redirect_to Specify a url to redirect to automatically.
* @param $redirect_time How long to wait before redirecting (in seconds).
*/
function warning_page($msg, $redirect_to = "", $redirect_time = 0)
{
page_header($redirect_to, $redirect_time);
echo ' <div class="warning">'.$msg.'</div>';
page_footer();
exit;
}
/*** print a success_page in html.
*
* @param $msg The success message as a text string
* @paran $redirect_to Specify a url to redirect to automatically.
* @param $redirect_time How long to wait before redirecting (in seconds).
*/
function success_page($msg, $redirect_to = "", $redirect_time = 0)
{
page_header($redirect_to, $redirect_time);
echo ' <div class="success">'.$msg.'</div>';
page_footer();
exit;
}
?>
| true |
e6154f72949202d308a4fe53b3b388212fd2a6fd | PHP | zjjzjw/web_fangquan | /fangquan/core/app/Src/Brand/Domain/Model/BrandCustomProductEntity.php | UTF-8 | 1,001 | 2.640625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Src\Brand\Domain\Model;
use App\Foundation\Domain\Entity;
class BrandCustomProductEntity extends Entity
{
public $identity_key = 'id';
/**
* @var int
*/
public $id;
/**
* @var int
*/
public $brand_id;
/**
* @var int
*/
public $loupan_id;
/**
* @var int
*/
public $developer_id;
/**
* @var int
*/
public $product_name;
public function __construct()
{
}
public function toArray($is_filter_null = false)
{
return [
'id' => $this->id,
'product_name' => $this->product_name,
'brand_id' => $this->brand_id,
'developer_id' => $this->developer_id,
'loupan_id' => $this->loupan_id,
'created_at' => $this->created_at->toDateTimeString(),
'updated_at' => $this->updated_at->toDateTimeString(),
];
}
} | true |
67253c4cebd2776b1fe3f41251a639795f2469d3 | PHP | dreboard/design_patterns | /singleton/classes/SingletonChild.php | UTF-8 | 226 | 2.65625 | 3 | [] | no_license | <?php
namespace Design_Patterns\Singleton;
/**
* Class SingletonChild
* @package Design_Patterns\Singleton
*/
class SingletonChild extends Singleton {
/**
* @var $instance
*/
protected static $instance;
} | true |
6644d917384e47b9370def34be6af88b4b538573 | PHP | comeonly/rakuten_gold_ssl | /run.php | UTF-8 | 5,243 | 2.59375 | 3 | [] | no_license | #!/usr/local/bin/php
<?php
require __DIR__ . '/vendor/autoload.php';
use Touki\FTP\FTP;
use Touki\FTP\Model\Directory;
use Touki\FTP\Model\File;
use Touki\FTP\Connection\Connection;
use Touki\FTP\FTPWrapper;
use Touki\FTP\PermissionsFactory;
use Touki\FTP\FilesystemFactory;
use Touki\FTP\WindowsFilesystemFactory;
use Touki\FTP\DownloaderVoter;
use Touki\FTP\UploaderVoter;
use Touki\FTP\CreatorVoter;
use Touki\FTP\DeleterVoter;
use Touki\FTP\Manager\FTPFilesystemManager;
if ($argc < 3) {
exit("usage: php run.php <username> <password>\n");
}
$username = $argv[1];
$password = $argv[2];
$dry = (!empty($argv[3]) && $argv[3] === 'dry') ? true : false;
$connection = new Connection('ftp.rakuten.ne.jp', $username, $password, $port = 16910, $timeout = 90, $passive = true);
$connection->open();
$ftp = initFtp($connection);
if (!$ftp) {
exit("initialized false something wrong.\n");
}
echo "start convert.\n";
getFiles($ftp, '/', $dry);
exit("done.\n");
function getFiles($ftp, $path, $dry = false) {
$list = $ftp->findFiles(new Directory($path));
foreach ($list as $file) {
$filePath = $file->getRealpath();
if (preg_match('/\.html?$/', $filePath)) {
$ftp->download('/tmp/tmp.html', $file);
$target = file_get_contents('/tmp/tmp.html');
if ($dry) {
echo '##target file : ' . $filePath . "\n";
if (preg_match_all('/(?:src|href)=["\']?http:\/\/[^"\' >]+/', $target, $matches)) {
echo implode("\n", $matches[0]) . "\n";
} else {
echo "couldn't find any http links\n";
}
} else {
$target = str_replace('http://', 'https://', $target);
file_put_contents('/tmp/tmp.html', $target);
$ftp->upload(new File($filePath), '/tmp/tmp.html');
}
}
}
$list = $ftp->findDirectories(new Directory($path));
foreach ($list as $directory) {
getFiles($ftp, $directory->getRealpath());
}
}
function initFtp($connection) {
/**
* The wrapper is a simple class which wraps the base PHP ftp_* functions
* It needs a Connection instance to get the related stream
*/
$wrapper = new FTPWrapper($connection);
/**
* This factory creates Permissions models from a given permission string (rw-)
*/
$permFactory = new PermissionsFactory;
/**
* This factory creates Filesystem models from a given string, ex:
* drwxr-x--- 3 vincent vincent 4096 Jul 12 12:16 public_ftp
*
* It needs the PermissionsFactory so as to instanciate the given permissions in
* its model
*/
$fsFactory = new FilesystemFactory($permFactory);
/**
* If your server runs on WINDOWS, you can use a Windows filesystem factory instead
*/
// $fsFactory = new WindowsFilesystemFactory;
/**
* This manager focuses on operations on remote files and directories
* It needs the FTPWrapper so as to do operations on the serveri
* It needs the FilesystemFfactory so as to create models
*/
$manager = new FTPFilesystemManager($wrapper, $fsFactory);
/**
* This is the downloader voter. It loads multiple DownloaderVotable class and
* checks which one is needed on given options
*/
$dlVoter = new DownloaderVoter;
/**
* Loads up default FTP Downloaders
* It needs the FTPWrapper to be able to share them with the downloaders
*/
$dlVoter->addDefaultFTPDownloaders($wrapper);
/**
* This is the uploader voter. It loads multiple UploaderVotable class and
* checks which one is needed on given options
*/
$ulVoter = new UploaderVoter;
/**
* Loads up default FTP Uploaders
* It needs the FTPWrapper to be able to share them with the uploaders
*/
$ulVoter->addDefaultFTPUploaders($wrapper);
/**
* This is the creator voter. It loads multiple CreatorVotable class and
* checks which one is needed on the given options
*/
$crVoter = new CreatorVoter;
/**
* Loads up the default FTP creators.
* It needs the FTPWrapper and the FTPFilesystemManager to be able to share
* them whith the creators
*/
$crVoter->addDefaultFTPCreators($wrapper, $manager);
/**
* This is the deleter voter. It loads multiple DeleterVotable classes and
* checks which one is needed on the given options
*/
$deVoter = new DeleterVoter;
/**
* Loads up the default FTP deleters.
* It needs the FTPWrapper and the FTPFilesystemManager to be able to share
* them with the deleters
*/
$deVoter->addDefaultFTPDeleters($wrapper, $manager);
/**
* Finally creates the main FTP
* It needs the manager to do operations on files
* It needs the download voter to pick-up the right downloader on ->download
* It needs the upload voter to pick-up the right uploader on ->upload
* It needs the creator voter to pick-up the right creator on ->create
* It needs the deleter voter to pick-up the right deleter on ->delete
*/
return new FTP($manager, $dlVoter, $ulVoter, $crVoter, $deVoter);
}
?>
| true |
01ec7c4acd189b2577037c7ac9e20f3dcc4126a1 | PHP | ludoliv/projet_olympiadeSI1A12B | /BD/Classe/Heure.php | UTF-8 | 449 | 2.9375 | 3 | [] | no_license | <?php
class Heure{
private $_ID;
private $_hDeb;
private $_hFin;
public function __construct($id,$deb,$fin)
{
$this->_ID = $id;
$this->_hDeb = $deb;
$this->_hFin = $fin;
}
public function getID(){
return $this->_ID;
}
public function getDeb(){
return $this->_hDeb;
}
public function getFin(){
return $this->_hFin;
}
}
?>
| true |
4e2143388f0578bb9b41fef5f143f767e3dc4fda | PHP | douyin-tools/game_admin | /app/Admincenter/Common/function.php | UTF-8 | 1,417 | 2.515625 | 3 | [] | no_license | <?PHP
function islogin(){
$admin_sessionid = session('admin_sessionid');
if (!$admin_sessionid) {
return false;
}
$admin_auth_id = session('admin_auth_id');
if(!$admin_sessionid || !$admin_auth_id){
return 0;
}
if(session('backup_list')){//如果是还原数据库则暂时不验证
}else{
$sessioninfo = M('Adminsession')->where(['userid'=>$admin_auth_id])->find();
if(!$sessioninfo){
//return 0;
}else{
if($admin_sessionid!=$sessioninfo['sessionid']){
return -1;//别的地方登录
}
if(C('sessiontime') && NOW_TIME-$sessioninfo['time']>C('sessiontime')){
return -2;//登录超时
}
}
}
$userinfo = M('Adminmember')->where(['id'=>$admin_auth_id])->find();
$userinfo['groupname'] = M('admingroup')->where(['groupid'=>$userinfo['groupid']])->getField('groupname');
return $userinfo;
}
/**
* 格式化字节大小
* @param number $size 字节数
* @param string $delimiter 数字和单位分隔符
* @return string 格式化后的带单位的大小
* @author 麦当苗儿 <zuojiazi@vip.qq.com>
*/
function format_bytes($size, $delimiter = '') {
$units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
return round($size, 2) . $delimiter . $units[$i];
}
/**
* 生产代理推广码
* @param $id
* @return string
*/
function createAgentCode($id) {
return dechex($id + 10000000);
}
| true |
51dfdff3a2c94d1cf3fe58d2d3d2e2d51b58bf56 | PHP | lundborgm/picture-this-1 | /app/users/edit-profile.php | UTF-8 | 3,925 | 2.90625 | 3 | [
"MIT"
] | permissive | <?php
// Back-end
// Linked to in edit-profile.php (front-end)
declare(strict_types=1);
require __DIR__ . '/../autoload.php';
// In this file we edit users account email, password and biography.
$_SESSION['messages'] = [];
if (isset($_FILES['avatar'])) {
//die(var_dump($_FILES['avatar']));
// array(5) {
// ["name"]=> string(7) "hej.jpg"
// ["type"]=> string(10) "image/jpeg"
// ["tmp_name"]=> string(66) "/private/var/folders/dp/f8nxyp614sn4n6yxjy7dzcgc0000gn/T/phpjXJga1"
// ["error"]=> int(0)
// ["size"]=> int(23940) }
$avatar = $_FILES['avatar'];
$fileExtension = pathinfo($avatar['name'])['extension'];
$fileName = GUID() . '.' . $fileExtension;
$destination = __DIR__ . '/avatar/' . $fileName;
$id = $_SESSION['user']['id'];
// Only .png and .jpg files are allowed.
if (!in_array($avatar['type'], ['image/jpeg', 'image/png'])) {
$_SESSION['errors'][0] = 'The uploaded file type is not allowed. Only .jpg and .png allowed.';
redirect('/edit-profile.php');
}
// File size equal to or lower than two megabytes allowed.
// 2 Megabyte = 2097152 Bytes
if ($avatar['size'] > 2097152) {
$_SESSION['errors'][] = 'The uploaded file exceeded the filesize limit.';
redirect('/edit-profile.php');
}
move_uploaded_file($avatar['tmp_name'], $destination);
// Connection to database is made in autoload.php and saved in the variable $pdo
// Preparing SQL query to insert/update image
$statement = $pdo->prepare('UPDATE users SET avatar = :avatar WHERE id = :id');
if (!$statement) {
die(var_dump($pdo->errorInfo()));
}
// Binding parameters with variables and running the script
$statement->execute([
':avatar' => $fileName,
':id' => $id,
]);
$selectingUser = $pdo->prepare('SELECT avatar FROM users WHERE id = :id');
$selectingUser->execute([
':id' => $id,
]);
$user = $selectingUser->fetch(PDO::FETCH_ASSOC);
// Updating old session avatar to current avatar
$_SESSION['user']['avatar'] = $user['avatar'];
$_SESSION['messages'][0] = 'Image successfully uploaded!';
redirect('/edit-profile.php');
}
if (isset($_POST['first-name'], $_POST['last-name'], $_POST['biography'])) {
// die(var_dump($_POST['first-name'])); - working!!
$updatedFirstName = filter_var($_POST['first-name']);
$updatedLastName = filter_var($_POST['last-name']);
$updatedBiography = filter_var($_POST['biography']);
$id = $_SESSION['user']['id'];
// Connection to database is made in autoload.php and saved in the variable $pdo
// Preparing SQL query to update user information
$statement = $pdo->prepare('UPDATE users SET first_name = :updatedFirstName, last_name = :updatedLastName, biography = :updatedBiography WHERE id = :id');
if (!$statement) {
// PHP doesn't print SQL errors in the browser
die(var_dump($pdo->errorInfo()));
}
// Binding parameters with variables and running the script
$statement->execute([
':updatedFirstName' => $updatedFirstName,
':updatedLastName' => $updatedLastName,
':updatedBiography' => $updatedBiography,
':id' => $id
]);
// Preparing SQL query to fetch the updated user information
$statementtwo = $pdo->prepare('SELECT first_name, last_name, biography FROM users WHERE id = :id');
$statementtwo->execute([
':id' => $id
]);
$fetchNewUserInfo = $statementtwo->fetch(PDO::FETCH_ASSOC);
// View updated information in the profile page
$_SESSION['user']['first_name'] = $fetchNewUserInfo['first_name'];
$_SESSION['user']['last_name'] = $fetchNewUserInfo['last_name'];
$_SESSION['user']['biography'] = $fetchNewUserInfo['biography'];
// Confirmation message displayed on client side
$_SESSION['messages'][] = 'Profile successfully updated!';
redirect('/profile.php');
}
| true |
8ba8222e3f8b9a4c881dd6a92be2ce914f261121 | PHP | DSWD-CFMS/kce | /app/Http/Controllers/Auth/LoginController.php | UTF-8 | 2,427 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers\Auth;
include("../vendor/autoload.php");
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
/* for Socket */
use ElephantIO\Client;
use ElephantIO\Engine\SocketIO\Version2X;
/* for Socket */
use App\Users;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* @var string
*/
protected $redirectTo = '/home';
/**
* Login username to be used by the controller.
*
* @var string
*/
protected $username;
/**
* Create a new controller instance.
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
$this->username = $this->findUsername();
}
// public function Broadcast_Event($key,$data){
// // $version = new Version2X("http://172.26.158.126:3011");
// $version = new Version2X("http://localhost:3011");
// $client = new Client($version);
// $client->initialize();
// $client->emit($key, $data);
// $client->close();
// }
/**
* Get the login username to be used by the controller.
*
* @return string
*/
public function findUsername()
{
// $user = Users::where('username',$this->username)->first();
$currently_logged_user = Users::select('id','role')->where('username',$this->username)->get();
// $data = $currently_logged_user->toArray();
// $this->Broadcast_Event('Signed_In',$data);
$login = request()->input('login');
$fieldType = filter_var($login, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
request()->merge([$fieldType => $login]);
return $fieldType;
}
/**
* Get username property.
*
* @return string
*/
public function username()
{
return $this->username;
}
}
| true |
c487c7e1e259558ea6114375ab0c7554c66d8645 | PHP | MukulEd/LaravelVue | /app/Services/TodoService.php | UTF-8 | 1,623 | 2.609375 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Services;
use App\Models\TodoList;
use App\Exceptions\ServiceException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
class TodoService
{
public function storeListData(Request $request)
{
if(auth()->user()){
$data=$this->computeListData($request);
return TodoList::create($data);
}
throw new ServiceException('User Unauthorized');
}
public function editListData(Request $request)
{
if(auth()->user())
{
$data=$this->computeListData($request);
return TodoList::find($request->id)->update($data);
}
throw new ServiceException('User Unauthorized');
}
public function getUserListData()
{
if(auth()->user())
return TodoList::where('user',auth()->user()->id)->orderBy('created_at','DESC')->get();
throw new ServiceException('User Unauthorized');
}
public function getList($listId)
{
if(auth()->user())
{
return TodoList::find($listId);
}
throw new ServiceException('User Unauthorized');
}
private function computeListData($request){
$data=[];
$data['title']=$request->title;
$data['listItems']=$request->listItems;
$data['user']=auth()->user()->id;
return $data;
}
public function deleteToDoList($id)
{
$itemList=TodoList::find($id);
if(!empty($itemList))
return $itemList->delete();
throw new ServiceException('Invalid Data');
}
}
| true |
8e8e8b0441178b12f6fc1b36385122906b600928 | PHP | AmmarKust/school | /app/Http/Controllers/NewsLetterController.php | UTF-8 | 514 | 2.578125 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Newsletter;
class NewsLetterController extends Controller
{
public function store(Request $request)
{
$this->validate($request, [
'email' => 'required',
], [
'email.required' => 'Email Address is required.',
]);
$newsletter = new Newsletter();
$newsletter->email = $request->email;
$newsletter->save();
}
}
| true |
a996fb7b3e11c1066f5ea8d07831f1a5f6f91c33 | PHP | sync667/Steam-Web-API2 | /src/sync667/SteamWebApi/api/ISteamAppsAPI.php | UTF-8 | 2,652 | 2.8125 | 3 | [
"Apache-2.0"
] | permissive | <?php
namespace sync667\SteamWebApi\Api;
use sync667\SteamWebApi\Api\AbstractSteamAPI;
use sync667\SteamWebApi\Util\SteamApiUtil;
use sync667\SteamWebApi\Constants\ApiModules;
use sync667\SteamWebApi\Constants\ApiMethods;
use sync667\SteamWebApi\Config\ApiConfiguration;
use sync667\SteamWebApi\Http\HTTPMethod;
/**
* ISteamAppsAPI class handles operations relating to Steam apps.
*
* @link [https://wiki.teamfortress.com/wiki/WebAPI] [Wiki For Web API]
* @author Gokhan Akkurt
*
*/
class ISteamAppsAPI extends AbstractSteamAPI{
/**
* Gets full list of every publicly facing program in the store/library.
* @link [https://wiki.teamfortress.com/wiki/WebAPI/GetAppList] [GetAppList]
* @param $appId [Steam ID of the user]
* @param $name [relationship name]
* @return $response
*
*/
public static function getAppList($appId, $name=''){
$params = SteamApiUtil::formGETParameters(array('appid' => $appId, 'name'=> $name, 'format'=> parent::getConfiguration()->getResponseFormat()));
$module = ApiModules::ISteamApps;
$endpoint = ApiMethods::getEndpointUrl($module, 'GetAppList');
$url = SteamApiUtil::formUrl($module,$endpoint);
return parent::sendRequest(HTTPMethod::GET, $url, $params);
}
/**
* Gets all steam-compatible servers related to a IPv4 Address.
* @link [https://wiki.teamfortress.com/wiki/WebAPI/GetServersAtAddress] [GetServersAtAddress]
* @param $address [IPv4 Address]
* @return $response
*
*/
public static function getServersAtAddress($address){
$params = SteamApiUtil::formGETParameters(array('addr' => $address, 'format'=> parent::getConfiguration()->getResponseFormat()));
$module = ApiModules::ISteamApps;
$endpoint = ApiMethods::getEndpointUrl($module, 'GetServersAtAddress');
$url = SteamApiUtil::formUrl($module,$endpoint);
return parent::sendRequest(HTTPMethod::GET, $url, $params);
}
/**
* Checks if a given app version is the most current available.
* @link [https://wiki.teamfortress.com/wiki/WebAPI/UpToDateCheck] [UpToDateCheck]
* @param $appId [Application ID for the game]
* @param $version [current version]
* @return $response
*
*/
public static function upToDateCheck($appId, $version){
$params = SteamApiUtil::formGETParameters(array('appid' => $appId, 'version'=> $version, 'format'=> parent::getConfiguration()->getResponseFormat()));
$module = ApiModules::ISteamApps;
$endpoint = ApiMethods::getEndpointUrl($module, 'UpToDateCheck');
$url = SteamApiUtil::formUrl($module,$endpoint);
return parent::sendRequest(HTTPMethod::GET, $url, $params);
}
} | true |
5a242892f719bf2458660f1958d63a386f58b16d | PHP | glennfriend/ydin-ydin | /src/ThirdParty/Laravel/Console/Concerns/CsvUtility.php | UTF-8 | 4,604 | 2.921875 | 3 | [] | no_license | <?php
declare(strict_types=1);
namespace Ydin\ThirdParty\Laravel\Console\Concerns;
use Exception;
use Generator;
use League\Csv\AbstractCsv;
use League\Csv\Exception as CsvException;
use League\Csv\Reader;
use Ydin\Csv\Convert as CsvConvert;
/**
* dependency Illuminate\Console\Command
* dependency composer League\Csv
*/
trait CsvUtility
{
/**
* @param string $key
* @return mixed|null
* @throws Exception
*/
protected function getCsvConfig(string $key)
{
$config = $this->csvConfig();
if (!isset($config['csvFile']) || !$config['csvFile']) {
throw new Exception('csvConfig() -> csvFile ont found');
}
return $config[$key] ?? null;
}
/**
* NOTE: 該程式會將 string("NULL") convert to boolean(null)
*
* @return Generator
* @throws CsvException
*/
protected function generatorCsvContent(): Generator
{
$csv = $this->_getCsvReader();
$headers = $this->getCsvHeaders();
foreach ($csv->getRecords() as $row) {
// dump($row);
$row = array_combine($headers, $row);
// NOTE: custom convert
array_walk($row, function (&$value, $key) {
if ("NULL" === $value) {
$value = null;
}
});
yield $this->csvRowHook($row);
}
return;
}
/**
* @throws Exception
*/
protected function csvConfirm()
{
$this->_csvValidate();
$csvFile = $this->getCsvConfig('csvFile');
if (!$this->confirm("Import file: `{$csvFile}` ?")) {
exit;
}
}
// --------------------------------------------------------------------------------
// overwrite methods
// --------------------------------------------------------------------------------
/**
* NOTE: you can overwrite it
*
* @return array
*/
protected function csvConfig(): array
{
/*
$config = [
'csvFile' => storage_path('import-2021-07-06.csv'),
];
*/
return [];
}
/**
* NOTE: you can overwrite it
*
* @param array $row
* @return array
*/
protected function csvRowHook(array $row): array
{
/*
$row['master_key'] = $row['name'];
// NOTE: custom convert
array_walk($row, function (&$value, $key) {
if ("gender" === $key) {
if ("1" === $value) {
$value = "male";
} elseif ("0" === $value) {
$value = "male";
} else {
$value = "other";
}
}
if (in_array($key, ['price', 'money', 'twd', usd', ])) {
// $1,230 to 1230
$value = filter_var($value, FILTER_SANITIZE_NUMBER_INT);
}
});
*/
return $row;
}
/**
* NOTE: you can overwrite it
*
* @return array
* @throws CsvException
*/
protected function getCsvHeaders(): array
{
// return ['id', 'name', 'attribute', 'value'];
$csv = $this->_getCsvReader();
return CsvConvert::headerConvert($csv->getHeader());
}
// --------------------------------------------------------------------------------
// private
// --------------------------------------------------------------------------------
/**
* @throws Exception
*/
protected function _csvValidate()
{
$csvFile = $this->getCsvConfig('csvFile');
if (!file_exists($csvFile)) {
throw new Exception("import CSV file not found");
}
$mimeType = mime_content_type($csvFile);
switch ($mimeType) {
case 'text/plain':
// safe
break;
default:
throw new Exception("csv file MIME type error");
}
}
/**
* @return AbstractCsv|Reader
* @throws CsvException
*/
protected function _getCsvReader(): AbstractCsv
{
$csvFile = $this->getCsvConfig('csvFile');
$csv = Reader::createFromPath($csvFile);
$csv->setHeaderOffset(0);
return $csv;
}
}
/*
$this->csvConfirm();
// 直接使用
// foreach($this->generatorCsvContent() as $row) {}
// 整理後使用
$keyRows = [];
foreach ($this->generatorCsvContent() as $row) {
dd($row);
$key = $row['zip_code'];
$keyRows[$key] = $row;
}
// add csvConfig()
// add csvRowHook()
*/
| true |
704256e01fa467de6bd7fdadeaaa64d97e4fc34d | PHP | emiliopedrollo/hackathon2019 | /app/Support/helpers.php | UTF-8 | 1,225 | 2.921875 | 3 | [
"MIT"
] | permissive | <?php
function cpf( $base = null, $dotted = false ) {
if (strlen($base) == 9 and is_numeric($base))
{
$base = str_split($base);
} else {
$base = [];
$base[0] = rand( 0, 9 );
$base[1] = rand( 0, 9 );
$base[2] = rand( 0, 9 );
$base[3] = rand( 0, 9 );
$base[4] = rand( 0, 9 );
$base[5] = rand( 0, 9 );
$base[6] = rand( 0, 9 );
$base[7] = rand( 0, 9 );
$base[8] = rand( 0, 9 );
}
$d1 = $base[8] * 2 + $base[7] * 3 + $base[6] * 4 + $base[5] * 5 + $base[4] * 6 + $base[3] * 7 + $base[2] * 8 + $base[1] * 9 + $base[0] * 10;
$d1 = 11 - ( $d1 % 11 );
if ( $d1 >= 10 ) {
$d1 = 0;
}
$d2 = $d1 * 2 + $base[8] * 3 + $base[7] * 4 + $base[6] * 5 + $base[5] * 6 + $base[4] * 7 + $base[3] * 8 + $base[2] * 9 + $base[1] * 10 + $base[0] * 11;
$d2 = 11 - ( $d2 % 11 );
if ( $d2 >= 10 ) {
$d2 = 0;
}
if ( $dotted ) {
return $base[0] . $base[1] . $base[2] . "." . $base[3] . $base[4] . $base[5] . "." . $base[6] . $base[7] . $base[8] . "-" . $d1 . $d2;
}
return $base[0] . $base[1] . $base[2] . $base[3] . $base[4] . $base[5] . $base[6] . $base[7] . $base[8] . $d1 . $d2;
} | true |
cb4f7457aa2c0be2ba2c544bd0e43d180c2f42c8 | PHP | chunchunchundashui/invert | /application/common.php | UTF-8 | 1,734 | 2.734375 | 3 | [
"Apache-2.0"
] | permissive | <?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------
// 应用公共文件
// 拿值
// function position($data) {
// foreach ($data as $k => $v) {
// $string = implode('@', $v);
// $str = explode('@', $string);
// foreach ($str as $k1 => $v1) {
// $arr[] = array();
// $str1 = explode(':', $v1);
// foreach ($str1 as $k2 => $v2) {
// dump($v2);die;
// $arr[$str1[0]] = $v2[1];
// }
// }
// }
// return $arr;
// }
function position($data) {
foreach ($data as $k => $v) {
$string = implode('@', $v);
$str = explode('@', $string);
foreach ($str as $k1 => $v1) {
$str1 = explode(':', $v1);
$arr[$str1[0]] = $str1[1];
}
}
return $arr;
}
// 拿名称
// function position1($data) {
// foreach ($data as $k => $v) {
// $string = implode('@', $v);
// $str = explode('@', $string);
// foreach ($str as $k1 => $v1) {
// $arr = array();
// $str1[] = explode(':', $v1);
// foreach ($str1 as $k2 => $v2) {
// $arr[] = $v2[0];
// }
// }
// }
// return $arr;
// }
// 字符串截取
function subText($text, $length) {
if (mb_strlen($text, 'utf8') > $length) {
return mb_substr($text,0,$length,'utf-8').'...';
}
return $text;
}
| true |
1a45403c921af8278a04cdf0ce2d2126f0a8ee8b | PHP | coolpankaj/reminder | /mail.php | UTF-8 | 2,227 | 2.53125 | 3 | [] | no_license | <?php
session_start();
error_reporting(4);
$msg='';
if(isset($_POST["submit"]))
{
$r_mail=$_POST["r_mail"];
$subject=$_POST["sub"];
$body=$_POST["body"];
$date2=$_POST["date"];
$hour=$_POST["hr"];
$min=$_POST["min"];
function gap($date2)
{
$time = new DateTime("$date");
$date1 = $time->format('Y-n-j');
echo $date1."<br>";
echo $date2."<br>";
//$date1 = "2007-03-24";
//$date2 = "2009-06-26";
$diff = abs(strtotime($date2) - strtotime($date1));
echo $diff;
$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
printf("%d years, %d months, %d days\n", $years, $months, $days);
}
echo gap("$date2");
// $time = new DateTime("$date");
// $date = $time->format('n-j-Y');
// $diff=explode('-', $date);
// $days=$diff[0];
// $months=$diff[1];
// $year=$diff[2];
// echo "year".$year."<br>";
// echo "months".$months."<br>";
// echo "days".$days."<br>";
// echo "rmail".$r_mail."<br>";
// echo "subject".$subject."<br>";
// echo "body".$body."<br>";
// echo "date".$adate."<br>";
// echo "hour".$hour."<br>";
// echo "min".$min."<br>";
}
?>
<!--
// $msg .="Reminder<br>";
// $msg .="<b>Subject:</b> " .$subject . "<br>";
// $msg .="<b>Body:</b> " .$body . "<br>";
// $sub="Reminder";
// $from=$email;
// $to=$r_mail;
// $headers = 'MIME-Version: 1.0' . "\r\n";
// $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// $headers .= 'From:'.$email . "\r\n" .
// 'Reply-To:' . "\r\n" .
// 'X-Mailer: PHP/'.phpversion();
// if ( mail($to,$sub,$msg,$headers))
// {
// echo "<script>alert('Reminder set successfully.');</script>";
// echo "<script>window.location.href='nmail.php'</script>";
// #echo print($_SESSION['loginssid']);
// }
// else
// {
// echo "<script>alert('Unable to set reminder.');</script>";
// }
// } -->
| true |
c42031e59426b5e0a41384e591496afa8b1539bf | PHP | jcarlosj/Aquila-WordPress-Theme | /inc/classes/class-block-patterns.php | UTF-8 | 2,645 | 2.828125 | 3 | [] | no_license | <?php
/** Gutenberg: Block Patterns
* @package Aquila
*/
namespace AQUILA_THEME\Inc;
use AQUILA_THEME\Inc\Traits\Singleton;
class Block_Patterns {
use Singleton;
protected function __construct() {
// wp_die( 'Class Assets' );
// Cargamos Clases.
$this -> setup_hooks();
}
protected function setup_hooks() {
/** Actions */
add_action( 'init', [ $this, 'register_block_patterns' ] );
add_action( 'init', [ $this, 'register_block_pattern_categories' ] );
}
public function register_block_patterns() {
$block_content = $this -> get_pattern_content( 'template-parts/patterns/block-two-columns' );
register_block_pattern(
'aquila/block-image-text-button',
array(
'title' => __( 'Aquila Block: Image/Text/Button', 'aquila' ),
'description' => _x( 'Block image text and button.', 'Block pattern description', 'aquila' ),
'categories' => [ 'block' ],
'content' => $block_content
)
);
$cover_content = $this -> get_pattern_content( 'template-parts/patterns/cover' );
register_block_pattern(
'aquila/cover',
[
'title' => __( 'Aquila Cover: Image/Text/Button', 'aquila' ),
'description' => _x( 'Cover image text and button.', 'Block pattern description', 'aquila' ),
'categories' => [ 'cover' ],
'content' => $cover_content
]
);
}
public function get_pattern_content( $template_path ) {
ob_start(); // Activa el almacenamiento en búfer de la salida
get_template_part( $template_path );
$template_content = ob_get_contents(); // Devuelve contenido del búfer de salida
ob_end_clean(); // Limpiar (eliminar) el búfer de salida
return $template_content;
}
public function register_block_pattern_categories() {
$pattern_categories = [
'block' => __( 'Block', 'aquila' ),
'carousel' => __( 'Carousel', 'aquila' ),
'cover' => __( 'Cover', 'aquila' ),
];
if( ! empty( $pattern_categories ) && is_array( $pattern_categories ) ) {
foreach( $pattern_categories as $pattern_category => $pattern_category_label ) {
register_block_pattern_category(
$pattern_category,
array( 'label' => $pattern_category_label )
);
}
}
}
} | true |
780148b32aa7a9fbbe91d97ea53161d2d84825cb | PHP | benjaminkott/ext-iconset-bootstrap | /Classes/Icons/IconProvider.php | UTF-8 | 1,855 | 2.515625 | 3 | [] | no_license | <?php
declare(strict_types = 1);
/*
* This file is part of the package bk2k/iconset-bootstrap.
*
* For the full copyright and license information, please read the
* LICENSE file that was distributed with this source code.
*/
namespace BK2K\IconsetBootstrap\Icons;
use BK2K\BootstrapPackage\Icons\IconList;
use BK2K\BootstrapPackage\Icons\IconProviderInterface;
use BK2K\BootstrapPackage\Icons\SvgIcon;
use TYPO3\CMS\Core\Utility\GeneralUtility;
class IconProvider implements IconProviderInterface
{
public function getIdentifier(): string
{
return 'iconset_bootstrap';
}
public function getName(): string
{
return 'Bootstrap';
}
public function supports(string $identifier): bool
{
return 'iconset_bootstrap' === $identifier;
}
public function getIconList(): IconList
{
$icons = new IconList();
$directory = 'EXT:iconset_bootstrap/Resources/Public/Icons/Bootstrap/';
$path = GeneralUtility::getFileAbsFileName($directory);
$files = iterator_to_array(new \FilesystemIterator($path, \FilesystemIterator::KEY_AS_PATHNAME));
ksort($files);
foreach ($files as $fileinfo) {
if ($fileinfo instanceof \SplFileInfo
&& $fileinfo->isFile()
&& strtolower($fileinfo->getExtension()) === 'svg'
) {
$icons->addIcon(
(new SvgIcon())
->setSrc($directory . $fileinfo->getFilename())
->setIdentifier($fileinfo->getBasename('.' . $fileinfo->getExtension()))
->setName($fileinfo->getBasename('.' . $fileinfo->getExtension()))
->setPreviewImage($directory . $fileinfo->getFilename())
);
}
}
return $icons;
}
}
| true |
cb95aec74ae51fca22ac2a7d4a592f73caa5e4ab | PHP | sarrouuna/ranimjeux | /app/View/Factures/imprimerachat11.ctp | UTF-8 | 10,541 | 2.640625 | 3 | [] | no_license | <?php
if ($pointdeventeachat != 0) {
$pontdevente = ClassRegistry::init('Pointdevente')->find('first',array('conditions'=>array('Pointdevente.id'=>$pointdeventeachat)));
$soc = ClassRegistry::init('Societe')->find('first',array('conditions'=>array('Societe.id'=>$pontdevente['Pointdevente']['societe_id'])));
}else{
$soc = ClassRegistry::init('Societe')->find('first');
}
$m="";
if ($date1 != "__/__/____" && $date1 != "1970-01-01" && $date2 != "__/__/____" && $date2 != "1970-01-01") {
$date1 = date('d/m/Y', strtotime(str_replace('-', '/', @$date1)));
$date2 = date('d/m/Y', strtotime(str_replace('-', '/',@$date2)));
$m = ' du ' . $date1 . ' au ' . $date2;
}
if ($datedec1 != "__/__/____" && $datedec1 != "1970-01-01" && $datedec2 != "__/__/____" && $datedec2 != "1970-01-01") {
$datedec1 = date('d/m/Y', strtotime(str_replace('-', '/', @$datedec1)));
$datedec2 = date('d/m/Y', strtotime(str_replace('-', '/',@$datedec2)));
$m = ' du ' . $datedec1 . ' au ' . $datedec2;
}
$w = 0;
if (count($tvas) != 0) {
$w = 35 / (count($tvas) * 2);
}
//debug($w);die;
ob_start();
?>
<table style=" width: 100%; ">
<tr>
<td style=" width: 30%;" align="left" >
<strong ><h1><?php echo $soc['Societe']['nom']; ?></h1></strong>
</td>
<td style=" width: 70%;">
<table style=" width: 100%;font-size: 1.5mm;">
<tr>
<br>
<td height="35px" align="right" ><h3>Liste des factures achat <?php echo @$m; ?></h3></td>
</tr>
</table>
</td>
</tr>
<br>
<tr>
<td align="left" width="55%" ><?php echo $soc['Societe']['adresse']; ?></td>
<td align="left" width="45%" ><strong>Tél : </strong><?php echo $soc['Societe']['tel']; ?></td>
</tr>
<tr>
<td align="left" width="55%" ><strong>TVA :</strong><?php echo $soc['Societe']['codetva']; ?></td>
<td align="left" width="45%" ><strong>Fax :</strong><?php echo $soc['Societe']['fax']; ?></td>
</tr>
<tr>
<td align="left" width="55%" ><strong>R.C :</strong><?php echo $soc['Societe']['rc']; ?></td>
<td align="left" width="45%" ><strong>Site web : </strong><?php echo $soc['Societe']['site']; ?></td>
</tr>
</table>
<br><br><br>
<table align="center" cellpadding="0" cellspacing="0" style=" width: 100%; font-size: 3mm;" border="1">
<tr align="center">
<td bgcolor="#CCCCCC" style=" width: 8%;" align="center" ><strong>N° FACT</strong></td>
<td bgcolor="#CCCCCC" style=" width: 5%;" align="center" ><strong>Date</strong></td>
<td bgcolor="#CCCCCC" style=" width: 5%;" align="center" ><strong>Code Frs</strong></td>
<td bgcolor="#CCCCCC" style=" width: 18%;" align="center" ><strong>Nom_Prenom</strong></td>
<td bgcolor="#CCCCCC" style=" width: 7%;" align="center" ><strong>Piece Frs</strong></td>
<td bgcolor="#CCCCCC" style=" width: 5%;" align="center" ><strong>Base 0%</strong></td>
<?php foreach ($tvas as $t) { //debug($t);die; ?>
<td bgcolor="#CCCCCC" style=" width: <?php echo $w; ?>%;" align="center" ><strong>Base <?php echo intval(floatval($t['Tva']['name'])); ?>%</strong></td>
<td bgcolor="#CCCCCC" style=" width: <?php echo $w; ?>%;" align="center" ><strong>TVA <?php echo intval(floatval($t['Tva']['name'])); ?>%</strong></td>
<?php } ?>
<td bgcolor="#CCCCCC" style=" width: 5%;" align="center" ><strong>Timbre</strong></td>
<td bgcolor="#CCCCCC" style=" width: 10%;" align="center" ><strong>Net a payer</strong></td>
</tr>
<?php
$i = 0;
$total = 0;
$totht = 0;
$totnetapayer = 0;
$tottimbre = 0;
$totbase6 = 0;
$totbase12 = 0;
$totbase18 = 0;
$tottva6 = 0;
$tottva12 = 0;
$tottva18 = 0;
$objfactavoir = ClassRegistry::init('Lignefacture');
$ccp = 0;
$listvaall = array();
$totfactzero = 0;
$nbpage = 0;
//debug($tablignefactures);die;
$tf=array();
foreach ($tvas as $t) {
$tf[intval(floatval($t['Tva']['name']))]['montant'] = 0;
$tf[intval(floatval($t['Tva']['name']))]['base'] = 0;
$tf[intval(floatval($t['Tva']['name']))]['nom'] = intval(floatval($t['Tva']['name']));
}
//debug($tf);die;
if ($tablignefactures != array()) {
foreach ($tablignefactures as $br) {
$total = $total + $br['totalttc'];
$base6 = '';
$base12 = '';
$base18 = '';
$tva6 = '';
$tva12 = '';
$tva18 = '';
$lignefact = array();
$lignefactavoir = array();
$listva = array();
$p = 0;
$f = '';
foreach ($tvas as $t) { //debug($t);die;
$tv = $t['Tva']['name'];
$lignefactavoirzero = $objfactavoir->find('all', array('fields' => array('SUM(Lignefacture.totalht*(1+(COALESCE(Lignefacture.fodec,0)/100))) as mtva', 'Lignefacture.tva'), 'conditions' => (array('Lignefacture.facture_id' => $br['id_piece'], 'Lignefacture.tva' => 0)), 'recursive' => -1));
if ($lignefactavoirzero[0][0]['mtva'] != NULL) {
$f = $lignefactavoirzero[0][0]['mtva'];
}
$lignefactavoir = $objfactavoir->find('all', array('fields' => array('SUM(Lignefacture.totalht*(1+(COALESCE(Lignefacture.fodec,0)/100))) as mtva','SUM(Lignefacture.totalht*(1+(COALESCE(Lignefacture.fodec,0)/100))) as base'), 'conditions' => (array('Lignefacture.tva' => $tv, 'Lignefacture.facture_id' => $br['id_piece'])), 'recursive' => -1));
//debug($br['id_piece']);die;
if ($lignefactavoir[0][0]['mtva'] != NULL) {
$tvmnt = floatval($lignefactavoir[0][0]['mtva']) * floatval($tv) / 100;
//debug($fact);die;
$listva[$p]['nom'] = 'Base ' . intval(floatval($t['Tva']['name'])) . '%';
$listva[$p]['mtva'] = sprintf("%.3f", $tvmnt);
$listva[$p]['base'] = sprintf("%.3f", $lignefactavoir[0][0]['base']);
$listva[$p]['tva'] = intval(floatval($t['Tva']['name']));
$p++;
$listvaall[$ccp]['nom'] = 'Base ' . intval(floatval($t['Tva']['name'])) . '%';
$listvaall[$ccp]['mtva'] = sprintf("%.3f", $tvmnt);
$listvaall[$ccp]['base'] = sprintf("%.3f", $lignefactavoir[0][0]['base']);
$listvaall[$ccp]['tva'] = intval(floatval($t['Tva']['name']));
$ccp++;
} else {
$listva[$p]['nom'] = 'Base ' . intval(floatval($t['Tva']['name'])) . '%';
$listva[$p]['mtva'] = 0;
$listva[$p]['base'] = 0;
$listva[$p]['tva'] = intval(floatval($t['Tva']['name']));
$p++;
$listvaall[$ccp]['nom'] = 'Base ' . intval(floatval($t['Tva']['name'])) . '%';
$listvaall[$ccp]['mtva'] = 0;
$listvaall[$ccp]['base'] = 0;
$listvaall[$ccp]['tva'] = intval(floatval($t['Tva']['name']));
$ccp++;
}
}
// debug($listva);
// die;
//debug($br);die;
$totnetapayer = $totnetapayer + $br['totalttc'];
$tottimbre = $tottimbre + $br['timbre'];
$num=$br['numero'];
//if($br['numerofrs']!=NULL){
// $num=$br['numerofrs'];
//}
?>
<tr bgcolor="#FFFFFF" align="center">
<td align="center" heigth="30px" ><?php echo $num; ?></td>
<td align="center" ><?php echo date("d/m/y", strtotime(str_replace('-', '/', $br['date']))); ?></td>
<td align="center" ><?php echo $br['code']; ?></td>
<td align="left" ><?php echo substr($br['Fournisseur'],0,30); ?></td>
<td align="left" ><?php echo $br['numerofrs']; ?></td>
<td align="right" ><?php echo $f; ?></td>
<?php foreach ($listva as $v) { //debug($v); die; ?>
<td align="right" ><?php echo $v['base']; ?></td>
<td align="right" ><?php echo $v['mtva']; ?></td>
<?php } ?>
<td align="right" ><?php echo $br['timbre']; ?></td>
<td align="right" ><?php echo $br['totalttc']; ?></td>
</tr>
<?php
$totfactzero = floatval($totfactzero) + floatval($f);
}
} else {
foreach ($tvas as $t) {
$listvaall[$ccp]['nom'] = 'Base ' . intval(floatval($t['Tva']['name'])) . '%';
$listvaall[$ccp]['mtva'] = 0;
$listvaall[$ccp]['base'] = 0;
$listvaall[$ccp]['tva'] = intval(floatval($t['Tva']['name']));
$ccp++;
}
}
//$tf = array(); //debug($listvaall);die;
foreach ($listvaall as $l) {
$tf[$l['tva']]['montant'] = $tf[$l['tva']]['montant'] + $l['mtva'];
$tf[$l['tva']]['base'] = $tf[$l['tva']]['base'] + $l['base'];
$tf[$l['tva']]['nom'] = $l['nom'];
}
?>
<tr align="center">
<td bgcolor="#CCCCCC" colspan="5" nobr="nobr" align="right" >Total</td>
<td bgcolor="#CCCCCC" width="5%" align="right" ><?php echo sprintf("%.3f", $totfactzero); ?></td>
<?php foreach ($tf as $y) {//debug($y);die; ?>
<td bgcolor="#CCCCCC" width="<?php echo $w; ?>%" align="right" ><?php echo sprintf("%.3f", $y['base']); ?></td>
<td bgcolor="#CCCCCC" width="<?php echo $w; ?>%" align="right" ><?php echo sprintf("%.3f", $y['montant']); ?></td>
<?php } ?>
<td bgcolor="#CCCCCC" width="5%" align="right" ><?php echo sprintf("%.3f", $tottimbre); ?></td>
<td bgcolor="#CCCCCC" width="10%" align="right" ><?php echo sprintf("%.3f", $totnetapayer); ?></td>
</tr>
</table>
<?php //die;
//die;
$content = ob_get_clean();
// convert in PDF
//require_once(dirname(__FILE__).'/../html2pdf.class.php');
//require_once('../Vendor/html2pdf.class.php');
//require_once('html2pdf/html2pdf.class.php');
//APP::import("Vendor", "html2pdf");
APP::import("Vendor", "html2pdf/html2pdf");
try {
$html2pdf = new HTML2PDF('L', 'A4', 'fr');
$html2pdf->pdf->SetDisplayMode('fullpage');
$html2pdf->writeHTML($content);
$html2pdf->Output('Listefactureachat.pdf');
} catch (HTML2PDF_exception $e) {
echo $e;
exit;
} | true |
2081eb0536ece459e10234fe4b9e58372ef09aa5 | PHP | hajime-matsumoto/seaf | /lib/Base/Event/interface/ObservableIF.php | UTF-8 | 464 | 2.84375 | 3 | [] | no_license | <?php // vim: set ft=php ts=4 sts=4 sw=4 et:
/**
* Seaf Project
*/
namespace Seaf\Base\Event;
/**
* Eventオブザーブできるオブジェクト
*/
interface ObservableIF extends ObserverIF
{
public function addObserver(ObserverIF $observer);
public function fireEvent($type, $args = []);
public function once($type, callable $callback);
public function on($type, callable $callback);
public function off($type, callable $callback);
}
| true |
2e32b5d00eddeb43208b1d57cda826884b45bfb1 | PHP | techart/object | /src/Object/Wrapper.php | UTF-8 | 4,637 | 3.109375 | 3 | [] | no_license | <?php
namespace Techart\Object;
/**
* Враппер над объектом
*
* @package Object
*/
class Wrapper
implements \Techart\Core\PropertyAccessInterface, \Techart\Core\CallInterface
{
/**
* Расширяемый объект
*/
protected $object;
/**
* массив атрибутов, с помощью которых и происходит расширение
*
* @var array
*/
protected $attrs = array();
/**
* Конструктор
*
* @param object $object
* @param array $attrs
*
* @throw \Techart\Core\InvalidArgumentValueException Если параметры не соответствуют указанным типам
*/
public function __construct($object, array $attrs)
{
if (!(is_object($object))) {
throw new \Techart\Core\InvalidArgumentValueException('object', 'Must be object');
}
$this->object = $object;
$this->attrs = $attrs;
}
/**
* Доступ на чтение.
*
* Может быть либо именем свойства, либо ключом массива,
* либо специальным значением:
* - '__object' - вернет объект, переданный в конструкторе,
* - '__attrs' - вернет массив, переданный в конструкторе.
*
* @param string $property Имя свойства
*
* @return mixed
*/
public function __get($property)
{
switch ($property) {
case '__object':
return $this->object;
case '__attrs':
return $this->attrs;
default:
return array_key_exists($property, $this->attrs) ?
$this->attrs[$property] :
(
(property_exists($this->object, $property)) ?
$this->object->$property :
null
);
}
}
/**
* Доступ на запись.
*
* Сначала обращение идет к массиву расширения, затем к самому объекту
*
* @param string $property Имя свойства
* @param mixed $value
*
* @throws \Techart\Core\ReadOnlyObjectException Если $property имеет значение '__object' или '__attrs'
*
* @return self
*/
public function __set($property, $value)
{
if ($property == '__object' || $property == '__attrs') {
throw new \Techart\Core\ReadOnlyObjectException($this);
}
if (array_key_exists($property, $this->attrs)) {
$this->attrs[$property] = $value;
} else {
$this->object->$property = $value;
}
return $this;
}
/**
* Проверяет установленно ли свойство объекта
*
* @param string $property Имя свойства
*
* @return boolean
*/
public function __isset($property)
{
return isset($this->attrs[$property]) || isset($this->object->$property);
}
/**
* Удаление свойства.
*
* @param string $property Имя свойства
*
* @throws \Techart\Core\ReadOnlyObjectException Если $property имеет значение '__object' или '__attrs'
*
* @return self
*/
public function __unset($property)
{
if ($property == '__object' || $property == '__attrs') {
throw new \Techart\Core\ReadOnlyObjectException($this);
}
if (array_key_exists($property, $this->attrs)) {
unset($this->attrs[$property]);
} else {
if (property_exists($this->object, $property)) {
unset($this->object->$property);
}
}
// else
// throw new Core_MissingPropertyException($property);
return $this;
}
/**
* Вызов метода
*
* Если в расширении есть callback, то используем его, иначе пробрасываем вызов в искомый объект
*
* @param string $method
* @param array $args
*/
public function __call($method, $args)
{
if (\Techart\Core\Types::is_callable($c = $this->__get($method))) {
return call_user_func_array($c, $args);
}
return call_user_func_array(array($this->object, $method), $args);
}
}
| true |
4bd06609834ff1ddd8ce1ea1385d56baa7ac3edc | PHP | xeoscript/phorms | /tests/FieldTest.php | UTF-8 | 1,380 | 2.765625 | 3 | [
"MIT"
] | permissive | <?php
abstract class FieldTest extends PHPUnit_Framework_TestCase {
protected $field = null;
protected $defaults = array();
public $require = array('validators' => array('required'));
/**
* @return array ($input, $result, [$constructor_args])
*/
abstract function validation_data();
function getField($args, $input) {
// use field defaults
if( $args === null ) $args = $this->defaults;
// every field has label as its first arg
array_unshift($args, 'My Field');
$rc = new ReflectionClass($this->field);
$field = $rc->newInstanceArgs($args); /** @var Phorm_Field */
$field->set_value($input);
return $field;
}
/**
* @dataProvider validation_data
* @param string $input
* @param mixed $result
* @param array $args
*/
function testInputs($input, $result, $args=null) {
$field = $this->getField($args, $input);
if($field->is_valid()) {
$this->assertSame($result, $field->get_value());
} else {
$this->assertEquals($result, $field->errors(false));
}
}
/**
* @return array ($input, $html, [$constructor_args])
*/
abstract function html_data();
/**
* @dataProvider html_data
* @param string $input
* @param string $html
* @param array $args
*/
function testHTML($input, $html, $args=null) {
$field = $this->getField($args, $input);
$this->assertEquals($html, $field->html());
}
} | true |
7aaea8b752bdfdffdb33d160c3c8e5ac51166a50 | PHP | alexgl/tripal | /base/tripal_core/jobs.php | UTF-8 | 14,485 | 2.515625 | 3 | [] | no_license | <?php
/**
* @defgroup tripal_jobs_api Core Module Jobs API
* @{
* Tripal offers a job management subsystem for managing tasks that may require an extended period of time for
* completion. Drupal uses a UNIX-based cron job to handle tasks such as checking the availability of updates,
* indexing new nodes for searching, etc. Drupal's cron uses the web interface for launching these tasks, however,
* Tripal provides several administrative tasks that may time out and not complete due to limitations of the web
* server. Examples including syncing of a large number of features between chado and Drupal. To circumvent this,
* as well as provide more fine-grained control and monitoring, Tripal uses a jobs management sub-system built into
* the Tripal Core module. It is anticipated that this functionality will be used for managing analysis jobs provided by
* future tools, with eventual support for distributed computing.
*
* The Tripal jobs management system allows administrators to submit tasks to be performed which can then be
* launched through a UNIX command-line PHP script or cron job. This command-line script can be added to a cron
* entry along-side the Drupal cron entry for automatic, regular launching of Tripal jobs. The order of execution of
* waiting jobs is determined first by priority and second by the order the jobs were entered.
*
* The API functions described below provide a programmatic interface for adding, checking and viewing jobs.
* @}
* @ingroup tripal_api
*/
/**
* Adds a job to the Tripal Jbo queue
*
* @param $job_name
* The human readable name for the job
* @param $modulename
* The name of the module adding the job
* @param $callback
* The name of a function to be called when the job is executed
* @param $arguments
* An array of arguements to be passed on to the callback
* @param $uid
* The uid of the user adding the job
* @param $priority
* The priority at which to run the job where the highest priority is 10 and the lowest priority
* is 1. The default priority is 10.
*
* @return
* The job_id of the registered job
*
* @ingroup tripal_jobs_api
*/
function tripal_add_job ($job_name,$modulename,$callback,$arguments,$uid,$priority = 10){
# convert the arguments into a string for storage in the database
$args = implode("::",$arguments);
$record = new stdClass();
$record->job_name = $job_name;
$record->modulename = $modulename;
$record->callback = $callback;
$record->status = 'Waiting';
$record->submit_date = time();
$record->uid = $uid;
$record->priority = $priority; # the lower the number the higher the priority
if($args){
$record->arguments = $args;
}
if(drupal_write_record('tripal_jobs',$record)){
$jobs_url = url("admin/tripal/tripal_jobs");
drupal_set_message(t("Job '$job_name' submitted. Check the <a href='$jobs_url'>jobs page</a> for status"));
} else {
drupal_set_message("Failed to add job $job_name.");
}
return $record->job_id;
}
/**
* An internal function for setting the progress for a current job
*
* @param $job_id
* The job_id to set the progress for
* @param $percentage
* The progress to set the job to
*
* @return
* True on success and False otherwise
*
* @ingroup tripal_core
*/
function tripal_job_set_progress($job_id,$percentage){
if(preg_match("/^(\d+|100)$/",$percentage)){
$record = new stdClass();
$record->job_id = $job_id;
$record->progress = $percentage;
if(drupal_write_record('tripal_jobs',$record,'job_id')){
return 1;
}
}
return 0;
}
/**
* Returns a list of jobs associated with the given module
*
* @param $modulename
* The module to return a list of jobs for
*
* @return
* An array of objects where each object describes a tripal job
*
* @ingroup tripal_jobs_api
*/
function tripal_get_module_active_jobs ($modulename){
$sql = "SELECT * FROM {tripal_jobs} TJ ".
"WHERE TJ.end_time IS NULL and TJ.modulename = '%s' ";
return db_fetch_object(db_query($sql,$modulename));
}
/**
* Returns the Tripal Job Report
*
* @return
* The HTML to be rendered which describes the job report
*
* @ingroup tripal_core
*/
function tripal_jobs_report () {
//$jobs = db_query("SELECT * FROM {tripal_jobs} ORDER BY job_id DESC");
$jobs = pager_query(
"SELECT TJ.job_id,TJ.uid,TJ.job_name,TJ.modulename,TJ.progress,
TJ.status as job_status, TJ,submit_date,TJ.start_time,
TJ.end_time,TJ.priority,U.name as username
FROM {tripal_jobs} TJ
INNER JOIN {users} U on TJ.uid = U.uid
ORDER BY job_id DESC", 10,0,"SELECT count(*) FROM {tripal_jobs}");
// create a table with each row containig stats for
// an individual job in the results set.
$output .= "Waiting jobs are executed first by priority level (the lower the ".
"number the higher the priority) and second by the order they ".
"were entered";
$output .= "<table class=\"tripal-table tripal-table-horz\">".
" <tr>".
" <th>Job ID</th>".
" <th>User</th>".
" <th>Job Name</th>".
" <th nowrap>Dates</th>".
" <th>Priority</th>".
" <th>Progress</th>".
" <th>Status</th>".
" <th>Actions</th>".
" </tr>";
$i = 0;
while($job = db_fetch_object($jobs)){
$class = 'tripal-table-odd-row';
if($i % 2 == 0 ){
$class = 'tripal-table-even-row';
}
$submit = tripal_jobs_get_submit_date($job);
$start = tripal_jobs_get_start_time($job);
$end = tripal_jobs_get_end_time($job);
$cancel_link = '';
if($job->start_time == 0 and $job->end_time == 0){
$cancel_link = "<a href=\"".url("admin/tripal/tripal_jobs/cancel/".$job->job_id)."\">Cancel</a><br>";
}
$rerun_link = "<a href=\"".url("admin/tripal/tripal_jobs/rerun/".$job->job_id)."\">Re-run</a><br>";
$view_link ="<a href=\"".url("admin/tripal/tripal_jobs/view/".$job->job_id)."\">View</a>";
$output .= " <tr class=\"$class\">";
$output .= " <td>$job->job_id</td>".
" <td>$job->username</td>".
" <td>$job->job_name</td>".
" <td nowrap>Submit Date: $submit".
" <br>Start Time: $start".
" <br>End Time: $end</td>".
" <td>$job->priority</td>".
" <td>$job->progress%</td>".
" <td>$job->job_status</td>".
" <td>$cancel_link $rerun_link $view_link</td>".
" </tr>";
$i++;
}
$output .= "</table>";
$output .= theme_pager();
return $output;
}
/**
* Returns the start time for a given job
*
* @param $job
* An object describing the job
*
* @return
* The start time of the job if it was already run and either "Cancelled" or "Not Yet Started" otherwise
*
* @ingroup tripal_jobs_api
*/
function tripal_jobs_get_start_time($job){
if($job->start_time > 0){
$start = format_date($job->start_time);
} else {
if(strcmp($job->job_status,'Cancelled')==0){
$start = 'Cancelled';
} else {
$start = 'Not Yet Started';
}
}
return $start;
}
/**
* Returns the end time for a given job
*
* @param $job
* An object describing the job
*
* @return
* The end time of the job if it was already run and empty otherwise
*
* @ingroup tripal_jobs_api
*/
function tripal_jobs_get_end_time($job){
if($job->end_time > 0){
$end = format_date($job->end_time);
} else {
$end = '';
}
return $end;
}
/**
* Returns the date the job was added to the queue
*
* @param $job
* An object describing the job
*
* @return
* The date teh job was submitted
*
* @ingroup tripal_jobs_api
*/
function tripal_jobs_get_submit_date($job){
return format_date($job->submit_date);
}
/**
* A function used to manually launch all queued tripal jobs
*
* @param $do_parallel
* A boolean indicating whether jobs should be attempted to run in parallel
*
* @ingroup tripal_jobs_api
*/
function tripal_jobs_launch ($do_parallel = 0){
// first check if any jobs are currently running
// if they are, don't continue, we don't want to have
// more than one job script running at a time
if(!$do_parallel and tripal_jobs_check_running()){
return;
}
// get all jobs that have not started and order them such that
// they are processed in a FIFO manner.
$sql = "SELECT * FROM {tripal_jobs} TJ ".
"WHERE TJ.start_time IS NULL and TJ.end_time IS NULL ".
"ORDER BY priority ASC,job_id ASC";
$job_res = db_query($sql);
while($job = db_fetch_object($job_res)){
// set the start time for this job
$record = new stdClass();
$record->job_id = $job->job_id;
$record->start_time = time();
$record->status = 'Running';
$record->pid = getmypid();
drupal_write_record('tripal_jobs',$record,'job_id');
// call the function provided in the callback column.
// Add the job_id as the last item in the list of arguments. All
// callback functions should support this argument.
$callback = $job->callback;
$args = split("::",$job->arguments);
$args[] = $job->job_id;
print "Calling: $callback(" . implode(", ",$args) . ")\n";
call_user_func_array($callback,$args);
// set the end time for this job
$record->end_time = time();
$record->status = 'Completed';
$record->progress = '100';
drupal_write_record('tripal_jobs',$record,'job_id');
// send an email to the user advising that the job has finished
}
}
/**
* Returns a list of running tripal jobs
*
* @return
* and array of objects where each object describes a running job or false if no jobs are running
*
* @ingroup tripal_jobs_api
*/
function tripal_jobs_check_running () {
// iterate through each job that has not ended
// and see if it is still running. If it is not
// running but does not have an end_time then
// set the end time and set the status to 'Error'
$sql = "SELECT * FROM {tripal_jobs} TJ ".
"WHERE TJ.end_time IS NULL and NOT TJ.start_time IS NULL ";
$jobs = db_query($sql);
while($job = db_fetch_object($jobs)){
if($job->pid and posix_kill($job->pid, 0)) {
// the job is still running so let it go
// we return 1 to indicate that a job is running
print "Job is still running (pid $job->pid)\n";
return 1;
} else {
// the job is not running so terminate it
$record = new stdClass();
$record->job_id = $job->job_id;
$record->end_time = time();
$record->status = 'Error';
$record->error_msg = 'Job has terminated unexpectedly.';
drupal_write_record('tripal_jobs',$record,'job_id');
}
}
// return 1 to indicate that no jobs are currently running.
return 0;
}
/**
* Returns the HTML code to display a given job
*
* @param $job_id
* The job_id of the job to display
*
* @return
* The HTML describing the indicated job
* @ingroup tripal_core
*/
function tripal_jobs_view ($job_id){
return theme('tripal_core_job_view',$job_id);
}
/**
* Registers variables for the tripal_core_job_view themeing function
*
* @param $variables
* An array containing all variables supplied to this template
*
* @ingroup tripal_core
*/
function tripal_core_preprocess_tripal_core_job_view (&$variables){
// get the job record
$job_id = $variables['job_id'];
$sql =
"SELECT TJ.job_id,TJ.uid,TJ.job_name,TJ.modulename,TJ.progress,
TJ.status as job_status, TJ,submit_date,TJ.start_time,
TJ.end_time,TJ.priority,U.name as username,TJ.arguments,
TJ.callback,TJ.error_msg,TJ.pid
FROM {tripal_jobs} TJ
INNER JOIN users U on TJ.uid = U.uid
WHERE TJ.job_id = %d";
$job = db_fetch_object(db_query($sql,$job_id));
// we do not know what the arguments are for and we want to provide a
// meaningful description to the end-user. So we use a callback function
// deinfed in the module that created the job to describe in an array
// the arguments provided. If the callback fails then just use the
// arguments as they are
$args = preg_split("/::/",$job->arguments);
$arg_hook = $job->modulename."_job_describe_args";
if(is_callable($arg_hook)){
$new_args = call_user_func_array($arg_hook,array($job->callback,$args));
if(is_array($new_args) and count($new_args)){
$job->arguments = $new_args;
} else {
$job->arguments = $args;
}
} else {
$job->arguments = $args;
}
// make our start and end times more legible
$job->submit_date = tripal_jobs_get_submit_date($job);
$job->start_time = tripal_jobs_get_start_time($job);
$job->end_time = tripal_jobs_get_end_time($job);
// add the job to the variables that get exported to the template
$variables['job'] = $job;
}
/**
* Set a job to be re-ran (ie: add it back into the job queue)
*
* @param $job_id
* The job_id of the job to be re-ran
*
* @ingroup tripal_jobs_api
*/
function tripal_jobs_rerun ($job_id){
global $user;
$sql = "select * from {tripal_jobs} where job_id = %d";
$job = db_fetch_object(db_query($sql,$job_id));
$args = explode("::",$job->arguments);
tripal_add_job ($job->job_name,$job->modulename,$job->callback,$args,$user->uid,
$job->priority);
drupal_goto("admin/tripal/tripal_jobs");
}
/**
* Cancel a Tripal Job currently waiting in the job queue
*
* @param $job_id
* The job_id of the job to be cancelled
*
* @ingroup tripal_jobs_api
*/
function tripal_jobs_cancel ($job_id){
$sql = "select * from {tripal_jobs} where job_id = %d";
$job = db_fetch_object(db_query($sql,$job_id));
// set the end time for this job
if($job->start_time == 0){
$record = new stdClass();
$record->job_id = $job->job_id;
$record->end_time = time();
$record->status = 'Cancelled';
$record->progress = '0';
drupal_write_record('tripal_jobs',$record,'job_id');
drupal_set_message("Job #$job_id cancelled");
} else {
drupal_set_message("Job #$job_id cannot be cancelled. It is in progress or has finished.");
}
drupal_goto("admin/tripal/tripal_jobs");
}
| true |
40aff6e2a9705cc2bb56cf6f8d4adccec8c0393d | PHP | EdsonDiegoQuispeRodriguez/Semana13 | /index.php | UTF-8 | 647 | 3.9375 | 4 | [] | no_license | <?php
#sin parámetro
function coste_hotel1(){
return 90;
}
#con parametro
function coste_hotel2($numNoches){
$resp = $numNoches*90;
echo $resp;
}
#con retorno
function coste_hotel3($numNoches){
$resp = $numNoches*90;
return $resp;
}
#llamado de funciones
$numeroNoches=4;
echo "Sin parametro <br>";
$respuesta = (coste_hotel1()*$numeroNoches);
echo $respuesta;
echo "<br><br>";
echo "Con parametro <br>";
coste_hotel2($numeroNoches);
echo "<br><br>";
echo "Con retorno <br>";
echo coste_hotel3($numeroNoches);
?> | true |
624b386e939683bf6fc83bf6ba3e5a2711da6b7a | PHP | aciden/genPass | /backend/src/Infrastructure/Persistence/Doctrine/Application/DoctrineApplicationRepository.php | UTF-8 | 1,411 | 2.703125 | 3 | [] | no_license | <?php
namespace Generator\Infrastructure\Persistence\Doctrine\Application;
use Doctrine\ORM\EntityRepository;
use Generator\Entity\Application\Application;
use Generator\Entity\Application\ApplicationRepositoryInterface;
use Generator\Entity\User\User;
class DoctrineApplicationRepository extends EntityRepository implements ApplicationRepositoryInterface
{
/**
* @param int $id
* @return Application
*/
public function findById(int $id): Application
{
/** @var Application $application */
$application = $this->find($id);
return $application;
}
/**
* @param User $user
* @return array|mixed
*/
public function findAllByUser(User $user)
{
$qb = $this->createQueryBuilder('application')
->where('application.active = :active')
->andWhere('application.user = :user')
->orderBy('UPPER(application.name)', 'ASC')
->setParameters([
'active' => true,
'user' => $user
])
->getQuery();
return $qb->getResult();
}
/**
* @param Application $application
* @throws \Doctrine\ORM\ORMException
* @throws \Doctrine\ORM\OptimisticLockException
*/
public function save(Application $application): void
{
$this->_em->persist($application);
$this->_em->flush();
}
} | true |
ab7cb86af67c76b2235a900c3ccd0e74cf7d32a0 | PHP | wecodedoctor/CodeDoctorFlash | /CodedoctorFlashCore/RegisterPostType/AbstractRegisterPostType.php | UTF-8 | 2,073 | 2.8125 | 3 | [
"Apache-2.0"
] | permissive | <?php
namespace CodedoctorWordpressFlashCore\RegisterPostType;
use CodedoctorWordpressFlashCore\Loader\AbstractClassLoader;
use function Symfony\Component\String\u;
abstract class AbstractRegisterPostType extends AbstractClassLoader
{
/**
* @var string $post_type
*/
protected string $post_type;
/**
* @var string $hook_name
*/
protected $hook_name;
public function boot()
{
$this->_autoload_posttype();
$this->_autoload_hookname();
add_action('init', array($this, 'register_post'), 0);
add_filter( $this->hook_name, [$this, 'fetchQuery'], 10, 1 );
}
/**
* Boot the post type registration
* @return void
*/
public function register_post(): void
{
$args = $this->register_post_type_args();
register_post_type($this->post_type, $args);
}
abstract public function register_post_type_args(): array;
/**
* Get post listing query hook name
* @return string
*/
public function getHookName(): string
{
return $this->hook_name;
}
/**
* Get the post type
* @return string
*/
public function getPostType(): string {
return $this->post_type;
}
/**
* Fetch the posts of the post_type
* @param array $args
* @return \WP_Query
*/
public function fetchQuery(array $args = array()): \WP_Query
{
$args = array_merge($args, [
'post_type' => $this->post_type
]);
return new \WP_Query($args);
}
/**
* Autoload post type
* @return void
*/
protected function _autoload_posttype(): void {
if(empty($this->post_type)) {
$current_class_name = get_called_class();
$this->post_type = u($current_class_name)->snake();
}
}
/**
* Autoload hookname
* @return void
*/
protected function _autoload_hookname(): void {
if($this->post_type) {
$this->hook_name = 'get_post' . $this->post_type;
}
}
} | true |
0574b65d96d721e3c8067210566716218cf7aa1c | PHP | wangkaikai12345/edu | /app/Observers/TopicObserver.php | UTF-8 | 856 | 2.625 | 3 | [] | no_license | <?php
namespace App\Observers;
use App\Models\Follow;
use App\Models\Topic;
use App\Notifications\NewTopicNotification;
class TopicObserver
{
/**
* TODO 为粉丝发送消息通知可以移入队列之中
* 话题创建
*
* @param Topic $topic
*/
public function created(Topic $topic)
{
$topic->plan()->increment('topics_count');
// 粉丝发送通知
$fans = Follow::where('user_id', $topic->user_id)->get();
if ($fans->count()) {
foreach ($fans as $fan) {
// 发送通知
$fan->follow->notify(new NewTopicNotification($topic));
}
}
}
/**
* 话题删除
*
* @param Topic $topic
*/
public function deleted(Topic $topic)
{
$topic->plan()->decrement('topics_count');
}
}
| true |
964673a60e09ce597bd5b19711071ab94d9f88b1 | PHP | jlpetelot/vineapolis | /database/seeds/RegionvinicolesTableSeeder.php | UTF-8 | 3,328 | 2.53125 | 3 | [] | no_license | <?php
use Illuminate\Database\Seeder;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
class RegionvinicolesTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
// On remet la table à zéro
DB::table('regionvinicoles')->truncate();
$date = Carbon::now();
DB::table('regionvinicoles')->insert([
[
'region' => "Alsace",
'created_at' => $date,
'updated_at' => $date
],
[
'region' => "Armagnac",
'created_at' => $date,
'updated_at' => $date
],
[
'region' => "Auvergne",
'created_at' => $date,
'updated_at' => $date
],
[
'region' => "Beaujolais",
'created_at' => $date,
'updated_at' => $date
],
[
'region' => "Bordeaux",
'created_at' => $date,
'updated_at' => $date
],
[
'region' => "Bourgogne",
'created_at' => $date,
'updated_at' => $date
],
[
'region' => "Bugey",
'created_at' => $date,
'updated_at' => $date
],
[
'region' => "Champagne",
'created_at' => $date,
'updated_at' => $date
],
[
'region' => "Cognac",
'created_at' => $date,
'updated_at' => $date
],
[
'region' => "Corse",
'created_at' => $date,
'updated_at' => $date
],
[
'region' => "Côtes du Rhône Méridional",
'created_at' => $date,
'updated_at' => $date
],
[
'region' => "Côtes du Rhône Septentrional",
'created_at' => $date,
'updated_at' => $date
],
[
'region' => "Jura",
'created_at' => $date,
'updated_at' => $date
],
[
'region' => "Languedoc-Roussillon",
'created_at' => $date,
'updated_at' => $date
],
[
'region' => "Loire",
'created_at' => $date,
'updated_at' => $date
],
[
'region' => "Lorraine",
'created_at' => $date,
'updated_at' => $date
],
[
'region' => "Provence",
'created_at' => $date,
'updated_at' => $date
],
[
'region' => "Savoie",
'created_at' => $date,
'updated_at' => $date
],
[
'region' => "Sud-Ouest",
'created_at' => $date,
'updated_at' => $date
],
]);
}
}
| true |
c391f459bd50e23bd488a0760e011277595020c4 | PHP | dockent/backend | /src/app/models/BuildImageByDockerfilePath.php | UTF-8 | 1,104 | 2.796875 | 3 | [] | no_license | <?php
namespace Dockent\models;
use Dockent\components\FormModel;
use Phalcon\Validation\Validator\Callback;
use Phalcon\Validation\Validator\PresenceOf;
/**
* Class BuildImageByDockerfilePath
* @package Dockent\models
*/
class BuildImageByDockerfilePath extends FormModel
{
/**
* @var string
*/
protected $dockerfilePath = '';
public function rules()
{
$this->validator->add('dockerfilePath', new PresenceOf());
$this->validator->add('dockerfilePath', new Callback([
'callback' => function ($data): bool {
return is_dir($data['dockerfilePath']) && file_exists($data['dockerfilePath'] . DIRECTORY_SEPARATOR . 'Dockerfile');
},
'message' => 'Dockerfile not found'
]));
}
/**
* @return string
*/
public function getDockerfilePath(): string
{
return $this->dockerfilePath;
}
/**
* @param string $dockerfilePath
*/
public function setDockerfilePath(string $dockerfilePath): void
{
$this->dockerfilePath = $dockerfilePath;
}
} | true |
18d222fbaa5e628c8f85fe4853ba9a1e71c08996 | PHP | nuriakman/acadam | /musteri.kayit.formu.php | UTF-8 | 6,023 | 2.625 | 3 | [] | no_license | <?php
// FORM Kayıt için gönderilmişse gerekli işlemi yapalım
if(isset( $_POST["adi_soyadi"] )) {
// Hata mesajları için bir dizi tanımlayalım
$MESAJ = array();
if($_POST["parola"] <> $_POST["parola2"]) {
$MESAJ[] = "Parola ve tekrarı aynı değil";
}
if($_POST["ilce_kodu"] == 0) {
$MESAJ[] = "İlçe seçimi yapılmadı";
}
// INSERT için SQL hazırlayalım...
$SQL = sprintf("INSERT INTO musteriler SET
adi_soyadi = '%s',
telefonu = '%s',
eposta = '%s',
parola = '%s',
il_kodu = '%s',
ilce_kodu = '%s',
mahalle = '%s',
cadde = '%s',
sokak = '%s',
bina_adi = '%s',
bina_no = '%s',
kapi_no = '%s',
adres_tarifi = '%s'",
$_POST["adi_soyadi"],
$_POST["telefonu"],
$_POST["eposta"],
$_POST["parola"],
$_POST["il_kodu"],
$_POST["ilce_kodu"],
$_POST["mahalle"],
$_POST["cadde"],
$_POST["sokak"],
$_POST["bina_adi"],
$_POST["bina_no"],
$_POST["kapi_no"],
$_POST["adres_tarifi"] );
// Kontrol için SQL'i yazdıralım...
// dd($SQL);
$ISLEM_SONUCU = 0; // 0: Başarısız, 1: Başarılı
if( count($MESAJ) == 0 ) {
// KAYIT için hazırız. Veritabanına ekleyelim
$rows = mysqli_query($db, $SQL);
$ISLEM_SONUCU = 1;
die("<H1>MÜŞTERİ KAYIT BAŞARILI</H1>");
// Yönlendirme???
// Yönlendirme???
// Yönlendirme???
} else {
// Hatalar var, kayıt yapamıyoruz...
$ISLEM_SONUCU = 0;
}
}
################### Şehir adlarını hazırlayalım...
################### Şehir adlarını hazırlayalım...
// Tabloda iller tekrar ediyor. Bu nedenle DISTINCT ile alıyorum ki tekil olarak gelsinler
$SQL = "SELECT DISTINCT il_kodu, il_adi FROM ref_il_ilce ORDER BY il_adi";
$rows = mysqli_query($db, $SQL);
$optionsIller = "<option value=''>*** SEÇİNİZ ***</option> \n"; // İl COMBO'muz bizi SEÇİNİZ ifadesi ile karşılasın
while($row = mysqli_fetch_assoc($rows)) { // Kayıt adedince dönelim
// Her bir il adı ve kodunun COMBO içinde olması gereken halini hazırlayalım
$optionsIller .= sprintf("<option value='%s'>%s</option> \n", $row["il_kodu"], $row["il_adi"]);
} // while
?>
<div class="row">
<div class="col-md-12 my-4 text-center">
<h2>Müşteri Kayıt Formu</h2>
<?php
if( isset($MESAJ) and count($MESAJ) > 0 ) {
echo "<div style='color:red'>";
foreach ($MESAJ as $key => $value) { echo "$value <br />"; }
echo "</div>";
}
?>
</div>
</div>
<form id="FormMusteriKayit" method="POST" autocomplete="off">
<div class="row">
<div class="col-md-6">
<div class="form-group">Adınız Soyadınız *<input required type="text" name="adi_soyadi" class="form-control" value="<?php echo $_POST["adi_soyadi"];?>" placeholder="Adınız soyadınız"></div>
<div class="form-group">Telefonunuz *<input required type="text" name="telefonu" class="form-control" value="<?php echo $_POST["telefonu"];?>" placeholder="Telefon numaranız"></div>
<div class="form-group">ePosta Adresi *<input required type="email" name="eposta" class="form-control" value="<?php echo $_POST["eposta"];?>" placeholder="ePosta adresiniz"></div>
<div class="form-group">Parolanız *<input required type="password" name="parola" class="form-control" value="" placeholder="Giriş için parolanız"></div>
<div class="form-group">Parolanız (tekrar)*<input required type="password" name="parola2" class="form-control" value="" placeholder="Parolanız (tekrar)"></div>
<div class="form-group">Şehir * <select required name="il_kodu" id="il_kodu" onchange="IlceleriDoldur()" class="form-control" >> <?php echo $optionsIller; ?> </select> </div>
<div class="form-group">İlçe * <select required name="ilce_kodu" id="ilce_kodu" class="form-control" ></select> </div>
</div>
<div class="col-md-6">
<div class="form-group">Mahalle <input type="text" name="mahalle" class="form-control" value="<?php echo $_POST["mahalle"];?>" placeholder="Mahalle adı"></div>
<div class="form-group">Cadde <input type="text" name="cadde" class="form-control" value="<?php echo $_POST["cadde"];?>" placeholder="Cadde adı"></div>
<div class="form-group">Sokak <input type="text" name="sokak" class="form-control" value="<?php echo $_POST["sokak"];?>" placeholder="Sokak adı"></div>
<div class="form-group">Bina/Site Adı <input type="text" name="bina_adi" class="form-control" value="<?php echo $_POST["bina_adi"];?>" placeholder="Bina/Site adı"></div>
<div class="form-group">Bina No <input type="text" name="bina_no" class="form-control" value="<?php echo $_POST["bina_no"];?>" placeholder="Bina No"></div>
<div class="form-group">Kapı No <input type="text" name="kapi_no" class="form-control" value="<?php echo $_POST["kapi_no"];?>" placeholder="Kapı No"></div>
<div class="form-group">Adres Tarifi <input type="text" name="adres_tarifi" class="form-control" value="<?php echo $_POST["adres_tarifi"];?>" placeholder="Adres tarifiniz"></div>
<input class="btn btn-success" type="submit" value="Kaydet !">
</div>
</div> <!-- Form Satırı -->
</form>
<script type="text/javascript">
function IlceleriDoldur() {
$.getJSON("ajax.ilceleri.hazirla.php", "il_kodu=" + $("#il_kodu").val(), function(data) {
$("#ilce_kodu option").remove();
$.each(data.ILCELER, function(key, val) {
$("#ilce_kodu").append($("<option />").val(key).text(val));
});
});
} // IlceleriDoldur()
</script>
| true |
6383d1e7c8572da3b5b0f283b5aaff2bba5355c4 | PHP | yukofksm/WebDevelopmenPortfolio_YukoDec2019 | /action/roomAction.php | UTF-8 | 3,022 | 2.703125 | 3 | [
"CC-BY-4.0",
"CC-BY-3.0"
] | permissive | <?php
require_once '../class/room.php';
$room = new Room();
session_start();
//ADD ROOM
if(isset($_POST['add'])){
$number = $_POST['number'];
$type = $_POST['type'];
$view = $_POST['view'];
$price = $_POST['price'];
$cap_adult = $_POST['cap_adult'];
$cap_kids = $_POST['cap_kids'];
$img_name = $_FILES['picture']['name'];
$room->addRoom($number,$type,$view,$price,$cap_adult,$cap_kids,$img_name);
//EDIT ROOM
}elseif(isset($_POST['edit'])){
$newNumber = $_POST['newNumber'];
$newType = $_POST['newType'];
$newView = $_POST['newView'];
$newPrice= $_POST['newPrice'];
$newAdultCap= $_POST['newAdultCap'];
$newKidsCap= $_POST['newKidsCap'];
$newStatus = $_POST['newStatus'];
$roomID= $_POST['id'];
$picture= $_POST['oldPicture'];
$img_name = $_FILES['picture']['name'];
if(empty($img_name)){
$room->editRoom1($newNumber,$newType,$newView,$newPrice,$newAdultCap,$newKidsCap,$picture,$newStatus,$roomID);
}else{
$room->editRoom2($newNumber,$newType,$newView,$newPrice,$newAdultCap,$newKidsCap,$img_name,$newStatus,$roomID);
}
}elseif ($_GET['actiontype']=='delete_room') {
$id = $_GET['room_id'];
$room->deleteRoom($id);
//Date 空いてるか確認するやつ
}elseif(isset($_POST['check'])){
$id = $_POST['id'];
$checkIn = date_create($_POST['checkIn']);
$checkIn = date_format($checkIn, 'Y-m-d');
$checkOut = date_create($_POST['checkOut']);
$checkOut = date_format($checkOut, 'Y-m-d');
$room_price = $_POST['room_price'];
$dayCount = ((strtotime($checkOut) - strtotime($checkIn)) / 86400);
$totalPrice = $room_price * $dayCount;
$_SESSION['checkin'] = $checkIn;
$_SESSION['checkout'] = $checkOut;
$_SESSION['total'] = $totalPrice;
$room->checkDate($checkIn,$checkOut,$id);
// $display = $room->displayAvailableRoom($result);
// if($room->checkDate($checkIn,$checkOut,$roomType)){
// }
//bookRoom.phpからFinal Confirmationへいくやつ
}elseif(isset($_POST['book'])){
$id = $_POST['id'];
$_SESSION['final_adult']= $_POST['adult'];
$_SESSION['final_kids']= $_POST['kids'];
if($_SESSION['login'] == "logined"){
header("Location: ../finalComfimation.php?id=$id");
}else {
echo "NG";
}
}elseif(isset($_POST['finalBook'])){
$checkIn = $_POST['checkin'];
$checkOut = $_POST['checkout'];
$adult = $_POST['final_adult'];
$kids = $_POST['final_kids'];
$roomID = $_POST['id'];
$userID = $_POST['userID'];
$fname = $_POST['fname'];
$room->finalBook($checkIn,$checkOut,$adult,$kids,$roomID,$userID,$fname);
}
?> | true |
1181a998fd09589cb807e1454f1578243d559ad9 | PHP | Thoronir42/paf | /extensions/SeStep/GeneralSettingsInMemory/src/Model/InMemoryNode.php | UTF-8 | 1,401 | 2.6875 | 3 | [
"MIT"
] | permissive | <?php declare(strict_types=1);
namespace SeStep\GeneralSettingsInMemory\Model;
use SeStep\GeneralSettings\DomainLocator;
use SeStep\GeneralSettings\Model\INode;
use SeStep\GeneralSettingsInMemory\InMemoryOptionsAdapter;
abstract class InMemoryNode implements INode
{
/** @var array */
protected $data;
/** @var InMemoryOptionSection */
private $parent;
/** @var string */
private $name;
public function __construct(InMemoryOptionSection $parent, string $name, array &$data)
{
$this->data = $data;
$this->parent = $parent;
$this->name = $name;
}
/**
* Returns fully qualified name. That is in most cases concatenated getDomain() and getName().
* @return mixed
*/
public function getFQN(): string
{
return DomainLocator::concatFQN($this->name, $this->parent);
}
protected function getName(): string
{
return $this->name;
}
public function getType(): string
{
return $this->data['type'];
}
public function getCaption(): ?string
{
return $this->data['caption'] ?? null;
}
final protected function getRoot(): InMemoryOptionsAdapter
{
$section = $this;
while (!($section instanceof InMemoryOptionsAdapter) && $section->parent) {
$section = $section->parent;
}
return $section;
}
}
| true |
7b41e8168c3e29575e9ced68d57462bd0b117b1c | PHP | albert2lyu/wechat-yii | /actions/ActionBase.php | UTF-8 | 510 | 2.71875 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
/**
* 所有action都需要继承的父类
* ActionBase.php
* User: wlq
* CreateTime: 16-3-18 上午11:07
*/
namespace app\actions;
use yii\base\Action;
abstract class ActionBase extends Action{
//子类处理逻辑
abstract protected function invoke();
//Action 必须实现的run方法
public function run(){
$res = $this->invoke();
$this->_display( $res );
}
//处理返回结果
private function _display( $res ){
echo $res;
}
} | true |
113ce135adc95fd306cdd7a1dbedbae0a1dac059 | PHP | tatelucas/growpro | /app/code/local/metrof/MadeToOrder/Model/Product.php | UTF-8 | 11,076 | 2.71875 | 3 | [] | no_license | <?php
/**
* FGI
*/
/**
* Catalog product
*
* @category Metrof
* @package Metrof_MadeToOrder
*/
class Metrof_MadeToOrder_Model_Product extends Mage_Catalog_Model_Product
{
/**
* Product Types
*/
const STATUS_ENABLED = 1;
const STATUS_DISABLED = 2;
const TYPE_SIMPLE = 'simple';
const TYPE_BUNDLE = 'bundle';
const TYPE_CONFIGURABLE = 'configurable';
const TYPE_GROUPED = 'grouped';
const TYPE_VIRTUAL = 'virtual';
const TYPE_DYNAMIC_PRICE = 'simple';
const DEFAULT_TYPE = 'simple';
protected $productWidth = 0;
protected $productHeight = 0;
protected $productDepth = 0;
protected $productSqft = 0;
protected $productLine = '';
protected $dynPrice = -1;
public function getPrice() {
if ($this->hasDynamicPrice()) {
if ($this->dynPrice > 0 ) { return $this->dynPrice;}
$dyn = $this->getDynamicPrice();
//var_dump($dyn);exit();
//exit();
$this->dynPrice = $dyn;
return $dyn;
} else {
return $this->getData('price');
}
}
public function hasDynamicPrice() {
switch ($this->getTypeId()) {
case Metrof_MadeToOrder_Model_Product::TYPE_SIMPLE:
case Metrof_MadeToOrder_Model_Product::TYPE_DYNAMIC_PRICE:
return true;
break;
}
return false;
}
/**
* Return true if we found some user submitted sizes in the POST
* This should trigger other processing if the user submitted sizes
*/
public function setupDynamicAttribs() {
$foundAttribs = false;
//look in request
//FIXME try to grab the global Zend Request object somehow
if(isset($_POST['mto_width']) ) {
//if not, use some defaults
$foundAttribs = true;
$this->productWidth = @$_POST['mto_width'];
} else {
//if not, use some defaults
$this->productWidth = @$this->_data['mto_width_min'];
}
if(isset($_POST['mto_height']) ) {
$foundAttribs = true;
$this->productHeight = @$_POST['mto_height'];
} else {
//if not, use some defaults
$this->productHeight = @$this->_data['mto_height_min'];
}
if(isset($_POST['mto_depth']) ) {
$foundAttribs = true;
$this->productDepth = @$_POST['mto_depth'];
} else {
//if not, use some defaults
$this->productDepth = @$this->_data['mto_height_min'];
}
//product line is sku minus '-CS'
$this->productLine = substr($this->getData('sku'),0, -3);
//calc sqft, round down
//TODO add in fractional inches
$this->productSqft = floor($this->productWidth * $this->productHeight);
//var_dump($this->productWidth);exit();
return $foundAttribs;
}
public function getCalculatedPrice(array $options)
{
$price = $this->getPrice();
foreach ($this->getSuperAttributes() as $attribute) {
if(isset($options[$attribute['attribute_id']])) {
if($value = $this->_getValueByIndex($attribute['values'], $options[$attribute['attribute_id']])) {
if($value['pricing_value'] != 0) {
$price += $this->getPricingValue($value);
}
}
}
}
return $price;
}
/**
* This method is mainly to be run from the product view page, after a user
* enters some config values. Otherwise it should simply shortcut and
* return the default price.
*/
public function getDynamicPrice() {
if (!$this->setupDynamicAttribs()) {
return $this->getData('price');
}
if (! function_exists('simplexml_load_string') ) {
return $this->getData('price');
}
$xmlString = $this->getPriceXml();
try {
$xml = @simplexml_load_string($this->getPriceXml());
} catch (Exception $e) {
return $this->getData('price');
}
if (! is_object($xml) ) {
return $this->getData('price');
}
$moreConditions = true;
//limit to 3 nested conditions
foreach ($xml->productLine[0]->product->children() as $subTag) {
if ( $subTag->getName() == 'condition' ) {
$result = $this->evalConditions($subTag);
if ( is_object($result) && $result->getName() == 'calculation' ) {
$price = (float)$result * $this->productSqft;
break;
} else if ($result !== false) {
$price = (string)$result;
break;
}
}
if ( $subTag->getName() == 'calculation' ) {
$price = $this->productSqft * (float)$subTag;
break;
}
}
if (!isset($price) || $result === false) {
return 'sqft = '.$this->productSqft .' w = '.$this->productWidth;
throw new Exception ('error in pricing logic');
}
//chop off dollar sign if one exists.
if (substr($price,0,1) === '$') {
$price = substr($price,1);
}
return $price;
}
/**
* Recursive function, returns price, calculation tag, or false
*/
protected function evalConditions($condition) {
if ($condition->getName() === 'condition') {
//eval
$rslt = true;
switch ($condition['type']) {
case 'range':
list($min,$max) = explode('-',$condition['value']);
if ($condition['attrib'] == 'sqft') { $test = (float)$this->productSqft;}
if ($condition['attrib'] == 'width') { $test = (float)$this->productWidth;}
/*
var_dump($test);
var_dump($max);
var_dump('$test <= $max');
var_dump($test <= $max);
//var_dump($condition);
// */
$rslt = $test >= (int)$min;
$rslt = ($test <= (int)$max) && $rslt;
break;
}
if (!$rslt) { return false; }
//eval went okay
//do children
$hasChildren = false;
foreach($condition->children() as $subTag) {
$hasChildren = true;
$rslt = $this->evalConditions($subTag);
//we found a price
if (is_string($rslt)) { return $rslt; }
}
if (!$hasChildren) { return (string)$condition; }
}
//we're not even a condition, return ourselves as a condition
//TODO: should we just return the price right here?
if ($condition->getName() === 'calculation' ) {
return (float)$condition * $this->productSqft;
}
return $rslt;
}
/**
* This should return the string content of a file based on the product line.
*/
public function getPriceXml() {
//app/code/local is in the include path
//file get contents does not use include path
if (! file_exists(BP.'/app/code/local/Metrof/MadeToOrder/pricingsheets/samplexml.txt') ) {
return '';
}
return @file_get_contents(BP.'/app/code/local/Metrof/MadeToOrder/pricingsheets/samplexml.txt');
}
public function getTypeId() {
return isset($this->_data['type_id'])? $this->_data['type_id']:NULL;
}
public function getName() {
return isset($this->_data['name'])? $this->_data['name']:NULL;
}
public function getSampleXml() {
return <<<EOF
<?xml version="1.0"?>
<fgipricingrules>
<productLine line="50050">
<product sku="VL-OR1">
<condition type="eq" attrib="thickness" value="1">
<calculation attrib="sqft">0.86</calculation>
</condition>
<condition type="eq" attrib="thickness" value="2">
<calculation attrib="sqft">0.96</calculation>
</condition>
</product>
</productLine>
<productLine line="20000">
<product sku="20000">
<condition type="range" attrib="width" value="0-33">
<condition type="eq" attrib="depth" value="1/2">
<condition type="range" attrib="sqft" value="0-99">$3.20</condition>
<condition type="range" attrib="sqft" value="100-199">$3.28</condition>
<condition type="range" attrib="sqft" value="200-249">$3.42</condition>
</condition>
<condition type="eq" attrib="depth" value="1">
<condition type="range" attrib="sqft" value="0-99">$3.30</condition>
<condition type="range" attrib="sqft" value="100-199">$3.28</condition>
<condition type="range" attrib="sqft" value="200-249">$3.42</condition>
</condition>
<condition type="eq" attrib="depth" value="2">
<condition type="range" attrib="sqft" value="0-99">$3.40</condition>
<condition type="range" attrib="sqft" value="100-199">$3.28</condition>
<condition type="range" attrib="sqft" value="200-249">$3.99</condition>
</condition>
</condition>
<condition type="range" attrib="width" value="34-66">
<condition type="eq" attrib="depth" value="1/2">
<condition type="range" attrib="sqft" value="0-99">$9.10</condition>
<condition type="range" attrib="sqft" value="100-199">$9.28</condition>
<condition type="range" attrib="sqft" value="200-249">$9.42</condition>
</condition>
<condition type="eq" attrib="depth" value="1">
<condition type="range" attrib="sqft" value="0-99">$9.10</condition>
<condition type="range" attrib="sqft" value="100-199">$9.28</condition>
<condition type="range" attrib="sqft" value="200-249">$9.42</condition>
</condition>
<condition type="eq" attrib="depth" value="2">
<condition type="range" attrib="sqft" value="0-99">$9.10</condition>
<condition type="range" attrib="sqft" value="100-199">$9.28</condition>
<condition type="range" attrib="sqft" value="200-249">$9.99</condition>
</condition>
</condition>
</product>
</productLine>
</fgipricingrules>
EOF;
}
}
| true |
78cf89f301ad0e2e7d6abdbb1f79d757101e940c | PHP | exgamer/yii2-account-module | /src/services/AccountOperationService.php | UTF-8 | 4,805 | 2.53125 | 3 | [] | no_license | <?php
namespace concepture\yii2account\services;
use concepture\yii2account\models\Account;
use concepture\yii2logic\models\ActiveRecord;
use concepture\yii2logic\services\Service;
use concepture\yii2logic\services\traits\StatusTrait;
use concepture\yii2account\enum\AccountOperationTypeEnum;
use concepture\yii2account\forms\AccountForm;
use concepture\yii2account\forms\AccountOperationForm;
use concepture\yii2account\traits\ServicesTrait;
use Exception;
/**
* Class AccountOperationService
* @package concepture\yii2account\services
* @author Olzhas Kulzhambekov <exgamer@live.ru>
*/
class AccountOperationService extends Service
{
use StatusTrait;
use ServicesTrait;
/**
* Пополнение счета
*
* @param integer $entity_id
* @param integer $entity_type_id
* @param integer $payment_system_id
* @param string $payment_system_transaction_number
* @param integer $payment_system_transaction_status
* @param double $sum
* @param integer $currency_id
* @param string $description
* @return boolean
* @throws Exception
*/
public function refill($entity_id, $entity_type_id, $payment_system_id, $payment_system_transaction_number, $payment_system_transaction_status, $sum, $currency_id, $description = null)
{
$account = $this->accountService()->getOneByCondition([
'entity_id' => $entity_id,
'entity_type_id' => $entity_type_id,
'currency_id' => $currency_id,
]);
if (! $account){
$accountForm = new AccountForm();
$accountForm->entity_id = $entity_id;
$accountForm->entity_type_id = $entity_type_id;
$accountForm->currency_id = $currency_id;
$accountForm->status = 1;
$account = $this->accountService()->create($accountForm);
}
return $this->doOperation($payment_system_id, $payment_system_transaction_number, $payment_system_transaction_status, $sum, $account, AccountOperationTypeEnum::REFILL, $description);
}
/**
* Снятие со счета
*
* @param integer $entity_id
* @param integer $entity_type_id
* @param integer $payment_system_id
* @param string $payment_system_transaction_number
* @param integer $payment_system_transaction_status
* @param double $sum
* @param integer $currency_id
* @param string $description
* @return boolean
* @throws Exception
*/
public function writeOff($entity_id, $entity_type_id, $payment_system_id, $payment_system_transaction_number, $payment_system_transaction_status, $sum, $currency_id, $description = null)
{
$account = $this->accountService()->getOneByCondition([
'entity_id' => $entity_id,
'entity_type_id' => $entity_type_id,
'currency_id' => $currency_id,
]);
if (! $account){
throw new Exception("account not exists");
}
if ($account->balance < $sum){
throw new Exception("not enough balance");
}
return $this->doOperation($payment_system_id, $payment_system_transaction_number, $payment_system_transaction_status, $sum, $account, AccountOperationTypeEnum::WRITE_OFF, $description);
}
/**
* Операция
*
* @param integer $payment_system_id
* @param string $payment_system_transaction_number
* @param integer $payment_system_transaction_status
* @param double $sum
* @param Account $account
* @param integer $type
* @param string $description
* @return bool
* @throws Exception
*/
protected function doOperation($payment_system_id, $payment_system_transaction_number, $payment_system_transaction_status, $sum, $account, $type, $description = null)
{
$form = new AccountOperationForm();
$form->type = $type;
$form->payment_system_transaction_number = $payment_system_transaction_number;
$form->payment_system_transaction_status = $payment_system_transaction_status;
$form->payment_system_id = $payment_system_id;
$form->sum = $sum;
$form->account_id = $account->id;
if ($description){
$form->description = $description;
}
if (! $this->accountOperationService()->create($form))
{
throw new Exception("operation failed");
}
if ($type == AccountOperationTypeEnum::REFILL){
$account->balance += $form->sum;
}elseif ($type == AccountOperationTypeEnum::WRITE_OFF){
$account->balance -= $form->sum;
}else{
return false;
}
if (! $account->save(false)){
throw new Exception("operation failed");
}
return true;
}
} | true |
b67cf5bd2f2d1ab0db120a5beee882c9a8fd1970 | PHP | victorblanco/fCAB | /i18n/Language.class.php | UTF-8 | 541 | 3.203125 | 3 | [] | no_license | <?php
class Language extends LanguageFactory {
/**
* Default Number Format Instance
*/
protected static $default = null;
/**
* Array of language names
*/
protected $names = array();
/**
* Returns a language name
*
* @param string $language
* @return string
*/
public function name( $language ) {
if ( !isset( $this->names[$language] ) ) {
throw new Exception( sprintf( 'No name defined for Language "%s" on this locale', $language ) );
}
return $this->names[$language];
}
}
| true |
cf86370ba4f9c4cfc2d249d450d299d845b92d30 | PHP | orchestra-io/sample-symfony2 | /vendor/monolog/tests/Monolog/LoggerTest.php | UTF-8 | 1,760 | 2.609375 | 3 | [
"MIT"
] | permissive | <?php
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog;
class LoggerTest extends \PHPUnit_Framework_TestCase
{
public function testLog()
{
$logger = new Logger(__METHOD__);
$handler = $this->getMock('Monolog\Handler\NullHandler', array('handle'));
$handler->expects($this->once())
->method('handle');
$logger->pushHandler($handler);
$this->assertTrue($logger->addWarning('test'));
}
public function testLogNoHandler()
{
$logger = new Logger(__METHOD__);
$handler = $this->getMock('Monolog\Handler\NullHandler', array('handle'), array(Logger::ERROR));
$handler->expects($this->never())
->method('handle');
$logger->pushHandler($handler);
$this->assertFalse($logger->addWarning('test'));
}
public function logValues()
{
return array(array(true), array(false));
}
public function testPushPopHandler()
{
$logger = new Logger(__METHOD__);
$handler1 = $this->getMock('Monolog\Handler\NullHandler', array('handle'));
$handler2 = $this->getMock('Monolog\Handler\NullHandler', array('handle'));
$handler3 = $this->getMock('Monolog\Handler\NullHandler', array('handle'));
$logger->pushHandler($handler1);
$logger->pushHandler($handler2);
$logger->pushHandler($handler3);
$this->assertEquals($handler3, $logger->popHandler());
$this->assertEquals($handler2, $logger->popHandler());
$this->assertEquals($handler1, $logger->popHandler());
}
}
| true |
c966bd3dc927dde559a0a4c3bcaf4bfddf4466af | PHP | LubaRo/test-box-storage | /Box/DbBox.php | UTF-8 | 1,671 | 3.265625 | 3 | [] | no_license | <?php
namespace Box;
/**
* DbBox
*
* Allows to save and load box data from database
*/
class DbBox extends AbstractBox
{
private $dbTable = 'storage';
private $dbName = '';
private $dbHost = '';
private $dbUser = '';
private $dbPwd = '';
/**
* Prepare multiple values for sql query
*
* @return string
*/
private function prepareValuesRow(): string
{
$values = [];
foreach ($this->storage as $key => $value) {
$values[] = "('{$key}', '{$value}')";
}
return implode(', ', $values);
}
/**
* Save box data to database
*
* @return void
*/
public function save()
{
$pdo = $this->getDbConnection();
$valuesRow = $this->prepareValuesRow();
$pdo->exec("REPLACE INTO {$this->dbTable} (`key`, `value`) VALUES {$valuesRow}");
}
/**
* Load data from database to box instance
*
* @return void
*/
public function load()
{
$pdo = $this->getDbConnection();
$query = "SELECT * FROM {$this->dbTable}";
$data = $pdo->query($query)->fetchAll(\PDO::FETCH_ASSOC);
foreach ($data as ['key' => $key, 'value' => $value]) {
$this->setData($key, $value);
}
}
/**
* Establishes and returns a database connection
*
* @return \PDO
*/
private function getDbConnection()
{
$data = "mysql:dbname={$this->dbName};host={$this->dbHost}";
$pdo = new \PDO($data, $this->dbUser, $this->dbPwd);
$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
return $pdo;
}
}
| true |
7e6a13793312f68a574eabd802cbcacd85bd2d53 | PHP | Light-orochi/E-commerce-website | /newad.php | UTF-8 | 6,180 | 2.796875 | 3 | [] | no_license | <?php
session_start();
$pagetitle='NEW ADD';
include'init.php';
if (isset($_SESSION['user'])) {
if ($_SERVER['REQUEST_METHOD']=="POST") {
$formerror=array();
$name=filter_var($_POST['name'],FILTER_SANITIZE_STRING);
$desc=filter_var($_POST['descrp'],FILTER_SANITIZE_STRING);
$price=filter_var($_POST['price'],FILTER_SANITIZE_NUMBER_INT);
$country=filter_var($_POST['countery'],FILTER_SANITIZE_STRING);
$status=filter_var($_POST['status'],FILTER_SANITIZE_NUMBER_INT);
$category=filter_var($_POST['categories'],FILTER_SANITIZE_STRING);
$tags=filter_var($_POST['tags'],FILTER_SANITIZE_STRING);
if (strlen($name) < 4) {
$formErrors[] = 'Item Title Must Be At Least 4 Characters';
}
if (strlen($desc) < 10) {
$formErrors[] = 'Item Description Must Be At Least 10 Characters';
}
if (strlen($country) < 2) {
$formErrors[] = 'Item Title Must Be At Least 2 Characters';
}
if (empty($price)) {
$formErrors[] = 'Item Price Cant Be Empty';
}
if (empty($status)) {
$formErrors[] = 'Item Status Cant Be Empty';
}
if (empty($category)) {
$formErrors[] = 'Item Category Cant Be Empty';
}
if (empty($formErrors)) {
// Insert Userinfo In Database
$stmt = $con->prepare("INSERT INTO
items(Name, Descripition, Price, Country_Made, Status, Add_Date, Cat_ID, Member_ID,tags)
VALUES(:zname, :zdesc, :zprice, :zcountry, :zstatus, now(), :zcat, :zmember,:ztags)");
$stmt->execute(array(
'zname' => $name,
'zdesc' => $desc,
'zprice' => $price,
'zcountry' => $country,
'zstatus' => $status,
'zcat' => $category,
'zmember' => $_SESSION['uid'],
'ztags'=> $tags
));
// Echo Success Message
if ($stmt) {
$succesMsg = 'Item Has Been Added';
}
}
}
?>
<h1 class="text-center">NEW AD</h1>
<div class="container">
<div class="panel panel-primary">
<div class="panel-heading">Creat new ad</div>
<div class="panel-body">
<div class="row">
<div class="col-md-8">
<form class="form-horizontal" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<div class="form-group form-group-lg ">
<label class="control-label col-sm-2">Name</label>
<div class="col-sm-10 col-md-9 ">
<input type="text" class="form-control" name="name" placeholder="Enter email" >
</div>
</div>
<div class="form-group form-group-lg ">
<label class="control-label col-sm-2">Description</label>
<div class="col-sm-10 col-md-9 ">
<input type="text" class="form-control" name="descrp"placeholder="Describe your item">
</div>
</div>
<div class="form-group form-group-lg ">
<label class="control-label col-sm-2">Price</label>
<div class="col-md-9 col-sm-10">
<input type="text" class="form-control"name="price" placeholder="Enter price">
</div>
</div>
<div class="form-group form-group-lg ">
<label class="control-label col-sm-2">Countery</label>
<div class="col-md-9 col-sm-10">
<input type="text" class="form-control" name="countery"placeholder="Enter Counter made">
</div>
</div>
<div class="form-group form-group-lg ">
<label class="col-sm-2 control-label">Status</label>
<div class="col-sm-10 col-md-9">
<select class="form-control"name="status">
<option value="">...</option>
<option value="1">New</option>
<option value="2">Like New</option>
<option value="3">Used</option>
<option value="4">Very Old</option>
</select>
</div>
</div>
<div class="form-group form-group-lg ">
<label class="col-sm-2 control-label">Categories</label>
<div class="col-sm-10 col-md-9">
<select class="form-control"name="categories">
<option value="">...</option>
<?php
$stmt2=$con->prepare("SELECT * FROM categories where parent=0");
$stmt2->Execute();
$rows2=$stmt2->fetchALL();
foreach ($rows2 as $row2) {
echo "<option value='" . $row2['ID'] . "'>" . $row2['Name'] . "</option>";
}
?>
</select>
</div>
</div>
<div class="form-group form-group-lg ">
<label class="control-label col-sm-2">Tags</label>
<div class="col-md-9 col-sm-10">
<input type="text" class="form-control" name="tags" placeholder="Seperat tags by gomma">
</div>
</div>
<div class="form-group form-group-lg ">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" class="btn btn-primary btn-lg" value="save">
</div>
</div>
</form>
</div>
<div class="col-md-4">
<div class="col-sm-10 col-md-12">
<div class="thumbnail item-box">
<span class="price-tag">eshta</span>
<img src="img.png" alt="mizo"/>
<div class="caption">
<h3>hamo</h3>
<p>mido<p>
</div>
</div>
</div>
</div>
</div>
<?php
if (! empty($formErrors)) {
foreach ($formErrors as $error) {
echo '<div class="alert alert-danger">' . $error . '</div>';
}
}
if (isset($succesMsg)) {
echo '<div class="alert alert-success">' . $succesMsg . '</div>';
}
?>
</div>
</div>
</div>
<?php }
else {
header('Location:Login.php');
}
include $tpl .'footer.php';
?>
| true |
ae24209e544ca397f1439f3b2931b7fd42d6b3d6 | PHP | drovot/rocketlaunches-api | /app/Http/Middleware/TrackingMiddleware.php | UTF-8 | 703 | 2.578125 | 3 | [] | no_license | <?php
namespace App\Http\Middleware;
use App\Http\Response\Response;
use App\Tracking\TrackingManager;
use Closure;
use Illuminate\Http\Request;
class TrackingMiddleware
{
/** @var TrackingManager */
private TrackingManager $trackingManager;
/**
* TrackingMiddleware constructor.
*/
public function __construct()
{
$this->trackingManager = new TrackingManager();
}
/**
* Track incoming request.
*
* @param Request $request
* @param Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
$this->trackingManager->handle($request);
return $next($request);
}
}
| true |
0f53814e970d5c63a7f312ebf6c88ac2a42ffdaa | PHP | AlThunder/Practical_tasks | /Practical_tasks_PHP/1_Language_basics_PHP/19/HomeWork/index.php | UTF-8 | 973 | 3.515625 | 4 | [] | no_license | <?php
/*$a = function($x, $y){
$sum = $x + $y;
echo $sum.'<br/>';
};
$a(2, 3);
function koD($arr, $func){
$i = 0;
foreach ($arr as $value) {
echo $value.$func;
$i++;
if (is_numeric($value) !== true){
echo "Значение $value не числовое";
}
}
if (is_int($i/2) == false){
echo 'Массив $arr имеет нечетное число элементов';
}
}
/*function test($a, $func)
{
$arr = [];
for ($i = 0; $i < $a; $i++)
{
$arr[] = $func($i);
}
return $arr;
}
$r = test (10, function($f)
{
return $f * $f;
});
foreach ($r as $v) echo $v.", ";*/
/*$r = [1, 2, 3, 4];
$i = 0;
$s = false;
foreach ($r as $value){
$s = 1 ;
}*/
$sum = function ($a, $b)
{
return $a + $b;
};
function test(array $data)
{
foreach (array_chunk($data, 2) as $numbers) {
echo "$numbers[0], $numbers[1]";
}
}
$numbers = [2, 3, 4, 5, 6, 7];
test($numbers);
?> | true |
f162edfd0c9a4d2af8984defd9979b99adf2d04f | PHP | adrelliott/leadfarm_v1 | /application/controllers/_to_delete/22222/_delet_me/booking_all_dates.php | UTF-8 | 9,504 | 2.734375 | 3 | [] | no_license | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Booking extends T_Booking {
public function __construct() {
parent::__construct();
}
public function index($view_file = 'index') {
parent::index($view_file);
// Generate the view!
$this->_generate_view($this->data);
}
public function view($view_file = 'edit', $rID = 'new', $ContactId = FALSE) {
parent::view($view_file, $rID, $ContactId);
// Generate the view!
$this->_generate_view($this->data);
}
public function get_booking_array() {
$this->load->model('booking_model');
$results = $this->booking_model->get_all_bookings();
header ('Content-Type: text/json');
echo json_encode ($results);
exit;
}
public function post_process_booking($data) {
if (! $this->workshop) return; //only for workshop users
if ( empty($this->data['view_setup']['tables']['bookings_join']['table_data'])) return; //make sure we have data to play with
//Now sort it into today's work, yesterdays and tomorrows
$retval = array();
$jobs = $this->data['view_setup']['tables']['bookings_join']['table_data'];
//Set up the daye we're looking at
if (isset($_GET['current_day'])) $current_day = strtotime($_GET['current_day'] . ' 00:00:00');
else $current_day = strtotime(date('Y-m-d 00:00:00'));
//set up all other days
$dates['timestamps'] = array
(
'today' => $current_day,
'tomorrow' => $current_day + (24 * 60* 60),
'yesterday' => $current_day - (24 * 60* 60),
'in_the_past' => $current_day - 2*(24 * 60* 60),
'in_the_future' => $current_day + 2*(24 * 60* 60),
);
$dates['dates'] = array
(
'today' => date('Y-m-d H:i:s', $dates['timestamps']['today']),
'tomorrow' => date('Y-m-d H:i:s', $dates['timestamps']['tomorrow']),
'yesterday' => date('Y-m-d H:i:s', $dates['timestamps']['yesterday']),
'in_the_past' => date('Y-m-d H:i:s', $dates['timestamps']['in_the_past']),
'in_the_future' => date('Y-m-d H:i:s', $dates['timestamps']['in_the_future']),
);
//Now sort the jobs into these 3 arrays
foreach($jobs as $k => $array)
{
if ( isset( $array['ActionDate']) )
{
$action_date = strtotime( $array['ActionDate'] );
$action_time = explode(' ', $array['ActionDate'] );
$action_time = substr($action_time[1], 0, -3); //remove the seconds!
//Is it a job for tomorrow...?
if ( $action_date < $dates['timestamps']['in_the_future']
AND $action_date >= $dates['timestamps']['tomorrow'] )
$key = 'tomorrow';
//Is it a job for today...?
elseif ( $action_date < $dates['timestamps']['tomorrow']
AND $action_date >= $dates['timestamps']['today'] )
$key = 'today';
//$jobs['today'][$array['Id']] = $array;
//is it a job for yesterday?
elseif ( $action_date < $dates['timestamps']['today']
AND $action_date >= $dates['timestamps']['yesterday'] )
$key = 'yesterday';
//$jobs['yesterday'][$array['Id']] = $array;
//is it a future job?
elseif ( $action_date >= $dates['timestamps']['in_the_future'] )
$key = 'in_the_future';
//$jobs['in_the_future'][$array['Id']] = $array;
//must be a past job then?
else //$jobs['in_the_past'][$array['Id']] = $array;
$key = 'in_the_past';
//get the time of the booking
$retval[$key][$array['Id']][$array['_Status']] = $array;
$retval[$key][$array['Id']]['time'] = $action_time;
$fields = $this->data['config']['record']['view']['fields'];
$retval[$key][$array['Id']]['field'] = array
(
'UserID' => $fields['UserID'],
'_EstimatedDuration' => $fields['_EstimatedDuration'],
'ActionDate' => $fields['ActionDate'],
'_Status' => $fields['_Status']
);
}
}
//create mechanics dropdown
$mechanics = $this->data['view_setup']['tables']['users']['table_data'];
foreach ($mechanics as $k => $array)
{
$mechanics['dropdowns'][$array['FirstName'] . ' ' . substr($array['LastName'],0,1)] = $array['Id'];
}
//add all this dat back to the array available in the view
$this->data['view_setup']['jobs'] = $retval;
$this->data['view_setup']['dropdowns']['users'] = $mechanics['dropdowns'];
foreach ($dates['dates'] as $k => $v)
$this->data['view_setup']['dates'][$k] = array
(
'full' => $v,
'nice' => date('jS M, Y', $dates['timestamps'][$k]),
'date' => date('Y-m-d', $dates['timestamps'][$k])
);
/*
//set up the wokrshop_booking array
$retval = array();
$options = $this->data['config']['record']['view']['fields']['_Status']['options'];
$results = $this->data['view_setup']['tables']['bookings_join']['table_data'];
foreach ( $results as $k => $array )
{
echo "<br/>this is the date of the event". strtotime($array['ActionDate']);
echo "<br/>this todaty". strtotime("now");
echo "<br/>this si timestampe".time();
echo "<br/>this tomorow ?". strtotime("+1 day");
//if( strtotime($array['ActionDate']) < )
$retval[$array['_Status']][] = $array;
//whats the stage? (not checked in, checked in or)
}
die;
//print_array($this->data, 1);
$this->data['view_setup']['tables']['workshop']['table_data'] = $retval;
return;
* */
}
/*
* public function get_booking_array2() {
$results = array ();
$title = '<strong>MOT</strong> (Ford Fiesta, YG02 YTR)';
$description = '';
$start_ts = mktime (8, 0, 0, 1, 30, 2013);
$end_ts = mktime (10, 0, 0, 1, 30, 2013);
//$url = 'http://leadfarm-staging.co.uk/22222/booking';
$url = 'booking/view/edit/8/0';
$results[] = array (
'id' => 1, /* ID of the event */
// 'title' => strip_tags ($title), /* Title that has been made HTML-safe */
//'htmlTitle' => $title, /* Original title */
// 'description' => $description, /* HTML description */
// 'start' => date ('Y-m-d H:i:s', $start_ts),
//'start' => date ('Y-m-d', $start_ts),
// 'end' => date ('Y-m-d H:i:s', $end_ts),
//'end' => date ('Y-m-d', $end_ts),
// 'allDay' => false,
// 'url' => $url,
// 'color' => '#70B437' /* Hex-code for background-colour */
// );
// header ('Content-Type: text/json');
// echo json_encode ($results);
// exit;
// }
/* public function get_bookings() {
//get all the booking data
$year = date('Y');
$month = date('m');
echo json_encode(array(
array(
'id' => 111,
'title' => "Event1",
'start' => "$year-$month-10",
'url' => "http://yahoo.com/"
),
array(
'id' => 222,
'title' => "Event2",
'start' => "$year-$month-20",
'end' => "$year-$month-22",
'url' => "http://yahoo.com/"
)
));
{
title: 'All Day Event',
start: new Date(y, m, 1)
},
{
title: 'Long Event',
start: new Date(y, m, d - 5),
end: new Date(y, m, d - 2)
},
{
id: 999,
title: 'Repeating Event',
start: new Date(y, m, d - 3, 16, 0),
allDay: false
},
{
id: 999,
title: 'Repeating Event',
start: new Date(y, m, d + 4, 16, 0),
allDay: false
},
{
title: 'Meeting',
start: new Date(y, m, d, 10, 30),
allDay: false
},
{
title: 'Lunch',
start: new Date(y, m, d, 12, 0),
end: new Date(y, m, d, 14, 0),
allDay: false
},
{
title: 'Birthday Party',
start: new Date(y, m, d + 1, 19, 0),
end: new Date(y, m, d + 1, 22, 30),
allDay: false
},
{
title: 'Click for Google',
start: new Date(y, m, 28),
end: new Date(y, m, 29),
url: 'http://google.com/'
}
}*/
}
| true |
4670ac857ad8cb00aeee8469ecb8f4118e0f5699 | PHP | webuni/srazy-api-client | /src/Model/Event.php | UTF-8 | 4,096 | 2.71875 | 3 | [
"MIT"
] | permissive | <?php
/*
* This is part of the webuni/srazy-api-client.
*
* (c) Martin Hasoň <martin.hason@gmail.com>
* (c) Webuni s.r.o. <info@webuni.cz>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Webuni\Srazy\Model;
use Doctrine\Common\Collections\ArrayCollection;
class Event
{
private $uri;
private $name;
private $description;
private $series;
private $sessions;
private $start;
private $end;
private $address;
private $mapUrl;
private $confirmedAttendees;
private $unconfirmedAttendees;
private $comments;
private $location;
private $polls;
public function __construct($name = null, $uri = null, \DateTime $date = null)
{
$this->name = $name;
$this->uri = $uri;
$this->start = $date;
$this->series = new ArrayCollection();
$this->sessions = new ArrayCollection();
$this->comments = new ArrayCollection();
$this->polls = new ArrayCollection();
$this->confirmedAttendees = new ArrayCollection();
$this->unconfirmedAttendees = new ArrayCollection();
}
public function getUri()
{
return $this->uri;
}
public function setUri($uri)
{
$this->uri = $uri;
}
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
public function getDescription()
{
return $this->description;
}
public function setDescription($description)
{
$this->description = $description;
}
public function getAddress()
{
return $this->address;
}
public function setAddress($address)
{
$this->address = $address;
}
public function getMapUrl()
{
return $this->mapUrl;
}
public function setMapUrl($mapUrl)
{
$this->mapUrl = $mapUrl;
}
public function getSeries()
{
return $this->series;
}
public function setSeries(Series $series = null)
{
$this->series = $series;
}
public function getStart()
{
return $this->start;
}
public function setStart(\DateTime $start = null)
{
$this->start = $start;
}
public function getEnd()
{
return $this->end;
}
public function setEnd(\DateTime $end = null)
{
$this->end = $end;
}
public function getLocation()
{
return $this->location;
}
public function setLocation($location)
{
$this->location = $location;
}
public function getSessions()
{
return $this->sessions;
}
/**
* @param Session[]|ArrayCollection $sessions
*/
public function setSessions(ArrayCollection $sessions)
{
$this->sessions = $sessions;
if (null !== $this->end) {
return;
}
foreach ($sessions as $session) {
if ($session->isType(Session::TYPE_END)) {
$this->setEnd($session->getStart());
break;
}
}
}
public function getConfirmedAttendees()
{
return $this->confirmedAttendees;
}
public function setConfirmedAttendees(ArrayCollection $confirmedAttendees)
{
$this->confirmedAttendees = $confirmedAttendees;
}
public function getUnconfirmedAttendees()
{
return $this->unconfirmedAttendees;
}
public function setUnconfirmedAttendees(ArrayCollection $unconfirmedAttendees)
{
$this->unconfirmedAttendees = $unconfirmedAttendees;
}
public function getComments()
{
return $this->comments;
}
public function setComments(ArrayCollection $comments)
{
$this->comments = $comments;
}
/**
* @return Poll[]|ArrayCollection
*/
public function getPolls()
{
return $this->polls;
}
public function setPolls(ArrayCollection $polls)
{
$this->polls = $polls;
}
}
| true |
c8b68173dcd3114150c3b6b9e2bfdeaaaf7bfe7a | PHP | BGCX261/zinventory-svn-to-git | /branches/modules/helpers/classes/functionsphpmailer.php | UTF-8 | 3,373 | 2.578125 | 3 | [
"BSD-3-Clause"
] | permissive |
<?php defined('SYSPATH') or die('No direct script access.');
/**
* Funciones especiales para uso domestico
*
* @author Hardlick
*/
class Helper_functionsphpmailer {
/**
*
* Funcion Send Email
* Sirve para enviar correos electronicos a un destinatario
* parametros Aceptados: fromName,toEmail,mensaje,asunto,
* @author Hardlick
*/
static function sendEmail($args=array())
{
global $smarty;
//include_once ('applicationlibraries/phpmailer/class.phpmailer.php');
//include("libraries/phpmailer/class.smtp.php");
$mail = new PHPMailer();
$mail->SMTPSecure= "ssl";
$mail->IsSMTP();
$mail->Host = "smtp.gmail.com"; // SMTP server
$mail->Timeout=200;
//$mail->SMTPDebug = 2;
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Port = 465;
$mail->Username = "hcasanova@perfectumdata.com";
$mail->Password = "04379800";
$mail->From = "hcasanova@perfectumdata.com";
$mail->FromName = $args['fromName'];
$mail->AddAddress($args['toEmail']);
$mail->Subject = $args['asunto'];
$mail->Body = $args['mensaje'];
$mail->AltBody = $args['mensaje'];
$mail->WordWrap = 50;
$mail->IsHTML(true);
if(!$mail->Send()) {
return $mail->ErrorInfo;
}else {
return "1";
}
}
/**
*
* Funcion Send Email with attachment
* Sirve para enviar correos electronicos a un destinatario con un archivo adjunto
* parametros Aceptados: fromName,toEmail,mensaje,asunto, file
* @author Hardlick
*/
static function sendEmailattach($args=array())
{
global $smarty;
include_once ('libraries/phpmailer/class.phpmailer.php');
include("libraries/phpmailer/class.smtp.php");
$mail = new PHPMailer();
$mail->SMTPSecure= "ssl";
$mail->IsSMTP();
$mail->Host = "smtp.gmail.com"; // SMTP server
$mail->Timeout=200;
//$mail->SMTPDebug = 2;
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Port = 465;
$mail->Username = "hcasanova@perfectumdata.com";
$mail->Password = "04379800";
$mail->From = "hcasanova@perfectumdata.com";
$mail->FromName = $args['fromName'];
$mail->AddAddress($args['toEmail']);
$mail->Subject = $args['subject'];
$mail->Body = $args['message'];
$mail->AltBody = $args['message'];
$mail->WordWrap = 50;
$mail->AddAttachment("".$args['file']);
$mail->IsHTML(true);
if(!$mail->Send()) {
return $mail->ErrorInfo;
}
else {
return "1";
}
}
static function getRealIP()
{
$client_ip =
( !empty($_SERVER['REMOTE_ADDR']) ) ?
$_SERVER['REMOTE_ADDR']
:
( ( !empty($_ENV['REMOTE_ADDR']) ) ?
$_ENV['REMOTE_ADDR']
:
"unknown" );
return $client_ip;
}
}
?>
| true |
1cf2caccea2ba83a04492001901d175224f0d649 | PHP | pedrosinderbarroso/HelpingHands | /HelpingHands/php/nurseView.php | UTF-8 | 544 | 2.671875 | 3 | [
"MIT"
] | permissive | <?php
require_once "db_connect.php";
//$nid = $_SESSION["nid"];
$result = $db->query("SELECT nurse.nid, nurse.name, nurse.last_name, nurse.city, nurse.state, nurse.price, nurse.photos AS pic, description_skills.description FROM nurse INNER JOIN description_skills ON nurse.nid = description_skills.d_nid");
//Initialize array variable
$dbdata = array();
//Fetch into associative array
while ( $row = $result->fetch_assoc()) {
$dbdata[]=$row;
}
//Print array in JSON format
echo json_encode($dbdata);
$db->close();
?>
| true |
7486dee545e85b22725b091ba06ca58bedbbbee3 | PHP | 547358880/myFirstFramework | /lib/Log/Log.php | UTF-8 | 1,353 | 2.84375 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: xujing
* Date: 2016/6/17
* Time: 13:09
* Description
*/
namespace Cake\Log;
class Log
{
protected static $dsnClassMap = array(
'console' => 'Cake\Log\Engine\ConsoleLog',
'file' => 'Cake\Log\Engine\FileLog',
'syslog' => 'Cake\Log\Engine\SyslogLog'
);
protected static $dirtyConfig = false;
/*
* LogEngineRegistery class
*/
protected static $registry;
protected static $levels = array(
'error'
);
protected static $levelMap = array(
'error' => LOG_ERR
);
/*
* Initializes register and configurations
*/
protected static function init()
{
if (empty(static::$registry)) {
static::$registry = new LogEngineRegistery();
}
if (static::$dirtyConfig) {
echo '111';
}
static::$dirtyConfig = false;
}
/*
* Writes the given message and type to call of the configured log
* ### Levels:
*
* ### Basic usage
*
* Write a 'warning' message to the logs:
*
* ```
* Log::write('warning', 'Stuff is broken here');
* ```
*
* ### Using scopes
*/
public static function write($level, $message, $context = array())
{
static::init();
die('dasd');
}
} | true |
53f1a422437f6533ead02699e07d59389a7cfbd8 | PHP | e-novinfo/csvparsertohtml | /app/Helpers/TemplateHelper.php | UTF-8 | 4,464 | 3.28125 | 3 | [] | no_license | <?php
/**
* CSVParserToHTML - TemplateHelper
*
* @since 26.04.2017
*
* @version 1.0.0.0
*
* @author e-novinfo
* @copyright e-novinfo 2017
*/
namespace enovinfo\CSVParserToHTML\Helpers;
class TemplateHelper
{
/********************************/
/********** PROPERTIES **********/
/********************************/
/**
* @var string $folder where the template to load is
* @var string $file the filename of the template to load
* @var array $values array of values for replacing each tag on the template (the key for each value is its corresponding tag)
*/
protected $folder;
protected $file;
protected $values = array();
/*********************************************************************************/
/*********************************************************************************/
/*******************************/
/********** CONSTRUCT **********/
/*******************************/
/**
* @param string $folder where the template to load is
* @param string $file the filename of the template to load
*/
public function __construct($folder = null, $file)
{
$this->_setValues($folder, $file);
}
/*********************************************************************************/
/*********************************************************************************/
/*****************************/
/********** SETTERS **********/
/*****************************/
/**********/
/********** SET VALUES **********/
/**********/
/**
* @param string $folder where the template to load is
* @param string $file the filename of the template to load
*/
private function _setValues($folder, $file)
{
$this->_setFolder($folder);
$this->_setFile($file);
}
/**********/
/********** FOLDER **********/
/**********/
/**
* @param string $folder where the template to load is
*/
private function _setFolder($folder)
{
if (!empty($folder)) {
$this->folder = $folder;
} else {
$this->folder = __DIR__ . '/../../views/';
}
}
/**********/
/********** FILE **********/
/**********/
/**
* @param string $file the filename of the template to load
*/
private function _setFile($file)
{
$this->file = $file;
}
/**********/
/********** DATA **********/
/**********/
/**
* @param string $key the name of the tag to replace
* @param string $value the value to replace
*/
public function set($key, $value)
{
$this->values[$key] = $value;
}
/*********************************************************************************/
/*********************************************************************************/
/****************************/
/********** OUTPUT **********/
/****************************/
/**
* @return string
*/
public function output()
{
$filePath = __DIR__ . '/../../views/' . $this->file;
if (!file_exists($filePath)) {
return "Error loading template file ($this->file).<br />";
}
$output = file_get_contents($filePath);
foreach ($this->values as $key => $value) {
$tagToReplace = "[@$key]";
$output = str_replace($tagToReplace, $value, $output);
}
return $output;
}
/*********************************************************************************/
/*********************************************************************************/
/***************************/
/********** MERGE **********/
/***************************/
/**
* @param array $templates an array of Template objects to merge
* @param string $separator the string that is used between each Template object
* @return string
*/
public static function merge($templates, $separator = "\n")
{
$output = "";
foreach ($templates as $template) {
$content = (get_class($template) !== "enovinfo\CSVParserToHTML\Helpers\TemplateHelper") ? "Error, incorrect type - expected Template." : $template->output();
$output .= $content . $separator;
}
return $output;
}
}
| true |
ffd0c5c6b5a5495e26c94170e14a59cf54394d16 | PHP | webdevgods/WdgImageGallery | /src/WdgImageGallery/Options/ModuleOptionsInterface.php | UTF-8 | 462 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
namespace WdgImageGallery\Options;
interface ModuleOptionsInterface
{
public function setImageListElements(array $listElements);
public function getImageListElements();
public function setAlbumListElements(array $listElements);
public function getAlbumListElements();
public function setImageTag($thumbnailImageTag);
/**
* Filebank tag for product specific images
*/
public function getImageTag();
}
| true |
9a17697de491caff6538f2e1de43f10807a47948 | PHP | wells5609/wp-http-api-extension | /WP_HTTP_Response.php | UTF-8 | 1,917 | 2.875 | 3 | [] | no_license | <?php
/**
* class WP_HTTP_Response
*
* Object representation of HTTP response.
*/
class WP_HTTP_Response extends ArrayObject {
public function __construct( $response ){
parent::__construct( $response, ArrayObject::ARRAY_AS_PROPS );
if ( isset( $this->_start_time ) ){
$this->offsetSet( 'request_time', microtime(true) - $this->_start_time );
unset( $this->_start_time );
}
}
public function get_body(){
return $this->offsetGet( 'body' );
}
public function get_cookies(){
return $this->offsetGet( 'cookies' );
}
public function get_headers(){
return $this->offsetGet( 'headers' );
}
public function get_header( $name ){
return $this->offsetExists( 'headers' ) && isset( $this->headers[ $name ] ) ? $this->headers[ $name ] : null;
}
public function get_content_type(){
return $this->get_header( 'content-type' );
}
public function get_response( $part = null ){
if ( $this->offsetExists( 'response' ) ){
if ( empty($part) )
return $this->response;
if ( isset($this->response[ $part ]) )
return $this->response[ $part ];
}
return null;
}
public function is_content_type( $type ){
if ( ! $content_type = $this->get_content_type() )
return null;
if ( $type == $content_type ) return true;
if ( false !== strpos( $content_type, $type ) )
return true;
return false;
}
public function get_body_object(){
if ( $this->offsetExists( 'body' ) ){
if ( $this->is_content_type( 'json' ) ){
return json_decode( $this->body );
} elseif ( $this->is_content_type( 'xml' ) ){
libxml_use_internal_errors();
return simplexml_load_string( $this->body );
} else {
return (object) $this->body; // just for sanity...
}
}
return null;
}
public function __toString(){
if ( ! isset($this['body']) ){
return '';
}
return (string) $this->body;
}
} | true |
46579b9046087500a6d8be6b5197311da2d094ad | PHP | GraffNaStyk/wikipedia | /app/facades/dotter/Has.php | UTF-8 | 1,073 | 2.59375 | 3 | [] | no_license | <?php
namespace App\Facades\Dotter;
class Has
{
public static function check($method, $item = [])
{
if (isset($item[3])) {
if (isset($method[$item[0]][$item[1]][$item[2]][$item[3]]) && !empty($method[$item[0]][$item[1]][$item[2]][$item[3]])) {
return true;
} else {
return false;
}
} else if (isset($item[2])) {
if (isset($method[$item[0]][$item[1]][$item[2]]) && !empty($method[$item[0]][$item[1]][$item[2]])) {
return true;
} else {
return false;
}
} else if (isset($item[1])) {
if (isset($method[$item[0]][$item[1]]) && !empty($method[$item[0]][$item[1]])) {
return true;
} else {
return false;
}
} else {
if (isset($method[$item[0]]) && !empty($method[$item[0]])) {
return true;
} else {
return false;
}
}
}
}
| true |