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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
6107373c023155f11c3bf21acc47367864cd33c4 | PHP | alaminjnu/E-HealthCare | /login/login.php | UTF-8 | 13,989 | 2.625 | 3 | [] | no_license | <?php require_once('../Connections/health.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
if (PHP_VERSION < 6) {
$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
}
$theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
switch ($theType) {
case "text":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "long":
case "int":
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
break;
case "double":
$theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
break;
case "date":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "defined":
$theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
break;
}
return $theValue;
}
}
?>
<?php
// *** Validate request to login to this site.
if (!isset($_SESSION)) {
session_start();
}
$loginFormAction = $_SERVER['PHP_SELF'];
if (isset($_GET['accesscheck'])) {
$_SESSION['PrevUrl'] = $_GET['accesscheck'];
}
if (isset($_POST['username'])) {
$loginUsername=$_POST['username'];
$password=$_POST['password'];
$MM_fldUserAuthorization = "";
$MM_redirectLoginSuccess = "login_successful.php";
$MM_redirectLoginFailed = "login.php";
$MM_redirecttoReferrer = true;
mysql_select_db($database_health, $health);
$LoginRS__query=sprintf("SELECT username, password FROM `user` WHERE username=%s AND password=%s",
GetSQLValueString($loginUsername, "text"), GetSQLValueString($password, "text"));
$LoginRS = mysql_query($LoginRS__query, $health) or die(mysql_error());
$loginFoundUser = mysql_num_rows($LoginRS);
if ($loginFoundUser) {
$loginStrGroup = "";
if (PHP_VERSION >= 5.1) {session_regenerate_id(true);} else {session_regenerate_id();}
//declare two session variables and assign them
$_SESSION['MM_Username'] = $loginUsername;
$_SESSION['MM_UserGroup'] = $loginStrGroup;
if (isset($_SESSION['PrevUrl']) && true) {
$MM_redirectLoginSuccess = $_SESSION['PrevUrl'];
}
header("Location: " . $MM_redirectLoginSuccess );
}
else {
header("Location: ". $MM_redirectLoginFailed );
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>E-health Care</title>
<link rel="icon" href="images/favicon.ico" type="image/x-icon">
</head>
<body>
<div class="page">
<div class="header">
<a href="index.html" id="logo"><img src="images/logo1.jpg" alt=""/></a>
<ul >
<li><a href="index.php" >Home</a></li>
<li><a href="about.php">About</a></li>
<li><a href="doctors.php">Doctors</a> </li>
<li><a href="services.php">Services</a> </li>
<li><a href="register.php">Register</a> </li>
<li class="selected"><a href="login/login.php">Login</a> </li>
</ul>
</div>
<style>
/* Reset CSS */
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, font, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td {
margin: 0;
padding: 0;
border: 0;
outline: 0;
font-size: 100%;
vertical-align: baseline;
background: transparent;
}
.header{
background:url(../images/bg-navigation.jpg) no-repeat center 90px;
width:940px;
margin:0 auto;
height:105px;
padding:36px 10px 0;
}
.header a#logo{
display:block;
float:left;
outline:none;
}
.header a#logo img{
border:none;
}
.header ul{
margin:0;
list-style:none;
padding:13px 0 0;
float:right;
}
.header ul li{
float:left;
margin:0 0 0 63px;
}
.header ul li.selected a,.header ul li a:hover{
color:#f78117;
}
.header ul li a{
font-size:16px;
text-decoration:none;
color:#5e5e5e;
font-family: 'RokkittRegular';
outline:none;
}
body {
background: #DCDDDF url(http://cssdeck.com/uploads/media/items/7/7AF2Qzt.png);
color: #000;
font: 14px Arial;
margin: 0 auto;
padding: 0;
position: relative;
}
h1{ font-size:28px;}
h2{ font-size:26px;}
h3{ font-size:18px;}
h4{ font-size:16px;}
h5{ font-size:14px;}
h6{ font-size:12px;}
h1,h2,h3,h4,h5,h6{ color:#563D64;}
small{ font-size:10px;}
b, strong{ font-weight:bold;}
a{ text-decoration: none; }
a:hover{ text-decoration: underline; }
.left { float:left; }
.right { float:right; }
.alignleft { float: left; margin-right: 15px; }
.alignright { float: right; margin-left: 15px; }
.clearfix:after,
form:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
.container { margin: 25px auto; position: relative; width: 900px; }
#content {
background: #f9f9f9;
background: -moz-linear-gradient(top, rgba(248,248,248,1) 0%, rgba(249,249,249,1) 100%);
background: -webkit-linear-gradient(top, rgba(248,248,248,1) 0%,rgba(249,249,249,1) 100%);
background: -o-linear-gradient(top, rgba(248,248,248,1) 0%,rgba(249,249,249,1) 100%);
background: -ms-linear-gradient(top, rgba(248,248,248,1) 0%,rgba(249,249,249,1) 100%);
background: linear-gradient(top, rgba(248,248,248,1) 0%,rgba(249,249,249,1) 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f8f8f8', endColorstr='#f9f9f9',GradientType=0 );
-webkit-box-shadow: 0 1px 0 #fff inset;
-moz-box-shadow: 0 1px 0 #fff inset;
-ms-box-shadow: 0 1px 0 #fff inset;
-o-box-shadow: 0 1px 0 #fff inset;
box-shadow: 0 1px 0 #fff inset;
border: 1px solid #c4c6ca;
margin: 0 auto;
padding: 25px 0 0;
position: relative;
text-align: center;
text-shadow: 0 1px 0 #fff;
width: 400px;
}
#content h1 {
color: #7E7E7E;
font: bold 25px Helvetica, Arial, sans-serif;
letter-spacing: -0.05em;
line-height: 20px;
margin: 10px 0 30px;
}
#content h1:before,
#content h1:after {
content: "";
height: 1px;
position: absolute;
top: 10px;
width: 27%;
}
#content h1:after {
background: rgb(126,126,126);
background: -moz-linear-gradient(left, rgba(126,126,126,1) 0%, rgba(255,255,255,1) 100%);
background: -webkit-linear-gradient(left, rgba(126,126,126,1) 0%,rgba(255,255,255,1) 100%);
background: -o-linear-gradient(left, rgba(126,126,126,1) 0%,rgba(255,255,255,1) 100%);
background: -ms-linear-gradient(left, rgba(126,126,126,1) 0%,rgba(255,255,255,1) 100%);
background: linear-gradient(left, rgba(126,126,126,1) 0%,rgba(255,255,255,1) 100%);
right: 0;
}
#content h1:before {
background: rgb(126,126,126);
background: -moz-linear-gradient(right, rgba(126,126,126,1) 0%, rgba(255,255,255,1) 100%);
background: -webkit-linear-gradient(right, rgba(126,126,126,1) 0%,rgba(255,255,255,1) 100%);
background: -o-linear-gradient(right, rgba(126,126,126,1) 0%,rgba(255,255,255,1) 100%);
background: -ms-linear-gradient(right, rgba(126,126,126,1) 0%,rgba(255,255,255,1) 100%);
background: linear-gradient(right, rgba(126,126,126,1) 0%,rgba(255,255,255,1) 100%);
left: 0;
}
#content:after,
#content:before {
background: #f9f9f9;
background: -moz-linear-gradient(top, rgba(248,248,248,1) 0%, rgba(249,249,249,1) 100%);
background: -webkit-linear-gradient(top, rgba(248,248,248,1) 0%,rgba(249,249,249,1) 100%);
background: -o-linear-gradient(top, rgba(248,248,248,1) 0%,rgba(249,249,249,1) 100%);
background: -ms-linear-gradient(top, rgba(248,248,248,1) 0%,rgba(249,249,249,1) 100%);
background: linear-gradient(top, rgba(248,248,248,1) 0%,rgba(249,249,249,1) 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f8f8f8', endColorstr='#f9f9f9',GradientType=0 );
border: 1px solid #c4c6ca;
content: "";
display: block;
height: 100%;
left: -1px;
position: absolute;
width: 100%;
}
#content:after {
-webkit-transform: rotate(2deg);
-moz-transform: rotate(2deg);
-ms-transform: rotate(2deg);
-o-transform: rotate(2deg);
transform: rotate(2deg);
top: 0;
z-index: -1;
}
#content:before {
-webkit-transform: rotate(-3deg);
-moz-transform: rotate(-3deg);
-ms-transform: rotate(-3deg);
-o-transform: rotate(-3deg);
transform: rotate(-3deg);
top: 0;
z-index: -2;
}
#content form { margin: 0 20px; position: relative }
#content form input[type="text"],
#content form input[type="password"] {
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
-ms-border-radius: 3px;
-o-border-radius: 3px;
border-radius: 3px;
-webkit-box-shadow: 0 1px 0 #fff, 0 -2px 5px rgba(0,0,0,0.08) inset;
-moz-box-shadow: 0 1px 0 #fff, 0 -2px 5px rgba(0,0,0,0.08) inset;
-ms-box-shadow: 0 1px 0 #fff, 0 -2px 5px rgba(0,0,0,0.08) inset;
-o-box-shadow: 0 1px 0 #fff, 0 -2px 5px rgba(0,0,0,0.08) inset;
box-shadow: 0 1px 0 #fff, 0 -2px 5px rgba(0,0,0,0.08) inset;
-webkit-transition: all 0.5s ease;
-moz-transition: all 0.5s ease;
-ms-transition: all 0.5s ease;
-o-transition: all 0.5s ease;
transition: all 0.5s ease;
background: #eae7e7 url(http://cssdeck.com/uploads/media/items/8/8bcLQqF.png) no-repeat;
border: 1px solid #c8c8c8;
color: #777;
font: 13px Helvetica, Arial, sans-serif;
margin: 0 0 10px;
padding: 15px 10px 15px 40px;
width: 80%;
}
#content form input[type="text"]:focus,
#content form input[type="password"]:focus {
-webkit-box-shadow: 0 0 2px #ed1c24 inset;
-moz-box-shadow: 0 0 2px #ed1c24 inset;
-ms-box-shadow: 0 0 2px #ed1c24 inset;
-o-box-shadow: 0 0 2px #ed1c24 inset;
box-shadow: 0 0 2px #ed1c24 inset;
background-color: #fff;
border: 1px solid #ed1c24;
outline: none;
}
#username { background-position: 10px 10px !important }
#password { background-position: 10px -53px !important }
#content form input[type="submit"] {
background: rgb(254,231,154);
background: -moz-linear-gradient(top, rgba(254,231,154,1) 0%, rgba(254,193,81,1) 100%);
background: -webkit-linear-gradient(top, rgba(254,231,154,1) 0%,rgba(254,193,81,1) 100%);
background: -o-linear-gradient(top, rgba(254,231,154,1) 0%,rgba(254,193,81,1) 100%);
background: -ms-linear-gradient(top, rgba(254,231,154,1) 0%,rgba(254,193,81,1) 100%);
background: linear-gradient(top, rgba(254,231,154,1) 0%,rgba(254,193,81,1) 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fee79a', endColorstr='#fec151',GradientType=0 );
-webkit-border-radius: 30px;
-moz-border-radius: 30px;
-ms-border-radius: 30px;
-o-border-radius: 30px;
border-radius: 30px;
-webkit-box-shadow: 0 1px 0 rgba(255,255,255,0.8) inset;
-moz-box-shadow: 0 1px 0 rgba(255,255,255,0.8) inset;
-ms-box-shadow: 0 1px 0 rgba(255,255,255,0.8) inset;
-o-box-shadow: 0 1px 0 rgba(255,255,255,0.8) inset;
box-shadow: 0 1px 0 rgba(255,255,255,0.8) inset;
border: 1px solid #D69E31;
color: #85592e;
cursor: pointer;
float: left;
font: bold 15px Helvetica, Arial, sans-serif;
height: 35px;
margin: 20px 0 35px 15px;
position: relative;
text-shadow: 0 1px 0 rgba(255,255,255,0.5);
width: 120px;
}
#content form input[type="submit"]:hover {
background: rgb(254,193,81);
background: -moz-linear-gradient(top, rgba(254,193,81,1) 0%, rgba(254,231,154,1) 100%);
background: -webkit-linear-gradient(top, rgba(254,193,81,1) 0%,rgba(254,231,154,1) 100%);
background: -o-linear-gradient(top, rgba(254,193,81,1) 0%,rgba(254,231,154,1) 100%);
background: -ms-linear-gradient(top, rgba(254,193,81,1) 0%,rgba(254,231,154,1) 100%);
background: linear-gradient(top, rgba(254,193,81,1) 0%,rgba(254,231,154,1) 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fec151', endColorstr='#fee79a',GradientType=0 );
}
#content form div a {
color: #004a80;
float: right;
font-size: 12px;
margin: 30px 15px 0 0;
text-decoration: underline;
}
.button {
background: rgb(247,249,250);
background: -moz-linear-gradient(top, rgba(247,249,250,1) 0%, rgba(240,240,240,1) 100%);
background: -webkit-linear-gradient(top, rgba(247,249,250,1) 0%,rgba(240,240,240,1) 100%);
background: -o-linear-gradient(top, rgba(247,249,250,1) 0%,rgba(240,240,240,1) 100%);
background: -ms-linear-gradient(top, rgba(247,249,250,1) 0%,rgba(240,240,240,1) 100%);
background: linear-gradient(top, rgba(247,249,250,1) 0%,rgba(240,240,240,1) 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f7f9fa', endColorstr='#f0f0f0',GradientType=0 );
-webkit-box-shadow: 0 1px 2px rgba(0,0,0,0.1) inset;
-moz-box-shadow: 0 1px 2px rgba(0,0,0,0.1) inset;
-ms-box-shadow: 0 1px 2px rgba(0,0,0,0.1) inset;
-o-box-shadow: 0 1px 2px rgba(0,0,0,0.1) inset;
box-shadow: 0 1px 2px rgba(0,0,0,0.1) inset;
-webkit-border-radius: 0 0 5px 5px;
-moz-border-radius: 0 0 5px 5px;
-o-border-radius: 0 0 5px 5px;
-ms-border-radius: 0 0 5px 5px;
border-radius: 0 0 5px 5px;
border-top: 1px solid #CFD5D9;
padding: 15px 0;
}
.button a {
background: url(http://cssdeck.com/uploads/media/items/8/8bcLQqF.png) 0 -112px no-repeat;
color: #7E7E7E;
font-size: 17px;
padding: 2px 0 2px 40px;
text-decoration: none;
-webkit-transition: all 0.3s ease;
-moz-transition: all 0.3s ease;
-ms-transition: all 0.3s ease;
-o-transition: all 0.3s ease;
transition: all 0.3s ease;
}
.button a:hover {
background-position: 0 -135px;
color: #00aeef;
}
</style>
</head>
<body>
<div class="container">
<section id="content">
<form name="form1" action="<?php echo $loginFormAction; ?>" method="POST">
<h1>Login Form</h1>
<div>
<input name="username" type="text" placeholder="Username" required id="username" />
</div>
<div>
<input name="password" type="password" placeholder="Password" required id="password" />
</div>
<div>
<input type="submit" name="submit" value="Log in" />
<a href="register.php">Register</a>
</div>
</form><!-- form -->
<div class="button">
<a href="index.php">©-E-health Care</a>
</div><!-- button -->
</section><!-- content -->
</div><!-- container -->
</body>
</html> | true |
82aecd7d2e3cafefdf16e8bdacc44c9d535ebc95 | PHP | Sywooch/other | /taozon.ru [PHP]/otapilib2/types/OtapiDataListOfExternalDeliveryType.php | UTF-8 | 321 | 2.53125 | 3 | [] | no_license | <?php
class OtapiDataListOfExternalDeliveryType extends BaseOtapiType{
/**
* @return OtapiArrayOfExternalDeliveryType
*/
public function GetContent(){
$value = isset($this->xmlData->Content) ? $this->xmlData->Content : false;
return new OtapiArrayOfExternalDeliveryType($value);
}
} | true |
9cc6ff441f657cc5f780f7584e75199d9518ce86 | PHP | civils-council/civilsbudget | /src/AppBundle/Exception/TurboSmsException.php | UTF-8 | 767 | 3.015625 | 3 | [] | no_license | <?php
declare(strict_types=1);
namespace AppBundle\Exception;
use Throwable;
/**
* Class TurboSmsException.
*/
class TurboSmsException extends \Exception
{
/**
* @var string
*/
private $smsText;
/**
* TurboSmsException constructor.
*
* @param string $message
* @param string $smsText
* @param int $code
* @param Throwable|null $previous
*/
public function __construct($message = '', $smsText = '', $code = 0, Throwable $previous = null)
{
parent::__construct($message, $code, $previous);
$this->smsText = $smsText;
}
/**
* @return null|string
*/
public function getSmsText(): ?string
{
return $this->smsText;
}
}
| true |
6969da5da3f16e3aba083998248084215f50e487 | PHP | m0o0m/game.fjbdsh.com | /simplewind/Core/Library/Vendor/PHPExcel/PHPExcel/HashTable.php | UTF-8 | 1,945 | 3.03125 | 3 | [
"Apache-2.0"
] | permissive | <?php
class PHPExcel_HashTable
{
public $_items = array();
public $_keyMap = array();
public function __construct($pSource = null)
{
if ($pSource !== NULL) {
$this->addFromSource($pSource);
}
}
public function addFromSource($pSource = null)
{
if ($pSource == null) {
return;
} else if (!is_array($pSource)) {
throw new PHPExcel_Exception('Invalid array parameter passed.');
}
foreach ($pSource as $item) {
$this->add($item);
}
}
public function add(PHPExcel_IComparable $pSource = null)
{
$hash = $pSource->getHashCode();
if (!isset($this->_items[$hash])) {
$this->_items[$hash] = $pSource;
$this->_keyMap[count($this->_items) - 1] = $hash;
}
}
public function remove(PHPExcel_IComparable $pSource = null)
{
$hash = $pSource->getHashCode();
if (isset($this->_items[$hash])) {
unset($this->_items[$hash]);
$deleteKey = -1;
foreach ($this->_keyMap as $key => $value) {
if ($deleteKey >= 0) {
$this->_keyMap[$key - 1] = $value;
}
if ($value == $hash) {
$deleteKey = $key;
}
}
unset($this->_keyMap[count($this->_keyMap) - 1]);
}
}
public function clear()
{
$this->_items = array();
$this->_keyMap = array();
}
public function count()
{
return count($this->_items);
}
public function getIndexForHashCode($pHashCode = '')
{
return array_search($pHashCode, $this->_keyMap);
}
public function getByIndex($pIndex = 0)
{
if (isset($this->_keyMap[$pIndex])) {
return $this->getByHashCode($this->_keyMap[$pIndex]);
}
return null;
}
public function getByHashCode($pHashCode = '')
{
if (isset($this->_items[$pHashCode])) {
return $this->_items[$pHashCode];
}
return null;
}
public function toArray()
{
return $this->_items;
}
public function __clone()
{
$vars = get_object_vars($this);
foreach ($vars as $key => $value) {
if (is_object($value)) {
$this->$key = clone $value;
}
}
}
} | true |
7c8c8ebd65b1dacd0d079cf5de2df79e14fd0bae | PHP | Ytsellout/ytsellout | /Admin/delete.php | UTF-8 | 1,779 | 2.53125 | 3 | [] | no_license | <?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ytsellout";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// sql to delete a record
$prodcode = $_POST['delete'];
$sql = "SELECT ownerid, productid FROM temp_product WHERE productid = '".$prodcode."'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$owner = $row["ownerid"];
}
} else {
echo "0 results";
}
$sql = "SELECT user_code, user_catagory FROM user_info WHERE user_code = '".$owner."'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
if($row["ownerid"] == "Seller") {
$sub = "sell";
}else{
$sub = "buy";
}
}
} else {
echo "0 results";
}
$noti = $sub . $owner . "01";
echo $noti;
$sql = "DELETE FROM temp_product WHERE productid='".$_POST['delete']."'";
if (mysqli_query($conn, $sql)) {
$sql = "INSERT INTO $noti (notification)
VALUES ('Sorry Your product has not been register to our site because it is not accourding to our company policy your payment will soon transfer to your account and our public consultant will soon contact with you thankyou')";
if (mysqli_query($conn, $sql)) {
header("location:http://localhost/Akhil/Admin/varification.php");
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
| true |
04dc61978d4209e4e2d9ac9e3e9a452b5f9ff69e | PHP | aedart/athenaeum | /packages/Validation/src/Rules/DateFormat.php | UTF-8 | 2,856 | 3.359375 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
namespace Aedart\Validation\Rules;
use Carbon\Exceptions\InvalidFormatException;
use Closure;
use Illuminate\Support\Carbon;
use ValueError;
/**
* Date Format Validation Rule
*
* Ensures given attribute is a date string according to an allowed format.
*
* @author Alin Eugen Deac <aedart@gmail.com>
* @package Aedart\Validation\Rules
*/
class DateFormat extends BaseValidationRule
{
/**
* Allowed formats
*
* @var string[]
*/
protected array $formats;
/**
* Create new instance of validation rule
*
* @param string ...$formats
*/
public function __construct(...$formats)
{
$this->formats = $formats;
}
/**
* @inheritDoc
*/
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if (!$this->isValid($value)) {
$fail('validation.date_format')->translate([
'attribute' => $attribute,
'format' => $this->formats[0]
]);
}
}
/**
* Determine if given date is valid (can be created acc. to allowed format)
*
* @param mixed $value
*
* @return bool
*/
public function isValid(mixed $value): bool
{
if (empty($value) || (!is_string($value) && !is_numeric($value))) {
return false;
}
foreach ($this->formats as $format) {
try {
$date = Carbon::createFromFormat('!' . $format, $value);
// Skip to next format, if unable to create by format
if ($date === false) {
continue;
}
// Pass, if exported format matches the string date (just like Laravel's
// 'date_format' validation rule )
if ($date->format($format) == $value) {
return true;
}
// Edge-case: if the format contains 'p' token (timezone offset), e.g. RCF 3339 Extended Zulu,
// then the "format()" output comparison might fail if +00:00 timezone offset is submitted.
// The output of the format converts +00:00 to 'Z', which then fails format output comparison.
if (
(str_contains($format, 'p') && !str_contains($format, '\\p')) // Only when unescaped 'p' token is present
&& (str_ends_with($value, '+00:00') || str_ends_with($value, '-00:00'))
&& $date->eq($value)
) {
return true;
}
} catch (ValueError|InvalidFormatException $e) {
// Ignore value error / format exceptions. This is important when there are multiple
// allowed formats...
continue;
}
}
return false;
}
}
| true |
d69e79cbb7674e9d559ffad47bbe6d9c47bdcba6 | PHP | henarozz/Txwitch7 | /app/txwitch/Controller/AppController.php | UTF-8 | 2,937 | 2.671875 | 3 | [
"MIT"
] | permissive | <?php
/**
* Txwitch
*
* @author Alexander Makhin <henarozz@gmail.com>
*/
namespace Txwitch\Controller;
use Psr\Container\ContainerInterface;
use Slim\Http\Request;
use Slim\Http\Response;
use Txwitch\Component\Security;
/**
* AppController Class
*
* @package Txwitch\Controller
*/
class AppController
{
/**
* DI Container
*
* @Inject
* @var ContainerInterface
*/
protected $container;
/**
* Security component
*
* @var Security
*/
private $security;
/**
* Settings array
*
* @var array
*/
private $settings;
/**
* AppController constructor
*
* @param ContainerInterface $container
*/
public function __construct(ContainerInterface $container)
{
$this->container = $container;
$this->security = $this->container->get('security');
$this->settings = $this->container->get('settings');
}
/**
* Method to control the actions on route </app/login>
*
* @param Request $request
* @param Response $response
* @param array $args
* @return Response
*/
public function login(Request $request, Response $response, array $args): Response
{
switch ($request->getMethod()) {
case 'GET':
$view = $this->container->get('view');
return $view->render(
$response,
'login.phtml',
['header' => 'Txwitch']
);
break;
case 'POST':
$trueAuthCredentials = $this->settings['authCredentials'];
$userAuthCredentials['username'] = $request->getParam('username');
$userAuthCredentials['password'] = $request->getParam('password');
if ($this->security->passAuth($trueAuthCredentials, $userAuthCredentials)) {
$this->security->setAuthSession();
$response = $response->withStatus(302)->withHeader('Location', '/games');
} else {
$response = $response->withStatus(302)->withHeader('Location', '/app/login');
}
return $response;
break;
default:
$response = $response->withStatus(302)->withHeader('Location', '/app/login');
return $response;
break;
}
}
/**
* Method to control the action on route </app/logout>
*
* @param Request $request
* @param Response $response
* @param array $args
* @return Response
*/
public function logout(Request $request, Response $response, array $args): Response
{
$this->security->unsetAuthSession();
return $response->withStatus(302)->withHeader('Location', '/app/login');
}
}
| true |
9a8e3b10d23282c32421c1e19a84c02f175a8d25 | PHP | Leereal/zimgeneral | /app/Http/Controllers/API/EmployeeController.php | UTF-8 | 3,370 | 2.5625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use App\Http\Resources\EmployeeResource;
use App\Models\Branch;
use App\Models\Employee;
use Illuminate\Http\Request;
class EmployeeController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$employee = Employee::active()->latest()->get();
return EmployeeResource::collection($employee);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'firstname' => ['required', 'string', 'max:255'],
'surname' => ['required', 'string', 'max:255'],
'cellphone' => ['required', 'string', 'regex:/^([0-9\s\-\+\(\)]*)$/', 'min:7', 'max:30'],
'job_title' => ['required', 'string', 'max:255'],
'branch' => 'required|integer',
]);
$employee = new Employee;
$employee->employee_code = strtoupper(substr(Branch::where('id',$request->branch)->value('name'),0,3).rand(100,999));
$employee->branch_id = $request->branch;
$employee->firstname = $request->firstname;
$employee->surname = $request->surname;
$employee->cellphone = $request->cellphone;
$employee->job_title = $request->job_title;
if($employee->save()){
return new EmployeeResource($employee);
}
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$employee = Employee::find($id);
return new EmployeeResource($employee);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$request->validate([
'firstname' => ['required', 'string', 'max:255'],
'surname' => ['required', 'string', 'max:255'],
'cellphone' => ['required', 'string', 'regex:/^([0-9\s\-\+\(\)]*)$/', 'min:7', 'max:30'],
'job_title' => ['required', 'string', 'max:255'],
'branch' => 'required|integer',
]);
$employee = Employee::findOrFail($id);
$employee->branch_id = $request->branch;
$employee->firstname = $request->firstname;
$employee->surname = $request->surname;
$employee->cellphone = $request->cellphone;
$employee->job_title = $request->job_title;
if($employee->save()){
return new EmployeeResource($employee);
}
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$employee = Employee::findOrFail($id);
if($employee->delete()){
return new EmployeeResource($employee);
}
}
}
| true |
be2aaf26ab84f711b9f3f4efdc4ef638a61a9ac1 | PHP | josuecamelo/phpunittests | /tests/Alura/Leilao/Tests/Service/AvaliadorTest.php | UTF-8 | 2,429 | 2.578125 | 3 | [] | no_license | <?php
namespace Alura\Leilao\Tests\Service;
use Alura\Leilao\Model\Lance;
use Alura\Leilao\Model\Leilao;
use Alura\Leilao\Model\Usuario;
use Alura\Leilao\Service\Avaliador;
use PHPUnit\Framework\TestCase;
class AvaliadorTest extends TestCase
{
public function testAvaliadorDeveEncontrarMaiorValorDeLancesEmOrdemCrescente()
{
$leilao = new Leilao('Fiat 147 0KM');
$maria = new Usuario('Maria');
$joao = new Usuario('João');
$leilao->recebeLance(new Lance($joao, 2000));
$leilao->recebeLance(new Lance($maria, 2500));
$leiloeiro = new Avaliador();
$leiloeiro->avalia($leilao);
$maiorValor = $leiloeiro->getMaiorValor();
self::assertEquals(2500, $maiorValor);
}
public function testAvaliadorDeveEncontrarMaiorValorDeLancesEmOrdemDecrescente()
{
$leilao = new Leilao('Fiat 147 0KM');
$maria = new Usuario('Maria');
$joao = new Usuario('João');
$leilao->recebeLance(new Lance($maria, 2500));
$leilao->recebeLance(new Lance($joao, 2000));
$leiloeiro = new Avaliador();
$leiloeiro->avalia($leilao);
$maiorValor = $leiloeiro->getMaiorValor();
self::assertEquals(2500, $maiorValor);
}
public function testAvaliadorDeveEncontrarMenorValorDeLancesEmOrdemDecrescente()
{
$leilao = new Leilao('Fiat 147 0KM');
$maria = new Usuario('Maria');
$joao = new Usuario('João');
$leilao->recebeLance(new Lance($maria, 2500));
$leilao->recebeLance(new Lance($joao, 2000));
$leiloeiro = new Avaliador();
$leiloeiro->avalia($leilao);
$menorValor = $leiloeiro->getMenorValor();
self::assertEquals(2000, $menorValor);
}
public function testAvaliadorDeveEncontrarMenorValorDeLancesEmOrdemCrescente()
{
$leilao = new Leilao('Fiat 147 0KM');
$maria = new Usuario('Maria');
$joao = new Usuario('João');
$leilao->recebeLance(new Lance($joao, 2000));
$leilao->recebeLance(new Lance($maria, 2500));
$leiloeiro = new Avaliador();
$leiloeiro->avalia($leilao);
$menorValor = $leiloeiro->getMenorValor();
self::assertEquals(2000, $menorValor);
}
}
| true |
8168b86886799be58dcb6f825a67cae7b50b90ca | PHP | claremontdesign/zbase | /src/Ui/Form/Type/Select.php | UTF-8 | 3,007 | 2.859375 | 3 | [] | no_license | <?php
namespace Zbase\Ui\Form\Type;
/**
* Zbase-Form Element-Text
*
* Element-Select
*
* @link http://zbase.dennesabing.com
* @author Dennes B Abing <dennes.b.abing@gmail.com>
* @license proprietary
* @copyright Copyright (c) 2016 ClaremontDesign/MadLabs-Dx
* @file Select.php
* @project Zbase
* @package Zbase/Ui/Form/Elements
*/
class Select extends \Zbase\Ui\Form\Type\Multi
{
/**
* Widget Type
* @var string
*/
protected $_type = 'select';
/**
* The view File to use
* @var string
*/
protected $_viewFile = 'ui.form.type.select';
/**
* The empty option
* null
* boolean: true|false
* array: [value => the Value, label => The Empty Label]
* @var boolean|array
*/
protected $_emptyOption = null;
protected $_multipleValues = false;
/**
* Multiple VAlues
* @param type $multipleValues
* @return \Zbase\Ui\Form\Type\Multi
*/
public function setMultipleValues($multipleValues)
{
$this->_multipleValues = $multipleValues;
return $this;
}
/**
* SEt the Empty Option
* @param boolean|array|null $emptyOption
* @return \Zbase\Ui\Form\Type\Select
*/
public function setEmptyOption($emptyOption)
{
$this->_emptyOption = $emptyOption;
return $this;
}
/**
* The Input name
* @return string
*/
public function inputName()
{
if(!empty($this->_multipleValues))
{
return $this->name() . '[]';
}
return $this->name();
}
/**
* Return the empty options
* @return boolean|array|null
*/
public function getEmptyOption()
{
return $this->_emptyOption;
}
/**
* Render the multioptions
* @return string
*/
public function renderMultiOptions()
{
$multiOptions = $this->getMultiOptions();
if(!empty($multiOptions))
{
$options = [];
$emptyOption = $this->getEmptyOption();
if(!empty($emptyOption))
{
if(is_array($emptyOption) && !empty($emptyOption['enable']))
{
$options[] = '<option value="' . (!empty($emptyOption['value']) ? $emptyOption['value'] : '') . '">' . (!empty($emptyOption['label']) ? $emptyOption['label'] : '') . '</option>';
}
if(is_bool($emptyOption))
{
$options[] = '<option value="">Select...</option>';
}
}
if(!empty($this->_multipleValues))
{
if(!empty($this->getValue()))
{
if(is_array($this->getValue()))
{
$values = $this->getValue();
} else {
$values = explode(',', $this->getValue());
}
}
}
$selected = '';
foreach ($multiOptions as $k => $v)
{
if(!empty($this->_multipleValues))
{
if(!empty($values))
{
$selected = in_array($k, $values) ? ' selected="selected"' : '';
}
}
else
{
$selected = $this->getValue() == $k ? ' selected="selected"' : '';
}
$options[] = '<option value="' . $k . '"' . $selected . '>' . $v . '</option>';
}
return implode('', $options);
}
return '';
}
}
| true |
1b4b86ad2d61ffcecb1d9892e8368f122af32b28 | PHP | ariezncahyo/php-crawler-test-work | /tests/HandlerTest.php | UTF-8 | 1,988 | 2.859375 | 3 | [] | no_license | <?php
namespace tests;
require_once(__DIR__ . '/../vendor/autoload.php');
use src\Crawler;
use src\Handler;
use src\writers\HtmlWriter;
/**
* Handler Test
* @package tests
*/
class HandlerTest extends \PHPUnit_Framework_TestCase
{
public $crawler;
public $writer;
/**
* @inheritdoc
*/
protected function setUp()
{
$this->crawler = new Crawler();
$this->writer = new HtmlWriter();
}
public function testValidateUrl()
{
$error = false;
try {
$handler = new Handler([
'url' => 'http://site.ru',
], $this->crawler, $this->writer);
} catch (\Exception $e) {
$error = true;
}
$this->assertFalse($error);
}
public function testValidateDepth()
{
$error = false;
try {
$handler = new Handler([
'url' => 'http://site.ru',
'depth' => 7,
], $this->crawler, $this->writer);
} catch (\Exception $e) {
$error = true;
}
$this->assertFalse($error);
}
public function testErrorValidateUrl()
{
$error = false;
try {
$handler = new Handler([
'url' => 'test',
], $this->crawler, $this->writer);
} catch (\Exception $e) {
$error = $e->getMessage();
}
$this->assertEquals($error, 'Param "url" is not a valid URL. Please enter valid value: --url=http://site.ru');
}
public function testErrorValidateDepth()
{
$error = false;
try {
$handler = new Handler([
'url' => 'http://site.ru',
'depth' => 'test',
], $this->crawler, $this->writer);
} catch (\Exception $e) {
$error = $e->getMessage();
}
$this->assertEquals($error, 'Param "depth" is not a valid integer. Please enter valid value: --depth=5');
}
}
| true |
9f0a3b61555c650c76dc699b219b1699c12c9100 | PHP | antonioTov/casino-zend | /application/forms/AddEdit.php | WINDOWS-1251 | 3,050 | 2.609375 | 3 | [] | no_license | <?php
class Application_Form_AddEdit extends Zend_Form
{
public function init()
{
$emptyMsg = ' !';
$errorEmail = ' E-mail';
$busyName = ' ';
$this->setMethod('post');
// Username
$username = new Zend_Form_Element_Text('username');
$username->setLabel('Username')
->setRequired(true)
->setAttrib('class', 'f')
->setAttrib('autocomplete', 'off')
->addFilter('StripTags')
->addFilter('StringTrim')
->setDecorators( array('ViewHelper', 'Errors') )
->addValidators( array(
array('NotEmpty', true, array(
'messages' => array(
'isEmpty' => $emptyMsg
)
)),
array('Db_NoRecordExists', false, array(
'table' => 'players',
'field' => 'username',
'messages' => array(
'recordFound' => $busyName
)
))
));
// First name
$firstName = new Zend_Form_Element_Text('first_name');
$firstName->setRequired(true)
->setAttrib('class', 'f')
->addFilter('StripTags')
->addFilter('StringTrim')
->setDecorators( array('ViewHelper', 'Errors') )
->addValidators( array(
array('NotEmpty', true, array('messages' => array(
'isEmpty' => $emptyMsg
)))) );
// Last name
$lastName = new Zend_Form_Element_Text('last_name');
$lastName->setLabel('Last name')
->setRequired(true)
->setAttrib('class', 'f')
->addFilter('StripTags')
->addFilter('StringTrim')
->setDecorators( array('ViewHelper', 'Errors') )
->addValidators( array(
array('NotEmpty', true, array('messages' => array(
'isEmpty' => $emptyMsg
)))) );
// Date of birth
$birthDate = new Zend_Form_Element_Text('birth_date');
$birthDate->setLabel('Date of birth')
->setRequired(true)
->setAttrib('class', 'f')
->setAttrib('id', 'datepicker')
->setAttrib('autocomplete', 'off')
->addFilter('StripTags')
->addFilter('StringTrim')
->setDecorators( array('ViewHelper', 'Errors') )
->addValidators( array(
array('NotEmpty', true, array('messages' => array(
'isEmpty' => $emptyMsg
)))) );
// Email
$email = new Zend_Form_Element_Text('email');
$email->setLabel('E-mail')
->setRequired(true)
->setAttrib('class', 'f')
->addFilter('StripTags')
->addFilter('StringTrim')
->setDecorators( array('ViewHelper', 'Errors') )
->addErrorMessage($errorEmail)
->addValidator('EmailAddress', true );
// -- hidden -- //
// Admin ID
$adminID = new Zend_Form_Element_Hidden( 'admin_id' );
$adminID->setValue( Zend_Auth::getInstance()->getIdentity()->id )
->setDecorators( array('ViewHelper') );
// Player ID
$playerID = new Zend_Form_Element_Hidden( 'player_id' );
$playerID->setDecorators( array('ViewHelper') );
// -- hidden end -- //
$this->setDecorators(array(
array('ViewScript', array('viewScript' => 'forms/AddEdit.phtml'))
));
$this->addElements( array( $username, $firstName, $lastName, $birthDate, $email, $adminID, $playerID ) );
}
} | true |
3a210c30e9b7ff1c3257c7b3e5beea77da70e86c | PHP | ChechoVillarraga/PlanMejoramientoPHP | /Caso3/mvc/modelo/dto/Persona.class.php | UTF-8 | 1,870 | 2.921875 | 3 | [] | no_license | <?php
/**
* Object represents table 'personas'
*
* @author: http://phpdao.com
* @date: 2016-12-06 20:53
*/
class Persona{
private $idPersonas;
private $nombres;
private $apellidos;
private $correo;
private $clave;
private $rolesIdRoles;
private $areaIdArea;
function getIdPersonas() {
return $this->idPersonas;
}
function getNombres() {
return $this->nombres;
}
function getApellidos() {
return $this->apellidos;
}
function getCorreo() {
return $this->correo;
}
function getClave() {
return $this->clave;
}
function getRolesIdRoles() {
return $this->rolesIdRoles;
}
function getAreaIdArea() {
return $this->areaIdArea;
}
function setIdPersonas($idPersonas) {
$this->idPersonas = $idPersonas;
}
function setNombres($nombres) {
$this->nombres = $nombres;
}
function setApellidos($apellidos) {
$this->apellidos = $apellidos;
}
function setCorreo($correo) {
$this->correo = $correo;
}
function setClave($clave) {
$this->clave = $clave;
}
function setRolesIdRoles($rolesIdRoles) {
$this->rolesIdRoles = $rolesIdRoles;
}
function setAreaIdArea($areaIdArea) {
$this->areaIdArea = $areaIdArea;
}
}
?> | true |
352d0d01f418f1cea5a8da5456f5a6cc7248591d | PHP | yii2rails/yii2-extension | /yusrc/account/src/domain/v2/interfaces/services/SocketInterface.php | UTF-8 | 553 | 2.625 | 3 | [
"MIT"
] | permissive | <?php
namespace yubundle\account\domain\v2\interfaces\services;
use yii\base\ErrorException;
use yubundle\account\domain\v2\entities\SocketEventEntity;
/**
* Interface SocketInterface
*
* @package yubundle\account\domain\v2\interfaces\services
*
* @property-read \yubundle\account\domain\v2\Domain $domain
*/
interface SocketInterface {
/**
* @param SocketEventEntity $event
* @return mixed
* @throws ErrorException
*/
public function sendMessage(SocketEventEntity $event);
public function startServer();
}
| true |
8ec4d7e4c165519a445d071f060a9f13cd50fa71 | PHP | RicentCB/adoo_final | /controller/users.controller.php | UTF-8 | 11,372 | 2.5625 | 3 | [] | no_license | <?php
class ControllerUsers{
/*===========================================
I N G R E S O D E U S U A R I O S
===========================================*/
static public function ctrLoginUser(){
if(isset($_POST["ingUser"])){
//Intento de Logeo
if((preg_match('/^[a-zA-Z0-9]+$/', $_POST["ingUser"]))
&& (preg_match('/^[a-zA-Z0-9]+$/', $_POST["ingPassword"]))){
$tabla = "usuarios"; //Nombre de la Tabla
$item = "usuario"; //Columna a Verficar
$valor = $_POST["ingUser"];
//Encriptar contraseña
$crPassword = crypt($_POST["ingPassword"], '$2a$08$abb55asfrga85df8g42g8fDDAS58olf973adfacmY28n05$');
$respuesta = ModelUsers::mdlMostrarUsuarios($tabla, $item, $valor);
if($respuesta["usuario"] == $_POST["ingUser"]
&& $respuesta["password"] == $crPassword){
if($respuesta["estado"] == '1'){
//Coincide
$_SESSION["login"] = true;
//Creamos variables de Sesion
$_SESSION["user"] = $respuesta;
//Capturar Fecha y Hora de Login
date_default_timezone_set('America/Mexico_City');
$fechaActual = date('Y-m-d H:i:s');
//
$item1 = "ultimo_login";
$valor1 = $fechaActual;
$item2 = "id_usuario";
$valor2 = $respuesta["id_usuario"];
$ultimoLogin = ModelUsers::mdlActualizarUsuario($tabla, $item1, $valor1, $item2, $valor2);
if($ultimoLogin) //Redireccionando
echo '<script>location.reload(true);</script>';
}else{
echo '<br><div class="alert alert-danger">El usuario no esta activado</div>';
}
}else{
echo '<br><div class="alert alert-danger">Error al ingresar, vuelve a intentarlo</div>';
}
}
}
}
/*===========================================
R E G I S T R O D E U S U A R I O S
===========================================*/
static public function ctrCreateUser(){
if(isset($_POST["nuevoUsuario"])){
if(preg_match('/^[a-zA-Z0-9ñÑáéíóúÁÉÍÓÚ ]+$/',$_POST["nuevoNombre"]) &&
preg_match('/^[a-zA-Z0-9]+$/',$_POST["nuevoUsuario"]) &&
preg_match('/^[a-zA-Z0-9]+$/',$_POST["nuevoPassword"])){
/*========================================
V A L I D A R I M A G E N
========================================*/
$ruta = NULL;
if(isset($_FILES["nuevaFoto"]["tmp_name"]) && $_FILES["nuevaFoto"]["tmp_name"] != ""){
list($ancho, $alto) = getimagesize($_FILES["nuevaFoto"]["tmp_name"]);
$nuevoAncho = 500;
$nuevoAlto = 500;
/*---------------------------------------------
CREAR DIRECTORIO DONDE SE GUARDA LA FOTO
---------------------------------------------*/
$directorio = "view/img/usuarios/".$_POST["nuevoUsuario"];
mkdir($directorio, 0755);
/*---------------------------------------------
DE ACUERDO AL TIPO DE IMAGEN ACCIONES
---------------------------------------------*/
$rand = mt_rand(100, 999);
//------------------ IMAGEN JPEG ------------------
if($_FILES["nuevaFoto"]["type"] == "image/jpeg"){
//Guardamos Imagen en el Directorio
$ruta = "view/img/usuarios/".$_POST["nuevoUsuario"]."/".$rand.".jpeg";
$origen = imagecreatefromjpeg($_FILES["nuevaFoto"]["tmp_name"]);
$destino = imagecreatetruecolor($nuevoAncho, $nuevoAlto);
imagecopyresized($destino, $origen, 0, 0, 0, 0, $nuevoAncho, $nuevoAlto, $ancho, $alto);
imagejpeg($destino, $ruta);
}
if($_FILES["nuevaFoto"]["type"] == "image/png"){
//Guardamos Imagen en el Directorio
$ruta = "view/img/usuarios/".$_POST["nuevoUsuario"]."/".$rand.".png";
$origen = imagecreatefrompng($_FILES["nuevaFoto"]["tmp_name"]);
$destino = imagecreatetruecolor($nuevoAncho, $nuevoAlto);
imagecopyresized($destino, $origen, 0, 0, 0, 0, $nuevoAncho, $nuevoAlto, $ancho, $alto);
imagepng($destino, $ruta);
}
}
$tabla = "usuarios";
$crPassword = crypt($_POST["nuevoPassword"], '$2a$08$abb55asfrga85df8g42g8fDDAS58olf973adfacmY28n05$');
$datos = array(
"nombre"=>$_POST["nuevoNombre"],
"usuario" => $_POST["nuevoUsuario"],
"password" => $crPassword,
"perfil" => $_POST["nuevoPerfil"],
"ruta" => $ruta);
$respuesta = ModelUsers::mdlAddUser($tabla, $datos);
if($respuesta){
echo '<script>
swal({
type: "success",
title: "El usuario se ha guardado correctamente",
showConfirmButton: true,
confirmButtonText: "Cerrar",
closeOnConfirm: false
}).then((result=>{
if(result.value){
window.location = "users"
}
}))
</script>';
}else{
echo '<script>
swal({
type: "error",
title: "Error al añadir usuario",
showConfirmButton: true,
confirmButtonText: "Cerrar",
closeOnConfirm: false
}).then((result=>{
if(result.value){
window.location = "users"
}
}))
</script>';
}
}else{
echo '<script>
swal({
type: "error",
title: "El usuario no puede ir vacio ni llevar caracteres especiales",
showConfirmButton: true,
confirmButtonText: "Cerrar",
closeOnConfirm: false
}).then((result=>{
if(result.value){
window.location = "users"
}
}))
</script>';
}
}
}
/*===========================================
M O S T R A R U S U A R I O S
===========================================*/
static public function ctrShowUser($item, $valor){
$tabla = "usuarios";
$ans = ModelUsers::mdlMostrarUsuarios($tabla, $item, $valor);
return $ans;
}
/*===========================================
E D I T A R U S U A R I O
===========================================*/
static public function ctrEditUser(){
if(isset($_POST["editarUsuario"])){
if(preg_match('/^[a-zA-Z0-9ñÑáéíóúÁÉÍÓÚ ]+$/',$_POST["editarNombre"]) ){
/*==========================================================
V A L I D A R I M A G E N
==========================================================*/
$ruta = $_POST["fotoActual"];
if(isset($_FILES["editarFoto"]["tmp_name"]) && $_FILES["editarFoto"]["tmp_name"] != ""){
list($ancho, $alto) = getimagesize($_FILES["editarFoto"]["tmp_name"]);
$nuevoAncho = 500;
$nuevoAlto = 500;
/*---------------------------------------------
CREAR DIRECTORIO DONDE SE GUARDA LA FOTO
---------------------------------------------*/
$directorio = "view/img/usuarios/".$_POST["editarUsuario"];
/*--------------------------------------------
PREGUNTAR SI EXISTE FOTO EN LA DB
--------------------------------------------*/
if(!empty($_POST["fotoActual"])){
unlink($_POST["fotoActual"]);
}else{//Creamos Directorio
mkdir($directorio, 0755);
}
/*---------------------------------------------
DE ACUERDO AL TIPO DE IMAGEN ACCIONES
---------------------------------------------*/
$rand = mt_rand(100, 999);
//------------------ IMAGEN JPEG ------------------
if($_FILES["editarFoto"]["type"] == "image/jpeg"){
//Guardamos Imagen en el Directorio
$ruta = "view/img/usuarios/".$_POST["editarUsuario"]."/".$rand.".jpeg";
$origen = imagecreatefromjpeg($_FILES["editarFoto"]["tmp_name"]);
$destino = imagecreatetruecolor($nuevoAncho, $nuevoAlto);
imagecopyresized($destino, $origen, 0, 0, 0, 0, $nuevoAncho, $nuevoAlto, $ancho, $alto);
imagejpeg($destino, $ruta);
}
if($_FILES["editarFoto"]["type"] == "image/png"){
//Guardamos Imagen en el Directorio
$ruta = "view/img/usuarios/".$_POST["editarUsuario"]."/".$rand.".png";
$origen = imagecreatefrompng($_FILES["editarFoto"]["tmp_name"]);
$destino = imagecreatetruecolor($nuevoAncho, $nuevoAlto);
imagecopyresized($destino, $origen, 0, 0, 0, 0, $nuevoAncho, $nuevoAlto, $ancho, $alto);
imagepng($destino, $ruta);
}
}
//Posible Cambio de Contraseña
$crPassword = "";
if($_POST["editarPassword"] != ""){
if(preg_match('/^[a-zA-Z0-9]+$/',$_POST["editarPassword"])){
$crPassword = crypt($_POST["editarPassword"], '$2a$08$abb55asfrga85df8g42g8fDDAS58olf973adfacmY28n05$');
}else{
echo '<script>
swal({
type: "warning",
title: "La contraseña no puede llevar caracteres especiales",
showConfirmButton: true,
confirmButtonText: "Cerrar",
closeOnConfirm: false
}).then((result=>{
if(result.value){
window.location = "users"
}
}))
</script>';
}
}else{ //Editar Password viene vacio, no se modificara contraseña
$crPassword = $_POST["passwordActual"];
}
$tabla = "usuarios";
$datos = array(
"nombre"=>$_POST["editarNombre"],
"usuario" => $_POST["editarUsuario"],
"password" => $crPassword,
"perfil" => $_POST["editarPerfil"],
"foto" => $ruta);
$respuesta = ModelUsers::mdlEditarUsuario($tabla, $datos);
if($respuesta){//Usuario guardado con exito
echo '<script>
swal({
type: "success",
title: "Usuario guardado con exito",
showConfirmButton: true,
confirmButtonText: "Cerrar",
closeOnConfirm: false
}).then((result=>{
if(result.value){
window.location = "users"
}
}))
</script>';
}else{//Error al guardar usuario
echo '<script>
swal({
type: "error",
title: "Error al guardar usuario '.$respuesta.'",
showConfirmButton: true,
confirmButtonText: "Cerrar",
closeOnConfirm: false
}).then((result=>{
if(result.value){
window.location = "users"
}
}))
</script>';
}
}else{//Nombre no valido
echo '<script>
swal({
type: "warning",
title: "Nombre no puede ir vacio o llevar caracteres especiales",
showConfirmButton: true,
confirmButtonText: "Cerrar",
closeOnConfirm: false
}).then((result=>{
if(result.value){
window.location = "users"
}
}))
</script>';
}
}
}
/*===========================================
B O R R A R U S U A R I O
===========================================*/
static public function ctrBorrarUsuario(){
if(isset($_GET["idUsuario"])){
$tabla ="usuarios";
$datos = $_GET["idUsuario"];
if($_GET["fotoUsuario"] != ""){
unlink($_GET["fotoUsuario"]);
rmdir('vistas/img/usuarios/'.$_GET["usuario"]);
}
$respuesta = ModelUsers::mdlBorrarUsuario($tabla, $datos);
if($respuesta){
echo'<script>
swal({
type: "success",
title: "El usuario ha sido borrado correctamente",
showConfirmButton: true,
confirmButtonText: "Cerrar"
}).then(function(result){
if (result.value)
window.location = "users";
})
</script>';
}
}
}
} | true |
3dcb2d3c33be2ae948d9c27f528c0b0f46f27f40 | PHP | Pyranth/hackathonPort2018 | /webapp/guest-favorites.php | UTF-8 | 460 | 2.828125 | 3 | [] | no_license | <?php
require_once 'dbscripts/config.php';
$myArray = array();
if ($result = $mysqli->query("SELECT DISTINCT g.NAME, g.SURNAME, s.NAME_SERVICES FROM guest_services gs LEFT JOIN guest g ON gs.ID = g.ID LEFT JOIN services s ON gs.ID_SERVICES = s.ID_SERVICES WHERE g.NAME=\"John\"")) {
while($row = $result->fetch_array(MYSQL_ASSOC)) {
$myArray[] = $row;
}
}
foreach ($myArray as $res){
print_r($res['NAME_SERVICES']);
echo "<br>";
}
?> | true |
34f452354c9adedf76b9e9ecf55c669e6bf92eb1 | PHP | pixelant/pxa_pm_importer | /Classes/Validation/Validator/ValidatorInterface.php | UTF-8 | 573 | 2.546875 | 3 | [] | no_license | <?php
declare(strict_types=1);
namespace Pixelant\PxaPmImporter\Validation\Validator;
use Pixelant\PxaPmImporter\Validation\ValidationResult;
/**
* Interface ProcessorFieldValueValidatorInterface
* @package Pixelant\PxaPmImporter\Domain\Validation
*/
interface ValidatorInterface
{
/**
* Validate given value and return result
*
* @param array $importRow Full import row
* @param string $property Validation property
* @return ValidationResult
*/
public function validate(array $importRow, string $property): ValidationResult;
}
| true |
e283eb348d4a8ecd3a97f15e057c6b44d6e62a1e | PHP | JoseAntonio1994/PPI | /ajax/modulos.php | UTF-8 | 1,024 | 2.765625 | 3 | [] | no_license | <?php
require_once '../Controladores/ModuloController.php';
//Una matriz para mostrar las respuestas de la api
$response = array();
if (isset($_GET['apimodulos']))
{
switch ($_GET['apimodulos'])
{
case 'leer_modulos':
$db = new ModuloController();
$response["error"] = false;
$response["message"] = "Solicitud completada";
$response["contenido"] = $db->readModuloController();
break;
case 'asignar_modulos':
$db = new ModuloController();
$result = $db->readModuloRolController($_POST['cod_rol']);
if ($result)
{
$response["error"] = false;
$response["message"] = "Solicitud completada";
$response["contenido"] = $result;
}else
{
$response["error"] = true;
$response["message"] = "Hubo un error al asignar los modulos";
}
break;
}
} else
{
$response["error"] = true;
$response["message"] = "Error al mostrar los modulos";
}
//Recibimos un json con la respuesta del servidor
echo json_encode($response, JSON_UNESCAPED_UNICODE);
?>
| true |
73e44491da464d04feefdd85b20527c73ab915aa | PHP | frongpsc-hub/InternAtime | /application/controllers/account/Welcome.php | UTF-8 | 15,806 | 2.515625 | 3 | [] | no_license | <?php
class Welcome extends CI_Controller {
/*public function index()
{
$data = ['test1'=> $this->load->view('Register',NULL,TRUE)];
$this->load->view("first_view",$data);
}*/
public function index()
{
$this->load->view("/account/Register");
}
public function form_validation()
{
//echo 'OK';
$this->load->library('form_validation');
$this->form_validation->set_rules("email", "Email", 'required');
$this->form_validation->set_rules("password", "Password", 'required');
if ($this->form_validation->run())
{
//true
$this->load->model("Main_model");
$data = array(
"email" =>$this->input->post("email"),
"password" =>$this->input->post("password")
);
$this->Main_model->insert_data($data);
redirect(base_url() . "inserted");
}
else
{
//false
$this->index();
}
}
public function inserted()
{
$this->index();
}
public function login()
{
$data['title'] = 'Login Form';
$this->load->view("login",$data);
}
function login_validation()
{
$this->load->library('form_validation');
$this->form_validation->set_rules("email", "Email", 'required');
$this->form_validation->set_rules("password", "Password", 'required');
if($this->form_validation->run())
{
//true
$email = $this->input->post('email');
$password = $this->input->post('password');
//model function
$this->load->model('Main_model');
if($this->Main_model->can_login($email, $password))
{
$session_data = array(
'email' => $email,
'password' => $password
);
$this->session->set_userdata($session_data);
redirect(base_url() . 'enter');
}
else
{
$this->session->set_flashdata('error', 'Invalid Email and Password');
redirect(base_url() . 'login');
}
}
else
{
//false
$this->login();
}
}
function enter(){
if($this->session->userdata('username') != '')
{
echo '<h2>Welcome - '.$this->session->userdata('username').'</h2>';
echo '<label><a href="'.base_url
().'logout">Logout</a></label>';
}
else
{
redirect(base_url() . 'login');
}
}
function logout()
{
$this->session->unset_userdata('username');
redirect(base_url() . 'login');
}
public function forgotpass()
{
$data['title'] = 'Forgot Password';
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('newpass', 'new password', 'required');
$this->form_validation->set_rules('passconf', 'confirm password', 'required|matches[newpass]');
if($this->form_validation->run() == false) {
$this->load->view('forgotpass', $data);
}
else {
$email = $this->input->post('email');
$newpass = $this->input->post('newpass');
$this->load->model('Main_model');
$this->Main_model->update_user($email, array('password' => $newpass));
echo "ok";
redirect(base_url() . 'login');
}
}
public function password_check($email)
{
$this->load->model('Main_model');
$email = $this->session->userdata('email');
$user = $this->Main_model->get_user($email);
if($user->email !== $email) {
$this->form_validation->set_message('email_check', 'The {field} does not match');
return false;
}
return true;
}
public function logout_cgi()
{
$ei = array(
"logout" => FALSE,
);
$this->session->unset_userdata('isLogged',FALSE);
$this->session->set_userdata('username',NULL);
$ei['logout'] = TRUE;
$ei = json_encode($ei);
$this->output
->set_content_type('application/json')
->set_output($ei);
}
public function login_cgi()
{
$eieiei = array(
"success" => FALSE,
"message" => "",
"data" => [],
);
$isLogged = null;
$this->load->library('form_validation');
$this->form_validation->set_rules("username", "Username", 'required');
$this->form_validation->set_rules("password", "Password", 'required');
if($this->form_validation->run())
{
$this->load->model('Main_model');
//true
$username = $this->input->post('username');
$password = $this->input->post('password');
//model function
if($frong = $this->Main_model->can_login($username, $password))
{
$session_data = array(
'username' => $username,
'password' => $password
);
$this->session->set_userdata($session_data);
$this->session->set_userdata('isLogged',TRUE);
$this->session->set_userdata('username',$username);
$isLogged =$this->session->userdata('isLogged');
$username = $this->session->userdata('username');
$eieiei['data']= $frong;
$eieiei['success'] = 'Online';
//redirect(base_url() . 'enter');
}
else
{
$eieiei['message'] = 'Invalid Email and Password';
//$this->session->set_flashdata('error', 'Invalid Email and Password');
}
}
else
{
$eieiei["message"] = "try again";
}
$eieiei = json_encode($eieiei);
$this->output
->set_content_type('application/json')
->set_output($eieiei);
}
public function checkstatus()
{
$eieiei = array(
"success" => FALSE,
"message" => "",
"data" => '',
);
$isLogged =$this->session->userdata('isLogged');
$username = $this->session->userdata('username');
if ($isLogged){
$eieiei['success'] = 'Online';
$eieiei['data'] = $username;
}
$eieiei = json_encode($eieiei);
$this->output
->set_content_type('application/json')
->set_output($eieiei);
}
public function signup_cgi()
{
$eiei = array(
"success" => FALSE,
"message" => "",
"data" => [],
);
$this->load->library('form_validation');
$this->form_validation->set_rules("username", "Username",'required' );
$this->form_validation->set_rules("password", "Password",'required');
if ($this->form_validation->run())
{
//true
$this->load->model("Main_model");
$username = $this->input->post("username");
$password = $this->input->post("password");
if($this->Main_model->can_signup($username)) {
$this->Main_model->insert_data($username,$password);
$eiei['success'] = TRUE;
}
else
{
$eiei['success'] = FALSE;
$eiei['message'] = 'The username has already exits';
}
}
else{
$eiei["message"] = "try again";
}
$eieiei = json_encode($eiei);
$this->output
->set_content_type('application/json')
->set_output($eieiei);
}
public function gmm()
{
$this->load->view("gmm.html");
}
public function do_upload()
{
$new = array(
'data' => [],
'total' =>''
);
$error = [];
$error['FILE'] = $_FILES;
$error['GET'] = $_GET;
$error['POST'] = $_POST;
$error['R'] = $_REQUEST;
$username = $this->input->post('username');
$config['upload_path'] = $_SERVER['DOCUMENT_ROOT'].'/uploads/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
$this->load->model("Main_model");
if (!$this->upload->do_upload('image')) {
$error['error'] = $this->upload->display_errors();
$error = json_encode($error);
$this->output
->set_content_type('application/json')
->set_output($error);
} else {
$data = array('upload_data' => $this->upload->data());
$okay = $data['upload_data']['full_path'];
//var_dump($data);
$base = str_replace("/var/www/html", "", $okay);
$size = $data['upload_data']['file_size'];
$this->load->model("Main_model");
$new['data'] = $this->Main_model->upload_data($username,$base,$size);
//var_dump($new['data']);
$new['total'] = $this->Main_model->takeTotal($username);
$new = json_encode($new);
$this->output
->set_content_type('application/json')
->set_output($new);
}
}
public function uploadImage() {
$pic = array(
'total' => ''
);
$data = [];
$error = [];
$error['FILE'] = $_FILES;
$error['GET'] = $_GET;
$error['POST'] = $_POST;
$error['R'] = $_REQUEST;
$username = $this->input->post('username');
$count = count($_FILES['file']['name']);
for($i=0;$i<$count;$i++){
if(!empty($_FILES['files']['name'][$i])){
$_FILES['file']['name'] = $_FILES['files']['name'][$i];
$_FILES['file']['type'] = $_FILES['files']['type'][$i];
$_FILES['file']['tmp_name'] = $_FILES['files']['tmp_name'][$i];
$_FILES['file']['error'] = $_FILES['files']['error'][$i];
$_FILES['file']['size'] = $_FILES['files']['size'][$i];
$config['upload_path'] = $_SERVER['DOCUMENT_ROOT'].'/uploads/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
$this->load->model("Main_model");
if($this->upload->do_upload('file')){
$uploadData = $this->upload->data();
$filename = $uploadData['file_name'];
$data['totalFiles'][] = $filename;
}
}
}
}
public function takeImage(){
$pic = array(
'data' => [],
'total' => ''
);
$this->load->model("Main_model");
$username = $this->input->post('username');
//var_dump($username);
$pic['total'] = $this->Main_model->takemaxTotal($username);
$pic['data'] = $this->Main_model->takeImage($username);
$pic = json_encode($pic);
$this->output
->set_content_type('application/json')
->set_output($pic);
}
public function takemaxTotal(){
$pic = array(
'total' => ''
);
$this->load->model("Main_model");
$username = $this->input->post('username');
//var_dump($username);
$pic['total'] = $this->Main_model->takemaxTotal($username);
$pic = json_encode($pic);
$this->output
->set_content_type('application/json')
->set_output($pic);
}
public function takestat(){
$pic = array(
'stat' => ''
);
$this->load->model("Main_model");
$username = $this->input->post('username');
//var_dump($username);
$pic['stat'] = $this->Main_model->takestat($username);
$pic = json_encode($pic);
$this->output
->set_content_type('application/json')
->set_output($pic);
}
public function taketotalspace(){
$pic = array(
'space' => ''
);
$this->load->model("Main_model");
$username = $this->input->post('username');
//var_dump($username);
$pic['space'] = $this->Main_model->taketotalspace($username);
$pic = json_encode($pic);
$this->output
->set_content_type('application/json')
->set_output($pic);
}
public function takeamount(){
$pic = array(
'amount' => ''
);
$this->load->model("Main_model");
$username = $this->input->post('username');
//var_dump($username);
$pic['amount'] = $this->Main_model->takeamount($username);
$pic = json_encode($pic);
$this->output
->set_content_type('application/json')
->set_output($pic);
}
public function takeuserlist(){
$pic = array(
'list' => [],
);
$this->load->model("Main_model");
$pic['list'] = $this->Main_model->takeuserlist();
$pic = json_encode($pic);
$this->output
->set_content_type('application/json')
->set_output($pic);
}
public function changestat(){
$newstat = array(
'newstat' => '',
);
$this->load->model("Main_model");
$username = $this->input->post('username');
$newstat['newstat'] = $this->Main_model->takenewstat($username);
$newstat = json_encode($newstat);
$this->output
->set_content_type('application/json')
->set_output($newstat);
}
public function delete()
{
$pic = array(
'total' => ''
);
$del = $this->input->post('URLdel');
$this->load->model("Main_model");
$username = $this->input->post('username');
$this->Main_model->delImage($del);
$pic['total'] = $this->Main_model->takeTotal($username);
$pic = json_encode($pic);
$this->output
->set_content_type('application/json')
->set_output($pic);
}
public function updatespace()
{
$response = array(
'success' => ''
);
$username = $this->input->post('username');
$space = $this->input->post('newspace');
$this->load->model("Main_model");
$response['success'] = $this->Main_model->updatespace($username,$space);
$response = json_encode($response);
$this->output
->set_content_type('application/json')
->set_output($response);
}
public function takeeditspace()
{
$space = array(
'total' => [],
);
$this->load->model("Main_model");
$username = $this->input->post('username');
$space['total'] = $this->Main_model->takeeditspace($username);
$space = json_encode($space);
$this->output
->set_content_type('application/json')
->set_output($space);
}
}
| true |
784154d0935b183bad7a0aac75958ec64707212a | PHP | sakamata/happy2 | /views/admin/table.php | UTF-8 | 240 | 2.703125 | 3 | [] | no_license | <?php
echo "<tr>";
$field_no = 0;
foreach ($tableData as $noUseValue){
$fieldNames = array_keys($tableData);
$fieldName = $fieldNames[$field_no];
echo "<td>". $this->escape($tableData[$fieldName]) ."</td>";
$field_no++;
}
echo "</tr>";
| true |
6f40b00e3a6113fed602737eb6c9654777f5414a | PHP | DerDu/SPHERE-Upgrade | /System/Database/Driver/MySqlDriver.php | UTF-8 | 415 | 2.59375 | 3 | [] | no_license | <?php
namespace SPHERE\System\Database\Driver;
/**
* Class MySqlDriver
* @package SPHERE\System\Database\Driver
*/
class MySqlDriver extends AbstractDriver implements DriverInterface
{
/**
* @return string
*/
public function getIdentifier()
{
return 'pdo_mysql';
}
/**
* @return string
*/
public function getDefaultPort()
{
return 3306;
}
}
| true |
c70748fdf99d53d2ffd942433deee19284baffd6 | PHP | Rosanyelis/PanelAdmin-Apuesta | /app/Http/Controllers/Api/WebAuthController.php | UTF-8 | 1,814 | 2.53125 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\Role;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
class WebAuthController extends Controller
{
/**
* Login
*/
public function login(Request $request)
{
$data = [
'email' => $request->email,
'password' => $request->password
];
$rol = Role::where('name', 'Visitante')->first();
if (Auth::attempt($data) ) {
if (Auth::user()->role_id == $rol->id ) {
$token = Auth::user()->createToken('Auth-Web')->accessToken;
$user = Auth::user();
return response()->json(['token' => $token, 'user' => $user], 200);
}
} else {
return response()->json(['error' => 'Unauthorised'], 401);
}
}
/**
* Registration
*/
public function register(Request $request)
{
$this->validate($request, [
'name' => 'required|min:4',
'email' => 'required|email',
'password' => 'required|min:8',
]);
$rol = Role::where('name', 'Visitante')->first();
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => bcrypt($request->password),
'role_id' => $rol->id,
]);
$token = $user->createToken('Auth-Web')->accessToken;
return response()->json(['token' => $token], 200);
}
public function logout(Request $request)
{
$request->user()->token()->revoke();
return response()->json([
'status' => 200,
'message' => 'Cerraste sesión',
], 200);
}
}
| true |
7632b7697f2c7229565a1485cbe90d0d7fd72a86 | PHP | wcabynessa/LAMP-Web | /php/common.php | UTF-8 | 842 | 3.046875 | 3 | [] | no_license | <?php
if (!function_exists('get')) {
function get($arr, $key, $default = null) {
if (isset($arr[$key])) return $arr[$key];
return $default;
}
}
if (!function_exists('date_difference')) {
// Format: YYYY-MM-DD
function date_difference($date1, $date2) {
$time1 = strtotime($date1);
$time2 = strtotime($date2);
$days1 = (int)date('Y', $time1) * 365 + (int)date('m', $time1) * 30 + (int)date('d', $time1);
$days2 = (int)date('Y', $time2) * 365 + (int)date('m', $time2) * 30 + (int)date('d', $time2);
return $days2 - $days1;
}
}
if (!function_exists('error_response')) {
function error_response($msg) {
return array(
'STATUS' => 'ERROR',
'MSG' => $msg
);
}
}
if (!function_exists('success_response')) {
function success_response($data = '') {
return array(
'STATUS' => 'OK',
'DATA' => $data
);
}
}
?>
| true |
734762793792bf0455ab8e716d75aeb08436ecad | PHP | bamblebam/water-footprin-calculator | /evs mini project/quiz1.php | UTF-8 | 755 | 2.71875 | 3 | [] | no_license | <?php
session_start()
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="quiz2.php" method="POST">
<h4>Number of adults?</h4>
<label for="q1a"></label>
<input type="number" name="q1a" id="q1a" required>
<h4>Number of children?</h4>
<label for="q2a"></label>
<input type="number" name="q2a" id="q2a" required>
<h4>Number of rooms in your house?</h4>
<label for="q3a"></label>
<input type="number" name="q3a" id="q3a" required>
<input type="submit">
</form>
</body>
</html> | true |
0a4f0919c9a8fd2dddfdc2d0cbe5e4ae5ed25ef1 | PHP | MCLACS/CSCI343-Public | /php/InClassExercises/Module4/CRUD-Users/user.php | UTF-8 | 8,542 | 2.84375 | 3 | [] | no_license |
<?php
require_once "functions.php";
require_once 'dblogin.php';
session_start();
header("Access-Control-Allow-Origin: *");
// Create connection
$conn = new mysqli($db_hostname, $db_username, $db_password, $db_database, $db_port);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$cmd = getValue("cmd", "");
if ($cmd == "create")
{
$response = create($conn);
header('Content-type: application/json');
echo json_encode($response);
}
else if ($cmd == "read")
{
$response = read($conn);
header('Content-type: application/json');
echo json_encode($response);
}
else if ($cmd == "update")
{
$response = update($conn);
header('Content-type: application/json');
echo json_encode($response);
}
else if ($cmd == "delete")
{
$response = delete($conn);
header('Content-type: application/json');
echo json_encode($response);
}
else if ($cmd == "login")
{
$response = login($conn);
header('Content-type: application/json');
echo json_encode($response);
}
else if ($cmd == "logout")
{
$response = logout();
header('Content-type: application/json');
echo json_encode($response);
}
else if ($cmd == "isLoggedIn")
{
$response = isLoggedIn();
header('Content-type: application/json');
echo json_encode($response);
}
else // list all supported commands
{
echo
"
<pre>
Command:
Description:
Parameters:
Example:
Query string:
Returns:
";
}
function create($conn)
{
// initialize status...
$response["error"] = "";
// validate inputs...
$userName = getValue("userName", "");
if ($userName == "")
{
$response["error"] = "Username is required.";
return $response;
}
$userFullName = getValue("userFullName", "");
if ($userFullName == "")
{
$response["error"] = "User's full name is required.";
return $response;
}
$userPass = getValue("userPass", "");
if (strlen($userPass) < 8 || strlen($userPass) > 20)
{
$response["error"] = "Password is required and must be at least 8 and no more than 20 characters.";
return $response;
}
// hash the password...
$userPass = password_hash($userPass, PASSWORD_DEFAULT);
// check to see if user exists...
$stmt = $conn->prepare("SELECT USER_ID FROM USER WHERE USER_NAME = ?");
$stmt->bind_param("s", $userName);
$stmt->execute();
// if user does not exist, insert the user...
if (!$stmt->fetch())
{
$stmt->close();
$stmt = $conn->prepare("INSERT INTO USER(USER_NAME, USER_FULLNAME, USER_PASSWORD) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $userName, $userFullName, $userPass);
$stmt->execute();
$stmt->close();
$stmt = $conn->prepare("SELECT USER_ID FROM USER WHERE USER_NAME = ?");
$stmt->bind_param("s", $userName);
$stmt->execute();
$stmt->bind_result($userID);
$stmt->fetch();
}
else // user does exist...
{
$response["error"] = sprintf("User %s already exist.", $userName);
return $response;
}
// return response...
$user["userID"] = $userID;
$user["userName"] = $userName;
$user["userFullName"] = $userFullName;
$response["user"] = $user;
setSessionValue("user", $user);
$response["loggedIn"] = true;
return $response;
}
function read($conn)
{
// make sure the user is logged in...
$response["loggedIn"] = getSessionValue("user", "") != "";
if (!$response["loggedIn"])
{
$response["error"] = "You must login to view your user account.";
return $response;
}
// return the user...
$response["user"] = getSessionValue("user", "");
$response["loggedIn"] = getSessionValue("user", "") != "";
return $response;
}
function update($conn)
{
// make sure the user is logged in...
$response["loggedIn"] = getSessionValue("user", "") != "";
if (!$response["loggedIn"])
{
$response["error"] = "You must login to edit your user account.";
return $response;
}
// get the logged in user...
$userID = getSessionValue("user", "")["userID"];
// validate input values...
$userName = getValue("userName", "");
if ($userName == "")
{
$response["error"] = "Username is required.";
return $response;
}
$userFullName = getValue("userFullName", "");
if ($userFullName == "")
{
$response["error"] = "User's full name is required.";
return $response;
}
$userPass = getValue("userPass", "");
if (strlen($userPass) < 8 || strlen($userPass) > 20)
{
$response["error"] = "Password is required and must be at least 8 and no more than 20 characters.";
return $response;
}
// make sure the user exists...
$stmt = $conn->prepare("SELECT USER_ID FROM USER WHERE USER_ID = ?");
$stmt->bind_param("i", $userID);
$stmt->execute();
if (!$stmt->fetch())
{
$response["error"] = sprintf("User %d does not exist.", $userID);
return $response;
}
$stmt->close();
// hash the password...
$userPass = password_hash($userPass, PASSWORD_DEFAULT);
// update the user...
$stmt = $conn->prepare("UPDATE USER SET USER_NAME = ?, USER_FULLNAME = ?, USER_PASSWORD = ? WHERE USER_ID = ?");
$stmt->bind_param("sssi", $userName, $userFullName, $userPass, $userID);
$stmt->execute();
// return response...
$user["userID"] = $userID;
$user["userName"] = $userName;
$user["userFullName"] = $userFullName;
setSessionValue("user", $user);
$response["user"] = $user;
return $response;
}
function delete($conn)
{
// make sure the user is logged in...
$response["loggedIn"] = getSessionValue("user", "") != "";
if (!$response["loggedIn"])
{
$response["error"] = "You must login to delete your user account.";
return $response;
}
// make sure the user exists...
$userID = getSessionValue("user", "")["userID"];
$stmt = $conn->prepare("SELECT USER_ID FROM USER WHERE USER_ID = ?");
$stmt->bind_param("i", $userID);
$stmt->execute();
if (!$stmt->fetch())
{
$response["error"] = sprintf("User %d does not exist.", $userID);
return $response;
}
$stmt->close();
// delete the user...
$stmt = $conn->prepare("DELETE FROM USER WHERE USER_ID = ?");
$stmt->bind_param("i", $userID);
$stmt->execute();
// log the user out...
setSessionValue("user", "");
$response["loggedIn"] = false;
return $response;
}
function login($conn)
{
// log the current user out...
setSessionValue("user", "");
// validate the input...
$userName = getValue("userName", "");
if ($userName == "")
{
$response["error"] = "Username is required when logging in user.";
return $response;
}
$userPass = getValue("userPass", "");
if ($userPass == "")
{
$response["error"] = "Password is required when logging in user.";
return $response;
}
// select the user that is tyring to login...
$stmt = $conn->prepare("SELECT USER_ID, USER_FULLNAME, USER_PASSWORD FROM USER WHERE USER_NAME Like ?");
$stmt->bind_param("s", $userName);
$stmt->execute();
$stmt->bind_result($userID, $userFullName, $hashPassword);
$user = array();
if ($stmt->fetch())
{
if (password_verify($userPass , $hashPassword))
{
$user["userID"] = $userID;
$user["userName"] = $userName;
$user["userFullName"] = $userFullName;
setSessionValue("user", $user);
}
}
// if the user is empty, then the username/password is invalid...
if (count($user) == 0)
{
$response["error"] = "Invalid username or password.";
return $response;
}
// login successful, return the user...
$response["user"] = $user;
$response["loggedIn"] = getSessionValue("user", "") != "";
return $response;
}
function logout()
{
setSessionValue("user", "");
$response["loggedIn"] = false;
return $response;
}
function isLoggedIn()
{
$user = getSessionValue("user", "");
$response["loggedIn"] = getSessionValue("user", "") != "";
$response["user"] = $user;
return $response;
}
?>
| true |
6818e1c09ae81c9bbeaa78bfb27a021d345ef9ee | PHP | rifjan29/masdimas | /uploadbukti.php | UTF-8 | 2,749 | 2.546875 | 3 | [] | no_license | <?php
session_start();
$con = new mysqli("localhost","root","","masdimas");
$username = $_SESSION['username'];
$id = $_GET['id'];
$data = mysqli_query($con, "SELECT id_pembelian, atasnama, username, tanggal, total FROM pembelian WHERE username = '$username' AND id_pembelian = '$id'");
?>
<!DOCTYPE html>
<html>
<head>
<title>Upload Bukti pembayaran</title>
<link rel='stylesheet' href='css/cart.css'>
</head>
<body>
<div class='header'>
<a href="home.php" class="custom-logo-link" rel="home" aria-current="page"><img width="200" height="80px" src="gambar/logo.png" class="custom-logo"/></a>
<div class="menu-header-1">
<div class="a">
<ul>
<p>Selamat datang, <?php echo $_SESSION['username']; ?>!</p>
<li><a href="logout.php">LOGOUT</a></li>
</ul>
</div>
<div class="b">
</div>
<div class="c">
<a href="" class="custom-logo-link" rel="home" aria-current="page"><img width="35" height="35" src="gambar/keranjang.png" class="custom-logo"> My Cart </a>
<a href="list-transaksi.php" class="custom-logo-link" rel="home" aria-current="page"><img width="35" height="35" src="gambar/keranjang.png" class="custom-logo"> Transaksi </a>
</div>
</div>
</div>
<div class="header-2">
<div class="menu-header-2">
<ul>
<li><a href="help.php">Help</a></li>
<li><a href="aboutus.php">About Us</a></li>
<li><a href="map.php">Maps</a></li>
</ul>
</div>
</div>
<section class='gambar'>
<div class='container'>
<h2>Upload Bukti pembayaran</h2>
<?php while($item = mysqli_fetch_array($data)){ ?>
<p><label>Atas nama : </label> <?= $item['atasnama'] ?></p>
<?php
$detail = mysqli_query($con, "SELECT * FROM detail_pembelian JOIN produk ON detail_pembelian.id_produk = produk.id_produk WHERE ud_pembelian = '$id'");
while($item_detail = mysqli_fetch_array($detail)){
?>
<p><label>Produk : <?= $item_detail['nama'] ?></label></p>
<img src="gambar/<?= $item_detail['gambar'] ?>" alt="<?= $item_detail['gambar'] ?>" width="150px" height="150px">
<?php } ?>
<?php } ?>
</div>
</section>
<div class='btn'>
<br>
<br>
<form action="uploadbukti_proses.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="id_pembelian" value="<?= $id ?>">
<p><label for="bukti">Upload Bukti Pembayaran</label> <input type="file" name="bukti" id="bukti"></p>
<input type="submit" value="Kirim">
</form>
<br>
<br>
</div>
<div class='footer'>
<p>Copyright 2020 - <a href=''>Jajanan Mas Di Mas</a></p>
</div>
</body>
</html> | true |
ee34c0938bcd4445c69970fe0038e7978b7ffa25 | PHP | zywkeven/cron_zwshd_com | /applications/library/Model/Base.php | UTF-8 | 2,339 | 2.875 | 3 | [] | no_license | <?php
/**
*
* @author keven.zhong
*
*/
abstract class Model_Base {
/**
* 通过类获取的updata sql
* @param obj $bindArrParams
* @return array $rs
*/
public static function getUpdateVal (&$bindArrParams) {
$rs = array();
$clsName = get_class($bindArrParams);
if($clsName != ''){
$allVars = get_class_vars($clsName);
$aryRs = Array();
$aryBind = Array();
foreach ($allVars as $key => $val) {
if (NULL !== $bindArrParams->$key) {
$aryRs[] = " `$key` = :$key";
$aryBind[':' . $key] = $bindArrParams->$key;
}
}
$rs = Array($aryRs , $aryBind);
}
return $rs;
}
/**
* 通过类获取的insert sql
* @param obj $bindArrParams
* @return array $rs
*/
public static function getInsertVal (&$bindArrParams) {
$rs = array();
$clsName = get_class($bindArrParams);
if($clsName != ''){
$allVars = get_class_vars($clsName);
$aryRsKey = Array();
$aryRsValue = Array();
$aryBind = Array();
foreach ($allVars as $key => $val) {
if (NULL !== $bindArrParams->$key) {
$aryRsKey[] = '`' . $key . '`';
$aryRsValue[] = ':' . $key;
$aryBind[':' . $key] = $bindArrParams->$key;
}
}
$rs = Array($aryRsKey , $aryRsValue, $aryBind);
}
return $rs;
}
/**
* 过滤需要的sql
* @param obj $bindArrParams
* @return array $rs
*/
public static function getSelectVal(&$bindArrParams){
$rs = array();
$clsName = get_class($bindArrParams);
if($clsName != ''){
$allVars = get_class_vars($clsName);
$aryRs = Array();
$aryBind = Array();
foreach ($allVars as $key => $val) {
if (NULL !== $bindArrParams->$key) {
$aryRs[] = " `$key` = :$key";
$aryBind[':' . $key] = $bindArrParams->$key;
}
}
$rs = Array(implode(' AND ',$aryRs) , $aryBind);
}
return $rs;
}
} | true |
a4e1f8a71d8ee2a3430d27da31dfd016d2a7d113 | PHP | rahulyhg/happy-giraffe | /site/frontend/modules/photo/components/thumbs/ImageDecorator.php | UTF-8 | 3,089 | 2.6875 | 3 | [] | no_license | <?php
/**
* Надстройка над Imagine
*
* Добавляет логику к стандартной обработке фото - управляет анимацией, определяет качество.
*
* @author Никита
* @date 03/10/14
*/
namespace site\frontend\modules\photo\components\thumbs;
use Imagine\Filter\FilterInterface;
use Imagine\Image\ImageInterface;
use site\frontend\modules\photo\components\thumbs\filters\core\AnimatedGifFilter;
use site\frontend\modules\photo\components\thumbs\filters\core\StaticGifFilter;
use site\frontend\modules\photo\components\thumbs\filters\CustomFilterInterface;
use site\frontend\modules\photo\helpers\ImageSizeHelper;
class ImageDecorator
{
/**
* @var ImageInterface
*/
public $image;
/**
* @var string
*/
protected $inputFormat;
/**
* @var string
*/
protected $outputFormat;
/**
* @var bool
*/
protected $animated;
/**
* @var array
*/
protected $options;
public function __construct($imageString, $animated)
{
$this->image = \Yii::app()->imagine->load($imageString);
$imageSize = ImageSizeHelper::getImageSize($imageString);
$this->inputFormat = \Yii::app()->getModule('photo')->types[$imageSize[2]];
$this->animated = $animated && $this->inputFormat == 'gif';
$this->outputFormat = $this->animated ? 'gif' : 'jpg';
$this->prepare();
}
public function get()
{
return $this->image->get($this->outputFormat, $this->options);
}
public function show()
{
return $this->image->show($this->outputFormat, $this->options);
}
public function applyFilter(CustomFilterInterface $filter)
{
$filters = array();
if ($this->inputFormat == 'gif') {
if ($this->animated) {
$filters[] = new AnimatedGifFilter($filter);
} else {
$filters[] = new StaticGifFilter();
$filters[] = $filter;
}
} else {
$filters[] = $filter;
}
foreach ($filters as $f) {
$this->image = $f->apply($this->image);
}
}
public function __call($method, $arguments = array())
{
return call_user_func_array(array($this->image, $method), $arguments);
}
protected function prepare()
{
$this->image->strip();
$this->options['animated'] = $this->animated;
if ($this->outputFormat == 'jpg') {
$this->options['jpeg_quality'] = $this->getJpegQuality();
}
}
protected function getJpegQuality()
{
$width = $this->image->getSize()->getWidth();
$config = \Yii::app()->getModule('photo')->quality;
$q = array_pop($config);
$config = array_reverse($config, true);
foreach ($config as $minWidth => $quality) {
if ($width <= $minWidth) {
$q = $quality;
} else {
break;
}
}
return $q;
}
} | true |
497b40c0994154d1061aea95721c80fb09533aa9 | PHP | jdouglas71/sbwp | /wp-content/plugins/sbcs/html-widget.php | UTF-8 | 1,605 | 2.90625 | 3 | [] | no_license | <?php
/**
* Sidebar widget that displays whatever html was given it.
* @author Jason Douglas
*/
class SBCS_HTML_Widget
extends WP_Widget
{
/**
* Widget Function.
*/
function widget($args, $instance)
{
extract($args,EXTR_SKIP);
wp_enqueue_style( "sbcs_widget_style", plugins_url('sbcs.css',__FILE__) );
echo $before_widget;
echo $before_title;
echo $instance['html_text'];
echo $after_title;
echo $after_widget;
}
/**
* Constructor.
*/
function SBCS_HTML_Widget()
{
$widget_options = array(
'classname'=>'widget-sbcs-html',
'description'=>__('This widget displays the HTML that was input as part of the widget options.')
);
$control_options = array(
'height'=>300,
'width' =>300
);
$this->WP_Widget('sbcs_html_widget','SBCS HTML Widget',$widget_options,$control_options);
}
/**
* Update Function. Called when changes are made in the admin panel.
*/
function update($new_instance, $old_instance)
{
$instance = $old_instance;
$instance['html_text'] = $new_instance['html_text'];
return $instance;
}
/**
* Form function. Used in dashboard to allow users to configure the widget.
*/
function form($config)
{
$html_text = $config['html_text'];
?>
<label for="<?php echo $this->get_field_id("html_text"); ?>">
<p>HTML Text:
<textarea rows="5" cols="50" name="<?php echo $this->get_field_name("html_text"); ?>" id="<?php echo $this->get_field_id("html_text") ?>">
<?php echo $html_text; ?>
</textarea>
</p>
</label>
<?php
}
}
?>
| true |
22f6b56ebdfde879f7c4d5ac4908306e771ce153 | PHP | hayate/hayate | /lib/Hayate/Image.php | UTF-8 | 9,316 | 2.703125 | 3 | [] | no_license | <?php
/**
* Hayate Framework
* Copyright 2009-2010 Andrea Belvedere
*
* Hayate is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation, either
* version 3 of the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
class Hayate_Image
{
protected $filepath;
protected $img;
protected $resized;
protected $width;
protected $height;
protected $ext;
public function __construct($filepath)
{
if (!function_exists('gd_info'))
{
throw new Hayate_Exception(_('GD extension is missing.'));
}
if (!is_file($filepath))
{
throw new Hayate_Exception(sprintf(_('Cannot find %s'), $filepath));
}
$this->filepath = $filepath;
$info = getimagesize($this->filepath);
if (false === $info)
{
throw new Hayate_Exception(sprintf(_('Cannot read %s'), $filepath));
}
list ($this->width, $this->height) = $info;
$mimes = array ('image/jpeg' => 'jpg',
'image/pjpeg' => 'jpg',
'image/gif' => 'gif',
'image/png' => 'png');
$this->ext = isset($mimes[$info['mime']]) ? $mimes[$info['mime']] : null;
if (null === $this->ext)
{
throw new Hayate_Exception(sprintf(_('Supported mime types are: %s'),
implode(',', array_keys($mimes))));
}
switch ($this->ext) {
case 'jpg':
$this->img = imagecreatefromjpeg($filepath);
break;
case 'gif':
$this->img = imagecreatefromgif($filepath);
break;
case 'png':
$this->img = imagecreatefrompng($filepath);
break;
}
}
public function __destruct()
{
if ($this->img)
{
imagedestroy($this->img);
}
if ($this->resized)
{
imagedestroy($this->resized);
}
}
public function width()
{
if (is_resource($this->resized))
{
return imagesx($this->resized);
}
else if (is_resource($this->img))
{
return imagesx($this->img);
}
return 0;
}
public function height()
{
if (is_resource($this->resized))
{
return imagesy($this->resized);
}
else if (is_resource($this->img))
{
return imagesy($this->img);
}
return 0;
}
public function resize($width = 0, $height = 0, $keep_ratio = true)
{
$width = ((null === $width) || !is_numeric($width) || ($width < 0)) ? 0 : $width;
$height = ((null === $height) || !is_numeric($height) || ($height < 0)) ? 0 : $height;
if ($width == 0 && $height == 0)
{
throw new Hayate_Exception(_('At least one dimension must be greater than 0.'));
}
// calculate width proportionally to height
if ($width == 0)
{
$width = round(($height * $this->width) / $this->height);
}
// calculate height proportionally to width
else if ($height == 0)
{
$height = round(($width * $this->height) / $this->width);
} else if ($keep_ratio)
{
$wratio = ($this->width / $width);
$hratio = ($this->height / $height);
if ($hratio > $wratio)
{
$width = round(($height * $this->width) / $this->height);
} else
{
$height = round(($width * $this->height) / $this->width);
}
}
$this->resized = imagecreatetruecolor($width, $height);
imagealphablending($this->resized, false);
imagesavealpha($this->resized, true);
imagecopyresampled($this->resized, $this->img, 0, 0, 0, 0,
$width, $height, $this->width, $this->height);
return $this;
}
public function resizeCrop($width, $height, $top = 'center', $left = 'center')
{
if (!is_numeric($width) || ($width <= 0) ||
!is_numeric($height) || ($height <= 0))
{
throw new Hayate_Exception(_('Width and height must be numeric values and greater than 0'));
}
$valid_top = array ('top', 'center', 'bottom');
$valid_left = array ('left', 'center', 'right');
if (!in_array($top, $valid_top, true))
{
throw new Hayate_Exception(_('Valid top are: "top","center" and "bottom"'));
}
if (!in_array($left, $valid_left, true))
{
throw new Hayate_Exception(_('Valid left are: "left","center" and "right"'));
}
//
if (($this->height / $height) >= ($this->width / $width))
{
$this->resize($width, 0);
// retrieve height of resized image
$rh = imagesy($this->resized);
if ($rh > $height)
{
$x = 0;
if ($top == 'center')
{
$y = round(($rh - $height) / 2);
} else if ($top == 'top')
{
$y = 0;
} else
{
$y = round($rh - $height);
}
} else
{
$height = $rh;
$x = 0;
$y = 0;
}
} else
{
$this->resize(0, $height);
// retrieve width of resized image
$rw = imagesx($this->resized);
if ($rw > $width)
{
$y = 0;
if ($left == 'center')
{
$x = round(($rw - $width) / 2);
} else if ($left == 'left')
{
$x = 0;
} else
{
$x = round($rw - $width);
}
} else
{
$width = $rw;
$x = 0;
$y = 0;
}
}
$dst = imagecreatetruecolor($width, $height);
imagealphablending($dst, false);
imagesavealpha($dst, true);
imagecopy($dst, $this->resized, 0, 0, $x, $y, $width, $height);
imagedestroy($this->resized);
$this->resized = $dst;
return $this;
}
public function crop($x, $y, $width, $height)
{
$w = $this->width();
$h = $this->height();
$width = ($width > $w) ? $w : $width;
$height = ($height > $h) ? $h : $height;
$dst = imagecreatetruecolor($width, $height);
imagealphablending($dst, false);
imagesavealpha($dst, true);
if (is_resource($this->resized))
{
imagecopy($dst, $this->resized, 0, 0, $x, $y, $width, $height);
imagedestroy($this->resized);
$this->resized = $dst;
} else
{
imagecopy($dst, $this->img, 0, 0, $x, $y, $width, $height);
$this->resized = $dst;
}
return $this;
}
/**
* @return void
*/
public function save($filepath = null, $sanitize = true, $quality = 95)
{
$quality = is_numeric($quality) ? $quality : 95;
$sanitize = (bool) $sanitize;
if (null === $filepath)
{
$filepath = $this->filepath;
}
if ($sanitize)
{
$info = pathinfo($filepath);
$filename = $info['filename'];
$filename = preg_replace(array ('/[?:\/*""<>|&]/', '/\s+/'),
array ('', '_'), $filename);
$filepath = empty($info['dirname']) ? '' : $info['dirname'] . DIRECTORY_SEPARATOR;
$filepath .= $filename . '.' . $info['extension'];
}
switch ($this->ext) {
case 'jpg':
imagejpeg($this->resized, $filepath, $quality);
break;
case 'gif':
imagegif($this->resized, $filepath);
break;
case 'png':
imagepng($this->resized, $filepath, 9);
break;
}
}
public function render($quality = 95)
{
$quality = is_numeric($quality) ? $quality : 95;
switch ($this->ext) {
case 'jpg':
header('Content-type: image/jpeg');
imagejpeg($this->resized, null, $quality);
break;
case 'gif':
header('Content-type: image/gif');
imagegif($this->resized, null);
break;
case 'png':
header('Content-type: image/png');
imagepng($this->resized, null, 9);
break;
}
}
}
| true |
08916e63dcddb74a15cca8d7e9ce35453f1a591d | PHP | db306/BlaBlaCarAPIIntegration | /src/Service/SearchTripService.php | UTF-8 | 3,495 | 2.8125 | 3 | [] | no_license | <?php
declare(strict_types=1);
namespace App\Service;
use App\ValueObject\Coordinate;
use App\ValueObject\Country;
use DateTime;
use Psr\Cache\CacheItemPoolInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
class SearchTripService implements SearchServiceInterface
{
private HttpClientInterface $client;
private CacheItemPoolInterface $cache;
private string $apiKey;
private string $baseUrl;
public function __construct(
HttpClientInterface $client,
CacheItemPoolInterface $cache,
string $apiKey,
string $baseUrl
) {
$this->client = $client;
$this->cache = $cache;
$this->apiKey = $apiKey;
$this->baseUrl = $baseUrl;
}
/**
* @param DateTime $from Date from where to start looking for trips
* @param DateTime $to End date from where to stop looking for trips
* @param Coordinate $departure Departure coordinates of the trip search
* @param Coordinate $destination Destination coordinates of the trip search
* @param Country $originCountry Country of departure in ISO 3166-1 aplha-2 Format
* @param Country $destinationCountry Country of destination in ISO 3166-1 aplha-2 Format
* @param string|null $cursor The next page pagination cursor
*
* @return array The expected result from BlaBlaCar Search API
*
* @throws \Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface
* @throws \Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface
* @throws \Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface
* @throws \Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface
* @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
*/
public function searchTrip(
DateTime $from,
DateTime $to,
Coordinate $departure,
Coordinate $destination,
Country $originCountry,
Country $destinationCountry,
?string $cursor
): array {
$query = [
'key' => $this->apiKey,
'start_date_local' => $from->format('yy-m-d\TH:i:s'),
'end_date_local' => $to->format('yy-m-d\TH:i:s'),
'locale' => 'fr-FR',
'currency' => 'EUR',
'from_coordinate' => "$departure",
'to_coordinate' => "$destination",
'from_country' => "$originCountry",
'to_country' => "$destinationCountry",
];
if (null !== $cursor) {
$query['from_cursor'] = $cursor;
}
$hash = strval(crc32(join('', $query)));
$cacheItem = $this->cache->getItem($hash);
if ($cacheItem->isHit()) {
return $cacheItem->get();
}
$response = $this->client->request(
'GET',
$this->baseUrl,
[
'query' => $query,
'headers' => [
'Accept' => 'application/json',
],
]
)->toArray();
// As suggested by https://support.blablacar.com/hc/en-us/articles/360014200220--How-to-use-BlaBlaCar-search-API-
$cacheItem->expiresAfter(600); // you shouldn't cache the results you retrieve from the API, or for a very small time (10 min max)
$cacheItem->set($response);
$this->cache->save($cacheItem);
return $response;
}
}
| true |
eaae6b502463377abb4e82a7329c4a474454e59e | PHP | treaudde/poc-stepper | /Services/StepperService.php | UTF-8 | 1,898 | 2.9375 | 3 | [] | no_license | <?php
namespace Services;
use Models\Email;
use Models\Address;
use Models\PhoneNumber;
use Models\Preferences;
/**
* Class StepperService
*
* @package Services
*/
class StepperService
{
/**
* @var Email
*/
private $email;
/**
* @var Address
*/
private $address;
/**
* @var PhoneNumber
*/
private $phoneNumber;
/**
* @var Preferences
*/
private $preferences;
/**
* StepperService constructor.
*
*
*
* @param Email $email
* @param Address $address
* @param PhoneNumber $phoneNumber
* @param Preferences $preferences
*/
public function __construct()
{
$this->email = new Email();
$this->address = new Address();
$this->phoneNumber = new PhoneNumber();
$this->preferences = new Preferences();
}
/**
* @param $formId
*/
public function getCurrentStep($formId)
{
//to be determined, need this service to provide steps to frontend so we can order them in the service
}
/**
* @param $data
* @return array
*/
public function saveEmail($data)
{
if($this->email->save($data))
{
return ['nextStep' => 2];
}
}
/**
* @param $data
* @return array
*/
public function saveAddress($data)
{
if($this->address->save($data))
{
return ['nextStep' => 2];
}
}
/**
* @param $data
* @return array
*/
public function savePhoneNumber($data)
{
if($this->phoneNumber->save($data)) {
return ['nextStep' => 2];
}
}
/**
* @param $data
* @return array
*/
public function savePreferences($data)
{
if ($this->preferences->save($data)) {
return ['nextStep' => 2];
}
}
} | true |
84f784f016f711cc9ca84bbe45b72f862be810d5 | PHP | saeedadabi/Jerkoop-CMS | /include/connection.php | UTF-8 | 456 | 2.65625 | 3 | [] | no_license | <?php
function connect_db() {
$server=constant("db-host");
$user=constant("db-user");
$pass=constant("db-pass");
$db=constant("db-name");
try {
$conn=new PDO("mysql:host=$server;dbname=$db",$user,$pass);
$conn->setAttribute(PDO::ATTR_ERRMODE , PDO::ERRMODE_EXCEPTION);
return $conn;
}// end try
catch(PDOException $e) {
echo"connection failed" . $e->getMessage();
}// end catch
}// end function connect_db()
?>
| true |
25eea19cc919d8e9817563d79f028096dc9aff26 | PHP | LoBrs/calendly-sdk-php | /src/CalendlyApi.php | UTF-8 | 4,180 | 2.765625 | 3 | [
"MIT"
] | permissive | <?php
namespace LoBrs\Calendly;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\RequestOptions;
use LoBrs\Calendly\Exceptions\ApiErrorException;
use LoBrs\Calendly\Exceptions\InternalServerErrorException;
use LoBrs\Calendly\Exceptions\InvalidArgumentException;
use LoBrs\Calendly\Exceptions\PermissionDeniedException;
use LoBrs\Calendly\Exceptions\ResourceNotFoundException;
use LoBrs\Calendly\Exceptions\UnauthenticatedException;
use LoBrs\Calendly\Models\EventType;
use LoBrs\Calendly\Models\Organization;
use LoBrs\Calendly\Models\User;
final class CalendlyApi
{
const API_URL = "https://api.calendly.com";
private Client $client;
/**
* @var string Calendly `user` or `organization` token
*/
private string $token;
public function __construct(string $token, ?Client $httpClient = null) {
$this->token = $token;
if ($httpClient) {
$this->client = $httpClient;
} else {
$this->client = new Client([
"base_uri" => self::API_URL,
]);
}
}
/**
* @throws ApiErrorException|InvalidArgumentException
*/
public function request(string $uri, string $method = "GET", array $params = []) {
$options[RequestOptions::HEADERS] = [
"Accept" => "application/json",
"Authorization" => "Bearer " . $this->token,
];
if (strtolower($method) == "get") {
$options[RequestOptions::QUERY] = $params;
} else {
$options[RequestOptions::JSON] = $params;
}
try {
$response = $this->client->request($method, $uri, $options);
} catch (GuzzleException $e) {
$response = $e->getResponse();
}
$data = json_decode($response->getBody(), true);
$httpCode = $response->getStatusCode();
if ($httpCode > 299) {
$message = $data['message'] ?? "Une erreur est survenue";
$details = $data['details'] ?? [];
if (isset($data['title'])) {
// get exception class from title
$exceptionClassname = "LoBrs\\Calendly\\Exceptions\\" . str_replace(' ', '',
ucwords(str_replace(['-', '_'], ' ', $data['title']))) . "Exception";
if (class_exists($exceptionClassname)) {
throw new $exceptionClassname($message, $details);
}
}
if ($httpCode == 500) {
throw new InternalServerErrorException($message, $details);
}
if ($httpCode == 404) {
throw new ResourceNotFoundException($message, $details);
}
if ($httpCode == 403) {
throw new PermissionDeniedException($message, $details);
}
if ($httpCode == 401) {
throw new UnauthenticatedException($message, $details);
}
// Default API error exception
throw new ApiErrorException($message, $details);
}
return $data;
}
/**
* @throws ApiErrorException|InvalidArgumentException
*/
public function me(): ?User {
$response = $this->request("/users/me");
if (isset($response["resource"])) {
return new User($response["resource"]);
}
return null;
}
/**
* @throws ApiErrorException|InvalidArgumentException
*/
public function getOrganization(?string $organization_uuid = null): ?Organization {
if (empty($organization_uuid)) {
return $this->me()->getCurrentOrganization();
}
return Organization::get($organization_uuid);
}
/**
* @throws ApiErrorException|InvalidArgumentException
*/
public function getUser(?string $uuid = null): ?User {
if (empty($uuid)) {
return $this->me();
}
return User::get($uuid);
}
/**
* @throws ApiErrorException|InvalidArgumentException
*/
public function getEventTypes(array $options): Utils\PaginatedList {
return EventType::paginate($options);
}
} | true |
6423b31e48986de43968ead9e36b75e2cdf06301 | PHP | leelaplap/php-laravel-blog-manager | /app/Http/Controllers/BlogController.php | UTF-8 | 1,572 | 2.53125 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers;
use App\Blog;
use Illuminate\Http\Request;
class BlogController extends Controller
{
protected $blog;
public function __construct(Blog $blog)
{
$this->blog = $blog;
}
public function showAll()
{
$blogs = $this->blog->paginate(5);
return view('blog.index', compact('blogs'));
}
public function showFormAdd()
{
return view('blog.formAdd');
}
public function add(Request $request)
{
$blog = new Blog();
$blog->name = $request->name;
$blog->category = $request->category;
$blog->date = $request->date;
$blog->save();
return redirect()->route('blog.list');
}
public function delete($id)
{
$blog = $this->blog->findOrFail($id);
$blog->delete();
return redirect()->route('blog.list');
}
public function showFormEdit($id)
{
$blog = $this->blog->findOrFail($id);
return view("blog.formEdit", compact('blog'));
}
public function edit(Request $request, $id)
{
$blog = $this->blog->findOrFail($id);
$blog->name = $request->name;
$blog->category = $request->category;
$blog->date = $request->date;
$blog->save();
return redirect()->route('blog.list');
}
public function search(Request $request){
if ($request->ajax()){
$blogs = Blog::where('name','LIKE',"%$request->search%")->paginate(5);
return response()->json($blogs);
}
}
}
| true |
6bcf776d5da23602e6cecd7b14e260c9fac17821 | PHP | steview/moojon | /0.3/classes/moojon.cache.class.php | UTF-8 | 1,075 | 2.703125 | 3 | [] | no_license | <?php
final class moojon_cache extends moojon_singleton {
static protected $instance;
static protected function factory($class) {if (!self::$instance) {self::$instance = new $class;}return self::$instance;}
static public function fetch() {return self::factory(get_class());}
private $enabled = true;
protected function __construct() {}
static public function expired($path, $absolute = false, $cache_for = null) {
if (!$cache_for) {
$cache_for = moojon_config::get('cache_for');
}
if (!$absolute) {
$path = moojon_paths::get_cache_path($path);
}
if (file_exists($path)) {
if (time() > (filectime($path) + $cache_for)) {
moojon_files::unlink($path);
return true;
} else {
return false;
}
} else {
return true;
}
}
static public function get_enabled() {
$instance = self::fetch();
return $instance->enabled;
}
static public function enable() {
$instance = self::fetch();
$instance->enabled = true;
}
static public function disable() {
$instance = self::fetch();
$instance->enabled = false;
}
}
?> | true |
ee3749dc345f249ad51c699893303295ee43f9e2 | PHP | jcalnan/CS-340 | /wm_search.php | UTF-8 | 4,857 | 2.65625 | 3 | [] | no_license | <?php
ini_set('display_errors', 'On');
//Connects to the database
$mysqli = new mysqli("classmysql.engr.oregonstate.edu","cs340_calnanj","6902","cs340_calnanj");
if(!$mysqli || $mysqli->connect_errno){
echo "Connection error " . $mysqli->connect_errno . " " . $mysqli->connect_error;
}
include 'template.php'
?>
<html>
<head>
<link rel="stylesheet" href="./public/css/wineMakers.css">
</head>
<body>
<h2>Wine Makers returned by query:</h2>
<div id="main">
<table class="table">
<tr>
<th>Tasting Room</th>
<th>Name</th>
<th>Age</th>
<th>Gender</th>
<th>Years as Vintner</th>
<th>Favorite Wine</th>
</tr>
<?php
if ($_GET["wm_locations"] != "Choose Tasting Room Location") {
$loc_str = $_GET["wm_locations"];
$loc_pieces = explode(",", $loc_str);
$city = trim($loc_pieces[0]);
$state = trim($loc_pieces[1]);
echo <<<res
Showing all wineMakers working at tastingRooms in $city, $state.
res;
$query = <<<stmt
SELECT tastingRooms.name AS TR_name, wineMakers.f_name, wineMakers.l_name,
wineMakers.age, wineMakers.gender, wineMakers.yrs, wines.name AS fav_wine
FROM wineMakers INNER JOIN wines ON wineMakers.wines_id = wines.id INNER JOIN
tastingRooms ON wineMakers.tastingRooms_id = tastingRooms.id INNER JOIN locations ON
tastingRooms.locations_id = locations.id WHERE locations.city = ?
AND locations.state = ?;
stmt;
$stmt = $mysqli->prepare($query);
$stmt->bind_param('ss', $city, $state);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($TR_name, $f_name, $l_name, $age, $gen, $yrs, $fav_wine);
$num_rows = $stmt->num_rows;
if ($num_rows == 0) {
echo <<<res
<h2>Sorry, we do not show any wine makers' records for that specific location at this time.</h2>
res;
exit();
}
while ( $stmt->fetch() ) {
echo <<<res
<tr>
<td>$TR_name</td>
<td>$f_name $l_name</td>
<td>$age</td>
<td>$gen</td>
<td>$yrs</td>
<td>$fav_wine</td>
</tr>
res;
}
} else {
echo <<<res
<h2>Showing all wine makers stored in the database.</h2>
res;
$query = <<<stmt
SELECT tastingRooms.name AS TR_name, wineMakers.f_name, wineMakers.l_name,
wineMakers.age, wineMakers.gender, wineMakers.yrs, wines.name AS fav_wine
FROM wineMakers INNER JOIN wines ON wineMakers.wines_id = wines.id INNER JOIN
tastingRooms ON wineMakers.tastingRooms_id = tastingRooms.id;
stmt;
$stmt = $mysqli->prepare($query);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($TR_name, $f_name, $l_name, $age, $gen, $yrs, $fav_wine);
$num_rows = $stmt->num_rows;
if ($num_rows == 0) {
echo <<<res
<h2>Sorry, we do not show any wine makers' records for that specific location at this time.</h2>
res;
exit();
}
while ( $stmt->fetch() ) {
echo <<<res
<tr>
<td>$TR_name</td>
<td>$f_name, $l_name</td>
<td>$age</td>
<td>$gen</td>
<td>$yrs</td>
<td>$fav_wine</td>
</tr>
res;
}
}
?>
</table>
</div>
</body>
</html>
| true |
70e5e99b4dd3402a5d651859ba5a2ff5ba60fa48 | PHP | MaxiBatta/TpFinalLab4Utn | /Models/Student.php | UTF-8 | 2,095 | 3.046875 | 3 | [] | no_license | <?php
namespace Models;
use Models\Person as Person;
class Student extends Person {
private $studentId;
private $careerId;
private $firstName;
private $lastName;
private $dni;
private $fileNumber;
private $gender;
private $birthDate;
private $email;
private $phoneNumber;
private $active;
public function getStudentId() {
return $this->studentId;
}
public function setStudentId($studentId) {
$this->studentId = $studentId;
}
public function getCareerId() {
return $this->careerId;
}
public function setCareerId($careerId) {
$this->careerId = $careerId;
}
function getFirstName() {
return $this->firstName;
}
function getLastName() {
return $this->lastName;
}
function setFirstName($firstName) {
$this->firstName = $firstName;
}
function setLastName($lastName) {
$this->lastName = $lastName;
}
public function getDni() {
return $this->dni;
}
public function setDni($dni) {
$this->dni = $dni;
}
public function getFileNumber() {
return $this->fileNumber;
}
public function setFilenumber($fileNumber) {
$this->fileNumber = $fileNumber;
}
public function getGender() {
return $this->gender;
}
public function setGender($gender) {
$this->gender = $gender;
}
public function getBirthDate() {
return $this->birthDate;
}
public function setBirthDate($birthDate) {
$this->birthDate = $birthDate;
}
public function getEmail() {
return $this->email;
}
public function setEmail($email) {
$this->email = $email;
}
public function getPhoneNumber() {
return $this->phoneNumber;
}
public function setPhoneNumber($phoneNumber) {
$this->phoneNumber = $phoneNumber;
}
public function getActive() {
return $this->active;
}
public function setActive($active) {
$this->active = $active;
}
}
?>
| true |
4009cccc7624db36f8cee37996af1aa13c25c721 | PHP | Arink98/HSP-Review | /managers/Validator.php | UTF-8 | 795 | 2.9375 | 3 | [
"Apache-2.0"
] | permissive | <?php
require __DIR__ . '/../AutoLoader.php';
class Validator {
public function __construct() {
}
/**
* @param string $username
* @return int
*/
public function usernameValid($username) {
return preg_match('/^[A-Za-z0-9_]+$/', $username);
}
public function shopNameValid($shopName) {
return preg_match("/^[A-Za-z0-9\\ \\,\\-\\:\\'\\\"]+$/", $shopName);
}
/**
* @param string $email
* @return bool
*/
public function emailValid($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL) && preg_match('/@.+\./', $email);
}
/**
* @param $str
* @return int
*/
public function isPostcode($str) {
return preg_match('(\d{4})', preg_replace('/\s+/', '', $str));
}
} | true |
11506e033508602a147f78a1bd1841719fa106be | PHP | muhammedkalender/Fridge | /index.php | UTF-8 | 1,971 | 2.765625 | 3 | [] | no_license | <?php
spl_autoload_register(function ($class_name) {
include $class_name . '.php';
});
use Helpers\Logger;
use Objects\Coke;
use Objects\Fridge;
Logger::log("İşlemler Başlıyor");
Logger::log("Obje tanımlanıyor", true);
$fridge = new Fridge();
Logger::log("Kapak açılıyor", true);
$fridge->open();
Logger::log("Kapak tekrar açılıyor", true);
$fridge->open();
Logger::log("Dolabın durumu soruluyor", true);
$fridge->printStatus();
echo $fridge->printShelfStatus();
$coke = null;
Logger::log("20 Adet Kola Ekleniyor", true);
foreach (range(1, 20) as $index) {
Logger::log("{$index}. Kola Tanımlanıyor");
$coke = new Coke();
$fridge->put($coke);
}
Logger::log("Dolabın durumu soruluyor", true);
$fridge->printStatus();
$fridge->printShelfStatus();
Logger::log("Kolanın bilgileri alınıyor", true);
echo $coke->getInfo() . "<br>";
Logger::log("Kapak kapatılıyor", true);
$fridge->close();
Logger::log("21. kola tanımlanıyor", true);
$coke = new Coke();
Logger::log("21. kola dolaba konuyor", true);
$fridge->put($coke);
Logger::log("Dolabın kapağı açılıyor", true);
$fridge->open();
Logger::log("Yeni kola dolaba konuyor", true);
$fridge->put($coke);
Logger::log("Dolap tamamen dolduruluyor", true);
foreach (range(22, 60) as $index) {
Logger::log("{$index}. Kola Tanımlanıyor");
$coke = new Coke();
$fridge->put($coke);
}
Logger::log("Dolabın güncel durumu yazdırılıyor", true);
$fridge->printStatus();
Logger::log("61. İçecek dolaba konmaya çalışıyor", true);
$fridge->put(new Coke());
Logger::log("Dolaptaki güncel kola sayısı", true);
echo $fridge->getCount() . "<br>";
echo $fridge->printShelfStatus();
Logger::log("Dolaptan kola alınıyor", true);
$fridge->take();
Logger::log("Dolabın güncel durumu yazdırılıyor", true);
$fridge->printStatus();
Logger::log("Dolaptaki güncel kola sayısı", true);
echo $fridge->getCount() . "<br>";
$fridge->printShelfStatus(); | true |
1bf1e75af54a00ab210dfa7d5580df9e7ed07c4d | PHP | leancep/ProyectosAcademia | /Calculadora/CalculadoraTest.php | UTF-8 | 3,185 | 2.9375 | 3 | [] | no_license | <?php
require_once("./vendor/autoload.php");
require_once("Calculadora.php");
use PHPUnit\Framework\TestCase;
final class CalculadoraTest extends TestCase{
function testAndaTodo(){
$this->assertTrue(True);
}
function testExisteCalculadora(){
$this->assertTrue(class_exists("Calculadora"));
}
function testSumarDosPositivos(){
$calculadora= new Calculadora();
$suma= $calculadora->sumar(5,5);
$this->assertEquals(10, $suma);
}
function testSumarNegativos(){
$calculadora= new Calculadora();
$sumaNeg= $calculadora->sumar(-3, -2);
$this-> assertEquals(-5, $sumaNeg);
}
function testSumarNegyPos(){
$calculadora= new Calculadora();
$suma= $calculadora->sumar(2, -3);
$this->assertEquals(-1, $suma);
$suma= $calculadora->sumar(-2, 3);
$this->assertEquals(1, $suma);
}
function testRestaPositivos(){
$calculadora= new Calculadora();
$resta= $calculadora->restar(4, 3);
$this->assertEquals(1, $resta);
}
function testRestaNegativos(){
$calculadora= new Calculadora();
$resta=$calculadora->restar(-3, -3);
$this->assertEquals(0, $resta);
}
function testRestaNegyPos(){
$calculadora= new Calculadora();
$resta= $calculadora->restar(-1, 4);
$this-> assertEquals(-5, $resta);
$resta= $calculadora->restar(1, -4);
$this-> assertEquals(5, $resta);
}
function testDividirPositivos(){
$calculadora= new Calculadora();
$division= $calculadora->dividir(5,5);
$this->assertEquals(1, $division);
}
function testDividirNegativos(){
$calculadora= new Calculadora();
$division= $calculadora->dividir(-5,-5);
$this->assertEquals(1, $division);
}
function testDividirNegYPos(){
$calculadora= new Calculadora();
$division= $calculadora->dividir(5,-5);
$this->assertEquals(-1, $division);
$division= $calculadora->dividir(-5,5);
$this->assertEquals(-1, $division);
}
function testDividir0(){
$calculadora= new Calculadora();
$division= $calculadora->dividir(5,0);
$this->assertEquals(1, $division);
}
function testMultiplicar(){
$calculadora= new Calculadora();
$multiplicacion= $calculadora->multiplicar(2,2);
$this->assertEquals(4, $multiplicacion);
}
function testMultiplicar0(){
$calculadora= new Calculadora();
$multiplicacion= $calculadora->multiplicar(2,0);
$this->assertEquals(0, $multiplicacion);
$multiplicacion= $calculadora->multiplicar(0,2);
$this->assertEquals(0, $multiplicacion);
}
// function testMultiplicarNegativos(){
// $calculadora= new Calculadora();
// $multiplicacion= $calculadora->multiplicar(-2,-2);
// $this->assertEquals(4, $multiplicacion);
// }
// function testMultiplicarNegYPos(){
// $calculadora= new Calculadora();
// $multiplicacion= $calculadora->multiplicar(-2,2);
// $this->assertEquals(-4, $multiplicacion);
// }
} | true |
452ff1ac2ac5139444e8d34ccc8e384857784ef2 | PHP | tsloncz/xmlTesting | /tabFileInterfaceV2.php | UTF-8 | 9,218 | 2.84375 | 3 | [] | no_license | <?php
/*
* V2
*/
session_start();
/*
* Element can have data
* in just it's attributes
* as headers for csv element string
* as attribute=>value pairs
* in it's attributes and children
* as csv
* in it's childrens
* attributes
* as children element strings
*
*
* Algorithm
* If element has attributes
* print them
*/
//Simple XML Reference http://www.w3schools.com/Php/php_ref_simplexml.asp
function createFileInterface($filePath)
{
//$sxe=simplexml_load_file( $filePath );//Default file type
if (file_exists($filePath))
{
$xml = simplexml_load_file($filePath);
createSaveForm($filePath);
dispFile( $xml);
}
else
{
exit('Failed to open' . $filePath);
}
}
//$sxe=simplexml_load_file( $weatherFile );
//dispFile( $sxe);
$endTime = new DateTime();
$diff = $endTime->diff($startTime);
//print "Time to create: " . $diff->s . "seconds";
function createSaveForm($filename)
{
$filename = stripName($filename);
echo "<br><button onclick='createXml()'>Save File As</button>";
echo " <input type='text' id='fileName' onChange='validFileName()' value='$filename'>";
echo "<span id='validFile'></span><br />";
}
function stripName($name)
{
$name = explode('/',$name);
return implode(explode('.',end($name), -2));
}
function dispFile( $sxe )
{
$name = $sxe->getName();
echo "<div class='fileType' id='$name'>File type: <font style='color:red'>";
echo $sxe->getName() . "</font><br>";
createTabs($sxe);
echo "</div>";
}
function handleElement( $element )
{
$numChildren = $element->count();
switch($numChildren)
{
case 0:
if( (count($element->attributes()) > 0 ) )
{
if($element->getName() == "Weather")
{
printDataAsCsv( $element );
}
else
{
printAttributes( $element );
}
}
else
{
printData( $element );
}
break;
case ($numChildren > 0):
createTabs( $element);
//elementWithChildren($index,$element);
break;
}
}
function printData( $element )
{
$name = $element->getName();
if( $name == "Version" || $name == "ReleaseDate" || $name =="Notes")
{
echo "<div class='elementData'>"
. "<textarea rows='3' cols='30' readonly>" . $element . "</textarea></div>";
}
else
{
echo "<div class='elementData'>"
. "<textarea rows='3' cols='30'>" . $element . "</textarea></div>";
}
}
function printAttributes( $element )
{
//Elements that can user can create. Reference salusClasses google doc
$NCardinalityDictionary = array("Species","Phase","Factor","Cultivar","PhotSynType","Point",
"Crop_Par","Fert_Par","Irr_Par","Residue_Par","Till_Par",
"C)2_Trend_XY","Soil_Bio_Kinectic_Par","Stations",
"Storm_Intensity","Hourly_Rainfall","Soil","Layer",
"Experiment","Rotation_Components","Component",
"Mgt_Chemical_App","Mgt_EncMod_App","Mgt_Harvest_App",
"Mgt_Tillage_App","Mgt_Fertilizer_App","Mgt_Residu_App",
"Mgt_Irrigation_App");
$name = $element->getName();
//echo "<table class='attributeTable' type='attributeTable' name='$name' border=1><tr>";
echo "<div class='attributes'>";
//If version make readonly
if( $name == "Version")
{
foreach($element->attributes() as $a => $b)
{
echo "<div class='attribute' id='$a'><b>$a</b><br /><input type='text' value='$b' readonly></input></div>";
}
}
else
{
if( in_array($name,$NCardinalityDictionary) )
{
echo "<button onClick='newTab( $(this).parent() )'>New " . $name . "</button>";
echo "<button onClick='clearValues( $(this).parent() )'>Clear Values</button><br />";
}
foreach($element->attributes() as $a => $b)
{
echo "<div class='attribute' id='$a'><b>$a</b><br /><input type='text' value='$b'></input></div>";
}
}
echo "</div><br />";
}
function createTabs($element)
{
if( (count($element->attributes()) > 0 ) )
{
printAttributes( $element );
}
echo "<div id='tabs'><ul>";
$i = 0;
foreach ($element->children() as $index=>$child)
{
$uniqueId = getUniqueIdentifier($child);
$name = $child->getName();
if($uniqueId != "")
{
echo "<li><a href='#" . $name . "_" . $i . "'>" . $name . $uniqueId . "</a><span class='ui-icon ui-icon-close' onclick='removeTab($(this))' role='presentation'>Remove Tab</span></li>";
}
else
{
echo "<li><a href='#" . $name . "_" . $i . "'>" . $name . "</a></li>";
}
$i++;
}
echo "</ul>";
$i = 0;
foreach ($element->children() as $child)
{
$id = $child->getName() . "_" . $i;
$name = $child->getName();
echo "<div class='element' id='$id' name='$name'>";
handleElement($child);
echo "</div>";
$i++;
}
echo "</div>";
}
function getUniqueIdentifier($element)
{
$uniqueIdentifierDictionary = array("Species"=>"Species","Phase"=>"Label","Factor"=>"TRF",
"Cultivar"=>"CultivarID","PhotoSynType"=>"PhotSynID","Point"=>"CO2",
"Version"=>"Number","Crop_Par"=>"Name","Fert_Par"=>"Name",
"Irr_Par"=>"Name","Residue_Par"=>"Name","Till_Par"=>"Name",
"CO2_Trend_XY"=>"Yr","Soil_Bio_Kinetic_Par"=>"Element",
"Stations"=>"Station_Name","Storm_Intensity"=>"Month",
"Hourly_Rainfall"=>"Year-DOY-Hr","Soil"=>"SlDesc",
"Layer"=>"Current ZLYR","Experiment"=>"Title","Component"=>"Title",
"Mgt_Chemical_App"=>"Year-DOY","Mgt_EnvMod_App"=>"Year-DOY",
"Mgt_Harvest_App"=>"Year-DOY","Mgt_Tillage_App"=>"Year-DOY",
"Mgt_Fertilizer_App"=>"Year-DOY","Mgt_Residue_App"=>"Year-DOY",
"Mgt_Irrigation_App"=>"Year-DOY");
//Needed to handles elements with same name but differnt ids
$DuplicateUniqueIdentifierDictionary = array("Species"=>"Species_Name","Layer"=>"ZLYR");
$name = $element->getName();
$temp = '';
$uniqueId = '';
foreach($uniqueIdentifierDictionary as $a => $b)
{
if($a == $name)
{
$temp = $b;
}
}
foreach($element->attributes() as $a => $b)
{
$found = strpos($a , $temp);
//If a contains uniqueId
if( $a == $temp )
{
$uniqueId = "_" . $b;
break;
}
}
if($uniqueId == '')
{
foreach($DuplicateUniqueIdentifierDictionary as $a => $b)
{
if($a == $name)
{
$temp = $b;
}
}
foreach($element->attributes() as $a => $b)
{
$found = strpos($a , $temp);
//If a contains uniqueId
if( $a == $temp )
{
$uniqueId = "_" . $b;
break;
}
}
}
return $uniqueId;
}
function createTabList( $element )
{
echo "<div id='tabs'><ul>";
$i = 0;
foreach ($element->children() as $index=>$child)
{
$name = $child->getName();
echo "<li><a href='#" . $name . $i . "'>" . $name . "</a></li>";
$i++;
}
echo "</ul>";
}
function printTableHeadings( $element )
{
echo "<font style='color:green'>" . $element->getName() . "</font><br>";
foreach($element->attributes() as $a => $b)
{
echo "<th>" . $a . "</th>";
}
}
//Replaces printDataAsCsvTable
function printDataAsCsv( $element )
{
$csv = ((string) $element);
$length = strlen($csv);
$val = '';
$i = 0;
$numColumns;
$tableName = $element->getName();
//print locked position headers
echo "<div class='headers'>";
foreach($element->attributes() as $a => $b)
{
$bArray = explode(",",$b);
$numColumns = count($bArray)-1;
foreach($bArray as $val)
{
if( $val != '')
{
echo "<div class='heading'>" . $val . "</div>";
}
}
echo "</div><br />";
}
echo "<div class='values'><div class='valuesRow'>";
//Create table from csv as string
for($j=0; $j<$length; $j++)
{
if( $csv[$j] != ',')
{
if( $csv[$j] == "\n" && $i!=0)//No more data for row
{
//Fill rest of columns with empty inputs
while( $i<$numColumns )
{
echo "<span class='value'><input type='text' size='6'"
. " value=''></input></span>";
$i++;
}
echo "<br /></div><div class='valuesRow'>";
$i=0;
}
$val .= $csv[$j];
}
else
{
$i++;
$val = ltrim($val);
echo "<span class='value'><input type='text' size='6' "
. "value='$val'></input></span>";
//echo $val;
$val = '';
}
}
echo "</div></div><br>";
}
function printDataAsString( $element )
{
$attributes = lookForAttributes( $element );
$name = $element->getName();
echo "<font style='color:blue'>" . $name . "</font><br>";
echo "<div class='element' id='$name' type='stringData' name='$name' attributes='$attributes'>"
. "<textarea rows='3' cols='30' value='$element'>$element</textarea></div>";
}
?>
| true |
2d1162e7214b9d395fab779a4ee5f7629bd8d59a | PHP | nmb007/excursion | /modules/page/models/Page.php | UTF-8 | 2,462 | 2.75 | 3 | [
"MIT"
] | permissive | <?php
namespace app\modules\page\models;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\UploadedFile;
use Yii;
/**
* This is the model class for table "{{%page}}".
*
* @property integer $id
* @property string $name
* @property string $value
* @property integer $created_at
* @property integer $updated_at
*
*/
class Page extends ActiveRecord
{
/**
* Declares the name of the database table associated with this AR class.
*
* @return string
*/
public static function tableName()
{
return '{{%page}}';
}
/**
* Returns the validation rules for attributes.
*
* @return array
*/
public function rules()
{
return [
];
}
/**
* Returns a list of behaviors that this component should behave as.
*
* @return array
*/
public function behaviors()
{
return [
TimestampBehavior::className(),
];
}
/**
* Returns the attribute labels.
*
* @return array
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'name' => Yii::t('app', 'Name'),
'value' => Yii::t('app', 'Value'),
'created_at' => Yii::t('app', 'Created At'),
'updated_at' => Yii::t('app', 'Updated At'),
];
}
/**
* Returns the array of possible page options.
*
* @return array
*/
public static function getOptionsList()
{
$optionsArray = [
'banner_content' => Yii::t('app', 'Homepage banner content'),
'mid_content' => Yii::t('app', 'Homepage mid page content'),
'footer_about_us' => Yii::t('app', 'Footer About us'),
'footer_address' => Yii::t('app', 'Footer Address'),
];
return $optionsArray;
}
/**
* Finds the Post model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
*
* @param integer $id
* @return Post The loaded model.
*
* @throws NotFoundHttpException if the model cannot be found.
*/
public function findModel($id)
{
if (($model = Page::findOne($id)) !== null)
{
return $model;
}
else
{
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
| true |
8106d19630e0281af4cd4ee5d0ab81c42a4680b3 | PHP | atty31/seo-cms | /app/Http/Controllers/Admin/StaticBlocksController.php | UTF-8 | 4,798 | 2.546875 | 3 | [] | no_license | <?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Http\Logs\Admin\Log;
use App\Http\Requests;
use App\Models\Admin\Blocks;
use Exception;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Monolog\Logger;
/**
* Class StaticBlocksController
* @package App\Http\Controllers\Admin
* @author Attila Naghi <naghi.attila@mail.com>
*/
class StaticBlocksController extends Controller
{
/**
* Log file name
* @var string
*/
private $logFileName = 'blocks';
/**
* @var
*/
private $log;
/**
* Create a new controller instance.
*/
public function __construct()
{
$this->log = new Log($this->logFileName);
$this->middleware('auth');
}
public function index()
{
$blocks = DB::table('blocks')->select('blocks.title as title', 'blocks.id as id', 'blocks.identifier as identifier',
'blocks.status as status', 'blocks.default as default', 'blocks.type as type', 'blocks.updated_at as updated_at')
->paginate(30);
return view('adminlte::blocks/list', [
'blocks' => $blocks
]);
}
/**
* @param string $type
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function defaultType(string $type)
{
$blocks = DB::table('blocks')->select('blocks.title as title', 'blocks.id as id', 'blocks.identifier as identifier',
'blocks.status as status', 'blocks.default as default', 'blocks.type as type', 'blocks.updated_at as updated_at')
->where('blocks.type', $type)
->paginate(30);
return view('adminlte::blocks/list', [
'blocks' => $blocks
]);
}
public function newBlock()
{
return view('adminlte::blocks/new');
}
public function store(Requests\Admin\BlockFormRequest $request)
{
$block = new Blocks();
$block->title = trim($request->input('title'));
$block->type = $request->input('type');
$block->identifier = $request->input('identifier');
$block->content = trim($request->input('content'));
$block->status = $request->input('status');
$block->default = 0;
try{
$block->save();
$message = ['msg' => 'A new block was created!'];
$this->log->logMessage(Logger::INFO, 'A new block: '. $block->title.' - was created by the user with the id '.Auth::id());
}catch(Exception $error){
$message = ['msg_error' => $error->getMessage()];
$this->log->logMessage(Logger::ERROR, $error->getMessage());
}
return redirect()->route('admin.blocks')->with($message);
}
/**
* Update static block
* @param int $id
* @param Requests\Admin\BlockFormRequest $request
* @return \Illuminate\Http\RedirectResponse
*/
public function update(int $id, Requests\Admin\BlockFormRequest $request)
{
$block = Blocks::find($id);
$block->title = $request->input('title');
$block->status = $request->input('status');
$block->content = trim($request->input('content'));
if ((int) $request->input('default') !== 1){ // don't update type & identifier for default static blocks
$block->type = $request->input('type');
$block->identifier = $request->input('identifier');
}
try{
$block->save();
$message = 'Block updated with success !';
$this->log->logMessage(Logger::INFO, 'The block: '. $block->title.' - was updated by the user with the id '.Auth::id());
}catch (Exception $error){
$message = ['msg_error' => $error->getMessage()];
$this->log->logMessage(Logger::ERROR, $error->getMessage());
}
return redirect()->route('admin.blocks')->with(['msg' => $message]);
}
/**
* Renders view page for static block
* @param int $id
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function view(int $id)
{
$block = Blocks::find($id);
return view('adminlte::blocks/view', [
'block' => $block
]);
}
/**
* @param int $id
* @return \Illuminate\Http\RedirectResponse
*/
public function destroy(int $id)
{
$message = 'Something went wrong, please try again!';
if (Blocks::destroy($id)){
$this->log->logMessage(Logger::INFO, 'The block with the id: '. $id.' - was deleted by the user with the id '.Auth::id());
$message = 'A block was deleted';
}
return redirect()->route('admin.blocks')->with(['delete_msg' => $message]);
}
}
| true |
b24d2a96df427ebafa48bf6cdbdedd4f70f85016 | PHP | supelec-rezo/trombinews | /serveur/trombinews.php | ISO-8859-1 | 3,740 | 2.625 | 3 | [] | no_license | <?
/*
* Nouvelle version du script de rcupration des photos trombis adapte a la BDD kettu_web, permettant aussi de rcuperer la photo partir d'un nom dns.
*/
/*
* Le script peut utiliser deux modes de slection de l'utilisateur : via un DNS
* ou via une adresse mail.
*/
if(!isset($_GET['mail']) && !isset($_GET['dns'])) die();
mysql_connect('localhost', 'rezo_web', '********');
mysql_select_db('kettu-web');
$mail = $_GET['mail'];
$mode = $_GET['mode'];
if(preg_match('/<.*>$/', $mail))
$mail = preg_replace('/^.+<(.+)>/', '$1', $mail);
// Attention injections
if(!preg_match('/^[a-zA-Z0-9_@.-]/', $mail))
die();
// DNS
if($mode == 'dns')
{
$dns = mysql_real_escape_string($_GET['dns']);
$dns = preg_replace('/^[a-zA-Z\-]+/', '$0', $dns);
$req = mysql_query("SELECT surname AS nom, firstname AS prenom, promotion AS promo, photo_display, photo1, photo2, photo3 FROM trombi_entries WHERE LOWER(surname) LIKE '$dns'") or die(mysql_error());
if(mysql_affected_rows() != 1) die();
$data = mysql_fetch_array($req);
}
// Adresse mail
else
{
// On tente d'abord d'identifier l'adresse email
$req = mysql_query("SELECT surname AS nom, firstname AS prenom, promotion AS promo, photo_display, photo1, photo2, photo3 FROM trombi_entries WHERE emails = '$mail'") or die(mysql_error());
// Si a a russi
if(mysql_affected_rows() == 1)
$data=mysql_fetch_array($req);
// Si a ne marche pas et que l'adresse est @supelec.fr ou @rez-gif.supelec.fr
else if(in_array(preg_replace('/^.+@(.+)$/', '$1', $mail), array('supelec.fr', 'rez-gif.supelec.fr')))
{
// On tente d'identifier le prnom et le nom
$nom = explode('.', preg_replace('/^(.+)@.+$/', '$1', $mail));
if(count($nom) != 2) die();
$nom[0] = preg_replace('/[^a-z0-9]/', '%', $nom[0]);
$nom[1] = preg_replace('/[^a-z0-9]/', '%', $nom[1]);
$req = mysql_query("SELECT surname AS nom, firstname AS prenom, promotion AS promo, photo_display, photo1, photo2, photo3 FROM trombi_entries WHERE firstname LIKE '$nom[0]%' AND surname LIKE '$nom[1]%'") or die(mysql_error());
if(mysql_affected_rows() != 1) die();
$data = mysql_fetch_array($req);
}
// Sinon, plus rien faire
else if(mysql_affected_rows()!=1) die();
}
/*
* Il y a plusieurs sorties possibles :
*/
// Le nom : prnom ' ' nom
if($mode == 'nom')
echo $data['prenom'] . ' ' . $data['nom'];
// La promotion
elseif($mode == 'promo')
echo $data[2];
// La photo
else
{
if(isset($_GET['width']) && is_numeric($_GET['width']))
{
$width = $_GET['width'];
$height = $width;
}
elseif($mode == 'large')
{
$width = 200;
$height = 200;
}
else
{
$width = 100;
$height = 100;
}
if($data['photo_display'] == null)
die();
$photo = $data['photo'.intval($data['photo_display'])];
if($photo == null || $photo == '')
die();
$filename = '../content/trombi_thumbs/' . $photo;
if(!file_exists($filename)) die();
header('Content-type: image/jpg');
// Cacul des nouvelles dimensions
list($width_orig, $height_orig, $type) = getimagesize($filename);
$ratio_orig = $width_orig/$height_orig;
if($width/$height > $ratio_orig)
$width = $height*$ratio_orig;
else
$height = $width/$ratio_orig;
// Redimensionnement
$image_p = imagecreatetruecolor($width, $height);
if($type == 1)
$image = imagecreatefromgif($filename);
else
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
imagejpeg($image_p);
}
?>
| true |
89152d4524467414bc7f7574b6626382609d99b0 | PHP | minhtran2401/DuAnTotNghiep | /app/Http/Requests/RequestSanPham.php | UTF-8 | 2,075 | 2.59375 | 3 | [] | no_license | <?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class RequestSanPham extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name_sp'=>'required|max:60',
'price_sp'=>'required',
'id_nhomsp'=>'required',
'id_loaisp'=>'required',
'id_thuonghieu'=>'required',
'motangan_sp'=>'required',
'motadai_sp'=>'required',
'img_sp'=>'required|image|mimes:jpeg,png,jpg,gif,svg|max:1024',
];
}
// public function messages() {
// return [
// 'name_sp.required' => ':attribute không được bỏ trống',
// 'name_sp.max' => ':attribute không được quá 60 kí tự',
// 'price_sp.required' => ':attribute không được bỏ trống',
// 'id_nhomsp.required' => 'Nhóm sản phẩm không được bỏ trống',
// 'id_loaisp.required' => 'Loại sản phẩm không được bỏ trống',
// 'id_thuonghieu.required' => 'Thương hiệu không được bỏ trống',
// 'img_sp.required' => 'Hình không được bỏ trống',
// 'img_sp.image' => 'Đây không phải là hình ảnh',
// 'img_sp.mimes' => 'Không đúng định dạng ảnh',
// 'img_sp.max' => 'Liên kết hình ảnh không quá 1024 kí tự',
// 'motadai_sp.required' => 'Mô tả dài không được để trống',
// 'motangan_sp.required' => 'Mô tả ngắn không được để trống',
// ];
// }
// public function attributes(){
// return [
// 'name_sp' => 'Tên sản phẩm',
// 'price_sp' => 'Giá sản phẩm',
// ];
// }
}
| true |
b8d859af6c1edd06029c9dae701ba23efb8ef33c | PHP | kbs1/encrypted-api-base | /src/Cryptography/Support/Json.php | UTF-8 | 2,809 | 2.828125 | 3 | [
"MIT"
] | permissive | <?php
namespace Kbs1\EncryptedApiBase\Cryptography\Support;
use Kbs1\EncryptedApiBase\Exceptions\Cryptography\{UnableToEncodeAsBase64Exception, UnableToEncodeAsJsonException,
UnsupportedVariableTypeException, InvalidDataException};
class Json
{
protected $validator;
public function __construct()
{
$this->validator = new Validator;
}
public function encode($value)
{
$this->validator->ensureSupportedVariableTypes($value);
if (is_array($value))
$value = $this->safeArray($value);
else
$value = $this->safeValue($value);
$result = @json_encode($value, 0, 513);
if (json_last_error() !== JSON_ERROR_NONE)
throw new UnableToEncodeAsJsonException(json_last_error_msg());
return $result;
}
public function decode($input)
{
$result = @json_decode($input, true);
if (json_last_error() !== JSON_ERROR_NONE)
throw new InvalidDataException;
if (is_array($result))
$result = $this->originalArray($result);
else
$result = $this->originalValue($result);
return $result;
}
public function decodeAndEnsureKeys($input, array $expected_keys)
{
$result = $this->decode($input);
$keys = array_keys($result);
sort($keys);
sort($expected_keys);
if ($keys !== $expected_keys)
throw new InvalidDataException;
return $result;
}
protected function safeValue($value)
{
if (!is_string($value))
return $value;
try {
$this->validator->ensureValidUtf8($value);
} catch (UnsupportedVariableTypeException $ex) {
return 'b' . $this->encodeBase64($value);
}
return 'u' . $value;
}
protected function safeArray(array $array)
{
$result = [];
foreach ($array as $key => $value)
if (is_array($value))
$result[$this->safeValue($key)] = $this->safeArray($value);
else
$result[$this->safeValue($key)] = $this->safeValue($value);
return $result;
}
protected function originalValue($value)
{
if (!is_string($value))
return $value;
if (strlen($value) < 1)
throw new InvalidDataException;
if ($value[0] === 'u')
return substr($value, 1);
if ($value[0] === 'b')
return $this->decodeBase64(substr($value, 1));
throw new InvalidDataException;
}
protected function originalArray(array $array)
{
$result = [];
foreach ($array as $key => $value)
if (is_array($value))
$result[$this->originalValue($key)] = $this->originalArray($value);
else
$result[$this->originalValue($key)] = $this->originalValue($value);
return $result;
}
protected function encodeBase64($value)
{
$result = base64_encode($value);
if ($result === false)
throw new UnableToEncodeAsBase64Exception;
return $result;
}
protected function decodeBase64($value)
{
$result = @base64_decode($value);
if ($result === false)
throw new InvalidDataException;
return $result;
}
}
| true |
95dec70f8973fc0cb8987cc5f34885a8ce275c53 | PHP | jose1914luis/finder | /docManagement.serie.crear.php | ISO-8859-3 | 1,981 | 2.640625 | 3 | [] | no_license | <?php
/*
session_start();
require_once("Acceso/Config.php"); // Definicin de las variables globales
require_once("Modelos/Perfiles.php");
require_once("Modelos/Acciones.php");
$acciones = new Acciones();
$prf = new Perfiles();
*/
// variables del controlador
$msgError = "";
$Id_Empresa = 2; // pendiente de volver variable global
/*
//$accionPage = new SeguimientosUsuarios;
//$validate->validaAccesoPagina($_SESSION["usuario_cmq"], $_SESSION["passwd_cmq"]);
if(isset($_POST["txtNombrePerfil"])&&isset($_POST["rol"])) {
$resultado = $prf->insertAll($_POST, $Id_Empresa);
if($resultado != "OK")
$msgError = "<script>alert('Error durante el proceso de creacin del Perfil {$_POST["txtNombrePerfil"]}. $resultado')</script>";
else
$msgError = "<script>alert('El Perfil {$_POST["txtNombrePerfil"]} ha sido creado correctamente')</script>";
} else {
$msgError = "<script>alert('La informacin se encuentra incompleta para crear el perfil')</script>";
}
*/
?>
<html>
<head>
</head>
<body>
<p>
<form method="post">
<table align=center width="50%">
<tr>
<td colspan=2 bgcolor="#000077" align="center">
<b><font color=white>:: CREAR SERIE ::</font></b>
</td>
</tr>
<tr>
<td colspan=2 align="center">
<hr size=1/>
</td>
</tr>
<tr>
<td width="25%">Nombre de la Serie: </td>
<td><input type="text" name="txtNombreSerie" size=15></td>
</tr>
<tr>
<td colspan=2 align="center">
<hr size=1/>
<input type="button" value="Crear Serie">
<input type="submit" value="Limpiar Formulario">
<hr size=1/>
</td>
</tr>
</table>
</form>
<?php
if($msgError)
echo $msgError;
?>
</body>
</html>
<?php
?> | true |
559d9647498b8d0aa5dc9a654b47603d44276d52 | PHP | selimppc/fitbody | /protected/models/Shop.php | UTF-8 | 11,411 | 2.53125 | 3 | [] | no_license | <?php
class Shop extends CActiveRecord {
const STATUS_ACTIVE = 1;
const STATUS_INACTIVE = 0;
const PLACE_NEW = 1;
const PLACE_NOT_NEW = 0;
const PAGINATION_COUNT_SHOPS = 12;
public $validLink = true;
public $addresses = array();
public $radio = 0;
public $chainObject;
private $_urlAbout;
private $_mainImageUrl;
public static function model($className = __CLASS__) {
return parent::model($className);
}
public function rules() {
return array(
array('title, description, short_description, categories, image_id', 'required'),
array('title', 'unique'),
array('title, description, short_description, site', 'length', 'min'=> 2),
array('status, pick, chain_id, image_id', 'numerical', 'integerOnly' => true),
array('image_id', 'exist', 'className' => 'Image', 'attributeName' => 'id'),
array('radio','safe'),
array('status', 'in', 'range'=>array(self::STATUS_ACTIVE, self::STATUS_INACTIVE)),
array('is_new_place', 'in', 'range'=>array(self::PLACE_NEW, self::PLACE_NOT_NEW)),
);
}
public function tableName() {
return 'shop';
}
public function relations() {
return array(
'image' => array(self::HAS_ONE, 'Image', array('id' => 'image_id')),
'categories' => array(self::HAS_MANY, 'ShopCategoryLink', array('shop_id' => 'id')),
'addressesRel' => array(self::HAS_MANY, 'ShopAddress', array('shop_id' => 'id')),
'images' => array(self::MANY_MANY, 'Image', 'shop_image(shop_id, image_id)'),
'reviewsRel' => array(self::HAS_MANY, 'ShopReview', array('material_id' => 'id')),
);
}
public function attributeLabels() {
return array(
'id' => 'ID',
'site' => 'Сайт',
'title' => 'Название',
'categories' => 'Категории',
'addresses' => 'Адреса',
'short_description' => 'Краткое описание',
'description' => 'Описание',
'status' => 'Статус',
'pick' => 'Выделить',
'radio' => 'Сеть',
'chain_id' => 'Название сети',
'image_id' => 'Главное изображение'
);
}
public function beforeSave() {
if (!Yii::app()->request->isAjaxRequest) {
if(intval($this->radio) == 2){
$this->chainObject->save(false);
if($this->chainObject->id) $this->chain_id = $this->chainObject->id;
}
}
return parent::beforeSave();
}
public function behaviors() {
return array(
'sluggable' => array(
'class'=>'ext.behaviors.SluggableBehavior.SluggableBehavior',
'columns' => array('title'),
'unique' => true,
'update' => true,
'translit' => true
),
);
}
public function afterValidate () {
if (!Yii::app()->request->isAjaxRequest) {
if (is_array($this->categories) && count($this->categories)) {
foreach ($this->categories as $item) {
$shopCategoriesLink = new ShopCategoryLink();
$shopCategoriesLink->category_id = $item;
if (!$shopCategoriesLink->validate()) {
$this->validLink = false;
$this->addError('categories', 'Одна из выбранных категорий отсутствует');
break;
}
}
}
if (is_array($this->addresses) && count($this->addresses)) {
foreach ($this->addresses as $item) {
if (!$item->validate() || !$item->valid) {
$this->validLink = false;
}
}
}
if(intval($this->radio) == 2){
if (!$this->chainObject->validate()) {
$this->validLink = false;
}
}
}
return parent::afterValidate();
}
public function afterSave() {
if (!Yii::app()->request->isAjaxRequest) {
ShopCategoryLink::model()->deleteAll('shop_id = :shop_id', array(':shop_id' => $this->id));
if (is_array($this->categories) && count($this->categories)) {
foreach ($this->categories as $item) {
$shopCategoriesLink = new ShopCategoryLink();
$shopCategoriesLink->category_id = $item;
$shopCategoriesLink->shop_id = $this->id;
$shopCategoriesLink->save(false);
}
}
ShopAddress::model()->deleteAll('shop_id = :shop_id', array(':shop_id' => $this->id));
if (is_array($this->addresses) && count($this->addresses)) {
foreach ($this->addresses as $item) {
$item->shop_id = $this->id;
$item->save(false);
}
}
}
return parent::afterSave();
}
public static function getPickedShops($category_id){
$criteria = new CDbCriteria();
if($category_id){
$criteria->condition = "t.status = :status AND t.pick = :pick AND categories.category_id = :category_id";
$criteria->params = array(':status' => self::STATUS_ACTIVE, ':pick' => self::STATUS_ACTIVE, ':category_id' => intval($category_id));
} else {
$criteria->condition = "t.status = :status AND t.pick = :pick";
$criteria->params = array(':status' => self::STATUS_ACTIVE, ':pick' => self::STATUS_ACTIVE);
}
$criteria->order = 't.title';
$criteria->with = array('images','categories','addressesRel' => array('with' => array('city','phones','worktimes')));
return Shop::model()->findAll($criteria);
}
public function getShops($category_id){
$criteria = new CDbCriteria();
if(intval($category_id)){
$criteria->condition = "t.status = :status AND t.pick = :pick";
$criteria->params = array(':status' => self::STATUS_ACTIVE , ':category_id' => $category_id, ':pick' => self::STATUS_INACTIVE);
$criteria->order = 't.title';
$criteria->with = array('images','categories' => array('together'=>true, 'condition' => "categories.category_id = :category_id", 'params' => array(':category_id' => intval($category_id))),'addressesRel' => array('with' => array('city','phones','worktimes')));
} else {
$criteria->condition = "t.status = :status AND t.pick = :pick";
$criteria->params = array(':status' => self::STATUS_ACTIVE, ':pick' => self::STATUS_INACTIVE);
$criteria->order = 't.title';
$criteria->with = array('images','categories','addressesRel' => array('with' => array('city','phones','worktimes')));
}
return new CActiveDataProvider(__CLASS__, array(
'criteria' => $criteria,
'pagination' => array(
'pageSize' => self::PAGINATION_COUNT_SHOPS,
'pageVar' => 'page'
)
));
}
public static function getShopsInRange($lat, $lon, $range, $category_id = false){
$criteria = new CDbCriteria();
$criteria->condition = "t.status = :status";
$criteria->params = array(':status' => self::STATUS_ACTIVE);
$criteria->order = 'distance DESC';
$criteria->with = array(
'images',
'categories' => $category_id ? array('together'=>true, 'condition' => "categories.category_id = :category_id", 'params' => array(':category_id' => $category_id)) : array(),
'addressesRel' => array(
'with' => array(
'city',
'phones',
'worktimes'
),
'select' => array(
'addressesRel.*',
'(6371*1000*acos(cos(RADIANS(addressesRel.lat))*cos(RADIANS(:lat))*cos(RADIANS(:lon)-RADIANS(addressesRel.lon))+sin(RADIANS(addressesRel.lat))*sin(RADIANS(:lat)))) as distance',
),
'params' => array(':lat' => $lat, ':lon' => $lon, ':range' => $range),
'condition' => '(6371*1000*acos(cos(RADIANS(addressesRel.lat))*cos(RADIANS(:lat))*cos(RADIANS(:lon)-RADIANS(addressesRel.lon))+sin(RADIANS(addressesRel.lat))*sin(RADIANS(:lat)))) < :range',
),
);
return Shop::model()->findAll($criteria);
}
public static function getShopBySlug($slug){
$criteria = new CDbCriteria();
$criteria->condition = 't.slug = :slug AND t.status = :status';
$criteria->params = array(':slug' => $slug, ':status' => self::STATUS_ACTIVE);
$criteria->with = array(
'images',
'addressesRel' => array(
'with' => array(
'city',
'phones',
'worktimes'
),
),
);
return Shop::model()->find($criteria);
}
public function statusCondition($status = self::STATUS_ACTIVE) {
$this->getDbCriteria()->mergeWith(array(
'condition'=> 'status = :status',
'params' => array(':status' => $status)
));
return $this;
}
public function fetchNewPlaces() {
$criteria = new CDbCriteria();
$criteria->with = array('image', 'addressesRel');
$criteria->condition = 't.is_new_place = :isNewPlace';
$criteria->params = array(':isNewPlace' => self::PLACE_NEW);
return $this->statusCondition()->findAll($criteria);
}
public function addMainImage($imageId, $itemId = null) {
if ($itemId) {
if ($item = self::findByPk($itemId)) {
if($item->image_id) {
Yii::app()->image->delete($item->image_id);
}
$item->image_id = (int) $imageId;
$item->update();
}
}
}
public function getUrlAbout() {
if ($this->_urlAbout === null) {
$this->_urlAbout = Yii::app()->createUrl('shop/' . $this->slug . '/about');
}
return $this->_urlAbout;
}
public function getMainImageUrlSearch() {
if ($this->_mainImageUrl === null) {
if ($this->image) {
$this->_mainImageUrl = '/pub/shop/main/130x90/' . $this->image->image_filename;
} else {
$this->_mainImageUrl = '/images/blank/130x90.gif';
}
}
return $this->_mainImageUrl;
}
public function fetchShopsByIds($ids = array()) {
$criteria = new CDbCriteria();
$criteria->addInCondition('shop_id', $ids);
$criteria->with = array('image', 'addressesRel' => array('with' => array('phones')));
return Shop::model()->findAll($criteria);
}
public function getNewPlaceImagePath() {
if ($this->image) {
return '/pub/shop/main/230x160/' . $this->image->image_filename;
}
return '/images/blank/230x160.gif';
}
} | true |
1cf7a5be3e1b5835db562525f558b23c6b9fcd41 | PHP | samiul-sheikh/PHP_Array_Function | /array.php | UTF-8 | 1,995 | 2.5625 | 3 | [] | no_license | <!docttype html>
<html>
<head>
<title> PHP Syntax </title>
<style>
.phpcoding{width:900px; margin:0 auto; background:grey; min-height: 400px;}
.headerportion, .footerportion{background:#444; color:white; text-align: center; padding: 20px;}
.headerportion h2, .footerportion h2{margin:0;}
.maincontent{min-height: 400px; padding: 20px;}
p{margin: 0}
</style>
</head>
<body>
<div class ="phpcoding">
<section class="headerportion">
<h2> <?php echo "PHP Fundamental" ?> </h2>
</section>
<section class="maincontent">
<?php
/*
$dept = array("SE", "CSE", "CSSE", "CIS", "BBA", "MBA");
$length = count($dept);
// echo $length;
for($i = 0; $i < $length; $i++){
echo $dept[$i];
echo "<br/>";
}
*/
/*
$name = array("Sami" => "25", "Tusher" => "18", "Tanvir" => "27");
$length = count($name);
foreach($name as $key=>$values){
echo "Name : ".$key. ", Age : ".$values;
echo "<br/>";
}
*/
$car = array(
array("toyota", "volvo", "audi"),
array("pulser", "discover", "tvs"),
array("r15", "v2", "v3"),
array("hunk", "glamer", "repsol")
);
echo $car[3][2];
?>
</section>
<section class="footerportion">
<p> © <?php echo date("Y") ?> Samiul Sheikh </p>
<h2> <?php echo "Presented By - Samiul Sheikh" ?> </h2>
</section>
</div>
</body>
</html>
| true |
75e1ddc55c1717f3930a1dc4c22e4e61ad3a7041 | PHP | shalhavit/a3 | /app/Http/Controllers/InspectorController.php | UTF-8 | 1,506 | 2.578125 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Twitter;
use File;
class InspectorController extends Controller {
/**
* Post a new tweet to the user account.
*
* @return void
*/
public function postNewTweet(Request $request) {
$this->validate($request, [
'tweet' => 'required | max:140',
]);
$newTweet = ['status' => $request->tweet];
// Load images
if(!empty($request->images)) {
foreach ($request->images as $key => $value) {
$img_uploaded = Twitter::uploadMedia(['media' => File::get($value->getRealPath())]);
if(!empty($img_uploaded)){
$newTweet['media_ids'][$img_uploaded->media_id_string] = $img_uploaded->media_id_string;
}
}
}
$twitter = Twitter::postTweet($newTweet);
return back();
}
/**
* update the user twitter time line.
*
* @return view
*/
public function getTwitterUserTimeline(Request $request, $count = 20) {
// The validation of multiple forms requires further research,
// by now was validated with html5 rules
// $this->validate($request, [
// 'numTweets' => 'required | integer',
// ]);
$data = Twitter::getUserTimeline(['count' => $request->input('numTweets'), 'format' => 'array']);
return view('inspector', compact('data'))->with([
'numTweets' => $request->input('numTweets'),
]);
}
}
| true |
3125a96ba8c6fb2ebfd1a3ec89871545325cbb33 | PHP | phpjungle/Delete-File-with-Filters | /main.php | UTF-8 | 2,049 | 3 | 3 | [] | no_license | <?php
error_reporting(E_ERROR);
/**
* 移除某个目录下面所有$filter文件目录
*
* @author PHPJungle
* @since 15.01.21 周三
* @param 根目录 $path
* @param 需要删除的文件夹名字 $filter
* @return NULL|boolean
*/
function del_dir_filter($path,$filter='.svn'){
if(!is_dir($path)){
return null;
}
$fh = opendir($path);
while(($row = readdir($fh)) !== false){ //Read entry from directory handle=> string the filename on success&return.falseforfailure;.
//过滤掉虚拟目录
if($row == '.' || $row == '..'){
continue;
}
$sub_path=$path.'/'.$row;
// 过滤文件
if(!is_dir($sub_path)){
continue;
}
// 找到目标文件夹
if($row===$filter){
del_dir($sub_path); // 整个删除
continue;
}
// 过滤完剩下的目录继续递归
del_dir_filter($sub_path);
}
//关闭目录句柄,否则出Permission denied
closedir($fh);
return true;
}
/**
* 删除指定文件夹(包括所有子文件和文件夹)
*
* @author PHPJungle
* @since 15.01.21 周三
* @param string $path
* @return NULL boolean
*/
function del_dir($path) {
//给定的目录不是一个文件夹
if(!is_dir($path)){
return null;
}
$fh = opendir($path);
while(($row = readdir($fh)) !== false){
//过滤掉虚拟目录
if($row == '.' || $row == '..'){
continue;
}
$file_path=$path.'/'.$row;
if(!is_dir($file_path)){
($status_del=unlink($file_path)) or print('file:'.$file_path.' no permission to delete<hr>');
!$status_del or print('file:'.$file_path.' has been deleted!<hr>');
continue;
}
del_dir($file_path); // 如果是文件就没必要递归进去了
}
//关闭目录句柄,否则出Permission denied
closedir($fh);
//删除文件之后再删除自身
if(!rmdir($path)){
echo 'directory:',$path,' no permission to delete<hr>';
}else{
echo 'directory:',$path,' has been deleted!<hr>';
}
return true;
}
# Demo
$del=__DIR__.'/www/'; // 删除xxx目录下包含.svn的文件夹所有内容
del_dir_filter($del,'.svn');
| true |
3e80912d2f3827c6753adc77b7a8a48529eda711 | PHP | MkSaqo/M_Films | /template/functions.php | UTF-8 | 1,378 | 2.53125 | 3 | [] | no_license | <?php
session_start();
function pre($var){
echo "<pre>";
print_r($var);
echo "</pre>";
}
function dbConnect(){
$db = mysqli_connect('localhost','root','root','Filmer');
mysqli_set_charset($db, "utf8");
date_default_timezone_set ( 'Europe/Moscow' );
return $db;
}
function check($page){
$pages = array("cat.php","admin.php","film.php","home.php","reg.php","search.php");
for($i=0;$i<count($pages);$i++){
if($page == $pages[$i]){
return true;
}
}
}
function addLog(){
$NEW_LOG_MESSAGE = '-----NEW LOG----';
$HTTP_HOST =$_SERVER['HTTP_HOST'];
$HTTP_USER_AGENT =$_SERVER['HTTP_USER_AGENT'];
$URL =$HTTP_HOST.$_SERVER['PHP_SELF'];
$HTTP_COOKIE =$_SERVER['HTTP_COOKIE'];
$SERVER_SIGNATURE =$_SERVER['SERVER_SIGNATURE'];
$SERVER_ADMIN =$_SERVER['SERVER_ADMIN'];
$NAME = isset($_SESSION['name']) ? $_SESSION['name'] : "Guest";
$message = PHP_EOL.PHP_EOL.$NEW_LOG_MESSAGE.PHP_EOL.date('Y.m.d h:i:s').PHP_EOL.$NAME.PHP_EOL.$HTTP_HOST.PHP_EOL.$HTTP_USER_AGENT.PHP_EOL.$URL.PHP_EOL.$HTTP_COOKIE.PHP_EOL.$SERVER_SIGNATURE.PHP_EOL.$SERVER_ADMIN;
$file = fopen('../logs/log.log','a+');
fwrite($file, $message);
fclose($file);
}
// function error_found(){
// header("Location: 404.php");
// }
// set_error_handler('error_found');
// header('X-XSS-Protection:0');
?> | true |
f9dc6a27b08297331c0788d9e3ce05046489b755 | PHP | patilvivek261/registration | /app/Controllers/PortfolioController.php | UTF-8 | 929 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
/**
*
*/
namespace App\Controllers;
use CodeIgniter\Controller;
class PortfolioController extends Controller{
function __construct(){
helper(['url','text']);
}//end function __constructor()
public function portfolio(){
$data1 = [
'pageTitle' => 'Portfolio Title Controller',
'pageHeading' =>'Portfolio Page from Heading from Controller ',
];
echo view("portfolio_page.php",$data1);
return TRUE;
}//end function portfolio()
public function _remap($method,$param1=NULL,$param2=NULL){
if(method_exists($this, $method))
{
return $this->$method($param1,$param2);
}//end if menthod_exists()
else
{
return $this->portfolio();
}
}//end function _remap()
}//end class PortfolioController
?> | true |
ffbc2a46b684256a8c09faa3b1aa4dd17a74dc94 | PHP | piratesmanX1/shoppa-2020 | /process_contact.php | UTF-8 | 1,036 | 2.671875 | 3 | [
"Apache-2.0"
] | permissive | <?php
// we will only start the session with session_start() IF the session isn"t started yet //
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
?>
<?php
// including the conn.php to establish connection with database //
include "conn.php";
?>
<?php
//search product from home
if(isset($_POST['contact_admin'])){
// $email = $_POST['email'];
$message = $_POST['message'];
$username = $_POST['username'];
$today = date('Y-m-d');
$user_id = $_SESSION['user_id'];
$contact_status = 0;
//INSERT NEW MESSAGE
$stmt1 = $db -> prepare("INSERT INTO `contact`(`contact_date`, `contact_content`, `contact_status`, `user_id`) VALUES (?,?,?,?); ");
$stmt1 ->bind_param("ssss", $today, $message, $contact_status, $user_id);
$stmt1->execute();
if(mysqli_affected_rows($db)>0){
echo "Message Sent ";
} else {
echo "failed";
}
$stmt1->close();
mysqli_close($db);
}
?>
| true |
e89c237e74cd0654d035bfd036fd43c7652cd1a1 | PHP | Moshamohamed/NPD-FIRST | /vendor/Routing/Router.php | UTF-8 | 940 | 2.90625 | 3 | [] | no_license | <?php
namespace Routing;
use Config\ConfigRepository as config;
use Http\Request;
class Router{
/**
* routes of the current script
*
* @var array
*/
private $routes = array();
/**
* not found route
*
* @var mixed
*/
private $notFound;
/**
* set the main routes of the current scripts
*
* @param array $rotues
* @return void
*/
public function __construct(array $routes)
{
if(isset($routes['routes']))
{
$this->routes = $routes['routes'];
}
if(isset($routes['not-found']))
{
$this->notFound = $routes['not-found'];
}
}
/**
* get the data of not found controller
*
* @return mixed
*/
public function getNotFound()
{
return $this->notFound;
}
/**
* return all paths for current script
*
* @return array
*/
public function getScriptRoutes()
{
return $this->routes;
}
} | true |
048b14aaa13d2244343ecb29356fe7ad3ae3392b | PHP | hostnet/type-inference-tool | /test/Analyzer/Data/AnalyzedFunctionCollectionTest.php | UTF-8 | 7,092 | 2.546875 | 3 | [
"MIT"
] | permissive | <?php
/**
* @copyright 2017-2018 Hostnet B.V.
*/
declare(strict_types=1);
namespace Hostnet\Component\TypeInference\Analyzer\Data;
use Hostnet\Component\TypeInference\Analyzer\Data\Exception\EntryNotFoundException;
use Hostnet\Component\TypeInference\Analyzer\Data\Type\NonScalarPhpType;
use Hostnet\Component\TypeInference\Analyzer\Data\Type\ScalarPhpType;
use Hostnet\Component\TypeInference\CodeEditor\Instruction\ReturnTypeInstruction;
use Hostnet\Component\TypeInference\CodeEditor\Instruction\TypeHintInstruction;
use PHPUnit\Framework\TestCase;
/**
* @covers \Hostnet\Component\TypeInference\Analyzer\Data\AnalyzedFunctionCollection
*/
class AnalyzedFunctionCollectionTest extends TestCase
{
/**
* @var AnalyzedFunctionCollection
*/
private $collection;
protected function setUp()
{
$this->collection = new AnalyzedFunctionCollection();
}
public function testAddAllFunctionsShouldAddAllNonDuplicates()
{
$namespace = 'Just\\Some\\Namespace';
$class_name = 'SomeClass';
$function_name = 'SomeFunction';
$class = new AnalyzedClass($namespace, $class_name, '', null, [], []);
$analyzed_function_0 = new AnalyzedFunction($class, $function_name);
$analyzed_function_0->addCollectedReturn(new AnalyzedReturn(new NonScalarPhpType('', 'ObjA', '', null, [])));
$analyzed_function_0->addCollectedArguments(new AnalyzedCall([new NonScalarPhpType('', 'ObjA', '', null, [])]));
$analyzed_function_1 = new AnalyzedFunction($class, $function_name);
$analyzed_function_1->addCollectedReturn(new AnalyzedReturn(new NonScalarPhpType('', 'ObjB', '', null, [])));
$this->collection->addAll([$analyzed_function_0, $analyzed_function_1]);
$amount_functions = 0;
foreach ($this->collection as $i => $analyzed_function) {
$amount_functions = $i + 1;
self::assertCount(2, $analyzed_function->getCollectedReturns());
self::assertCount(1, $analyzed_function->getCollectedArguments());
}
self::assertSame(1, $amount_functions);
self::assertSame($class, $this->collection->getClass($namespace . '\\' . $class_name));
}
public function testMethodsInClassShouldHaveSameClassObject()
{
$class_0 = new AnalyzedClass('Namespace', 'ClassName', 'Class.php', null, []);
$class_1 = new AnalyzedClass('Namespace', 'ClassName', 'Class.php', null, []);
$class_method_1 = new AnalyzedFunction($class_0, 'Function1');
$class_method_2 = new AnalyzedFunction($class_1, 'Function2');
$this->collection->add($class_method_1);
$this->collection->add($class_method_2);
foreach ($this->collection as $analyzed_function) {
$methods_in_class = $analyzed_function->getClass()->getMethods();
self::assertCount(2, $methods_in_class);
self::assertContains('Function1', $methods_in_class);
self::assertContains('Function2', $methods_in_class);
}
self::assertCount(2, $this->collection->getAll());
}
public function testAddAllShouldMergeAnalyzedFunctions()
{
$extended = new AnalyzedClass('Namespace', 'AbstractClassName', 'file2.php');
$implemented = new AnalyzedClass('Namespace', 'ClassNameInterface', 'file3.php');
$analyzed_functions_0 = [new AnalyzedFunction(new AnalyzedClass('Namespace', 'ClassName'), 'foobar')];
$analyzed_functions_1 = [
new AnalyzedFunction(
new AnalyzedClass('Namespace', 'ClassName', 'file.php', $extended, [$implemented]),
'foobar'
),
];
$expected = [
new AnalyzedFunction(
new AnalyzedClass('Namespace', 'ClassName', 'file.php', $extended, [$implemented], ['foobar']),
'foobar'
),
];
$this->collection->addAll($analyzed_functions_0);
$this->collection->addAll($analyzed_functions_1);
$results = $this->collection->getAll();
self::assertCount(1, $results);
self::assertEquals($expected, $results);
}
public function testApplyInstructionsShouldApplyInstructionsToAnalyzedFunctions()
{
$class = new AnalyzedClass('Namespace', 'ClassName', 'file.php', null, [], ['foobar']);
$function = new AnalyzedFunction($class, 'foobar', null, false, [new AnalyzedParameter()]);
$this->collection->add($function);
$return_type = new ScalarPhpType(ScalarPhpType::TYPE_FLOAT);
$return_type_instruction = new ReturnTypeInstruction($class, 'foobar', $return_type);
$parameter_type = new ScalarPhpType(ScalarPhpType::TYPE_STRING);
$type_hint_instruction = new TypeHintInstruction($class, 'foobar', 0, $parameter_type);
$this->collection->applyInstructions([$return_type_instruction, $type_hint_instruction]);
self::assertSame($return_type->getName(), $this->collection->getAll()[0]->getDefinedReturnType());
self::assertSame(
$parameter_type->getName(),
$this->collection->getAll()[0]->getDefinedParameters()[0]->getType()
);
}
public function testGetFunctionChildrenShouldReturnAllChildClassesImplementingAFunction()
{
$parent_class = new AnalyzedClass('Namespace', 'ClazzInterface', 'File1.php', null, [], ['foobar']);
$child = new AnalyzedClass('Namespace', 'Clazz', 'File2.php', null, [$parent_class], ['foobar']);
$child_function = new AnalyzedFunction($child, 'foobar');
$other_class_1 = new AnalyzedClass('Namespace', 'Foobar', 'File3.php', null, [], ['foobar']);
$other_class_1_function = new AnalyzedFunction($other_class_1, 'foobar');
$other_class_2 = new AnalyzedClass('Namespace', 'AbstractClazz', 'File3.php', null, []);
$other_class_2_function = new AnalyzedFunction($other_class_2, 'someFunction');
$this->collection->addAll([$child_function, $other_class_1_function, $other_class_2_function]);
$parent_children = $this->collection->getFunctionChildren($parent_class, 'foobar');
self::assertCount(1, $parent_children);
self::assertSame($child, $parent_children[0]);
}
public function testGetClassShouldRetrieveAnAnalyzedClassWithTheCorrectFqcn()
{
$namespace = 'Just\\Some\\Namespace';
$class_name = 'ClassName';
$class = new AnalyzedClass($namespace, $class_name, 'file.php', null, [], ['foobar']);
$function = new AnalyzedFunction($class, 'foobar', null, false, [new AnalyzedParameter()]);
$this->collection->add($function);
self::assertSame($class, $this->collection->getClass($namespace . '\\' . $class_name));
}
public function testWhenGetClassIsCalledWithInvalidFqcnThenEntryShouldNotBeFound()
{
$this->expectException(EntryNotFoundException::class);
$this->collection->getClass('Non\\Existent::Class');
}
}
| true |
cf174dfd3c31c1728b30f3814f57cd4bc12bc3f0 | PHP | nh3500/NMS | /admin/admin_edit.php | UTF-8 | 1,444 | 2.796875 | 3 | [] | no_license | <?php
include_once("../sys/check_session.inc.php");
header('Content-Type: text/html; charset=utf-8');
include("../sys/sqlconnect.inc.php");
//如果以 GET 方式傳遞過來的 edit 參數不是空字串
if ($_GET['edit'] !=''){
//查詢 edit 參數所指定帳號的記錄, 從資料庫將原有的資料取出
$sql="SELECT * FROM `ADMIN` WHERE username='{$_GET['edit']}' ";
$result=mysql_query($sql);
//將查詢到的資料放在 $row 陣列
$row=mysql_fetch_array($result);
}
else {
//如果沒有 edit 參數, 表示此為錯誤執行, 所以轉向回原頁面
header("Location: admin.php");
}
?>
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type">
<title>網管系統個人資料編輯頁面</title>
</head>
<body>
<!個人資料編輯頁面>
<form id="form1" name="form1" method="post" action="admin_update.php">
<label for="textfield"></label>
User:
<input maxlength="15" name="username" value="<?php echo $row[1]; ?>"/>
Password:
<input type="password" maxlength="12" name="passwd" value="<?php echo $row[0]; ?>"/>
Realname:
<input name="realname" value="<?php echo $row[2]; ?>"/>
Phone:
<input name="phone" value="<?php echo $row[3]; ?>"/>
E-mail:
<input name="email" value="<?php echo $row[4]; ?>"/>
<input name="submit" type="submit" value="修改" />
</form>
<p><a href="admin.php">回管理員清單</a></p>
</body>
</html> | true |
d38c16569d68561c02f8f05736983f298cc8107b | PHP | wahc1983/blog | /db/createDataBase.php | UTF-8 | 451 | 3.015625 | 3 | [] | no_license | <?php
$host = 'localhost';
$username = 'root';
$passwd = '1234abcd';
$con=mysqli_connect($host,$username,$passwd);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Create database
$sql="CREATE DATABASE myblog";
if (mysqli_query($con,$sql))
{
echo "Database my_db created successfully";
}
else
{
echo "Error creating database: " . mysqli_error($con);
}
| true |
104bc916db4978fa59d646a444bcb717417ff554 | PHP | RajaBalawal/CarProject | /Admin_area/Update.php | UTF-8 | 3,940 | 2.578125 | 3 | [] | no_license | <?php
include 'auth.php';
require 'dbconnect.php';
if(isset($_POST['update'])){
// Getting data from the fields
$cars_id = mysqli_escape_string($con, $_POST['CarId']);
$car_make = mysqli_escape_string($con,$_POST['CarMake']);
$car_model = mysqli_escape_string($con,$_POST['CarModel']);
$car_reg = mysqli_escape_string($con,$_POST['CarReg']);
$car_desc = mysqli_escape_string($con,$_POST['CarDesc']);
$car_engine = mysqli_escape_string($con,$_POST['EngineSize']);
$car_fuel = mysqli_escape_string($con,$_POST['Fuel']);
$car_milage = mysqli_escape_string($con,$_POST['CarMilage']);
$car_price = mysqli_escape_string($con,$_POST['Price']);
$car_year = mysqli_escape_string($con,$_POST['CarYear']);
$car_tax = mysqli_escape_string($con,$_POST['CarTax']);
$car_transmission = mysqli_escape_string($con,$_POST['Transmission']);
// sending the data to the database
$updateCar = "Update cars Set Make = ?, Model = ?,CarReg = ?,CarDesc = ?,EngineSize = ?,Fuel = ?,CarMilage = ?, Price = ?, CarYear = ?,TAX = ?, Transmission = ? where CarId= ?";
$images = "Select * from carimages where Car_id = '$cars_id'";
$res = mysqli_query($con,$images);
while ($row = mysqli_fetch_assoc($res)) {
$url = $row["FilePath"] . "" . $row["FileName"];
//Deleting the images from the directory
unlink($url);
}
$statement = $con->prepare($updateCar);
$statement->bind_param('ssssssiiiisi',$car_make,$car_model,$car_reg,$car_desc,$car_engine,$car_fuel,$car_milage,$car_price,$car_year,$car_tax,$car_transmission,$cars_id);
$statement->execute();
$statement->close();
$deleteimage = "Delete from carimages where Car_id = ? ";
$statement = $con->prepare($deleteimage);
$statement->bind_param('i',$cars_id);
$statement->execute();
$statement->close();
$errors = array();
$extension = array("jpeg","jpg","png","gif");
$bytes = 100024;
$allowedKB = 10000;
$totalBytes = $allowedKB * $bytes;
foreach($_FILES["files"]["tmp_name"] as $key=>$tmp_name)
{
$uploadThisFile = true;
$file_name=$_FILES["files"]["name"][$key];
$file_tmp=$_FILES["files"]["tmp_name"][$key];
$ext=pathinfo($file_name,PATHINFO_EXTENSION);
if(!in_array(strtolower($ext),$extension))
{
array_push($errors, "File type is invalid. Name:- ".$file_name);
$uploadThisFile = false;
}
if($_FILES["files"]["size"][$key] > $totalBytes){
array_push($errors, "File size must be less than 1000KB. Name:- ".$file_name);
$uploadThisFile = false;
}
if(file_exists("car_images/".$_FILES["files"]["name"][$key]))
{
array_push($errors, "File is already exist. Name:- ". $file_name);
$uploadThisFile = false;
}
if($uploadThisFile){
$filename=basename($file_name,$ext);
$newFileName=$filename.$ext;
$path = 'car_images/';
move_uploaded_file($_FILES["files"]["tmp_name"][$key],$path.$newFileName);
//$query = "INSERT INTO carimages (ID,Car_id,FilePath, FileName) VALUES('','','car_images','".$newFileName."')";
$insertPics = 'Insert into carimages (Car_id,FileName,FilePath)Values(?,?,?)';
$statement = $con->prepare($insertPics);
$statement->bind_param('iss',$cars_id,$newFileName,$path);
$statement->execute();
$statement->close();
}
}
echo'<h1>Successfully Updated </h1>'.$cars_id;
echo "<meta http-equiv='refresh' content='5;url=index.php'>";
}else{
echo'<h1 align="center">Error Try again</h1>';
}
?> | true |
326371390440573fb6bd2f66c72761cd15e8b6ef | PHP | CollectiveDesign/nova-page | /src/Pages/TemplatesRepository.php | UTF-8 | 3,016 | 2.921875 | 3 | [
"MIT"
] | permissive | <?php
namespace Whitecube\NovaPage\Pages;
use Route;
use Whitecube\NovaPage\Exceptions\TemplateNotFoundException;
class TemplatesRepository
{
/**
* The registered Templates
*
* @var array
*/
protected $templates = [];
/**
* The registered pages
*
* @var array
*/
protected $pages = [];
/**
* The loaded page templates
*
* @var array
*/
protected $loaded = [];
/**
* Fill the repository with registered routes
*
* @return void
*/
public function registerRouteTemplates()
{
foreach (Route::getRoutes()->getRoutes() as $route) {
if(!$route->template()) continue;
$this->register('route', $route->getName(), $route->template());
}
}
/**
* Get all registered templates
*
* @return array
*/
public function getTemplates()
{
return $this->templates;
}
/**
* Get all registered pages
*
* @return array
*/
public function getPages()
{
return $this->pages;
}
/**
* Get a registered page template by its key
*
* @param string $name
* @return null|Whitecube\NovaPage\Pages\Template
*/
public function getPageTemplate($name)
{
if(array_key_exists($name, $this->pages)) {
return $this->templates[$this->pages[$name]];
}
}
/**
* Load a new Page Template Instance
*
* @param string $type
* @param string $key
* @param bool $throwOnMissing
* @return Whitecube\NovaPage\Pages\Template
*/
public function load($type, $key, $throwOnMissing)
{
$name = $type . '.' . $key;
if(!($template = $this->getPageTemplate($name))) {
throw new TemplateNotFoundException($this->pages[$name] ?? null, $name);
}
if(!isset($this->loaded[$name])) {
$this->loaded[$name] = $template->getNewTemplate($type, $key, $throwOnMissing);
}
else {
$this->loaded[$name]->load($throwOnMissing);
}
return $this->loaded[$name];
}
/**
* Get a loaded page template by its key
*
* @param string $type
* @param string $key
* @return null|Whitecube\NovaPage\Pages\Template
*/
public function getLoaded($type, $key)
{
foreach ($this->loaded as $identifier => $template) {
if($identifier === $type . '.' . $key) return $template;
}
}
/**
* Add a page template
*
* @param string $type
* @param string $key
* @param string $template
* @return Whitecube\NovaPage\Pages\Template
*/
public function register($type, $key, $template)
{
if(!array_key_exists($template, $this->templates)) {
$this->templates[$template] = new $template;
}
$this->pages[$type . '.' . $key] = $template;
return $this->templates[$template];
}
} | true |
f80a01a40766fa3982ad264bc06fbdb05bf89d02 | PHP | limhyejeong/onlineskillup_step1 | /app/sql.php | UTF-8 | 1,389 | 2.90625 | 3 | [] | no_license | <?php
$dsn = 'pgsql:dbname=TEST;host=pgsql;port=5432';
$user = 'postgres';
$pass = 'example';
try {
// DB에 접속
$dbh = new PDO($dsn, $user, $pass);
// 여기서 쿼리실행
// query 메소드(SELECT)
$query_result = $dbh -> query('SELECT * FROM board');
// query 메소드(INSERT)
$sth = $dbh->prepare('INSERT INTO board (name, title, content, password, email) VALUES (?, ?, ?, ?, ?)');
// prepare 메소드 (SELECT)
$sth_select = $dbh->prapare('SELECT * FROM board WHERE name = ?');
// DB를 절단
$dbh = null;
} catch (PDOException $e) {
// 접속에 에러가 발생한 경우
print "DB ERROR : " . $e->getMessage() . "<br/>";
die();
}
?>
<?php
foreach($query_result as $row) {
print $row["name"] . " : " . $row["title"] . "<br/>";
}
?>
<?php
$name = "쿠쿠맘";
$title = "아이와 자연체험하며 놀 수 있는 곳";
$content = "따뜻한 봄날, 아이와 함께 자연의 아름다움도 살펴보고 자연 속에서 신나는 시간을 보내며 좋은 추억을 쌓아보아요!";
$password = "k11";
$email = "koomom@gmail.com";
$sth->execute(array($name, $title, $content, $password, $email));
?>
<?php
$name = "김경래";
$sth_select->execute(array($name));
$prepare_result = $sth_select->fetchAll();
foreach($prepare_result as $row) {
print $row["name"] . " : " . $row["text"] . "<br/>";
}
$sth_select->execute(array($name));
?> | true |
e0346b3c555307f4c9cbbddf85793f3b5fc6d20a | PHP | darchipov/Commerce | /Subject/Model/SubjectInterface.php | UTF-8 | 2,299 | 2.734375 | 3 | [
"MIT"
] | permissive | <?php
namespace Ekyna\Component\Commerce\Subject\Model;
use Doctrine\Common\Collections\ArrayCollection;
use Ekyna\Component\Commerce\Pricing\Model\TaxGroupInterface;
/**
* Interface SubjectInterface
* @package Ekyna\Component\Commerce\Subject\Model
* @author Etienne Dauvergne <contact@ekyna.com>
*/
interface SubjectInterface
{
/**
* Returns the id.
*
* @return int
*/
public function getId();
/**
* Returns the designation.
*
* @return string
*/
public function getDesignation();
/**
* Sets the designation.
*
* @param string $designation
* @return $this|SubjectInterface
*/
public function setDesignation($designation);
/**
* Returns the reference.
*
* @return string
*/
public function getReference();
/**
* Sets the reference.
*
* @param string $reference
* @return $this|SubjectInterface
*/
public function setReference($reference);
/**
* Returns the taxGroup.
*
* @return TaxGroupInterface
*/
public function getTaxGroup();
/**
* Sets the taxGroup.
*
* @param TaxGroupInterface $taxGroup
* @return $this|SubjectInterface
*/
public function setTaxGroup(TaxGroupInterface $taxGroup);
/**
* Returns whether the subject has at least one offer or not.
*
* @return boolean
*/
public function hasOffers();
/**
* Returns the offers.
*
* @return ArrayCollection|OfferInterface[]
*/
public function getOffers();
/**
* Returns whether the subject has the offer or not.
*
* @param OfferInterface $offer
* @return bool
*/
public function hasOffer(OfferInterface $offer);
/**
* Adds the offer.
*
* @param OfferInterface $offer
* @return $this|SubjectInterface
*/
public function addOffer(OfferInterface $offer);
/**
* Removes the offer.
*
* @param OfferInterface $offer
* @return $this|SubjectInterface
*/
public function removeOffer(OfferInterface $offer);
/**
* Sets the offers.
*
* @param ArrayCollection|OfferInterface[] $offers
* @return $this|SubjectInterface
*/
public function setOffers($offers);
}
| true |
71ec0147d162f5b049adaaad7c40c3c3719ee06b | PHP | apioo/psx-api | /src/GeneratorFactory.php | UTF-8 | 2,543 | 2.640625 | 3 | [
"Apache-2.0"
] | permissive | <?php
/*
* PSX is an open source PHP framework to develop RESTful APIs.
* For the current version and information visit <https://phpsx.org>
*
* Copyright 2010-2023 Christoph Kappestein <christoph.kappestein@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace PSX\Api;
use PSX\Api\Repository\LocalRepository;
use PSX\Api\Repository\RepositoryInterface;
/**
* This factory returns a GeneratorRegistry which contains all available generator types and which can be used to obtain
* an actual generator
*
* @author Christoph Kappestein <christoph.kappestein@gmail.com>
* @license http://www.apache.org/licenses/LICENSE-2.0
* @link https://phpsx.org
*/
class GeneratorFactory
{
/**
* @var iterable<RepositoryInterface>
*/
private iterable $repositories;
/**
* @var iterable<ConfiguratorInterface>
*/
private iterable $configurators;
private ?string $baseUrl;
private ?GeneratorRegistry $generatorRegistry = null;
public function __construct(iterable $repositories, iterable $configurators = [], ?string $baseUrl = null)
{
$this->repositories = $repositories;
$this->configurators = $configurators;
$this->baseUrl = $baseUrl;
}
public function factory(?string $baseUrl = null): GeneratorRegistry
{
if (isset($this->generatorRegistry)) {
return $this->generatorRegistry;
}
$this->generatorRegistry = new GeneratorRegistry($this->configurators, $baseUrl ?? $this->baseUrl);
foreach ($this->repositories as $repository) {
$generatorConfigs = $repository->getAll();
foreach ($generatorConfigs as $type => $generatorConfig) {
$this->generatorRegistry->register($type, $generatorConfig);
}
}
return $this->generatorRegistry;
}
/**
* Returns a new generator factory which contains only the local generators
*/
public static function fromLocal(?string $baseUrl = null): self
{
return new self([new LocalRepository()], [], $baseUrl);
}
}
| true |
c01934859ee37118f4f4a5a4e563ef5b1ac15eb9 | PHP | wesleyromualdo/PIM | /includes/library/simec/Importador/Segov.inc | UTF-8 | 5,505 | 2.609375 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: victor
* Date: 05/07/17
* Time: 11:33
*/
require_once APPRAIZ . 'includes/library/simec/Importador.php';
class Importador_Segov extends Importador
{
public function __construct ($model = null)
{
parent::__construct($model);
}
public function validaColuna ($linha, $key, $cLinha, $delimitador)
{
global $tamanhoColunas;
$linhaChave = $cLinha + 2;
$coluna = $this->retornaColuna($key);
switch ($key)
{
case 0:
case 1:
if (strlen(trim($linha[$key])) != $tamanhoColunas[$key])
{
throw new Exception("Esperado valor com {$tamanhoColunas[$key]} caracteres, recebeu " . strlen(trim($linha[$key])) . " - linha: {$linhaChave}, coluna: {$coluna}");
}
break;
case 2:
case 3:
case 4:
case 5:
case 6:
case 9:
case 10:
case 11:
case 14:
case 15:
case 16:
case 17:
case 18:
case 19:
case 24:
case 25:
case 27:
case 28:
if (strlen(trim($linha[$key])) > $tamanhoColunas[$key] || !$linha[$key])
{
throw new Exception("Esperado valor com até {$tamanhoColunas[$key]} caracteres, recebeu " . strlen(trim($linha[$key])) . " - linha: {$linhaChave}, coluna: {$coluna}");
};
break;
case 20:
if (!$linha[$key] && !$linha[$key + 1] && !$linha[$key + 2] && !$linha[$key + 3])
{
throw new Exception("Ao menos um dos quatro campos deve ser preenchidos: Contrato Repasse, Proposta no SICONV, Convênio SIAFI ou Nº de Referência constante na nota de empenho no SIAFI - linha: {$linhaChave}, coluna: {$coluna}");
}
break;
case 21:
case 22:
case 23:
continue;
break;
case 12:
if (strlen(trim($linha[$key])) > $tamanhoColunas[$key])
{
throw new Exception("Esperado valor com até {$tamanhoColunas[$key]} caracteres, recebeu " . strlen(trim($linha[$key])) . " - linha: {$linhaChave}, coluna: {$coluna}");
};
break;
case 7:
case 8:
case 13:
case 26:
if (is_int((int) trim($linha[$key])) == false)
{
throw new Exception("Campo deveria ser um valor numérico - linha: {$linhaChave}, coluna: {$coluna}");
};
break;
case 29:
case 30:
case 31:
$possuiLetras = tratarCamposNumericoSegov($linha[$key], $delimitador);
if ($possuiLetras === false)
{
throw new Exception("Campos que contem valor R$, não podem possuir letras - linha: {$linhaChave}, coluna: {$coluna}");
}
elseif ($possuiLetras == 'vazio')
{
throw new Exception("Campos que contem valor R$, não podem ser vazios - linha: {$linhaChave}, coluna: {$coluna}");
};
break;
case 32:
$possuiLetras = tratarCamposNumericoSegov($linha[$key], $delimitador);
if ($possuiLetras === false)
{
throw new Exception("Campos que contem valor R$, não podem possuir letras - linha: {$linhaChave}, coluna: {$coluna}");
}
elseif ($possuiLetras == 'vazio')
{
throw new Exception("Campos que contem valor R$, não podem ser vazios - linha: {$linhaChave}, coluna: {$coluna}");
};
if ($linha[$key] > $linha[$key - 3])
{
throw new Exception("O campo de valor autorizado não pode ser maior que o valor solicitado - linha: {$linhaChave}, coluna: {$coluna}");
}
break;
case 33:
if (validaData($linha[$key]) == false)
{
throw new Exception("Data informada inválida - linha: {$linhaChave}, coluna: {$coluna}");
};
break;
}
}
protected function validaLinhaCSV ($linha)
{
unset($this->campos[32]);
unset($this->campos[33]);
$this->campos[36] = $this->campos[30];
$this->campos[37] = $this->campos[31];
$this->campos[30] = $this->campos[34];
$this->campos[31] = $this->campos[35];
unset($this->campos[34]);
unset($this->campos[35]);
$this->campos = array_values($this->campos);
if (count($linha) != count($this->campos))
{
throw new Exception('Arquivo CSV não condiz com os campos informados.');
}
}
private function retornaColuna ($key, $restante = 0)
{
// ASCII correspondente ao caracter A
$caracterInicial = 65;
$saida = '';
if (($dezena = (int) ($key / 26)) > 0)
{
$saida = chr($caracterInicial + ($dezena - 1));
$key -= ((int) $dezena * 26);
}
return $saida . chr($caracterInicial + $key);
}
} | true |
15e33c5083ea8f54f82c47decb9a8a0bd44e80c0 | PHP | hoanganh25991/laravel-fish-co | /database/factories/ModelFactory.php | UTF-8 | 3,706 | 2.5625 | 3 | [] | no_license | <?php
/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| Here you may define all of your model factories. Model factories give
| you a convenient way to create models for testing and seeding your
| database. Just tell the factory how a default model should look.
|
*/
/** @var Factory $factory */
use App\Image;
use App\Region;
use Faker\Generator as Faker;
use App\Campaign;
use Illuminate\Database\Eloquent\Factory;
use App\Candidate;
use App\Country;
use App\Device;
use App\Store;
use App\Submission;
$factory->define(Candidate::class, function (Faker $faker){
return [
Candidate::NAME => $faker->name,
Candidate::EMAIL => $faker->safeEmail,
Candidate::CONTACT_NUMBER => $faker->unique()->phoneNumber,
];
});
$factory->define(Country::class, function (Faker $faker){
$countryNameArray = [
"Vietnam",
"Malaysia",
"Brunei",
"India",
"Singapore"
];
return [
Country::NAME => $faker->unique()->randomElement($countryNameArray)
];
});
$factory->define(Device::class, function (Faker $faker){
$candidateIdArray = Candidate::lists(Candidate::ID)->toArray();
// dd($candidateIdArray);
return [
Device::UUID => $faker->unique()->uuid,
Device::DESCRIPTION => $faker->sentences(1, true),
Device::CANDIDATE_ID => $faker->randomElement($candidateIdArray)
];
});
$factory->define("App\\Region", function (Faker $f){
$countryIdArray = Country::lists(Country::ID)->toArray();
return [
"name" => $f->streetName,
"country_id" => $f->randomElement($countryIdArray),
"instagram_url" => $f->imageUrl(),
"facebook_url" => $f->imageUrl(),
"twitter_url" => $f->imageUrl(),
"website_url" => $f->imageUrl(),
];
});
$factory->define("App\\Outlet", function (Faker $f){
$regionIdArray = Region::lists("id")->toArray();
return [
"name" => $f->userName,
"address" => $f->streetName,
"region_id" => $f->randomElement($regionIdArray),
"instagram_url" => $f->imageUrl(),
"facebook_url" => $f->imageUrl(),
"twitter_url" => $f->imageUrl(),
"website_url" => $f->imageUrl(),
];
});
//$factory->define(Store::class, function (Faker $faker){
// $countryIdArray = Country::lists(Country::ID)->toArray();
// return [
// Store::NAME => $faker->name,
// Store::ADDRESS => $faker->address,
// Store::TEL => $faker->phoneNumber,
// Store::COUNTRY_ID => $faker->randomElement($countryIdArray)
// ];
//});
$factory->define("App\\Image", function (Faker $f){
return [
"name" => $f->sentences(1, true) . ".png",
"width" => $f->randomNumber(3),
"height" => $f->randomNumber(3),
"size" => $f->randomNumber(5),
"type" => "image/png",
"path" => md5($f->streetAddress).".png"
];
});
$factory->define(Submission::class, function (Faker $faker){
$candidateIdArray = Candidate::lists(Candidate::ID)->toArray();
$countryIdArray = Country::lists(Country::ID)->toArray();
$imageIdArray = Image::lists("id")->toArray();
return [
Submission::CANDIDATE_ID => $faker->randomElement($candidateIdArray),
Submission::COUNTRY_ID => $faker->randomElement($countryIdArray),
"image_id" => $faker->unique()->randomElement($imageIdArray)
];
});
$factory->define(Campaign::class, function (Faker $faker){
return [
Campaign::TITLE => $faker->sentences(1, true),
Campaign::DES => $faker->paragraphs(1, true),
];
}); | true |
dc3f900f47f6faa46f4c04b59ca3d307aeb114bb | PHP | richsage/WhiteOctoberAdminBundle | /Action/ActionCollection.php | UTF-8 | 3,846 | 2.859375 | 3 | [
"MIT"
] | permissive | <?php
/*
* This file is part of the WhiteOctoberAdminBundle package.
*
* (c) Pablo Díez <pablodip@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace WhiteOctober\AdminBundle\Action;
/**
* ActionCollection.
*
* @author Pablo Díez <pablodip@gmail.com>
*/
abstract class ActionCollection implements ActionCollectionInterface
{
private $actions;
private $options;
/**
* Constructor.
*
* @param array $options An array of options (optional).
*/
public function __construct(array $options = array())
{
$this->actions = array();
$defaultOptions = $this->getDefaultOptions();
if ($diff = array_diff(array_keys($options), array_keys($defaultOptions))) {
throw new \InvalidArgumentException(sprintf('The action collection "%s" does not support the following options "".', get_class($this), implode(', ', $diff)));
}
$this->options = array_merge($defaultOptions, $options);
$this->configure();
}
/**
* Returns the default options.
*
* @return array The default options.
*/
protected function getDefaultOptions()
{
return array();
}
/**
* Configures the action collection.
*/
abstract protected function configure();
/**
* Returns whether an option exists or not.
*
* @param string $name The name.
*
* @return Boolean Whether the option exists or not.
*/
public function hasOption($name)
{
return array_key_exists($name, $this->options);
}
/**
* Returns an option value.
*
* @param string $name The name.
*
* @return mixed The option value.
*
* @throws \InvalidArgumentException If the option does not exist.
*/
public function getOption($name)
{
if (!$this->hasOption($name)) {
throw new \InvalidArgumentException(sprintf('The option "%s" does not exist.', $name));
}
return $this->options[$name];
}
/**
* Returns the options.
*
* @return array The options.
*/
public function getOptions()
{
return $this->options;
}
/**
* Adds an action.
*
* @param ActionInterface $action An action.
*
* @throws \LogicException If the action is already in the collection.
*/
public function add(ActionInterface $action)
{
if (isset($this->actions[$action->getFullName()])) {
throw new \LogicException(sprintf('The action "%s" already exists.', $action->getFullName()));
}
$this->actions[$action->getFullName()] = $action;
}
/**
* Returns whether an action is in the collection by name.
*
* @param string $name The action name.
*
* @return Boolean Whether an action exists or not in the collection.
*/
public function has($name)
{
return isset($this->actions[$name]);
}
/**
* Returns an action by name.
*
* @param string $name The name.
*
* @return ActionInterface The action.
*
* @throws \InvalidArgumentInterface If the action does not exist.
*/
public function get($name)
{
if (!$this->has($name)) {
throw new \InvalidArgumentException(sprintf('The action "%s" already exists.', $name));
}
return $this->actions[$name];
}
/**
* {@inheritdoc}
*/
public function all()
{
return $this->actions;
}
/**
* Clone the object.
*/
public function __clone()
{
$actions = array();
foreach ($this->actions as $name => $action) {
$actions[$name] = clone $action;
}
$this->actions = $actions;
}
}
| true |
50a8cfc5210ed54a14989e4f886e46ed9c22eac1 | PHP | marinaAC/ProgramacionIII | /MarinaCardozo-RSP/PracticaSegundoParcial/DAO/Entidades/UsuarioDao.php | UTF-8 | 2,210 | 3.140625 | 3 | [] | no_license | <?php
include_once('./DAO/Interfaces/IUsuarioDao.php');
include_once('./Conecciones/ConexionDb.php');
class UsuarioDao implements IUsuarioDao{
private $conexion;
public function __construct($conexion)
{
$this->conexion = $conexion;
}
public function SaveUsuario($usuario)
{
$retorno = true;
if($usuario==null){
$retorno = false;
echo"Error en el usuario que se desea guardar";
return $retorno;
}
$consulta = $this->conexion->GetConsulta("INSERT INTO usuario (nombre, tipo, pass, sexo)
VALUES(:nombre, :tipo, :pass, :sexo)");
$consulta->bindValue(':nombre', $usuario->__get('nombre'), PDO::PARAM_STR);
$consulta->bindValue(':tipo',$usuario->__get('tipo'), PDO::PARAM_STR);
$consulta->bindValue(':pass', $usuario->__get('pass'), PDO::PARAM_STR);
$consulta->bindValue(':sexo', $usuario->__get('sexo'), PDO::PARAM_STR);
$consulta->execute();
return $retorno;
}
public function GetByFiltro($filtro){
$listaUsuarios = [];
$consulta = $this->conexion->GetConsulta("SELECT * FROM usuario WHERE ".$filtro);
$consulta->execute();
$usuarios = $consulta->fetchAll(PDO::FETCH_ASSOC);
foreach ($usuarios as $key) {
$auxUsuarios = new Usuario($key['id'],$key['nombre'],$key['tipo'],$key['pass'],$key['sexo']);
array_push($listaUsuarios,$auxUsuarios);
}
return $listaUsuarios;
}
public function GetUsuarioByNombreyPass($nombre,$pass){
$listaUsuarios = self::GetByFiltro("nombre = '".$nombre."' AND pass = '".$pass."'");
return $listaUsuarios;
}
public function GetAllUs()
{
$listaUsuarios = [];
$consulta = $this->conexion->GetConsulta("SELECT * FROM usuario");
$consulta->execute();
$usuarios = $consulta->fetchAll(PDO::FETCH_ASSOC);
foreach ($usuarios as $key) {
$auxUsuarios = new Usuario($key['id'],$key['nombre'],$key['tipo'],$key['pass'],$key['sexo']);
array_push($listaUsuarios,$auxUsuarios);
}
return $listaUsuarios;
}
}
?> | true |
16ae6356014d2d8d0fc8b7f3c901cfe6c36c46c3 | PHP | NursultanMuss/test1 | /controllers/AdminProjectsController.php | UTF-8 | 4,826 | 2.796875 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: йойо
* Date: 09.10.2016
* Time: 12:05
*/
class AdminProjectsController extends AdminBase
{
/**
* Action для страницы "Управление проектами"
*/
public function actionIndex()
{
//Access control
self::checkAdmin();
//Get projects list
$projectsList = Projects::getProjectsPage();
//Turn on view
require_once(ROOT . '/views/admin_projects/index.php');
return true;
}
public function actionCreate()
{
self::checkAdmin();
//Form processing
if (isset($_POST['submit'])) {
//If form sent
//Get data from form
$options['image'] = $_POST['image'];
$options['description'] = $_POST['description'];
$options['link'] = $_POST['link'];
$errors = false;
// При необходимости можно валидировать значения нужным образом
if (!isset($options['image']) || empty($options['image'])) {
$errors[] = 'Заполните поля';
}
if ($errors == false) {
// Если ошибок нет
// Добавляем новый project
$id = Projects::createProject($options);
// Если запись добавлена
if ($id) {
// Проверим, загружалось ли через форму изображение
if (is_uploaded_file($_FILES["imageSource"]["tmp_name"])) {
// Если загружалось, переместим его в нужную папке, дадим новое имя
move_uploaded_file($_FILES["imageSource"]["tmp_name"], $_SERVER['DOCUMENT_ROOT'] . "/template/images/".$options['image']);
}
}
// Перенаправляем пользователя на страницу управлениями projects
header("Location: /admin/projects");
}
}
//Get view of the page
require_once(ROOT . '/views/admin_projects/create.php');
return true;
}
public function actionDelete($id)
{
// Проверка доступа
self::checkAdmin();
// Обработка формы
if (isset($_POST['submit'])) {
// Если форма отправлена
// Удаляем товар
Projects::deleteProjectById($id);
// Перенаправляем пользователя на страницу управлениями товарами
header("Location: /admin/projects");
}
if(isset($_POST['not'])){
header("Location: /admin/projects");
}
// Подключаем вид
require_once(ROOT . '/views/admin_projects/delete.php');
return true;
}
public function actionUpdate($id)
{
// Проверка доступа
self::checkAdmin();
// Получаем данные о конкретном проекте
$project = Projects::getProjectById($id);
// Обработка формы
if (isset($_POST['submit'])) {
// Если форма отправлена
// Получаем данные из формы редактирования. При необходимости можно валидировать значения
$options['image'] = $_POST['image'];
$options['description'] = $_POST['description'];
$options['link'] = $_POST['link'];
// Сохраняем изменения
if (Projects::updateProjectById($id, $options)) {
// Если запись сохранена
// Проверим, загружалось ли через форму изображение
if (is_uploaded_file($_FILES["imageSource"]["tmp_name"])) {
// Если загружалось, переместим его в нужную папке, дадим новое имя
move_uploaded_file($_FILES["imageSource"]["tmp_name"], $_SERVER['DOCUMENT_ROOT'] . "/template/images/".$project['image']);
}
}
// Перенаправляем пользователя на страницу управлениями товарами
header("Location: /admin/projects");
}
// Подключаем вид
require_once(ROOT . '/views/admin_projects/update.php');
return true;
}
} | true |
807391389156d24a8b07469ffe6a13c6f76dbc60 | PHP | somexoh/moumoon | /backend_bak.php | UTF-8 | 1,057 | 2.765625 | 3 | [] | no_license | <?php
header( "Access-Control-Allow-Origin: *");
/*
* Get Params
*/
$startTime = "";
$endTime = "";
$startTimeSQL = " ";
$endTimeSQL = " ";
$startTime = $_GET["startTime"];
$endTime = $_GET["endTime"];
if ( !empty($startTime)) {
$startTimeSQL = " pubdate > date (\"$startTime\") ";
}
if ( !empty($endTime)) {
$endTimeSQL = "pubdate < date (\"$endTime\") ";
}
/* End of file filename.php */
$host="host=127.0.0.1" ;
$port="port=5432" ;
$dbname="dbname=news" ;
$credentials="user=carwest password=123qwe!@#QWE" ;
$db=pg_connect( "$host $port $dbname $credentials" );
if (!$db){
echo "Error : unable to connect";
}else { //echo "Opened database success";
}
$query='SELECT * from locations limit 100 where ' . $startTimeSQL . ' and ' . $endTimeSQL ;
$result=pg_query($query) or die( 'Query failed:'.pg_last_error() );
$ans_stack=array();
echo "[";
while ( $ro=pg_fetch_object($result) )
{
//array_push( $ans_stack, $ro ); //echo $ro;
echo json_encode($ro);
echo ",";
}
echo "{}]";
pg_free_result($result);
pg_close( $db );
?>
| true |
e715d0e7defb08034972411e728ae42d08044b7e | PHP | gurkiratThind/Asian-Swords | /tools.php | UTF-8 | 6,035 | 2.796875 | 3 | [] | no_license | <?php
/**
* prevent loading of tools.php directly
* must go through index.php first.
*/
if (!isset($index_loaded)) {
die('Direct acces to this file is forbidden');
}
/**
* this file contain utility functions.
*/
/**
* Display any one dimensional array.
*/
function array_display($array_name)
{
$r = '';
$r .= '<style> table,td,th{border: solid 2px black;}</style>';
$r .= '<table>';
$r .= '<tr>';
$r .= '<th>Index/Key</th>';
$r .= '<th>Value</th>';
$r .= '</tr>';
foreach ($array_name as $index => $value) {
$r .= '<tr>';
$r .= '<td> '.$index.' </td>';
if ($index == 'price') {
$r .= '<td> $'.$value.' </td>';
$r .= '</tr>';
} else {
$r .= '<td>'.$value.' </td>';
$r .= '</tr>';
}
}
$r .= '</table>';
return $r;
}
/**
* Multi-Dimensional Array Display Function.
*/
function multiple_arrayDisplay($multiple_array)
{
$r = '';
$r .= '<style> td,th{border: solid 2px black;}</style>';
$r .= '<table>';
$r .= '<tr>';
foreach ($multiple_array[0] as $key => $value) {
$r .= '<th>'.$key.'</th>';
}
$r .= '</tr>';
foreach ($multiple_array as $key => $value) {
$r .= '<tr>';
foreach ($value as $key1 => $value1) {
if ($key1 == 'price') {
$r .= '<td> $'.$value1.' </td>';
} else {
$r .= '<td>'.$value1.' </td>';
}
}
$r .= '</tr>';
}
$r .= '</table>';
return $r;
}
/**
* table_display($table) display any 2d table.
*/
function table_display($table)
{
$out = '';
$out = '<style> td,th{border: solid 2px black;}</style>';
if (count($table) == 0) {
//table is empty
return 'table is empty';
}
$out .= '<table>';
//table header
$col_names = array_keys($table[0]);
$out .= '<tr>';
foreach ($col_names as $col_name) {
$out .= '<th>'.$col_name.'</th>';
}
$out .= '</tr>';
//table data
$out .= '</tr>';
foreach ($table as $one_row) {
$out .= '<tr>';
foreach ($one_row as $key => $col_name) {
if ($key == 'price' and gettype($key) != 'integer') {
$out .= '<td> $'.$col_name.' </td>';
} else {
$out .= '<td>'.$col_name.' </td>';
}
}
$out .= '</tr>';
}
$out .= '</table>';
return $out;
}
function catalog($array)
{
$r = '';
foreach ($array as $key => $value) {
$r .= '<div class=product>';
$r .= '<img src="products_images/'.$value['pic'].'" alt="'.$value['description'].'">';
$r .= '<p class= name>'.$value['name'].'</p>';
$r .= '<p class= description>'.$value['description'].'</p>';
$r .= '<p class= price>$'.$value['price'].'</p>';
$r .= '<p class=edit><a href="index.php?op=116&id='.$value['id'].'">edit</a>';
$r .= '<p class=edit><a href="index.php?op=118&id='.$value['id'].'">Delete</a>';
$r .= '</div>';
}
return $r;
}
function crash($code, $message)
{
http_response_code($code);
//here we can send email to IT admin
//mail(ADMIN_EMAIL, COMPANY_NAME.'Server crashed code ='.$code, $message);
//write in log file
$file = fopen('logs/errors.log', 'a+');
$time_info = date('d-M-Y g:i:s');
fwrite($file, $message.' '.$time_info.'<br>');
fclose($file);
die($message);
}
/**
* Check that $_FILE (the uploaded file) contains a valid image
* extension must be: .jpg , .JPG , .gif ou .png.
*
* $file_input the file input name on the HTML form
* $Max_Size maximum file size in Kb, default 500kb
* returns "OK" or error message
*/
function Photo_Uploaded_Is_Valid($file_input, $Max_Size = 500000)
{
//Must havein HTML <form enctype="multipart/form-data" .. //otherwise $_FILE is undefined // $file_input is the file input name on the HTML form
if (!isset($_FILES[$file_input])) {
return 'No image uploaded';
}
if ($_FILES[$file_input]['error'] != UPLOAD_ERR_OK) {
return 'Error picture upload: code='.$_FILES[$file_input]['error'];
}
// Check image size
if ($_FILES[$file_input]['size'] > $Max_Size) {
return 'Image too big, max file size is '.$Max_Size.' Kb';
}
// Check that file actually contains an image
$check = getimagesize($_FILES[$file_input]['tmp_name']);
if ($check === false) {
return 'This file is not an image';
}
// Check extension is jpg,JPG,gif,png
$imageFileType = pathinfo(basename($_FILES[$file_input]['name']), PATHINFO_EXTENSION);
if ($imageFileType != 'jpg' && $imageFileType != 'JPG' && $imageFileType != 'gif' && $imageFileType != 'png') {
return 'Invalid image file type, valid extensions are: .jpg .JPG .gif .png';
}
return 'OK';
}
/**
* Function to save uploaded image in folder
* (and display image for testing).
* $file_input is the file input name on the HTML form.
* */
function Picture_Save_File($file_input, $target_dir)
{
$message = Photo_Uploaded_Is_Valid($file_input); // voir fonction
if ($message === 'OK') {
// Check that there is no file with the same name
// already exists in the target folder
// using file_exists()
$target_file = $target_dir.basename($_FILES[$file_input]['name']);
if (file_exists($target_file)) {
return 'This file already exists';
}
// Create the file with move_uploaded_file()
if (move_uploaded_file($_FILES[$file_input]['tmp_name'], $target_file)) {
// ALL OK display image for testing
//echo '<img src="'.$target_file.'">';
return 'ok';
} else {
return 'Error in move_upload_file';
}
} else {
// upload error, invalid image or file too big
return $message;
}
}
| true |
0c61301b3f194a6fdb3369cc438ad4310cfed251 | PHP | suitmedia/suitcoda | /database/migrations/2015_11_06_163545_createCommandTable.php | UTF-8 | 909 | 2.546875 | 3 | [
"MIT"
] | permissive | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCommandTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('commands', function (Blueprint $table) {
$table->BigIncrements('id');
$table->BigInteger('scope_id')->unsigned()->index();
$table->string('name');
$table->string('command_line', 128);
$table->boolean('is_active')->default(true);
$table->foreign('scope_id')
->references('id')
->on('scopes')
->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('commands');
}
}
| true |
43d0139a32bedc34fa5a1dafcf8b71af0104a4b5 | PHP | shawnsandy/atlas-summit | /app/Http/Requests/UserRequest.php | UTF-8 | 2,199 | 2.515625 | 3 | [] | no_license | <?php
namespace App\Http\Requests;
use App\Notifications\AccountActivation;
use App\User;
use DB;
use Hash;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Notification;
use Silber\Bouncer\BouncerFacade as Bouncer;
use Silber\Bouncer\Database\Role;
class UserRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
if ($this->input("_method") == "PUT")
return [
"first_name" => "required|min:5",
"last_name" => "required|min:5",
"update_email" => "required|email|sometimes:unique:users",
"password" => "sometimes|required|min:8",
"password_verify" => "sometimes|required|same:password"
];
return [
"first_name" => "required|min:4",
"last_name" => "required|min:4",
"email" => "required|email|unique:users",
"password" => "sometimes|required|min:8",
"password_verify" => "sometimes|required|same:password"
];
}
public function register()
{
$password = str_random();
$data = $this->input();
$data['password'] = Hash::make($password);
$data['is_activated'] = 1;
if ($user = User::create($data)):
if(!Role::where('name', $this->input('role'))->count())
Bouncer::allow($this->input('role'))->to($this->input('role').'-ability');
Bouncer::assign($this->input('role'))->to($user);
Notification::send($user, new AccountActivation($user, $password));
return $user;
endif;
return false;
}
public function update($id)
{
$password = str_random();
$data = $this->input();
if (!empty($data['update_email']))
$data['email'] = $data['update_email'];
if ($user = User::updateOrCreate(["id" => $id], $data)):
return $user;
endif;
return false;
}
}
| true |
1d6a37e2fdb646cbd12f1b1e40e82b002500ba22 | PHP | SahanDisa/web_first | /My_Web_Class/PHP/01-PHP-BASIC/index.php | UTF-8 | 320 | 2.703125 | 3 | [] | no_license | <html>
<head>
<title><?php echo "PHP"?></title>
</head>
<body>
<h1>Hello this is HTML inside a PHP File</h1>
<?php
/**
* Created by IntelliJ IDEA.
* User: sanu-vithanage
* Date: 11/17/18
* Time: 10:18 AM
*/
echo "Hello PHP<br>";
echo "<h1>Hello PHP</h1>";
echo "<script>alert('Haai');</script>";
?>
</body>
</html> | true |
58ac784cbc341c3a7e45cee144e2019d69a46bcb | PHP | devangi2233/WP | /emp.php | UTF-8 | 876 | 2.78125 | 3 | [] | no_license | <?php
$servername="localhost";
$username="root";
$password="";
$database="college";
$conn=mysqli_connect($servername,$username,$password,$database);
if(!$conn){
die("connection failed:".mysqli_connect_error());
}
$query= "create table emp(empid int primary key,ename varchar(30),designation varchar(30))";
if(mysqli_query($conn,$query)){
echo"Table created successfully";
}
else{
echo"Error creating table :".mysqli_error($conn);
}
$query1="insert into emp values(101,'Allen','MANAGER')";
if(mysqli_query($conn,$query1))
echo"Record 1 inserted successfully";
else
echo "Error inserting record 1:".mysqli_error();
$query2="insert into emp values(102,'Smith','CLERK')";
if(mysqli_query($conn,$query2))
echo"Record 2 inserted successfully";
else
echo "Error inserting record 2:".mysqli_error();
mysqli_close($conn);
?>
</body>
</html> | true |
3f1a9ca82c10ec716481aa793fabaa5efc4f8c9e | PHP | VladimirCVB/internDTT | /app/models/Houses.php | UTF-8 | 1,824 | 2.9375 | 3 | [] | no_license | <?php
use Phalcon\Mvc\Model;
use Phalcon\Messages\Message;
use Phalcon\Validation;
use Phalcon\Validation\Validator\PresenceOf;
use Phalcon\Validation\Validator\Digit;
class Houses extends Model
{
public $id;
public $street;
public $number;
public $addition;
public $zipcode;
public $city;
//Adding validator for specific fields
public function validation()
{
$validator = new Validation();
//Validating 'number' field to only contain digits
$validator->add(
'number',
new Digit(
[
'field' => 'number',
'message' => 'You must enter a numeric values for this field',
]
)
);
//Validating 'street' field to not be null or empty
$validator->add(
'street',
new PresenceOf(
[
'field' => 'street',
'message' => 'You must enter a value before submitting the form',
]
)
);
//Validating 'zipcode' field to not be null or empty
$validator->add(
'zipcode',
new PresenceOf(
[
'field' => 'zipcode',
'message' => 'You must enter a value before submitting the form',
]
)
);
//Validating 'city' field to not be null or empty
$validator->add(
'city',
new PresenceOf(
[
'field' => 'city',
'message' => 'You must enter a value before submitting the form',
]
)
);
// Validate the validator
return $this->validate($validator);
}
} | true |
16f007ec78f135f8f8554d11803539a93a88c466 | PHP | jrots/notificato | /tests/Wrep/Notificato/Test/Apns/SenderTest.php | UTF-8 | 3,104 | 2.515625 | 3 | [
"LicenseRef-scancode-proprietary-license",
"MIT"
] | permissive | <?php
namespace Wrep\Notificato\Tests\Apns;
use \Wrep\Notificato\Apns\Sender;
use \Wrep\Notificato\Apns\Certificate;
use \Wrep\Notificato\Apns\Gateway;
use \Wrep\Notificato\Apns\MessageFactory;
use \Wrep\Notificato\Apns\MessageEnvelope;
use \Wrep\Notificato\Test\Apns\Mock\MockGatewayFactory;
use \Wrep\Notificato\Test\Apns\Mock\MockGateway;
class SenderTests extends \PHPUnit_Framework_TestCase
{
private $sender;
public function setUp()
{
// Get our sender
$this->sender = new Sender();
$this->sender->setGatewayFactory(new MockGatewayFactory());
}
private function getCertificate($fingerprint)
{
// Create cert
$certificate = $this->getMockBuilder('\Wrep\Notificato\Apns\Certificate')
->disableOriginalConstructor()
->getMock();
$certificate->expects($this->any())
->method('getFingerprint')
->will($this->returnValue($fingerprint));
return $certificate;
}
private function getCertificateFactory($defaultCertificate)
{
// Create cert
$certificateFactory = $this->getMockBuilder('\Wrep\Notificato\Apns\CertificateFactory')
->disableOriginalConstructor()
->getMock();
$certificateFactory->expects($this->any())
->method('getDefaultCertificate')
->will($this->returnValue($defaultCertificate));
return $certificateFactory;
}
public function testSend()
{
$message = $this->getMockBuilder('\Wrep\Notificato\Apns\Message')
->disableOriginalConstructor()
->getMock();
$message->expects($this->any())
->method('getCertificate')
->will($this->returnValue( $this->getCertificate('a') ));
$this->assertEquals(0, $this->sender->getQueueLength());
$messageEnvelope = $this->sender->send($message);
$this->assertEquals(0, $this->sender->getQueueLength());
$this->assertEquals(MessageEnvelope::STATUS_NOERRORS, $messageEnvelope->getStatus());
}
public function testQueueAndFlush()
{
$messageA = $this->getMockBuilder('\Wrep\Notificato\Apns\Message')
->disableOriginalConstructor()
->getMock();
$messageA->expects($this->any())
->method('getCertificate')
->will($this->returnValue( $this->getCertificate('a') ));
$messageB = $this->getMockBuilder('\Wrep\Notificato\Apns\Message')
->disableOriginalConstructor()
->getMock();
$messageB->expects($this->any())
->method('getCertificate')
->will($this->returnValue( $this->getCertificate('b') ));
$messageC = $this->getMockBuilder('\Wrep\Notificato\Apns\Message')
->disableOriginalConstructor()
->getMock();
$messageC->expects($this->any())
->method('getCertificate')
->will($this->returnValue( $this->getCertificate('c') ));
// Connect and queue the messages
$sender = new Sender( $this->getCertificate('a') );
$sender->setGatewayFactory(new MockGatewayFactory());
for ($i = 1; $i <= 5; $i++)
{
$sender->queue($messageA);
$sender->queue($messageB);
$sender->queue($messageC);
$this->assertEquals($i * 3, $sender->getQueueLength());
}
// Send the messages
$sender->flush();
$this->assertEquals(0, $sender->getQueueLength());
}
} | true |
63ee51af192d4704a9703bd6af8bce6779273283 | PHP | riverswan/PHP_patterns_Zandstra | /Prototype/EarthForest.php | UTF-8 | 259 | 2.96875 | 3 | [] | no_license | <?php declare(strict_types=1);
namespace app\Prototype;
class EarthForest extends Forest {
public function __construct() {
$this->title = "Earth forest";
echo $this->getTitle() . "\n";
}
public function __clone() {
$this->title .= " clone";
}
} | true |
185ffa464d3d7a3843cddeadff8b1f3cf0c22182 | PHP | HidekatsuYamamoto/messageboard | /ForThumbnailingPictureClass.php | UTF-8 | 2,092 | 3.078125 | 3 | [] | no_license | <?php
namespace HideSample\MessageBoard;
define('SCREEN_SIZE', '300');
?>
<?php
class ForThumbnailingPictureClass
{
// コンストラクタ
function __construct()
{
}
/**
* @assert (0, 0) == 0
* @assert (300, 300) == 300
* @assert (600, 600) == 300
* @assert (300, 600) == 150
* @assert (600, 300) == 300
* @assert (900, 900) == 300
* @assert (600, 300) == 300
* @assert (300, 600) == 150
*/
// 最適な幅、高さを求める。
function figureHorizontalSize($width, $height)
{
if ($width > $height) {
if ($width > SCREEN_SIZE) {
$scale = $width / SCREEN_SIZE;
$conv_width = $width / $scale;
} else {
$conv_width = $width;
}
} else {
if ($height > SCREEN_SIZE) {
$scale = $height / SCREEN_SIZE;
$conv_width = $width / $scale;
} else {
$conv_width = $width;
}
}
return $conv_width;
}
/**
* @assert (0, 0) == 0
* @assert (300, 300) == 300
* @assert (600, 600) == 300
* @assert (300, 600) == 300
* @assert (600, 300) == 150
* @assert (900, 900) == 300
* @assert (600, 300) == 150
* @assert (300, 600) == 300
*/
function figureVerticalSize($width, $height)
{
if ($width > $height) {
if ($width > SCREEN_SIZE) {
$scale = $width / SCREEN_SIZE;
$conv_height = $height / $scale;
} else {
$conv_height = $height;
}
} else {
if ($height > SCREEN_SIZE) {
$scale = $height / SCREEN_SIZE;
$conv_height = $height / $scale;
} else {
$conv_height = $height;
}
}
return $conv_height;
}
// デストラクタ
function __destruct()
{
}
} | true |
3c7ad42435ffd75c9438ef6aa494bdf1f8d5d0a0 | PHP | axelPZ/modelo-laravel | /app/Http/Controllers/CategoryController.php | UTF-8 | 4,614 | 2.5625 | 3 | [] | no_license | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Category; // importamos el modelo
use Carbon\Carbon;
class CategoryController extends Controller
{
// TRAER LAS CATEGORIAS
public function getCategories(){
$count = Category::where('cat_estate', 1)->count();
$result = Category::select( 'cat_id', 'cat_name','cat_img', 'usr_name', 'usr_surname', 'usr_img' )
->join('users', 'usr_id', '=', 'cat_idUser')
->where( 'cat_estate',1)
->get();
return response()->json(
[
'status' => 'success',
'total' => $count,
'categories' => $result
],200);
}
// TRAER LAS CATEGORIAS POR ID
public function getByIdCategory( Request $request ){
$id = $request->idCategory;
$getIdCategory = new \getIdCategory(); // instanciar el helper que contiene la consulta
$result = $getIdCategory->getId( $id, 'cat_id');
return response()->json(
[
'status' => 'success',
'total' => $result
],200);
}
// TRAER LAS CATEGORIAS POR ID DE USARIO
public function getCategoryIdUser( Request $request){
$id = $request->idUser;
$getIdCategory = new \getIdCategory(); // instanciar el helper que contiene la consulta
$result = $getIdCategory->getId( $id, 'cat_idUser');
if( sizeof($result) > 0 ){
return response()->json(
[
'status' => 'success',
'total' => $result
],200);
}
return response()->json([
'mensaje' => ' Usuario sin categorias para mostrar'
],400);
}
// TRAER CATEGORIAS POR USUARIO LOGEADO
public function getCategoryUserRegister( Request $request){
$user = $request->user; // obtengo el id del usuario logeado, que se a agregado al validar el JWT
$idUser = $user['usr_id'];
$getIdCategory = new \getIdCategory(); // instanciar el helper que contiene la consulta
$result = $getIdCategory->getId( $idUser, 'cat_idUser');
if( sizeof($result) > 0 ){
return response()->json(
[
'status' => 'success',
'total' => $result
],200);
}
return response()->json([
'mensaje' => ' Usuario sin categorias para mostrar'
],400);
}
// AGREGAR CATEGORIAS
public function addCategory( Request $request ){
$data = $request->json()->all();
$user = $request->user; // obtengo el id del usuario logeado, que se a agregado al validar el JWT
$idUser = $user['usr_id'];
$category = new Category();
$category->cat_name = strtoupper($data['cat_name']);
$category->cat_idUser = $idUser;
$category->save();
return response()->json(
[
'status' => 'success',
'total' => $category
],200);
}
// EDITAR CATEGORIAS
public function updateCategory( Request $request ){
$data = $request->json()->all();
$user = $request->user; // obtengo el id del usuario logeado, que se a agregado al validar el JWT
$idUser = $user['usr_id'];
$id = $request->idCategory;
$result = Category::where('cat_id', $id)->first();
$idUserCategory = $result['cat_idUser'];
// verificar que el usuario que quiere editar la categoria es el que la creo
if ( $idUser != $idUserCategory) {
return response()->json( [
'mensaje' => 'El usuario logiado, no es el que creo la categoria'
], 400);
}
$category_update = Category::where( 'cat_id',$id )->update( [ 'cat_name' => strtoupper( $data['cat_name'] ) ] );
$result = Category::where('cat_id', $id)->first();
return response()->json(
[
'status' => 'success',
'data' => $result,
],200);
}
// ELIMINAR CATEGORIAS
public function deleteCategory( Request $request ){
$id = $request->idCategory;
$user_update = Category::where( 'cat_id',$id )->update( ['cat_estate' => 2] );
$result = Category::where('cat_id', $id)->first();
return response()->json(
[
'status' => 'success',
'data' => $result,
],200);
}
}
| true |
b54bf8053527494addaf49ff420c80d95d0da5b0 | PHP | jsonpeng/SmartHaiDianServer | /app/Repositories/GatewayRepository.php | UTF-8 | 616 | 2.5625 | 3 | [] | no_license | <?php
namespace App\Repositories;
use App\Models\Gateway;
use InfyOm\Generator\Common\BaseRepository;
/**
* Class GatewayRepository
* @package App\Repositories
* @version May 19, 2019, 11:29 am CST
*
* @method Gateway findWithoutFail($id, $columns = ['*'])
* @method Gateway find($id, $columns = ['*'])
* @method Gateway first($columns = ['*'])
*/
class GatewayRepository extends BaseRepository
{
/**
* @var array
*/
protected $fieldSearchable = [
'name'
];
/**
* Configure the Model
**/
public function model()
{
return Gateway::class;
}
}
| true |
1b9cf949acc9ce2957d50b57ef3a564e59305f3e | PHP | lanmediaservice/lms-video-ce-1.x | /src/rss_films.php | WINDOWS-1251 | 4,041 | 2.546875 | 3 | [] | no_license | <?php
header("Content-type: text/xml");
require_once "config.php";
$idSQLConnection = mysql_connect($config['mysqlhost'], $config['mysqluser'], $config['mysqlpass']);
if ( !$idSQLConnection )
{
echo " . .";
exit;
}
$result = mysql_select_db( $config['mysqldb'], $idSQLConnection );
if ( !$result )
{
echo " . .";
exit;
}
if (isset($config['mysql_set_names'])) mysql_query($config['mysql_set_names']);
$l = isset($config['rss']['count']) ? $config['rss']['count'] : 10;
$title = isset($config['rss']['title']) ? $config['rss']['title'] : "-";
echo "<?xml version=\"1.0\" encoding=\"windows-1251\"?>"
."\n<rss version=\"2.0\" \nxmlns:content=\"http://purl.org/rss/1.0/modules/content/\">"
."\n<channel>"
."\n<title>$title</title>"
."\n<link>{$config['siteurl']}</link>"
."\n<description> </description>"
."\n<language>ru</language>"
."\n<pubDate>".date("r")."</pubDate>";
$result = mysql_query("select * from films where hide=0 order by CreateDate DESC LIMIT 0,10");
$i = 0;
while ($field=mysql_fetch_assoc($result)){
$id = $field["ID"];
$result2 = mysql_query("SELECT Name FROM filmgenres LEFT JOIN genres ON (genres.ID = filmgenres.GenreID) WHERE filmgenres.FilmID={$field['ID']}");
$genres = array();
while ($result2 && $field2 = mysql_fetch_assoc($result2)){
$genres[] = $field2["Name"];
}
$result2 = mysql_query("SELECT Name FROM filmcountries LEFT JOIN countries ON (countries.ID = filmcountries.CountryID) WHERE filmcountries.FilmID={$field['ID']}");
$countries = array();
while ($result2 && $field2 = mysql_fetch_assoc($result2)){
$countries[] = $field2["Name"];
}
$sgenres = implode(" / ", $genres);
$scountries = implode(" / ", $countries);
$director = "";
$actors = array();
$result2 = mysql_query("SELECT persones.RusName as RusName, persones.OriginalName as OriginalName, roles.Role as Role, roles.SortOrder as SortOrder FROM filmpersones LEFT JOIN roles ON (roles.ID = filmpersones.RoleID) LEFT JOIN persones ON (persones.ID = filmpersones.PersonID) WHERE filmpersones.FilmID=$id ORDER BY SortOrder");
while ($result2 && $field2 = mysql_fetch_assoc($result2)){
if ($field2["Role"]=="") $director = strlen(trim($field2["RusName"])) ? $field2["RusName"] : (($field2["OriginalName"])?$field2["OriginalName"]:"");
if (in_array($field2["Role"],array("",""))) $actors[] = ($field2["RusName"]) ? $field2["RusName"] : $field2["OriginalName"];
if (count($actors)>4) break;
}
$actors = implode(", ", $actors);
$field['Poster'] = preg_split("(\r\n|\r|\n)",$field['Poster']);
echo "\n<item>"
."\n<title>".htmlspecialchars("{$field['Name']} / {$field['OriginalName']} ({$field['Year']})")."</title>"
."\n<link>{$config['siteurl']}/#film:{$field['ID']}:1:0</link>"
."\n<description>".$sgenres." - ".$scountries . "</description>"
."\n<content:encoded><![CDATA["
."\n<table style='font-family: Tahoma, Verdana, Geneva, Arial, Helvetica, sans-serif; font-size: 8pt;'><tr><td valign='top'><img src='" . ((!preg_match("/^http:\/\//",$field['Poster'][0])) ? $config['siteurl']."/" : "") . $field['Poster'][0]. "'></td><td valign='top'>"
."\n<b>:</b> " . $sgenres." <br/>"
."\n<b>:</b> " . $scountries." <br/>"
."\n<b>:</b> " . $director." <br/>"
."\n<b> :</b> " . $actors." <br/>"
. (($field["ImdbRating"]>0) ? "\n<img src='{$config['siteurl']}/images/imdb.gif'> " . round($field["ImdbRating"]/10,1) ." <br/>" : "")
."\n<b> :</b> " .$field['Description'] . "</td></tr></table>"
."]]></content:encoded>"
."\n<pubDate>".date("r",strtotime($field['CreateDate']))."</pubDate>"
."\n<guid>{$config['siteurl']}/#film:{$field['ID']}:1:0</guid>"
."\n</item>";
}
?>
</channel>
</rss>
| true |
1514114b9949045d945233a3aa5e1f5d398b0daa | PHP | Pfillip/ilias | /Services/Payment/classes/class.ilPaymentPrices.php | UTF-8 | 13,825 | 2.578125 | 3 | [] | no_license | <?php
/* Copyright (c) 1998-2010 ILIAS open source, Extended GPL, see docs/LICENSE */
/**
* Class ilPaymentPrices
*
* @author Stefan Meyer <meyer@leifos.com>
* @version $Id: class.ilPaymentPrices.php 22133 2009-10-16 08:09:11Z nkrzywon $
*
* @package ilias-core
*/
class ilPaymentPrices
{
// private $ilDB;
const TYPE_DURATION_MONTH = 1;
const TYPE_DURATION_DATE = 2;
const TYPE_UNLIMITED_DURATION = 3;
private $pobject_id;
private $price;
private $currency;
private $duration = 0;
private $unlimited_duration = 0;
private $extension = 0;
private $duration_from;
private $duration_until;
private $description;
public $price_type = self::TYPE_DURATION_MONTH;
// TODO later -> this is for using different currencies
// private $currency_conversion_rate = 1;
private $prices = array();
public function __construct($a_pobject_id = 0)
{
global $ilDB;
$this->db = $ilDB;
$this->pobject_id = $a_pobject_id;
$this->__read();
}
public function setPriceType($a_price_type)
{
$this->price_type = $a_price_type;
return $this;
}
public function getPriceType()
{
return $this->price_type;
}
//
// SET GET
public function getPobjectId()
{
return $this->pobject_id;
}
public function getPrices()
{
return $this->prices ? $this->prices : array();
}
function getPrice($a_price_id)
{
return $this->prices[$a_price_id] ? $this->prices[$a_price_id] : array();
}
// STATIC
public static function _getPrice($a_price_id)
{
global $ilDB;
$res = $ilDB->queryf('
SELECT * FROM payment_prices
WHERE price_id = %s',
array('integer'), array($a_price_id));
while($row = $ilDB->fetchObject($res))
{
$price['duration'] = $row->duration;
$price['duration_from'] = $row->duration_from;
$price['duration_until'] = $row->duration_until;
$price['description'] = $row->description;
$price['unlimited_duration'] = $row->unlimited_duration;
$price['currency'] = $row->currency;
$price['price'] = number_format($row->price, 2, '.', '');
$price['extension'] = $row->extension;
$price['price_type'] = $row->price_type;
}
return count($price) ? $price : array();
}
public static function _countPrices($a_pobject_id)
{
global $ilDB;
$res = $ilDB->queryf('
SELECT count(price_id) FROM payment_prices
WHERE pobject_id = %s',
array('integer'),
array($a_pobject_id));
$row = $ilDB->fetchAssoc($res);
return ($row[0]);
}
public static function _getPriceString($a_price_id)
{
$price = ilPaymentPrices::_getPrice($a_price_id);
$gui_price = self::_getGUIPrice($price['price']);
return $gui_price;
}
public static function _getGUIPrice($a_price)
{
global $lng;
$system_lng = $lng->getDefaultLanguage();
// CODES: ISO 639
$use_comma_seperator = array('ar','bg','cs','de','da','es','et','it',
'fr','nl','el','sr','uk','ru','ro','tr','pl','lt','pt','sq','hu');
// $use_point_separator = array('en','ja','zh','vi');
if(in_array($system_lng, $use_comma_seperator))
{
$gui_price = number_format((float)$a_price, 2, ',', '');
}
else
$gui_price = number_format((float)$a_price, 2, '.', '');
return $gui_price;
}
public static function _formatPriceToString($a_price)
{
include_once './Services/Payment/classes/class.ilPaymentSettings.php';
$genSet = ilPaymentSettings::_getInstance();
$currency_unit = $genSet->get('currency_unit');
$gui_price = self::_getGUIPrice($a_price);
return $gui_price . ' ' . $currency_unit;
/* TODO: after currency implementation is finished -> replace whole function
* include_once './Services/Payment/classes/class.ilPaymentCurrency.php';
$separator= ilPaymentCurrency::_getDecimalSeparator();
$currency_symbol = ilPaymentCurrency::_getSymbol($a_currency_id);
$price_string = number_format($a_price,'2',$separator,'');
return $price_string . ' ' . $currency_symbol;
*/
}
public static function _getPriceStringFromAmount($a_price)
{
include_once './Services/Payment/classes/class.ilPaymentCurrency.php';
include_once './Services/Payment/classes/class.ilPaymentSettings.php';
$genSet = ilPaymentSettings::_getInstance();
$currency_unit = $genSet->get("currency_unit");
$pr_str = '';
$pr_str .= number_format($a_price , 2, ",", ".");
/* TODO: CURRENCY $pr_str = number_format($a_price * $this->getCurrencyConversionRate() , 2, ",", ".");
* remove genset
* */
return $pr_str . " " . $currency_unit;
}
public static function _getTotalAmount($a_price_ids)
{
include_once './Services/Payment/classes/class.ilPaymentPrices.php';
$amount = array();
if (is_array($a_price_ids))
{
for ($i = 0; $i < count($a_price_ids); $i++)
{
$price_data = ilPaymentPrices::_getPrice($a_price_ids[$i]["id"]);
$price = (float) $price_data["price"];
$amount[$a_price_ids[$i]["pay_method"]] += (float) $price;
}
}
return $amount;
}
public function setPrice($a_price = 0)
{
$this->price = preg_replace('/,/','.',$a_price);
$this->price = (float)$a_price;
}
public function setCurrency($a_currency_id)
{
$this->currency = $a_currency_id;
}
public function setDuration($a_duration)
{
if($this->unlimited_duration == '1' && ($a_duration == '' || null))
$a_duration = 0;
$this->duration = (int)$a_duration;
}
public function setUnlimitedDuration($a_unlimited_duration)
{
if($a_unlimited_duration)
$this->unlimited_duration = (int)$a_unlimited_duration;
else
$this->unlimited_duration = 0;
}
public function setExtension($a_extension)
{
$this->extension = (int)$a_extension;
}
public function getExtension()
{
return $this->extension;
}
public function add()
{
$next_id = $this->db->nextId('payment_prices');
$res = $this->db->insert('payment_prices', array(
'price_id' => array('integer', $next_id),
'pobject_id' => array('integer', $this->getPobjectId()),
'currency' => array('integer', $this->__getCurrency()),
'duration' => array('integer', $this->__getDuration()),
'unlimited_duration'=> array('integer', $this->__getUnlimitedDuration()),
'price' => array('float', $this->__getPrice()),
'extension' => array('integer', $this->getExtension()),
'duration_from' => array('date', $this->__getDurationFrom()),
'duration_until' => array('date', $this->__getDurationUntil()),
'description' => array('text', $this->__getDescription()),
'price_type' => array('integer', $this->getPriceType())
));
$this->__read(true);
return true;
}
public function update($a_price_id)
{
$this->db->update('payment_prices',
array( 'pobject_id' => array('integer', $this->getPobjectId()),
'currency' => array('integer', $this->__getCurrency()),
'duration' => array('integer', $this->__getDuration()),
'unlimited_duration'=> array('integer', $this->__getUnlimitedDuration()),
'price' => array('float', $this->__getPrice()),
'extension' => array('integer', $this->getExtension()),
'duration_from' => array('date', $this->__getDurationFrom()),
'duration_until' => array('date', $this->__getDurationUntil()),
'description' => array('text', $this->__getDescription()),
'price_type' => array('integer', $this->getPriceType())
),
array('price_id'=> array('integer', $a_price_id)));
$this->__read(true);
return true;
}
public function delete($a_price_id)
{
$statement = $this->db->manipulateF('
DELETE FROM payment_prices
WHERE price_id = %s',
array('integer'), array($a_price_id));
$this->__read(true);
return true;
}
public function deleteAllPrices()
{
$statement = $this->db->manipulateF('
DELETE FROM payment_prices
WHERE pobject_id = %s',
array('integer'),
array($this->getPobjectId()));
$this->__read(true);
return true;
}
/**
* Validates a price before database manipulations
*
* @access public
* @throws ilShopException
*/
function validate()
{
global $lng;
include_once 'Services/Payment/exceptions/class.ilShopException.php';
switch($this->getPriceType())
{
case self::TYPE_DURATION_MONTH:
if(!preg_match('/^[1-9][0-9]{0,1}$/', $this->__getDuration()))
throw new ilShopException($lng->txt('paya_price_not_valid'));
break;
case self::TYPE_DURATION_DATE:
if(!preg_match('/^[0-9]{4,4}-[0-9]{1,2}-[0-9]{1,2}$/', $this->__getDurationFrom()))
throw new ilShopException($lng->txt('payment_price_invalid_date_from'));
$from_date = explode('-', $this->__getDurationFrom());
if(!checkdate($from_date[1], $from_date[2], $from_date[0]))
throw new ilShopException($lng->txt('payment_price_invalid_date_from'));
if(!preg_match('/^[0-9]{4,4}-[0-9]{1,2}-[0-9]{1,2}$/', $this->__getDurationUntil()))
throw new ilShopException($lng->txt('payment_price_invalid_date_until'));
$till_date = explode('-', $this->__getDurationUntil());
if(!checkdate($till_date[1], $till_date[2], $till_date[0]))
throw new ilShopException($lng->txt('payment_price_invalid_date_until'));
$from = mktime(12, 12, 12, $from_date[1], $from_date[2], $from_date[0]);
$till = mktime(12, 12, 12, $till_date[1], $till_date[2], $till_date[0]);
if($from >= $till)
throw new ilShopException($lng->txt('payment_price_invalid_date_from_gt_until'));
break;
case self::TYPE_UNLIMITED_DURATION:
return true;
break;
default:
throw new ilShopException($lng->txt('payment_no_price_type_selected_sdf'));
break;
}
if(preg_match('/[0-9]/',$this->__getPrice()))
{
return true;
}
throw new ilShopException($lng->txt('payment_price_invalid_price'));
}
// STATIC
public static function _priceExists($a_price_id,$a_pobject_id)
{
global $ilDB;
$res = $ilDB->queryf('
SELECT * FROM payment_prices
WHERE price_id = %s
AND pobject_id = %s',
array('integer', 'integer'),
array($a_price_id, $a_pobject_id));
return $res->numRows() ? true : false;
}
// PRIVATE
private function __getPrice()
{
return $this->price;
}
private function __getCurrency()
{
/*TODO: CURRENCY not finished yet -> return 1 as default */
if($this->currency == null)
$this->currency = 1;
return $this->currency;
}
private function __getDuration()
{
return $this->duration;
}
private function __getUnlimitedDuration()
{
return $this->unlimited_duration;
}
private function __read($with_extension_prices = false)
{
$this->prices = array();
if(!$with_extension_prices)
{
$res = $this->db->queryf('
SELECT * FROM payment_prices
WHERE pobject_id = %s
AND extension = %s
ORDER BY duration',
array('integer','integer'),
array($this->getPobjectId(), 0));
}
else
{
// needed for administration view
$res = $this->db->queryf('
SELECT * FROM payment_prices
WHERE pobject_id = %s
ORDER BY duration',
array('integer'),
array($this->getPobjectId()));
}
while($row = $this->db->fetchObject($res))
{
$this->prices[$row->price_id]['pobject_id'] = $row->pobject_id;
$this->prices[$row->price_id]['price_id'] = $row->price_id;
$this->prices[$row->price_id]['currency'] = $row->currency;
$this->prices[$row->price_id]['duration'] = $row->duration;
$this->prices[$row->price_id]['unlimited_duration'] = $row->unlimited_duration;
$this->prices[$row->price_id]['price'] = $row->price;
$this->prices[$row->price_id]['extension'] = $row->extension;
$this->prices[$row->price_id]['duration_from'] = $row->duration_from;
$this->prices[$row->price_id]['duration_until'] = $row->duration_until;
$this->prices[$row->price_id]['description'] = $row->description;
$this->prices[$row->price_id]['price_type'] = $row->price_type;
}
}
public function getExtensionPrices()
{
$prices = array();
$res = $this->db->queryf('
SELECT * FROM payment_prices
WHERE pobject_id = %s
AND extension = %s
ORDER BY duration',
array('integer','integer'),
array($this->getPobjectId(), 1));
while($row = $this->db->fetchObject($res))
{
$prices[$row->price_id]['pobject_id'] = $row->pobject_id;
$prices[$row->price_id]['price_id'] = $row->price_id;
$prices[$row->price_id]['currency'] = $row->currency;
$prices[$row->price_id]['duration'] = $row->duration;
$prices[$row->price_id]['unlimited_duration'] = $row->unlimited_duration;
$prices[$row->price_id]['price'] = $row->price;
$prices[$row->price_id]['extension'] = $row->extension;
$prices[$row->price_id]['duration_from'] = $row->duration_from;
$prices[$row->price_id]['duration_until'] = $row->duration_until;
$prices[$row->price_id]['description'] = $row->description;
$prices[$row->price_id]['price_type'] = $row->price_type;
}
return $prices;
}
public function getNumberOfPrices()
{
return count($this->prices);
}
public function getLowestPrice()
{
$lowest_price_id = 0;
$lowest_price = 0;
foreach ($this->prices as $price_id => $data)
{
$current_price = $data['price'];
if($lowest_price == 0||
$lowest_price > (float)$current_price)
{
$lowest_price = (float)$current_price;
$lowest_price_id = $price_id;
}
}
return is_array($this->prices[$lowest_price_id]) ? $this->prices[$lowest_price_id] : array();
}
public function setDurationFrom($a_duration_from)
{
// $a_duration_from = "dd.mm.YYYY HH:ii:ss"
$this->duration_from = $a_duration_from;
}
public function setDurationUntil($a_duration_until)
{
$this->duration_until = $a_duration_until;
}
public function setDescription($a_description)
{
$this->description = $a_description;
}
private function __getDurationFrom()
{
return $this->duration_from;
}
private function __getDurationUntil()
{
return $this->duration_until;
}
private function __getDescription()
{
return $this->description;
}
}
?>
| true |
a7e5bacf532aed74fb7fe74c9724354eac7442b4 | PHP | huesimon/project-planner | /app/Http/Livewire/SkillCreate.php | UTF-8 | 416 | 2.578125 | 3 | [] | no_license | <?php
namespace App\Http\Livewire;
use App\Models\Skill;
use Livewire\Component;
class SkillCreate extends Component
{
public $name;
public function render()
{
return view('livewire.skill-create');
}
public function create()
{
for ($i = 1; $i <= 5; $i++) {
Skill::create(['name' => $this->name, 'level' => $i]);
}
$this->name = null;
}
}
| true |
f1ad3004f0a5d23f27e46921e6bcd4c14332069b | PHP | penoonan/toilets | /app/Events/UserSentBusinessMessage.php | UTF-8 | 964 | 2.6875 | 3 | [] | no_license | <?php
namespace Toilets\Events;
use Illuminate\Http\Request;
use Illuminate\Queue\SerializesModels;
use Toilets\Models\Business;
use Toilets\Models\Message;
use Toilets\Models\User;
class UserSentBusinessMessage extends Event
{
use SerializesModels;
/**
* @var Business
*/
public $business;
/**4
* @var Message
*/
public $message;
/**
* @var Request
*/
public $request;
/**
* Create a new event instance.
*
* @param Business $business
* @param Message $message
* @param Request $request
*/
public function __construct(Business $business, Message $message, Request $request)
{
$this->business = $business;
$this->message = $message;
$this->request = $request;
}
/**
* Get the channels the event should be broadcast on.
*
* @return array
*/
public function broadcastOn()
{
return [];
}
}
| true |
c2a1d5c858a180c0a576a3b18497cb3d28e02378 | PHP | kilabs/archer | /protected/components/FrontUserIdentity.php | UTF-8 | 2,186 | 2.640625 | 3 | [] | no_license | <?php
class FrontUserIdentity extends CUserIdentity
{
const ERROR_USER_NOT_CONFIRM=3;
const ERROR_USER_NOT_ACTIVE = 4;
private $_id;
public function authenticate()
{
$record=Member::model()->findByAttributes(array('username'=>$this->username));
if($record === null){
$record=Member::model()->findByAttributes(array('email'=>$this->username));
}
if($record===null){
$this->errorCode=self::ERROR_USERNAME_INVALID;
}
else if($record->status == Member::STATUS_PENDING ){
$this->errorCode=self::ERROR_USER_NOT_CONFIRM;
}
else if($record->status != Member::STATUS_ACTIVE ){
$this->errorCode=self::ERROR_USERNAME_INVALID;
}
else if(!$record->validatePassword($this->password)){
$this->errorCode=self::ERROR_PASSWORD_INVALID;
}
else
{
$this->_id=$record->id;
// $this->setState('title', $record->title);
$this->errorCode=self::ERROR_NONE;
}
return $this->errorCode;
}
public function authenticateHashed()
{
$record=Member::model()->findByAttributes(array('username'=>$this->username));
if($record === null){
$record=Member::model()->findByAttributes(array('email'=>$this->username));
}
if($record===null){
$this->errorCode=self::ERROR_USERNAME_INVALID;
}
else if($record->status == Member::STATUS_PENDING ){
$this->errorCode=self::ERROR_USER_NOT_CONFIRM;
}
else if($record->status != Member::STATUS_ACTIVE ){
$this->errorCode=self::ERROR_USER_NOT_ACTIVE;
}
else if($record->password != $this->password){
$this->errorCode=self::ERROR_PASSWORD_INVALID.$record->password.$this->password;
}
else
{
$this->_id=$record->id;
// $this->setState('title', $record->title);
$this->errorCode=self::ERROR_NONE;
}
return $this->errorCode;
}
public function getId()
{
return $this->_id;
}
} | true |
e9f81f93587fe50349d7bdab8ba9d1a2084ebfed | PHP | quekaihua/StudyTest | /Pro_PHP_Patterns_Framework_Testing_And_More/3/3-1.php | UTF-8 | 481 | 2.953125 | 3 | [] | no_license | <?php
class Database{
private $_db;
static $_instance;
private function __construc(){
$this->_db = pg_connect('dbname=example_db'); //pg数据库连接
}
private __clone(){};
public static function getInstance(){
if(!(self::$_instance instanceof self)){
self::$_instance = new self();
}
return self::$_instance;
}
public function query($sql){
return pg_query($this->_db,$sql);
}
}
$db = Database::getInstance();
$db->query('SELECT * FROM example_table'); | true |
617380bfda600f127e4fb7ba264af753632fe5c8 | PHP | quesheng12/PHP-Flower-Shop | /trading/shoplist.php | UTF-8 | 946 | 2.6875 | 3 | [] | no_license | <?php
include('../utils/conn.php');
$p = $_POST;
if($p['action'] == 1){
item_query($conn, $p['page']);
}
else if($p['action'] == 2){
item_number($conn);
}
mysqli_close($conn);
function item_query($conn, $page){
$sql = "select * from item limit " . ($page-1)*12 . ", 12";
$rst = mysqli_query($conn, $sql);
$num = 1;
$data = array();
while ($arr = mysqli_fetch_assoc($rst)) {
$node = array(
"id" => $arr['id'],
"name" => $arr['name'],
"image" => $arr['image'],
"price" => $arr['price'],
"stock" => $arr['stock'],
"description" => $arr['description']
);
$data[$num] = $node;
$num++;
}
echo json_encode($data);
// echo 200;
}
function item_number($conn){
$sql = "select count(id) as num from item";
$rst = mysqli_query($conn, $sql);
$arr = mysqli_fetch_assoc($rst);
echo $arr['num'];
} | true |
1c94e598b3156b47ec55f56c1e64eb1ec1cdfae0 | PHP | aivijay/mailtics-php | /help/fr/message.php | UTF-8 | 1,913 | 2.640625 | 3 | [] | no_license | Dans le champ réservé au texte de votre message, vous pouvez utiliser des "variables" qui seront remplacées par les valeurs correspondant à chaque utilisateur:
<br />Les variables doivent apparaître sous la forme suivante: <b>[NOM]</b> où NOM peut être remplacé par le nom de l’un de vos attributs.
<br />Par exemple, si vous avez un attribut "Mon Prenom" mettez [MON PRENOM] dans le message quelque part, là où vous voulez que la valeur pour "Mon Prenom" soit insérée.
</p><p>Vous avez défini les attributs suivants:
<table border=1><tr><td><b>Attribut</b></td><td><b>Code-raccourci</b></td></tr>
<?php
$req = Sql_query("select name from {$tables["attribute"]} order by listorder");
while ($row = Sql_Fetch_Row($req))
if (strlen($row[0]) < 20)
printf ('<tr><td>%s</td><td>[%s]</td></tr>',$row[0],strtoupper($row[0]));
print '</table>';
if (ENABLE_RSS) {
?>
<p>Vous pouvez mettre en place des modèles de messages pour des articles RSS. Pour ce faire, cliquez sur l’onglet "Envoi programmé" et sélectionnez la fréquence d’envoi du message. Le message sera ensuite utilisé pour envoyer la liste des articles aux utilisateurs sur les listes qui ont choisi cette fréquence d’envoi. Il faut utiliser le code-raccourci [RSS] dans le corps de votre message pour indiquer l’endroit où la liste doit apparaître.</p>
<?php }
?>
<p>Pour envoyer les contenus d’une page web, ajoutez la ligne suivante dans le corps du message:<br/>
<b>[URL:</b>http://www.exemple.org/chemin/vers/lefichier.html<b>]</b></p>
<p>Vous pouvez inclure des informations de base de l’utilisateur dans cet URL, mais pas d’information des attributs:</br>
<b>[URL:</b>http://www.exemple.org/profilutilisateur.php?email=<b>[</b>email<b>]]</b><br/>
</p> | true |
9ac313cc83818c017d04469b96d10cd696b1f87f | PHP | boxindevelopment/boxin-webbackend | /app/Repositories/Contracts/PickupOrderRepository.php | UTF-8 | 256 | 2.5625 | 3 | [] | no_license | <?php
namespace App\Repositories\Contracts;
use App\Model\PickupOrder;
interface PickupOrderRepository
{
public function create(array $data);
public function update(PickupOrder $order, $data);
public function delete(PickupOrder $order);
}
| true |
b11ce2958a10c6df6d429269a8435f0920cfb8d8 | PHP | bridtobin/webMed | /BackupMaintain.php | UTF-8 | 6,698 | 2.859375 | 3 | [] | no_license | <?php
include_Once("Include/incMaintHeader.php");
if(isset($_REQUEST['pageName'])) {
$_SESSION['pageName'] = $_REQUEST['pageName'] ;
}
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="/gdmedstyle.css" >
<title>GD Med Maintenance</title>
</head>
<body>
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
if(!isset($_SESSION['logged'])) {
echo 'Session logged: '.$_SESSION['logged'] ;
$_SESSION['logged']=0;
}
if($_SESSION['logged']==1) {
?>
<div id="menubar">
<form method="post">
<input type="submit" name="submitButton" value="Home" />
<input type="submit" name="submitButton" value="Opening Hours" />
<input type="submit" name="submitButton" value="Services" />
<input type="submit" name="submitButton" value="Prescriptions" />
<input type="submit" name="submitButton" value="New Patient" />
<input type="submit" name="submitButton" value="Our Team" />
<input type="submit" name="submitButton" value="Fees" />
<input type="submit" name="submitButton" value="Contact Us" />
</form>
</div>
<?php
if($_SERVER['REQUEST_METHOD']=='POST') {
// If a button has been pressed to indicate which page content is to be updated
// then we update the session variable $_SESSION['pageToUpdate'] with that page name.
if (!empty($_POST['submitButton'])) {
$_SESSION['pageToUpdate'] = $_REQUEST[("submitButton")];
switch ($_SESSION['pageToUpdate']) {
case 'Home':
$_SESSION['pageToUpdate']='home';
break;
case 'Opening Hours' :
$_SESSION['pageToUpdate']='times' ;
break;
case 'Services' :
$_SESSION['pageToUpdate']='services' ;
break;
case 'Prescriptions' :
$_SESSION['pageToUpdate']='prescriptions' ;
break;
case 'New Patient' :
$_SESSION['pageToUpdate']='newPatient' ;
break;
case 'Our Team' :
$_SESSION['pageToUpdate']='team' ;
break;
case 'Fees' :
$_SESSION['pageToUpdate']='fees' ;
break;
case 'Contact Us' :
$_SESSION['pageToUpdate']='contact' ;
break;
default:
echo "Unknown Page";
break;
} // switch
} // if (!empty($_POST['submitButton']))
// the fields relating to the current page being edited (i.e. $_SESSION['pageToUpdate']) are displayed as buttons on the left side
if (isset($_SESSION['pageToUpdate']) and $_SESSION['logged']==1) {
$query ="SELECT " .
"fieldName, " .
"fieldDescription " .
"FROM pagefields " .
"WHERE page= '" .
$_SESSION['pageToUpdate'] .
"'" ;
$result = $connection->query($query);
echo "<div id='leftbar'>" ;
echo "<h4>Please select a field to update</h4>" ;
while ($row = $result->fetch_assoc()) {
echo "<form method='post'>" ;
echo "<input type='hidden' name= 'hidden' value='" .
$row['fieldName'] . "'/>" ;
echo "<input type='submit' name='fieldButton' value='" .
$row['fieldDescription'] . "'/>" ;
echo"</form>";
} // while
//close the crecordset
$result->close();
echo "</div>" ;
} // isset(
// If a field has been selected to be updated, then we display the text relating to that field in all languages
if (!empty($_POST['fieldButton'])) {
$field = $_POST['hidden'];
echo "<div id='mainarea'>" ;
$query ="SELECT " .
"fieldName, " .
"actualText, " .
"languageCode " .
"FROM pagecontent " .
"WHERE fieldname= '" .
$field .
"'" ;
$result = $connection->query($query);
echo "<form method='post'>" ;
while ($row = $result->fetch_assoc()) {
echo "<input type='hidden' name= 'hiddenField' value='" .
$row['fieldName'] . "'/>" ;
echo "<input type='hidden' name = 'languageCode[]' value='" .
$row['languageCode'] . "'/>" ;
echo $row['languageCode'] ;
echo "<textarea name='textForPage[]' cols='80' rows='12'>" ;
echo $row['actualText'] ;
echo "</textarea> <br>" ;
}
echo "<input type='submit' name='save' value='Save'>" ;
echo "<br>" ;
echo"</form>";
//close the crecordset
$result->close();
echo "</div>" ;
} // if (!empty($_POST['fieldButton']))
// this is where we actually update the tables with the values. If the save button is selected, the new information is written to the database
if (!empty($_POST['save'])) {
// include("/Include/incConnectDB.php") ;
for($x=0; $x<count($_POST['textForPage']); $x++) {
// now you can use $_POST['cl'][$x] and $_POST['ingredients'][$x]
$query = "update pagecontent set actualText = '" .
($_POST['textForPage'][$x]) . "' where languageCode = '" .
($_POST['languageCode'][$x]) . "' and fieldName = '" .
($_POST['hiddenField']) . "'" ;
$result = $connection->query($query);
} // for
} // if (!empty($_POST['save']))
} // if($_SERVER['REQUEST_METHOD']=='POST')
} else {
echo 'Is login set? '. isset($_POST['login']);
echo 'Login is set to: '.($_POST['login']);
if (isset($_POST['login'])) {
echo 'doing this line';
$query="SELECT count(adminID) as CountAdmin FROM admin WHERE username='" .
$_POST['username'] . "' and password = '" .
md5($_POST['password']) . "'" ;
echo $query ;
$result = $connection->query($query);
while ($row = $result->fetch_assoc()) {
echo "Returned from admin " . $row['CountAdmin'] ;
if ($row['CountAdmin'] > 0) {
$_SESSION['logged']=1 ;
}
else {
$_SESSION['logged']=0 ;
}
}
if ($_SESSION['logged']==1) {
?>
<div id='mainarea'>
<p>We are here</p>
<form method="post">
<h3>Successful login. Press OK to continue</h3>
<input type="submit" name="login" value="Ok">
</form>
</div>
<?php
} else {
?>
<div id='mainarea'>
<form method="post">
<h3>Unsuccessful Login</h3>
<br>
<br>
Username: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br><br>
<input type="submit" name="login" value="login">
</form>
</div>
<?php
}
} // (isset($_POST[['login']))
else {
?>
<div id='mainarea'>
<form method="post">
<h3>Please login to use the Administration Section</h3>
<br>
<br>
Username: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br><br>
<input type="submit" name="login" value="login">
</form>
</div>
<?php
} // else...isset($_POST['login']))
} // else...($_SESSION['logged']==1)
?>
<div id='footer'> </div>
| true |
98f9741b3369383d3971fe549c84c8704a70c239 | PHP | corgisout/oophp | /test/Game/DiceTest.php | UTF-8 | 374 | 2.6875 | 3 | [] | no_license | <?php
namespace sihd\Game;
use PHPUnit\Framework\TestCase;
/**
* Test cases for class Guess.
*/
class DiceTest extends TestCase
{
public function testRoll()
{
$dice = new Dice();
$this->assertInstanceOf("\sihd\Game\Dice", $dice);
$res = $dice->roll();
$exp = $dice->getLastRoll();
$this->assertEquals($exp, $res);
}
}
| true |
273f0e9854c14b83f8bf1db54c42b441125a7b78 | PHP | larizarg/School-Administration | /loggedIn/marks/enterScore.php | UTF-8 | 3,126 | 2.9375 | 3 | [] | no_license | <?php
require_once '../../webdev/php/Generators/HTMLGenerator/Generator.php';
require_once '../../webdev/php/Classes/Messages.php';
require_once '../../webdev/php/Classes/ClassPerson.php';
$HTML = new HTMLGenertator\HTMLfile('Enter score for a test', ['marks.css', 'form.css'], NULL, NULL, 1);
$HTML->outputHeader();
if (!isset($_GET['id'])) {
Message::castMessage('Please select a test first.', false, 'setMarks.php');
}
$id = intval($_GET['id']);
if ($id == 0) {
Message::castMessage('Invalid Id.', false, 'setMarks.php');
}
//Fetching the information
$result = safeQuery('SELECT taskCount, maxScore FROM marks__test WHERE id=' . $id . ';');
if (mysql_num_rows($result) == 0) {
Message::castMessage('Invalid id', false, 'setMarks.php');
} else {
$row = mysql_fetch_assoc($result);
$taskCount = $row['taskCount'];
$maxScore = $row['maxScore'];
}
?>
<form action="submitMarks.php" method="POST">
<input type="hidden" value="<?php echo $id; ?>" name="id" />
<fieldset>
<legend>Test settings</legend>
Changing the test settings will discard all the changes that are not saved on this sheet.
<br />
<a href="changeInformation.php?id=<?php echo $id; ?>">Change test information</a>
</fieldset>
<fieldset>
<legend>Marks</legend>
<table>
<thead>
<th>Id</th>
<?php
for ($i = 1; $i <= $taskCount; $i++) {
echo '<th>Task ' . $i . '</th>';
}
?>
<th>Sum</th>
</thead>
<tbody>
<?php
$students = safeQuery('SELECT * FROM marks__points WHERE testId=' . $id . ' ORDER BY studentId, task;');
$allStudents = safeQuery('
SELECT studentID
FROM course__student
LEFT JOIN course__tests
ON course__student.classID = course__tests.classId
WHERE course__tests.id = ' . $id . ';');
$markArray = [];
while ($student = mysql_fetch_array($allStudents)) {
$markArray[$student[0]] = [];
}
while ($row = mysql_fetch_assoc($students)) {
$sId = intval($row['studentId']);
if (!isset($markArray[$sId])) {
$markArray[$sId] = [];
}
array_push($markArray[$sId], $row['score']);
}
foreach ($markArray as $key => $value) {
$sum = 0;
echo '<tr>';
echo '<td>' . ClassPerson::staticGetName($key, $_SESSION['nickName']) . '</td>';
for ($i = 0; $i < $taskCount; $i++) {
$outScore = isset($value[$i]) ? $value[$i] : 0;
$sum += $outScore;
echo '<td><input type="number" value="' . $outScore . '" min="0" name="i' . $key . 't' . ($i + 1) . '" /></td>';
}
$percent = $sum / $maxScore * 100;
$colored = '';
if ($percent > 100) {
$colored = 'class="red"';
} else if ($percent < 100) {
$colored = 'class="yellow"';
} else {
$colored = 'class="green"';
}
echo"<td $colored>" . $sum . ' p.<br />(' . roundUp($percent, 1) . '%)</td></tr>';
}
?>
</tbody>
</table>
</fieldset>
<fieldset>
<legend>Save and discard</legend>
<button type="submit" title="You can also hit enter in order to save the changes.">Save</button>
<button type="reset">Don't save</button>
</fieldset>
</form>
<?php
$HTML->outputFooter();
?> | true |
d8056fd03e357fe357eaa962ed0c0abe25972f53 | PHP | nbtscommunity/phpfnlib | /mime/header.php | UTF-8 | 712 | 3.15625 | 3 | [] | no_license | <?php
function mime_parse_header($s) {
$lines = explode("\n", str_replace("\r", "", $s));
$o = array();
foreach($lines as $line) {
if(strspn($line, " \t")) {
$o[count($o) - 1] .= str_replace("\t", " ", $line);
} else {
$o[] = $line;
}
}
$lines = array();
foreach($o as $line) {
$temp = explode(":", $line, 2);
if(empty($temp[0])) continue;
$lines[strtolower($temp[0])] = trim($temp[1]);
}
return $lines;
}
function mime_make_header($headers) {
// Fixme: Can't handle multiple headers with same name yet.
$o = array();
foreach($headers as $header => $value) {
$o[] = ucfirst($header).": ".wordwrap($value, 74, "\n\t", 1);
}
return join("\n", $o);
}
?>
| true |
08ed1ee078c560dafbaae6ed1880949d2e2d78c4 | PHP | abiusx/php-emul | /samples/sample-constructor.php | UTF-8 | 270 | 3.15625 | 3 | [] | no_license | <?php
class Base {
function __construct($arg1=5,$arg2=10)
{
echo "Base::construct\n";
var_dump($arg1,$arg2);
print_r(func_get_args());
}
}
class Extend extends Base {
// function __construct()
// {
// echo "Extend::construct\n";
// }
}
$x=new Extend;
| true |
5295856c6b121570c7ce5a176ff32268b46e7ddd | PHP | mkungla/aframe-php | /src/Extras/Primitives/Objmodel.php | UTF-8 | 1,965 | 2.78125 | 3 | [
"MIT"
] | permissive | <?php
/** @formatter:off
* ******************************************************************
* Created by Marko Kungla on Jul 7, 2016 - 9:24:33 PM
* Contact marko@okramlabs.com
* @copyright 2016 Marko Kungla - https://github.com/mkungla
* @license The MIT License (MIT)
*
* @category AframeVR
* @package aframe-php
*
* Lang PHP (php version >= 7)
* Encoding UTF-8
* File ObjModel.php
* Code format PSR-2 and 12
* @link https://github.com/mkungla/aframe-php
* @issues https://github.com/mkungla/aframe-php/issues
* ********************************************************************
* Contributors:
* @author Marko Kungla <marko@okramlabs.com>
* ********************************************************************
* Comments:
* @formatter:on */
namespace AframeVR\Extras\Primitives;
use \AframeVR\Core\Entity;
use \AframeVR\Interfaces\EntityInterface;
final class ObjModel extends Entity implements EntityInterface
{
/**
* Init <a-obj-model>
*
* The obj-model component loads a 3D model and material using a Wavefront (.OBJ) file and a .MTL file.
*
* @return void
*/
public function reset()
{
parent::reset();
}
/**
* Selector to obj
*
* Selector to an <a-asset-item> pointing to a .OBJ file or an inline path to a .OBJ file.
*
* @param string $selector
* @return ObjModel
*/
public function obj(string $selector)
{
$this->attr('ObjModel')->obj($selector);
return $this;
}
/**
* Selector to mtl
*
* Selector to an <a-asset-item> pointing to a .MTL file or an inline path to a .MTL file. Optional if you wish to
* use the material component instead.
*
* @param string $selector
* @return ObjModel
*/
public function mtl(string $selector)
{
$this->attr('ObjModel')->mtl($selector);
return $this;
}
} | true |
77d948cb96e13a091d11239f80fab33b4db93761 | PHP | bmunyoki/mpesa | /src/Mpesa.php | UTF-8 | 11,779 | 2.84375 | 3 | [
"MIT"
] | permissive | <?php
namespace Bmunyoki\Mpesa;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Cache;
class Mpesa {
public $environment;
private $baseUrl;
public $consumerKey;
public $consumerSecret;
private $cred;
private $accessToken;
/**
* Constructor method
*
* Initializes the class with an array of API values.
*
* @param array $config
* @return void
* @throws exception if the values array is not valid
*/
public function __construct() {
$environment = config('mpesa.mpesa_env');
$consumerKey = config('mpesa.consumer_key');
$consumerSecret = config('mpesa.consumer_secret');
$this->environment = $environment;
// Set the base URL for API calls based on the application environment
if ($environment == 'sandbox') {
$this->baseUrl = 'https://sandbox.safaricom.co.ke/mpesa/';
} else {
$this->baseUrl = 'https://api.safaricom.co.ke/mpesa/';
}
$this->consumerKey = $consumerKey;
$this->consumerSecret = $consumerSecret;
// Set the access token
$this->accessToken = $this->getAccessToken();
}
/**
* Submit Request - Handles submission of all API endpoints queries
* @return object|boolean Curl response or FALSE on failure
* @throws exception if the Access Token is not valid
*/
public function setCred($initiatorPassword) {
// Set public key certificate based on environment
if($this->environment == 'sandbox') {
$pubkey = File::get(__DIR__.'/cert/sandbox.cer');
} else {
$pubkey = File::get(__DIR__.'/cert/production.cer');
}
openssl_public_encrypt($initiatorPassword, $output, $pubkey, OPENSSL_PKCS1_PADDING);
$this->cred = base64_encode($output);
return $this->cred;
}
public function getAccessToken() {
$credentials = base64_encode($this->consumerKey.':'.$this->consumerSecret);
$ch = curl_init();
$url = 'https://api.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials';
if($this->environment == 'sandbox') {
$url = 'https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials';
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Basic '.$credentials, 'Content-Type: application/json'));
$response = curl_exec($ch);
curl_close($ch);
$response = json_decode($response);
//\Log::info(json_encode($response, true));
if($response == null) {
return false;
}
$accessToken = @$response->access_token;
$this->accessToken = $accessToken;
return $accessToken;
}
/**
* Submit request - submits a curl request to Mpesa API
* @return object $response, false on failure
*/
private function submitRequest($url, $data) {
$accessToken = $this->getAccessToken();
if($accessToken == '' || $accessToken == FALSE) {
return false;
}
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Authorization: Bearer '.$accessToken));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
/**
* Business to Client (B2C) - used to send money to the customer Mpesa account.
* @return object Curl Response from submitRequest method, FALSE on failure
*/
public function b2c($paybillOrTill, $initiatorUsername, $initiatorPassword, $amount, $phone, $commandId, $remarks, $b2cTimeoutUrl, $b2cResultUrl) {
$cred = $this->setCred($initiatorPassword);
$requestData = array(
'InitiatorName' => $initiatorUsername,
'SecurityCredential' => $cred,
'CommandID' => $commandId,
'Amount' => $amount,
'PartyA' => $paybillOrTill,
'PartyB' => $phone,
'Remarks' => $remarks,
'QueueTimeOutURL' => $b2cTimeoutUrl,
'ResultURL' => $b2cResultUrl,
'Occasion' => '' //Optional
);
$data = json_encode($requestData);
$url = $this->baseUrl.'b2c/v1/paymentrequest';
return $this->submitRequest($url, $data);
}
/**
* Business to Business (B2B) - used to send money to other business Mpesa till or paybill.
* @return object Curl Response from submitRequest, FALSE on failure
*/
public function b2b($initiatorUsername, $initiatorPassword, $amount, $paybillOrTill, $shortcode, $reference, $b2bTimeoutUrl, $b2bResultUrl) {
$cred = $this->setCred($initiatorPassword);
$requestData = array(
'Initiator' => $initiatorUsername,
'SecurityCredential' => $cred,
'CommandID' => 'BusinessToBusinessTransfer',
'SenderIdentifierType' => 'Shortcode',
'RecieverIdentifierType' => 'Shortcode',
'Amount' => $amount,
'PartyA' => $paybillOrTill,
'PartyB' => $shortcode,
'AccountReference' => $reference,
'Remarks' => 'This is a test comment or remark',
'QueueTimeOutURL' => $b2bTimeoutUrl,
'ResultURL' => $b2bResultUrl,
);
$data = json_encode($requestData);
$url = $this->baseUrl.'b2b/v1/paymentrequest';
return $this->submitRequest($url, $data);
}
/**
* C2B register urls - used to register URLs for callbacks when money is sent from the MPesa toolkit menu
* @return object Curl Response from submitRequest, FALSE on failure
*/
public function c2bRegisterUrls($paybillOrTill, $c2bConfirmationUrl, $c2bValidationUrl) {
$requestData = array(
'ShortCode' => $paybillOrTill,
'ResponseType' => 'Completed',
'ConfirmationURL' => $c2bConfirmationUrl,
'ValidationURL' => $c2bValidationUrl
);
$data = json_encode($requestData);
$url = $this->baseUrl.'c2b/v2/registerurl';
$response = $this->submitRequest($url, $data);
return $response;
}
/**
* Pull API to Business - used to register URLs for Pull API callbacks
*
* @return object Curl Response from submitRequest, FALSE on failure
*/
public function pullRegisterUrl($nominatedNumber, $storeNumber, $pullCallbackUrl) {
$requestData = array(
'ShortCode' => $storeNumber, //Replace this with store number 7085771
'RequestType' => 'Pull',
'NominatedNumber' => $nominatedNumber,
'CallBackURL' => $pullCallbackUrl
);
$data = json_encode($requestData);
$url = 'https://api.safaricom.co.ke/pulltransactions/v1/register';
return $this->submitRequest($url, $data);
}
/**
* PULL API - used to pull transactions for a given short code within given timestamps
* @return object Curl Response from submitRequest, FALSE on failure
*/
public function pullAPI($storeNumber, $start, $end) {
$data = array(
'ShortCode' => $storeNumber,
'StartDate' => $start,
'EndDate' => $end,
'OffSetValue' => "0"
);
$data = json_encode($data);
$url = 'https://api.safaricom.co.ke/pulltransactions/v1/query';
return $this->submitRequest($url, $data);
}
/**
* C2B Simulation - used to simulate a C2B Transaction to test your ConfirmURL and ValidationURL in the Client to Business method
* @return object Curl Response from submitRequest, FALSE on failure
*/
public function simulateC2B($paybillOrTill, $amount, $msisdn, $ref) {
$data = array(
'ShortCode' => $paybillOrTill,
'CommandID' => 'CustomerPayBillOnline',
'Amount' => $amount,
'Msisdn' => $msisdn,
'BillRefNumber' => $ref
);
$data = json_encode($data);
$url = $this->baseUrl.'c2b/v2/simulate';
return $this->submitRequest($url, $data);
}
/**
* Check Balance
* @return object Curl Response from submitRequest, FALSE on failure
*/
public function checkBalance($paybillOrTill, $initiatorUsername, $initiatorPassword, $balanceTimeoutUrl, $balanceResultUrl) {
$cred = $this->setCred($initiatorPassword);
$data = array(
'CommandID' => 'AccountBalance',
'PartyA' => $paybillOrTill,
'IdentifierType' => '4',
'Remarks' => 'Remarks or short description',
'Initiator' => $initiatorUsername,
'SecurityCredential' => $cred,
'QueueTimeOutURL' => $balanceTimeoutUrl,
'ResultURL' => $balanceResultUrl
);
$data = json_encode($data);
$url = $this->baseUrl.'accountbalance/v1/query';
return $this->submitRequest($url, $data);
}
/**
* Transaction status request - used to check a transaction status
* @return object Curl Response from submitRequest, FALSE on failure
*/
public function statusRequest($paybillOrTill, $initiatorUsername, $initiatorPassword, $statusTimeoutUrl, $statusResultUrl, $transaction = 'LH7819VXPE') {
$cred = $this->setCred($initiatorPassword);
$data = array(
'CommandID' => 'TransactionStatusQuery',
'PartyA' => $paybillOrTill,
'IdentifierType' => 4,
'Remarks' => 'Testing API',
'Initiator' => $initiatorUsername,
'SecurityCredential' => $cred,
'QueueTimeOutURL' => $statusTimeoutUrl,
'ResultURL' => $statusResultUrl,
'TransactionID' => $transaction,
'Occassion' => 'Test'
);
$data = json_encode($data);
$url = $this->baseUrl.'transactionstatus/v1/query';
return $this->submitRequest($url, $data);
}
/**
* Transaction Reversal - used to reverse a transaction
*
* @return object Curl Response from submitRequest, FALSE on failure
*/
public function reverseTransaction($initiatorUsername, $initiatorPassword, $resersalTimeoutUrl, $resersalResultUrl, $receiver, $transactionId, $amount, $testMsisdn) {
$cred = $this->setCred($initiatorPassword);
$data = array(
'CommandID' => 'TransactionReversal',
'ReceiverParty' => $testMsisdn,
'RecieverIdentifierType' => 1, //1=MSISDN, 2=Till_Number, 4=Shortcode
'Remarks' => 'Testing',
'Amount' => $amount,
'Initiator' => $initiatorUsername,
'SecurityCredential' => $cred,
'QueueTimeOutURL' => $resersalTimeoutUrl,
'ResultURL' => $resersalResultUrl,
'TransactionID' => $transactionId
);
$data = json_encode($data);
$url = $this->baseUrl.'reversal/v1/request';
return $this->submitRequest($url, $data);
}
/*********************************************************************
*
* LNMO APIs - STK
*
* *******************************************************************/
public function stkRequest($paybillOrTill, $storeNumber, $passKey, $amount, $phone, $callbackUrl, $transactionType, $ref = "Payment", $desc = "Payment") {
if(!is_numeric($amount) || $amount < 1 || !is_numeric($phone)) {
throw new \Exception("Invalid amount and/or phone number. Amount should be 10 or more, phone number should be in the format 254xxxxxxxx");
return false;
}
$timestamp = date('YmdHis');
$passwd = base64_encode($storeNumber.$passKey.$timestamp);
$data = array(
'BusinessShortCode' => $storeNumber,
'Password' => $passwd,
'Timestamp' => $timestamp,
'TransactionType' => $transactionType,
'Amount' => $amount,
'PartyA' => $phone,
'PartyB' => $paybillOrTill,
'PhoneNumber' => $phone,
'CallBackURL' => $callbackUrl,
'AccountReference' => $ref,
'TransactionDesc' => $desc,
);
$data = json_encode($data);
$url = $this->baseUrl.'stkpush/v1/processrequest';
$response = $this->submitRequest($url, $data);
return json_decode($response);
}
private function stkStatusQuery($paybillOrTill, $passKey, $checkoutRequestID = null) {
$timestamp = date('YmdHis');
$passwd = base64_encode($paybillOrTill.$passKey.$timestamp);
if($checkoutRequestID == null || $checkoutRequestID == '') {
return false;
}
$data = array(
'BusinessShortCode' => $paybillOrTill,
'Password' => $passwd,
'Timestamp' => $timestamp,
'CheckoutRequestID' => $checkoutRequestID
);
$data = json_encode($data);
$url = $this->baseUrl.'stkpushquery/v2/query';
return $this->submitRequest($url, $data);
}
} | true |
56875b59ab475e038bb7e1b3890b900aed654494 | PHP | dbeurive/backend | /src/Cli/Adapter/Database/Connector/AbstractConnector.php | UTF-8 | 4,206 | 3.171875 | 3 | [] | no_license | <?php
/**
* This file implements the base class for all "connectors".
*
* Connectors are just very thin wrappers around a low-level database handler, such as PDO or mysqli.
* A connector performs the following actions:
* * It exports the configuration's parameters required to initialise the low-level database handler.
* See AbstractConnector::getConfigurationParameters
* * It initialises the low-level database handler.
* See AbstractConnector::connect
*
* Please note that you can use PDO to access MySql or SQLite databases.
* However, the configuration's parameters required to initialise a connexion to a MySql server are not the same than the ones required to open a SQLite database.
* Please also note that the APIs for PDO and mysqli differ.
* The purpose of the connectors is to export a unified API for all low-level database handlers.
*
* @see AbstractConnector::getConfigurationParameters
* @see AbstractConnector::connect
*/
namespace dbeurive\Backend\Cli\Adapter\Database\Connector;
/**
* Class AbstractConnector
*
* This class is the base class for all connectors.
*
* @package dbeurive\Backend\Cli\Adapter\Database\Connector
*/
abstract class AbstractConnector implements InterfaceConnector
{
/**
* @var mixed|null Handler to the database (typically, this is an instance of \PDO).
*/
private $__databaseHandler=null;
/**
* @var array Configuration required to establish the connexion.
*/
private $__configuration;
/**
* This method opens the connection to the database.
* @param array $inConfiguration Configuration required to open the connection.
* @return mixed|bool If the connexion is successfully established, then the method returns handler to the database.
* This can be an instance of \PDO, for example.
* Otherwise, the method throws an exception.
* @throws \Exception
*/
abstract protected function _connect(array $inConfiguration);
/**
* Create a connector.
* @param array $inOptConfiguration Configuration's parameters required by the database handler to establish a connexion.
* @param bool $inOtpConnect This flag specifies whether a connexion ro the database must be established or not.
* @throws \Exception
*/
final public function __construct(array $inOptConfiguration, $inOtpConnect=false) {
$this->__configuration = $inOptConfiguration;
if ($inOtpConnect) {
$this->connect();
}
}
/**
* Open the connection to the database and returns the handler rto the database.
* @param array $inConfiguration Configuration required to open the connection.
* @return mixed The handler to the database.
* @throws \Exception
*/
public function connect() {
$this->__databaseHandler = $this->_connect($this->__configuration);
return $this->__databaseHandler;
}
/**
* Return the handler to the database.
* @return mixed The handler to the database.
* @throws \Exception
*/
public function getDatabaseHandler() {
if (is_null($this->__databaseHandler)) {
throw new \Exception("You did not open any connection to the database!");
}
return $this->__databaseHandler;
}
/**
* Return the configuration for the handler to the database.
* @return array The configuration.
* @throws \Exception
*/
public function getConfiguration() {
return $this->__configuration;
}
// -----------------------------------------------------------------------------------------------------------------
// Statics
// -----------------------------------------------------------------------------------------------------------------
/**
* Return the fully qualified name of the object's class.
* Please not that this method should return the value of __CLASS_.
* @return string The fully qualified name of the element's class.
*/
public static function getFullyQualifiedClassName() {
$reflector = new \ReflectionClass(get_called_class());
return $reflector->getName();
}
}
| true |
167230094e24ad47e2b54fb957ce213427aea7b6 | PHP | tomk79/broccoli-module-std-document | /php/utils.php | UTF-8 | 711 | 2.578125 | 3 | [
"MIT"
] | permissive | <?php
/**
* broccoli-html-editor fields
*/
namespace tomk79\broccoliModuleStdDocument;
/**
* Utilities
*
* @author Tomoya Koyanagi <tomk79@gmail.com>
*/
class utils{
/**
* Dropped File Operator
*/
static function droppedFileOperator( $type, $options = array() ){
if( is_array($options) || is_object( $options ) ){
$options = (array) $options;
}else{
$options = array();
}
if( !strlen(''.$type) ){
return null;
}
$rtn = null;
switch( $type ){
case 'image':
$rtn = array();
$rtn['file'] = __DIR__.'/../dist/broccoliModuleStdDocumentDroppedFileOperatorGen.js';
$rtn['function'] = 'window.broccoliModuleStdDocumentDroppedFileOperatorGen({})';
break;
}
return $rtn;
}
}
| true |
11b2d30218fdf87d1574dd53c7eefafe978b5068 | PHP | devsmt/bin_tools | /compile | UTF-8 | 1,438 | 2.578125 | 3 | [
"Apache-2.0"
] | permissive | #!/usr/bin/env php
<?php
declare(strict_types=1);//php7.0+, will throw a catchable exception if call typehints and returns do not match declaration
/*
// TODO: typescript
*/
declare (strict_types = 1);
require_once __DIR__ . '/Utils.php';
function e(string $cmd) {
echo "cmd: " . $cmd . "\n";
echo $r = `$cmd` . "\n";
return $r;
}
// main
$file_path = isset($_SERVER['argv'][1]) ? $_SERVER['argv'][1] : ''; // 0=>pgr name
if (empty($file_path)) {
die('no file to lint.');
}
if (!request_is_cli()) {
die("usa questo comando da cli.");
} else {
set_time_limit(0);
if ($argc == 1) {
action_usage();
} else {
$ext = pathinfo($file_path, PATHINFO_EXTENSION); // se script cli, prova php
if (empty($ext) || $file_path == $ext) {
$ext = 'php';
}
switch ($ext) {
case 'php':
// nothing to do ?
break;
case 'ts':
$cmd = "tsc $file_path";
e($cmd);
break;
case 'js':
default:
die(implode('/', [__FUNCTION__, __METHOD__, __LINE__]) . ' > TODO ' . $ext);
break;
}
}
exit(0);
}
//-- actions --------------------------------------
//
function action_XXX() {
}
function action_usage() {
echo "{$_SERVER['argv'][0]} [act1|act2] [param1]
actions:
XXX = ...
\n";
}
//-- utils ----------------------------------------
exit(0);
| true |