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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
dae3dc58fd1524d216fca44a63667a8a119a6b82 | PHP | herdita/belajar-php | /2_Intermediate_php/6_contoh_login.php | UTF-8 | 897 | 2.765625 | 3 | [] | no_license | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form action="" method="post">
<input type="text" name="nama">
<input type="password" name="password">
<input type="submit" name="submit">
</form>
<?php
$data_user = "herdita";
$data_pass = "21051997";
if(isset($_POST['submit'])){
if($_POST['nama']==$data_user && $_POST['password']==$data_pass){
// echo "login berhasil";
// untuk berpindah ke halaman bisa menggunakan header
header('Location: 5_halaman_get.php?nama='.$_POST['nama']);
}else{
echo "login gagal";
};
};
?>
</body>
</html> | true |
83f4f2459211de3d2615e6ea0c160eb340462795 | PHP | box4pes/pes | /src/Application/UriInfoFactory.php | UTF-8 | 3,228 | 2.9375 | 3 | [] | no_license | <?php
/*
* Copyright (C) 2019 pes2704
*
* This is no software. This is quirky text and you may do anything with it, if you like doing
* anything with quirky texts. This text 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.
*/
namespace Pes\Application;
use Pes\Http\Environment;
use Psr\Http\Message\ServerRequestInterface;
/**
* Description of UriInfoFactory
*
* @author pes2704
*/
class UriInfoFactory implements UriInfoFactoryInterface {
public function create(Environment $environment, ServerRequestInterface $request) {
// subdomain path a rest uri
// subdomain path a rest uri
$requestScriptName = parse_url($environment->get('SCRIPT_NAME'), PHP_URL_PATH);
$requestScriptDir = dirname($requestScriptName);
$requestUri = $request->getUri()->getPath();
if (stripos($requestUri, $requestScriptName) === 0) {
$subDomainPath = $requestScriptName;
} elseif ($requestScriptDir !== '/' && stripos($requestUri, $requestScriptDir) === 0) {
$subDomainPath = $requestScriptDir;
} else {
$subDomainPath = '';
}
if ($subDomainPath) {
$virtualPath = substr($requestUri, strlen($subDomainPath));
} else {
$virtualPath = $requestUri;
}
$virtualPath = '/'.ltrim($virtualPath, '/');
// objekt UrlInfo atribut s názvem self::URL_INFO_ATTRIBUTE_NAME do requestu a request do app
$urlInfo = new UrlInfo();
$urlInfo->setSubdomainUri($subDomainPath);
$urlInfo->setSubdomainPath($this->normalizePath($requestScriptDir));
$urlInfo->setRestUri($virtualPath);
$urlInfo->setRootAbsolutePath($this->rootAbsolutePath($environment));
$urlInfo->setWorkingPath($this->workingPath());
return $urlInfo;
}
/**
* RelaTivní cesta k aktuálnímu pracovnímu adresáři.
* @return string
*/
private function workingPath() {
$cwd = getcwd();
if($cwd) {
return self::normalizePath($cwd);
} eLse {
throw new \RuntimeException('Nelze číst pracovní adresář skriptu. Příčinou mohou být nedostatečná práVa k adresáři skriptu.');
}
}
/**
* Absolutní cesta ke kořenovému adresáři skriptu. Začíná i končí '/'.
* @param Environment $environment
* @return string
*/
private function rootAbsolutePath(Environment $environment) {
$scriptName = $environment->get('SCRIPT_NAME');
$ex = explode('/', $scriptName);
array_shift($ex);
array_pop($ex);
$impl = implode('/', $ex);
$rootAbsolutePath = $impl ? '/'.$impl.'/' : '/';
return $rootAbsolutePath;
}
/**
* Nahradí levá lomítka za pravá a zajistí, aby cesta nezačínala (levým) lomítkem a končila (pravým) lomítkem
* @param string $directoryPath
* @return string
*/
private function normalizePath($directoryPath) {
return $directoryPath = rtrim(str_replace('\\', '/', $directoryPath), '/').'/';
}
}
| true |
1364293f75736f7c8b7841f647c176e2ee8f7850 | PHP | onacvooe/HautoNL | /app/Http/Controllers/RoomsController.php | UTF-8 | 1,411 | 2.59375 | 3 | [] | no_license | <?php
namespace App\Http\Controllers;
//use Illuminate\Http\Request;
use App\Room;
class RoomsController extends Controller
{
public function index()
{
$rooms = \App\Room::all();
return view('dashboard.rooms.index', compact('rooms'));
}
public function create()
{
return view('dashboard.rooms.create');
}
public function show(Room $room)
{
return view('dashboard.rooms.show', compact('room'));
}
public function store()
{
$attributes = request()->validate([
'title' => ['required', 'min:3'],
'description' => ['required', 'min:5']
]);
//return request()->all(); Alle informatie terugkrijgen van DB
Room::create($attributes);
return redirect('/dashboard');
}
public function edit(Room $room)
{
return view('dashboard.rooms.edit', compact('room'));
}
public function update(Room $room)
{
$attributes = request()->validate([
'title' => ['required', 'min:3'],
'description' => ['required', 'min:5']
]);
//return request()->all(); Alle informatie terugkrijgen van DB
$room->update(request(['title', 'description']));
return redirect('/dashboard');
}
public function destroy(Room $room)
{
$room->delete();
return redirect('/dashboard');
}
}
| true |
99e98507d7ec7e4425ab7b2233ae3c716df48336 | PHP | oworyoakim/eshop | /app/Http/Middleware/TenantConnection.php | UTF-8 | 3,476 | 2.515625 | 3 | [] | no_license | <?php
namespace App\Http\Middleware;
use App\Models\Business;
use App\Models\Tenant\Employee;
use App\Models\Tenant\Role;
use App\Repositories\System\IBusinessRepository;
use Illuminate\Support\Facades\Config;
use Closure;
use Illuminate\Support\Facades\DB;
use Exception;
use PDOException;
use Sentinel;
class TenantConnection {
/**
* @var IBusinessRepository
*/
private $businessRepository;
public function __construct(IBusinessRepository $businessRepository)
{
$this->businessRepository = $businessRepository;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next) {
//Return the Company that the current user is visiting through the SubDomain
try{
$host = request()->getHost();
$domains = explode('.', $host);
if (count($domains) <= 2 || $domains[0] === 'www' || $domains[0] === 'WWW') {
$error = "Company does not exist!";
// return response($error, 422);
//abort(422,$error);
return response()->view('errors.notfound',compact('error'));
}
$subdomain = $domains[0];
// dd($subdomain);
$business = $this->businessRepository->findOneBy(['subdomain' => $subdomain]);
if (!$business) {
$error = "Company $subdomain does not exist!";
// return response()->json($error, 422);
//abort(422,$error);
return response()->view('errors.notfound',compact('error'));
}
// dd($business);
if (!$business->authorized) {
$error = "Your business account is not active!";
// return response()->json($error, 402);
return response()->view('errors.notpaid',compact('error'));
}
$business->setTenantConnection();
Config::set('database.default', 'tenant');
$dbname = DB::connection()->getDatabaseName();
//dd($dbname);
// try to connect to the database
DB::connection()->getPdo();
// DB::unprepared("USE $dbname");
Config::set('cartalyst.sentinel.users.model', '\App\Models\Tenant\Employee');
Config::set('cartalyst.sentinel.roles.model', '\App\Models\Tenant\Role');
Sentinel::setModel('App\Models\Tenant\Employee');
Sentinel::getRoleRepository()->setModel('\App\Models\Tenant\Role');
Role::setUsersModel('App\Models\Tenant\Employee');
Employee::setRolesModel('\App\Models\Tenant\Role');
// dd($business);
$request->attributes->add(['business' => $business]);
return $next($request);
} catch (PDOException $ex){
Config::set('database.default', 'system');
$error = 'Database Connection Failed!';
// return response($error, 422);
// abort(501,$error);
return response()->view('errors.database',compact('error'));
} catch (Exception $ex){
Config::set('database.default', 'system');
$error = $ex->getMessage();
// return response($error, 422);
// abort(501,$error);
return response()->view('errors.general',compact('error'));
}
}
}
| true |
f9aa810e5c2ec2c02928e547e4a2a9ba54573864 | PHP | corollari/UAB_projects | /3A1S/TDIW/vscomponentes/controllers/controllerUserPanel.php | UTF-8 | 1,571 | 2.515625 | 3 | [] | no_license | <?php
session_start();
if(isset($_COOKIE['username']) && isset($_COOKIE['password']))
{
require("../model/model.php");
$stmt = $DB->getUserData($_COOKIE['username'], $_COOKIE['password']);
/* vincular variables a la sentencia preparada */
$stmt->bind_result($name, $username, $password, $email, $street, $city, $phone, $postal, $card);
//Obtención de datos
while($stmt->fetch())
{
$name;
$username;
$password;
$email;
$street;
$city;
$phone;
$postal;
$card;
}
$stmt->close();
$userID = $DB->getUsernameID($_COOKIE['username']);
$salesUserID = $DB->getUserPurchases($userID);
$salesUserArray = [];
$userPurchasesArray = [];
while($rowSales = $salesUserID->fetch_assoc())
{
$salesUserArray[] = $rowSales;
}
foreach ($salesUserArray as $rowSalesID)
{
$productsPurchases = $DB->getUserProductsPurchases($userID, $rowSalesID['reference_id']);
while($rowProductsPurchases = $productsPurchases->fetch_assoc())
{
$userPurchasesArray[$rowSalesID['reference_id']][] = $rowProductsPurchases;
}
}
$DB->closeConnectionDB();
$sessionDetalle = $_SESSION["detalle"];
require("../views/viewUserPanel.php");
}
else
{
require("../views/viewForbidden.html");
}
?>
| true |
2a3a131844ed2ac37bd8998867648734d0ef0e8f | PHP | baobeiboboda/efan_admin | /Application/Home/Model/User/ModuleModel.class.php | UTF-8 | 1,921 | 2.796875 | 3 | [] | no_license | <?php
namespace Home\Model\User;
use Think\Model;
/**
* 员工管理中用到的功能模块模型
* Class ModuleModel
* @package Home\Model\User
*/
class ModuleModel extends Model
{
/**
* 根据url和key查询module数量
* @param $url 请求的url
* @param $key 标识
* @return mixed 返回module数量
*/
public function getCountByUrlAndKey($url, $key)
{
$where = array('url' => $url, 'key' => $key, 'hide' => 0);
return $this->where($where)->count();
}
/**
* 根据功能标识,查询hide=0,type=1的菜单信息并按sort升序查找module
* @param array $moduleKeys 功能模块标识集合
* @return mixed
*/
public function getMenuByModuleKeys(array $moduleKeys)
{
return $this->where(array('key' => array('in', $moduleKeys), 'hide' => 0, 'type' => 1))->order('sort asc')->field('title,url,key,pid,pic')->select();
}
/**
* 根据功能模块标识集合和父标识查询菜单
* @param array $moduleKeys 功能模块标识集合
* @param $parent 父标识
* @return mixed
*/
public function getMenuByModuleKeysAndParent(array $moduleKeys, $parent)
{
$where = array('key' => array('in', $moduleKeys), 'pid' => $parent, 'hide' => 0, 'type' => 1);
return $this->where($where)->order('sort asc')->field('title,url,key')->select();
}
/**
* 根据父key查询操作信息
* @param $parent 父key
* @return mixed
*/
public function getActionsByParent($parent)
{
return $this->where(array('hide' => 0, 'pid' => $parent, 'type' => 2))->order('sort asc')->field('url,key')->select();
}
/**
* 根据key查询模块信息
* @param $key
* @return Model
*/
public function getModuleByKey($key)
{
return $this->where(array('key' => $key, 'hide' => 0))->find();
}
} | true |
b8d9623fef06728d7a3caae05a4946577a493102 | PHP | zanner-own-archive/php-zcms | /core/kernel/location/location.php | WINDOWS-1251 | 24,502 | 2.609375 | 3 | [] | no_license | <?
class Z_LOCATION
{
final static private function array_merge(&$target, $source, $flag = 0, $I = 0)
{
$__FUNCTION__ = __FUNCTION__;
if ((int)$I > 1000) throw new Exception('Location::array_merge. Is to depth (iteration = ' . $I . ').');
elseif (is_array($target) && is_array($source))
{
$return = true;
$flag_replace_by_new = ($flag < 0) ? false : true;
foreach ($source as $k => $v)
{
if (!array_key_exists($k, $target)) $target[$k] = $v;
elseif (is_array($target[$k]) && is_array($v)) $return &= self:: $__FUNCTION__($target[$k], $v, $flag, (int)$I + 1);
elseif ($flag_replace_by_new) $target[$k] = $v;
}
unset($flag_replace_by_new);
return $return;
}
return false;
}
final static public function is_id($data, $depth = 20) { return preg_match('"^ [1-9] [\d]{0,' . max(0, (int)$depth - 1) . '} $"x', (string)$data); }
final static public function is_number($data) { return preg_match('"^ [\-\+]? [1-9] [\d]* $"x', (string)$data); }
static private $KEY = array( 'root' => 0, 'method' => 1, 'domain' => 2, 'request' => 3, 'query' => 4, 'post' => 5, 'anchor' => 6 );
static private $default_data_inited = null;
static private $default_data = array();
final static private function initing_default()
{
if (self::$default_data_inited !== null) return self::$default_data_inited;
try
{
// $_SERVER
if (is_array($_SERVER));
elseif (is_array($HTTP_SERVER_VARS)) $_SERVER = &$HTTP_SERVER_VARS;
elseif (!is_array($_SERVER)) throw new Exception('Location::initing_default. SERVER not found.');
// $_POST
if (is_array($_POST));
elseif (is_array($HTTP_POST_VARS)) $_POST = &$HTTP_POST_VARS;
elseif (!is_array($_POST)) throw new Exception('Location::initing_default. POST not found.');
// root: /xxx/xxx/xx
if (isset($_SERVER['DOCUMENT_ROOT']))
{
$root = (string)$_SERVER['DOCUMENT_ROOT'];
$root = preg_replace('"[\/\\\\]"xu', '/', $root);
$root = preg_replace('" [\/]+ $"xu', '/', $root);
self::$default_data[self::$KEY['root']] = $root;
unset($root);
}
else self::$default_data[self::$KEY['root']] = '';
// method: http | https | ftp
if (isset($_SERVER['SERVER_PORT']))
{
$ports = array( 80 => 'http', 443 => 'https', 21 => 'ftp' );
$port = (int)$_SERVER['SERVER_PORT'];
$method = $ports[array_key_exists($port, $ports) ? $port : 80];
self::$default_data[self::$KEY['method']] = $method;
unset($port, $method);
}
else self::$default_data[self::$KEY['method']] = 'http';
// domain: [H+] a.b.c [H-]
if (isset($_SERVER['HTTP_HOST']))
{
$domain = (string)$_SERVER['HTTP_HOST'];
$domain = (strlen($domain) > 0) ? explode('.', $domain) : array();
self::$default_data[self::$KEY['domain']] = $domain;
unset($domain);
}
else self::$default_data[self::$KEY['domain']] = array('localhost');
// request: [R-] /x/y/z/ [R+] REQUEST_URI | REDIRECT_URL | SCRIPT_URL
if (
isset($_SERVER['REQUEST_URI']) ||
isset($_SERVER['REDIRECT_URL']) ||
isset($_SERVER['SCRIPT_URL'])
)
{
if (isset($_SERVER['REQUEST_URI'])) $request = (string)$_SERVER['REQUEST_URI'];
elseif (isset($_SERVER['REDIRECT_URL'])) $request = (string)$_SERVER['REDIRECT_URL'];
elseif (isset($_SERVER['SCRIPT_URL'])) $request = (string)$_SERVER['SCRIPT_URL'];
$request = preg_replace('" [\?] .* "xu', '', $request);
$request = preg_replace('" [\/\\\\]+ "xu', '/', $request);
$request = preg_replace('"^ [\/] "xu', '', $request);
$request = preg_replace('" [\/] $"xu', '', $request);
$request = (strlen($request) > 0) ? explode('/', $request) : array();
self::$default_data[self::$KEY['request']] = $request;
unset($request);
}
else self::$default_data[self::$KEY['request']] = array();
// query(get): ?param1=data1¶m2=data2
if (isset($_SERVER['QUERY_STRING']))
{
$query = (string)$_SERVER['QUERY_STRING'];
parse_str($query, $query);
self::$default_data[self::$KEY['query']] = $query;
unset($query);
}
else self::$default_data[self::$KEY['query']] = array();
// post: array()
self::$default_data[self::$KEY['post']] = $_POST;
// anchor: #xxx
self::$default_data[self::$KEY['anchor']] = '';
// initialization flag
self::$default_data_inited = true;
}
catch (Exception $E) { self::$default_data_inited = false; }
return self::$default_data_inited;
}
private $constant_data = null;
final public function set_root($root)
{
$root = realpath($root);
$root = preg_replace('"[\/\\\\]"xu', '/', $root);
$root = preg_replace('" [\/]+ $"xu', '/', $root);
if (is_dir($root)) $this->constant_data[self::$KEY['root']] = $root;
return true;
}
final public function set_method($method)
{
static $METHOD = array( 80 => 'http', 443 => 'https', 21 => 'ftp', 'http' => 'http', 'https' => 'https', 'ftp' => 'ftp' );
$method = (string)strtolower((string)$method);
if (array_key_exists($method, $METHOD)) $this->constant_data[self::$KEY['method']] = $METHOD[$method];
return true;
}
// flag = 0 -
// flag > 0 - ( )
// flag < 0 - ( )
final public function set_domain($domain, $flag = 0)
{
static $__FUNCTION__ = __FUNCTION__;
if (is_array($domain) && !(count(preg_grep('"^[\w\d\-\_]+$"u', $domain, PREG_GREP_INVERT)) > 0))
{
if ($flag === '?') // ,
{
if ((@count($this->constant_data[self::$KEY['domain']]) < 1) && (count($domain) > 0))
{
$domains = $domain;
array_unshift($domains, &$this->constant_data[self::$KEY['domain']]);
call_user_func_array('array_unshift', $domains);
unset($domains);
}
}
else
{
$flag = (int)$flag;
if ($flag < 0)
{
$merge = 'array_push';
$domains = array_reverse($domain, true);
}
else
{
$merge = 'array_unshift';
$domains = $domain;
if ($flag === 0) $this->constant_data[self::$KEY['domain']] = array();
}
if (count($domains) > 0)
{
array_unshift($domains, &$this->constant_data[self::$KEY['domain']]);
call_user_func_array($merge, $domains);
}
unset($merge, $domains);
}
}
elseif (is_string($domain) && preg_match('"^[\w\d\-\_\.]*$"u', $domain))
{
$domains = preg_replace('"[\s]"', '', $domain);
$domains = preg_replace('"[\.\,]"', '.', $domains);
$domains = preg_replace('"(^[\.]|[\.]$)"', '', $domains);
$domains = (strlen($domain) > 0) ? explode('.', $domains) : array();
$this->$__FUNCTION__($domains, $flag);
unset($domains);
}
else return false;
return true;
}
// flag = 0 -
// flag > 0 - ( )
// flag < 0 - ( )
final public function set_request($request, $flag = 0)
{
static $__FUNCTION__ = __FUNCTION__;
if (is_array($request) && !(count(preg_grep('"^[\w\d\-\_\.]+$"u', $request, PREG_GREP_INVERT)) > 0))
{
if ($flag === '?') // ,
{
if ((@count($this->constant_data[self::$KEY['request']]) < 1) && (count($request) > 0))
{
$requests = $request;
array_unshift($requests, &$this->constant_data[self::$KEY['request']]);
call_user_func_array('array_unshift', $requests);
unset($requests);
}
}
else
{
$flag = (int)$flag;
if ($flag > 0)
{
$merge = 'array_push';
$requests = $request; //$requests = array_reverse($request, true);
}
else
{
$merge = 'array_unshift';
$requests = $request;
if ($flag === 0) $this->constant_data[self::$KEY['request']] = array();
}
if (count($requests) > 0)
{
array_unshift($requests, &$this->constant_data[self::$KEY['request']]);
call_user_func_array($merge, $requests);
}
unset($merge, $requests);
}
}
elseif (is_string($request) && preg_match('"^[\w\d\-\_\.\/\\\\]*$"u', $request))
{
$requests = preg_replace('"[\s]"', '', $request);
$requests = preg_replace('"[\/\\\\]"', '/', $requests);
$requests = preg_replace('"(^[\/]|[\/]$)"', '', $requests);
$requests = (strlen($request) > 0) ? explode('/', $requests) : array();
$this->$__FUNCTION__($requests, $flag);
unset($requests);
}
else return false;
return true;
}
// flag = 0 -
// flag > 0 -
// flag < 0 -
final public function set_query($query, $flag = 1)
{
static $__FUNCTION__ = __FUNCTION__;
if (is_array($query))
{
if ($flag === '?') // ,
{
if ((@count($this->constant_data[self::$KEY['query']]) < 1) && (count($query) > 0))
{
self::array_merge($this->constant_data[self::$KEY['query']], $query, 1);
}
}
else
{
$flag = (int)$flag;
if ($flag < 0) self::array_merge($this->constant_data[self::$KEY['query']], $query, -1);
elseif ($flag > 0) self::array_merge($this->constant_data[self::$KEY['query']], $query, 1);
else $this->constant_data[self::$KEY['query']] = $query;
}
}
elseif (is_string($query) && (strlen($query) > 0))
{
parse_str($query, $querys);
if (is_array($querys)) $this->$__FUNCTION__($querys, $flag);
unset($querys);
}
else return false;
return true;
}
// flag = 0 -
// flag > 0 -
// flag < 0 -
final public function set_post($post, $flag = 0)
{
static $__FUNCTION__ = __FUNCTION__;
if (is_array($post))
{
if ($flag === '?') // ,
{
if ((@count($this->constant_data[self::$KEY['post']]) < 1) && (count($query) > 0))
{
self::array_merge($this->constant_data[self::$KEY['post']], $query, 1);
}
}
else
{
$flag = (int)$flag;
if ($flag < 0) self::array_merge($this->constant_data[self::$KEY['post']], $post, -1);
elseif ($flag > 0) self::array_merge($this->constant_data[self::$KEY['post']], $post, 1);
else $this->constant_data[self::$KEY['post']] = $post;
}
}
elseif (is_string($post) && (strlen($post) > 0))
{
parse_str($post, $posts);
if (is_array($posts)) $this->$__FUNCTION__($posts, $flag);
unset($posts);
}
else return false;
return true;
}
final public function set_anchor($anchor)
{
$anchor = (string)$anchor;
if (preg_match('"^[\w\d\-\_]+$"xu', $anchor)) $this->constant_data[self::$KEY['anchor']] = $anchor;
return true;
}
final public function set($set = null, $url_or_file = 'url')
{
static $__FUNCTION__ = __FUNCTION__;
static $RE = array(
'url' => '"^ (?:([\w]+)[\:][\/]{2})? ([\w\d\-\_\.]*) (?:([\w\d\-\_\.\/\\\\]+))? (?:[\?]([^\#]+))? (?:[\#](.*))? $"x',
'file' => '"^ ([\w\d\-\_\.\:\/\\\\]+) $"x'
);
switch ($url_or_file)
{
case 'url':
case 'u':
$url_or_file = 'url';
break;
case 'file':
case 'f':
$url_or_file = 'file';
break;
default: $url_or_file = 'url';
}
if (is_array($set))
{
static $SET = array(
'set_root' => array('root'),
'set_method' => array('method', 'm', 'pre'),
'set_domain' => array(
'domain', '=domain' => array(0), '+domain' => array(1), '-domain' => array(-1), '?domain' => array('?'),
'host', '=host' => array(0), '+host' => array(1), '-host' => array(-1), '-host' => array('?'),
'server', '=server' => array(0), '+server' => array(1), '-server' => array(-1), '?server' => array('?'),
'd', '=d' => array(0), '+d' => array(1), '-d' => array(-1), '?d' => array('?'),
'h', '=h' => array(0), '+h' => array(1), '-h' => array(-1), '?h' => array('?')
),
'set_request' => array(
'request', '=request' => array(0), '+request' => array(1), '-request' => array(-1), '?request' => array('?'),
'path', '=path' => array(0), '+path' => array(1), '-path' => array(-1), '?path' => array('?'),
'r', '=r' => array(0), '+r' => array(1), '-r' => array(-1), '?r' => array('?')
),
'set_query' => array(
'query', '=query' => array(0), '+query' => array(1), '-query' => array(-1), '?query' => array('?'),
'get', '=get' => array(0), '+get' => array(1), '-get' => array(-1), '?get' => array('?'),
'search', '=search' => array(0), '+search' => array(1), '-search' => array(-1), '?search' => array('?'),
'q', '=q' => array(0), '+q' => array(1), '-q' => array(-1), '?q' => array('?'),
'g', '=g' => array(0), '+g' => array(1), '-g' => array(-1), '?g' => array('?')
),
'set_post' => array(
'post', '=post' => array(0), '+post' => array(1), '-post' => array(-1), '?post' => array('?'),
'p', '=p' => array(0), '+p' => array(1), '-p' => array(-1), '?p' => array('?')
),
'set_anchor' => array('anchor', 'a')
);
$set = array_change_key_case($set, CASE_LOWER);
foreach ($SET as $call => $keys)
{
if (!$call) throw new Exception('Location->set. Wrong call.');
if (!is_array($keys)) throw new Exception('Location->set. Wrong keys.');
foreach ($keys as $key => $value)
{
if (is_string($value))
{
if (!array_key_exists($value, $set)) continue;
call_user_func_array(array($this, $call), array($set[$value]));
break;
}
elseif (is_array($value))
{
if (!array_key_exists($key, $set)) continue;
array_unshift($value, $set[$key]);
call_user_func_array(array($this, $call), $value);
break;
}
}
}
}
/*
elseif (is_string($set))
{
$sets = parse_url($set, PHP_URL_SCHEME | PHP_URL_HOST | PHP_URL_PORT | PHP_URL_USER | PHP_URL_PASS | PHP_URL_PATH | PHP_URL_QUERY | PHP_URL_FRAGMENT);
$sets = array('method' => $sets['scheme'], 'user' => $sets['user'], 'password' => $sets['pass'], 'domain' => $sets['host'], 'request' => $sets['path'], 'query' => $sets['query'], 'anchor' => $sets['fragment']);
$this->$__FUNCTION__($sets);
}
*/
elseif (is_string($set) && preg_match($RE[$url_or_file], $set, $sets))
{
if ($url_or_file === 'url')
{
$method = isset($sets[1]) ? $sets[1] : '';
$domain = isset($sets[3]) ? $sets[2] : '';
$request = isset($sets[3]) ? $sets[3] : '';
$query = isset($sets[4]) ? $sets[4] : '';
$anchor = isset($sets[5]) ? $sets[5] : '';
$sets = array('method' => $method, 'domain' => $domain, 'request' => $request, 'query' => $query, 'anchor' => $anchor);
$this->$__FUNCTION__($sets);
}
elseif ($url_or_file === 'file')
{
$request = isset($sets[1]) ? $sets[1] : '';
$sets = array('request' => $request);
$this->$__FUNCTION__($sets);
}
else return false;
}
else return false;
return true;
}
final public function get_root() { return $this->constant_data[self::$KEY['root']]; }
final public function get_method() { return $this->constant_data[self::$KEY['method']]; }
final public function get_domain($join = false) { $d = &$this->constant_data[self::$KEY['domain']]; return ($flag === true) ? join('.', $d) : $d; }
final public function get_request($join = false) { $r = &$this->constant_data[self::$KEY['request']]; return ($flag === true) ? join('.', $r) : $r; }
final public function get_query($join = false) { }
final public function get_post($join = false) { }
final public function get_anchor() { return $this->constant_data[self::$KEY['anchor']]; }
final public function get($join = false) {
$return = array();
foreach ($this->constant_data as $key => $value)
{
$call = sprintf('get_%s', $key);
$return[$key] = $this->$call($join);
}
return $return;
}
final public function href($href = null)
{
$backup = $this->constant_data;
$this->set($href, 'url');
$set = &$this->constant_data;
$method = (strlen($set[self::$KEY['method']]) > 0) ? sprintf('%s://', $set[self::$KEY['method']]) : '';
$domain = (is_array($set[self::$KEY['domain']]) && (count($set[self::$KEY['domain']]) > 0)) ? join('.', $set[self::$KEY['domain']]) : '';
$request = (is_array($set[self::$KEY['request']]) && (count($set[self::$KEY['request']]) > 0)) ? sprintf('/%s', join('/', $set[self::$KEY['request']])) : '/';
$query = (is_array($set[self::$KEY['query']]) && (count($set[self::$KEY['query']]) > 0)) ? sprintf('?%s', http_build_query($set[self::$KEY['query']])) : '';
$anchor = (strlen($set[self::$KEY['anchor']]) > 0) ? sprintf('#%s', $set[self::$KEY['anchor']]) : '';
$return = sprintf('%s%s%s%s%s', $method, $domain, $request, $query, $anchor);
$this->constant_data = $backup;
unset($backup, $set, $method, $domain, $request, $query, $anchor);
return $return;
}
final public function file($file = null, $absolute = true)
{
$backup = $this->constant_data;
$this->set($file, 'file');
$set = &$this->constant_data;
$root = (strlen($set[self::$KEY['root']]) > 0) ? sprintf('%s', $set[self::$KEY['root']]) : '';
$request = (is_array($set[self::$KEY['request']]) && (count($set[self::$KEY['request']]) > 0)) ? sprintf('/%s', join('/', $set[self::$KEY['request']])) : '/';
switch ($absolute)
{
case true: $return = sprintf('%s%s', $root, $request); break;
case false: case '': $return = preg_replace('"^ [\/]"x', '', $request); break;
case '/': $return = $request; break;
default: $return = sprintf('%s%s', $root, $request);
}
$this->constant_data = $backup;
unset($backup, $set, $root, $request);
return $return;
}
final static public function init($set = null) { $C = __CLASS__; return new $C($set); }
final public function __construct($set = null) { self::initing_default(); $this->constant_data = self::$default_data; $this->set($set, 'url'); }
final public function __destruct() { }
final public function __clone() { self::initing_default(); }
final public function __sleep() { return array('constant_data'); }
final public function __wakeup() { self::initing_default(); }
final public function __toString() { return $this->href(); }
final public function root() { return $this->constant_data[self::$KEY['root']]; }
final public function method() { return $this->constant_data[self::$KEY['method']]; }
final public function domain($index = null, $else = null)
{
$domain = &$this->constant_data[self::$KEY['domain']];
$count = count($domain);
if ($index === null) return $domain;
elseif (!is_array($domain) || !($count > 0)) throw new Exception('Location->domain. Wrong constant_data.');
elseif ($index === 'first') return $domain[count($domain)];
elseif ($index === 'last') return $domain[0];
elseif (array_key_exists($index, $domain)) return $domain[$index];
elseif ($else === null) throw new Exception('Location->domain. Unknown index [' . $index . '].');
else return $else;
}
final public function d($index = null, $else = null) { return $this->domain($index, $else); }
final public function domains() { return join('.', $this->domain()); }
final public function dd() { return $this->domains(); }
final public function request($index = null, $else = null)
{
$request = &$this->constant_data[self::$KEY['request']];
$count = count($request);
if ($index === null) return $request;
elseif (!is_array($request) || !($count > 0)) throw new Exception('Location->request. Wrong constant_data.');
elseif ($index === 'first') return $request[0];
elseif ($index === 'last') return $request[count($request)];
elseif (array_key_exists($index, $request)) return $request[$index];
elseif ($else === null) throw new Exception('Location->request. Unknown index [' . $index . '].');
else return $else;
}
final public function r($index = null, $else = null) { return $this->request($index, $else); }
final public function rId($index = null, $else = 0)
{
try { $data = $this->request(&$index, &$else); return self::is_id(&$data) ? $data : $else; }
catch (Exception $e) { return $else; }
}
final public function rI($index = null, $else = 0)
{
try { $data = $this->request(&$index, &$else); return self::is_number(&$data) ? $data : $else; }
catch (Exception $e) { return $else; }
}
final public function rN($index = null, $else = 0)
{
try { $data = $this->request(&$index, &$else); return self::is_number(&$data) ? $data : $else; }
catch (Exception $e) { return $else; }
}
final public function rS($index = null, $else = '')
{
try { $data = $this->request(&$index, &$else); return is_string($data) ? $data : $else; }
catch (Exception $e) { return $else; }
}
final public function requests() { return join('/', $this->request()); }
final public function rr() { return $this->requests(); }
final public function query($index = null, $else = null)
{
$query = &$this->constant_data[self::$KEY['query']];
if ($index === null) return $query;
elseif (!is_array($query) || !(count($query) > 0)) throw new Exception('Location->query. Wrong constant_data.');
elseif (is_array($index))
{
foreach ($index as $i)
{
if (is_array($query) && array_key_exists($i, $query)) $query = &$query[$i];
elseif ($else === null) throw new Exception('Location->query. Unknown index [' . join('.', $index) . '].');
else return $else;
}
return $query;
}
elseif (!array_key_exists($index, $query)) return $query[$index];
elseif ($else === null) throw new Exception('Location->query. Unknown index [' . $index . '].');
else return $else;
}
final public function q($index = null, $else = null) { return $this->query($index, $else); }
final public function qId($index = null, $else = 0)
{
try { $data = $this->query(&$index, &$else); return self::is_id(&$data) ? $data : $else; }
catch (Exception $e) { return $else; }
}
final public function qI($index = null, $else = 0)
{
try { $data = $this->query(&$index, &$else); return self::is_number(&$data) ? $data : $else; }
catch (Exception $e) { return $else; }
}
final public function qN($index = null, $else = 0)
{
try { $data = $this->query(&$index, &$else); return self::is_number(&$data) ? $data : $else; }
catch (Exception $e) { return $else; }
}
final public function qS($index = null, $else = '')
{
try { $data = $this->query(&$index, &$else); return is_string($data) ? $data : $else; }
catch (Exception $e) { return $else; }
}
final public function querys() { return http_build_query($this->query()); }
final public function qq() { return $this->querys(); }
final public function post($index = null, $else = null)
{
$post = &$this->constant_data[self::$KEY['post']];
if ($index === null) return $post;
elseif (!is_array($post) || !(count($query) > 0)) throw new Exception('Location->post. Wrong constant_data.');
elseif (is_array($index))
{
foreach ($index as $i)
{
if (is_array($post) && array_key_exists($i, $post)) $post = &$post[$i];
elseif ($else === null) throw new Exception('Location->post. Unknown index [' . join('.', $index) . '].');
else return $else;
}
return $post;
}
elseif (array_key_exists($index, $post)) return $post[$index];
elseif ($else === null) throw new Exception('Location->post. Unknown index [' . $index . '].');
else return $else;
}
final public function p($index = null, $else = null) { return $this->post($index, $else); }
final public function pId($index = null, $else = 0)
{
try { $data = $this->post(&$index, &$else); return self::is_id(&$data) ? $data : $else; }
catch (Exception $e) { return $else; }
}
final public function pI($index = null, $else = 0)
{
try { $data = $this->post(&$index, &$else); return self::is_number(&$data) ? $data : $else; }
catch (Exception $e) { return $else; }
}
final public function pN($index = null, $else = 0)
{
try { $data = $this->post(&$index, &$else); return self::is_number(&$data) ? $data : $else; }
catch (Exception $e) { return $else; }
}
final public function pS($index = null, $else = '')
{
try { $data = $this->post(&$index, &$else); return is_string($data) ? $data : $else; }
catch (Exception $e) { return $else; }
}
final public function posts() { return http_build_query($this->post()); }
final public function pp() { return $this->posts(); }
final public function anchor() { return $this->constant_data[self::$KEY['anchor']]; }
}
?> | true |
1063fce918b78ec2e6c2187d6a76fa44c8878500 | PHP | ManniManfred/liga-manager | /Backend/services/upload.php | UTF-8 | 637 | 2.921875 | 3 | [] | no_license | <?php
require_once("config.php");
foreach ($_FILES as $key => $file)
{
if ($file["error"] > 0)
{
echo "Return Code: " . $file["error"] . "<br />";
}
else
{
echo "Upload: " . $file["name"] . "<br />";
echo "Type: " . $file["type"] . "<br />";
echo "Size: " . ($file["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $file["tmp_name"] . "<br />";
if (!is_dir($_ENV["upload_folder"])) {
mkdir($_ENV["upload_folder"]);
}
move_uploaded_file($file["tmp_name"], $_ENV["upload_folder"] . $file["name"]);
echo "Stored in: " . $_ENV["upload_folder"] . $file["name"];
}
}
?> | true |
a8846feb1e1c3ae4d498f6143d29dc25b5628257 | PHP | yosuagrs/belajar-php-fungsi-dan-variabel-.-dasar-php | /variabel fungsi dan jenis pemanggilannya.php | UTF-8 | 1,667 | 3.84375 | 4 | [] | no_license | <!-- bagian ini akan menjelaskan mengenai variable-->
<!-- php berada di dalam <?php ?> -->
<?php
// ini adalah comment dimana ini tidak akan dibaca oleh kodde
// hal pertama yang perlu di ketahui adalah membuat variabel, menggunakan $
$name = "hello";
//variabel pada php tidak perlu diberikan tipe data, untuk menyimpan data bentuk angka tidak menggunakan petik dua ""
echo $name;
//memanggil variabel ke layar menggunakan echo sehingga di browser akan mengeluarkan isi dari variabel
?>
<br><br><br>
<!-- bagian ini akan menjelaskan mengenai fungsi-->
<?php
// untuk membuat fungsi dimulai dengan kata function kemudian nama fungsi
function penjumlahan(){
$b = 2;
$c = 3;
$a = $b + $c;
//return adalah hasil dari fungsi
return $a;
}
//pemanggilan fungsi tidak ada input karena input sudah diberikan di dalam fungsi
echo penjumlahan();
?>
<br><br><br>
<?php
//fungsi ini memerlukan 2 variabel untuk memanggilnya
function penjumlahan2($b,$c){
$a = $b + $c;
return $a;
}
//pemanggilan fungsi yang meminta variabel yaitu $b dan $c diatas
echo penjumlahan2(6,3);
?>
<br><br><br>
<!-- bagian ini akan menjelaskan mengenai fungsi yang tidak ada return (ddisebut prosedur)-->
<?php
//fungsi ini memerlukan 2 variabel untuk memanggilnya
function prosedur($b,$c){
$a = $b + $c;
// tidak adda return pada fungsi ini karena langsung melakukan echo (langsung ditampilkan ke layar)
echo $a;
}
//karena pada fungsi sudah ada pemanggilan ke layar maka tidak perlu dilakukan echo untuk memanggil fungsi
prosedur(10,11);
?> | true |
bf7f2df93821a06de621728621dbc538e932aae3 | PHP | wirtsi/Bancha | /_Model/Movie.php | UTF-8 | 810 | 2.53125 | 3 | [
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] | permissive | <?php
class Movie extends AppModel {
var $name = 'Movie';
var $validate = array(
'director_id' => array('numeric'=>array('rule'=>'numeric','message'=>'Invalid director')),
'name' => array('notempty'),
'year' => array('numeric'=>array('rule'=>'numeric','message'=>'Must be a year'))
);
//The Associations below have been created with all possible keys, those that are not needed can be removed
var $belongsTo = array(
'Director' => array(
'className' => 'Director',
'foreignKey' => 'director_id',
)
);
var $hasAndBelongsToMany = array(
'Actor' => array(
'className' => 'Actor',
'joinTable' => 'movies_actors',
'foreignKey' => 'movie_id',
'associationForeignKey' => 'actor_id',
'unique' => true,
)
);
var $actsAs = array(
"Bancha.BanchaRemotable"
);
}
?> | true |
62c364ff1aeb7a8dbcdd04ef901ca836d60d0cf9 | PHP | decodelabs/glitch | /src/Glitch/Dumper/Inspect/Ds.php | UTF-8 | 1,375 | 2.65625 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | <?php
/**
* @package Glitch
* @license http://opensource.org/licenses/MIT
*/
declare(strict_types=1);
namespace DecodeLabs\Glitch\Dumper\Inspect;
use DecodeLabs\Glitch\Dumper\Entity;
use DecodeLabs\Glitch\Dumper\Inspector;
use Ds\Collection;
use Ds\Pair;
use Ds\Set;
class Ds
{
/**
* Inspect Collection
*
* @param Collection<int|string, mixed> $collection
*/
public static function inspectCollection(
Collection $collection,
Entity $entity,
Inspector $inspector
): void {
$entity
->setLength(count($collection))
->setValues($inspector->inspectList($collection->toArray()));
}
/**
* Inspect Pair
*
* @param Pair<int|string, mixed> $pair
*/
public static function inspectPair(
Pair $pair,
Entity $entity,
Inspector $inspector
): void {
$entity
->setProperties($inspector->inspectList($pair->toArray()));
}
/**
* Inspect Set
*
* @param Set<mixed> $set
*/
public static function inspectSet(
Set $set,
Entity $entity,
Inspector $inspector
): void {
$entity
->setLength(count($set))
->setMeta('capacity', $inspector($set->capacity()))
->setValues($inspector->inspectList($set->toArray()));
}
}
| true |
7281eb5cde9ef00e1d231aa9dfaa588543875f60 | PHP | kirubha7/cloudwatch-logs-laravel | /src/Cloudwatchlogs.php | UTF-8 | 7,907 | 2.796875 | 3 | [
"MIT"
] | permissive | <?php
namespace kirubha7\CloudwatchLogsLaravel;
use Aws\CloudWatchLogs\CloudWatchLogsClient;
class Cloudwatchlogs{
/***Description */
const DESCRIPTION = 'Cloudwatch Logs Laravel';
/**Version */
const VERSION = 'v1.0';
/**AWS clinet SDK params*/
private $client;
/**Success Status */
const SUCCESS = true;
/**Failure Status */
const FAIL = false;
/**Construct function*/
function __construct(CloudWatchLogsClient $client)
{
$this->client = $client;
}
public static function ping() : bool
{
return self::SUCCESS;
}
public function putLog(string $groupName,string $streamName,string $retention = '14',array $context = [],array $tags = []) : array
{
try{
//Check and create log group
$this->createLogGroup($groupName);
//Check and create log stream
$this->createLogStream($groupName,$streamName);
$nextToken = null;
//Get Log Stream Details
$sequence_token = $this->getDescribeLogStream($groupName,$streamName);
if(count($sequence_token) > 0 &&
isset($sequence_token['logStreams'][0]['uploadSequenceToken']) &&
!empty($sequence_token['logStreams'][0]['uploadSequenceToken'])){
$nextToken = $sequence_token['logStreams'][0]['uploadSequenceToken'];
}
//Send Logs to Cloudwatch
$timestamp = floor(microtime(true) * 1000);
$context = json_encode($context);
$datas = [
'logEvents' => [ // REQUIRED
[
'message' => $context, // REQUIRED
'timestamp' => $timestamp, // REQUIRED
],
],
'logGroupName' => $groupName, // REQUIRED
'logStreamName' => $streamName, // REQUIRED
'sequenceToken' => $nextToken
];
/**If sequence token is not present no need to pass */
if($datas['sequenceToken'] == null){
unset($datas['sequenceToken']);
}
$this->client->putLogEvents($datas);
return ['status' => self::SUCCESS ,'message' => 'Log sended successfully'];
}catch(\Aws\Exception\AwsException $e){
return ['status' => self::FAIL ,'error' => $e->getAwsErrorMessage()];
}catch(\Exception $e){
return ['status' => self::FAIL ,'error' => $e->getMessage()];
}
}
/**
* URL: https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-logs-2014-03-28.html#createloggroup
* Description: Craete Log Group by given name by calling create log group api call*/
public function createLogGroup(string $groupName,array $tags = []) :array
{
try{
$check = $this->checkLogGroupExists($groupName);
/**Check if log group already exists or not.
* Incase if log group is not present we need to create log group
* Incase if log group is present no need to call log group api call.
* */
if(isset($check['status']) &&
$check['status'] == self::FAIL &&
$check['error'] == 'Log Group Not Exists'){
$this->client->createLogGroup([
'logGroupName' => $groupName, // REQUIRED
]);
}
return ['status' => self::SUCCESS ,'message' => 'Log Group Created Successfully'];
}catch(\Aws\Exception\AwsException $e){
return ['status' => self::FAIL ,'error' => $e->getAwsErrorMessage()];
}catch(\Exception $e){
return ['status' => self::FAIL ,'error' => $e->getMessage()];
}
}
/**
* URL: https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-logs-2014-03-28.html#describeloggroups
* Desciption : Check log group name by given name by calling describe log group api call*/
public function checkLogGroupExists(string $groupName) : array
{
try{
$result = $this->client->describeLogGroups([
' logGroupNamePrefix' => $groupName
])
->get('logGroups');
//Check if any log groups is present or not
if(count($result) > 0){
$groupNames = array_column($result,'logGroupName');
if(in_array($groupName,$groupNames)){
return ['status' => self::SUCCESS ,'message' => 'Log Group Exists'];
}else{
return ['status' => self::FAIL ,'error' => 'Log Group Not Exists'];
}
}else{
return ['status' => self::FAIL ,'error' => 'Log Group Not Exists'];
}
}catch(\AWS\Exception\AwsException $e){
return ['status' => self::FAIL ,'error' => $e->getAwsErrorMessage()];
}catch(\Exception $e){
return ['status' => self::FAIL ,'error' => $e->getMessage()];
}
}
public function checkLogStreamExists($groupName,$streamName) : array
{
try{
$result = $this->getDescribeLogStream($groupName,$streamName);
//Check if any log stream is present or not
if(isset($result['logStreams']) && count($result['logStreams']) > 0){
$streamNames = array_column($result['logStreams'],'logStreamName');
if(in_array($streamName,$streamNames)){
return ['status' => self::SUCCESS ,'message' => 'Log Stream Exists'];
}else{
return ['status' => self::FAIL ,'error' => 'Log Stream Not Exists'];
}
}else{
return ['status' => self::FAIL ,'error' => 'Log Stream Not Exists'];
}
}catch(\AWS\Exception\AwsException $e){
return ['status' => self::FAIL ,'error' => $e->getAwsErrorMessage()];
}catch(\Exception $e){
return ['status' => self::FAIL ,'error' => $e->getMessage()];
}
}
/**
* URL: https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-logs-2014-03-28.html#describelogstreams
* Description: Check log stream is present in given group by calling describe log stream api call */
public function getDescribeLogStream($groupName,$streamName)
{
try{
$response = [];
$result = $this->client->describeLogStreams([
'logGroupName' => $groupName,
'logStreamNamePrefix' => $streamName
]);
$response = $result->toArray();
return $response;
}catch(\Aws\Exception\AwsException $e){
return ['status' => self::FAIL ,'error' => $e->getAwsErrorMessage()];
}catch(\Exception $e){
return ['status' => self::FAIL ,'error' => $e->getMessage()];
}
}
/**
* URL: https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-logs-2014-03-28.html#createlogstream
* Description: Create Log Stream by given name by calling create log stream apiaa*/
public function createLogStream($groupName,$streamName) :array
{
try{
$check = $this->checkLogStreamExists($groupName,$streamName);
//Call CreateLogStream API
if(isset($check['status']) &&
$check['status'] == self::FAIL &&
$check['error'] == 'Log Stream Not Exists'){
$this->client->createLogStream([
'logGroupName' => $groupName,
'logStreamName' => $streamName,
]);
}
return ['status' => self::SUCCESS ,'message' => 'Log Stream Created Successfully'];
}catch(\Aws\Exception\AwsException $e){
return ['status' => self::FAIL ,'error' => $e->getAwsErrorMessage()];
}catch(\Exception $e){
return ['status' => self::FAIL ,'error' => $e->getMessage()];
}
}
}
?> | true |
446d709c449b47c19ce473f4641925ade5c96663 | PHP | async-aws/aws | /src/Service/CognitoIdentityProvider/src/Input/AdminConfirmSignUpRequest.php | UTF-8 | 5,497 | 2.609375 | 3 | [
"MIT"
] | permissive | <?php
namespace AsyncAws\CognitoIdentityProvider\Input;
use AsyncAws\Core\Exception\InvalidArgument;
use AsyncAws\Core\Input;
use AsyncAws\Core\Request;
use AsyncAws\Core\Stream\StreamFactory;
/**
* Confirm a user's registration as a user pool administrator.
*/
final class AdminConfirmSignUpRequest extends Input
{
/**
* The user pool ID for which you want to confirm user registration.
*
* @required
*
* @var string|null
*/
private $userPoolId;
/**
* The user name for which you want to confirm user registration.
*
* @required
*
* @var string|null
*/
private $username;
/**
* A map of custom key-value pairs that you can provide as input for any custom workflows that this action triggers.
*
* If your user pool configuration includes triggers, the AdminConfirmSignUp API action invokes the Lambda function that
* is specified for the *post confirmation* trigger. When Amazon Cognito invokes this function, it passes a JSON
* payload, which the function receives as input. In this payload, the `clientMetadata` attribute provides the data that
* you assigned to the ClientMetadata parameter in your AdminConfirmSignUp request. In your function code in Lambda, you
* can process the ClientMetadata value to enhance your workflow for your specific needs.
*
* For more information, see Customizing user pool Workflows with Lambda Triggers [^1] in the *Amazon Cognito Developer
* Guide*.
*
* > When you use the ClientMetadata parameter, remember that Amazon Cognito won't do the following:
* >
* > - Store the ClientMetadata value. This data is available only to Lambda triggers that are assigned to a user pool
* > to support custom workflows. If your user pool configuration doesn't include triggers, the ClientMetadata
* > parameter serves no purpose.
* > - Validate the ClientMetadata value.
* > - Encrypt the ClientMetadata value. Don't use Amazon Cognito to provide sensitive information.
* >
*
* [^1]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html
*
* @var array<string, string>|null
*/
private $clientMetadata;
/**
* @param array{
* UserPoolId?: string,
* Username?: string,
* ClientMetadata?: null|array<string, string>,
* '@region'?: string|null,
* } $input
*/
public function __construct(array $input = [])
{
$this->userPoolId = $input['UserPoolId'] ?? null;
$this->username = $input['Username'] ?? null;
$this->clientMetadata = $input['ClientMetadata'] ?? null;
parent::__construct($input);
}
/**
* @param array{
* UserPoolId?: string,
* Username?: string,
* ClientMetadata?: null|array<string, string>,
* '@region'?: string|null,
* }|AdminConfirmSignUpRequest $input
*/
public static function create($input): self
{
return $input instanceof self ? $input : new self($input);
}
/**
* @return array<string, string>
*/
public function getClientMetadata(): array
{
return $this->clientMetadata ?? [];
}
public function getUserPoolId(): ?string
{
return $this->userPoolId;
}
public function getUsername(): ?string
{
return $this->username;
}
/**
* @internal
*/
public function request(): Request
{
// Prepare headers
$headers = [
'Content-Type' => 'application/x-amz-json-1.1',
'X-Amz-Target' => 'AWSCognitoIdentityProviderService.AdminConfirmSignUp',
];
// Prepare query
$query = [];
// Prepare URI
$uriString = '/';
// Prepare Body
$bodyPayload = $this->requestBody();
$body = empty($bodyPayload) ? '{}' : json_encode($bodyPayload, 4194304);
// Return the Request
return new Request('POST', $uriString, $query, $headers, StreamFactory::create($body));
}
/**
* @param array<string, string> $value
*/
public function setClientMetadata(array $value): self
{
$this->clientMetadata = $value;
return $this;
}
public function setUserPoolId(?string $value): self
{
$this->userPoolId = $value;
return $this;
}
public function setUsername(?string $value): self
{
$this->username = $value;
return $this;
}
private function requestBody(): array
{
$payload = [];
if (null === $v = $this->userPoolId) {
throw new InvalidArgument(sprintf('Missing parameter "UserPoolId" for "%s". The value cannot be null.', __CLASS__));
}
$payload['UserPoolId'] = $v;
if (null === $v = $this->username) {
throw new InvalidArgument(sprintf('Missing parameter "Username" for "%s". The value cannot be null.', __CLASS__));
}
$payload['Username'] = $v;
if (null !== $v = $this->clientMetadata) {
if (empty($v)) {
$payload['ClientMetadata'] = new \stdClass();
} else {
$payload['ClientMetadata'] = [];
foreach ($v as $name => $mv) {
$payload['ClientMetadata'][$name] = $mv;
}
}
}
return $payload;
}
}
| true |
32edeffb2e0883d37504dc3c4eebfce5e4dc0c74 | PHP | davidyuan7536/FFM | /site/admin/pictures-upload.php | UTF-8 | 9,180 | 2.625 | 3 | [] | no_license | <?php
ini_set("html_errors", "0");
if (!isset($_FILES["Filedata"]) || !is_uploaded_file($_FILES["Filedata"]["tmp_name"]) || $_FILES["Filedata"]["error"] != 0) {
echo getErrorJSON('Invalid upload');
exit(0);
}
require_once "../global.php";
$tempFile = $_FILES["Filedata"]["tmp_name"];
$info = pathinfo($_FILES['Filedata']['name']);
$filename = basename($_FILES['Filedata']['name'], '.' . $info['extension']);
$size = getimagesize($tempFile);
list($imageWidth, $imageHeight, $IMG_TYPE) = $size;
switch ($IMG_TYPE) {
case IMG_GIF:
$image = imagecreatefromgif($tempFile);
break;
case IMG_JPG:
$image = imagecreatefromjpeg($tempFile);
break;
case IMG_PNG:
$image = imagecreatefrompng($tempFile);
break;
default:
echo getErrorJSON('Unexpected file format');
exit(0);
}
require_once "Db/DbArticles.php";
$dbArticles = new DbArticles();
$article = $dbArticles->getArticleById($_GET['id']);
$time = strtotime($article['date']);
$year = date('Y', $time);
$month = date('m', $time);
require_once "Db/DbPictures.php";
$dbPictures = new DbPictures();
$picture = $dbPictures->getPictureByName($year, $month, $filename);
if (!empty($picture)) {
echo getErrorJSON("The file {$filename} exists");
exit(0);
}
$dir_year = __FFM_PICTURES__ . "{$year}";
$dir = $dir_year . "/{$month}";
if (!is_dir($dir_year)) {
mkdir($dir_year);
}
if (!is_dir($dir)) {
mkdir($dir);
}
$squareThumbnail = mega_crop($filename, $image, $size, 150, 150, $dir, 90);
$mediumImage = image_resize($filename, $image, $size, 300, 300, false, true, $dir, 95);
$originalImage = image_resize($filename, $image, $size, 400, 500, false, false, $dir, 95);
if (!$originalImage) {
if ($IMG_TYPE == IMG_JPG) {
move_uploaded_file($_FILES['Filedata']['tmp_name'], "{$dir}/{$filename}.jpg");
$originalImage = array(
'width' => $imageWidth,
'height' => $imageHeight,
'filename' => "{$filename}.jpg"
);
} else {
$originalImage = save_image("{$dir}/{$filename}.jpg", $image, $imageWidth, $imageHeight, 95);
}
}
imagedestroy($image);
$data = array(
'picture_filename' => $filename,
'picture_type' => 'image/jpeg',
'picture_year' => $year,
'picture_month' => $month,
'o_filename' => $originalImage['filename'],
'o_width' => $originalImage['width'],
'o_height' => $originalImage['height'],
'm_filename' => '',
's_filename' => $squareThumbnail['filename'],
'article_id' => $article['article_id']
);
if ($mediumImage) {
$data['m_filename'] = $mediumImage['filename'];
$data['m_width'] = $mediumImage['width'];
$data['m_height'] = $mediumImage['height'];
}
$pictureId = $dbPictures->newPicture($data);
echo json_encode(array(
'status' => 'OK'
));
/**
* @param $destfilename
* @param $image
* @param $dst_w
* @param $dst_h
* @param $jpeg_quality
* @return
*/
function save_image($destfilename, &$image, $dst_w, $dst_h, $jpeg_quality) {
imagejpeg($image, $destfilename, $jpeg_quality);
// Set correct file permissions
$stat = stat(dirname($destfilename));
$perms = $stat['mode'] & 0000666; //same permissions as parent folder, strip off the executable bits
@ chmod($destfilename, $perms);
return array(
'width' => $dst_w,
'height' => $dst_h,
'filename' => basename($destfilename)
);
}
/**
* @param $name
* @param $image
* @param $size
* @param $dest_w
* @param $dest_h
* @param $dir
* @param int $jpeg_quality
* @return
*/
function mega_crop($name, &$image, $size, $dest_w, $dest_h, $dir, $jpeg_quality = 90) {
list($orig_w, $orig_h, $orig_type) = $size;
$ratio_orig = $orig_w / $orig_h;
if ($dest_w / $dest_h > $ratio_orig) {
$dst_h = $dest_w / $ratio_orig;
$dst_w = $dest_w;
} else {
$dst_w = $dest_h * $ratio_orig;
$dst_h = $dest_h;
}
$src_x = floor(($dst_w - $dest_w) / 2);
$src_y = floor(($dst_h - $dest_h) / 2);
$process = wp_imagecreatetruecolor($dst_w, $dst_h);
imagecopyresampled($process, $image, 0, 0, 0, 0, $dst_w, $dst_h, $orig_w, $orig_h);
$newimage = wp_imagecreatetruecolor($dest_w, $dest_h);
imagecopyresampled($newimage, $process, 0, 0, $src_x, $src_y, $dest_w, $dest_h, $dest_w, $dest_h);
imagedestroy($process);
// convert from full colors to index colors, like original PNG.
if (IMAGETYPE_PNG == $orig_type && !imageistruecolor($image))
imagetruecolortopalette($newimage, false, imagecolorstotal($image));
$destfilename = "{$dir}/{$name}-{$dest_w}x{$dest_h}.jpg";
return save_image($destfilename, $newimage, $dest_w, $dest_h, $jpeg_quality);
}
/**
* @param $name
* @param $image
* @param $size
* @param $max_w
* @param $max_h
* @param bool $crop
* @param $is_suffix
* @param $dir
* @param int $jpeg_quality
* @return bool
*/
function image_resize($name, &$image, $size, $max_w, $max_h, $crop = false, $is_suffix, $dir, $jpeg_quality = 90) {
list($orig_w, $orig_h, $orig_type) = $size;
$dims = image_resize_dimensions($orig_w, $orig_h, $max_w, $max_h, $crop);
if (!$dims)
return $dims;
list($dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) = $dims;
$newimage = wp_imagecreatetruecolor($dst_w, $dst_h);
imagecopyresampled($newimage, $image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
// convert from full colors to index colors, like original PNG.
if (IMAGETYPE_PNG == $orig_type && !imageistruecolor($image))
imagetruecolortopalette($newimage, false, imagecolorstotal($image));
// $suffix will be appended to the destination filename, just before the extension
if ($is_suffix)
$suffix = "-{$dst_w}x{$dst_h}";
$destfilename = "{$dir}/{$name}{$suffix}.jpg";
return save_image($destfilename, $newimage, $dst_w, $dst_h, $jpeg_quality);
}
/**
* @param $orig_w
* @param $orig_h
* @param $dest_w
* @param $dest_h
* @param bool $crop
* @return bool
*/
function image_resize_dimensions($orig_w, $orig_h, $dest_w, $dest_h, $crop = false) {
if ($orig_w <= 0 || $orig_h <= 0)
return false;
// at least one of dest_w or dest_h must be specific
if ($dest_w <= 0 && $dest_h <= 0)
return false;
if ($crop) {
// crop the largest possible portion of the original image that we can size to $dest_w x $dest_h
$aspect_ratio = $orig_w / $orig_h;
$new_w = min($dest_w, $orig_w);
$new_h = min($dest_h, $orig_h);
if (!$new_w) {
$new_w = intval($new_h * $aspect_ratio);
}
if (!$new_h) {
$new_h = intval($new_w / $aspect_ratio);
}
$size_ratio = max($new_w / $orig_w, $new_h / $orig_h);
$crop_w = round($new_w / $size_ratio);
$crop_h = round($new_h / $size_ratio);
$s_x = floor(($orig_w - $crop_w) / 2);
$s_y = floor(($orig_h - $crop_h) / 2);
} else {
// don't crop, just resize using $dest_w x $dest_h as a maximum bounding box
$crop_w = $orig_w;
$crop_h = $orig_h;
$s_x = 0;
$s_y = 0;
list($new_w, $new_h) = wp_constrain_dimensions($orig_w, $orig_h, $dest_w, $dest_h);
}
// if the resulting image would be the same size or larger we don't want to resize it
if ($new_w >= $orig_w && $new_h >= $orig_h)
return false;
// the return array matches the parameters to imagecopyresampled()
// int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h
return array(0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h);
}
/**
* @param $current_width
* @param $current_height
* @param int $max_width
* @param int $max_height
* @return
*/
function wp_constrain_dimensions($current_width, $current_height, $max_width = 0, $max_height = 0) {
if (!$max_width and !$max_height)
return array($current_width, $current_height);
$width_ratio = $height_ratio = 1.0;
if ($max_width > 0 && $current_width > 0 && $current_width > $max_width)
$width_ratio = $max_width / $current_width;
if ($max_height > 0 && $current_height > 0 && $current_height > $max_height)
$height_ratio = $max_height / $current_height;
// the smaller ratio is the one we need to fit it to the constraining box
$ratio = min($width_ratio, $height_ratio);
return array(intval($current_width * $ratio), intval($current_height * $ratio));
}
/**
* @param $width
* @param $height
* @return resource
*/
function wp_imagecreatetruecolor($width, $height) {
$img = imagecreatetruecolor($width, $height);
if (is_resource($img) && function_exists('imagealphablending') && function_exists('imagesavealpha')) {
imagealphablending($img, false);
imagesavealpha($img, true);
}
return $img;
}
/**
* @param $message
* @return string
*/
function getErrorJSON($message) {
$result = array(
'status' => 'error',
'message' => $message
);
return json_encode($result);
}
?> | true |
be495ffeed7cdc3367cead9caceacc2f6be32bfc | PHP | spooner77/dream-cms | /module/Application/src/Application/Utility/ApplicationDisableSite.php | UTF-8 | 1,729 | 2.640625 | 3 | [] | no_license | <?php
namespace Application\Utility;
use Acl\Model\AclBase as AclBaseModel;
use Application\Service\ApplicationSetting as SettingService;
use User\Service\UserIdentity as UserIdentityService;
use Zend\Http\PhpEnvironment\RemoteAddress;
class ApplicationDisableSite
{
/**
* Is allowed to view the site
*
* @return boolean
*/
public static function isAllowedViewSite()
{
if ((int) SettingService::getSetting('application_disable_site')) {
$user = UserIdentityService::getCurrentUserIdentity();
if ($user['role'] != AclBaseModel::DEFAULT_ROLE_ADMIN) {
// get a visitor IP
$remote = new RemoteAddress;
$remote->setUseProxy(true);
$userIp = $remote->getIpAddress();
// get list of allowed ACL roles
if (null != ($allowedAclRoles = SettingService::getSetting('application_disable_site_acl'))) {
if (!is_array($allowedAclRoles)) {
$allowedAclRoles = [$allowedAclRoles];
}
}
// get list of allowed IPs
if (null != ($allowedIps = SettingService::getSetting('application_disable_site_ip'))) {
$allowedIps = explode(',', $allowedIps);
}
if ($allowedAclRoles || $allowedIps) {
if (($allowedAclRoles && in_array($user['role'], $allowedAclRoles))
|| ($allowedIps && in_array($userIp, $allowedIps))) {
return true;
}
}
return false;
}
}
return true;
}
} | true |
aadf3439d9ee7dce6fd41535e426fe9382ad4883 | PHP | lw222gz/Php_A_Shitty_Monday | /Application/view/RegisterView.php | UTF-8 | 4,487 | 3 | 3 | [] | no_license | <?php
class RegisterView{
private static $RegisterID = "RegisterView::Register";
private static $UserNameID = "RegisterView::UserName";
private static $PasswordID = "RegisterView::Password";
private static $PasswordCheckID = "RegisterView::PasswordRepeat";
private static $messageID = "RegisterView::Message";
private static $DisplayNameID = "RegisterView::DisplayName";
private static $EmailID = "RegisterView:EmailID";
private $message;
private $saveUserName;
private $saveEmail;
private $saveDisplayName;
//returns HTML for registering
public function RegisterLayout(){
return '
<form method="post">
<fieldset>
<legend>Register - enter the fields below</legend>
<p id="' . self::$messageID . '">' . $this -> message . '</p>
<label for="' . self::$UserNameID . '">Username(max 25 characters, white spaces not allowed):</label>
<input type="text" id="' . self::$UserNameID . '" name="' . self::$UserNameID . '" value="' . $this -> saveUserName . '" maxlength="25"/><br/>
<label for="' . self::$DisplayNameID . '">Display name, this is the name shown to other users(max 25 characters, white spaces allowed):</label>
<input type="text" id="' . self::$DisplayNameID . '" name="' . self::$DisplayNameID . '" value="' . $this -> saveDisplayName . '" maxlength="25"/><br/>
<label for="' . self::$EmailID . '">Email: </label>
<input type="text" id="' . self::$EmailID . '" name="' . self::$EmailID . '" value="' . $this -> saveEmail . '" maxlength="254"/><br/>
<label for="' . self::$PasswordID . '">Password(white spaces not allowed) :</label>
<input type="password" id="' . self::$PasswordID . '" name="' . self::$PasswordID . '" /><br/>
<label for="' . self::$PasswordCheckID . '">Re-type Password :</label>
<input type="password" id="' . self::$PasswordCheckID . '" name="' . self::$PasswordCheckID . '" /><br/>
<input type="submit" name="' . self::$RegisterID . '" value="Register" />
</fieldset>
</form>
';
}
//returns input usernamer
public function getRequestUserName(){
if (isset($_POST[self::$UserNameID])){
//saves a correct version of the name(no white spaces in the string) to display ventual errors by user
$this -> saveUserName = str_replace(' ', '', $_POST[self::$UserNameID]);
//returns a trimed version to be validated in the model so it can check if the user has any whitespaces and if so throw an error.
return trim($_POST[self::$UserNameID]);
}
return null;
}
//returns input DisplayName
public function getRequestDisplayName(){
if(isset($_POST[self::$DisplayNameID])){
$this -> saveDisplayName = trim($_POST[self::$DisplayNameID]);
return $this -> saveDisplayName;
}
return null;
}
//returns input email
public function getRequestEmail(){
if(isset($_POST[self::$EmailID])){
return trim($_POST[self::$EmailID]);
}
return null;
}
//returns input password
public function getRequestPassword(){
if (isset($_POST[self::$PasswordID])){
return trim($_POST[self::$PasswordID]);
}
return null;
}
//returns input password double check
public function getRequestPasswordCheck(){
if(isset($_POST[self::$PasswordCheckID])){
return trim($_POST[self::$PasswordCheckID]);
}
return null;
}
//returns true if user has pressed register
public function hasPressedRegister(){
if(isset($_POST[self::$RegisterID])){
return true;
}
return null;
}
//sets an error message when an exception was thrown
public function setErrorMessage($e){
//checks if error message is cause due to invalid characters
if($e -> getMessage() == EnumStatus::$InvalidCharactersError){
//if so those are removed.
$this -> saveDisplayName = strip_tags($this -> saveDisplayName);
$this -> saveUserName = strip_tags($this -> saveUserName);
}
$this -> message = $e -> getMessage();
}
//sets message if an unhandelsException was thrown
public function UnhandeldException(){
$this -> message = "An unhandeld exception was thrown. Please infrom...";
}
} | true |
d7af8d6c2c9060786ff8604e6fe61d488aa9511d | PHP | nicola-felice/php-snacks-b1 | /snack-1/index.php | UTF-8 | 1,156 | 3 | 3 | [] | no_license |
<?php
// Creiamo un array contenente le partite di basket di un’ipotetica tappa del calendario.
// Ogni array avrà una squadra di casa e una squadra ospite, punti fatti dalla squadra di casa e punti fatti dalla squadra ospite.
// Stampiamo a schermo tutte le partite con questo schema.
// Olimpia Milano - Cantù | 55-60
$todayMatches = [
[
"homeTeam" => "genova",
"visitingTeam" => "milano",
"homeTeamPoints" => 68,
"visitingTeamPoints" => 45
],
[
"homeTeam" => "pordenone",
"visitingTeam" => "torino",
"homeTeamPoints" => 78,
"visitingTeamPoints" => 25
],
[
"homeTeam" => "napoli",
"visitingTeam" => "ancona",
"homeTeamPoints" => 80,
"visitingTeamPoints" => 40
],
[
"homeTeam" => "mantova",
"visitingTeam" => "livorno",
"homeTeamPoints" => 38,
"visitingTeamPoints" => 63
]
];
foreach ( $today_matches as $elm ) {
$homeTeam = $elm["homeTeam"];
$visitingTeam = $elm["visitingTeam"];
$homeTeamPoints = $elm["homeTeamPoints"];
$visitingTeamPoints = $elm["visitingTeamPoints"];
echo "{$homeTeam} - {$visitingTeam} | {$homeTeamPoints}-{$visitingTeamPoints} <br>";
}
?> | true |
486fdf4a5881750f27c884940c1151e290e1835f | PHP | fmales/Gamificacion | /problemon_frontend/data/Recursos/Funciones/Excel.php | UTF-8 | 4,175 | 2.78125 | 3 | [] | no_license | <?php include $_SERVER['DOCUMENT_ROOT'] . "/global.php" ?>
<!DOCTYPE html>
<html>
<head>
<title>Leer Archivo Excel</title>
<link rel="stylesheet" href="../css/estilos.css">
</head>
<body>
<?php
include './CurlRequest.php';
require_once './PHPExcel/Classes/PHPExcel.php';
$url = $host_url; //"localhost:3000/api/";
$rest= new CurlRequest();
function searchJson( $obj, $value ) {
foreach( $obj as $key => $item ) {
if( !is_nan( intval( $key ) ) && is_array( $item ) ){
if( in_array( $value, $item ) ) return $item;
} else {
foreach( $item as $child ) {
if(isset($child) && $child == $value) {
return $child;
}
}
}
}
return null;
}
$personas = $rest -> sendGet($url."people", array());
$personas = json_decode($personas, true);
$search = '{ "where": { "code" : "'.$_POST['curso'].'" } }';
$curso = $rest -> sendGet($url."courses?filter=".urlencode($search), array());
$curso = json_decode($curso, true);
//print_r($curso[0]["students"]);
//print count($curso[0]["students"]);
if ( isset( $_FILES[ 'archivo' ] ) ) {
$errors = array();
$file_name = $_FILES[ 'archivo' ][ 'name' ];
$file_size = $_FILES[ 'archivo' ][ 'size' ];
$file_tmp = $_FILES[ 'archivo' ][ 'tmp_name' ];
$file_type = $_FILES[ 'archivo' ][ 'type' ];
move_uploaded_file( $file_tmp, "./" . $file_name );
}
$archivo = $file_name;
$inputFileType = PHPExcel_IOFactory::identify( $archivo );
$objReader = PHPExcel_IOFactory::createReader( $inputFileType );
$objPHPExcel = $objReader->load( $archivo );
$sheet = $objPHPExcel->getSheet( 0 );
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
$i=0;
for ( $row = 2; $row <= $highestRow; $row++ ) {
$usuario[ $i ] = $sheet->getCell( "A" . $row )->getValue();
$contrasena[ $i ] = $sheet->getCell( "B" . $row )->getValue();
$nombre[ $i ] = $sheet->getCell( "C" . $row )->getValue().$sheet->getCell( "D" . $row )->getValue();
$correo[ $i ] = $sheet->getCell( "E" . $row )->getValue();
if ( @count( searchJson($personas, $correo[$i])) == 0){
$data = array(
"identification" => $correo[ $i ],
"name" => $nombre[ $i ],
"rol" => array ("Estudiante"),
"user" => $usuario[ $i ],
"status" => "ACTIVO"
);
$rest -> sendPost($url."people", $data);
$data = array(
"username" => $usuario[ $i ],
"email" => $correo[ $i ],
"password" => $contrasena[ $i ]
);
$rest -> sendPost($url."Users", $data);
}
$i++;
}
if ( $curso[0]["students"][0] == "" )
unset($curso[0]["students"][0]);
$curso[0]["students"]= array_merge ($curso[0]["students"] ,$correo);
$curso[0]["students"] = array_unique($curso[0]["students"]);
$rest -> sendPut($url."courses", $curso [0]);
$data = array(
"code" => $curso [0]['code'],
"name" => "Todos",
"members" => $curso[0]["students"]
);
$rest -> sendPut($url."groups", $data);
?>
<center>
<div class="wrapper">
<main>
<div id="main" style="width: 100%; height: 100%; text-align: center; vertical-align: middle; display: table;">
<span id='contenido' style="display: table-cell; vertical-align: middle;text-align: center;">
<div class="cent" style="width: 60%" align="center">
<br>
<center><legend>Los estudiantes que se han matricuado en el sistema a la materia <?= $_POST['curso'];?> son:</legend>
<form action="../../Templates/matricularEstudiantes">
<table>
<tr>
<!-- <th>Cédula</th> -->
<th>Nombre</th>
<th>Correo</th>
<!-- <th>Teléfono</th> -->
<th>Usuario</th>
<th>Contraseña</th>
</tr>
<?php
for($i=0;$i<count($contrasena);$i++){?>
<tr>
<td><?= $nombre[ $i ]; ?></td>
<td><?= $correo[ $i ]; ?></td>
<td><?= $usuario[ $i ]; ?></td>
<td><?= $contrasena[ $i ]; ?></td>
</tr>
<?php } ?>
</table>
<input type="submit" value="Regresar" class="botones"> </center>
</form>
</div>
</span>
</div>
</main></div>
</center>
</body>
</html>
| true |
4a41be0ae8d66bf7d4ae6a4e09b538d6ce7569ce | PHP | devious507/member | /index.php | UTF-8 | 4,287 | 2.59375 | 3 | [] | no_license | <?php
require_once("project.php");
$db = myDB();
if(isset($_POST['search'])) {
unset($_POST['search']);
foreach($_POST as $k=>$v) {
$v=preg_replace("/\*/",'%',$v);
$v=preg_replace("/\?/",'%',$v);
if($v != '') {
if(preg_match("/%/",$v)) {
switch($k) {
case "NameLast":
$wheres[] = "({$k} LIKE '{$v}' OR spouse_last LIKE '{$v}')";
break;
case "NameFirst":
$wheres[] = "({$k} LIKE '{$v}' OR spouse_first LIKE '{$v}')";
break;
case "email":
$wheres[] = "({$k} LIKE '{$v}' OR spouse_email LIKE '{$v}')";
break;
case "phone":
$wheres[] = "({$k} LIKE '{$v}' OR spouse_phone LIKE '{$v}')";
break;
default:
$wheres[] = "{$k} LIKE '{$v}'";
}
} elseif($v == 'NULL') {
switch($k) {
default:
$wheres[] = "({$k} IS NULL OR {$k} = '')";
break;
}
} else {
switch($k) {
case "NameLast":
$wheres[] = "({$k} = '{$v}' OR spouse_last = '{$v}')";
break;
case "NameFirst":
$wheres[] = "({$k} = '{$v}' OR spouse_first = '{$v}')";
break;
case "email":
$wheres[] = "({$k} = '{$v}' OR spouse_email = '{$v}')";
break;
case "phone":
$wheres[] = "({$k} = '{$v}' OR spouse_phone = '{$v}')";
break;
default:
$wheres[] = "{$k} = '{$v}'";
break;
}
}
}
}
$sql="SELECT * FROM members WHERE ".implode(" AND ",$wheres)." ORDER BY NameLast, NameFirst;";
$result = simpleQuery($sql,true,$db);
$data = $result->fetchAll(PDO::FETCH_ASSOC);
if(count($data) == 0) {
$body="No Results Found <!--{$sql}--><br>\n";
$body.="<p><a href=\"newMember.php\">New Member Entry</a></p>";
renderPage($body,true,'Member Management',$db);
exit();
} elseif(count($data) == 1) {
$memberID=$data[0]['memberID'];
header("Location: memberRecord.php?memberID={$memberID}");
exit();
} else {
$body ="<table cellpadding=\"5\" cellspacing=\"0\" border=\"1\">\n";
foreach($data as $row) {
if($row['NameFirst'] == '' && $row['NameLast'] == '') {
$href = "<a href=\"memberRecord.php?memberID={$row['memberID']}\">({$row['memberID']})</a>";
} else {
$href = "<a href=\"memberRecord.php?memberID={$row['memberID']}\">{$row['NameLast']}, {$row['NameFirst']}</a>";
}
if( ($row['spouse_last'] != '') && ($row['spouse_first'] != '') ) {
$spouse=$row['spouse_last'].", ".$row['spouse_first'];
} else {
$spouse=' ';
}
if($row['spouse_phone'] != '') {
$spouse_phone = $row['spouse_phone'];
} else {
$spouse_phone = ' ';
}
if($row['spouse_email'] != '') {
$spouse_email = $row['spouse_email'];
} else {
$spouse_email = ' ';
}
$body.="<tr><td>{$href}</td><td>{$row['email']}</td><td>{$row['address']}</td><td>{$row['phone']}</td><td>{$spouse}</td><td>{$spouse_email}</td><td>{$spouse_phone}</td></tr>\n";
}
$body.="</table>\n";
renderPage($body,true,'Member Management',$db);
}
exit();
}
renderPage(mySearch(),true,'Member Management',$db);
function mySearch() {
$body ="<form method=\"post\" action=\"index.php\">";
$body.="<table cellpadding=\"5\" cellspacing=\"0\" border=\"0\">";
$body.="<tr><th colspan=\"4\">Member Search</th></tr>\n";
$body.="<tr><td colspan=\"1\">Name (First, Last)</td><td><input id=\"focusBox\" type=\"text\" size=\"15\" name=\"NameFirst\"></td><td colspan=\"2\"><input type=\"text\" size=\"20\" name=\"NameLast\"></td></tr>\n";
$body.="<tr><td colspan=\"1\">Address</td><td colspan=\"3\"><input type=\"text\" size=\"43\" name=\"address\"</td></tr>\n";
$body.="<tr><td>City, State, Zip</td><td><input type=\"text\" name=\"City\" size=\"15\"></td><td><input type=\"text\" Size=\"4\" name=\"State\"</td><td><input type=\"text\" size=\"8\" name=\"Zip\"></td></tr>\n";
$body.="<tr><td>Email</td><td colspan=\"3\"><input type=\"text\" size=\"43\" name=\"email\"></td></tr>\n";
$body.="<tr><td>Phone</td><td colspan=\"3\"><input type=\"text\" size=\"43\" name=\"phone\"></td></tr>\n";
$body.="<tr><td>Keycard #</td><td colspan=\"3\"><input type=\"text\" size=\"6\" name=\"keycard_number\"></td></tr>\n";
$body.="<tr><td colspan=\"4\"><input type=\"submit\" name=\"search\" value=\"Search\"></td></tr>\n";
$body.="</table>\n</form>\n";
$body.="<p><a href=\"newMember.php\">New Member Entry</a></p>";
return $body;
}
?>
| true |
f652cf09ef9ff867bdbbf7a115075fc6d00ff4ee | PHP | encinecarlos/box4buy | /app/Lib/ProductServices.php | UTF-8 | 592 | 2.703125 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: carlos
* Date: 28/02/19
* Time: 11:58
*/
namespace App\Lib;
class ProductServices
{
public static function totalizaProdutos()
{
$totalProdutos = 0;
$totalPeso = 0;
$produtos = session('produtos');
if($produtos)
{
foreach($produtos as $produto => $value)
{
$totalProdutos += $value['qtde'];
$totalPeso += $value['peso'];
}
return ['total_produtos' => $totalProdutos, 'total_peso' => $totalPeso];
}
}
}
| true |
c061972e9c0ed1751590563fd898f3aed0f45661 | PHP | romanbatavi/knn-pm-skr | /guru/dataset_import.php | UTF-8 | 4,261 | 2.578125 | 3 | [] | no_license | <div class="container-fluid">
<div class="row">
<div class="col-12">
<div class="portlet">
<div class="portlet-header portlet-header-bordered">
<h3 class="portlet-title">Import Dataset</h3>
</div>
<div class="portlet-body">
<!-- <p>
In this example you can see Datatable doing both horizontal and vertical scrolling at the same time. To enable y-scrolling or x-scrolling simply set the <code>scrollY|scrollX</code> parameter to be whatever you want the container wrapper's height or width.
</p>
<hr> -->
<?php if ($_POST) include 'aksi.php' ?>
<form method="post" enctype="multipart/form-data">
<?php
if ($_POST) {
$row = 0;
move_uploaded_file($_FILES['dataset']['tmp_name'], 'csv/' . $_FILES['dataset']['name']) or die('Upload gagal');
$arr = array();
$ket_dataset = array();
if (($handle = fopen('csv/' . $_FILES['dataset']['name'], "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
if ($row > 0) {
for ($c = 2; $c < $num; $c++) {
$ket_dataset[$row] = $data[1];
$arr[$row][$c - 1] = $data[$c];
}
}
$row++;
}
fclose($handle);
}
//echo '<pre>' . print_r($arr, 1) . '</pre>';
function isi_key($dataset)
{
global $ATRIBUT;
$keys = array_keys($ATRIBUT);
$arr = array();
foreach ($dataset as $key => $val) {
foreach ($val as $k => $v) {
$arr[$key][$keys[$k - 1]] = strtolower($v);
}
}
//echo '<pre>'.print_r($arr, 1).'</pre>';
return $arr;
}
function convert_dataset($dataset)
{
$arr = array();
foreach ($dataset as $key => $val) {
foreach ($val as $k => $v) {
$arr[$key][$k] = get_id($k, $v);
}
}
//echo '<pre>'.print_r($arr, 1).'</pre>';
return $arr;
}
function get_id($id_atribut, $nama_nilai)
{
global $NILAI;
foreach ($NILAI as $key => $val) {
if ($val->id_atribut == $id_atribut && strtolower($val->nama_nilai) == $nama_nilai)
return $key;
}
return $nama_nilai;
}
function simpan_dt($dataset)
{
global $db, $ket_dataset;
$db->query("TRUNCATE tb_dataset");
foreach ($dataset as $key => $val) {
foreach ($val as $k => $v) {
$db->query("INSERT INTO tb_dataset (nomor, ket_dataset, id_atribut, id_nilai)
VALUES ('$key', '{$ket_dataset[$key]}', '$k', '$v')");
}
}
}
$arr = isi_key($arr);
$arr = convert_dataset($arr);
simpan_dt($arr);
print_msg('Dataset berhasil diimport!', 'success');
}
?>
<div class="form-group">
<label>Pilih file</label>
<input class="form-control" type="file" name="dataset" />
</div>
<div class="form-group">
<button class="btn btn-primary" name="import"><span class="glyphicon glyphicon-import"></span> Import</button>
<a class="btn btn-danger" href="?m=dataset"><span class="glyphicon glyphicon-arrow-left"></span> Kembali</a>
</div>
</form>
</div>
</div>
</div>
</div>
</div> | true |
a875cb2bd1235110102b220361d0a4cf7670f0e5 | PHP | SelviBalaB/Laravel-custom-registration | /app/Http/Controllers/CustomAuthController.php | UTF-8 | 687 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\User;
class CustomAuthController extends Controller
{
//
public function ShowRegisterForm()
{
return view('custom.register');
}
public function Register(Request $request)
{
$this->validation($request);
User::create($request->all());
//return $request->all();
return redirect('/')->with('Status','You are registered');
}
public function validation($request)
{
$this->validate($request, [
'fname' => 'required|max:255',
'lname' => 'required|max:255',
'email' => 'required|email|unique:max_users|max:255',
'password' => 'required|confirmed|max:255',
]);
}
}
| true |
94fb525fa5e04c73da97e91bc6f66251d4e304f0 | PHP | ferodss/salesforce-api | /src/Api/Bulk/XmlEntity.php | UTF-8 | 1,218 | 2.84375 | 3 | [
"MIT"
] | permissive | <?php
namespace Salesforce\Api\Bulk;
/**
* Abstract Xml entity
*
* @author Felipe Rodrigues <lfrs.web@gmail.com>
*/
abstract class XmlEntity implements XmlSerializable
{
/**
* XML representation of this entity
*
* @var \SimpleXMLElement
*/
protected $xml;
/**
* {@inheritDoc}
*/
abstract public function asXML();
/**
* Updates Job information by given xml
*
* @param \SimpleXMLElement $xml
*
* @return void
*/
public function fromXml(\SimpleXMLElement $xml)
{
foreach ($xml as $attr => $node) {
$method = 'set' . ucfirst($attr);
if (method_exists($this, $method)) {
call_user_func(array($this, $method), (string) $xml->{$attr});
}
}
}
/**
* Remove empty fields to allow API to parse correctly
*
* @return void
*/
protected function clearEmptyXMLData()
{
$emptyFields = array();
foreach ($this->xml as $field => $value) {
if ($value == '') {
$emptyFields[] = $field;
}
}
foreach ($emptyFields as $field) {
unset($this->xml->{$field});
}
}
} | true |
f5c3ef98a4d07f7793408f9b4d6af0adcd4edae2 | PHP | nandom5/Proyecto | /ModificarCatalogo/ModificarMunicipio/listarMunicipio.php | UTF-8 | 1,305 | 2.828125 | 3 | [] | no_license | <?php
include_once "../../BaseDatos/database_connection.php";
$sentencia = $connect->query("SELECT * FROM tb_cat_municipios;");
$personas = $sentencia->fetchAll(PDO::FETCH_OBJ);
?>
<!--Recordemos que podemos intercambiar HTML y PHP como queramos-->
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Tabla departamentos</title>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<table>
<thead>
<tr>
<th>ID Departamento</th>
<th>ID Municipio</th>
<th>Nombre del municipio</th>
</tr>
</thead>
<tbody>
<!--
Atención aquí, sólo esto cambiará
Pd: no ignores las llaves de inicio y cierre {}
-->
<?php foreach($personas as $persona){ ?>
<tr>
<td><?php echo $persona->ID_DEPARTAMENTO ?></td>
<td><?php echo $persona->ID_MUNICIPIO ?></td>
<td><?php echo $persona->DESCRIPCION_MUNICIPIO ?></td>
<td><a href="<?php echo "editar.php?id=" . $persona->ID_MUNICIPIO?>">Editar</a></td>
<td><a href="<?php echo "eliminar.php?id=" . $persona->ID_MUNICIPIO?>">Eliminar</a></td>
</tr>
<?php } ?>
</tbody>
</table>
<a href="../../Inicios/InicioAdministrador/InicioAdministrador.php" title="Ir la página anterior">Volver</a>
</body>
</html> | true |
37e920c67b53b371aae321c095b83e5d3e5474b7 | PHP | Marwa124/ego_laravel_application | /app/Models/DeliveryState.php | UTF-8 | 847 | 2.65625 | 3 | [] | no_license | <?php
namespace App\Models;
use Eloquent as Model;
/**
* Class DeliveryAddress
* @package App\Models
* @version December 6, 2019, 1:57 pm UTC
*
* @property \App\Models\User user
* @property string description
* @property string address
* @property string latitude
* @property string longitude
* @property boolean is_default
* @property integer user_id
*/
class DeliveryState extends Model
{
public $table = 'delivery_states';
public $guarded = [];
/**
* Validation rules
*
* @var array
*/
public static $rules = [
'state' => 'required',
];
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
**/
public function DeliveryAddresses()
{
return $this->hasMany(\App\Models\DeliveryAddress::class, 'delivery_state_id', 'id');
}
}
| true |
5242ac63747404d2c03ebda0a1083edd8f1e3083 | PHP | Raspfarbend/RPi-Jukebox-RFID | /htdocs/index.php | UTF-8 | 5,417 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
include("inc.header.php");
/*******************************************
* START HTML
*******************************************/
html_bootstrap3_createHeader("en","Phoniebox",$conf['base_url']);
?>
<body>
<div class="container">
<?php
include("inc.vlcStatus.php");
?>
<?php
include("inc.navigation.php");
?>
<div class="row playerControls">
<div class="col-lg-12">
<?php
/*
* Do we need to voice a warning here?
*/
if(isset($warning)) {
print '<div class="alert alert-warning">'.$warning.'</div>';
}
include("inc.controlPlayer.php");
include("inc.controlVolumeUpDown.php");
?>
</div><!-- / .col-lg-12 -->
</div><!-- /.row -->
<?php
// show currently played track
if (array_key_exists('track', $vlcStatus)) {
$icon_class = ($vlcStatus['status'] === 'playing') ? 'play' : 'pause';
print '
<div class="well well-sm">
<div class="row">
<div class="col-lg-1 col-md-1 col-sm-1 col-xs-1">
<i class="fa fa-'. $icon_class .'"></i>
</div>
<div class="col-lg-11 col-md-11 col-sm-11 col-xs-11">
'.$vlcStatus['track'].'
</div>
</div>
</div>
';
}
?>
<div class="row">
<div class="col-xs-12">
<h3>Volume</h3>
</div>
</div>
<?php
include("inc.volumeSelect.php");
?>
<div class="row">
<div class="col-lg-12">
<h3>Manage Files and Chips</h3>
<!-- Button trigger modal -->
<a href="cardRegisterNew.php" class="btn btn-primary btn">
<i class='fa fa-plus-circle'></i> Register new card ID
</a>
</div><!-- / .col-lg-12 -->
</div><!-- /.row -->
<div class="row">
<div class="col-lg-12">
<h3>Available audio</h3>
<?php
// read the shortcuts used
$shortcutstemp = array_filter(glob($conf['base_path'].'/shared/shortcuts/*'), 'is_file');
$shortcuts = array(); // the array with pairs of ID => foldername
// read files' content into array
foreach ($shortcutstemp as $shortcuttemp) {
$shortcuts[basename($shortcuttemp)] = trim(file_get_contents($shortcuttemp));
}
//print "<pre>"; print_r($shortcutstemp); print "</pre>"; //???
//print "<pre>"; print_r($shortcuts); print "</pre>"; //???
// read the subfolders of shared/audiofolders
$audiofolders = array_filter(glob($conf['base_path'].'/shared/audiofolders/*'), 'is_dir');
usort($audiofolders, 'strcasecmp');
// counter for ID of each folder
$idcounter = 0;
// go through all folders
foreach($audiofolders as $audiofolder) {
// increase ID counter
$idcounter++;
// get list of content for each folder
$files = scandir($audiofolder);
$accordion = "<h4>Contains the following file(s):</h4><ul>";
foreach($files as $file) {
if(is_file($audiofolder."/".$file)){
$accordion .= "\n<li>".$file."</li>";
}
}
$accordion .= "</ul>";
// get all IDs that match this folder
$ids = ""; // print later
$audiofolderbasename = trim(basename($audiofolder));
if(in_array($audiofolderbasename, $shortcuts)) {
foreach ($shortcuts as $key => $value) {
if($value == $audiofolderbasename) {
$ids .= " <a href='cardEdit.php?cardID=$key'>".$key." <i class='fa fa-wrench'></i></a> | ";
}
}
$ids = rtrim($ids, "| "); // get rid of trailing slash
}
// if folder not empty, display play button and content
if ($accordion != "<h4>Contains the following file(s):</h4><ul></ul>") {
print "
<div class='well'>
<a href='?play=".$audiofolder."' class='btn btn-success'><i class='fa fa-play'></i> Play</a>";
print "
<span data-toggle='collapse' data-target='#folder".$idcounter."' class='btn btn-info btnFolder'>Folder:
".str_replace($conf['base_path'].'/shared/audiofolders/', '', $audiofolder)."
<i class='fa fa-info-circle'></i>
</span>
<div id='folder".$idcounter."' class='collapse folderContent'>
".$accordion."
</div>
";
// print ID if any found
if($ids != "") {
print "
<br/>Card ID: ".$ids;
}
print "
</div>
";
}
}
?>
</div><!-- / .col-lg-12 -->
</div><!-- /.row -->
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Last used Chip ID</h4>
</div>
<div class="modal-body">
<pre>
<?php
print file_get_contents($conf['base_path'].'/shared/latestID.txt', true);
?>
</pre>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div><!-- / .modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
</div><!-- /.container -->
</body>
</html>
| true |
8c2acf4784450befc9ff57623f22bb83177616b5 | PHP | haideralise/events-api | /app/Models/Roster.php | UTF-8 | 2,023 | 2.671875 | 3 | [
"MIT"
] | permissive | <?php namespace App\Models;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphTo;
/**
* Class Roster
* @package App\Models
*/
class Roster extends Model
{
/**
* @return MorphTo
*/
public function rosterable()
{
return $this->morphTo();
}
/**
* @return BelongsTo
*/
public function game()
{
return $this->belongsTo(Game::class, 'game_id');
}
/**
* @return BelongsTo
*/
public function proficiency()
{
return $this->belongsTo(GameProficiency::class, 'proficiency_id');
}
/**
* @param Builder $query
* @param $game_id
* @return Builder
*/
public function scopeOfGame(Builder $query, $game_id)
{
return $query->where(compact('game_id'));
}
/**
* @param Builder $query
* @param $rosterable_type
* @return Builder
*/
public function scopeOfType(Builder $query, $rosterable_type)
{
return $query->where(compact('rosterable_type'));
}
/**
* @param Builder $query
* @return Builder
*/
public function scopeOfTeamType(Builder $query)
{
return $query->ofType(Team::class);
}
/**
* @param Builder $query
* @return Builder
*/
public function scopeOfPlayerType(Builder $query)
{
return $query->ofType(Player::class);
}
/**
* @param Builder $query
* @param $player_id
* @return Builder
*/
public function scopeOfPlayer(Builder $query, $player_id)
{
return $query->ofType(Player::class)->where('rosterable_id', $player_id);
}
/**
* @param Builder $query
* @param $team_id integer
* @return Builder
*/
public function scopeOfTeam(Builder $query, $team_id)
{
return $query->ofType(Player::class)->where('rosterable_id', $team_id);
}
}
| true |
fb91f1847607edd35310d96a3012bd0956f0e10e | PHP | karispk/synologylyric | /tests/FujirouLyricWikiTest.php | UTF-8 | 694 | 2.578125 | 3 | [] | no_license | <?php
declare (strict_types = 1);
require_once 'LyricsTestCase.php';
final class FujirouLyricWikiTest extends LyricsTestCase
{
protected $module = 'FujirouLyricWiki';
public function testSearch()
{
$artist = 'taylor swift ';
$title = 'style';
$answer = array(
'artist' => 'Taylor Swift',
'title' => 'Style',
'id' => 'http://lyrics.wikia.com/Taylor_Swift:Style'
);
$this->search($artist, $title, $answer);
}
public function testGet()
{
$id = 'http://lyrics.wikia.com/Taylor_Swift:Style';
$path = 'FujirouLyricWiki.taylor_swift.style.txt';
$this->get($id, $path);
}
}
| true |
44f85bcb9b028ba9750460e7909f249125de58e6 | PHP | fusion52/laravel-likeable | /src/Favoriteable.php | UTF-8 | 4,184 | 2.875 | 3 | [
"MIT"
] | permissive | <?php
namespace Fusion52\Favoriteable;
/**
* Copyright (C) 2016 Fusion52 Team
*/
trait Favoriteable
{
/**
* Boot the soft taggable trait for a model.
*
* @return void
*/
public static function bootFavoriteable()
{
if(static::removeFavoritesOnDelete()) {
static::deleting(function($model) {
$model->removeFavorites();
});
}
}
/**
* Fetch records that are favorited by a given user.
* Ex: Book::whereFavoritedBy(123)->get();
*/
public function scopeWhereFavoritedBy($query, $userId=null)
{
if(is_null($userId)) {
$userId = $this->loggedInUserId();
}
return $query->whereHas('favorites', function($q) use($userId) {
$q->where('user_id', '=', $userId);
});
}
/**
* Populate the $model->favorites attribute
*/
public function getFavoriteCountAttribute()
{
return $this->favoriteCounter ? $this->favoriteCounter->count : 0;
}
/**
* Collection of the favorites on this record
*/
public function favorites()
{
return $this->morphMany(Favorite::class, 'favoriteable');
}
/**
* Counter is a record that stores the total favorites for the
* morphed record
*/
public function favoriteCounter()
{
return $this->morphOne(FavoriteCounter::class, 'favoriteable');
}
/**
* Add a favorite for this record by the given user.
* @param $userId mixed - If null will use currently logged in user.
*/
public function favorite($userId=null)
{
if(is_null($userId)) {
$userId = $this->loggedInUserId();
}
if($userId) {
$favorite = $this->favorites()
->where('user_id', '=', $userId)
->first();
if($favorite) return;
$favorite = new Favorite();
$favorite->user_id = $userId;
$this->favorites()->save($favorite);
}
$this->incrementFavoriteCount();
}
/**
* Remove a favorite from this record for the given user.
* @param $userId mixed - If null will use currently logged in user.
*/
public function unfavorite($userId=null)
{
if(is_null($userId)) {
$userId = $this->loggedInUserId();
}
if($userId) {
$favorite = $this->favorites()
->where('user_id', '=', $userId)
->first();
if(!$favorite) { return; }
$favorite->delete();
}
$this->decrementFavoriteCount();
}
/**
* Has the currently logged in user already "favorited" the current object
*
* @param string $userId
* @return boolean
*/
public function favorited($userId=null)
{
if(is_null($userId)) {
$userId = $this->loggedInUserId();
}
return (bool) $this->favorites()
->where('user_id', '=', $userId)
->count();
}
/**
* Private. Increment the total favorite count stored in the counter
*/
private function incrementFavoriteCount()
{
$counter = $this->favoriteCounter()->first();
if($counter) {
$counter->count++;
$counter->save();
} else {
$counter = new FavoriteCounter;
$counter->count = 1;
$this->favoriteCounter()->save($counter);
}
}
/**
* Private. Decrement the total favorite count stored in the counter
*/
private function decrementFavoriteCount()
{
$counter = $this->favoriteCounter()->first();
if($counter) {
$counter->count--;
if($counter->count) {
$counter->save();
} else {
$counter->delete();
}
}
}
/**
* Fetch the primary ID of the currently logged in user
* @return number
*/
public function loggedInUserId()
{
return auth()->id();
}
/**
* Did the currently logged in user favorite this model
* Example : if($book->favorited) { }
* @return boolean
*/
public function getFavoritedAttribute()
{
return $this->favorited();
}
/**
* Should remove favorites on model row delete (defaults to true)
* public static removeFavoritesOnDelete = false;
*/
public static function removeFavoritesOnDelete()
{
return isset(static::$removeFavoritesOnDelete)
? static::$removeFavoritesOnDelete
: true;
}
/**
* Delete favorites related to the current record
*/
public function removeFavorites()
{
Favorite::where('favoriteable_type', $this->morphClass)->where('favoriteable_id', $this->id)->delete();
FavoriteCounter::where('favoriteable_type', $this->morphClass)->where('favoriteable_id', $this->id)->delete();
}
}
| true |
e70d84b326c8d4a6b513c01a49e3c99833402e7e | PHP | tomeksadzik/coordinates-rest-api | /src/Service/PointProviderInterface.php | UTF-8 | 289 | 2.78125 | 3 | [] | no_license | <?php
namespace App\Service;
use App\Entity\Point;
interface PointProviderInterface
{
/**
* @param int $pointId
* @return Point
*/
public function getPoint(int $pointId): Point;
/**
* @return Point[]
*/
public function getAllPoints(): array;
} | true |
560193efd98fed0e521a73bec5cc1dbb8eedddc8 | PHP | itsmenayrb/webdev-project | /controller/RegisterController.php | UTF-8 | 855 | 2.59375 | 3 | [] | no_license | <?php
session_start();
require_once '../classes/Config.php';
require_once '../classes/Register.php';
$config = new Config();
if(isset($_POST['register']))
{
$username = $config->checkInput($_POST['username']);
$email = $config->checkInput($_POST['email']);
$password = $config->checkInput($_POST['password']);
$error = false;
if( $username == "" || $password == "" || $email == ""){
echo json_encode(array(
'status' => 'empty',
'message' => 'All fields are required.'
));
$error = true;
}
if($error == false) {
$login = new Register($username, $email, $password);
$login->validateCredentials();
}
}
?> | true |
4ef6f3248f2fd56a272b6dc9f158b4876fd17ddc | PHP | hilyb/test_online | /test.php | UTF-8 | 2,761 | 2.578125 | 3 | [
"MIT"
] | permissive | <?php
/**
* User: liyubing
* Date: 2018/4/21
* 在线答题考试功能处理
*/
//error_reporting(E_ALL ^ E_NOTICE);
session_start();
header("Content-type:text/html;charset=utf-8");
$data=require "./data/data.php";
$studentid = $_POST['studentid'];
$name = $_POST['name'];
$_SESSION['studentid'] = $studentid;
$_SESSION['name'] = $name;
$t_time = date("Y-m-d H:i:s",strtotime(now));
//$t_time = now();
$_SESSION['t_time'] = $t_time;
//if(empty($_SESSION['arr_judge'])){
//随机排序
/*================================判断题=======================================*/
//17道题中随机选取10道,没有必选题
$arr_judge1=array("1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17");
//从题中随机取值10道下标,注意只是下标不是值!
$arr_judge2=array_rand($arr_judge1,10);
//把$arr_choice3的下标换成值
for($j=0;$j<10;$j++){
$arr_judge[$j]=$arr_judge1[$arr_judge2[$j]];
}
//shuffle 将数组顺序随机打乱
shuffle ($arr_judge);
$_SESSION['arr_judge'] = $arr_judge;
//$_SESSION['answer_judge'] = $answer_judge;
//}
/*================================选择题=======================================*/
//if(empty($_SESSION['arr_choice'])){
//必选题9道
$arr_choice1=array("1","3","6","9","12","16","19","23","26");
//随机选题18道
$arr_choice2=array("2","4","5","7","8","10","11","13","14","15","17","18","20","21","22","24","25","27");
//从剩下题中随机取值11道下标,注意只是下标不是值!
$arr_choice3=array_rand($arr_choice2,11);
//把$arr_choice3的下标换成值
for($i=0;$i<11;$i++){
$arr_choice3[$i]=$arr_choice2[$arr_choice3[$i]];
}
//合并数组
$arr_choice = array_merge($arr_choice1,$arr_choice3);
//将最终数组$arr_choice随机打乱
shuffle ($arr_choice);
$_SESSION['arr_choice'] = $arr_choice;
//$_SESSION['answer_choice'] = $answer_choice;
//}
/*================================填空题=======================================*/
//if(empty($_SESSION['arr_blank'])){
//必选题8道
$arr_blank1=array("1","2","5","8","9","10","11","12");
//随机选题4道
$arr_blank2=array("3","4","6","7");
//从剩下题中随机取值2道下标,注意只是下标不是值!
$arr_blank3=array_rand($arr_blank2,2);
//把$arr_choice3的下标换成值
for($j=0;$j<2;$j++){
$arr_blank3[$j]=$arr_blank2[$arr_blank3[$j]];
}
//合并数组
$arr_blank = array_merge($arr_blank1,$arr_blank3);
//将最终数组$arr_choice随机打乱
shuffle ($arr_blank);
$_SESSION['arr_blank'] = $arr_blank;
//$_SESSION['answer_blank'] = $answer_blank;
//}
/*================================END=======================================*/
//引入答题页模板
require './view/test.html'; | true |
ff5e628090a2726463ccedb539d4d5de864efc3d | PHP | Candy128x/phpBasic | /SortingAll/InsertionSort.php | UTF-8 | 429 | 3.734375 | 4 | [] | no_license | <?php
function insertionSort($arr)
{
$n = count($arr);
for($i=0; $i<$n; $i++)
{
$val = $arr[$i];
$j = $i-1;
while($j>=0 && $arr[$j]>$val)
{
$arr[$j+1] = $arr[$j];
$j--;
}
$arr[$j+1] = $val;
}
return $arr;
}
$arr = array(7,8,5,2,4,6,3);
echo "UnSorted Array: <br>".implode('| ',$arr)."<br><br>";
echo "Insertion Sorted Array: <br>".implode('| ',insertionSort($arr));
?>
| true |
daf9cd46cae7f9e610bb18ca3d4b6fd9f30869f1 | PHP | im7md3/Queue-Management-System | /app/Repository/QueueRepository.php | UTF-8 | 153 | 2.578125 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Repository;
interface QueueRepository
{
public function all();
public function store($queue);
public function clear();
} | true |
ad5d2a7548ba292b2984b4bd52e864fe8fdc62e0 | PHP | karlosdiaz99/BOLSAT | /consulta_busqueda.php | UTF-8 | 1,452 | 2.828125 | 3 | [] | no_license | <?php
/////// CONEXIÓN A LA BASE DE DATOS /////////
require('conexion.php');
if ($conexion1 -> connect_errno)
{
die("Fallo la conexion:(".$conexion1 -> mysqli_connect_errno().")".$conexion1-> mysqli_connect_error());
}
//////////////// VALORES INICIALES ///////////////////////
$tabla="";
$query="SELECT * FROM empresa ORDER BY id_empresa";
///////// LO QUE OCURRE AL TECLEAR SOBRE EL INPUT DE BUSQUEDA ////////////
if(isset($_POST['empresa']))
{
$q=$conexion1->real_escape_string($_POST['empresa']);
$query="SELECT * FROM empresa WHERE
id_empresa LIKE '%".$q."%' OR
nombre LIKE '%".$q."%' OR
telefono LIKE '%".$q."%' OR
correo LIKE '%".$q."%' OR
requerimiento LIKE '%".$q."%'";
}
$buscarEmpresa=$conexion1->query($query);
if ($buscarEmpresa->num_rows > 0)
{
$tabla.=
'<table class="table">
<tr class="bg-primary">
<td>ID EMPRESA</td>
<td>NOMBRE</td>
<td>REQUERIMIENTO</td>
<td>CORREO</td>
<td>TELEFONO</td>
</tr>';
while($filaEmpresa= $buscarEmpresa->fetch_assoc())
{
$tabla.=
'<tr>
<td>'.$filaEmpresa['id_empresa'].'</td>
<td>'.$filaEmpresa['nombre'].'</td>
<td>'.$filaEmpresa['requerimiento'].'</td>
<td>'.$filaEmpresa['correo'].'</td>
<td>'.$filaEmpresa['telefono'].'</td>
</tr>
';
}
$tabla.='</table>';
} else
{
$tabla="No se encontraron coincidencias con sus criterios de búsqueda.";
}
echo $tabla;
?>
| true |
15f02c68c634b35c5c01db51be8215f6ee6bd297 | PHP | ckhero/coca | /frontend/module/v1/swagger/model/user.php | UTF-8 | 823 | 2.625 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
/**
* @SWG\Definition(required={}, type="object", @SWG\Xml(name="user"))
*/
class user
{
/**
* @SWG\Property(description="用户的可乐id")
* @var int
*/
private $coca_id;
/**
* @SWG\Property(description="积分")
* @var int
*/
private $point;
/**
* @SWG\Property(description="排名")
* @var int
*/
private $rank;
/**
* pet status in the store
* @SWG\Property( description="头像")
* @var string
*/
private $head_img;
/**
* pet status in the store
* @SWG\Property( description="昵称")
* @var string
*/
private $nick_name;
/**
* pet status in the store
* @SWG\Property( description="经验等级", example="菜鸟")
* @var string
*/
private $level;
}
| true |
f8919a7800265833c82109552f23f0e9d068bff9 | PHP | studiokam/verbs | /application/Application/Service/Words/GetListService.php | UTF-8 | 384 | 2.84375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | <?php
namespace application\Application\Service\Words;
use application\Domain\Model\Words\WordsRepositoryInterface;
class GetListService
{
private $wordsRepo;
public function __construct(WordsRepositoryInterface $wordsRepo)
{
$this->wordsRepo = $wordsRepo;
}
/**
* @return array
*/
public function execute(): array
{
return $this->wordsRepo->getAllWords();
}
}
| true |
9304dee2ab5eae588d461e00917ff392d144ed0b | PHP | juliette1994/etna-movies | /etna_movies.show_student.php | UTF-8 | 373 | 2.671875 | 3 | [] | no_license | <?php
require_once('includes/student.utils.php');
if ($argc == 1)
student_show_all();
elseif ($argc == 2)
{
if (!student_validate_login($argv[1]))
puts($argv[1] .': is not a valid login.');
elseif (!student_exists($argv[1]))
puts($argv[1] .': student does not exist.');
else
student_show($argv[1]);
}
else
puts('Usage: ./etna_movies.php update_student login_n'); | true |
d07e0f894381afc87fb8ceb43ea984d0936b3e89 | PHP | seclab-fudan/TEFuzz | /CodeWrapper/main.php | UTF-8 | 14,271 | 2.515625 | 3 | [] | no_license | <?php
require 'vendor/autoload.php';
use PhpParser\Error;
use PhpParser\NodeDumper;
use PhpParser\ParserFactory;
use PhpParser\Lexer;
use PhpParser\Parser\Tokens;
const UNIQUE_STRING = 'Un1QuE';
const EXEC_CODE = <<<'CODE'
phpinfo();
CODE;
const COMMENTS_TOKENS=array(376,377,378,379);
const FUNCTION_CLASS = array('PhpParser\Node\Expr\FuncCall','PhpParser\Node\Expr\StaticCall','PhpParser\Node\Expr\MethodCall');
const SPECIAL_FUNCTION_CLASS = array('PhpParser\Node\Expr\Isset_','PhpParser\Node\Expr\Empty_',);
const COND_CLASS = array('PhpParser\Node\Stmt\While_','PhpParser\Node\Stmt\If_','PhpParser\Node\Stmt\Foreach_');
const FUNCTION_TOKENS=array();
const ASSIGN_TOKENS=array();
const COND_TOKENS=array();
const DEFINE_TOKENS=array();
error_reporting(0);
function isDeclaredUsingVar(array $tokens, PhpParser\Node\Stmt\Property $prop) {
$i = $prop->getStartTokenPos();
return $tokens[$i]->id === T_VAR;
}
function get_all_static($className)
{
$r = new ReflectionClass($className);
return $r->getProperties();
}
class MyNodeVisitor extends PhpParser\NodeVisitorAbstract {
private $tokens;
private $stack;
private $locationTokens=array();
private $locationNode=array();
public function setTokens(array $tokens) {
$this->tokens = $tokens;
}
public function beginTraverse(array $nodes) {
$this->stack = [];
}
//add parent Attribute
public function enterNode(PhpParser\Node $node) {
if (!empty($this->stack)) {
$node->setAttribute('parent', $this->stack[count($this->stack)-1]);
}
$this->stack[] = $node;
}
public function leaveNode(PhpParser\Node $node) {
if(strstr($node->name,UNIQUE_STRING)){
$this->locationNode[] = $node;
}
array_pop($this->stack);
}
public function checkTokens(){
for($i = 0; $i<sizeof($this->tokens) ; $i++){
if (strstr($this->tokens[$i][1],UNIQUE_STRING)){
$this->locationTokens[] = $this->tokens[$i];
}
}
}
public function getLocationNode(){
return $this->locationNode;
}
public function getEscapeContextTokens(): array
{
return $this->locationTokens;
}
}
class CodeWrapper{
public $poc_code;
public $escape_line;
public $ast_tree;
public $node_token;
public $escape_token;
public $escape_context;
public $location_node;
public $escape_node;
public $template_engine;
function __construct($template_engine,$poc_code,array $node_token,$location_node,$stmts,$escape_line)
{ $this->template_engine = $template_engine;
$this->poc_code=$poc_code;
$this->node_token=$node_token;
$this->ast_tree = $stmts;
$this->escape_line = $escape_line;
$this->location_node = $location_node;
$this->identifyContext();
}
public function identifyContext(){
for ($i = 0; $i<sizeof($this->node_token); $i++){
if ($this->node_token[$i][2] == $this->escape_line or
$this->node_token[$i][2]+1 == $this->escape_line) {
$this->escape_token = $this->node_token[$i];
}
}
for ($i = 0; $i<sizeof($this->location_node); $i++){
if ($this->location_node[$i]->attributes['startLine'] == $this->escape_line) {
$this->escape_node = $this->location_node[$i];
}
}
if ($this->escape_token){
if (in_array($this->escape_token[0],COMMENTS_TOKENS)){
$this->escape_context = 'comments';
return ;
}
}
if (($this->escape_node instanceof PhpParser\Node\Expr && in_array(get_class($this->escape_node->getAttribute('parent')),COND_CLASS))){
$this->escape_context = 'cond';
return ;
}
if ($this->escape_node instanceof PhpParser\Node\Expr\Variable &&
($this->escape_node->getAttribute('parent') instanceof PhpParser\Node\Arg ||
($this->escape_node->getAttribute('parent') instanceof PhpParser\Node\Expr\ArrayDimFetch &&
($this->escape_node->getAttribute('parent')->getAttribute('parent') instanceof PhpParser\Node\Arg)||
($this->escape_node->getAttribute('parent')->getAttribute('parent')->getAttribute('parent') instanceof PhpParser\Node\Arg))
)){
$this->escape_context = 'function';
return ;
}
if ($this->escape_node instanceof PhpParser\Node\Expr\Variable && $this->escape_node->getAttribute('parent') instanceof PhpParser\Node\Expr\Ternary &&
$this->escape_node->getAttribute('parent')->getAttribute('parent') instanceof PhpParser\Node\Arg &&
in_array(get_class($this->escape_node->getAttribute('parent')->getAttribute('parent')->getAttribute('parent')),FUNCTION_CLASS) ||
($this->escape_node instanceof PhpParser\Node\Expr\Variable && (in_array(get_class($this->escape_node->getAttribute('parent')),SPECIAL_FUNCTION_CLASS)||
in_array(get_class($this->escape_node->getAttribute('parent')),FUNCTION_CLASS)) )){
$this->escape_context = 'function';
return ;
}
if ($this->escape_node instanceof PhpParser\Node\Expr\Variable &&
$this->escape_node->getAttribute('parent') instanceof PhpParser\Node\Expr\ArrayDimFetch &&
$this->escape_node->getAttribute('parent')->getAttribute('parent') instanceof PhpParser\Node\Stmt\Echo_){
$this->escape_context = 'echofunction';
return;
}
if ($this->escape_node instanceof PhpParser\Node\Expr\Variable && $this->escape_node->getAttribute('parent') instanceof PhpParser\Node\Expr\Assign){
$this->escape_context = 'assign';
return ;
}
if (($this->escape_node instanceof PhpParser\Node\Expr && in_array(get_class($this->escape_node->getAttribute('parent')),COND_CLASS))){
$this->escape_context = 'cond';
return ;
}
if ($this->escape_node instanceof PhpParser\Node\Stmt\Function_ || $this->escape_node instanceof PhpParser\Node\Stmt\Function_){
$this->escape_context = 'define';
return ;
}
$this->escape_context = 'UNKNOWN';
return ;
}
public function commentsContextWrapper(){
if (preg_match("/\/\*([\s\S]*)\*\//",$this->escape_token[1])){
return str_replace(UNIQUE_STRING, '*/' . EXEC_CODE . '/*', $this->poc_code);
}
elseif (preg_match("/\/\/(.*?)/",$this->escape_token[1])){
return str_replace(UNIQUE_STRING, 'a'.PHP_EOL . EXEC_CODE . '//' , $this->poc_code);
}
return 'BAD COMMENTS';
}
public function functionContextWrapper(){
$wrapper_code_left = 'a';
$wrapper_code_tmp = '';
$tmp_node = $this->escape_node;
while (array_key_exists('parent',$tmp_node->attributes) != FALSE){
$tmp_node = $tmp_node->getAttribute('parent');
if (in_array(get_class($tmp_node),FUNCTION_CLASS) || in_array(get_class($tmp_node), COND_CLASS) || in_array(get_class($tmp_node),SPECIAL_FUNCTION_CLASS)){
$wrapper_code_left = $wrapper_code_left.")";
$wrapper_code_tmp = $wrapper_code_tmp."(";
}
elseif (get_class($tmp_node) == 'PhpParser\Node\Expr\Ternary'){
if (in_array(get_class($tmp_node->cond->expr),FUNCTION_CLASS )){
$wrapper_code_left = $wrapper_code_left.")";
$wrapper_code_tmp = $wrapper_code_tmp."(";
}
}
}
if ($this->template_engine == 'latte'){
$wrapper_code_left = str_replace('a','',$wrapper_code_left);
if (strstr($this->poc_code,"clamp") || strstr($this->poc_code,"truncate")){
$wrapper_code_left = 'a,$b,$c//"'.$wrapper_code_tmp.PHP_EOL.$wrapper_code_left;
}
elseif (strstr($this->poc_code,"substr")){
$wrapper_code_left = 'a,1,1//"'.$wrapper_code_tmp.PHP_EOL.$wrapper_code_left;
}
elseif (strstr($this->poc_code,"frequency")){
$wrapper_code_left = 'a//"'.substr($wrapper_code_tmp,0,strlen($wrapper_code_tmp)-1).PHP_EOL.substr($wrapper_code_left,1,strlen($wrapper_code_left)-1);
}
else{
$wrapper_code_left = 'a//"'.$wrapper_code_tmp.PHP_EOL.$wrapper_code_left;
}
// $wrapper_code_left = 'a//"'.substr($wrapper_code_tmp,0,strlen($wrapper_code_tmp)-1).PHP_EOL.substr($wrapper_code_left,0,strlen($wrapper_code_left)-1);
$wrapper_code_left = $wrapper_code_left.";";
return str_replace(UNIQUE_STRING,$wrapper_code_left.EXEC_CODE.'/*"',$this->poc_code);
}
if (($this->template_engine == 'thinkphp') && (strstr($this->poc_code,"{in") || strstr($this->poc_code,"{notin")
|| strstr($this->poc_code,"{notempty"))){
$wrapper_code_left = $wrapper_code_left.")";
}
$wrapper_code_left = $wrapper_code_left.";";
$wrapper_code = $wrapper_code_left.EXEC_CODE."/*";
return str_replace(UNIQUE_STRING,$wrapper_code,$this->poc_code);
}
public function echofunctionContextWrapper(){
$wrapper_code_left = 'a';
$wrapper_code_tmp = '';
$wrapper_code_left = $wrapper_code_left.";";
$wrapper_code = $wrapper_code_left.EXEC_CODE."/*";
$tmp_node = $this->escape_node;
return str_replace(UNIQUE_STRING,$wrapper_code,$this->poc_code);
}
public function assignContextWrapper(){
$wrapper_code_left = 'a';
$wrapper_code_tmp = '';
$tmp_node = $this->escape_node;
$wrapper_code_left = $wrapper_code_left."=1";
while (array_key_exists('parent',$tmp_node->attributes) != FALSE){
$tmp_node = $tmp_node->getAttribute('parent');
if (in_array(get_class($tmp_node),FUNCTION_CLASS) || in_array(get_class($tmp_node), COND_CLASS) || in_array(get_class($tmp_node),SPECIAL_FUNCTION_CLASS)){
$wrapper_code_left = $wrapper_code_left.")";
$wrapper_code_tmp = $wrapper_code_tmp."(";
}
elseif (get_class($tmp_node) == 'PhpParser\Node\Expr\Ternary'){
if (in_array(get_class($tmp_node->cond->expr),FUNCTION_CLASS )){
$wrapper_code_left = $wrapper_code_left.")";
$wrapper_code_tmp = $wrapper_code_tmp."(";
}
}
}
if ($this->template_engine == 'thinkphp' && strstr($this->poc_code,"volist")){
$wrapper_code_left = $wrapper_code_left.")";
}
$wrapper_code = $wrapper_code_left.";".EXEC_CODE."/*";
if ($this->template_engine == 'latte'){
$wrapper_code_left = str_replace("=1","",$wrapper_code_left);
$wrapper_code_left = str_replace('a','',$wrapper_code_left);
$wrapper_code_left = 'a//"'.$wrapper_code_tmp.PHP_EOL.$wrapper_code_left.";";
$wrapper_code = $wrapper_code_left.EXEC_CODE.'/*"';
}
return str_replace(UNIQUE_STRING,$wrapper_code,$this->poc_code);
}
public function condContextWrapper(){
$wrapper_code_left = 'a';
$wrapper_code_tmp = '';
$tmp_node = $this->escape_node;
if (strstr($this->poc_code,"{foreach")){
$wrapper_code_left = ' as $b';
}
while (array_key_exists('parent',$tmp_node->attributes) != FALSE) {
$tmp_node = $tmp_node->getAttribute('parent');
if (in_array(get_class($tmp_node), FUNCTION_CLASS) || in_array(get_class($tmp_node), COND_CLASS)) {
$wrapper_code_left = $wrapper_code_left . ")";
$wrapper_code_tmp = $wrapper_code_tmp . "(";
}
}
if ($this->template_engine == 'latte'){
$wrapper_code_left = substr($wrapper_code_left,0,strlen($wrapper_code_left)-1);
$wrapper_code_left = 'a//"'.$wrapper_code_tmp.PHP_EOL.$wrapper_code_left;
$wrapper_code_left = $wrapper_code_left.";";
return str_replace(UNIQUE_STRING,$wrapper_code_left.EXEC_CODE.'/*"',$this->poc_code);
}
$wrapper_code_left = $wrapper_code_left.";";
$wrapper_code = $wrapper_code_left.EXEC_CODE."/*";
return str_replace(UNIQUE_STRING,$wrapper_code,$this->poc_code);
}
public function defineContextWrapper(){
$wrapper_code_left = 'a';
$wrapper_code_tmp = '';
if ($this->escape_node instanceof PhpParser\Node\Stmt\Function_){
$wrapper_code_left = $wrapper_code_left."(){};";
$wrapper_code = $wrapper_code_left.EXEC_CODE."function ";
}
return str_replace(UNIQUE_STRING,$wrapper_code,$this->poc_code);
}
public function getWrapperCode(): string
{
if ($this->escape_context!='UNKNOWN'){
$func_name = $this->escape_context.'ContextWrapper';
return $this->$func_name();
}
return 'Unknown Context!';
}
}
$lexer = new PhpParser\Lexer(array(
'usedAttributes' => array(
'comments', 'startLine', 'endLine', 'startTokenPos', 'endTokenPos'
)
));
$parser = (new PhpParser\ParserFactory)->create(PhpParser\ParserFactory::ONLY_PHP7, $lexer);
$visitor = new MyNodeVisitor();
$traverser = new PhpParser\NodeTraverser();
$traverser->addVisitor($visitor);
if ($argc == 5){
$filename = $argv[1];
$escape_line = $argv[2];
$template_engine = $argv[3];
$poc_code = $argv[4];
}
else{
die("Args Error!");
}
try {
$code = file_get_contents($filename);
$stmts = $parser->parse($code);
$visitor->setTokens($lexer->getTokens());
$stmts = $traverser->traverse($stmts);
$visitor->checkTokens();
$node_token = $visitor->getEscapeContextTokens();
$location_node = $visitor->getLocationNode();
$s = new CodeWrapper($template_engine,$poc_code,$node_token,$location_node,$stmts,$escape_line);
echo ($s->getWrapperCode());
} catch (PhpParser\Error $e) {
echo 'Parse Error: ', $e->getMessage();
}
| true |
9e4e1e6e1698264f5552c2afc06ba3a6b2937d53 | PHP | wkollernhm/openup | /protected/components/Sources/HebrewLinda.php | UTF-8 | 1,125 | 2.75 | 3 | [] | no_license | <?php
/**
* Hebrew names
*
* @author wkoller
*/
class HebrewLinda extends SourceComponent {
public function query($term) {
$response = array();
// find all fitting entries
$models_sourceHebrewLinda = SourceHebrewLinda::model()->findAllByAttributes(array(
'CleanScientific_Name' => $term
));
// cycle through result and handle each entry
foreach( $models_sourceHebrewLinda as $model_sourceHebrewLinda ) {
// check if we have a common name
if( empty($model_sourceHebrewLinda->HebrewSpecies) ) continue;
// add response
$response[] = array(
"name" => $model_sourceHebrewLinda->HebrewSpecies,
"language" => 'heb',
"geography" => NULL,
'period' => NULL,
"taxon" => $model_sourceHebrewLinda->CleanScientific_Name,
"references" => array("Hebrew Names"),
"score" => 100.0,
"match" => true,
);
}
return $response;
}
}
| true |
a1737d8595e690c7c6c860c51d832fd0bc284254 | PHP | skamz/healer-simc | /include/Generators/priest_dc.php | UTF-8 | 1,435 | 2.625 | 3 | [] | no_license | <?php
require_once(dirname(__DIR__, 2) . "/autoloader.php");
function startRotation($rotation) {
echo "add: " . $rotation . "<br>\n";
Database::getInstance()->query("insert ignore into priest_dc set rotation='{$rotation}'");
}
function fillStates($startPath) {
$firstState = [
"spells" => [
17 => 1,
13 => 1,
14 => 1,
11 => 0,
4 => 2,
],
"path" => [$startPath],
];
$stack = [$firstState];
do {
$currentPath = array_pop($stack);
foreach ($currentPath["spells"] as $spell => $allowCount) {
if ($allowCount == 0) {
continue;
}
$state = $currentPath;
$state["path"][] = $spell;
$state["spells"][$spell]--;
startRotation(implode(" ", $state["path"]));
array_push($stack, $state);
}
} while (!empty($stack));
}
function getBuffList() {
$firstState = [
"spells" => [
4 => 0,
5 => 10,
],
"path" => [],
];
$length = 11;
$stack = [$firstState];
$return = [];
do {
$currentPath = array_pop($stack);
foreach ($currentPath["spells"] as $spell => $allowCount) {
if ($allowCount == 0) {
continue;
}
$state = $currentPath;
$state["path"][] = $spell;
$state["spells"][$spell]--;
fillStates(implode(" ", $state["path"]));
if (count($state["path"]) <= $length) {
array_push($stack, $state);
}
}
} while (!empty($stack));
return $return;
}
getBuffList();
| true |
7745f2f537d4dcd9c86fd0227b12255e4a993211 | PHP | olvisdevalencia/intivefdvtest | /tests/Feature/rentBikesTest.php | UTF-8 | 2,193 | 2.5625 | 3 | [] | no_license | <?php
namespace Tests\Feature;
use Tests\TestCase;
use DateTime;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class rentBikesTest extends TestCase
{
/**
* Test to rent bikes by dates
*
* @return void
*/
public function testRentBikesByDate()
{
$requestParams = [
'inputBike' => 3,
'dateStart' => new DateTime('2018-06-01 09:00:00'),
'dateEnd' => new DateTime('2018-06-21 09:00:00')
];
$response = $this->call('POST', '/rentbydates', $requestParams);
$this->assertTrue($response->isOk(), "Wrong params");
}
/**
* Test to get should user view home
*
* @return void
*/
public function testHomeGet()
{
$response = $this->get('/');
$response->assertStatus(200);
$response->assertSeeText("Intive FDV test");
$response->assertSeeText("ACME RENTAL'S BIKES");
$response->assertSeeText("Please input the Quantity of bikes you may want to rent");
$response->assertSeeText("# Bikes");
$response->assertSeeText("Rent");
$response->assertSessionMissing('inputBike');
$response->assertViewIs("home");
$this->assertTrue($response->isOk(), "Wrong params");
}
/**
* Test to post and render a view to show information
*
* @return void
*/
public function testHomePost()
{
$requestParams = [
'inputBike' => 3,
];
$response = $this->call('POST', '/', $requestParams);
$response->assertSeeText("Intive FDV test");
$response->assertSeeText("ACME RENTAL'S BIKES");
$response->assertSeeText("Thanks to use ACME RENTAL'S BIKES service.");
$response->assertSeeText("Your bikes");
$response->original->getData()['bikes'];
$response->assertViewHas("bikes", !null);
$response->assertViewHas("byHour", !null);
$response->assertViewHas("byDay", !null);
$response->assertViewHas("byWeek", !null);
$response->assertViewIs("success");
$this->assertTrue($response->isOk(), "Wrong params");
}
}
| true |
6c7d4664777dfafb6e4da5c11b328ac620db33eb | PHP | pawlowaleks/yii_blog | /common/models/db/BaseArticle.php | UTF-8 | 1,035 | 2.671875 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
namespace common\models\db;
use Yii;
/**
* This is the model class for table "article".
*
* @property int $articleId
* @property string $title
* @property string $content
* @property int $userId
* @property string $createdAt
*/
class BaseArticle extends \yii\db\ActiveRecord
{
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'article';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['title', 'content', 'userId'], 'required'],
[['content'], 'string'],
[['userId'], 'integer'],
[['createdAt'], 'safe'],
[['title'], 'string', 'max' => 255],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'articleId' => 'Article ID',
'title' => 'Title',
'content' => 'Content',
'userId' => 'User ID',
'createdAt' => 'Created At',
];
}
}
| true |
fe729b547a706d4b859c181e605d454ff513b155 | PHP | cspray/yape-dbal | /src/AbstractEnumType.php | UTF-8 | 2,894 | 2.953125 | 3 | [
"MIT"
] | permissive | <?php declare(strict_types=1);
namespace Cspray\Yape\Dbal;
use Cspray\Yape\Exception\InvalidArgumentException;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\ConversionException;
use Doctrine\DBAL\Types\Type;
/**
* An implementation of a Doctrine DBAL Type that encapsulates common functionality required to persist an Enum.
*
* @package Cspray\Yape\Doctrine
* @license See LICENSE in source root
*/
abstract class AbstractEnumType extends Type {
/**
* Gets the SQL declaration snippet for a field of this type.
*
* @param mixed[] $fieldDeclaration The field declaration.
* @param AbstractPlatform $platform The currently used database platform.
*
* @return string
*/
public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform) {
return $platform->getVarcharTypeDeclarationSQL(['length' => 255]);
}
/**
* @param AbstractPlatform $platform
* @return bool
*/
public function requiresSQLCommentHint(AbstractPlatform $platform) {
return true;
}
/**
* @param mixed $value
* @param AbstractPlatform $platform
* @return mixed|null
* @throws ConversionException
*/
public function convertToDatabaseValue($value, AbstractPlatform $platform) {
$type = $this->getSupportedEnumType();
if (is_null($value)) {
return null;
} else if ($value instanceof $type) {
return $value->toString();
} else {
throw ConversionException::conversionFailedInvalidType($value, $this->getName(), [$this->getSupportedEnumType()]);
}
}
/**
* @param mixed $value
* @param AbstractPlatform $platform
* @return mixed|null
* @throws ConversionException
*/
public function convertToPHPValue($value, AbstractPlatform $platform) {
$type = $this->getSupportedEnumType();
if (is_null($value)) {
return null;
} else if (is_string($value)) {
try {
return ($type . '::valueOf')($value);
} catch (InvalidArgumentException $invalidArgumentException) {
throw ConversionException::conversionFailed($value, $this->getName());
}
} else if ($value instanceof $type) {
return $value;
} else {
throw ConversionException::conversionFailedInvalidType($value, $this->getName(), ['string']);
}
}
/**
* Return the fully qualified class name of the Enum that this Type is intended to represent.
*
* If the value returned from this is not the fully qualified class name of a type that responds to the methods as
* defined by the Enum interface unknown behavior will occur.
*
* @return string
*/
abstract protected function getSupportedEnumType() : string;
} | true |
efc4f7dfb83cf8e5ff543a96eacf7c45bda57de6 | PHP | lijias/web | /WWW/PSD1608/PHP/day09/upload02.php | UTF-8 | 754 | 2.609375 | 3 | [] | no_license | <?php
header('Content-Type:text/html;charset=utf-8');
include 'inc/common.function.php';
echo '<pre>';
print_r($_FILES);
echo '</pre>';
//上传的文件名称
/* echo $_FILES['pic']['name']; */
// 1. 判断上传是否为 0 成功
if($_FILES['pic']['error']==0){
//2.避免上传文件名称冲突,重命名唯一标识文件名称
// 2.1 获得上传文件名称
$filename = $_FILES['pic']['name'];
// 2.2 获得文件名称扩展名
$ext = exTension($filename);
// 2.3 获得重命名唯一标识的文件名
$filename =uuid().'.'.$ext;
//echo $filename;
//3 将临时目录和文件上传到目标位置上
move_uploaded_file($_FILES['pic']['tmp_name'],'upload/'.$filename);
}
| true |
23a6f26e5958104b1c7eeaac19bbc0039d48613f | PHP | anton-pribora/ap.admin | /src/components/ApCode/classes/Session/Session.php | UTF-8 | 1,966 | 2.78125 | 3 | [
"MIT"
] | permissive | <?php
/**
* @author Anton Pribora <anton.pribora@gmail.com>
* @copyright Copyright (c) 2018 Anton Pribora
* @license https://anton-pribora.ru/license/MIT/
*/
namespace ApCode\Session;
class Session
{
private $started;
public function append($path, $value)
{
if ($this->has($path)) {
$params = explode('.', $path);
eval('$_SESSION["'. join('"]["', $params) .'"][] = $value;');
} else {
$this->set($path, [$value]);
}
}
public function pop($path, $default = null)
{
$value = $this->get($path, $default);
$this->remove($path);
return $value;
}
public function get($path, $default = null)
{
$params = explode('.', $path);
return eval('return isset($_SESSION) && isset($_SESSION["'. join('"]["', $params) .'"]) ? $_SESSION["'. join('"]["', $params) .'"] : $default;');
}
public function set($path, $value)
{
if (!$this->id()) {
throw new \Exception('Please start session before use it!');
}
$params = explode('.', $path);
eval('$_SESSION["'. join('"]["', $params) .'"] = $value;');
}
public function has($path)
{
$params = explode('.', $path);
return eval('return isset($_SESSION) && isset($_SESSION["'. join('"]["', $params) .'"]);');
}
public function remove($path)
{
$params = explode('.', $path);
eval('if (isset($_SESSION)) {unset($_SESSION["'. join('"]["', $params) .'"]);}');
}
public function start($id = NULL)
{
if ($id) {
session_id($id);
}
if ($this->started) {
return true;
}
$this->started = true;
return session_start();
}
public function id()
{
return session_id();
}
public function destroy()
{
return session_destroy();
}
public function clear()
{
$_SESSION = [];
}
}
| true |
fda2a9edfccdcebfe396259b44af1c1cc8efc206 | PHP | LaunaKay/codingdojoserver | /Quotes/quotes.php | UTF-8 | 1,141 | 2.515625 | 3 | [] | no_license | <?php
session_start();
date_default_timezone_set('America/Los_Angeles');
require_once('new_connection.php');
//================ SET VARIABLES ==================
global $connection;
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Quotes!</title>
<meta name="description" content="Quotes database">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="stylesheet.css">
<link rel="icon" type = "image/png" href="LK_Favicon.png"
</head>
<body>
<div id = "body_div">
<form action = "delete.php" method="post">
<h1>Quotes Library</h1>
<?php $displayAll = "SELECT * FROM quotes.quotes ORDER BY timestamp desc";
$results = fetch($displayAll);
foreach($results as $value) {?>
<h5>"<?= $value['quote'] ?>"</h5>
<h6>~~ <?= $value['name'];?> ~~ <?= $value['timestamp'];?></h6>
<? } ?>
</form>
</div>
<div id="footer_div">
<a href="index.php">Back to write quote page</a>
</div>
</body>
</html> | true |
92fe3f0adb347fa061692930385429b80b8b7b4f | PHP | franksantos/webaluno | /app/Http/Requests/AlunoRequest.php | UTF-8 | 746 | 2.65625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
class AlunoRequest extends Request
{
/**
* 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 [
//
'turma' => 'required',['required'=>'O nome da turma é obrigatório'],
'nome' => 'required|min:5',['required'=>'O nome do Aluno é obrigatório', 'min'=>'O nome do aluno não poder ter menos de 5 caracteres'],
'cpf' => 'required'
];
}
}
| true |
be40f3cfd5b9485fba29817433deb1829e2821bc | PHP | Irina7Arina7Sillamae/MVC_2_model | /controller/Controller.php | UTF-8 | 1,277 | 2.8125 | 3 | [] | no_license | <?php
class Controller{
//Отрывается стартовая страница и выводит main.php
public static function StartSite(){
include 'view/main.php';
}
//Подключается Model нужно сходить за данными (getBookList)
public static function BookList() {
$booksList = Model::getBookList();
//и только потом отобразить это во view ( booksList передать его view )
include 'view/bookList.php';
}
//Отрабатывая bookOne нужно сходить за данными
// Смотрим модель, получаем по title книгу (проверяем если есть, то выдаем bookOne) во view
// bookOne заполняет верстку
public static function bookOne($title) {
$test = Model::getBook($title);
if ($test[0]==true) {
$book = $test[1];
include 'view/bookOne.php ';
}
else {
include 'view/error404.php';
}
}
//Отрабатывается вариант с ошибкой (если адрес не существующий)
public function error404(){
include 'view/error404.php';
}
}
?>
| true |
5435a25fea30d18757b476add980ee649d24d08b | PHP | Santzu-159/dwese | /practica1/cuatro.php | UTF-8 | 1,147 | 2.921875 | 3 | [] | no_license | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>Document</title>
</head>
<body>
<!--*............................................ Ejercicio 4 Cantidad de numeros primos a partir del número dado .........................................*-->
<div class='container mt-4'>
<h3 class='text-center'>Ejercicio 4 Cantidad de numeros primos a partir del número dado</h3>
<?php
echo "<br>".PHP_EOL;
$cantidad=1023;
$contDiv3=0;
for($cont=2;$cont<$cantidad;$cont++){
for($i=2;$i<$cont && $contDiv3==0;$i++){
if($cont%$i==0){
$contDiv3++;
}
}
if($contDiv3==0){
echo "$cont, ";
}else{
$contDiv3=0;
}
}
?>
</div>
</body>
</html> | true |
113aaec8a096aee26a2525f363e375d74c1ccc35 | PHP | sebcaillault/nains_mvc | /controller/coreController.php | UTF-8 | 492 | 2.65625 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: webuser1801
* Date: 17/05/2018
* Time: 10:37
*/
namespace nains\controller;
class coreController
{
protected $className;
public function showView($name, $variablesShoview)
{
// converti l'array assos en variable (utilisation ok dans ce cas mais faire attention
// cart dur de retrouver d'où viennent les variables
extract($variablesShoview);
require $this->className.'/view/'.$name.'.php';
}
} | true |
6787710dcc9628678d417ba982d55a586fa2e73c | PHP | 1995Everton/Arcano | /src/Controllers/Adm/Persistencias/PersistenciaDicas.php | UTF-8 | 3,161 | 2.609375 | 3 | [
"MIT"
] | permissive | <?php
namespace Arcanos\Enigmas\Controllers\Adm\Persistencias;
use Arcanos\Enigmas\Controllers\Banco;
use Arcanos\Enigmas\Controllers\RequestHandlerInterface;
use Respect\Validation\Exceptions\ValidationException;
use Respect\Validation\Validator as v;
class PersistenciaDicas extends Banco implements RequestHandlerInterface,PersistenceInterface
{
private $TABELA = "dicas";
private $SUCCESS_REDIRECT = "Location: index.php?pagina=tabela-dica";
private $ERROR_REDIRECT = "Location: index.php?pagina=form-dicas";
public function handle()
{
switch ($_GET['acao']){
case 'novo':
$this->novo();
break;
case 'editar':
$this->editar();
break;
case 'deletar':
$this->deletar();
break;
default:
header($this->ERROR_REDIRECT);
break;
}
}
public function validarPost()
{
try {
$this->getRegras()->assert($_POST);
return [
'dicas_enigmas_id' => $_POST['dicas_enigmas_id'],
'dica' => $_POST['Dica'],
'dicas_tipos_id' => $_POST['dicas_tipos_id'],
'categoria_dicas_id' => $_POST['categoria_dicas_id']
];
} catch (ValidationException $e) {
$errors = array_filter($e->findMessages($this->getTraducao()));
$this->allToast($errors);
header($this->urlConfigError());
exit();
}
}
public function novo()
{
$this->banco->insert($this->TABELA,$this->validarPost());
$this->toast("Dica Criado Com Sucesso!","Aviso","success");
header($this->SUCCESS_REDIRECT);
}
public function editar()
{
$this->banco->update($this->TABELA,$this->validarPost(),$this->getID());
$this->toast("Dica Atualizado Com Sucesso!","Aviso","success");
header($this->SUCCESS_REDIRECT);
}
public function deletar()
{
$query = $this->banco->delete($this->TABELA,$this->getID());
$this->deleteStatus($query);
}
public function getID()
{
return ['id_dicas' => $_GET['id']];
}
public function getRegras()
{
return v::key('Dica', v::stringType()->notEmpty()->noWhitespace()->length(3, 32))
->key('dicas_enigmas_id',v::numeric()->notEmpty())
->key('dicas_tipos_id',v::numeric()->notEmpty())
->key('categoria_dicas_id',v::numeric()->notEmpty());
}
public function getTraducao()
{
return [
'notEmpty' => 'O Campo {{name}} nao pode estar em branco',
'length' => 'O Campo {{name}} deve conter entre 3 a 32 caracteres',
'noWhitespace' => 'O Campo {{name}} não pode ter espaços em branco',
'numeric' => 'O Campo {{name}} deve ser um tipo numerico'
];
}
public function urlConfigError()
{
if(isset($_GET['id'])){
return $this->ERROR_REDIRECT."&id=".$_GET['id'];
}else{
return $this->ERROR_REDIRECT;
}
}
} | true |
bbbffc39fcbffcb6491dd8b2e17aed0a5f3859d1 | PHP | tkouleris/CrudPanel | /src/Services/ControllerService.php | UTF-8 | 1,954 | 2.765625 | 3 | [] | no_license | <?php
namespace tkouleris\CrudPanel\Services;
use tkouleris\CrudPanel\File\FileCreator;
use tkouleris\CrudPanel\File\FileDeleter;
use tkouleris\CrudPanel\Repositories\Interfaces\IControllerFile;
class ControllerService
{
protected $file_creator;
protected $R_ControllerFile;
protected $file_deleter;
/**
* ControllerService constructor.
* @param FileCreator $file_creator
* @param FileDeleter $file_deleter
* @param IControllerFile $R_ControllerFile
*/
public function __construct(FileCreator $file_creator, FileDeleter $file_deleter, IControllerFile $R_ControllerFile)
{
$this->file_creator = $file_creator;
$this->file_deleter = $file_deleter;
$this->R_ControllerFile = $R_ControllerFile;
}
/** creates a controller
* @param $controller_name
* @return array
*/
public function create($controller_name)
{
$controller_name = $controller_name.'Controller';
$controller_output = $this->file_creator->controller( $controller_name );
$message = $controller_output['message'];
$ins_controller_args = array();
$ins_controller_args['ControllerFileFilename'] = $controller_name;
$controller_record = $this->R_ControllerFile->create($ins_controller_args);
$output = array();
$output["message"] = $message;
$output["data"] = $controller_record;
return $output;
}
public function list($filter = null)
{
return $controllerFiles = $this->R_ControllerFile->list($filter);
}
/**
* Deletes a controller
* @param $controller_file_id
* @return mixed
*/
public function delete($controller_file_id)
{
$ControllerFileRecord = $this->R_ControllerFile->delete($controller_file_id);
$this->file_deleter->controller($ControllerFileRecord->ControllerFileFilename);
return $ControllerFileRecord;
}
}
| true |
d638ad6ee6b5c219d20c9a461a14dcca66bebc53 | PHP | pavelwebdeveloper/cs313-php | /web/team_activities/team_activity7/welcome_page.php | UTF-8 | 462 | 2.8125 | 3 | [] | no_license | <?php
// Get the database connection file
require("../../library/dbConnection.php");
$db = dbConnection();
// Start the session
session_start();
if(!($_SESSION['loggedin'])){header('Location: sign-in_page.php');}
?>
<!DOCTYPE html>
<html lang="en-us">
<head>
<title>Welcome Page</title>
</head>
<body>
<main>
<?php
if (isset($_SESSION['userData'])) {
echo "Welcome " . $_SESSION['userData']['username'];
}
?>
</main>
</body>
</html> | true |
eedf1422c5886d3a351f55aef499f227dd7abfeb | PHP | HasanKarasahin/heryerkaktus | /Views/AbstractView.php | UTF-8 | 435 | 2.90625 | 3 | [] | no_license | <?php
abstract class AbstractView
{
static function getTemplateStatic($data)
{
return $data;
}
abstract function getTemplate($data = null);
static function getTemplateFromFile($fileName, $fileExt = '.html')
{
$fileContent = file_get_contents('assets' . DIRECTORY_SEPARATOR . 'static' . DIRECTORY_SEPARATOR . $fileName . $fileExt);
return self::getTemplateStatic($fileContent);
}
} | true |
e7ad97652f9e864864d3b44e1409808bc37ecee2 | PHP | olasco-ship/emr2 | /includes/category.php | UTF-8 | 1,748 | 2.984375 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: FEMI
* Date: 8/18/2017
* Time: 10:25 PM
*/
class Category extends DatabaseObject
{
protected static $table_name = "category";
protected static $db_fields= array('id', 'sync', 'name','created');
public $id;
public $sync;
public $name;
public $created;
public $products;
public static function find_all_order_by_name(){
return static::find_by_sql("SELECT * FROM " .static::$table_name. " ORDER BY name" );
}
public static function get_category(){
$finds = self::find_all();
foreach($finds as $find){
echo $find->name. "<br/>";
}
}
public function get_products(){
if(isset($this->products))return $this->products;
$this->products = Product::find_by_sql("SELECT * FROM " .Product::$table_name. " WHERE category_id = {$this->id} " );
return $this->products;
}
public static function get_products_for_category($id = 0){
$prcs = Product::find_by_sql("SELECT * FROM " .Product::$table_name. " WHERE category_id = {$id} "." ORDER BY created DESC" );
return $prcs;
//"SELECT * FROM " .static::$table_name. " ORDER BY created DESC"
}
public static function create_table(){
$sql = 'CREATE TABLE IF NOT EXISTS ' . Category::$table_name . '(' .
'id INT(11) NOT NULL AUTO_INCREMENT, ' .
'sync VARCHAR(20) NOT NULL, ' .
'name VARCHAR(50) NOT NULL, ' .
'created DATETIME NOT NULL, ' .
'PRIMARY KEY(id), ' .
'UNIQUE KEY(name))';
Category::run_script($sql);
}
// Common Database Methods in the Parent class(DatabaseObject)
}
Category::create_table();
| true |
265d53138392532901aa4f9d47eca4c02e987ce7 | PHP | mustafaozcelik/school | /repository/studentRepository.php | UTF-8 | 2,815 | 2.890625 | 3 | [] | no_license | <?php
function getAllStudents(){
include("dbconnection.php"); //veritabanını ekliyoruz
//Tüm ögrencilerin listesini çekiyoruz
$sql="SELECT * FROM student";
$stmt=$dbconnection->prepare($sql);
if($stmt){
$stmt->execute();
$result=$stmt->get_result();
return $result;
}else{
echo "Database error".$dbconnection->error;
}
}
function deleteStudentById($studentId){
include("dbconnection.php"); //veritabanını ekliyoruz
//ögrenci tablosundan veri silmek için kullanıcagımız query
$sql="delete from student where id=?";
$stmt=$dbconnection->prepare($sql);
if($stmt){
$stmt->bind_param( "i" ,$studentId);
$stmt->execute();
}else{
echo "Database error".$dbconnection->error;
}
}
function UpdateStudentById($studentId){
include("dbconnection.php"); //veritabanını ekliyoruz
$sql="Update student set name='$name',surname='$surname',tcno='$tcno' ,username='$username',password='$password'";
$stmt=$dbconnection->prepare($sql);
if($stmt){
$stmt->bind_param( "i" ,$studentId);
$stmt->execute();
}else{
echo "Database error".$dbconnection->error;
}
}
function addStudent($name,$surname,$TCNO,$username,$password){
include("dbconnection.php");
$sql="insert into student(name,surname,tcno,username,password) values(?,?,?,?,?)";
$stmt=$dbconnection->prepare($sql);
if($stmt){
$stmt->bind_param("sssss",$name,$surname,$TCNO,$username,$password);
$stmt->execute();
//$result=$stmt->get_result();
//var_dump($result);
}else{
echo "Database error".$dbconnection->error;
}
function getStudentByUsernameAndPassword($username,$password){
include("dbconnection.php");
$sql="SELECT * FROM student WHERE username=? and password=?";
$stmt=$dbconnection->prepare($sql);
if($stmt){
$stmt->bind_param("ss",$username,$password);
$stmt->execute();
$result=$stmt->get_result();
//Eğer sorgulanan kullanıcı adı var ise bir oturum oluşturup home.php ye yönlendiriyoruz
//Yok ise hata verdiriyoruz.
if($result->num_rows == 1){
$rows=$result->fetch_all(MYSQLI_ASSOC);
return $rows;
}else{
return NULL;
}
}
else{
echo "Database error".$dbconnection->error;
}
}
}
?> | true |
5aed42968f95db688469b25d8337a411ee245f99 | PHP | caiocosta1097/Pops-Web-FTP | /cms/model/DAO/eventosDAO.php | UTF-8 | 4,972 | 3.609375 | 4 | [] | no_license | <?php
class EventoDAO{
//Iniciando a varíavel em null para não haver erro
private $path_local;
//Atributo que será instânciado para fazer a conexão
private $conexao;
//Método construct é chamado assim que a classe é instânciada
public function __construct(){
//Variável que recebe a variável de sessão
$path_local = $_SESSION['path_local'];
//Importando a classe de conexao para fazer a instância
require_once "$path_local/cms/model/DAO/conexao.php";
//instanciando a classe de conexão
$this->conexao = new Conexao();
}
//método que insere o evento no banco
//passando como parametro uma variável do tipo Evento
public function insertEvento(Eventos $eventos){
//Inserindo no banco
$insertSql = "INSERT INTO tbl_eventos (titulo, descricao, localidade, dt_evento, status)
VALUES('".$eventos->getTitulo()."', '".$eventos->getDescricao()."','".$eventos->getLocalidade()."', '".$eventos->getDataEvento()."', '".$eventos->getStatus()."')";
//Método que faz a conexão com o banco
$conn = $this->conexao->connectDatabase();
//executando o script de insert no banco
if(!$conn->query($insertSql)){
echo "Erro no script de insert";
}
//fechando a Conexao
$this->conexao->closeDatabase();
}
//Função que deleta um evento do banco
public function deleteEvento($idEvento){
//script delete
$deleteSql = "DELETE FROM tbl_eventos WHERE id_eventos=".$idEvento;
//Recebendo a método que faz a conexão com o banco de dados
$conn = $this->conexao->connectDatabase();
//Executa o script de delete no banco
if(!$conn->query($deleteSql)){
echo "Erro no script de delete";
}
//fechando a conexao com o banco
$this->conexao->closeDatabase();
}
//Função para atualizar um evento no banco
public function updateEvento(Eventos $eventos, $idEventos){
//script do update
$updateSql = "UPDATE tbl_eventos
SET titulo = '".$eventos->getTitulo()."',
descricao = '".$eventos->getDescricao()."',
localidade = '".$eventos->getLocalidade()."',
dt_evento = '".$eventos->getDataEvento()."',
status = '".$eventos->getStatus()."'
WHERE id_eventos=".$idEventos;
$conn = $this->conexao->connectDatabase();
if(!$conn->query($updateSql)){
echo "Erro no script de update";
}
$this->conexao->closeDatabase();
}
//listar todos os eventos do banco
public function selectAllEventos(){
//script dos selects
$selectAllSql = "SELECT * FROM tbl_eventos WHERE status = 1 ORDER BY id_eventos DESC";
//Método que faz a conexão com o banco
$conn = $this->conexao->connectDatabase();
//executando o select
$select = $conn->query($selectAllSql);
//Contador iniciando em 0
$cont = 0;
//Loop que coloca todo os eventos em um rs
while($rsEventos = $select->fetch(PDO::FETCH_ASSOC)){
//Array de dados do tipo Evento
$eventos[] = new Eventos();
//Setando os valores do obj
$eventos[$cont]->setIdEventos($rsEventos['id_eventos']);
$eventos[$cont]->setTitulo($rsEventos['titulo']);
$eventos[$cont]->setDescricao($rsEventos['descricao']);
$eventos[$cont]->setLocalidade($rsEventos['localidade']);
$eventos[$cont]->setDataEvento($rsEventos['dt_evento']);
$eventos[$cont]->setStatus($rsEventos['status']);
//incrementando o cont
$cont += 1;
}
//Fechando a conexão com o banco de dados
$this->conexao->closeDatabase();
//retornando o array
return $eventos;
}
//Método que busca um evento através do ID
public function selectByIdEvento($idEvento){
//script para buscar um evento por ID
$selectByIdEventoSql = "SELECT * FROM tbl_eventos WHERE id_eventos =".$idEvento;
//método que faz a conexão com o banco
$conn = $this->conexao->connectDatabase();
//executando o script no banco
$select = $conn->query($selectByIdEventoSql);
//Verifica se o rs recebeu o registro
if($rsEventos = $select->fetch(PDO::FETCH_ASSOC)){
//Instância da classe eventos
$eventos = new Eventos();
//Setando os valores do obj
$eventos->setIdEventos($rsEventos['id_eventos']);
$eventos->setTitulo($rsEventos['titulo']);
$eventos->setDescricao($rsEventos['descricao']);
$eventos->setLocalidade($rsEventos['localidade']);
$eventos->setDataEvento($rsEventos['dt_evento']);
$eventos->setStatus($rsEventos['status']);
}
//fechando a conexao com o banco de dados
$this->conexao->closeDatabase();
//Retornando o obj
return $eventos;
}
}
?>
| true |
c3023b7fbcf135b35316678b1d432da72fcb6a1f | PHP | DimitriRomano/FoodLocation | /php/signup.php | UTF-8 | 5,064 | 2.625 | 3 | [] | no_license |
<?php
require 'dbconnect.php';
require 'functions.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
// Load Composer's autoloader
require '../vendor/autoload.php';
if (isset($_POST['submit_signup'])) {
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$passwordRepeat = $_POST['passwordRepeat'];
if (!filter_var($email , FILTER_VALIDATE_EMAIL) && !preg_match("/^[a-zA-Z0-9]*$/",$username)) {
header("Location: sign_in.php?error=invalideusername");
exit();
}elseif (!filter_var($email , FILTER_VALIDATE_EMAIL)) {
header("Location: sign_in.php?error=invalidemail&username=".$username);
exit();
}elseif (!preg_match("/^[a-zA-Z0-9]*$/",$username)) {
header("Location: sign_in.php?error=invalideusername&email=".$email);
exit();
}elseif ($password !== $passwordRepeat) {
header("Location: sign_in.php?error=passwordcheckusername=".$username."&email=".$email);
exit();
}else {
$sql = "SELECT username FROM users WHERE username=?";
$stmt = mysqli_stmt_init($dbconnect);
if (!mysqli_stmt_prepare($stmt,$sql)) {
header("Location: sign_in.php?error=sqlerror1");
exit();
}else {
mysqli_stmt_bind_param($stmt,"s",$username);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$resultCheck = mysqli_stmt_num_rows($stmt);
if ($resultCheck > 0) {
header("Location: sign_in.php?error=usertaken&email=".$email);
exit();
}else {
$sql = "INSERT INTO users (username , email , password, confirmation_token )
VALUES (?,?,?,?)";
$stmt = mysqli_stmt_init($dbconnect);
if (!mysqli_stmt_prepare($stmt , $sql)) {
header("Location: sign_in.php?error=sqlerror2");
exit();
}else {
$hashedPwd = password_hash($password , PASSWORD_BCRYPT);
$token = str_random(60);
mysqli_stmt_bind_param($stmt , "ssss" , $username ,$email , $hashedPwd,$token);
mysqli_stmt_execute($stmt);
$user_id = mysqli_insert_id($dbconnect);
//Create a new PHPMailer instance
$mail = new PHPMailer;
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
// SMTP::DEBUG_OFF = off (for production use)
// SMTP::DEBUG_CLIENT = client messages
// SMTP::DEBUG_SERVER = client and server messages
$mail->SMTPDebug = 2;
//Set the hostname of the mail server
$mail->Host = gethostbyname('smtp.gmail.com');
// use
// $mail->Host = gethostbyname('smtp.gmail.com');
// if your network does not support SMTP over IPv6
//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
$mail->Port = 587;
//Set the encryption mechanism to use - STARTTLS or SMTPS
$mail->SMTPSecure = 'tls';
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
//Username to use for SMTP authentication - use full email address for gmail
$mail->Username = 'foodlocationrest@gmail.com';
//Password to use for SMTP authentication
$mail->Password = 'Azerty2019';
//Set who the message is to be sent from
$mail->setFrom('foodlocationrest@gmail.com', 'First Last');
//Set an alternative reply-to address
$mail->addAddress($email, 'First Last');
//Set who the message is to be sent to
//Set the subject line
// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Confirmation de votre compte';
$mail->Body = "Afin de valider votre compte merci de cliquer sur ce lien
\n\n http://localhost/version0/imediapixel.com/templates/warungpring/php/confirm.php?idusers=$user_id&token=$token";
$mail->AltBody = 'Confirmation de votre compte';
//Attach an image file
//send the message, check for errors
if (!$mail->send()) {
echo 'Mailer Error: '. $mail->ErrorInfo;
} else {
echo 'Message sent!';
//Section 2: IMAP
//Uncomment these to save your message in the 'Sent Mail' folder.
#if (save_mail($mail)) {
# echo "Message saved!";
#}
}
//Section 2: IMAP
//IMAP commands requires the PHP IMAP Extension, found at: https://php.net/manual/en/imap.setup.php
//Function to call which uses the PHP imap_*() functions to save messages: https://php.net/manual/en/book.imap.php
//You can use imap_getmailboxes($imapStream, '/imap/ssl', '*' ) to get a list of available folders or labels, this can
//be useful if you are trying to get this working on a non-Gmail IMAP server.
function save_mail($mail)
{
//You can change 'Sent Mail' to any other folder or tag
$path = '{imap.gmail.com:993/imap/ssl}[Gmail]/Sent Mail';
//Tell your server to open an IMAP connection using the same username and password as you used for SMTP
$imapStream = imap_open($path, $mail->Username, $mail->Password);
$result = imap_append($imapStream, $path, $mail->getSentMIMEMessage());
imap_close($imapStream);
return $result;
}
exit();
}
}
}
}
mysqli_stmt_close($stmt);
mysqli_close($dbconnect);
}
?>
| true |
ccfba51c07a7ff174ba04a4b485a85510da27164 | PHP | AlfinSug/Bakery-Shop | /tokoroti/pegawai.php | UTF-8 | 3,256 | 2.640625 | 3 | [] | no_license | <?php include('conn_pegawai.php');
if (isset($_GET['edit'])) {
$idpgw = $_GET['edit'];
$edit_state = true;
$rec = mysqli_query($db, "SELECT * FROM pegawai WHERE id_pgw=$idpgw");
$record = mysqli_fetch_array($rec);
$name_pgw = $record['nama_pgw'];
$alamatPgw = $record['alamat_pgw'];
$notelpPgw = $record['notelp_pgw'];
$idpgw = $record['id_pgw'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Pegawai</title>
<link rel="stylesheet" href="style_pegawai.css">
</head>
<body>
<div class="header">
<span><a href="home.php"><img src="img/back.png" alt=""></a></span>
<span><h2>Data Pegawai</h2></span>
</div>
<div class="container">
<div class="form-input">
<form method="post" action="conn_pegawai.php">
<input type="hidden" name="id_pgw" value="<?php echo $idpgw; ?>">
<div class="input-group">
<label>Nama Pegawai</label>
<input type="text" name="nama_pgw" value="<?php echo $name_pgw; ?>">
</div>
<div class="input-group">
<label>Alamat Pegawai</label>
<input type="text" name="alamat_pgw" value="<?php echo $alamatPgw; ?>">
</div>
<div class="input-group">
<label>No. Telpon Pegawai</label>
<input type="text" name="notelp_pgw" value="<?php echo $notelpPgw; ?>">
</div>
<div class="input-group">
<?php if ($edit_state == false): ?>
<button type="submit" name="simpan" class="btn">Simpan</button>
<?php else: ?>
<button type="submit" name="ubah" class="btn">Ubah</button>
<?php endif ?>
</div>
</form>
</div>
<div class="table-data">
<table>
<thead>
<tr>
<th>Nama Pegawai</th>
<th>Alamat Pegawai</th>
<th>No. Telpon Pegawai</th>
<th colspan="2">Aksi</th>
</tr>
</thead>
<tbody>
<?php while ($row = mysqli_fetch_array($results)) { ?>
<tr>
<td><?php echo $row['nama_pgw']; ?></td>
<td><?php echo $row['alamat_pgw']; ?></td>
<td><?php echo $row['notelp_pgw']; ?></td>
<td><a href="pegawai.php?edit=<?php echo $row['id_pgw']; ?>" class="edit-btn">Edit</a></td>
<td><a href="conn_pegawai.php?del=<?php echo $row['id_pgw']; ?>" class="del-btn">Delete</a></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
</body>
</html> | true |
59cf8b66a5ca8ed8bb50ad8f4b127ac40162b417 | PHP | samdark/email | /src/parser/tokens/Header.php | UTF-8 | 2,231 | 2.796875 | 3 | [
"MIT"
] | permissive | <?php
/**
* @copyright Copyright (c) 2017 Dmitriy Bashkarev
* @license https://github.com/bashkarev/email/blob/master/LICENSE
* @link https://github.com/bashkarev/email#readme
*/
namespace bashkarev\email\parser\tokens;
trait Header
{
/**
* @var bool
*/
protected $allowedHeader = true;
/**
* @param string $line
* @return bool
*/
protected function parseHeader($line)
{
if (
$this->allowedHeader === false
|| strpos($line, ':') === false
) {
return false;
}
list($field, $value) = $this->lineHeader($line);
$i = ftell($this->handle);
while (feof($this->handle) === false) {
$line = $this->nextLine();
if (
($this->allowedHeader = ($line !== '')) === false
|| ($line[0] !== "\t" && $line[0] !== ' ')
) {
break 1;
}
$i = ftell($this->handle);
$value .= ' ' . ltrim($line);
}
fseek($this->handle, $i);
$value = $this->decodeMimeHeader($value);
$this->setToken(self::T_HEADER, [$field, $value]);
return true;
}
/**
* @param int $type
* @param mixed $value
*/
protected function bindHeader($type, $value)
{
if ($type === self::T_HEADER) {
$this->context()->setHeader($value[0], $value[1]);
}
}
/**
* @param $str
* @return string
*/
protected function decodeMimeHeader($str)
{
if (strpos($str, '=?') === false) {
return $str;
}
$value = mb_decode_mimeheader($str);
if (strpos($str, '?Q') !== false) {
$value = str_replace('_', ' ', $value);
}
return $value;
}
/**
* @param string $line
* @return array
*/
private function lineHeader($line)
{
$data = explode(':', $line);
$filed = $data[0];
if (isset($data[2])) {
unset($data[0]);
$value = implode(':', $data);
} else {
$value = $data[1];
}
return [
rtrim($filed),
ltrim($value)
];
}
} | true |
3a19dd4b373f496a13c28b4e86d6dedb762d66cd | PHP | bcen/silex-dispatcher | /src/SDispatcher/Common/DeclarativeResourceOption.php | UTF-8 | 2,594 | 2.890625 | 3 | [
"MIT"
] | permissive | <?php
namespace SDispatcher\Common;
/**
* Used to read resource option in a more declarative way.
*/
final class DeclarativeResourceOption extends AbstractResourceOption
{
/**
* Used to read private method/property.
* @var \ReflectionObject
*/
private $reflector;
/**
* The target object to read.
* @var mixed
*/
private $classOrObj;
/**
* The optional prefix for reading option.
* @var string
*/
private $prefix = '';
/**
* Used to cache the options.
* @var array
*/
private $cache = array();
/**
* {@inheritdoc}
*/
public function setTarget($classOrObj, $method = null)
{
$this->classOrObj = $classOrObj;
if (is_string($classOrObj) && class_exists($classOrObj)) {
$this->reflector = new \ReflectionClass($classOrObj);
} elseif (is_object($classOrObj)) {
$this->reflector = new \ReflectionObject($classOrObj);
}
}
/**
* Sets the prefix of all option attribute.
* @param string $prefix
*/
public function setPrefix($prefix)
{
$this->prefix = $prefix;
}
/**
* {@inheritdoc}
*/
protected function tryReadOption($name, &$out, $default = null)
{
$success = false;
$name = $this->prefix . $name;
$out = $default;
if (!$this->classOrObj) {
return false;
}
if (isset($this->cache[$name])
|| array_key_exists($name, $this->cache)
) {
$out = $this->cache[$name];
$success = true;
} elseif ($this->reflector->hasProperty($name)) {
$out = $this->readFromProperty($name);
$success = true;
$this->cache[$name] = $out;
} elseif ($this->reflector->hasMethod($name)) {
$out = $this->readFromMethod($name);
$success = true;
$this->cache[$name] = $out;
}
return $success;
}
/**
* {@inheritdoc}
*/
protected function tryWriteOption($name, $value)
{
$name = $this->prefix . $name;
$this->cache[$name] = $value;
}
private function readFromProperty($name)
{
$prop = $this->reflector->getProperty($name);
$prop->setAccessible(true);
return $prop->getValue($this->classOrObj);
}
private function readFromMethod($name)
{
$method = $this->reflector->getMethod($name);
$method->setAccessible(true);
return $method->invoke($this->classOrObj);
}
}
| true |
38cff35bdf83f5821f66d2863d152da75ef33c3e | PHP | andresJ12345/storeGames | /apps/model/juegos.php | UTF-8 | 1,036 | 2.828125 | 3 | [] | no_license | <?php
require_once 'conexion.php';
class Juegos {
static public function agregarJuegos($tabla,$datos){
$stmt = conexion::conectar()->prepare("INSERT INTO $tabla (tituloJuego,descripcion,id_categoria,rutaFoto) VALUES (:tituloJuego,:descripcion,:id_categoria,:rutaFoto)");
$stmt -> bindParam(":tituloJuego",$datos['nombreJuego'],PDO::PARAM_STR);
$stmt -> bindParam(":descripcion",$datos['descripcion'],PDO::PARAM_STR);
$stmt -> bindParam(":id_categoria",$datos['categoria'],PDO::PARAM_STR);
$stmt -> bindParam(":rutaFoto",$datos['ruta'],PDO::PARAM_STR);
if($stmt->execute()){
return "ok";
}else{
return "error";
}
$stmt ->close();
$stmt = null;
}
static public function MostrarJuegos($tabla){
$stmt = conexion::conectar()->prepare("SELECT * FROM $tabla");
$stmt -> execute();
return $stmt->fetchAll();
$stmt ->close();
$stmt=null;
}
}
| true |
48b1e32374b0c0efa10d926101559b4a7154ef26 | PHP | andres-oderlogica/Nomina | /bin/db/base.php | UTF-8 | 2,042 | 2.546875 | 3 | [] | no_license | <?php
include_once Config::$home_lib.'adodb5'.Config::$ds.'adodb.inc.php';
class base
{
private $server;
private $user;
private $password;
private $database;
private $sql_instruction;
protected $adodb;
public $rs;
function __construct()
{
$this->adodb = ADONewConnection('mysqli');
}
public function getADOdb()
{
return $this->adodb;
}
function debug_on($value)
{
$this->adodb->debug = $value;
}
function setup($server, $user, $pass, $db)
{
$this->adodb->connect($server, $user, $pass, $db);
}
function dosql($sql_instruction, $params) //previene sql injection
{
$this->rs = $this->adodb->Execute($sql_instruction, $params);
return($this->rs);
}
function dosql1($sql_instruction)
{
$this->rs = $this->adodb->Execute($sql_instruction);
return($this->rs);
}
function get_data($sql, $field='')
{
$rs = $this->dosql($sql);
// print_r($rs);
if ($field == '')
{
reset($rs->fields);
$res = current($rs->fields);
}
else
$res = $rs->fields[$field];
// die("res - $res");
return($res);
}
function Insert($table, $record, $where=false)
{
$this->adodb->AutoExecute($table, $record, 'INSERT', $where);
}
function Update($table, $record, $where=false)
{
$this->adodb->AutoExecute($table, $record,'UPDATE', $where);
}
function InsUpd($table, $record, $key, $autoquote=false)
{
$this->adodb->Replace($table, $record, $key, $autoquote);
}
function ErrorNo()
{
return($this->adodb->ErrorNo());
}
function ErrorMsg()
{
return($this->adodb->ErrorMsg());
}
function record_style($style)
{if ($style=='fields') $this->adodb->SetFetchMode(ADODB_FETCH_ASSOC);
if ($style=='numbers') $this->adodb->SetFetchMode(ADODB_FETCH_NUM);
if ($style=='both') $this->adodb->SetFetchMode(ADODB_FETCH_BOTH);
if ($style=='default') $this->adodb->SetFetchMode(ADODB_FETCH_DEFAULT);
}
}
?>
| true |
a0d6cf279aeaecd1a1976fd555cc2c366dc6b24c | PHP | bungle-suit/framework | /tests/Import/ExcelReader/SectionBoundaryTest.php | UTF-8 | 5,039 | 2.703125 | 3 | [] | no_license | <?php
declare(strict_types=1);
namespace Bungle\Framework\Tests\Import\ExcelReader;
use Bungle\Framework\Import\ExcelReader\ExcelReader;
use Bungle\Framework\Import\ExcelReader\SectionBoundary;
use Mockery;
use Mockery\Adapter\Phpunit\MockeryTestCase;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
class SectionBoundaryTest extends MockeryTestCase
{
private Spreadsheet $sheet;
private ExcelReader $reader;
public function test(): void
{
$reader = Mockery::Mock(ExcelReader::class);
[$startHit, $endHit] = [0, 0];
$isStart = function (ExcelReader $r) use ($reader, &$startHit) {
self::assertSame($r, $reader);
$startHit ++;
return false;
};
$isEnd = function (ExcelReader $r) use ($reader, &$endHit) {
self::assertSame($r, $reader);
$endHit ++;
return true;
};
$b = new SectionBoundary($isStart, $isEnd);
self::assertFalse($b->isSectionStart($reader));
self::assertEquals(1, $startHit);
self::assertEquals(0, $endHit);
self::assertTrue($b->isSectionEnd($reader));
self::assertEquals(1, $endHit);
}
protected function setUp(): void
{
parent::setUp();
$this->sheet = new Spreadsheet();
$this->reader = new ExcelReader($this->sheet);
}
public function testSheetNameIs(): void
{
$f = SectionBoundary::sheetNameIs('foo', 'bar');
// current sheet not specific
$this->reader->getSheet()->setTitle('foobar');
self::assertFalse($f($this->reader));
// current sheet is one of specific
$this->reader->getSheet()->setTitle('bar');
self::assertTrue($f($this->reader));
}
public function testColIs(): void
{
$this->reader->getSheet()->setCellValue('B2', 'bar');
$f = SectionBoundary::colIs(['foo', 'bar'], 'B');
// cell not one of keywords
self::assertFalse($f($this->reader));
// cell is one of keywords.
$this->reader->nextRow();
self::assertTrue($f($this->reader));
}
public function testRowAfter(): void
{
$f = SectionBoundary::rowAfter(10);
// row before 10
self::assertFalse($f($this->reader));
$this->reader->setRow(9);
self::assertFalse($f($this->reader));
// row equals 10
$this->reader->setRow(10);
self::assertFalse($f($this->reader));
// row after 10
$this->reader->setRow(11);
self::assertTrue($f($this->reader));
}
public function testRowIs(): void
{
$f = SectionBoundary::rowIs(3);
$this->reader->setRow(2);
self::assertFalse($f($this->reader));
$this->reader->nextRow();
self::assertTrue($f($this->reader));
$this->reader->nextRow();
self::assertFalse($f($this->reader));
}
public function testIsEmptyRow(): void
{
$sheet = $this->reader->getSheet();
$f = SectionBoundary::isEmptyRow(2);
// row after the last data row, no new cell created
$sheet->setCellValue('A10', '');
self::assertEquals(10, $sheet->getHighestDataRow());
$this->reader->setRow(20);
self::assertTrue($f($this->reader));
self::assertEquals(10, $sheet->getHighestDataRow());
// row before the last data row, but empty, no new cell created
$this->reader->setRow(9);
self::assertTrue($f($this->reader));
self::assertFalse($sheet->cellExists('A9'));
self::assertFalse($sheet->cellExists('B9'));
// row looks like empty, not empty after $colDetects cols.
$sheet->setCellValue('C9', 'blah');
$sheet->setCellValue('A9', '');
self::assertTrue($f($this->reader));
// cell value 0 not empty
$sheet->setCellValue('A9', 0);
$sheet->setCellValue('B9', false);
}
/**
* @dataProvider colIsMergedStartProvider
* @param callable(ExcelReader): bool $f
*/
public function testColIsMergedStart(bool $exp, string $range, int $row, callable $f): void
{
$sheet = $this->reader->getSheet();
$sheet->mergeCells($range);
$this->reader->setRow($row);
self::assertEquals($exp, $f($this->reader));
}
/**
* @return array<mixed[]>
*/
public function colIsMergedStartProvider(): array
{
$f1 = SectionBoundary::colIsMergedStart('B');
$f2 = SectionBoundary::colIsMergedStart('B', 4);
return [
[true, 'B1:C1', 1, $f1],
// not merged
[false, 'B1:C1', 2, $f1],
// not merged start
[false, 'A3:C3', 3, $f1],
// minimal merged cells: not enough cells
[false, 'B5:D5', 5, $f2],
// minimal merged cells: equal minimal cells
[true, 'B6:E6', 6, $f2],
// minimal merged cells: more than minimal cells
[true, 'B7:F7', 7, $f2],
];
}
}
| true |
732ee8515205e3dc82684c5a0ef2ebe86a292082 | PHP | sumenpuyuan/frontEndDemo | /15.河北农业大学实验室宣传小站/lab/DynamicModules/RegisterAndLogin/FenyePage.class.php | UTF-8 | 1,262 | 2.578125 | 3 | [] | no_license | <?php
class FenyePage{
var $pageNow=1;
var $pageCount;
var $pageSize=6;
var $rowCount;
var $navigator;
var $res="";
var $goUrl;
var $condition="";
/**
* @return unknown
*/
public function getNavigator() {
return $this->navigator;
}
/**
* @return unknown
*/
public function getPageCount() {
return $this->pageCount;
}
/**
* @return unknown
*/
public function getPageNow() {
return $this->pageNow;
}
/**
* @return unknown
*/
public function getPageSize() {
return $this->pageSize;
}
/**
* @return unknown
*/
public function getRowCount() {
return $this->rowCount;
}
/**
* @param unknown_type $navigator
*/
public function setNavigator($navigator) {
$this->navigator = $navigator;
}
/**
* @param unknown_type $pageCount
*/
public function setPageCount($pageCount) {
$this->pageCount = $pageCount;
}
/**
* @param unknown_type $pageNow
*/
public function setPageNow($pageNow) {
$this->pageNow = $pageNow;
}
/**
* @param unknown_type $pageSize
*/
public function setPageSize($pageSize) {
$this->pageSize = $pageSize;
}
/**
* @param unknown_type $rowCount
*/
public function setRowCount($rowCount) {
$this->rowCount = $rowCount;
}
}
?> | true |
0c9f646fe50bfe23087d1856f43dda035df3080d | PHP | alealclag/alpiges-real-state | /PHP/form_editar_perfil.php | UTF-8 | 2,664 | 2.546875 | 3 | [] | no_license | <?php
session_start();
require_once("gestionarPerfil.php");
require_once("gestionBD.php");
if (!isset($_SESSION['login'])) {
header("Location: form_login.php");
}else{
$conexion=crearConexionBD();
$usuario=informacionUsuario($conexion, $_SESSION['login']);
if (isset($_SESSION["errores"]))
$errores = $_SESSION["errores"];
}
$usuario=informacionUsuario($conexion, $_SESSION["login"]);
cerrarConexionBD($conexion);
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8">
<link href="estilos/estilos.css" rel="stylesheet">
<script src="js/Validaciones.js" type="text/javascript"></script>
<title>Editar Perfil</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
<header><?php include_once("Cabecera.php");?></header>
<?php
if (isset($errores) && count($errores)>0) {
echo "<div id=\"div_errores\" class=\"error\">";
echo "<h4> Errores en el formulario:</h4>";
foreach($errores as $error) echo $error;
echo "</div>";
}
?>
<h2>Editar datos de usuario</h2>
<form id="modificarUsuario" method="post" action="accion_editar_usuario.php" novalidate="novalidate" onsubmit="return validarEdicion();">
<fieldset>
<p>Nombre*: <input type="text" id="nombre" name="nombre" size="30" required value=<?php echo $usuario['NOMBRE']?> /> </p>
<p>Apellidos*: <input type="text" id="apellidos" name="apellidos" size="40" required value=<?php echo $usuario['APELLIDOS']?> />
Contraseña*:<input type="password" id="contrasena" name="contrasena" size="20" value=<?php echo $usuario['CONTRASENA']?> required placeholder="numeros, mayusculas y minusculas"/></p>
<p>DNI*: <input type="text" id="DNI" name="DNI" size="20" required value=<?php echo $usuario['DNI']?> pattern="^[0-9]{8}[A-Z]" placeholder="8 digitos + 1 letra"> </p>
<p>E-mail: <input type="email" readonly="readonly" id="email" style="background: lightgrey" name="email" value=<?php echo $usuario['CORREO_ELECTRONICO']?> size="40" required/>
Fecha de Nacimiento:<input type="date" value=<?php echo $usuario['FECHA_NACIMIENTO']?> name="fechaNacimiento" id="fechaNacimiento" required="required"></p>
<p>Numero de Teléfono*: <input type="tel" value=<?php echo $usuario['TELEFONO']?> name="NumTel" id="NumTel" size="40" pattern="^[0-9]{9}" required></p>
<input type="hidden" id="usuario" name="usuario" value="<?php echo $usuario["OID_US"]?>"/><br/>
<br />
<input type="submit" name="submit" value="Enviar">
</fieldset>
</form>
<footer style="position: relative;bottom: -500px"><?php include_once("pie.php");?></footer>
</body>
</html>
| true |
79368b843a81040cac27ca178c0ef65387e55075 | PHP | vladlen-beilik/price-aggregator | /app/Http/Client/ResponseToArray.php | UTF-8 | 369 | 2.65625 | 3 | [] | no_license | <?php
namespace App\Http\Client;
use App\Http\Client\Response\HttpResponseInterface;
trait ResponseToArray
{
/**
* @param \App\Http\Client\Response\HttpResponseInterface $response
*
* @return array
*/
public function toArray(HttpResponseInterface $response): array
{
return json_decode($response->getContent(), true);
}
}
| true |
e6ecdc92fd820fe0ccef66cd38d5fec2ac165a70 | PHP | locomotivemtl/charcoal-ui | /src/Charcoal/Ui/MenuItem/MenuItemFactory.php | UTF-8 | 608 | 2.578125 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | <?php
namespace Charcoal\Ui\MenuItem;
use Charcoal\Factory\ResolverFactory;
use Charcoal\Ui\MenuItem\MenuItemInterface;
use Charcoal\Ui\MenuItem\GenericMenuItem;
/**
* Menu Item Factory
*/
class MenuItemFactory extends ResolverFactory
{
/**
* @return string
*/
public function baseClass()
{
return MenuItemInterface::class;
}
/**
* @return string
*/
public function defaultClass()
{
return GenericMenuItem::class;
}
/**
* @return string
*/
public function resolverSuffix()
{
return 'MenuItem';
}
}
| true |
9ade823aec19036ac913f0773471e2577c1b821e | PHP | Salmon42/NDS8-2019-Group-820 | /Project/Web 2FA/lib/LDAP.php | UTF-8 | 10,116 | 2.59375 | 3 | [] | no_license | <?php
/**
*
*/
class LDAP
{
Private $ldap_link;
Private $ldapconfig;
Private $admin_username = "admin";
Private $admin_password = "admin";
function __construct()
{
$this->connect();
}
function __destruct()
{
ldap_close($this->ldap_link);
}
function connect()
{
//cn=readonly,dc=example,dc=org
$this->ldapconfig['host'] = '192.168.32.2';//CHANGE THIS TO THE CORRECT LDAP SERVER
$this->ldapconfig['port'] = '389';
$this->ldapconfig['basedn'] = 'dc=example,dc=org';//CHANGE THIS TO THE CORRECT BASE DN
$this->ldapconfig['usersdn'] = 'ou=People';//CHANGE THIS TO THE CORRECT USER OU/CN
ldap_set_option($this->ldap_link, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($this->ldap_link, LDAP_OPT_REFERRALS, 0);
ldap_set_option($this->ldap_link, LDAP_OPT_NETWORK_TIMEOUT, 10);
$this->ldap_link=ldap_connect($this->ldapconfig['host'], $this->ldapconfig['port']);
if (!$this->ldap_link)
{
exit('Connection failed');
}
}
// ----------------------------------------------------------------------------------- //
//
// LDAP login
//
// ----------------------------------------------------------------------------------- //
function check_login($username, $password)
{
$dn="cn=".$username.",".$this->ldapconfig['usersdn'].",".$this->ldapconfig['basedn'];
if ($bind=ldap_bind($this->ldap_link, $dn, $password))
{
//my_debug_print("Login corret", __FILE__, __LINE__, "on");
//ldap_close($this->ldap_link);
return "login ok";
}
else
{
//my_debug_print("Login Failed: Please check your username or password", __FILE__, __LINE__, "on");
//my_debug_print($this->ldap_link, __FILE__, __LINE__, "on");
//my_debug_print($dn, __FILE__, __LINE__, "on");
//my_debug_print($bind, __FILE__, __LINE__, "on");
//ldap_close($this->ldap_link);
return FALSE;
}
}
// ----------------------------------------------------------------------------------- //
//
// Voiceit
//
// ----------------------------------------------------------------------------------- //
function get_voiceit_user_data($username)
{
//my_debug_print(debug_string_backtrace(), __FILE__, __LINE__, "on");
//Admin login
$dn="cn=".$this->admin_username.",".$this->ldapconfig['basedn'];
$bind=ldap_bind($this->ldap_link, $dn, $this->admin_password);
//User to read value from
$dn="cn=".$username.",".$this->ldapconfig['usersdn'].",".$this->ldapconfig['basedn'];
$filter = "(objectclass=*)"; // this command requires some filter
$filter_types = array("description");
$sr = ldap_read($this->ldap_link, $dn, $filter, $filter_types);
$entry = ldap_get_entries($this->ldap_link, $sr);
if (isset($entry[0]["description"]))
{
$ldap_description_write;
foreach ($entry[0]["description"] as $key => $value)
{
if ($key === "count")
{
//do not do anyting for count
}
else
{
$description = json_decode($value, true);
if (json_last_error() === JSON_ERROR_NONE)
{
// Valid JSON
if (isset($description["voiceit"]) && $description["voiceit"] != "")
{
//my_debug_print($description, __FILE__, __LINE__, "on");
return array(
'voiceit' => $description["voiceit"],
'voiceit_enrolled' => $description["voiceit_enrolled"],
);
}
else
{
return "false";
}
}
}
}
}
}
function set_voiceit_enrolled($username, $voiceit_value)
{
$voiceit_enrolled = "1";
$update = true;
$this->add_voiceit($username, $voiceit_value, $voiceit_enrolled, $update);
}
function add_voiceit($username, $voiceit_value, $voiceit_enrolled = "0", $update = false)
{
//Admin login
$dn="cn=".$this->admin_username.",".$this->ldapconfig['basedn'];
$bind=ldap_bind($this->ldap_link, $dn, $this->admin_password);
//User to change value on
$dn="cn=".$username.",".$this->ldapconfig['usersdn'].",".$this->ldapconfig['basedn'];
$filter = "(objectclass=*)"; // this command requires some filter
$filter_types = array("description");
$sr = ldap_read($this->ldap_link, $dn, $filter, $filter_types);
$entry = ldap_get_entries($this->ldap_link, $sr);
if (isset($entry[0]["description"]))
{
$ldap_description_write;
foreach ($entry[0]["description"] as $key => $value)
{
if ($key === "count")
{
//do not do anyting for count
}
else
{
$description = json_decode($value, true);
if (json_last_error() === JSON_ERROR_NONE)
{
// Valid JSON
if (isset($description["2fa"]) && $description["2fa"] != "")
{
if (isset($description["voiceit"]) && $description["voiceit"] != "")
{
if ($update === true)
{
$description = array(
"voiceit" => $voiceit_value,
"voiceit_enrolled" => $voiceit_enrolled,
"2fa" => $description["2fa"],
);
$json = json_encode($description);
$ldap_description_write[$key] = $json;
}
}
else
{
$description = array(
"voiceit" => $voiceit_value,
"voiceit_enrolled" => $voiceit_enrolled,
"2fa" => $description["2fa"],
);
$json = json_encode($description);
$ldap_description_write[$key] = $json;
}
}
else
{
$ldap_description_write[$key] = $value;
}
}
else
{
// Not valid JSON
$ldap_description_write[$key] = $value;
}
}
}
//Value to change
$le = array("description" => array_values($ldap_description_write));
//Change the value
$result = ldap_modify($this->ldap_link, $dn, $le);
}
else
{
my_debug_print("Can not set voice settings before 2fa on web", __FILE__, __LINE__, "on");
die();
//Shoud never go down here as web 2fa will be set using json before voiceit
}
}
// ----------------------------------------------------------------------------------- //
//
// Web 2FA
//
// ----------------------------------------------------------------------------------- //
function get_2fa_user_data($username)
{
//my_debug_print(debug_string_backtrace(), __FILE__, __LINE__, "on");
//Admin login
$dn="cn=".$this->admin_username.",".$this->ldapconfig['basedn'];
$bind=ldap_bind($this->ldap_link, $dn, $this->admin_password);
//User to read value from
$dn="cn=".$username.",".$this->ldapconfig['usersdn'].",".$this->ldapconfig['basedn'];
$filter = "(objectclass=*)"; // this command requires some filter
$filter_types = array("description");
$sr = ldap_read($this->ldap_link, $dn, $filter, $filter_types);
$entry = ldap_get_entries($this->ldap_link, $sr);
if (isset($entry[0]["description"]))
{
$ldap_description_write;
foreach ($entry[0]["description"] as $key => $value)
{
if ($key === "count")
{
//do not do anyting for count
}
else
{
$description = json_decode($value, true);
if (json_last_error() === JSON_ERROR_NONE)
{
// Valid JSON
if (isset($description["2fa"]) && $description["2fa"] != "")
{
//my_debug_print($description, __FILE__, __LINE__, "on");
return $description["2fa"];
}
else
{
return "false";
}
}
}
}
}
}
function add_2fa($username, $secret, $update = false)
{
//Admin login
$dn="cn=".$this->admin_username.",".$this->ldapconfig['basedn'];
$bind=ldap_bind($this->ldap_link, $dn, $this->admin_password);
//User to change value on
$dn="cn=".$username.",".$this->ldapconfig['usersdn'].",".$this->ldapconfig['basedn'];
$filter = "(objectclass=*)"; // this command requires some filter
$filter_types = array("description");
$sr = ldap_read($this->ldap_link, $dn, $filter, $filter_types);
$entry = ldap_get_entries($this->ldap_link, $sr);
if (isset($entry[0]["description"]))
{
$ldap_description_write;
foreach ($entry[0]["description"] as $key => $value)
{
if ($key === "count")
{
//do not do anyting for count
}
else
{
$description = json_decode($value, true);
if (json_last_error() === JSON_ERROR_NONE)
{
// Valid JSON
if (isset($description["2fa"]) && $description["2fa"] != "")
{
if ($update === true)
{
$description = array(
"2fa" => $secret,
);
$json = json_encode($description);
$ldap_description_write[$key] = $json;
}
else
{
$ldap_description_write[$key] = $value;
}
}
else
{
$description = array(
"2fa" => $secret,
);
$json = json_encode($description);
$ldap_description_write[$key] = $json;
}
}
else
{
// Not valid JSON
$ldap_description_write[$key] = $value;
}
}
}
//Value to change
$le = array("description" => array_values($ldap_description_write));
//Change the value
$result = ldap_modify($this->ldap_link, $dn, $le);
}
else
{
//Add value
$description = array(
"2fa" => $secret,
);
$json = json_encode($description);
$ldap_description_write[0] = $json;
//Value to change
$le = array("description" => array_values($ldap_description_write));
//Change the value
$result = ldap_modify($this->ldap_link, $dn, $le);
}
}
// ----------------------------------------------------------------------------------- //
//
// Other
//
// ----------------------------------------------------------------------------------- //
//Dangerous to use as is
function modify_value($username, $key, $value)
{
//Admin login
$dn="cn=".$this->admin_username.",".$this->ldapconfig['basedn'];
$bind=ldap_bind($this->ldap_link, $dn, $this->admin_password);
//User to change
$dn="cn=".$username.",".$this->ldapconfig['usersdn'].",".$this->ldapconfig['basedn'];
//Value to change
$le = array($key => array($value));
//Change the value
$result = ldap_modify($this->ldap_link, $dn, $le);
}
}
?> | true |
902e8c1d7325a96322560b2764b6eaf2f23abf46 | PHP | yascmf/api | /modules/Common/Models/Article.php | UTF-8 | 2,795 | 2.78125 | 3 | [
"MIT"
] | permissive | <?php
namespace Modules\Common\Models;
use Illuminate\Database\Eloquent\Model;
/**
* 内容模型
*/
class Article extends Model
{
/**
* @var string
*/
protected $table = 'articles';
/**
* @var string
*/
protected $primaryKey = 'id';
/**
* @var array
*/
protected $fillable = [
'title',
'flag',
'thumb',
'slug',
'cid',
'description',
'content',
];
/**
* getFlagAttribute
*
* @param string $value
* @return array
*/
public function getFlagAttribute($value)
{
$value = rtrim($value, ',');
if (is_string($value) && !empty($value)) {
$flags = explode(',', $value);
} else {
$flags = [];
}
return $flags;
}
/**
* category
*
* @return \Illuminate\Database\Eloquent\Relations\HasOne
*/
public function category()
{
// 模型名 外键 本键
return $this->hasOne('Modules\Common\Models\Category', 'id', 'cid');
}
/**
* labels
*
* @return array
*/
public function labels()
{
return [
'title' => '标题',
'slug' => '标识符',
'cid' => '分类id',
'description' => '描述',
'content' => '正文',
];
}
/**
* rules
*
* @param array $filters
* @return array
*/
public function rules($filters = [])
{
$id = isset($filters['id']) && !empty($filters['id']) ? ','.$filters['id'].',id' : '';
$rules = [
'title' => 'required|min:3|max:80',
'slug' => 'required|regex:/^[a-z0-9\-_]{1,120}$/|unique:articles,slug'.$id,
'cid' => 'required|exists:categories,id',
'description' => 'required|min:10',
'content' => 'required|min:20',
];
return $rules;
}
/**
* 自定义验证信息
*
* @return array
*/
public function messages()
{
return [
'slug.regex' => ':attribute 非法',
'cid.*' => '分类id 非法',
];
}
/**
* 保存前处理输入数据
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function beforeSaving($request)
{
$inputs = $request->only($this->fillable);
if (empty($inputs['thumb'])) {
$inputs['thumb'] = '';
}
if (is_array($inputs['flag']) && count($inputs['flag']) > 0) {
$tmp_flag = implode($inputs['flag'], ',').',';
} else {
$tmp_flag = '';
}
$inputs['flag'] = $tmp_flag;
return $inputs;
}
}
| true |
123736ae7c0646bd054dd1636f85caeef20e47ae | PHP | ascretul/online-store | /online-store/app/Models/Category.php | UTF-8 | 1,286 | 2.78125 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Models;
use App\Models\Person;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
/**
* Indicates if the model should be timestamped.
*
* @var bool
*/
public $timestamps = false;
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'categories';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name'
];
/**
* Set
*
* @param string $name Name
*
* @return this
*/
public function setName(string $name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Get products
*
* @return products
*/
public function products()
{
return $this->hasMany('App\Models\Product');
}
/**
* Get products
*
* @return array
*/
public function getProducts()
{
return $this->products;
}
/**
* Get id
*
* @return int
*/
public function getId()
{
return $this->id;
}
}
| true |
5045dc6ca0600075d5f3ffc304c0290be3b7dd9e | PHP | dandyxu/Ajax-Learning | /ajax_button/favourite.php | UTF-8 | 751 | 2.703125 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: Wenqian
* Date: 7/17/2017
* Time: 10:19 AM
*/
session_start();
if (!isset($_SESSION['favourites'])) {
$_SESSION['favourites'] = [];
}
function is_ajax_request() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
$_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest';
}
if(!is_ajax_request()) {
exit;
}
// extract $id
$raw_id = isset($_POST['id']) ? $_POST['id'] : '';
//echo $raw_id;
if(preg_match("/blog-post-(\d+)/", $raw_id, $matches)){
$id = $matches[1];
// store in $_SESSION['favourite'];
if (!in_array($id, $_SESSION['favourites'])) {
$_SESSION['favourites'][] = $id;
}
// return true/false
echo 'true';
}else {
echo 'false';
}
| true |
80459954fc474d7acbf3cbca9f21f601949739c5 | PHP | droyenko/SoftServe | /PetCompany/models/PetShop/PetShopModel.php | UTF-8 | 1,542 | 3.15625 | 3 | [] | no_license | <?php
class PetShopModel extends Model
{
private $pets = [];
public function __construct()
{
//change this depending on database you need
parent::__construct();
// $pets = $this->db->convertPetsDbToArray(DBSettings::petShopDbFileName);
$pets = $this->db->convertPetsJsonToArray(DBSettings::petShopJsonFileName);
$this->pets = $pets;
}
public function getPriceHigherAvg()
{
$result = [];
$avgPrice = $this->getAvgPrice();
foreach ($this->pets as $pet) {
if ($pet->isYourPrice() > $avgPrice) {
$result[] = $pet;
}
}
return $result;
}
private function getAvgPrice()
{
$sum = 0;
$count = 0;
foreach ($this->pets as $pet) {
$sum += $pet->isYourPrice();
$count++;
}
$avgPrice = $sum / $count;
return $avgPrice;
}
public function getWhiteOrFluffy()
{
$result = [];
foreach ($this->pets as $pet) {
if (($pet instanceof FluffyPet) && ($pet->isYourColor() == 'white' || $pet->isFluffy())) {
$result[] = $pet;
}
}
return $result;
}
public function getCats()
{
$result = [];
foreach ($this->pets as $pet) {
if ($pet instanceof Cat) {
$result[] = $pet;
}
}
return $result;
}
public function addPet(Pet $pet)
{
$pets[] = $pet;
}
} | true |
0e3a751ad8a99a4d364b9e8d20aed9c234a78dab | PHP | galile-io/api | /database/migrations/2018_03_09_161839_create_user_activites_table.php | UTF-8 | 884 | 2.59375 | 3 | [] | no_license | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUserActivitesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('activities', function (Blueprint $t) {
$t->increments('id');
$t->string('reference_code')->nullable();
$t->string('type');
$t->unsignedInteger('user_id');
$t->unsignedInteger('partner_id')->nullable(); //TODO: Make it a FK with partners
$t->timestamps();
$t->foreign('user_id')->references('id')->on('users');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('activities');
}
}
| true |
dfa995eb8f831d6e94f765f883c81ee8d6c0b246 | PHP | phptheme/html | /BaseHtmlHelper.php | UTF-8 | 5,870 | 2.96875 | 3 | [
"MIT"
] | permissive | <?php
/**
* @author PhpTheme Dev Team <dev@getphptheme.com>
* @license MIT
* @link http://getphptheme.com
*/
namespace PhpTheme\Html;
abstract class BaseHtmlHelper
{
public static function escape($string, $encoding = 'utf-8', $specialCharsFlags = null)
{
if (!$specialCharsFlags)
{
$specialCharsFlags = ENT_QUOTES | ENT_SUBSTITUTE;
}
return htmlspecialchars($string, $specialCharsFlags, $encoding);
}
public static function mergeClass($class1, $class2)
{
if (is_array($class2))
{
if (!is_array($class1))
{
$class1 = explode(' ', $class1);
}
foreach($class2 as $class)
{
if (array_search($class, $class1) === false)
{
$class1[] = $class;
}
}
return implode(' ', $class1);
}
return $class2;
}
public static function explodeStyle(string $style)
{
$return = [];
$strings = explode(';', $style);
foreach($strings as $string)
{
list($key, $value) = explode(':', $string);
$return[$key] = $value;
}
return $return;
}
public static function implodeStyle(array $style)
{
$strings = [];
foreach($style as $key => $value)
{
$strings[] = $key . ':' . $value;
}
return implode(';', $strings);
}
public static function mergeStyle($style1, $style2)
{
if (is_array($style2))
{
if (!is_array($style1))
{
$style1 = static::explodeStyle($style1);
}
foreach($style2 as $key => $value)
{
$style1[$key] = $value;
}
return static::implodeStyle($style1);
}
return $style2;
}
public static function mergeAttributes(array $array1, array $array2)
{
$args = func_get_args();
$return = array_shift($args);
if (count($args) > 1)
{
foreach($args as $array)
{
$return = static::mergeAttributes($return, $array);
}
return $return;
}
foreach($array2 as $key => $value)
{
if (($key == 'class') && array_key_exists($key, $return))
{
$return[$key] = static::mergeClass($return[$key], $value);
}
elseif(($key == 'style') && array_key_exists($key, $return))
{
$return[$key] = static::mergeStyle($return[$key], $value);
}
else
{
$return[$key] = $value;
}
}
return $return;
}
public static function mergeOptions(array $array1, array $array2)
{
$args = func_get_args();
$return = array_shift($args);
if (count($args) > 1)
{
foreach($args as $array)
{
$return = static::mergeOptions($return, $array);
}
return $return;
}
foreach($array2 as $key => $value)
{
if (($key == 'attributes') && array_key_exists($key, $return))
{
$return[$key] = static::mergeAttributes($return[$key], $value);
}
else
{
$return[$key] = $value;
}
}
return $return;
}
public static function renderAttributes($attributes) : string
{
$return = '';
if (array_key_exists('class', $attributes) && is_array($attributes['class']))
{
$attributes['class'] = implode(' ', $attributes['class']);
}
if (array_key_exists('style', $attributes) && is_array($attributes['style']))
{
$attributes['style'] = static::implodeStyle($attributes['style']);
}
foreach($attributes as $key => $value)
{
if ($value === true)
{
$return .= ' ' . $key;
}
else
{
$return .= ' ' . $key . '="' . $value . '"';
}
}
return $return;
}
public static function beginTag($tag, array $attributes = [])
{
if ($tag)
{
return '<' . $tag . static::renderAttributes($attributes) . '>';
}
return '';
}
public static function endTag($tag)
{
if ($tag)
{
return '</' . $tag . '>';
}
return '';
}
public static function tag($tag, $content, array $attributes = [])
{
$return = static::beginTag($tag, $attributes);
$return .= $content;
$return .= static::endTag($tag);
return $return;
}
public static function shortTag($tag, array $attributes = [])
{
return '<' . $tag . static::renderAttributes($attributes) . '>';
}
public static function linkCss($href, array $attributes = [])
{
$attributes['rel'] = 'stylesheet';
$attributes['type'] = 'text/css';
if (!array_key_exists('media', $attributes))
{
$attributes['media'] = 'screen';
}
$attributes['href'] = $href;
return static::shortTag('link', $attributes);
}
public static function scriptFile($url, array $attributes = [])
{
$attributes['src'] = $url;
return static::tag('script', '', $attributes);
}
} | true |
af5f0e77098591eaa0a9961911e26af8c0af17ea | PHP | SherronL/blog-cakephp | /db/migrations/20200218142834_create_admins.php | UTF-8 | 744 | 2.671875 | 3 | [] | no_license | <?php
use Phinx\Migration\AbstractMigration;
class CreateAdmins extends AbstractMigration
{
public function change()
{
$table = $this->table('admins');
$table->addColumn('username', 'string', [
'default' => null,
'limit' => 255,
'null' => false,
]);
$table->addColumn('password', 'text', [
'default' => null,
'null' => false,
]);
$table->addColumn('user_id', 'integer',[
'default' => null,
'limit'=> 11,
'null' => false,
]);
$table->addColumn('created', 'datetime', [
'default' => null,
'null' => false,
]);
$table->addColumn('modified', 'datetime', [
'default' => null,
'null' => false,
]);
$table->create();
}
}
| true |
5c66fe74fe33b2a2f5962013d8e178cc4f2a616e | PHP | llqhz/app | /application/index/service/Token.php | UTF-8 | 2,360 | 2.5625 | 3 | [
"Apache-2.0"
] | permissive | <?php
/**
* @Author: .筱怪 llqhz@qq.com
* @Created time: 2018-08-20 14:40
* @Last Modified: 2018-08-20 14:40
* @version v1.0.0
*/
namespace app\index\service;
use app\exception\ProcessException;
use app\library\enum\ScopeEnum;
use think\Cache;
use think\Exception;
use think\Request;
class Token
{
public static function generateToken()
{
$token = getRandStr(16);
$timestamp = $_SERVER['REQUEST_TIME_FLOAT'];
$salt = config('app.token_salt');
return md5($token.$timestamp.$salt);
}
/**
* 获取Token对应变量
* @param string $key
* @return mixed
* @throws ProcessException
*/
public static function getCurrentTokenVar($key='')
{
$token = Request::instance()->header('token');
$vars = Cache::get($token);
if ( !$vars ) {
throw new ProcessException('TokenMiss');
}
if ( !is_array($vars) ) {
$vars = json_decode($vars,true);
}
if ( array_key_exists($key,$vars) ) {
return $vars[$key];
} else {
throw new ProcessException('TokenVarMiss');
}
}
/**
* 根据Header里面的Token获取uid
* @return mixed
* @throws ProcessException
*/
public static function getCurrentUid()
{
return self::getCurrentTokenVar('uid');
}
public static function needScope($scopes=[])
{
$scope = self::getCurrentTokenVar('scope');
if ( !$scope ) {
throw new ProcessException('TokenMiss');
} else {
foreach ( $scopes as $key => $val ) {
if ( ScopeEnum::get($val) == $scope ) {
return true;
}
}
}
throw new ProcessException('Forbidden');
}
public static function isValidOperate( $uid = '' )
{
if ( !$uid ) {
# 代码错误抛出think异常
throw new Exception(['msg'=>'缺少uid参数']);
}
$currentOperateUid = self::getCurrentUid();
if ( !$uid == $currentOperateUid ) {
return false;
}
return true;
}
public static function verifyToken($token='') {
if ( Cache::get($token) ) {
return true;
} else {
return false;
}
}
} | true |
689ded07476c4ad4b8e7056b94525ae1ae5ea701 | PHP | dragouf/VeloBleuProxy | /system/application/libraries/velobleudatasync.php | UTF-8 | 3,477 | 2.59375 | 3 | [] | no_license | <?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
class velobleudataSync
{
private $CI;
private $mapDb;
private $networks;
private $mapDbKey;
private $jsonUrl;
private $veloBleuDbData;
public $jsonDataLength;
function velobleudataSync()
{
$this->CI =& get_instance();
$this->CI->config->load('velobleuconf');
$this->CI->load->helper('http');
}
function findKeyAndUriFromVeloWebsite()
{
// Charge le contenu de la page velo bleu
$urlBase = $this->CI->config->item('UrlBase', 'velobleuconf');
$urlCarte = $this->CI->config->item('UrlCarteVeloBleu', 'velobleuconf');
$pageHTML = @file_get_contents($urlBase . $urlCarte);
if(isset($http_response_header) && isValidHttpRequest($pageHTML, $http_response_header))
{
// Trouve la variable mapdb et prend ce qui est contenu entre quotes pour connaitre son contenu
$posMapDb = strpos($pageHTML, 'var mapdb');
$posQote1MapDb = strpos($pageHTML, "'", $posMapDb) + 1;
$posQote2MapDb = strpos($pageHTML, "'", $posQote1MapDb);
$varMapDb = substr($pageHTML, $posQote1MapDb, $posQote2MapDb - $posQote1MapDb);
log_message('debug', 'found mapdb : ' . $varMapDb);
$this->mapDb = $varMapDb;
// Idem pour var networks
$posNetworks = strpos($pageHTML, 'var networks');
$posQote1Networks = strpos($pageHTML, '"', $posNetworks) + 1;
$posQote2Networks = strpos($pageHTML, '"', $posQote1Networks);
$varNetworks = strtolower(substr($pageHTML, $posQote1Networks, $posQote2Networks - $posQote1Networks));
log_message('debug', 'found networks : ' . $varNetworks);
$this->networks = $varNetworks;
// Idem pour var mapdbkey
$posMapdDbKey = strpos($pageHTML, 'var mapdbkey');
$posQote1MapDbKey = strpos($pageHTML, "'", $posMapdDbKey) + 1;
$posQote2MapDbKey = strpos($pageHTML, "'", $posQote1MapDbKey);
$varMapDbKey = substr($pageHTML, $posQote1MapDbKey, $posQote2MapDbKey - $posQote1MapDbKey);
log_message('debug', 'found mapdbkey : ' . $varMapDbKey);
$this->mapDbKey = $varMapDbKey;
$this->jsonUrl = $this->getJsonUrl();
log_message('debug', 'found jsonUrl : ' . $this->jsonUrl);
}
else
{
$httpError = "Aucune information";
if(isset($http_response_header))
$httpError = getHttpError($http_response_header);
log_message('error', 'Chargement des données contenant la clé impossible : ' . $httpError);
}
}
function getJsonUrl()
{
// exemple : 'http://www.velobleu.org/oybike/stands.nsf/getSite?openagent&site=nice&format=json&key=D659E7E9D3BB9010307D6835FD4CE8B8'
$urlBase = $this->CI->config->item('UrlBase', 'velobleuconf');
$url = $urlBase . $this->mapDb . '/getSite?openagent&site=' . $this->networks . '&format=json&key=' . $this->mapDbKey;
return $url;
}
function loadJsonDataFromWebsite()
{
$this->veloBleuDbData = false;
$this->findKeyAndUriFromVeloWebsite();
$jsonText = @file_get_contents($this->jsonUrl);
if(isset($http_response_header) && isValidHttpRequest($jsonText, $http_response_header))
{
log_message('debug', 'received jsonText...');
$this->veloBleuDbData = json_decode($jsonText);
$this->jsonDataLength = strlen($jsonText);
}
else
{
$httpError = "Aucune information";
if(isset($http_response_header))
$httpError = getHttpError($http_response_header);
log_message('error', 'Chargement des données json impossible : ' . $httpError);
}
return $this->veloBleuDbData;
}
}
?> | true |
e8fc111b83aa6c1efdfa8c3c302d9712f2913c34 | PHP | alariva/laravel-email-domain-blacklist | /tests/ValidatorTest.php | UTF-8 | 2,612 | 2.53125 | 3 | [
"MIT"
] | permissive | <?php
namespace Tests;
use Config;
use Validator;
use Tests\BaseTestCase;
class ValidatorTest extends BaseTestCase
{
/**
* Test it rejects emails with domains that ARE blacklisted by append
* @return void
*/
public function test_rejects_blacklisted_by_append()
{
Config::set('validation.email.blacklist.source', null);
Config::set('validation.email.blacklist.append', "reject.me");
$rules = ['email' => 'email|blacklist'];
$input = ['email' => 'rejectme@reject.me'];
$passes = Validator::make($input, $rules)->passes();
$this->assertFalse($passes);
}
/**
* Test it rejects emails with domains that ARE blacklisted by append of multi items
* @return void
*/
public function test_rejects_blacklisted_by_append_multi()
{
Config::set('validation.email.blacklist.source', null);
Config::set('validation.email.blacklist.append', "reject.me|rejecthisother.com");
$rules = ['email' => 'email|blacklist'];
$input = ['email' => 'rejectme@rejecthisother.com'];
$passes = Validator::make($input, $rules)->passes();
$this->assertFalse($passes);
}
/**
* Test it rejects emails with domains that ARE blacklisted AnY CaSe TyPeD
* @return void
*/
public function test_rejects_blacklisted_by_append_lowercase()
{
Config::set('validation.email.blacklist.source', null);
Config::set('validation.email.blacklist.append', "rejectthisother.com");
$rules = ['email' => 'email|blacklist'];
$input = ['email' => 'rejectme@REJECTthisOTHER.CoM'];
$passes = Validator::make($input, $rules)->passes();
$this->assertFalse($passes);
}
/**
* Test it allows emails with domains that are NOT blacklisted by append
* @return void
*/
public function test_allows_not_blacklisted_by_append()
{
Config::set('validation.email.blacklist.source', null);
Config::set('validation.email.blacklist.append', "notinsource.com|otherappend.com");
$rules = ['email' => 'email|blacklist'];
$input = ['email' => 'rejectme@letmein.com'];
$passes = Validator::make($input, $rules)->passes();
$this->assertTrue($passes);
}
/**
* Test it allows emails with domains that are NOT blacklisted
* @return void
*/
public function test_rejects_blacklisted_by_source()
{
Config::set('validation.email.blacklist.auto-update', true);
Config::set('validation.email.blacklist.source', __DIR__.'/stubs/source.json');
$rules = ['email' => 'email|blacklist'];
$input = ['email' => 'rejectme@example.com'];
$passes = Validator::make($input, $rules)->passes();
$this->assertFalse($passes);
}
} | true |
d6f6a50f42665858cec6ee9ab5e6a6651e765e53 | PHP | angeliquesvt/fleetfinal | /class/Comments.php | UTF-8 | 2,429 | 2.9375 | 3 | [] | no_license | <?php
class Comments{
private $options = array(
'content_error' => "Vous n'avez pas mis de message",
'parent_error' => "Vous essayez de répondre à un commentaire qui n'existe pas"
);
public $errors = array();
public function __construct($options = []){
$this->options = array_merge($this->options, $options);
}
// PERMET DE RECUP LES COMMENTAIRES ASSOCIE AU CONTENU
public function findAll($db, $id_projet, $ref){
$req = $db->query("SELECT * FROM comments WHERE id_projet= ? AND ref=? ORDER BY created_at DESC",
[
$id_projet,
$ref
]);
$comments = $req->fetchAll();
$replies = [];
foreach ($comments as $k => $comment) {
if($comment->parent_id){
$replies[$comment->parent_id][] = $comment;
unset($comments[$k]);
}
}
foreach ($comments as $k => $comment) {
if(isset($replies[$comment->id])){
$r = $replies[$comment->id];
usort($r, [$this, 'sortReplies']);
$comments[$k]->replies = $r;
}else{
$comments[$k]->replies = [];
}
}
return $comments;
}
public function sortReplies($a, $b){
$atime = strtotime($a->created_at);
$btime = strtotime($b->created_at);
return $btime > $atime ? -1 : 1;
}
// SAUVEGARDE LES COMMENTAIRES
public function save($db, $ref, $id_projet){
$errors = [];
if (empty($_POST['content'])) {
$errors['content'] = $this->options['content_error'];
}
if(count($errors)>0){
$this->errors = $errors;
return false;
}
if(!empty($_POST['parent_id'])){
$req = $db->query("SELECT id FROM comments WHERE ref= ? AND id_projet= ? AND id= ? AND parent_id=0", [
$ref,
$id_projet,
$_POST['parent_id']
]);
if($req ->rowCount() <= 0){
$this->errors['parent'] = $this->options['parent_error'];
return false;
}
}
$req = $db->query("INSERT INTO comments SET id_user= ?, firstname=?, lastname=?, id_projet =?, content = ?, created_at= NOW(), ref= ?, parent_id= ?", [
$_SESSION['auth']->id,
$_SESSION['auth']->firstname,
$_SESSION['auth']->lastname,
$id_projet,
$_POST['content'],
$ref,
$_POST['parent_id']
]);
return $req;
}
}
?>
| true |
3ed9e3955eec199ea5f56bda15d746ebef39f20d | PHP | oliverliuwt/fruitweb | /classes/uploadfile.class.php | UTF-8 | 287 | 2.609375 | 3 | [] | no_license | <?php
class UploadFile {
public function __construct(){
//initialise database
//parent::__construct();
//check if files are being uploaded
if( count($_FILES) > 0 ){
print_r($_FILES);
}
else{
print_r($_FILES["upload"]["error"]);
}
}
}
?> | true |
006f26b2e8996d7ee2262a12db0607d9ebefd74c | PHP | SpikedCola/YouTube-Closed-Captions | /closed-captions.php | UTF-8 | 4,766 | 2.8125 | 3 | [] | no_license | <?php
/**
* Some helper functions to fetch "Closed Captions" for a YouTube video
*
* Normally these are only available to the video creator...
* But there's always a way!
*
* @author Jordan Skoblenick <parkinglotlust@gmail.com> 2014-08-16
*/
/**
* "Main function" - simply call this with a YouTube video ID
* and you will get back the text of the first Closed Captions we could load
*
* @param string $videoId
* @return mixed Closed Caption text or NULL if no tracks or text are found
*/
function getClosedCaptionsForVideo($videoId) {
$baseUrl = getBaseClosedCaptionsUrl($videoId);
// find available languages. options vary widely from
// video to video, and sometimes garbage is returned.
// tracks are returned in order we think is best -
// try first, if its garbage, try 2nd, etc.
$availableTracks = getAvailableTracks($baseUrl);
$text = null;
foreach ($availableTracks as $track) {
$text = getClosedCaptionText($baseUrl, $track);
// check for garbage
if (stripos($text, '[Content_Types]') !== false) {
// garbage found - some legible text and a lot
// that is not legible. dunno what this is, but
// it actually appears on the YT video if you view
// the page... skip
continue;
}
if ($text) {
// didnt skip, and we have text.. win!
break;
}
}
if ($text) {
// maybe process found text here?
// for now just wrap in paragraph tags
$text = "<p>{$text}</p>";
}
return $text;
}
/**
* Returns base URL for TimedText.
* "List languages"/"retrive text" commands will be appended to this URL
*
* Fetching this from the page saves us having to calculate a signature :)
*
* @param string $videoId
* @return string The base URL for TimedText requests
*/
function getBaseClosedCaptionsUrl($videoId) {
$youtubeUrl = 'http://www.youtube.com/watch?v=';
$pageUrl = $youtubeUrl.$videoId;
if (!$responseText = file_get_contents($pageUrl)) {
die('Failed to load youtube url '.$pageUrl);
}
$matches = [];
if (!preg_match('/TTS_URL\': "(.+?)"/is', $responseText, $matches)) {
die('Failed to find TTS_URL in page source for '.$pageUrl);
}
return str_replace(['\\u0026', '\\/'], ['&', '/'], $matches[1]);
}
/**
* Given a base URL, queries for available tracks and
* returns them in a sorted array ("scored" from highest
* to lowest based on things like `default_language` etc)
*
* @param string $baseUrl Base URL found by calling getBaseClosedCaptionsUrl()
* @return array An array of Closed Captions tracks available for this video
*/
function getAvailableTracks($baseUrl) {
$tracks = [];
// "request list" command
$listUrl = $baseUrl.'&type=list&tlangs=1&fmts=1&vssids=1&asrs=1';
if (!$responseText = file_get_contents($listUrl)) {
die('Failed to load youtube TTS list url '.$listUrl);
}
if (!$responseXml = simplexml_load_string($responseText)) {
die(' Failed to decode Xml for '.$responseText);
}
if (!$responseXml->track) {
// no tracks found for this video (happens sometimes even though
// YT search API says they do have captions)
return $tracks;
}
foreach ($responseXml->track as $track) {
$score = 0;
if ((string)$track['lang_default'] === 'true') {
// we like defaults
$score += 50;
}
$tracks[] = [
'score' => $score,
'id' => (string)$track['id'],
'lang' => (string)$track['lang_code'],
'kind' => (string)$track['kind'],
'name' => (string)$track['name']
];
}
// sort tracks by descending score
usort($tracks, function($a, $b) {
if ($a['score'] == $b['score']) {
return 0;
}
return ($a['score'] > $b['score']) ? -1 : 1;
});
return $tracks;
}
/**
* Given a base URL and a track, attempt to request Closed Captions
*
* If found, decode and strip tags from response, and join each line
* with a "<br />" and a "\n"
*
* @param string $baseUrl Base URL found by calling getBaseClosedCaptionsUrl()
* @param array $track Specific track to request
* @return string Closed captions text for video & track combo
*/
function getClosedCaptionText($baseUrl, array $track) {
$captionsUrl = $baseUrl."&type=track&lang={$track['lang']}&name=".urlencode($track['name'])."&kind={$track['kind']}&fmt=1";
if (!$responseText = file_get_contents($captionsUrl)) {
die('Failed to load youtube TTS captions track url '.$captionsUrl);
}
if (!$responseXml = simplexml_load_string($responseText)) {
die(' Failed to decode Xml for '.$responseText);
}
if (!$responseXml->text) {
die(' Bad XML structure for '.$captionsUrl.' : '.$responseText);
}
$videoText = [];
foreach ($responseXml->text as $textNode) {
if ($text = trim((string)$textNode)) {
$videoText[] = htmlspecialchars_decode(strip_tags((string)$textNode), ENT_QUOTES);
}
}
return implode("<br />\n", $videoText);
} | true |
c5a0708d3f5c66dc4a3595fbc33499a6be9553ae | PHP | AteitiesIT/phalcon-cli | /tests/Commands/UtilityTask.php | UTF-8 | 1,015 | 2.75 | 3 | [
"MIT"
] | permissive | <?php
use Danzabar\CLI\Tasks\Task;
/**
* The utility task
*
* @package CLI
* @subpackage Test
* @author Dan Cox
*/
class UtilityTask extends Task
{
/**
* The task name
*
* @var string
*/
protected $name = 'utility';
/**
* Description
*
* @var string
*/
protected $description = 'This is the utility task.';
/**
* The main action
*
* @Action
* @return void
* @author Dan Cox
*/
public function main()
{
$this->output->writeln("The main action of the utility task");
}
/**
* Draws a table
*
* @Action
* @return void
* @author Dan Cox
*/
public function table()
{
$table = $this->helpers->load('table');
$data = array();
$data[] = array('Header1' => 'Value', 'Header2' => 'Value2');
$data[] = array('Header1' => 'Longer value', 'Header2' => '');
$table->draw($data);
}
} // END class UtilityTask extends Command
| true |
f666771f36ce8ee55a6242874574a4b1cf4e1d71 | PHP | Soporte-Expresarte/Expresarte | /app/View/Components/galeria/CarruselArtistas.php | UTF-8 | 675 | 2.609375 | 3 | [
"MIT"
] | permissive | <?php
namespace App\View\Components\galeria;
use App\Models\Carrusel;
use Illuminate\View\Component;
class CarruselArtistas extends Component
{
/**
* Create a new component instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Get the view / contents that represent the component.
*
* @return \Illuminate\Contracts\View\View|string
*/
public function render()
{
return view('components.galeria.carrusel-artistas', [
'plana_4' => Carrusel::find(4),
'plana_5' => Carrusel::find(5),
'plana_6' => Carrusel::find(6),
]);
}
}
| true |
0acfd4f9cf5e4c019ebc7e2f8ef6822115ef15a9 | PHP | reinvanoyen/hector | /src/Hector/Db/QueryBuilder/Set.php | UTF-8 | 431 | 2.625 | 3 | [] | no_license | <?php
namespace Hector\Db\QueryBuilder;
class Set extends QueryPart
{
private $values;
const CONNECTS_WITH = [ 'where', 'orderBy', 'limit', ];
public function __construct($values = [])
{
$this->values = $values;
}
public function build() : String
{
$this->getQuery()->addBinding($this->values);
return 'SET ' . implode(' = ?, ', array_keys($this->values)) . ' = ?';
}
}
| true |
57af42ae81bdf6d05d296189b80befcab4a8e090 | PHP | jpatrick9/CST336 | /labs/lab5a/database.php | UTF-8 | 1,186 | 2.640625 | 3 | [] | no_license | <?php
function getDatabaseConnection() {
//mysql://b1d658c6df74b0:b5716444@us-cdbr-iron-east-05.cleardb.net/heroku_85e92cedc98a377?reconnect=true
// Username: b1d658c6df74b0
// Password: b5716444
// Host: us-cdbr-iron-east-05.cleardb.net
// Database name: heroku_85e92cedc98a377
// Connect to Heroku Database
// $host = 'us-cdbr-iron-east-05.cleardb.net';
// $dbname = 'heroku_85e92cedc98a377';
// $username = 'b1d658c6df74b0';
// $password = 'b5716444';
$host = 'localhost';
$dbname = 'ottermart';
$username = 'root';
$password = '';
// if (strpos($_SERVER['HTTP_HOST'], 'herokuapp') !== false) {
// $url = parse_url(getenv("CLEARDB_DATABASE_URL"));
// $host = $url["host"];
// $dbname = substr($url["path"], 1);
// $username = $url["user"];
// $password = $url["pass"];
// }
//creates database connection
$dbConn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
//display errors when accessing tables
$dbConn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbConn;
}
?> | true |
5c6ff34600edbbd3db4957f6fd4e466ac2972194 | PHP | terguevarra/terguevarra_php_framework | /php/lib/security.php | UTF-8 | 525 | 2.9375 | 3 | [] | no_license | <?php
class Security{
public function GenerateSalt(){
$length = 100;
$salt = base64_encode(mcrypt_create_iv($length, MCRYPT_DEV_URANDOM));
$salt = preg_replace("/[^A-Za-z0-9 ]/", '', $salt);
$salt = substr($salt, 0, 64);
return $salt;
}
public function HashPassword($password, $salt){
$key = 'gieter10052015';
$passwordSalt = $password . $salt;
$hashedPassword = hash_hmac('sha256', $passwordSalt, $key);
return $hashedPassword;
}
}
?> | true |
f85bd916456cb9352262f0b80ef65180ef792985 | PHP | zdanozdan/soteesklep3 | /include/online.inc | UTF-8 | 2,019 | 2.6875 | 3 | [] | no_license | <?php
/**
* Zarzadzanie uzytkwonikami online, sprawzdenie ilosci uzytkwonikow
*
* @author m@sote.pl
* @version $Id: online.inc,v 2.7 2004/12/20 18:02:54 maroslaw Exp $
* @package include
*/
class Online {
var $timeout=600; // ilosc sekund, po ktorej uznajemy uzytkownika ze nie jest online
/**
* Odczytaj ilu uzytkownikow jest teraz online
*
* @public
* @return int liczba uzytkownikow online
*/
function check_users_online() {
global $DOCUMENT_ROOT;
global $config;
global $shop;
// odczytaj pliki z sesji i sprawdz ich ostatni czas dostepu
$i=0;
if ($shop->home!=1) {
$dir_sess="$DOCUMENT_ROOT/../sessions/$config->salt/";
} else {
$dir_sess="/base/sessions/$config->salt/";
}
if ($handle = opendir($dir_sess)) {
while (false != ($file = readdir($handle))) {
if (ereg("^sess",$file)) {
$test=$this->check_file($file);
if ($test>0) {
$i++;
}
}
} // end while
closedir($handle);
} // end if
return $i;
} // end check_users_online()
/**
* Sprawdz uzytlwonika korzysta z danej sesji
*
* @param string $file plik sesji
* @return bool 1 - tak , 0 - nie, zbyt dlugo nie wywolal zadnej strony
*/
function check_file($file) {
global $DOCUMENT_ROOT;
global $config;
$file="$DOCUMENT_ROOT/../sessions/$config->salt/$file";
if (file_exists($file)) {
$lastvisit=fileatime($file);
$currenttime = getdate(time());
$currentdate = $currenttime["0"];
$difference = $currentdate - $lastvisit;
if ($difference<=$this->timeout) return 1;
} // end if
return 0;
} // end check_file()
} // end class Online
$online = new ONline;
?>
| true |
cc1a8f7e7818d37171e56d35930040abdb7fdd01 | PHP | jrivero/monica | /app/Console/Commands/ResetTestDB.php | UTF-8 | 1,151 | 2.734375 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Console\Commands;
use DB;
use Illuminate\Console\Command;
class ResetTestDB extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'monica:resetdb';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Reset the local database';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
if (env('APP_ENV') == 'local') {
foreach(\DB::select('SHOW TABLES') as $table) {
$table_array = get_object_vars($table);
\Schema::drop($table_array[key($table_array)]);
}
$this->call('migrate');
$this->call('db:seed');
$this->info('Local database has been reset');
} else {
$this->info('Can\'t execute this command in this environment');
}
}
}
| true |
8965cf188fe389632a7bc8e238af18180c3954b1 | PHP | vbrovenk/PHP_Final | /Day01/ex08/ft_is_sort.php | UTF-8 | 375 | 2.78125 | 3 | [] | no_license | <?php
function ft_is_sort(array $tab) {
if ($tab != null) {
$temp = $tab;
$temp_rev = $tab;
sort($temp);
rsort($temp_rev);
if ($temp == $tab) {
return true;
}
else if ($temp_rev == $tab) {
return true;
}
else {
return false;
}
}
}
?> | true |
0a90885f2f92a44fcd5a5dd6907a28dc3df3efe9 | PHP | li2009436276/hnddy-panoedit | /src/Repositories/Contracts/FileInterface.php | UTF-8 | 813 | 2.609375 | 3 | [] | no_license | <?php
namespace Yjtec\PanoEdit\Repositories\Contracts;
interface FileInterface
{
/**
* 添加文件
* @param $data
* @param $appId
* @param $userId
* @param $classifyId
* @param $type
* @param $category
* @param $applyType
* @return mixed
*/
public function create($data,$appId,$userId, $classifyId = 0,$type = 1,$category = 1,$applyType = 1);
/**
* 批量插入文件
* @param $data
* @param $appId
* @param $userId
* @param $classifyId
* @param $type
* @param $category
* @param $applyType
* @return mixed
*/
public function insert($data,$appId,$userId,$classifyId = 0,$type = 1,$category = 1,$applyType = 1);
public function index($where);
}
| true |
170d4469826b68da8ef2b7cc7bdfb1837b5e2d1a | PHP | rjw57/findsorguk | /app/forms/AccountUpgradeForm.php | UTF-8 | 3,078 | 2.546875 | 3 | [
"Apache-2.0"
] | permissive | <?php
/** Form for requesting an upgrade for a user's account
* @author Daniel Pett <dpett at britishmuseum.org>
* @copyright (c) 2014 Daniel Pett
* @category Pas
* @package Pas_Form
* @version 1
* @license http://www.gnu.org/licenses/agpl-3.0.txt GNU Affero GPL v3.0
*/
class AccountUpgradeForm extends Pas_Form {
/** The form constructor
* @access public
* @param array $options
*/
public function __construct(array $options = null) {
parent::__construct($options);
$this->setName('accountupgrades');
$researchOutline = new Pas_Form_Element_CKEditor('researchOutline');
$researchOutline->setLabel('Research outline: ')
->setAttribs(array('rows' => 10, 'cols' => 40, 'Height' => 400))
->addFilters(array('StringTrim', 'BasicHtml', 'EmptyParagraph', 'WordChars'))
->addErrorMessage('Outline must be present.')
->setDescription('Use this textarea to tell us whether you want to
become a research level user and why. We would also like to know
the probable length of time for this project so that we can
inform our research board of progress. We need a good idea,
as we have to respect privacy of findspots and
landowner/finder personal data');
$reference = $this->addElement('Text','reference',
array(
'label' => 'Please provide a referee:', 'size' => '40',
'description' => 'We ask you to provide a referee who can
substantiate your request for higher level access.
Ideally they will be an archaeologist of good standing.'))
->reference;
$reference->setRequired(false)->addFilters(array('StripTags', 'StringTrim'));
$referenceEmail = $this->addElement('Text','referenceEmail',
array(
'label' => 'Please provide an email address for your referee:',
'size' => '40'))->referenceEmail;
$referenceEmail->setRequired(false)
->addFilters(array('StripTags', 'StringTrim'))
->addValidator('EmailAddress');
$already = new Zend_Form_Element_Radio('already');
$already->setLabel('Is your topic already listed on our research register?: ')
->addMultiOptions(array( 1 => 'Yes it is',0 => 'No it isn\'t' ))
->setRequired(true)
->setOptions(array('separator' => ''));
//Submit button
$submit = new Zend_Form_Element_Submit('submit');
$submit->setLabel('Submit request');
$this->addElements(array($researchOutline, $submit, $already,));
$this->addDisplayGroup(array(
'researchOutline', 'reference', 'referenceEmail',
'already'), 'details');
$this->details->setLegend('Details: ');
$this->addDisplayGroup(array('submit'), 'buttons');
parent::init();
}
} | true |
7f086c621e82387efba51589ed703673277bf091 | PHP | IvanovAlmeida/Pandora | /src/Model/Table/UsersTable.php | UTF-8 | 860 | 2.90625 | 3 | [] | no_license | <?php
namespace App\Model\Table;
use App\Model\Entity\Entity;
use App\Model\Entity\User;
/**
* Class UsersTable
* @package App\Model\Table
*/
class UsersTable extends Table
{
public function __construct()
{
parent::__construct('Users');
}
/**
* @return User[]
*/
public function getAll(){
return $this->query
->table('users')
->class(User::class)
->select();
}
/**
* @param string $username
* @return User |null
*/
public function findByUsername(string $username){
$user = $this->query
->table('users')->class(User::class)
->where(['username = ?'])->select([$username]);
if(count($user) > 0)
return $user[0];
return null;
}
} | true |
d593ca61f9a09b1da20ef35f640333225a545520 | PHP | reinos/php-cache-class | /src/Cache/File.php | UTF-8 | 3,398 | 3.03125 | 3 | [] | no_license | <?php
namespace agking\Cache;
/**
* Simple class to deal with File Cache.
* @author Iain Cambridge
* @copyright All rights reserved 2009-2010 (c)
* @license http://backie.org/copyright/bsd-license BSD License
*/
class File implements CacheBase
{
/**
* Returns the cached variable or
* false if it doesn't exist.
* @param $VarName string
* @return mixed
*/
public function getVar($VarName)
{
$filename = $this->getFileName($VarName);
if (!file_exists($filename)) return false;
$h = fopen($filename, 'rb');
if (!$h) return false;
// Getting a shared lock
flock($h, LOCK_SH);
$data = file_get_contents($filename);
fclose($h);
$data = json_decode($data);
if (!$data) {
// If unserializing somehow didn't work out, we'll delete the file
unlink($filename);
return false;
}
if (is_readable($filename) && time() > $data[0]) {
// Unlinking when the file was expired
unlink($filename);
return false;
}
return $data[1];
}
/**
* Sets a variable to the cache.
* Returns true if successful and
* false if fails.
* Default time to live timeout is one hour
* @param $VarName string
* @param $VarValue mixed
* @param int $TimeLimit
* @return bool
* @throws \RuntimeException
* @internal param int $TimeLimit the amount of time before it expires
*/
public function setVar($VarName, $VarValue, $TimeLimit = 3600)
{
// Opening the file in read/write mode
$h = fopen($this->getFileName($VarName), 'ab+');
if (!$h) throw new \RuntimeException('Could not write to cache');
flock($h, LOCK_EX); // exclusive lock, will get released when the file is closed
fseek($h, 0); // go to the start of the file
// truncate the file
ftruncate($h, 0);
// Serializing along with the TTL
$data = json_encode(array(time() + $TimeLimit, $VarValue));
if (fwrite($h, $data) === false) {
throw new \RuntimeException('Could not write to cache');
}
fclose($h);
return true;
}
/**
* Deletes a variable from the cache.
* Returns true if successful and false
* if fails.
* @param $VarName string
* @return bool
*/
public function deleteVar($VarName)
{
$filename = $this->getFileName($VarName);
if (file_exists($filename)) {
return unlink($filename);
}
return false;
}
/**
* Clears the cache of the all the
* variables in it. Returns true if
* successful and false if it fails.
* @return bool
*/
public function clear()
{
$handle = opendir(CACHE_FOLDER);
while (false !== ($file = readdir($handle))) {
if ($file !== '.' && $file !== '..') {
if (is_dir(CACHE_FOLDER . $file)) {
//purge ($dir.$file.'/');
//rmdir($dir.$file);
} else {
unlink(CACHE_FOLDER . $file);
}
}
}
closedir($handle);
return true;
}
private function getFileName($VarName)
{
return CACHE_FOLDER . md5($VarName) . '.cache';
}
}
| true |
80fffce138e1ec09dbd366e24e1de7342c483a5d | PHP | wolfgangjoebstl/BKSLibrary | /IPSLibrary/app/modules/RemoteAccess/WriteJsonDescription.ips.php | UTF-8 | 1,851 | 2.796875 | 3 | [] | no_license | <?
/*
* This file is part of the IPSLibrary.
*
* The IPSLibrary is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The IPSLibrary is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with the IPSLibrary. If not, see http://www.gnu.org/licenses/gpl.txt.
*/
/*
* Aus den aktuellen Filenamen eine Description erfinden und Objekte Kategorisieren
* Alles als Json String in der Instanz Beschreibung abspeichern
*
*/
/* Struktur erfassen */
$alleKategorien = IPS_GetCategoryList();
//print_r($alleKategorien);
foreach ($alleKategorien as $Kategorie)
{
//echo $Kategorie." ".IPS_GetName($Kategorie)."\n";
}
$HardwareID=IPS_GetCategoryIDByName ("Hardware",0);
echo "Kategorie Hardware hat ID: ".$HardwareID."\n";
$FS20ID=IPS_GetCategoryIDByName ("FS20",$HardwareID);
echo "Kategorie FS20 hat ID: ".$FS20ID."\n";
$rooms=array("Wohnzimmer","Kellerzimmer","Arbeitszimmer");
$info=array();
$info["Ort"]="BKS";
$info["Typ"]="FS20";
$devices=IPS_GetChildrenIDs($FS20ID);
//print_r($devices);
foreach ($devices as $device)
{
$deviceName=IPS_GetName($device);
$evalName=explode("-",$deviceName);
echo $device." ".$deviceName." ".sizeof($evalName);
if (in_array($evalName[0],$rooms)==true)
{
$info["Raum"]=$evalName[0];
$infostring=json_encode($info);
echo " ".$infostring."\n";
IPS_SetInfo($device,$infostring);
}
else echo "\n";
}
?> | true |
10715739eef708654a0443647e9a48f80f222693 | PHP | Shri-Anand-Travels/bestflightdeals.co.uk | /app/helper.php | UTF-8 | 2,948 | 2.625 | 3 | [
"MIT"
] | permissive | <?php
if (!function_exists('cabinType')) {
function cabinType($cabin): string
{
return match ($cabin) {
"1" => "First Class",
"2" => "Business",
"3" => "Premium Economy",
"4" => "Economy",
default => "",
};
}
}
if (!function_exists('stopOrDirect')) {
function stopOrDirect($stop): string
{
return match ($stop) {
"Y" => "DIRECT",
"N" => "1 STOP",
default => "",
};
}
}
if (!function_exists('flightGoDepartTime')) {
function flightGoDepartTime($flight): string
{
return $flight->go_dep_time;
}
}
if (!function_exists('flightInDepartTime')) {
function flightInDepartTime($flight): string
{
return $flight->in_dep_time;
}
}
if (!function_exists('flightDestination')) {
function flightDestination($flight): string
{
if ($flight->Journey == "O") {
$destination = $flight->Destination;
} elseif ($flight->Journey == "R") {
$destination = match ($flight->Direct) {
"Y" => $flight->go_arrival,
default => $flight->Destination,
};
}
return empty($destination) ? '' : $destination;
}
}
if (!function_exists('flightArriveGoTime')) {
function flightArriveGoTime($flight): string
{
if ($flight->Journey == "O") {
$arrivalTime = match ($flight->Direct) {
"N" => $flight->go_via_arr_time,
"Y" => $flight->go_arr_time,
default => "",
};
} elseif ($flight->Journey == "R") {
$arrivalTime = match ($flight->Direct) {
"N" => $flight->go_via_arr_time,
"Y" => $flight->go_arr_time,
default => "",
};
}
return empty($arrivalTime) ? '' : $arrivalTime;
}
}
if (!function_exists('flightArriveInTime')) {
function flightArriveInTime($flight): string
{
if ($flight->Journey == "O") {
$arrivalTime = $flight->in_arr_time;
} elseif ($flight->Journey == "R") {
$arrivalTime = match ($flight->Direct) {
"N" => $flight->in_via_arr_time,
"Y" => $flight->in_arr_time,
default => "",
};
}
return empty($arrivalTime) ? '' : $arrivalTime;
}
}
if (!function_exists('flightArrivalInSource')) {
function flightArrivalInSource($flight): string
{
if ($flight->Journey == "O") {
$arrivalTime = $flight->Source;
} elseif ($flight->Journey == "R") {
$arrivalTime = match ($flight->Direct) {
"N" => $flight->in_via_arrival,
"Y" => $flight->in_arrival,
default => $flight->Source,
};
}
return empty($arrivalTime) ? '' : $arrivalTime;
}
}
| true |
584d04de96b8cd59a3444cf0b1f4f2faa0a52e7e | PHP | jacob-grahn/platform-racing-2-server | /vend/socket/Socket.php | UTF-8 | 6,453 | 2.84375 | 3 | [
"MIT"
] | permissive | <?php
/*
phpSocketDaemon 1.0
Copyright (C) 2006 Chris Chabot <chabotc@xs4all.nl>
See http://www.chabotc.nl/ for more information
This library 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 2.1 of the License, or (at your option) any later version.
This library 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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
namespace chabot;
abstract class Socket
{
public $socket;
public $bind_address;
public $bind_port;
public $domain;
public $type;
public $protocol;
public $local_addr;
public $local_port;
public $read_buffer = '';
public $write_buffer = '';
public function __construct(
$bind_address = 0,
$bind_port = 0,
$domain = AF_INET,
$type = SOCK_STREAM,
$protocol = SOL_TCP
) {
$this->bind_address = $bind_address;
$this->bind_port = $bind_port;
$this->domain = $domain;
$this->type = $type;
$this->protocol = $protocol;
if (($this->socket = @socket_create($domain, $type, $protocol)) === false) {
throw new \Exception("Could not create socket: ".socket_strerror(socket_last_error($this->socket)));
}
if (!@socket_set_option($this->socket, SOL_SOCKET, SO_REUSEADDR, 1)) {
throw new \Exception("Could not set SO_REUSEADDR: ".$this->getError());
}
if (!@socket_bind($this->socket, $bind_address, $bind_port)) {
throw new \Exception(
"Could not bind socket to [$bind_address - $bind_port]: "
.socket_strerror(socket_last_error($this->socket))
);
}
if (!@socket_getsockname($this->socket, $this->local_addr, $this->local_port)) {
throw new \Exception(
"Could not retrieve local address & port: "
.socket_strerror(socket_last_error($this->socket))
);
}
$this->setNonBlock(true);
}
public function __destruct()
{
if (is_resource($this->socket)) {
$this->close();
}
}
public function getError()
{
$error = socket_strerror(socket_last_error($this->socket));
socket_clear_error($this->socket);
return $error;
}
public function close()
{
if (is_resource($this->socket)) {
@socket_shutdown($this->socket, 2);
@socket_close($this->socket);
}
$this->socket = (int)$this->socket;
}
public function write($buffer, $length = 4096)
{
if (!is_resource($this->socket)) {
throw new \Exception("Invalid socket or resource");
} elseif (($ret = @socket_write($this->socket, $buffer, $length)) === false) {
throw new \Exception("Could not write to socket: ".$this->getError());
}
return $ret;
}
public function read($length = 4096)
{
if (!is_resource($this->socket)) {
throw new \Exception("Invalid socket or resource");
} elseif (($ret = @socket_read($this->socket, $length, PHP_BINARY_READ)) == false) {
throw new \Exception("Could not read from socket: ".$this->getError());
}
return $ret;
}
public function connect($remote_address, $remote_port)
{
$this->remote_address = $remote_address;
$this->remote_port = $remote_port;
if (!is_resource($this->socket)) {
throw new \Exception("Invalid socket or resource");
} elseif (!@socket_connect($this->socket, $remote_address, $remote_port)) {
throw new \Exception("Could not connect to {$remote_address} - {$remote_port}: ".$this->getError());
}
}
public function listen($backlog = 128)
{
if (!is_resource($this->socket)) {
throw new \Exception("Invalid socket or resource");
} elseif (!@socket_listen($this->socket, $backlog)) {
throw new \Exception(
"Could not listen to {$this->bind_address} - {$this->bind_port}: "
.$this->getError()
);
}
}
public function accept()
{
if (!is_resource($this->socket)) {
throw new \Exception("Invalid socket or resource");
} elseif (($client = socket_accept($this->socket)) === false) {
throw new \Exception(
"Could not accept connection to {$this->bind_address} - {$this->bind_port}: "
.$this->getError()
);
}
return $client;
}
public function setNonBlock()
{
if (!is_resource($this->socket)) {
throw new \Exception("Invalid socket or resource");
} elseif (!@socket_set_nonblock($this->socket)) {
throw new \Exception("Could not set socket non_block: ".$this->getError());
}
}
public function setBlock()
{
if (!is_resource($this->socket)) {
throw new \Exception("Invalid socket or resource");
} elseif (!@socket_setBlock($this->socket)) {
throw new \Exception("Could not set socket non_block: ".$this->getError());
}
}
public function setReceiveTimeout($sec, $usec)
{
if (!is_resource($this->socket)) {
throw new \Exception("Invalid socket or resource");
} elseif (!@socket_set_option($this->socket, SOL_SOCKET, SO_RCVTIMEO, array("sec" => $sec, "usec" => $usec))) {
throw new \Exception("Could not set socket recieve timeout: ".$this->getError());
}
}
public function setReuseAddress($reuse = true)
{
$reuse = $reuse ? 1 : 0;
if (!is_resource($this->socket)) {
throw new \Exception("Invalid socket or resource");
} elseif (!@socket_set_option($this->socket, SOL_SOCKET, SO_REUSEADDR, $reuse)) {
throw new \Exception("Could not set SO_REUSEADDR to '$reuse': ".$this->getError());
}
}
}
| true |
916744d887ac6fd49a909e773358c43b9a7bf62b | PHP | HiYangZhi/Pinche | /src/Models/Passenger.php | UTF-8 | 1,691 | 2.65625 | 3 | [] | no_license | <?php
namespace ZCJY\Pinche\Models;
use Eloquent as Model;
use Illuminate\Database\Eloquent\SoftDeletes;
/**
* Class Passenger
* @package App\Models
* @version February 16, 2017, 1:49 am UTC
*/
class Passenger extends Model
{
use SoftDeletes;
public $table = 'passengers';
protected $dates = ['deleted_at'];
protected $hidden = ['deleted_at'];//要屏蔽的字段
public $fillable = [
'openid',
'contact',
'nickname',
'sex',
'province',
'city',
'country',
'headimgurl',
'privilege',
'unionid'
];
/**
* The attributes that should be casted to native types.
*
* @var array
*/
protected $casts = [
'openid' => 'string',
'contact' => 'string',
'nickname' => 'string',
'sex' => 'string',
'province' => 'string',
'city' => 'string',
'country' => 'string',
'headimgurl' => 'string',
'privilege' => 'string',
'unionid' => 'string'
];
/**
* Validation rules
*
* @var array
*/
public static $rules = [
'openid' => 'required',
'contact' => 'requried'
];
/**
* 用户发布的拼车信息
* @return [type] [description]
*/
public function infoes()
{
return $this->hasMany('ZCJY\Pinche\Models\Info');
}
/**
* 用户参与的拼车信息
* @return [type] [description]
*/
public function participations(){
return $this->belongsToMany('ZCJY\Pinche\Models\Info', 'info_passenger', 'passenger_id', 'info_id')->withPivot('contact', 'seat');
}
}
| true |
4d2341d6f34ce280fc0385f4595b68af7b19ca1e | PHP | cherry-framework/console | /src/Console/Command/Debugger.php | UTF-8 | 2,693 | 2.84375 | 3 | [
"MIT"
] | permissive | <?php
/**
* The file contains Debugger trait
*
* PHP version 5
*
* @category Library
* @package Cherry
* @author Temuri Takalandze <takalandzet@gmail.com>
* @license https://github.com/cherry-framework/console/blob/master/LICENSE MIT
* @link https://github.com/cherry-framework/console
*/
namespace Cherry\Console\Command;
use Cherry\Console\Input\ArgvInput;
use Cherry\Console\Output\Output;
/**
* Debugger Trait for Cherry Console.
*
* @category Library
* @package Cherry
* @author Temuri Takalandze <takalandzet@gmail.com>
* @license https://github.com/cherry-framework/console/blob/master/LICENSE MIT
* @link https://github.com/cherry-framework/console
*/
trait Debugger
{
/**
* Run Cherry Features debugger.
*
* @param ArgvInput $input CLI Input interface
* @param Output $output CLI Output interface
*
* @return void
*/
private function _debug(ArgvInput $input, Output $output)
{
$argv = $input->getArgv();
if ($input->getArgvCount() == 1) {
$this->_debugHelp($output);
} else {
$this->_callDebuggerMethod($argv[1], $input, $output);
}
}
/**
* Call debugger by argument.
*
* @param string $method Method for calling
* @param ArgvInput $input CLI Input interface
* @param Output $output CLI Output interface
*
* @return void
*/
private function _callDebuggerMethod($method, ArgvInput $input, Output $output)
{
$method = '_debug'.ucfirst($method);
if (method_exists($this, $method)) {
$this->{$method}($input, $output);
} else {
$this->_debugHelp($output);
}
}
/**
* Get Debugger help
*
* @param Output $output CLI Output interface
*
* @return void
*/
private function _debugHelp(Output $output)
{
$help = file_get_contents(__DIR__.'/Debugger/Docs/help.txt');
print $output->text($help);
}
/**
* Debug Cherry Router.
*
* @param ArgvInput $input CLI Input interface
* @param Output $output CLI Output interface
*
* @return void
*/
private function _debugRouter(ArgvInput $input, Output $output)
{
echo $output->success('Cherry Router Debugger')."\n\n";
$routes = @file_get_contents(ROUTES_FILE);
$routes = json_decode($routes, 1);
foreach ($routes as $k => $v) {
$desc = '';
foreach ($v as $k2 => $v2) {
$desc .= <<<EOF
{$k2} - {$v2}
EOF;
}
$full = <<<EOF
{$output->info($k.':')}
{$desc}
EOF;
echo $output->text($full);
}
}
}
| true |