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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
24d88bbbedfd4beb22e5ef25639b3061a4f0cba2 | PHP | tokenly/laravel-event-log | /src/Middleware/LogAPICalls.php | UTF-8 | 2,968 | 2.578125 | 3 | [
"MIT"
] | permissive | <?php
namespace Tokenly\LaravelEventLog\Middleware;
use Closure;
use Exception;
use Tokenly\LaravelEventLog\Facade\EventLog;
use Symfony\Component\HttpKernel\Exception\HttpException;
class LogAPICalls {
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
// ------------------------------------------------------------------------
// Log Before call
$begin_log_vars = [
'method' => '',
'route' => '',
'uri' => '',
'parameters' => '',
'inputBodySize' => '',
];
// get the request details
$method = $request->method();
$begin_log_vars['method'] = $method;
$route = $request->route();
if ($route) {
$route_uri = $route->uri();
$route_name = $route->getName();
$route_params = $route->parameters();
} else {
$route_name = '[unknown]';
$route_uri = '[unknown]';
$route_params = [];
}
$begin_log_vars['route'] = $route_name;
$begin_log_vars['uri'] = $route_uri;
$begin_log_vars['parameters'] = $route_params;
$body_size = $request->header('Content-Length');
if (!$body_size) { $body_size = 0; }
$begin_log_vars['inputBodySize'] = $body_size;
EventLog::debug('apiCall.begin', $begin_log_vars);
// ------------------------------------------------------------------------
// Execute the next closure
$status_code = null;
$caught_exception = null;
try {
$response = $next($request);
$status_code = $response->getStatusCode();
} catch (Exception $e) {
$caught_exception = $e;
$status_code = 500;
if ($e instanceof HttpException) { $status_code = $e->getStatusCode(); }
}
// ------------------------------------------------------------------------
// Log after call
$end_log_vars = [
'method' => $begin_log_vars['method'],
'route' => $begin_log_vars['route'],
'uri' => $begin_log_vars['uri'],
'parameters' => $begin_log_vars['parameters'],
'status' => $status_code,
];
if ($caught_exception !== null) {
// log the exception and then throw the error again
EventLog::logError('apiCall.end', $caught_exception, $end_log_vars);
throw $caught_exception;
} else if ($response->isServerError() OR $response->isClientError()) {
EventLog::warning('apiCall.end', $end_log_vars);
} else {
EventLog::debug('apiCall.end', $end_log_vars);
}
return $response;
}
} | true |
b97f1090fa3dd44787fa907b69a0fcb68bc5e46e | PHP | jebc88/AlphaDesign | /TAREAS-INDIVIDUALES/14-Marzo/EstebanBenavides/lib/Carrito.php | UTF-8 | 1,716 | 2.640625 | 3 | [] | no_license | <?php
require_once("ConectorBD.php");
class Carrito {
var $redirectUrl = 'carrito.php';
function __construct() {
$this->revisarCarrito();
}
function revisarCarrito() {
if(array_key_exists('carrito',$_SESSION) === false){
$_SESSION['carrito']= array();
}
}
function __destruct() {
}
// Funciona bien
function agregarACarrito($idMarca,$idProducto, $qty=1) {
$id= ConectorBD::checkCartItem($idMarca, $idProducto);
if(!$id){
$newId=ConectorBD::newCartInsert($idMarca, $idProducto, $qty);
//array_push($_SESSION['carrito'],$newId);
$_SESSION['carrito'][$newId]= $qty;
header("Location: $this->redirectUrl");
}else {
ConectorBD::updateCartInsert($id, $qty);
$_SESSION['carrito'][$id]+= $qty;
header("Location: $this->redirectUrl");
}
}
// Funciona bien
function listadoItemesCarrito() {
$aItemesCarro = ConectorBD::searchCartItems();
return $aItemesCarro;
}
// Funciona bien
function modificarArticulo($idMarca, $idProducto ,$cantidad) {
$idCarrito= ConectorBD::checkCartItem($idMarca, $idProducto);
ConectorBD::editItemQuantity($idCarrito, $cantidad);
$_SESSION['carrito'][$idCarrito]=$cantidad;
}
// Funciona bien
function eliminarArticuloDeCarrito($idMarca, $idProducto) {
$idCarrito= ConectorBD::checkCartItem($idMarca, $idProducto);
if(array_key_exists($idCarrito,$_SESSION['carrito'])){
unset($_SESSION['carrito'][$idCarrito]);
ConectorBD::deleteCartItem($idCarrito);
}
}
}
?> | true |
7bfa15e0123f084a211882d1a2d9a181c33ba079 | PHP | codertiu/city-edu | /console/migrations/m180429_052216_create_students_leave_table.php | UTF-8 | 561 | 2.5625 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
use yii\db\Migration;
/**
* Handles the creation of table `students_leave`.
*/
class m180429_052216_create_students_leave_table extends Migration
{
/**
* @inheritdoc
*/
public function up()
{
$this->createTable('students_leave', [
'id' => $this->primaryKey(),
'students_is'=>$this->integer()->notNull(),
'comment_id'=>$this->integer()->notNull()
]);
}
/**
* @inheritdoc
*/
public function down()
{
$this->dropTable('students_leave');
}
}
| true |
7cec13044522d887a63a80fa6c4ae987e8b721ad | PHP | Cyapow/cti-tech-test | /app/Filters/QueryFilters.php | UTF-8 | 1,645 | 2.765625 | 3 | [] | no_license | <?php
namespace App\Filters;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Inertia\Inertia;
class QueryFilters
{
protected $request;
protected $builder;
protected $sortable;
public function __construct(Request $request)
{
$this->request = $request;
}
public function apply(Builder $builder): Builder
{
$this->builder = $builder;
foreach ($this->filters() as $name => $value) {
if (! method_exists($this, $name)) {
continue;
}
if (strlen($value)) {
$this->$name($value);
}
}
return $this->builder;
}
public function filters(): array
{
return $this->request->all();
}
public function sort($sort)
{
if (! $this->sortable) {
return $this->builder;
}
$column = $this->sortColumn($sort);
if (! in_array($column, $this->sortable)) {
return $this->builder;
}
$order = $this->sortOrder($sort);
Inertia::share('sortingColumn', $column);
Inertia::share('sortingAsc', $order == 'asc');
Inertia::share('sortKey', $sort);
return $this->builder->orderBy($column, $order);
}
protected function sortColumn($sort)
{
return substr($sort, 1);
}
protected function sortOrder($sort): string
{
$direction = substr($sort, 0, 1);
if ($direction == '+') {
return 'asc';
}
if ($direction == '-') {
return 'desc';
}
return '';
}
}
| true |
b3d9ad0ba133172f33718a25e48d34bbc9235df4 | PHP | jorgefprietol/reservasy | /lib/Application/Authentication/AuthenticatedUser.php | UTF-8 | 3,437 | 2.59375 | 3 | [] | no_license | <?php
/**
Copyright 2020 Prieto Linares, Jorge Fidel
This file is part of Agenda Capacitaciones Yanbal 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 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 Agenda Capacitaciones Yanbal. If not, see <http://www.gnu.org/licenses/>.
*/
class AuthenticatedUser
{
/**
* @var string
*/
private $username;
/**
* @var string
*/
private $email;
/**
* @var string
*/
private $fname;
/**
* @var string
*/
private $lname;
/**
* @var string
*/
private $password;
/**
* @var string
*/
private $languageCode;
/**
* @var string
*/
private $timezoneName;
/**
* @var string
*/
private $phone;
/**
* @var string
*/
private $organization;
/**
* @var string
*/
private $title;
/**
* @var string[]|null
*/
private $groups = null;
/**
* @param string $username
* @param string $email
* @param string $fname
* @param string $lname
* @param string $password
* @param string $languageCode
* @param string $timezoneName
* @param string $phone
* @param string $organization
* @param string $title
* @param string[]|null $groups
*/
public function __construct($username, $email, $fname, $lname, $password, $languageCode, $timezoneName, $phone, $organization, $title, $groups = null)
{
$this->username = $username;
$this->email = $email;
$this->fname = $fname;
$this->lname = $lname;
$this->password = $password;
$this->languageCode = empty($languageCode) ? Configuration::Instance()->GetKey(ConfigKeys::LANGUAGE) : $languageCode;
$this->timezoneName = $timezoneName;
$this->phone = $phone;
$this->organization = $organization;
$this->title = $title;
$this->groups = is_null($groups) ? array() : $groups;;
}
/**
* @return string
*/
public function Email()
{
return $this->EnsureNull($this->email);
}
/**
* @return string
*/
public function FirstName()
{
return $this->EnsureNull($this->fname);
}
/**
* @return string
*/
public function LanguageCode()
{
return $this->EnsureNull($this->languageCode);
}
/**
* @return string
*/
public function LastName()
{
return $this->EnsureNull($this->lname);
}
/**
* @return string
*/
public function Organization()
{
return $this->EnsureNull($this->organization);
}
/**
* @return string
*/
public function Password()
{
return $this->password;
}
/**
* @return string
*/
public function Phone()
{
return $this->EnsureNull($this->phone);
}
/**
* @return string
*/
public function TimezoneName()
{
return $this->timezoneName;
}
/**
* @return string
*/
public function Title()
{
return $this->EnsureNull($this->title);
}
/**
* @return string
*/
public function Username()
{
return $this->username;
}
private function EnsureNull($value)
{
$value = trim($value);
if (empty($value))
{
return null;
}
return trim($value);
}
/**
* @return string[]|null
*/
public function GetGroups()
{
return $this->groups;
}
} | true |
fc3ba52a33bc9bd65c413fff6c57d24291d9f9a4 | PHP | msmeeks/talk_examples_solid_principles | /2_open_closed_b.php | UTF-8 | 439 | 2.78125 | 3 | [] | no_license | <?php
/**
* Open-Closed Principle Resolution
*/
interface Metric
{
public function processMetric();
}
class FooMetric implements Metric
{
public function processMetric() {...}
}
class BarMetric implements Metric
{
public function processMetric() {...}
}
class MetricManager
{
public function processMetrics($metrics) {
foreach ($metrics as $metric) {
$metric->processMetric();
}
}
}
| true |
28cbdef603638b34cf5e42fcfb544f17ce7d136c | PHP | behnam-shahriari/socialseeder | /app/Http/Controllers/Auth/SignupController.php | UTF-8 | 951 | 2.640625 | 3 | [] | no_license | <?php
/**
* User: MB
* Date: 10/18/2020
*/
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\AppController;
use App\Models\Actor;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
class SignupController extends AppController {
public function signUp(Request $request) {
$user = $this->validate($request, [
'firstName' => 'required|string|min:5',
'lastName' => 'required|string|min:5',
'email' => 'required|email|unique:actors,email',
'password' => 'required|string|min:8',
]);
$user['email'] = strtolower($user['email']);
$user['permission'] = 'client';
$user['password'] = Hash::make($user['password']);
$newUser = Actor::create($user);
if (isset($newUser)) {
return $this->success($newUser, "User has been signed up", [], 201);
}
return $this->error("Error in user creation");
}
}
| true |
b58860e9c8aa768c9001a2f9ddc56d16fe656739 | PHP | anna0308/MVC | /app/system/view.php | UTF-8 | 200 | 2.546875 | 3 | [] | no_license | <?php
class system_view
{
public function render($file)
{
if(file_exists('../views/'.$file.'.php')){
include('../views/'.$file.'.php');
} else {
echo "ERROR: file not found";
}
}
}
?> | true |
d8563b0f68b0dd221660e07804032bcd73008663 | PHP | 255153YW/php-test | /models/database/Employee.php | UTF-8 | 267 | 2.65625 | 3 | [] | no_license | <?php
/**
* Simple class used to represent the employee tables from the database
**/
Class Employee{
public $id;
public $firstname;
public $lastname;
public $address;
public $salary;
public $contact;
public $position;
public $username;
public $password;
}
?> | true |
dfadcbb37718ebaa5f5716fe8ea78a3dbff60a66 | PHP | MonirHossen/OOP-PHP | /basic program/p6.php | UTF-8 | 439 | 4.125 | 4 | [] | no_license |
<!--5. Find first N prime number.-->
<?php
$n = 200;
$primeCount = 0;
$k = 1;
while ($primeCount < $n)
{
if (IsPrime($k))
{
$primeCount++;
print "$primeCount : $k <br>";
}
$k ++;
}
function IsPrime($a)
{
$count = 0;
$s = sqrt($a);
for($i = 2; $i < $s; $i++)
{
if($a % $i == 0)
$count++;
break;
}
if ($count==0)
return true;
return false;
}
| true |
e959214204ea260532b3e50fdde2af30764b2500 | PHP | keepeye/webframe | /application/common/model/AdminUser.php | UTF-8 | 1,818 | 2.65625 | 3 | [
"Apache-2.0"
] | permissive | <?php
namespace app\common\model;
use app\component\contracts\AuthUser;
use think\Model;
/**
* 后台用户类
*
* 需要实现 \app\component\contracts\AuthUser 接口
*
* @package app\common\model
*/
class AdminUser extends Model implements AuthUser
{
/**
* @inheritdoc
*/
protected $table = 'admin_users';
protected $field = true;
protected $validate = 'common/AdminUser';
public static function init()
{
static::event('before_insert', [static::class,'onInsert']);
}
/**
* @inheritdoc
*/
public static function login($username,$password)
{
$user = static::get(['username'=>$username]);
if (!$user) {
return false;
}
if (!$user->checkPassword($password)) {
return false;
}
//更新登陆时间、ip
$user->setAttr('last_login_ip',request()->ip());
$user->setAttr('last_login_time',date('Y-m-d H:i:s'));
$re = $user->save();
if ($re === false) {
throw new \Exception($user->getError());
}
return $user;
}
/**
* @inheritdoc
*/
public static function findByIdentity($identity)
{
$user = static::get(['id'=>$identity]);
if (!$user) {
return null;
}
return $user;
}
/**
* @inheritdoc
*/
public function getIdentity()
{
return $this->id;
}
/**
* @inheritdoc
*/
public function checkPassword($password)
{
return $this->password == xz_hash($password);
}
public function setPasswordAttr($value)
{
return xz_hash($value);
}
protected static function onInsert(Model $obj)
{
$obj->setAttr('created_at',date('Y-m-d H:i:s'));
}
}
| true |
66bd24cac3a0c8af7e80cb5bbae97132d7ac8503 | PHP | ami0rez/Orientawjh | /Website/orientawjih-j/fct/classes/Choix.php | UTF-8 | 1,445 | 2.828125 | 3 | [] | no_license | <?php
class Choix{
public $id_ad=-1,$id_et=-1,$id,$diplomes,$lieus;
public $name,$desc,$date;
public $horizons,$fillieres,$conditions;
function __construct($id, $name, $desc) {
$this->id = $id;
$this->name = $name;
$this->desc = $desc;
}
}
class Filliere{
public $id;
public $name;
function __construct($id, $name) {
$this->id = $id;
$this->name = $name;
}
}
class Diplome{
public $id;
public $nom;
public $duree;
function __construct($id, $nom, $duree) {
$this->id = $id;
$this->nom = $nom;
$this->duree = $duree;
}
}
class Horizon{
public $id;
public $name;
//don't add diplmoes here cuz we xont have only one horizon
function __construct($id,$name) {
$this->id = $id;
$this->name = $name;
}
}
class Condition{
public $age_d,$age_f;
public $Note_seuile;
public $nbr_places,$id;
function __construct($id,$age_d,$age_f, $note_seuile,$nbr_places) {
$this->nbr_places=$nbr_places;
$this->id=$id;
$this->age_d = $age_d;
$this->age_f=$age_f;
$this->Note_seuile = $note_seuile;
}
}
class Lieu{
public $id;
public $name;
public $Long,$Latt;
function __construct($id, $name, $aLong, $latt) {
$this->id = $id;
$this->name = $name;
$this->Long = $aLong;
$this->Latt = $latt;
}
}
?>
| true |
6ba52248127505752e50ae9bbeec7a3bdb2714d5 | PHP | HelenVolovyk/mvc_shop | /Framework/Core/ErrorHandler.php | UTF-8 | 270 | 2.71875 | 3 | [] | no_license | <?php
namespace Framework\Core;
class ErrorHandler
{
public function register()
{
set_exception_handler([$this, 'exceptionHandler']);
}
public function exceptionHander(\Exception $e)
{
$this->showError(get_class($e), $e->getMessage());
return true;
}
} | true |
08381dd852e7eaa8eff508cc155bb695a53f775b | PHP | ducthang310/Zend-Bag | /modules/configuration/models/DbTable/Configuration.php | UTF-8 | 692 | 2.53125 | 3 | [] | no_license | <?php
class Configuration_Model_DbTable_Configuration extends Base_Model_DbTable_Backend
{
protected $_name = 'configuration';
protected static $_instance = NULL;
public function __construct($config = array())
{
parent::__construct($config);
}
public static function getInstance()
{
if (null === self::$_instance) {
self::$_instance = new self();
}
return self::$_instance;
}
public function getAll()
{
$db = Zend_Db_Table::getDefaultAdapter();
$select = $db->select();
$select->from('configuration', '*');
return $db->fetchAll($select);
}
} | true |
f48312ffab8ea95cc89612848e7d826202c73e91 | PHP | hrishiraol/monitoring | /oauth/getzohodata1.php | UTF-8 | 12,802 | 2.53125 | 3 | [] | no_license | <html>
<title>Bulk API - Oauth</title>
<body>
<h1>Create Bulk Report</h1>
<form action="" method="post">
<input type="submit" name="refreshToken" value="Refresh" /><br>
<input type="submit" name="createBulkReport" value="Create" /><br>
<input type="submit" name="checkBulkReport" value="Check" /><br>
<input type="submit" name="downloadBulkReport" value="Download" /><br>
</form>
<?php
if(isset ($_POST['createBulkReport'])){
createBulkReport();
}
if(isset ($_POST['checkBulkReport'])){
checkBulkReport();
}
if(isset ($_POST['downloadBulkReport'])){
downloadBulkReport();
}
if(isset ($_POST['refreshToken'])){
RenewRefreshToken();
}
/*
when the page loads, initaite first function - createBulkReport()
if access token is invalid
then RenewalRefreshToken() && createBulkReport()
wait for 30 sec to checkBulkReport()
keep checking checkBulkReport every 30 sec till it returns status - completed
then downloadBulkReport()
*/
//createBulkReport();
if (checkForAccess() =="INVALID_TOKEN"){
echo "Code: ".checkForAccess();
RenewRefreshToken();
createBulkReport();
checkBulkReport();
sleep (60);
downloadBulkReport();
} else {
checkBulkReport();
sleep (60);
downloadBulkReport();
}
function checkForAccess(){
$checktoken = file_get_contents("jobid0.json");
$array = json_decode($checktoken);
$codeStatus = $array->code;
return $codeStatus;
//var_dump($array);
//echo "\nCode from job: ".$codeStatus."<br>";
//echo "CODE: ". $array['data'][0]['code']."<br>";
/*
$valid = "Valid code";
$invalid = "Invalid code";
if ($codeStatus="INVALID_TOKEN"){
return $invalid;
} else {
return $valid;
} */
}
function createBulkReport(){
$readJson = file_get_contents("zoho-authtoken.json");
$array = json_decode($readJson);
$access_Token = $array->access_token;
$queryaccntapi = file_get_contents("queryaccntapi.json");
$queryequipapi = file_get_contents("queryequipapi.json");
$query = array();
$query[]= $queryaccntapi;
$query[]= $queryequipapi;
$filename= 0;
foreach ($query as $queryjob){
$ch = curl_init();
$curl_options = array();
$curl_options[CURLOPT_URL] = "https://www.zohoapis.com/crm/bulk/v2/read";
$curl_options[CURLOPT_RETURNTRANSFER] = true;
$curl_options[CURLOPT_HEADER] = 0; //Get Header details 0=false
$curl_options[CURLOPT_CUSTOMREQUEST] = "POST";
$curl_options[CURLOPT_POSTFIELDS]= $queryjob;
$headersArray = array();
$headersArray[] = "Authorization". ":" . "Zoho-oauthtoken " . $access_Token;
$headersArray[] = "Content-Type".":"."application/json";
$curl_options[CURLOPT_HTTPHEADER]=$headersArray;
curl_setopt_array($ch, $curl_options);
$result = curl_exec($ch);
curl_close($ch);
$fname= "jobid".$filename.".json";
file_put_contents($fname, $result);
$filename ++;
$query1 = array();
$query1[]= file_get_contents($fname);
}
}
function RenewRefreshToken(){
//echo "\nRenerefreshed called";
$readJson = file_get_contents("zohoauth.json");
$array = json_decode($readJson);
$client_id = $array->client_id;
$client_secret = $array->client_secret;
$refresh_token = $array->refresh_token;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://accounts.zoho.com/oauth/v2/token" );
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'refresh_token' => $refresh_token,
'client_id' => $client_id,
'client_secret' => $client_secret,
'grant_type' => 'refresh_token'
));
$response = curl_exec($ch);
file_put_contents("zoho-authtoken.json", $response);
//echo "Token Refreshed: ".json_decode($response)->access_token;
//var_dump($response);
//return json_decode($response)->access_token;
//header("Location: getzohodata.php");
}
function checkBulkReport(){
//echo "\nCheckBulkReport";
$readaccessToken = file_get_contents("zoho-authtoken.json");
$array = json_decode($readaccessToken);
$access_Token = $array->access_token;
$readID = JobID();
$filename= 0;
foreach($readID as $jobID){
$jobidcheck = $jobID['ID'];
$ch = curl_init();
$curl_options = array();
$curl_options[CURLOPT_URL] = "https://www.zohoapis.com/crm/bulk/v2/read/". $jobidcheck;
$curl_options[CURLOPT_RETURNTRANSFER] = true;
$curl_options[CURLOPT_HEADER] = 0; //Get Header details 0=false
$curl_options[CURLOPT_CUSTOMREQUEST] = "GET";
$headersArray = array();
$headersArray[] = "Authorization". ":" . "Zoho-oauthtoken " . $access_Token;
$headersArray[] = "Content-Type".":"."application/json";
$curl_options[CURLOPT_HTTPHEADER]=$headersArray;
curl_setopt_array($ch, $curl_options);
$result = curl_exec($ch);
curl_close($ch);
$fname= "checkjobid".$filename.".json";
file_put_contents($fname, $result);
$filename ++;
$query = array();
$query[]= file_get_contents($fname);
foreach ($query as $queryjob){
echo "Details"."<br>";
$jsonResponse = json_decode($queryjob);
$id = $jsonResponse->data[0]->id;
$state = $jsonResponse->data[0]->state;
$d_url = $jsonResponse->data[0]->result->download_url;
echo "Status: ". $state."<br>";
echo "JOB ID: ". $id."<br>";
echo "D URL : ". $d_url."<br>";
}
}
}
function checkReportStatus(){
$checkStatus = file_get_contents("checkjobid0.json");
$array = json_decode($checkStatus);
$reportStatus = $array->data[0]->state;
return $reportStatus;
}
function downloadBulkReport(){
$readaccessToken = file_get_contents("zoho-authtoken.json");
$array = json_decode($readaccessToken);
$access_Token = $array->access_token;
$readID = JobID();
$filename= 0;
foreach($readID as $jobID){
$jobidcheck = $jobID['ID'];
$ch = curl_init();
$curl_options = array();
$curl_options[CURLOPT_URL] = "https://www.zohoapis.com/crm/bulk/v2/read/". $jobidcheck."/result";
$curl_options[CURLOPT_RETURNTRANSFER] = true;
$curl_options[CURLOPT_HEADER] = 0; //Get Header details 0=false
$curl_options[CURLOPT_CUSTOMREQUEST] = "GET";
$headersArray = array();
$headersArray[] = "Authorization". ":" . "Zoho-oauthtoken " . $access_Token;
$headersArray[] = "Content-Type".":"."application/zip";
$curl_options[CURLOPT_HTTPHEADER]=$headersArray;
curl_setopt_array($ch, $curl_options);
$result = curl_exec($ch);
$responseInfo = curl_getinfo($ch);
curl_close($ch);
$directory = "zipfiles/";
$filepath= $directory."csv".$filename.".zip";
file_put_contents($filepath, $result);
extractZipArchive($filepath, "csvfiles/");
convertToJson("csvfiles/".$jobidcheck.".csv", $jobidcheck);
$filename++;
}
echo "Json created"."<br>";
changeFile();
}
function convertToJson($fname, $jid){
if (!($fp = fopen($fname, 'r'))) {
die("Can't open file...");
}
//read csv headers
$key = fgetcsv($fp,"1024",",");
// parse csv rows into array
$json = array();
while ($row = fgetcsv($fp,"1024",",")) {
$json[] = array_combine($key, $row);
}
// release file handle
fclose($fp);
$jfp = fopen("json/".$jid.".json","w");
fwrite($jfp, json_encode($json));
fclose($jfp);
// encode array to json
// return json_encode($json);
}
function JobID(){
$queryaccntapi = file_get_contents("jobid0.json");
$queryequipapi = file_get_contents("jobid1.json");
$query = array();
$query[]= $queryaccntapi;
$query[]= $queryequipapi;
foreach ($query as $queryjob){
$jsonResponse = json_decode($queryjob);
$status = $jsonResponse->data[0]->status;
$id = $jsonResponse->data[0]->details->id;
$jobarray[] = array(
'ID'=>$id,
'Status'=>$status
);
}
return $jobarray;
}
function changeFile(){
$accntID = file_get_contents("jobid0.json");
$equipID = file_get_contents("jobid1.json");
$jsonconvert1 = json_decode($accntID );
$jsonconvert2 = json_decode($equipID);
$id1 = $jsonconvert1->data[0]->details->id;
$id2 = $jsonconvert2->data[0]->details->id;
$accntPath = "json/".$id1.".json";
$equipPath = "json/".$id2.".json";
if (file_exists($accntPath)){
rename ($accntPath, "json/account.json");
rename ($equipPath, "json/equiplist.json");
echo "Files Renamed !!!"."<br>";
} else{
echo "Files does not Exists!!";
}
}
function extractZipArchive($archive, $destination){
$zip = new ZipArchive();
// Check if archive is readable.
if($zip->open($archive) === TRUE){
// Check if destination is writable
if(is_writeable($destination)){
$zip->extractTo($destination);
$zip->close();
//echo 'Files unzipped successfully';
}else{
//echo 'Directory not writeable by webserver.';
}
}else{
//echo 'Cannot read '. $archive.' archive.';
}
}
?>
</body>
</html> | true |
7538c4616ec58edce5e2c9714af261db9e475380 | PHP | petidesoftwares/filmsalesservice_api | /app/Models/Customer.php | UTF-8 | 2,261 | 2.65625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Tymon\JWTAuth\Contracts\JWTSubject;
class Customer extends Authenticatable implements JWTSubject
{
use HasFactory, SoftDeletes, Notifiable;
public $timestamps =true;
protected $fillable = [
'firstname',
'middle_name',
'surname',
'gender',
'email',
'dob',
'phone',
'password'
];
/**
* Hidden attributes
* @var string[]
*/
protected $hidden = [
'password', 'deleted_at'
];
/**
* Get the email the email to send the password reset link to
* @return mixed
*/
public function getPasswordResetEmail(){
return $this->email;
}
/**
* Get the orders of a customer by relationship
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function customerOrders(){
return $this->hasMany('App\Model\Orders','customer_id','id');
}
/**
* Get the cart associated to a customer by relationship
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function carts(){
return $this->hasMany('App\Model\Cart','customer_id','id');
}
/**
* Get the credit card of the customer
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function creditCard(){
return $this->hasMany('App\Models\CreditCard','customer_id','id');
}
/**
* Get the customers orders
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function order(){
return $this->hasMany('App\Models\Order','customer_id','id');
}
/**
* Get the JWT authentication identifier
* @return mixed
*/
public function getJWTIdentifier()
{
return $this->getKey();
}
/**
* Return a key value array, containing any custom claims to be added to the JWT.
*
* @return array
*/
public function getJWTCustomClaims()
{
return [];
}
}
| true |
9caec40a8aca6299c6b8df2a33b2aa7e923affe2 | PHP | Diamondgal/cbc5Project | /eventCreate1.php | UTF-8 | 1,223 | 2.78125 | 3 | [] | no_license | <?php
// header("content-type: text/plain");
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Headers: "origin, x-requested-with, content-type"');
header('Access-Control-Allow-Methods "GET, POST, OPTIONS"');
// header('Content-Type', 'application/x-www-form-urlencoded');
$servername = '';
$username = '';
$password = '';
$dbname = '';
//connect.php stores 4 variable names.
include "connect.php";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
// need to select & prepare data for the options dropdown on hostPage.html
if (isset($_GET["createEvent"])) {
$event = $_GET["createEvent"];
}
// echo $event;
$stmt = $conn->prepare("SELECT createEvent FROM events");
$stmt -> execute(['$event']);
$stmt -> setFetchMode(PDO::FETCH_ASSOC);
$tableRow = $stmt -> fetchAll();
$myJSON = json_encode($tableRow);
echo $myJSON;
// foreach ($tableRow as $t) {
// echo $t<option id="createEvent" value=""></option>;
?> | true |
e8345ff80ca98cb1e42b9805cf7aebb5c0bd5774 | PHP | ariel0080/Programacion3 | /previa/PIZZERIA/manejadores/1productoCarga.php | UTF-8 | 1,102 | 2.75 | 3 | [] | no_license | <!-- 1- POST - > va al index HeladoCarga.php
se ingresa sabor precio tipo (crema o agua) cantidad de kg
se guardan los datos tomando el sabor y el tipo como identificador ( no se puede repetir)
---------------- se guarda en helados.txt (o csv)---------------- -->
<?php
echo "<font size='3' color='blue' face='verdana' style='font-weight:bold' <br>Alta PRODUCTO (sin imagen) <br> </font>";
if (isset($_POST["sabor"]) && isset( $_POST ["tipo"] ) && isset( $_POST ["cantidad"]) && isset($_POST ["precio"]))
{
Pizzeria::agregarProducto($_POST["sabor"], $_POST["tipo"], $_POST["cantidad"], $_POST["precio"], null);
}
/* $sabor = $_POST["sabor"];
$tipo= $_POST["tipo"];
$cantidad= $_POST["cantidad"];
$precio= $_POST["precio"];
$lista = Heladeria::LeerJSON("./archivos/helados.txt", "helado");
$helado = Heladeria::existeHelado($lista, $sabor, $tipo);
if ($helado == null) {
$nuevoHelado = new Helado($sabor, $tipo, $cantidad, $precio);
array_push($lista, $nuevoHelado);
Heladeria::guardarJsonHeladeria($lista, "./archivos/helados.txt", "helado");
}
*/
| true |
c30e5400819ed1e66a8a2b9c5a74bc43a2977307 | PHP | hiadm/yblog | /modules/home/modules/content/controllers/ArticleController.php | UTF-8 | 973 | 2.515625 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
/**
* Created by PhpStorm.
* User : daimajie
* Email: daimajie@qq.com
* Date : 2019/2/20
* Time : 13:43
*/
namespace app\modules\home\modules\content\controllers;
use app\models\content\Article;
use app\modules\home\controllers\BaseController;
use yii\helpers\VarDumper;
use yii\web\NotFoundHttpException;
class ArticleController extends BaseController
{
//显示文章
public function actionView($id){
$model = $this->findModel($id);
//增加访问次数
$model->updateCounters(['visited' => 1]);
return $this->render('view',[
'model' => $model,
'prevAndNext' => Article::getPrevNext($id, $model['topic_id'])
]);
}
/**
* 获取指定文章
*/
protected function findModel($id)
{
if (($model = Article::singleArticle($id)) !== null) {
return $model;
}
throw new NotFoundHttpException('您请求的页面不存在.');
}
} | true |
8ed156f540238423e2e11584e5b29f6e595ad9c2 | PHP | jeroendn/cloudstorage-website | /php/ajax/add_share.php | UTF-8 | 1,324 | 2.59375 | 3 | [] | no_license | <?php
session_start();
include_once '../../php/dbconnection.php';
if ($_POST['mail'] != '' && $_POST['document_id'] != '') {
// get user data (ID)
$sql = "SELECT user_id FROM user WHERE user_mail=:mail LIMIT 1";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':mail', $_POST['mail'], PDO::PARAM_STR);
$stmt->execute();
$user = $stmt->fetchAll();
// check if file is already shared
$sql = "SELECT user_id, document_id FROM share WHERE user_id=:user_id AND document_id=:document_id LIMIT 1";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':user_id', $user[0]['user_id'], PDO::PARAM_STR);
$stmt->bindParam(':document_id', $_POST['document_id'], PDO::PARAM_STR);
$stmt->execute();
$share = $stmt->fetchAll();
// create the share
if (!empty($user[0]['user_id'])) {
if (empty($share)) {
$sql = "INSERT INTO share (document_id, user_id) VALUES (:document_id, :user_id)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':document_id', $_POST['document_id'], PDO::PARAM_STR);
$stmt->bindParam(':user_id', $user[0]['user_id'], PDO::PARAM_INT);
$stmt->execute();
}
else {
die(header("HTTP/1.0 400 File is already shared"));
}
}
else {
die(header("HTTP/1.0 404 User doesn't exist"));
}
}
else {
die(header("HTTP/1.0 400 Empty field"));
}
| true |
d16e5bf71dd9e772ff3ed00545e0cee4465326a8 | PHP | brunarocha/view-xml | /app/Http/Controllers/ReadXmlController.php | UTF-8 | 1,488 | 2.640625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ReadXmlController extends Controller
{
public function create()
{
return view('import.create');
}
public function store(Request $request)
{
$xml = simplexml_load_file($request->file('file'));
$newList = [];
foreach($xml as $row){
$obj = new \stdClass;
$obj = $row;
array_push($newList, $obj);
}
//dd($newList);
return view('import.show')->with('items', $newList);
}
/* public function SimpleXML2Array($xml){
$array = $xml;
//recursive Parser
foreach ($array as $key => $value){
if(strpos(get_class($value),"SimpleXMLElement")!==false){
$array[$key] = $this->SimpleXML2Array($value);
//$array[$key] = $value;
}
}
$l = [];
foreach ($array as $key => $value){
array_push($l,
"<label>$key: $value</label>");
}
return $array;
}*/
/*public function SimpleXML2Array($xml){
//$array = (array)$xml;
$array = $xml;
//recursive Parser
foreach ($array as $key => $value){
if(strpos(get_class($value),"SimpleXMLElement")!==false){
$array[$key] = $this->SimpleXML2Array($value);
//$array[$key] = $value;
}
}
return $array;
}*/
}
| true |
e331385f3e91fbacb3eb778cd324d90e8d104c82 | PHP | fortinhovihamba/SmartListApp | /pages/login.php | UTF-8 | 1,677 | 2.546875 | 3 | [] | no_license | <?php
session_start();
require_once('app/cnx.php');
if (isset($_POST['ok'])) {
extract($_POST);
$pass= sha1($pass);
$requete = "SELECT * FROM t_user LEFT JOIN t_role ON t_role.idrole=t_user.idrole
WHERE t_user.email='$login'AND t_user.mdps='$pass'
ORDER BY t_user.iduser asc";
$resultat = $bdd->query($requete);
$req=$resultat->rowCount();
if ($req > 0 ) {
// code...
foreach ($resultat as $data) {
// code...
$_SESSION['id'] = $data['iduser'];
$_SESSION['name'] = $data['noms'];
$_SESSION['slug'] = $data['slug'];
if($data['slug']=="admin"){
header("Location:pages/admin/admin.php");
}elseif ($data['slug']=="manager") {
// code...
header("Location:pages/users/user.php");
}
else{
header("Location:pages/users/utilisateur.php");
}
}
}
}
?>
<div class="login-box">
<form action="index.php?p=login" method="POST" class="form-horizontal">
<div class="textbox">
<span class="fa fa-user"</span>
<input type="text" placeholder="Entrez l'adresse email" name="login">
</div>
<div class="textbox">
<span class="fa fa-lock"</span>
<input type="password" placeholder="Entrez le mot de passe" name="pass">
</div>
<div class="btn1">
<button type="submit" class="btn btn-outline-primary my-2 my-sm-0" name="ok">Se connecter</button>
</div>
</form>
</div>
<br><br>
<p class="text-center"><a href="index.php?p=loginens">Se connecter étant Enseignant</a> | <a href="index.php?p=loginstd">Se connecter étant Étudiant</a></p>
<br><br>
| true |
ff704fa9a7d23f2b4983701cfbb5f41f3737bbc0 | PHP | pixeline/bugs | /install/install.php | UTF-8 | 4,350 | 2.671875 | 3 | [
"MIT"
] | permissive | <?php
class install {
public $config;
function __construct() {
$this->config = require '../config.app.php';
$this->language = $_GET["Lng"] ?? "en";
$this->language = require '../app/application/language/'.$_GET["Lng"].'/install.php';
}
public function check_connect() {
@$connect = ($GLOBALS["___mysqli_ston"] = mysqli_connect($this->config['database']['host'], $this->config['database']['username'], $this->config['database']['password']));
if(!$connect) { return array('error' => '<strong>'.($this->language['Database_Connect_Error'] ?? "We could not connect to database").'.</strong>!'); }
$check_db = $this->check_db($connect);
return $check_db;
if(!$check_db) { return array('error' => '<strong>'.($this->language['Database_Error'] ?? "Error on database process").'.</strong>'); }
return $check_db;
}
public function check_requirements() {
$errors = array();
if(!extension_loaded('pdo')) { $errors[] = 'pdo extension not found.'; }
if(!extension_loaded('pdo_mysql')) { $errors[] = 'mysql driver for pdo not found .'; }
if(version_compare(PHP_VERSION, '7.1', '<') && !extension_loaded('mcrypt')) { $errors[] = 'mcrypt extension not found.'; }
if(version_compare(PHP_VERSION, '7.0', '>') && !extension_loaded('openSSL')) { $errors[] = 'openSSL extension not found.'; }
if(version_compare(PHP_VERSION, '7.3', '<')) { $errors[] = 'PHP too old for Bugs. PHP 7.3 or above is needed.'; }
if(version_compare(PHP_VERSION, '8.0', '>') && !extension_loaded('openSSL')) { $errors[] = 'openSSL extension not found.'; }
return $errors;
}
public function check_tables($tab) {
return ($this->Requis("SELECT * FROM ".$tab."")) ? true : false;
}
public function create_database() {
$connect = mysqli_connect($this->config['database']['host'], $this->config['database']['username'], $this->config['database']['password']);
mysqli_query ($connect, "CREATE DATABASE IF NOT EXISTS ".$_POST['database_name']);
$this->db = mysqli_connect($this->config['database']['host'], $this->config['database']['username'], $this->config['database']['password'], $this->config['database']['database']);
return $this->db;
}
public function create_tables() {
$tablesCreator = require './mysql-structure.php';
foreach($tablesCreator as $query) {
$this->Requis($query);
}
}
public function create_adminUser() {
require '../app/laravel/hash.php';
require '../app/laravel/str.php';
/* Create Administrator Account */
$email = (trim($_POST["email"]) != '' ) ? $_POST["email"] : 'admin@email.com';
$first_name = (trim($_POST["first_name"]) != '' ) ? $_POST["first_name"] : 'first_name';
$last_name = (trim($_POST["last_name"]) != '' ) ? $_POST["last_name"] : 'last_name';
$password = (trim($_POST["password"]) != '' ) ? $_POST["password"] : 'admin';
$work = str_pad(8, 2, '0', STR_PAD_LEFT);
$salt = substr(str_shuffle(str_repeat('01234567789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',5)),0,40);
$salt = substr(strtr(base64_encode($salt), '+', '.'), 0, 22);
$password = crypt($password, '$2a$'.$work.'$'.$salt);
$language = $_POST['language'];
/* Check if email exists if so change the password on it */
$test_query = "select * from users where email = '".$email."' and deleted = 0 LIMIT 1";
$test_result = $this->Requis($test_query);
if($this->Combien($test_result) >= 1) {
$query = "UPDATE `users` SET
password = '".$password."',
firstname = '".$first_name."',
lastname = '".$last_name."'
WHERE email = '".$email."' AND deleted = 0
LIMIT 1
";
} else {
$query = "
INSERT INTO users(
role_id,
email,
password,
firstname,
lastname,
language,
created_at
)VALUES(
4,
'".$email."',
'".$password."',
'".$first_name."',
'".$last_name."',
'".$language."',
now()
)";
}
mysqli_query($GLOBALS["___mysqli_ston"], $query);
return true;
}
private function check_db($connect) {
$database_connect = ((bool)mysqli_query( $connect, "USE " . $this->config['database']['database']));
if($database_connect) {
return $database_connect;
}
return false;
}
public function Combien($resu) {
return mysqli_num_rows($resu);
}
public function Requis ($query) {
return mysqli_query($this->db, $query);
}
}
| true |
9711f5ac793453cf808ce5db2c1d4dc48696e309 | PHP | Tombrown1/inventory | /index.php | UTF-8 | 2,653 | 2.71875 | 3 | [] | no_license | <?php
session_start();
include_once 'database/connect.php';
$mysqli = dbconnect();
include_once 'classes/users.php';
if(isset($_POST['login'])){
$email = $_POST['email'];
$password = $_POST['password'];
// print_r($_POST);
// exit();
// Sanitize the Login variables before inseerting into the database!
$email = mysqli_real_escape_string($mysqli, $email);
$password = mysqli_real_escape_string($mysqli, $password);
$result = user_login($mysqli, $email, $password);
if(mysqli_num_rows($result) > 0){
while ($user_row = mysqli_fetch_assoc($result)) {
$_SESSION['user_id'] = $user_row['user_id'];
$_SESSION['fname'] = $user_row['fname'];
}
header("Location: view/supplier.php?Login = Success!");
}else{
header("Location: signup.php?Login = Error!");
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Signup</title>
<link rel="stylesheet" type="text/css" href="assets/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="assets/style/form.css" >
</head>
<body>
<section class="container-fluid bg">
<section class="row justify-content-center">
<section class="col-12 col-sm-6 col-md-3">
<div class="container header">
<h3>Inventory POS</h3>
</div>
<form class="form-container" action="<?php $_SERVER['PHP_SELF'] ?>" Method="POST">
<div class="form-group">
<label for="email">Email</label>
<input type="email" name="email" class="form-control" placeholder="Email" required>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" name="password" class="form-control" placeholder="Password" required>
</div>
<button type="submit" name="login" class="btn btn-primary btn-block">Submit</button><br>
<a href="signup.php" class="btn btn-info float-right"> Sign Up</a>
</form>
</section>
</section>
</section>
<script src="assets/jquery/cdn.jsdelivr.net_npm_jquery@3.2_dist_jquery.min"></script>
<script src="assets/jquery/bootstrap.min.js"></script>
</body>
</html> | true |
45c3577cf51a9b9a8784f87c7560b286e2ffd4ff | PHP | QuentG/MyBnb | /src/Service/Pagination.php | UTF-8 | 6,059 | 3.015625 | 3 | [] | no_license | <?php
namespace App\Service;
use Doctrine\Common\Persistence\ObjectManager;
use Exception;
use Symfony\Component\HttpFoundation\RequestStack;
use Twig\Environment;
/**
* Classe de Pagination qui extrait toute notion de calcul et de récupération de données de nos controllers
*
* Elle nécessite après instanciation qu'on lui passe l'entité sur laquelle on souhaite travailler
* Exemple : $pagination->setEntityClass(Comment::class);
*/
class Pagination {
/**
* Le nom de l'entité sur laquelle on veut effectuer une pagination
*
* @var string
*/
private $entityClass;
/**
* Le nombre d'enregistrement à récupérer
* Par défault il est à 10
*
* @var integer
*/
private $limit = 10;
/**
* La page sur laquelle on se trouve actuellement
*
* @var integer
*/
private $currentPage = 1;
/**
* Le nom de la route que l'on veut utiliser pour les boutons de la navigation
*
* @var string
*/
private $route;
/**
* Le chemin vers le template qui contient la pagination
*
* @var string
*/
private $templatePath;
/**
* Le manager de Doctrine qui nous permet par exemple de trouver le repository dont on a besoin
*
* @var ObjectManager
*/
private $manager;
/**
* Le moteur de template Twig qui va permettre de générer le rendu de la pagination
*
* @var Environment
*/
private $environment;
/**
* La requete qui va nous permettre de récupérer automatiquement le nom de la route
* sur laquelle nous nous trouvons
*
* @var RequestStack
*/
private $requestStack;
/**
* Pagination constructor.
*
* N'oubliez pas de configurer votre fichier services.yaml afin que Symfony sache quelle valeur
* utiliser pour le $templatePath !
*
* @param ObjectManager $manager
* @param Environment $environment
* @param RequestStack $requestStack
* @param string $templatePath
*/
public function __construct(ObjectManager $manager, Environment $environment, RequestStack $requestStack, string $templatePath)
{
$this->manager = $manager;
$this->environment = $environment;
$this->requestStack = $requestStack;
$this->templatePath = $templatePath;
}
/**
* Récupère les données paginées pour une entité spécifique
*
* Elle se sert de Doctrine afin de récupérer le repository pour l'entité spécifiée
* puis grâce au repository et à sa fonction findBy() on récupère les données dans une
* certaine limite et en partant d'un offset
*
* @throws Exception si la propriété $entityClass n'est pas définie !
*
* @return array
*/
public function getData()
{
if(empty($this->entityClass)) {
throw new Exception("Vous n'avez pas spécifié l'entité sur laquelle nous devons paginer ! Utilisez la méthode setEntityClass() de votre objet Pagination !");
}
// Calcul offset
// 1 * 10 = 10 - 10 = 0 && 2 * 10 = 20 - 10 = 10 etc..
$offset = $this->currentPage * $this->limit - $this->limit;
return $this->manager
->getRepository($this->entityClass)
->findBy([], [], $this->limit, $offset);
}
/**
* Récupère le nombre de pages qui existent sur une entité particulière
*
* Elle se sert de Doctrine pour récupérer le repository qui correspond à l'entité que l'on souhaite
* paginer (voir la propriété $entityClass) puis elle trouve le nombre total d'enregistrements grâce
* à la fonction findAll() du repository
*
* @throws Exception si la propriété $entityClass n'est pas configurée !
*
* @return int
*/
public function getPages(): int
{
if(empty($this->entityClass)) {
throw new Exception("Vous n'avez pas spécifié l'entité sur laquelle nous devons paginer ! Utilisez la méthode setEntityClass() de votre objet Pagination !");
}
$repo = $this->manager->getRepository($this->entityClass);
$total = count($repo->findAll());
$pages = ceil($total / $this->limit); // 2,4 => ceil() = 3
return $pages;
}
/**
* Affiche le rendu de la navigation au sein d'un template twig !
*
* On se sert du moteur de rendu Twig afin de compiler le template qui se trouve au chemin
* de notre propriété $templatePath, en lui passant les variables :
*
* - page => La page actuelle sur laquelle on se trouve
* - pages => le nombre total de pages qui existent
* - route => le nom de la route à utiliser pour les liens de navigation
*
* Attention : cette fonction ne retourne rien, elle affiche directement le rendu
*
*/
public function render()
{
$this->environment->display($this->templatePath, [
'page' => $this->currentPage,
'pages' => $this->getPages(),
// Récupération de la route actuelle grâce à la RequestStack
'route' => $this->route = $this->requestStack->getCurrentRequest()->attributes->get('_route')
]);
}
/**
* @param mixed $entityClass
* @return Pagination
*/
public function setEntityClass($entityClass)
{
$this->entityClass = $entityClass;
return $this;
}
/**
* @return mixed
*/
public function getEntityClass()
{
return $this->entityClass;
}
/**
* @param int $limit
* @return Pagination
*/
public function setLimit(int $limit): Pagination
{
$this->limit = $limit;
return $this;
}
/**
* @return int
*/
public function getLimit(): int
{
return $this->limit;
}
/**
* @param int $currentPage
* @return Pagination
*/
public function setCurrentPage(int $currentPage): Pagination
{
$this->currentPage = $currentPage;
return $this;
}
/**
* @return int
*/
public function getCurrentPage(): int
{
return $this->currentPage;
}
/**
* @param mixed $route
* @return Pagination
*/
public function setRoute($route)
{
$this->route = $route;
return $this;
}
/**
* @return mixed
*/
public function getRoute()
{
return $this->route;
}
/**
* @param mixed $templatePath
* @return Pagination
*/
public function setTemplatePath($templatePath)
{
$this->templatePath = $templatePath;
return $this;
}
/**
* @return mixed
*/
public function getTemplatePath()
{
return $this->templatePath;
}
} | true |
27c4c380cf0397d5321ea35c1775f0221ffc6577 | PHP | JavierLob/Servicio_Medico | /modelo/m_carrera.php | UTF-8 | 2,139 | 2.578125 | 3 | [] | no_license | <?php
require_once('m_mysql.php');
class claseCarrera extends bd_my
{
public $idtcarrera, $carrera, $estatuscarrera;
function __CONSTRUCT()
{
$this->idtcarrera = '';
$this->carrera = '';
$this->estatuscarrera = '';
}
public function set_datos($idtcarrera = '', $carrera = '', $estatuscarrera = '')
{
$this->idtcarrera = $idtcarrera;
$this->carrera = $carrera;
$this->estatuscarrera = $estatuscarrera;
}
public function incluir()
{
$respuesta = false;
$SQL = "INSERT INTO tcarrera (carrera, estatuscarrera) VALUES ('$this->carrera', '1');";
$this->conectar();
$respuesta = $this->ejecutar($SQL);
$this->desconectar();
return $respuesta;
}
public function validar()
{
$repetido = false;
$this->conectar();
$sql="SELECT * FROM tcarrera WHERE carrera='$this->carrera';";
$pcsql=$this->filtro($sql);
if($laRow=$this->proximo($pcsql))
{
$repetido = true;
}
$this->desconectar();
return $repetido;
}
public function modificar()
{
$respuesta = false;
$SQL = "UPDATE tcarrera SET carrera = '$this->carrera' WHERE idtcarrera='$this->idtcarrera';";
$this->conectar();
$respuesta = $this->ejecutar($SQL);
$this->desconectar();
return $respuesta;
}
public function consultar()
{
$Fila = array();
$this->conectar();
$sql="SELECT * FROM tcarrera WHERE idtcarrera='$this->idtcarrera';";
$pcsql=$this->filtro($sql);
if($laRow=$this->proximo($pcsql))
{
$Fila=$laRow;
}
$this->desconectar();
return $Fila;
}
public function listar()
{
$Filas = array();
$cont = 0;
$this->conectar();
$sql="SELECT * FROM tcarrera;";
$pcsql=$this->filtro($sql);
while($laRow=$this->proximo($pcsql))
{
$Filas[$cont] = $laRow;
$cont++;
}
$this->desconectar();
return $Filas;
}
public function cambiar_estatus()
{
$respuesta = false;
$SQL = "UPDATE tcarrera SET estatuscarrera = '$this->estatuscarrera' WHERE idtcarrera='$this->idtcarrera';";
$this->conectar();
$respuesta = $this->ejecutar($SQL);
$this->desconectar();
return $respuesta;
}
}
?> | true |
03f3d831dd8cecd94913184df2ea0e68f53777bb | PHP | adiv-phpian/twitter-reply-bot-codeigniter-framework | /application/models/Dashboard_model.php | UTF-8 | 5,762 | 2.5625 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | <?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* Database actions for free_agent controller
*
* This model represents user authentication data. It operates the following tables:
* - user account data,
* - user token
* - user profile
*
* @package Free_agent_model
* @author muthukrishnan (http://muthu.tk/)
*/
class Dashboard_model extends CI_Model
{
function __construct()
{
parent::__construct();
}
function get_user($user_id){
$this->db->where("user_id", $user_id);
return $this->db->get("users")->row();
}
function get_products($user_id){
$this->db->where("user_id", $user_id);
return $this->db->get("products");
}
function get_product($id){
$this->db->where(array("id" => $user_id,
"user_id" => $this->session->userdata("user_id")));
return $this->db->get("products");
}
function get_products_statistics_graph1($id, $options){
$result = array("names" => array(), "tweet_counts" => array());
$products = $this->get_products($id);
foreach($products->result() as $product){
if(!in_array($product->product_name, $options) && !empty($options)) continue;
$tweet_count = $this->get_tweet_counts($product);
$result['names'][] = "'".$product->product_name."'";
$result['tweet_counts'][] = $tweet_count['count'];
//$result['tweet_oral_match'][] = $tweet_count['oral_match'];
//$result['tweet_perfect_match'][] = $tweet_count['perfect_match'];
}
return $result;
}
function get_products_statistics_graph2($id, $options){
$data = array("tweet_datetime" => array(), "tweet_count" => array());
$products = $this->get_products($id);
$data1 = array();
$points = "";
foreach($products->result() as $product){
if(!in_array($product->product_name, $options) && !empty($options)) continue;
$p_counts = $this->get_tweet_counts_by_time($product);
if(is_array($p_counts['tweet_count'])){
foreach($p_counts['tweet_count'] as $row){
$points .= '[Date.UTC('. date("Y,m,d", strtotime("-1 months", strtotime($row->datetime))).'),'.$row->tweet_count.' ],';
//..print_R($points);
}
}else{
$points .= '[Date.UTC('. date("Y,m,d", strtotime("-1 months")).'), 0],';
}
$data1[$product->product_name]["points"] = '['.$points.']';
$points = "";
}
return $data1;
}
function get_tweet_counts($product){
$result = array();
$this->db->select("count(id) as count");
$this->db->order_by("id", "desc");
$this->db->where("product_id", $product->id)->limit("1");
$statistics = $this->db->get("tweets");
$result['count'] = 0;
if($statistics->num_rows() > 0){
$result['count'] = $statistics->row()->count;
}
return $result;
}
function get_tweet_count($product){
$result = array();
$this->db->select("COUNT(id) as tweet_count");
$this->db->where("product_id", $product->id);
$tweet_count = $this->db->get("tweets");
$result['tweet_count'] = 0;
if($tweet_count->num_rows() > 0){
$result['tweet_count'] = $tweet_count->row()->tweet_count;
}
$result['oral_count'] = 0;
$result['perfect_count'] = 0;
return $result;
}
function get_tweet_counts_by_time($product){
$result = array();
$this->db->select("COUNT(*) as tweet_count, datetime");
$this->db->where("product_id", $product->id);
$this->db->group_by("DATE(datetime)");
$tweet_count = $this->db->get("tweets");
$result['tweet_count'] = 0;
if($tweet_count->num_rows() > 0){
$result['tweet_count'] = $tweet_count->result();
}
return $result;
}
function update_product_statistics_graph1($product){
$product_count = $this->get_tweet_count($product);
$product_count['product_id'] = $product->id;
$product_count['datetime'] = date("Y-m-d H:i:s");
$this->db->where("product_id", $product->id);
$this->db->delete("product_statistics");
$this->db->insert("product_statistics", $product_count);
$p_counts = $this->get_tweet_counts_by_time($product);
$data = array();
$data1 = array();
if(is_array($p_counts['tweet_count'])){
foreach($p_counts['tweet_count'] as $row){
$data["tweet_datetime"][] = strtotime($row->datetime);
$data["tweet_count"][] = $row->tweet_count;
}
}else{
$data["tweet_datetime"][] = strtotime(date("Y-m-d H:i:s"));
$data["tweet_count"][] = "0";
}
$data1["tweet_datetime"] = implode(", ", $data["tweet_datetime"]);
$data1["tweet_count"] = implode(", ", $data["tweet_count"]);
if(is_array($p_counts['oral_count'])){
foreach($p_counts['oral_count'] as $row){
$data["oral_datetime"][] = strtotime($row->datetime);
$data["oral_count"][] = $row->oral_count;
}
}else{
$data["oral_datetime"][] = strtotime(date("Y-m-d H:i:s"));
$data["oral_count"][] = "0";
}
$data1["oral_datetime"] = implode(", ", $data["oral_datetime"]);
$data1["oral_count"] = implode(", ", $data["oral_count"]);
if(is_array($p_counts['perfect_count'])){
foreach($p_counts['perfect_count'] as $row){
$data["perfect_datetime"][] = strtotime($row->datetime);
$data["perfect_count"][] = $row->perfect_count;
}
}else{
$data["perfect_datetime"][] = strtotime(date("Y-m-d H:i:s"));
$data["perfect_count"][] = "0";
}
$data1["perfect_datetime"] = implode(",", $data["perfect_datetime"]);
$data1["perfect_count"] = implode(",", $data["perfect_count"]);
$data1['datetime'] = date("Y-m-d H:i:s");
$data1['product_id'] = $product->id;
$this->db->where("product_id", $product->id);
$this->db->delete("product_timeline_statistics");
//print_r($data1);die;
$this->db->insert("product_timeline_statistics", $data1);
}
}
/* End of file users.php */
/* Location: ./application/models/auth/users.php */
| true |
faa8db0a8ca133a77c48d889e4bdde3eac1a2df9 | PHP | jraulcr/curso-php | /imagenes_servidor/leer_imagen_bbdd.php | UTF-8 | 1,127 | 2.53125 | 3 | [] | no_license | <!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
require ("datosConexionBBDD.php");
$conexion = mysqli_connect($db_host, $db_usuario, $db_contra);
if (mysqli_connect_errno()) {
echo "Fallo al conectar la BB.DD";
exit();
}
mysqli_select_db($conexion, $db_nombre) or die('No se encuentra la BB.DD');
mysqli_set_charset($conexion, "utf8");
$consulta = "SELECT FOTO FROM PRODUCTOS WHERE CODIGOARTICULO='AR01'";
$resultado = mysqli_query($conexion, $consulta);
while ($fila = mysqli_fetch_array($resultado)) {
$ruta_img = $fila["FOTO"];
//echo $ruta_img;
}
?>
<img src="/intranet/uploads/<?php echo $ruta_img?>" alt="Imagen del primer articulo" width="25%">
</body>
</html>
| true |
f62004220b6579250910f8f84cfbe06a9299e249 | PHP | demvsystems/exec | /tests/CommandTest.php | UTF-8 | 2,918 | 2.921875 | 3 | [
"MIT"
] | permissive | <?php
use Demv\Exec\Command;
use Demv\Exec\Exception\OsNoMatchException;
use Demv\Exec\OS;
class CommandTest extends PHPUnit_Framework_TestCase
{
/**
* Test a simple app call
*/
public function testExec()
{
$input = 'Hello World';
$result = Command::create()
->app('echo')
->input($input)
->exec();
$this->assertEquals($input, $result->getRaw());
}
/**
* Test the OS restriction of the command
*/
public function testCorrectOs()
{
$input = 'Hello World';
$os = strtoupper(substr(PHP_OS, 0, 3));
$result = Command::create()
->setOS($os)
->app('echo')
->input($input)
->exec();
$this->assertEquals($input, $result->getRaw());
}
/**
* Test the OS restriction of the command
* @expectedException Demv\Exec\Exception\OsNoMatchException
*/
public function testWrongOs()
{
$input = 'Hello World';
$os = strtoupper(substr(PHP_OS, 0, 3));
$wrong_os = $os === OS::WIN ? OS::LINUX : OS::WIN;
$result = Command::create()
->setOS($wrong_os)
->app('echo')
->input($input)
->exec();
}
/**
* Test piping of 2 applications
*/
public function testPipe()
{
$input = [
'orange',
'banana',
'cherry',
];
$result = Command::create()
->app('echo')
->input('"' . implode(PHP_EOL, $input) . '"')
->app('sort')
->exec();
sort($input);
$this->assertEquals(implode($input, PHP_EOL), $result->getRaw());
}
/**
* Test a PHP application call
*/
public function testPhpApp()
{
$result = Command::create()
->phpApp()
->arg('v')
->exec();
$this->assertEquals('PHP', substr($result->getRaw(), 0, 3));
}
/**
* Test an awk application call
*/
public function testAwkApp()
{
$input = 'foo bar';
$expected = 'bar';
$result = Command::create()
->app('echo')
->input($input)
->awkApp()
->input('print $2;')
->exec();
$this->assertEquals($expected, $result->getRaw());
}
/**
* Test an xargs application call
*/
public function testXargsApp()
{
$expected = 'foo' . PHP_EOL . 'bar' . PHP_EOL . 'baz' . PHP_EOL;
$result = Command::create()
->xargsApp()
->input('echo', 'echo')
->arg('d,')
->arg('L')
->arg('1', '', '')
->app1()
->input('foo,bar,baz')
->exec();
$this->assertEquals($expected, $result->getRaw());
}
}
| true |
33e5fd8eb63cf0f4268da619ede6e7a82ddd12d2 | PHP | paolaht/EcoVida | /ecovida/app/Http/Controllers/MaterialController.php | UTF-8 | 3,546 | 2.8125 | 3 | [
"MIT"
] | permissive | <?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Requests\CreateMaterialRequest;
use Illuminate\Http\Request;
use App\Libraries\Repositories\MaterialRepository;
use Mitul\Controller\AppBaseController;
use App\Libraries\Repositories\MensajeRepository;
use Response;
use Flash;
class MaterialController extends AppBaseController
{
/** @var MaterialRepository */
private $materialRepository;
private $mensajeRepository;
function __construct(MaterialRepository $materialRepo, MensajeRepository $mensajeRepo)
{
$this->materialRepository = $materialRepo;
$this->mensajeRepository = $mensajeRepo;
}
/**
* Display a listing of the Material.
*
* @param Request $request
*
* @return Response
*/
public function index(Request $request)
{
$input = $request->all();
$result = $this->materialRepository->search($input);
$materials = $result[0];
$attributes = $result[1];
$input2 = $request->all();
$result2 = $this->mensajeRepository->search($input2);
$mensajes = $result2[0];
return view('materials.index')
->with('materials', $materials)
->with('attributes', $attributes)->with('mensajes', $mensajes);;;
}
/**
* Show the form for creating a new Material.
*
* @return Response
*/
public function create()
{
return view('materials.create');
}
/**
* Store a newly created Material in storage.
*
* @param CreateMaterialRequest $request
*
* @return Response
*/
public function store(CreateMaterialRequest $request)
{
$input = $request->all();
$material = $this->materialRepository->store($input);
Flash::message('El material se ha agregado corectamente.');
return redirect(route('materials.index'));
}
/**
* Display the specified Material.
*
* @param int $id
*
* @return Response
*/
public function show($id)
{
$material = $this->materialRepository->findMaterialById($id);
if(empty($material))
{
Flash::error('Material not found');
return redirect(route('materials.index'));
}
return view('materials.show')->with('material', $material);
}
/**
* Show the form for editing the specified Material.
*
* @param int $id
* @return Response
*/
public function edit($id)
{
$material = $this->materialRepository->findMaterialById($id);
if(empty($material))
{
Flash::error('Material no encontrado');
return redirect(route('materials.index'));
}
return view('materials.edit')->with('material', $material);
}
/**
* Update the specified Material in storage.
*
* @param int $id
* @param CreateMaterialRequest $request
*
* @return Response
*/
public function update($id, CreateMaterialRequest $request)
{
$material = $this->materialRepository->findMaterialById($id);
if(empty($material))
{
Flash::error('Material no encontrado');
return redirect(route('materials.index'));
}
$material = $this->materialRepository->update($material, $request->all());
Flash::message('Material actualizado de forma correcta.');
return redirect(route('materials.index'));
}
/**
* Remove the specified Material from storage.
*
* @param int $id
*
* @return Response
*/
public function destroy($id)
{
$material = $this->materialRepository->findMaterialById($id);
if(empty($material))
{
Flash::error('Material no encontrado');
return redirect(route('materials.index'));
}
$material->delete();
Flash::message('Material eliminado de forma correcta.');
return redirect(route('materials.index'));
}
}
| true |
46b7344d245c5afcb5a21e780bae851eb72d0885 | PHP | code-distortion/adapt | /src/Support/Exceptions.php | UTF-8 | 2,518 | 3.09375 | 3 | [
"MIT"
] | permissive | <?php
namespace CodeDistortion\Adapt\Support;
use CodeDistortion\Adapt\DI\Injectable\Interfaces\LogInterface;
use CodeDistortion\Adapt\Exceptions\AdaptException;
use CodeDistortion\Adapt\Exceptions\AdaptRemoteBuildException;
use Throwable;
/**
* Support methods relating to exceptions.
*/
class Exceptions
{
/**
* Generate and log the exception message.
*
* @param LogInterface $log The log object to log with.
* @param Throwable $e The exception to log.
* @param boolean $newLineAfter Add a new line afterwards?.
* @return void
*/
public static function logException($log, $e, $newLineAfter = false)
{
if (is_a($e, AdaptRemoteBuildException::class)) {
$title = $e->generateTitleForLog();
$lines = $e->generateLinesForLog();
} else {
$title = 'An Exception Occurred - ' . Exceptions::readableExceptionClass($e);
$message = $e->getMessage() . PHP_EOL
. "{$e->getFile()} on line {$e->getLine()}";
$lines = self::breakDownStringLinesIntoArray($message);
$e2 = $e;
while ($e2 = $e2->getPrevious()) {
/** @var Throwable $e2 */
$message = 'Previous Exception - ' . static::readableExceptionClass($e2) . PHP_EOL
. $e2->getMessage() . PHP_EOL
. "{$e2->getFile()} on line {$e2->getLine()}";
$e2Lines = self::breakDownStringLinesIntoArray($message);
$lines = array_merge($lines, [''], $e2Lines);
}
}
$log->logBox($lines, $title, 'error', $newLineAfter);
}
/**
* Generate a readable name for an exception.
*
* @param Throwable $e The exception that was thrown.
* @return string
*/
public static function readableExceptionClass($e): string
{
$exceptionClass = get_class($e);
if (!is_a($e, AdaptException::class)) {
return $exceptionClass;
}
$temp = explode('\\', $exceptionClass);
return array_pop($temp);
}
/**
* Break down a string of text with new lines into an array.
*
* @param string $string The string to break down.
* @return string[]
*/
private static function breakDownStringLinesIntoArray(string $string): array
{
$temp = str_replace("\r", "\n", str_replace("\r\n", "\n", $string));
return array_filter(explode("\n", $temp));
}
}
| true |
4ca8adc7f6b4700ac0880b1596c4e17e9f344ff7 | PHP | aamarinho/HorariosRest | /model/CalendarioMapper.php | UTF-8 | 5,276 | 2.6875 | 3 | [] | no_license | <?php
require_once(__DIR__ ."/../core/PDOConnection.php");
class CalendarioMapper {
private $db;
public function __construct() {
$this->db = PDOConnection::getInstance();
}
public function registrar(GrupoReducido $grupo) {
$stmt = $this->db->prepare("SELECT asignatura.cuatrimestre FROM asignatura INNER JOIN gruporeducido ON gruporeducido.id_asignatura=asignatura.id WHERE gruporeducido.id=?");
$stmt->execute(array($grupo->getId()));
$resul = $stmt->fetch(PDO::FETCH_ASSOC);
$cuatrimestre=$resul['cuatrimestre'];
$stmt = $this->db->prepare("SELECT f_inicio_uno,f_fin_uno,f_inicio_dos,f_fin_dos from configuracion WHERE id=1");
$stmt->execute();
$resul2 = $stmt->fetch(PDO::FETCH_ASSOC); //aqui tengo los valores de inicio y fin de cuatrimestre, para iterar entre ellos
if($cuatrimestre==1){
$fechainicio=$resul2['f_inicio_uno'];
$fechafin=$resul2['f_fin_uno'];
} else if($cuatrimestre==2){
$fechainicio=$resul2['f_inicio_dos'];
$fechafin=$resul2['f_fin_dos'];
} else{
$fechainicio=$resul2['f_inicio_uno'];
$fechafin=$resul2['f_fin_uno'];
}
$fechafin = strtotime($fechafin);
$fechas=array();
for($i = strtotime($grupo->getDia(),strtotime($fechainicio)); $i <= $fechafin; $i = strtotime('+1 week', $i)) {
array_push($fechas,date('Y-m-d', $i));
}
$stmt = $this->db->prepare("SELECT usuariogrupo.email FROM usuariogrupo INNER JOIN gruporeducido ON gruporeducido.id=usuariogrupo.id INNER JOIN usuario ON usuario.email=usuariogrupo.email WHERE usuario.tipo=2 AND usuariogrupo.id=?");
$stmt->execute(array($grupo->getId()));
$resul = $stmt->fetch(PDO::FETCH_ASSOC);
$responsable=$resul['email'];
foreach($fechas as $fecha){
$stmt = $this->db->prepare("INSERT INTO horario values ('',?,?,?,?,?,?,?,?)");
$stmt->execute(array("clase",$grupo->getId(),$grupo->getIdAsignatura(), $fecha ,$grupo->getHoraInicio(),$grupo->getHoraFin(), $responsable ,$grupo->getAula()));
}
}
public function getCalendario($email) {
$stmt = $this->db->prepare("SELECT nombre,id_grupo,id_asignatura,fecha,hora_inicio,hora_fin,responsable,aula FROM horario INNER JOIN usuariogrupo ON horario.id_grupo=usuariogrupo.id WHERE usuariogrupo.email=?");
$stmt->execute(array($email));
$resul = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $resul;
}
public function getEventos() {
$stmt = $this->db->prepare("SELECT id,nombre,id_grupo,id_asignatura,fecha,hora_inicio,hora_fin,responsable,aula from horario");
$stmt->execute();
$resul = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $resul;
}
public function getGruposSinGenerar(){
$stmt = $this->db->prepare("SELECT gruporeducido.id,gruporeducido.id_asignatura,gruporeducido.tipo,gruporeducido.dia,gruporeducido.hora_inicio,gruporeducido.hora_fin,gruporeducido.aula FROM gruporeducido WHERE gruporeducido.id NOT IN (SELECT DISTINCT horario.id_grupo FROM horario wHERE horario.nombre='clase')");
$stmt->execute();
$resul = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $resul;
}
public function registrarActividadDocente(Calendario $calendario) {
$stmt = $this->db->prepare("SELECT asignatura.id FROM asignatura INNER JOIN gruporeducido ON gruporeducido.id_asignatura=asignatura.id WHERE gruporeducido.id=?");
$stmt->execute(array($calendario->getIdgrupo()));
$asignatura = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt = $this->db->prepare("INSERT INTO horario values ('',?,?,?,?,?,?,?,?)");
$stmt->execute(array($calendario->getNombre(),$calendario->getIdgrupo(),$asignatura['id'], $calendario->getFecha(), $calendario->getHoraInicio(), $calendario->getHoraFin(),$calendario->getResponsable(),$calendario->getAula()));
}
public function getActividadDocenteById($id) {
$stmt = $this->db->prepare("SELECT * FROM horario where id=?");
$stmt->execute(array($id));
$resul = $stmt->fetch(PDO::FETCH_ASSOC);
return $resul;
}
public function eliminar($id) {
$stmt = $this->db->prepare("DELETE from horario WHERE id=?");
if ($stmt->execute(array($id))) {
return 1;
} else return 0;
}
public function editarActividadDocente(Calendario $calendario) {
$stmt = $this->db->prepare("SELECT asignatura.id FROM asignatura INNER JOIN gruporeducido ON gruporeducido.id_asignatura=asignatura.id WHERE gruporeducido.id=?");
$stmt->execute(array($calendario->getIdgrupo()));
$asignatura = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt = $this->db->prepare("UPDATE horario set nombre=?,id_grupo=?,id_asignatura=?,fecha=?,hora_inicio=?,hora_fin=?,responsable=?,aula=? where id=?");
if($stmt->execute(array($calendario->getNombre(), $calendario->getIdgrupo(), $asignatura['id'], $calendario->getFecha(),$calendario->getHoraInicio(),$calendario->getHoraFin(),$calendario->getResponsable(),$calendario->getAula(),$calendario->getId()))){
return true;
} else return false;
}
}
| true |
e894be6d78d98177c34bf8790c893d4ec8f5b225 | PHP | bytic/Collections | /legacy/Traits/DeprecatedTraits.php | UTF-8 | 328 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
namespace Nip\Collections\Legacy\Traits;
/**
* Trait DeprecatedTraits
* @package Nip\Collections\Legacy\Traits
*/
trait DeprecatedTraits
{
/**
* @param $key
* @return bool
* @deprecated Use ->has($key) instead
*/
public function exists($key)
{
return $this->has($key);
}
}
| true |
2901167fa85324966913eb3edfa16630c59b5f44 | PHP | Celeroctos/mis_developing | /protected/models/MisActiveRecord.php | UTF-8 | 11,617 | 2.8125 | 3 | [] | no_license | <?php
class MisActiveRecord extends CActiveRecord {
public function getTableName($alias = null) {
if ($alias != null) {
return $this->tableName().' as '.$alias;
} else {
return $this->tableName();
}
}
/**
* @param string|null $className
* @return static
*/
public static function model($className = null) {
if ($className == null) {
$className = get_called_class();
}
return parent::model($className);
}
/**
* This method is invoked after saving a record successfully.
* The default implementation raises the {@link onAfterSave} event.
* You may override this method to do postprocessing after record saving.
* Make sure you call the parent implementation so that the event is raised properly.
*/
protected function afterSave() {
parent::afterSave();
try {
$this->{$this->tableSchema->primaryKey} = Yii::app()->getDb()->getLastInsertID(
$this->tableName()."_id_seq"
);
} catch (Exception $ignored) {
/* We can't be sure, that we've just inserted new row in db */
}
}
/**
* @param $conn
* @param $filters
* @param $multipleFields - массив, раскрывающий значение "сборных" полей в интерфейсе. Например, поле ФИО, являющееся Именем + Фамилией + Отчеством. Формат:
* array('interfaceField' => array('dbfield1' ... ) ... )
* @param $aliases - массив в виде array('aliasOfTable' => array(field1, ...) ... ) - алиасы таблиц для поиска. Первое измерение - псевдоним таблицы, второе - поля данной таблицы-алиаса
* @param $fieldAliases - массив алиасов полей
* @subGroupOp - субгрупповой оператор в формате 'Оператор' => 'Поле'
*/
protected function getSearchConditions($conn, $filters, $multipleFields, $aliases, $fieldAliases, $subGroupOp = array()) {
foreach($filters['rules'] as $index => $filter) {
if(!isset($filter['data']) || (!is_array($filter['data']) && trim($filter['data']) == '') || (is_array($filter['data']) && count($filter['data']) == 0)) { // При пустых входных данных не нужно делать доп. условие
continue;
}
if(isset($multipleFields[$filter['field']])) {
// Условия по всем полям, которые попадают под составное поле
$opCounter = 0;
foreach($multipleFields[$filter['field']] as $key => $dbField) {
if($opCounter == 0) {
$groupFilter = $filters['groupOp'];
$opCounter++;
$isFound = false;
foreach($subGroupOp as $op => $fieldsInOp) {
foreach($fieldsInOp as $fieldInOp) {
// Если есть совпадение по оператору
if($fieldInOp == $dbField) {
$groupFilter = $op;
$isFound = true;
break;
}
}
if($isFound) {
break;
}
}
} else {
$groupFilter = 'OR';
}
if(isset($fieldAliases[$dbField])) {
$dbFieldReal = $fieldAliases[$dbField];
} else {
$dbFieldReal = $dbField;
}
$filterByField = array(
'field' => $dbFieldReal,
'field_alias' => $dbField,
'op' => $filter['op'],
'data' => $filter['data']
);
$this->getSearchOperator($conn, $groupFilter, $filterByField, $this->searchAlias($dbField, $aliases));
}
} else {
if(isset($fieldAliases[$filter['field']])) {
$dbFieldReal = $fieldAliases[$filter['field']];
} else {
$dbFieldReal = $filter['field'];
}
$isFound = false;
foreach($subGroupOp as $op => $fieldsInOp) {
foreach($fieldsInOp as $fieldInOp) {
// Если есть совпадение по оператору
if($fieldInOp == $filter['field']) {
$subGroupFilter = $op;
$isFound = true;
break;
}
}
if($isFound) {
break;
}
}
if(!$isFound) {
$subGroupFilter = $filters['groupOp'];
}
$filterByField = array(
'field' => $dbFieldReal,
'field_alias' => $filter['field'],
'op' => $filter['op'],
'data' => $filter['data']
);
$this->getSearchOperator($conn, $subGroupFilter, $filterByField, $this->searchAlias($filter['field'], $aliases));
}
}
}
public function getAll() {
return $this->getDbConnection()->createCommand()
->select("*")
->from($this->tableName())
->queryAll();
}
// Поиск алиаса для поля
protected function searchAlias($field, $aliasesArr) {
foreach($aliasesArr as $alias => $fields) {
foreach($fields as $key => $fieldName) {
if($field == $fieldName) {
return $alias;
}
}
}
exit('Алиас таблицы для поля '.$field.' в списке таблиц не найден!');
}
protected function useFunctionToField($field, $function, $arguments) {
switch($function) {
case 'replace' :
$field = 'REPLACE('.$field.', "'.$arguments[0].'", "'.$arguments[1].'")';
break;
}
return $field;
}
protected function useFunctionToValue($value, $function, $arguments) {
switch($function) {
case 'replace' :
$value = str_replace($arguments[0], $arguments[1], $value);
break;
}
return $value;
}
/**
* @param $conn
* @param $chainOp - оператор, который будет связывать sql-условия: AND или OR
* @param $filter
*/
protected function getSearchOperator($conn, $chainOp, $filter, $alias) {
//$filter['data'] = mb_strtolower($filter['data'], 'UTF-8'); // Прикольно. Он не может без необязательного параметра различить кодировку.
// $filter['data'] = trim($filter['data']);
switch($filter['op']) {
case 'eq' :
$chainOp == 'AND' ? $conn->andWhere($alias.'.'.$filter['field'].' = :'.$filter['field_alias'], array(':'.$filter['field_alias'] => $filter['data'])) : $conn->orWhere($alias.'.'.$filter['field'].' = :'.$filter['field_alias'], array(':'.$filter['field_alias'] => $filter['data']));
break;
case 'ne' :
$chainOp == 'AND' ? $conn->andWhere($alias.'.'.$filter['field'].' != :'.$filter['field_alias'], array(':'.$filter['field_alias'] => $filter['data'])) : $conn->orWhere($alias.'.'.$filter['field'].' != :'.$filter['field_alias'], array(':'.$filter['field_alias'] => $filter['data']));
break;
case 'lt' :
$chainOp == 'AND' ? $conn->andWhere($alias.'.'.$filter['field'].' < :'.$filter['field_alias'], array(':'.$filter['field_alias'] => $filter['data'])) : $conn->orWhere($alias.'.'.$filter['field'].' < :'.$filter['field_alias'], array(':'.$filter['field_alias'] => $filter['data']));
break;
case 'le' :
$chainOp == 'AND' ? $conn->andWhere($alias.'.'.$filter['field'].' <= :'.$filter['field_alias'], array(':'.$filter['field_alias'] => $filter['data'])) : $conn->orWhere($alias.'.'.$filter['field'].' <= :'.$filter['field_alias'], array(':'.$filter['field_alias'] => $filter['data']));
break;
case 'gt' :
$chainOp == 'AND' ? $conn->andWhere($alias.'.'.$filter['field'].' > :'.$filter['field_alias'], array(':'.$filter['field_alias'] => $filter['data'])) : $conn->orWhere($alias.'.'.$filter['field'].' > :'.$filter['field_alias'], array(':'.$filter['field_alias'] => $filter['data']));
break;
case 'ge' :
$chainOp == 'AND' ? $conn->andWhere($alias.'.'.$filter['field'].' >= :'.$filter['field_alias'], array(':'.$filter['field_alias'] => $filter['data'])) : $conn->orWhere($alias.'.'.$filter['field'].' >= :'.$filter['field_alias'], array(':'.$filter['field_alias'] => $filter['data']));
break;
case 'in' :
$chainOp == 'AND' ? $conn->andWhere(array('in', $alias.'.'.$filter['field'], $filter['data'])) : $conn->orWhere(array('in', $alias.'.'.$filter['field'], $filter['data']));
break;
case 'ni' :
$chainOp == 'AND' ? $conn->andWhere(array('not in', $alias.'.'.$filter['field'], $filter['data'])) : $conn->orWhere(array('not in', $alias.'.'.$filter['field'], $filter['data']));
break;
case 'bw' :
$chainOp == 'AND' ? $conn->andWhere(array('like', 'LOWER('.$alias.'.'.$filter['field'].')', $filter['data'].'%')) : $conn->orWhere(array('like', 'LOWER('.$alias.'.'.$filter['field'].')', $filter['data'].'%'));
break;
case 'bn' :
$chainOp == 'AND' ? $conn->andWhere(array('not like', 'LOWER('.$alias.'.'.$filter['field'].')', $filter['data'].'%')) : $conn->orWhere(array('not like', 'LOWER('.$alias.'.'.$filter['field'].')', $filter['data'].'%'));
break;
case 'ew' :
$chainOp == 'AND' ? $conn->andWhere(array('like', 'LOWER('.$alias.'.'.$filter['field'].')', '%'.$filter['data'])) : $conn->orWhere(array('like', 'LOWER('.$alias.'.'.$filter['field'].')', '%'.$filter['data']));
break;
case 'en' :
$chainOp == 'AND' ? $conn->andWhere(array('not like', 'LOWER('.$alias.'.'.$filter['field'].')', '%'.$filter['data'])) : $conn->orWhere(array('like', 'LOWER('.$alias.'.'.$filter['field'].')', '%'.$filter['data']));
break;
case 'cn' :
$chainOp == 'AND' ? $conn->andWhere(array('like', 'LOWER('.$alias.'.'.$filter['field'].')', '%'.$filter['data'].'%')) : $conn->orWhere(array('like', 'LOWER('.$alias.'.'.$filter['field'].')', '%'.$filter['data'].'%'));
break;
case 'nc' :
$chainOp == 'AND' ? $conn->andWhere(array('not like', 'LOWER('.$alias.'.'.$filter['field'].')', '%'.$filter['data'].'%')) : $conn->orWhere(array('like', 'LOWER('.$alias.'.'.$filter['field'].')', '%'.$filter['data'].'%'));
break;
default:
exit('Неверный оператор поиска.');
}
}
}
?> | true |
a589e414ccac4600e53867ef7db6d27883a724b1 | PHP | spotlighthometours/spotlighthometours.com | /checkout/checkout_getccdetails.php | UTF-8 | 2,297 | 2.609375 | 3 | [] | no_license | <?php
/**********************************************************************************************
Document: checkout_getccdetails.php
Creator: Brandon Freeman
Date: 02-28-11
Purpose: Returns cc information. (for Ajax request)
**********************************************************************************************/
//=======================================================================
// Error Reporting & Output Buffering
//=======================================================================
ini_set ('display_errors', 1);
error_reporting (E_ALL & ~E_NOTICE);
ob_start();
// Start the session
session_start();
//=======================================================================
// Includes
//=======================================================================
// Connect to MySQL
require_once ('../repository_inc/connect.php');
require_once ('../repository_inc/clean_query.php');
//=======================================================================
// Document
//=======================================================================
if (isset($_POST['cardid'])) {
$cardid = CleanQuery($_POST['cardid']);
} elseif (isset($_GET['cardid'])) {
$cardid = CleanQuery($_GET['cardid']);
}
$userid = -1;
if (isset($_POST['userid'])) {
$userid = CleanQuery($_POST['userid']);
} elseif (isset($_GET['userid'])) {
$userid = CleanQuery($_GET['userid']);
} elseif (isset($_SESSION['user_id'])) {
$userid = $_SESSION['user_id'];
}
header("Content-type: text/xml");
echo '<?xml version="1.0" encoding="UTF-8" ?> ' . chr(10);
$query = "SELECT crardId, cardName, cardAddress, cardCity, cardState, cardZip, cardType, cardNumber, cardMonth, cardYear FROM usercreditcards WHERE crardId = " . $cardid . " AND userid = " . $userid . " LIMIT 1";
$r = mysql_query($query) or die("Query failed with error: " . mysql_error());
$result = mysql_fetch_array($r);
echo '<ccard id="' . $result['crardId'] . '" name="' . $result['cardName'] . '" address="' . $result['cardAddress'] . '" city="' . $result['cardCity'] . '" state="' . $result['cardState'] . '" zip="' . $result['cardZip'] . '" type="' . $result['cardType'] . '" number="' . $result['cardNumber'] . '" month="' . $result['cardMonth'] . '" year="' . $result['cardYear'] . '" />' . Chr(10);
?> | true |
de3a19dd8b2a65d273acae7f69a835b0a91c788d | PHP | fracz/refactor-extractor | /results/Elgg--Elgg/958dc6efa414f17a97c198bd3aaa923d6c820533/before/ConfigTable.php | UTF-8 | 5,154 | 3.1875 | 3 | [] | no_license | <?php
namespace Elgg\Database;
/**
* These settings are stored in the dbprefix_config table and read
* during system boot into $CONFIG.
*
* WARNING: API IN FLUX. DO NOT USE DIRECTLY.
*
* @access private
*
* @package Elgg.Core
* @subpackage Database
* @since 1.10.0
*/
class ConfigTable {
/**
* Global Elgg configuration
*
* @var \stdClass
*/
private $CONFIG;
/**
* Constructor
*/
public function __construct() {
global $CONFIG;
$this->CONFIG = $CONFIG;
}
/**
* Removes a config setting.
*
* @param string $name The name of the field.
* @param int $site_guid Optionally, the GUID of the site (default: current site).
*
* @return bool Success or failure
*/
function remove($name, $site_guid = 0) {
$name = trim($name);
$site_guid = (int) $site_guid;
if ($site_guid == 0) {
$site_guid = (int) $this->CONFIG->site_guid;
}
if ($site_guid == $this->CONFIG->site_guid && isset($this->CONFIG->$name)) {
unset($this->CONFIG->$name);
}
$escaped_name = sanitize_string($name);
$query = "DELETE FROM {$this->CONFIG->dbprefix}config WHERE name = '$escaped_name' AND site_guid = $site_guid";
return _elgg_services()->db->deleteData($query) !== false;
}
/**
* Add or update a config setting.
*
* Plugin authors should use elgg_set_config().
*
* If the config name already exists, it will be updated to the new value.
*
* @warning Names should be selected so as not to collide with the names for the
* datalist (application configuration)
*
* @note Internal: These settings are stored in the dbprefix_config table and read
* during system boot into $CONFIG.
*
* @note Internal: The value is serialized so we maintain type information.
*
* @param string $name The name of the configuration value
* @param mixed $value Its value
* @param int $site_guid Optionally, the GUID of the site (current site is assumed by default)
*
* @return bool
*/
function set($name, $value, $site_guid = 0) {
$name = trim($name);
// cannot store anything longer than 255 characters in db, so catch before we set
if (elgg_strlen($name) > 255) {
_elgg_services()->logger->error("The name length for configuration variables cannot be greater than 255");
return false;
}
$site_guid = (int) $site_guid;
if ($site_guid == 0) {
$site_guid = (int) $this->CONFIG->site_guid;
}
if ($site_guid == $this->CONFIG->site_guid) {
$this->CONFIG->$name = $value;
}
$escaped_name = sanitize_string($name);
$escaped_value = sanitize_string(serialize($value));
$result = _elgg_services()->db->insertData("INSERT INTO {$this->CONFIG->dbprefix}config
SET name = '$escaped_name', value = '$escaped_value', site_guid = $site_guid
ON DUPLICATE KEY UPDATE value = '$escaped_value'");
return $result !== false;
}
/**
* Gets a configuration value
*
* Plugin authors should use elgg_get_config().
*
* @note Internal: These settings are stored in the dbprefix_config table and read
* during system boot into $CONFIG.
*
* @param string $name The name of the config value
* @param int $site_guid Optionally, the GUID of the site (default: current site)
*
* @return mixed|null
*/
function get($name, $site_guid = 0) {
$name = trim($name);
$site_guid = (int) $site_guid;
// check for deprecated values.
// @todo might be a better spot to define this?
$new_name = false;
switch($name) {
case 'pluginspath':
$new_name = 'plugins_path';
break;
case 'sitename':
$new_name = 'site_name';
break;
}
// @todo these haven't really been implemented in Elgg 1.8. Complete in 1.9.
// show dep message
if ($new_name) {
// $msg = "Config value $name has been renamed as $new_name";
$name = $new_name;
// elgg_deprecated_notice($msg, $dep_version);
}
if ($site_guid == 0) {
$site_guid = (int) $this->CONFIG->site_guid;
}
// decide from where to return the value
if ($site_guid == $this->CONFIG->site_guid && isset($this->CONFIG->$name)) {
return $this->CONFIG->$name;
}
$escaped_name = sanitize_string($name);
$result = _elgg_services()->db->getDataRow("SELECT value FROM {$this->CONFIG->dbprefix}config
WHERE name = '$escaped_name' AND site_guid = $site_guid");
if ($result) {
$result = unserialize($result->value);
if ($site_guid == $this->CONFIG->site_guid) {
$this->CONFIG->$name = $result;
}
return $result;
}
return null;
}
/**
* Loads all configuration values from the dbprefix_config table into $CONFIG.
*
* @param int $site_guid Optionally, the GUID of the site (current site is assumed by default)
*
* @return bool
*/
function loadAll($site_guid = 0) {
$site_guid = (int) $site_guid;
if ($site_guid == 0) {
$site_guid = (int) $this->CONFIG->site_guid;
}
if ($result = _elgg_services()->db->getData("SELECT * FROM {$this->CONFIG->dbprefix}config WHERE site_guid = $site_guid")) {
foreach ($result as $r) {
$name = $r->name;
$value = $r->value;
$this->CONFIG->$name = unserialize($value);
}
return true;
}
return false;
}
} | true |
81a925f7abc6a58ea12c6ad39055a09dc656d8b4 | PHP | aldemeery/enum-polyfill | /SplEnum.php | UTF-8 | 1,921 | 3.328125 | 3 | [
"MIT"
] | permissive | <?php
if (!class_exists('SplEnum')) {
/**
* A polyfill for the 'splEnum' class.
*
* @see http://php.net/manual/en/class.splenum.php
* @author Osama Aldemeery <aldemeery@gmail.com>
*/
abstract class SplEnum
{
/**
* @constant(__default) The default value of the enum.
*/
protected const __default = null;
/**
* The current value of the enum.
*
* @var mixed
*/
protected $value;
/**
* splEnum constructor.
*
* @param mixed $value The initial value of the enum.
* @throws UnexpectedValueException
*/
public function __construct($value = null)
{
$ref = new \ReflectionClass($this);
if (!in_array($value, $ref->getConstants())) {
throw new \UnexpectedValueException("Value '$value' is not part of the enum " . get_called_class());
}
$this->value = $value;
}
/**
* Get a list of all the constants in the enum
*
* @param boolean $include_default Whether to include the default value in the list or no.
*
* @return array The list of constants defined in the enum.
*/
public static function getConstList($include_default = false)
{
$reflected = new \ReflectionClass(new static(null));
$constants = $reflected->getConstants();
if (!$include_default) {
unset($constants['__default']);
return $constants;
}
return $constants;
}
/**
* The string representation of the enum.
*
* @return string The current value of the enum.
*/
final public function __toString()
{
return strval($this->value);
}
}
}
| true |
2e7bf8e085f95815cf450baa51f0683c1277290b | PHP | joao4597/f1tribo.ddns.net | /public_html/database/drivers.php | UTF-8 | 352 | 2.796875 | 3 | [] | no_license | <?php
function getAllDrivers() {
global $conn;
$stmt = $conn->prepare('SELECT * FROM drivers');
$stmt->execute();
return $stmt->fetchAll();
}
function getAllDriversByPoints() {
global $conn;
$stmt = $conn->prepare('SELECT * FROM drivers ORDER BY points DESC');
$stmt->execute();
return $stmt->fetchAll();
}
?> | true |
614e1b3308a0356fef317c38720b7b73b71989e8 | PHP | carstenwindler/frameworkless | /src/Repository/ProductRepository.php | UTF-8 | 1,388 | 2.875 | 3 | [] | no_license | <?php
declare(strict_types=1);
namespace MyMicroService\Repository;
use Doctrine\DBAL\Connection;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
class ProductRepository implements LoggerAwareInterface
{
use LoggerAwareTrait;
public function __construct(
private Connection $connection
) {
}
public function getAll(): array
{
return $this->connection->fetchAllAssociative(
'SELECT id, description FROM products'
);
}
public function get(int $id): array
{
return $this->connection->fetchAllAssociative(
'SELECT id, description FROM products WHERE id = ?',
[$id]
);
}
public function delete(int $id): int
{
return $this->connection->executeStatement(
'DELETE FROM products WHERE id = ?',
[$id]
);
}
public function add(string $description): int
{
$this->connection->executeStatement(
'INSERT INTO products (description) VALUES (?)',
[$description]
);
return (int) $this->connection->lastInsertId();
}
public function update(int $id, string $description): int
{
return $this->connection->executeStatement(
'UPDATE products SET description = ? WHERE id= ?',
[$description, $id]
);
}
}
| true |
d9ccaf0102889f59d78d7344b271bf9383ff9f36 | PHP | BNLMaor/crm | /includes/core.php | UTF-8 | 1,995 | 2.703125 | 3 | [] | no_license | <?php
session_start();
ob_start();
class Core
{
private $loadedClasses = [];
public $Route;
public $DB;
public $Custom;
public $User;
private static $instance = false;
public function __construct()
{
$initClasses = ["Database", "Route", "Custom", "User","Accessmanager","Language","Admin","Imap"];
foreach ($initClasses as $class)
{
$func = "init" . ucfirst($class);
$this->$func($class);
}
}
static public function initAll()
{
if (self::$instance === false)
self::$instance = new self();
return self::$instance;
}
private function initRoute($name)
{
include_once "classes/class.Route.php";
$this->Route = $name::load($this);
$this->loadedClasses[] = "route";
}
private function initDatabase($name)
{
include_once "classes/class.Database.php";
$this->DB = $name::load($this);
$this->loadedClasses[] = "database";
}
private function initCustom($name)
{
include_once "classes/class.Custom.php";
$this->Custom = $name::load($this);
$this->loadedClasses[] = "custom";
}
private function initUser($name)
{
include_once "classes/class.User.php";
$this->User = $name::load($this);
$this->loadedClasses[] = "user";
}
private function initAccessmanager($name)
{
include_once "classes/class.Accessmanager.php";
$this->AccessManager = $name::load($this);
$this->loadedClasses[] = "accessmanager";
}
private function initLanguage($name)
{
include_once "classes/class.Language.php";
$this->Lang = $name::load($this);
$this->loadedClasses[] = "language";
}
private function initAdmin($name)
{
include_once "classes/class.Admin.php";
$this->Admin = $name::load($this);
$this->loadedClasses[] = "admin";
}
private function initImap($name)
{
include_once "classes/class.Imap.php";
$this->Imap = $name::load($this);
$this->loadedClasses[] = "imap";
}
}
// Defines Template
define("TEMPLATE", ROOT."/sources/views/");
?> | true |
8c3c3b143c6c80baa34da5bd233a93b4083ee818 | PHP | ValtrX/apidavid | /index.php | UTF-8 | 4,226 | 2.84375 | 3 | [] | no_license | <?php
if (!empty($_GET['location'])) {
$country_url = 'https://api.datoscovid.org/timeline/' . urlencode($_GET['location']);
$country_json = file_get_contents($country_url);
$country_array = json_decode($country_json, true);
/* Convertimos Fechas a un array desde el array de cada pais */
$fechas = array_column($country_array, 'Date');
$confirmados = array_column($country_array, 'Confirmed');
$muertos = array_column($country_array, 'Deaths');
$recuperados = array_column($country_array, 'Recovered');
}
$countries_url = 'https://api.datoscovid.org/country';
$countries_json = file_get_contents($countries_url);
$countries_array = json_decode($countries_json, true);
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>David app</title>
<link rel="icon" type="image/png" href="img/David animado.png">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.4/dist/Chart.min.js"></script>
</head>
<body>
<!-- Seccion de busqueda -->
<section id="busqueda" class="text-center m-5">
<form action="">
<label for="country" class="label"><h2>Selecciona un pais: </h2></label>
<select name="location" id="location" style="font-size: 2vh;">
<?php
/* Array para seleccionar cada pais se envia en $_GET[] a la url*/
sort($countries_array);
foreach ($countries_array as $country_input) {
echo "<option value='" . $country_input['Country'] . "'>" . $country_input['Country'] . "</option>";
}?>
</select>
<br><br>
<button type="submit" value="Submit" class="btn btn-success btn-lg rounded-0">Buscar</button>
</form>
</section>
<?php
/* Mostrando los datos de cada pais dependiendo del pais que escojas */
if (!empty($country_array)) { // Si hay un pais seleccionado haz esto:
?>
<div style="width: 600px; height: 600px;" class="m-auto">
<canvas id="myChart" width="400" height="400"></canvas>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: <?php echo json_encode($fechas); ?> ,
datasets : [{
label: 'Casos Confirmados',
data: <?php echo json_encode($confirmados); ?> ,
fill : false,
backgroundColor: '#2258e0',
borderColor: '#2258e0',
pointRadius: 0,
}, {
label: 'Muertos',
data: <?php echo json_encode($muertos); ?> ,
fill : false,
backgroundColor: '#ff0000',
borderColor: '#ff0000',
pointRadius: 0,
}, {
label: 'Recuperados',
data: <?php echo json_encode($recuperados); ?> ,
fill : false,
backgroundColor: '#82e65e',
borderColor: '#82e65e',
pointRadius: 0,
}],
},
options: {
hover: {
mode: 'nearest',
intersect: true
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>
</div>
<?php } else {
echo "<h3 class='text-center'>Busca un pais :)</h3>";
}?>
<script type="text/javascript">
document.getElementById('location').value = "<?php echo $_GET['location']; ?>";
</script>
</body>
</html> | true |
594712b13cb5ed40331699b7d93b452b7a58ba39 | PHP | 5m477/vishleshakee | /app/Http/Controllers/queryStatusController.php | UTF-8 | 2,701 | 2.640625 | 3 | [] | no_license | <?php
namespace App\Http\Controllers;
use App\QueryStatus;
use Illuminate\Http\Request;
class queryStatusController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'queryID' => 'required',
'userID' => 'required',
'query' => 'required',
'fromDate' => 'required',
'toDate' => 'required',
'status' => 'required',
]);
$statusObj = new QueryStatus([
'queryID' => $request->get('queryID'),
'userID' => $request->get('userID'),
'query' => $request->get('query'),
'fromDate' => $request->get('fromDate'),
'toDate' => $request->get('toDate'),
'status'=>$request->get('status')
]);
$statusObj->save();
return response()->json(['data' => 'Submitted Successfully!'], 200);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$statusObj = QueryStatus::where('userID', $id)->get();
return $statusObj;
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$request->validate([
'status' => 'required']);
$statusCaptured = $request->input('status');
$statusObj = QueryStatus::where('queryID', $id)->update(array(
'status' => $statusCaptured));
return response()->json(['data' => 'Status Successfully Updated!'], 200);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$statusObj = QueryStatus::where('queryID', $id)->delete();
return $statusObj;
}
}
| true |
311238d673e4f57e9f2397ae6b1528f012b2cdc9 | PHP | aumartinez/php-team-metrics | /app/controllers/logout.php | UTF-8 | 1,442 | 2.703125 | 3 | [
"MIT"
] | permissive | <?php
class Logout extends Controller {
protected $output;
public function __construct($controller, $method) {
parent::__construct($controller, $method);
session_start();
# Any models required to interact with this controller should be loaded here
$this->load_model("DbModel");
$this->load_model("PageModel");
$this->load_model("StartupModel");
# Instantiate custom view output
$this->output = new PageView();
}
# Each method will request the model to present the local resource
public function index() {
# Clear session
session_unset();
session_destroy();
session_write_close();
setcookie(session_name(), "", 0, "/");
header("Location:/". PATH ."/login");
}
# Not found handler
public function not_found() {
# 404 page
$this->build_page("not-found");
# Clear session
session_unset();
session_destroy();
session_write_close();
setcookie(session_name(), "", 0, "/");
}
# Controller/Model/View link
protected function build_page($page_name) {
$html_src = $this->get_model("PageModel")->get_page($page_name);
$html = $this->output->replace_localizations($html_src);
$this->get_view()->render($html);
}
# Redirect
protected function redirect($page) {
header ("Location: /" . PATH . "/" . $page);
exit();
}
}
?>
| true |
11cf01b0b3c3d9eb5f3479533e709f22b20f7b02 | PHP | tylerbenjaminfryatt/Subscriber_Login_Notification_App | /includes/Sender.php | UTF-8 | 1,390 | 2.609375 | 3 | [] | no_license | <?php
require_once('PantryDatabase.php');
require_once('Mail.php');
/**
* The class for the notification sender
*/
class Sender {
// TODO: Change this to config.
const HOST = 'ssl://smtp.gmail.com';
const PORT = '465';
const USERNAME = 'CIS234A@gmail.com';
const PASSWORD = 'CIS234A_mail';
const FROM = 'PCC Pantry <pantry@pcc.edu>';
public static function sendNotification($message) {
$db = new PantryDatabase();
$subscribers = $db->getSubscribers();
$subject = 'PCC Pantry: Restock Update';
foreach ($subscribers as $subscriber) {
$headers = ['To' => $subscriber['email'],
'From' => Sender::FROM,
'Subject' => $subject,
'MIME-VERSION' => 1.0,
'Content-Type' => 'text/html; charset=utf-8'];
$transport = ['host' => Sender::HOST,
'port' => Sender::PORT,
'username' => Sender::USERNAME,
'password' => Sender::PASSWORD,
'auth' => TRUE];
$smtp = Mail::factory('smtp', $transport);
$smtp->send($headers['To'], $headers, $message);
}
date_default_timezone_set('America/Los_Angeles');
$db->addLog($_SESSION['user_id'], $message, date('Y/m/d G:i'), (string) count($subscribers));
header('Location: ../../send_notification.php');
}
}
| true |
4399d2159429e310a150aac66c01489e285fc757 | PHP | luisgcastillo40so/Weather | /Helper/Configuration.php | UTF-8 | 1,338 | 2.515625 | 3 | [] | no_license | <?php
namespace HTCode\Weather\Helper;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;
use Magento\Framework\Encryption\EncryptorInterface;
use Magento\Store\Model\ScopeInterface;
use Magento\Store\Model\StoreManagerInterface;
class Configuration extends AbstractHelper
{
public const API_KEY_PATH = 'weatherSection/weatherData/weatherApiKey';
public const TOWN_PATH = 'weatherSection/weatherData/town';
/**
* @var EncryptorInterface
*/
protected $encryptor;
/**
* @var StoreManagerInterface
*/
protected $storeManager;
public function __construct(Context $context, EncryptorInterface $encryptor, StoreManagerInterface $storeManager)
{
parent::__construct($context);
$this->encryptor = $encryptor;
$this->storeManager = $storeManager;
}
public function getApiKey()
{
return $this->encryptor->decrypt(
$this->scopeConfig->getValue(
self::API_KEY_PATH,
ScopeInterface::SCOPE_STORE,
$this->storeManager->getStore())
);
}
public function getTown()
{
return $this->scopeConfig->getValue(
self::TOWN_PATH,
ScopeInterface::SCOPE_STORE,
$this->storeManager->getStore()
);
}
}
| true |
aaf6e73a7c9d6f0a0239d8662872e32f3494a6e5 | PHP | activecollab/utils | /src/ValueContainer/ValueContainer.php | UTF-8 | 791 | 2.640625 | 3 | [
"MIT"
] | permissive | <?php
/*
* This file is part of the Active Collab Utils project.
*
* (c) A51 doo <info@activecollab.com>. All rights reserved.
*/
declare(strict_types=1);
namespace ActiveCollab\ValueContainer;
class ValueContainer implements ValueContainerInterface, WriteableValueContainerInterface
{
private bool $value_is_set = false;
private $value;
public function hasValue(): bool
{
return $this->value_is_set;
}
public function getValue()
{
return $this->value;
}
public function setValue($value): ValueContainerInterface
{
$this->value = $value;
return $this;
}
public function removeValue(): ValueContainerInterface
{
$this->value = null;
$this->value_is_set = false;
return $this;
}
}
| true |
7a043182bba1836d038e47f2766f2daecf458fb5 | PHP | M7moudAlrays/Diner-Club | /app/Http/Controllers/backend/OrderController.php | UTF-8 | 3,398 | 2.53125 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers\backend;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Order;
use App\Models\User;
use App\Notifications\AddReservation;
use Illuminate\Support\Facades\Auth;
class OrderController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$data['orders']=Order::get();
// dd($data);
return view('backend.orders.index')->with($data);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$data['categories']=Order::all();
// $user = User::first();
// Notification::send($user,new AddOrder);
return view('backend.orders.create')->with($data);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\giyRequest $request
*
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
if ($request->hasFile('image'))
{
$image = $request->file('image');
$imageName = time().'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/images');
$image->move($destinationPath,$imageName);
}
Order::create([
'name'=>$request->name,
'ingrediens'=>$request->ingrediens,
'description'=>$request->description,
'image'=>$request->image,
'category_id'=>$request->category_id
]);
//notification
// $user=Auth::get();
// $order=Order::latest()->first();
// $user->notify(new \App\Notifications\AddOrder($order));
session()->flash('success','Reciepe is inserted sucessfully');
return redirect()->route('reciepes.index');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show(Order $order)
{
$data['order']=$order;
return view('backend.orders.show')->with($data);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit( $id)
{ $order=Order::findOrFail($id);
$data['order']=$order;
return view('backend.orders.edit')->with($data);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Order $order)
{
$order->update([
'status'=>$request->status,
]);
session()->flash('success','order is updated sucessfully');
return redirect()->route('orders.index'); }
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$contact=Order::findOrFail($id);
$contact->delete();
session()->flash('success','order deleted successfully');
return redirect()->route('orders.index');
}
}
| true |
cf563294b96e81e9e4b9bee8b815001f36110905 | PHP | Yeun22/netflix | /cours/index.php | UTF-8 | 719 | 2.828125 | 3 | [] | no_license |
<?php
if(!empty($_POST['pseudo'])){
$pseudo = $_POST['pseudo'];
setcookie("pseudo", $pseudo, time()+365*24*2600);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PHP</title>
</head>
<body>
<h1> Entrer votre pseudo </h1>
<form method="post" action='index.php'>
<table>
<tr>
<td>Pseudo : </td>
<td><input type="text" name="pseudo"/></td>
</tr>
</table>
<button type="submit">Se connecter</button>
</form>
<?php
?>
</body>
</html> | true |
917627f867c9fd29ffe422695d8f88d0e6b8f92f | PHP | christianklisch/newsletter2go-api-php | /src/christianklisch/newsletter2goapi/entity/Status.php | UTF-8 | 1,335 | 2.953125 | 3 | [
"MIT"
] | permissive | <?php
namespace Newsletter2Go;
class Status
{
private $success;
private $value;
private $status;
private $reason;
public function __construct($vars = null)
{
if ($vars) {
if (array_key_exists('success', $vars))
$this->success = $vars['success'];
if (array_key_exists('value', $vars))
$this->value = $vars['value'];
if (array_key_exists('status', $vars))
$this->status = $vars['status'];
if (array_key_exists('reason', $vars))
$this->reason = $vars['reason'];
}
}
public function getSuccess()
{
return $this->success;
}
public function setSuccess($success)
{
$this->success = $success;
}
public function getValue()
{
return $this->value;
}
public function setValue($value)
{
$this->value = $value;
}
public function getStatus()
{
return $this->status;
}
public function setStatus($status)
{
$this->status = $status;
}
public function getReason()
{
return $this->reason;
}
public function setReason($reason)
{
$this->reason = $reason;
}
}
| true |
0aa6e5e29cc764879ea7ad34f2c9483aabb1189f | PHP | ITAAcademy/RobotaMolodi | /app/Http/Composers/Show/Company.php | UTF-8 | 539 | 2.53125 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Composers\Show;
use App\Http\Composers\Show\SeoInfo\CreatorContract;
use Illuminate\Contracts\View\View;
class Company
{
private $creator;
public function __construct(CreatorContract $creator)
{
$this->creator = $creator;
}
public function compose(View $view){
if($view->offsetExists('company')){
$company = $view->offsetGet('company');
}
$data = $this->creator->createSeoInfo($company);
$view->with('seo_meta_source' , $data);
}
} | true |
1f3088a42e6bdfffda4c37ec68f048fdb2cf9b70 | PHP | ragulara93/atexo | /tests/CardSortingTest.php | UTF-8 | 1,784 | 2.765625 | 3 | [] | no_license | <?php
declare(strict_types=1);
namespace App\Tests;
use App\Services\Game\CardSorting;
use PHPUnit\Framework\TestCase;
class CardSortingTest extends TestCase
{
public function testSortingCards(): void
{
$cardSorting = new CardSorting();
$initialSetCard = [
[
"value" => "jack",
"symbol" => "diamond"
],
[
"value" => 8,
"symbol" => "spade"
],
[
"value" => "queen",
"symbol" => "heart"
],
[
"value" => 9,
"symbol" => "club"
],
[
"value" => 10,
"symbol" => "diamond"
],
[
"value" => 4,
"symbol" => "diamond"
],
];
$expectedResult = [
[
"value" => 9,
"symbol" => "club"
],
[
"value" => "jack",
"symbol" => "diamond"
],
[
"value" => 4,
"symbol" => "diamond"
],
[
"value" => 10,
"symbol" => "diamond"
],
[
"value" => 8,
"symbol" => "spade"
],
[
"value" => "queen",
"symbol" => "heart"
],
];
$this->assertSame($expectedResult, $cardSorting->sortBySortingLogic($initialSetCard));
}
public function testSortingEmptyCards(): void
{
$cardSorting = new CardSorting();
$this->assertEmpty($cardSorting->sortBySortingLogic());
}
} | true |
262fce4ed0c54491d38f26621be52c30efafb243 | PHP | sy-records/realtimehot-weibo | /realtimehot-weibo.php | UTF-8 | 2,940 | 2.515625 | 3 | [
"Apache-2.0"
] | permissive | <?php
/*
Plugin Name: Realtimehot Weibo(微博热搜榜)
Plugin URI: https://github.com/sy-records/realtimehot-weibo
Description: 在WordPress的仪表盘、小工具、文章、页面等地方加入微博热搜榜,随时随地 get 实时微博热搜,一键直达!
Version: 1.1.0
Author: 沈唁
Author URI: https://qq52o.me
License: Apache 2.0
*/
function luffy_http_get($url)
{
$body = '';
$headers = [
'cookie' => 'SUB=_2AkMWJrkXf8NxqwJRmP8SxWjnaY12zwnEieKgekjMJRMxHRl-yj9jqmtbtRB6PaaX-IGp-AjmO6k5cS-OH2X9CayaTzVD'
];
$response = wp_remote_get($url, ['headers' => $headers]);
if (is_array($response) && !is_wp_error($response) && $response['response']['code'] == '200') {
$body = $response['body'];
}
return $body;
}
function luffy_get_weibo_link_content($content)
{
preg_match('/<tbody>(.*)<\/tbody>/s', $content, $tbody);
preg_match_all('/<a.*?>(.*?)<\/a>/', $tbody[1], $result);
return $result;
}
function luffy_weibo_realtimehot($num)
{
if (is_admin()) {
echo '<p>欢迎使用 <a href="https://github.com/sy-records/realtimehot-weibo" title="Realtimehot Weibo(微博热搜榜)" target="_blank">Realtimehot Weibo(微博热搜榜)</a> 插件。</p>';
}
$num = !empty($num) ? $num : 10;
if ($num <= 51) {
$num = $num - 1;
} else {
$num = 50;
}
$content = luffy_http_get('https://s.weibo.com/top/summary?cate=realtimehot');
$result = luffy_get_weibo_link_content($content);
if (!empty($result)) {
echo '<ol>';
for ($x = 0; $x <= $num; $x++) {
$a = str_replace('https://s.weibo.com/weibo?q=', '/weibo?q=', $result[0][$x]);
echo "<li>{$a}</li>";
}
echo '</ol>';
}
}
function luffy_weibo_realtimehot_register_widgets()
{
wp_add_dashboard_widget('dashboard_luffy_weibo_realtimehot', '微博热搜榜', 'luffy_weibo_realtimehot');
}
add_action('wp_dashboard_setup', 'luffy_weibo_realtimehot_register_widgets');
add_filter('widget_text', 'luffy_text2php', 99);
function luffy_text2php($text)
{
if (strpos($text, '<' . '?') !== false) {
ob_start();
eval('?' . '>' . $text);
$text = ob_get_contents();
ob_end_clean();
}
return $text;
}
function luffy_get_weibo_realtimehot($atts, $content = null)
{
extract(shortcode_atts(array('num' => ''), $atts));
if (empty($atts)) {
$num = 10;
}
if ($num <= 51) {
$num = $num - 1;
} else {
$num = 50;
}
$content = luffy_http_get('https://s.weibo.com/top/summary?cate=realtimehot');
$result = luffy_get_weibo_link_content($content);
$html = '<div><ol>';
if (!empty($result)) {
for ($x = 0; $x <= $num; $x++) {
$a = str_replace('https://s.weibo.com/weibo?q=', '/weibo?q=', $result[0][$x]);
$html .= "<li>{$a}</li>";
}
}
$html .= '</ol></div>';
return $html;
}
add_shortcode('get_weibo_realtimehot', 'luffy_get_weibo_realtimehot');
| true |
1f281d0c1d1142cdb6f42e22b61a4912e95c7a92 | PHP | revolution-messaging/mobilize-php | /src/Revmsg/Mobilize/Collection.php | UTF-8 | 3,382 | 2.75 | 3 | [
"MIT"
] | permissive | <?php
namespace Revmsg\Mobilize;
class Collection extends Entity\Object implements Entity\CollectionInterface
{
protected $scheme = 'Revmsg\Mobilize\Model\Collection';
protected $customMap = array();
public function filter($property, $value, $operator = 'eq')
{
$output = array();
if (!is_array($value)) {
$value = array($value);
}
switch ($operator)
{
case 'eq':
foreach ($this->model->getVariable('collection') as $item => $contents) {
if ($contents[$property] == $value[0]) {
$output[] = $contents;
}
}
break;
case 'ne':
foreach ($this->model->getVariable('collection') as $item => $contents) {
if ($contents[$property] != $value[0]) {
$output[] = $contents;
}
}
break;
case 'gt':
foreach ($this->model->getVariable('collection') as $item => $contents) {
if ($contents[$property] >= $value[0]) {
$output[] = $contents;
}
}
break;
case 'ge':
foreach ($this->model->getVariable('collection') as $item => $contents) {
if ($contents[$property] <= $value[0]) {
$output[] = $contents;
}
}
break;
case 'lt':
foreach ($this->model->getVariable('collection') as $item => $contents) {
if ($contents[$property] < $value[0]) {
$output[] = $contents;
}
}
break;
case 'le':
foreach ($this->model->getVariable('collection') as $item => $contents) {
if ($contents[$property] > $value[0]) {
$output[] = $contents;
}
}
break;
case 'in':
foreach ($this->model->getVariable('collection') as $item => $contents) {
if (in_array($contents[$property], $value)) {
$output[] = $contents;
}
}
break;
case 'nin':
foreach ($this->model->getVariable('collection') as $item => $contents) {
if (!in_array($contents[$property], $value)) {
$output[] = $contents;
}
}
break;
default:
throw new \Exception('Invalid operator.');
}
$this->model->setVariable('collection', $output);
return $this;
}
public function toArray($index = null)
{
$output = $this->getVariable('collection');
if (!empty($output)) {
if ($index === null) {
return $output;
} else {
return $output[$index];
}
} else {
return false;
}
}
public function findArray($property, $value, $index = 0)
{
$this->filter($property, $value, 'eq');
return $this->toArray($index);
}
}
| true |
2a74ba1638091f1d22a70089bf4089d0bc921109 | PHP | langostinko/torrent-parser | /lib/loaders/FilmTorrentLoader.php | UTF-8 | 2,503 | 2.640625 | 3 | [] | no_license | <?php
include_once(__DIR__."/AbstractLoader.php");
include_once(__DIR__.'/../defines.php');
include_once(__DIR__.'/../simple_html_dom.php');
class FilmTorrentLoader extends AbstractLoader {
private $link;
function __construct($link) {
$this->result = array();
$this->link = $link;
}
function getFilmTorrentMovieCallback($response, $info) {
$msg = $info['http_code'] . " :: " . $info['url'] . " fetched in " . $info['total_time'];
if ($info['http_code'] != 200) {
$this->logger->warning($msg);
return;
}
$this->logger->info($msg);
$html = str_get_html($response);
if (!$html) {
$this->logger->warning("failed to convert DOM");
return;
}
foreach ($html->find("table[class=res85gtj] tr") as $row) {
$movie = array();
$title = $row->find("td", 1);
if (!$title) {
continue;
}
$title = html_entity_decode($row->find("td", 1)->find("div b", 0)->plaintext, ENT_QUOTES, "UTF-8");
extractString($title, $movie);
extractTranslate($title, $movie);
$size = html_entity_decode($row->find("td", 2)->plaintext);
$movie['size'] = (float)$size;
if (strpos($size, 'G'))
$movie['size'] *= 1024;
$movie['seed'] = (int)$row->find("td", 3)->plaintext;
$movie['leech'] = (int)$row->find("td", 4)->plaintext;
$movie['link'] = $info['url'] . "?it=" . $movie['size'] . $movie['quality'];
$movie['description'] = $title;
$this->result[] = $movie;
}
}
function getFilmTorrentCallback($response, $info) {
$msg = $info['http_code'] . " :: " . $info['url'] . " fetched in " . $info['total_time'];
if ($info['http_code'] != 200) {
$this->logger->warning($msg);
return;
}
$this->logger->info($msg);
$html = str_get_html($response);
if (!$html) {
$this->logger->warning("failed to convert DOM");
return;
}
foreach ($html->find("div[class=post-title] a") as $row) {
\RollingCurl::$rc->get($row->href, null, null, array("callback"=>array($this, "getFilmTorrentMovieCallback")) );
}
}
function load() {
$this->result = array();
\RollingCurl::$rc->get($this->link, null, null, array("callback"=>array($this, "getFilmTorrentCallback")) );
}
}
?>
| true |
a2a7d5584a5c83a34f2bc8840ef420d2ba03fda3 | PHP | depekur/eating-time | /backend/database/migrations/2018_05_05_004443_create_ingredients_table.php | UTF-8 | 766 | 2.78125 | 3 | [] | no_license | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateIngredientsTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('ingredients', function(Blueprint $table)
{
$table->increments('id');
$table->string('name', 100);
$table->text('description', 65535)->nullable();
$table->integer('calories')->unsigned()->nullable();
$table->float('fat', 10, 0)->unsigned()->nullable();
$table->float('proteins', 10, 0)->unsigned()->nullable();
$table->float('carbs', 10, 0)->unsigned()->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('ingredients');
}
}
| true |
f92a401ae28ea5ed7d15416fe5880e1617cf0e23 | PHP | ghonaime91/laravel-todo-final-task | /app/Http/Controllers/todoListController.php | UTF-8 | 4,498 | 2.84375 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\users;
use App\Models\tasks;
class todoListController extends Controller
{
//middle ware
public function __construct(){
$this->middleware('userCheck',['except' => ['create','store','LoginView','login']]);
}
// create user
public function createUser()
{
//
return view('todo.register');
}
// store user
public function storeUser(Request $req)
{
//
$data = $this->validate($req,[
"name" => "required|string",
"email" => "required|email",
"password" => "required|min:6"
]);
# Hashing Password
$data['password'] = bcrypt($data['password']);
# Store Data
$op = users::create($data);
if($op){
$message = "User Created";
}else{
$message = "Error Try Again";
}
# Set Message To Session ....
session()->flash('Message',$message);
return redirect(url('/todo/register'));
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index() // tasks page
{
$fetched_data = tasks::get();
foreach ($fetched_data as $d) {
$d->start_date = date('d/m/y', $d->start_date) ;
$d->end_date = date('d/m/y', $d->end_date);
}
$data = ["data"=>$fetched_data];
return view('todo.index',$data);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create() // create task page
{
// tasks form
return view('todo.create');
}
public function loginView()
{
// tasks form
return view('todo.login');
}
public function login(Request $req)
{
// login
$data = $this->validate($req,[
"email" => "required|email",
"password" =>"required|min:6"
]);
if(auth()->attempt($data)) {
return redirect('/todo');
} else {
return redirect(url('/todo/login'));
}
}
public function logout() {
auth()->logout();
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $req) // storing the task
{
//
$data = $this->validate($req,[
"title" => "required|string",
"description" => "required",
"start_date" => "required|date",
"end_date" => "required|date",
"image" => "required|mimes:jpeg,png,jpg",
]);
# image
$img = $req->file('image');
$new_name = rand().'.'.$img->getClientOriginalExtension();
$img->move(public_path('images'),$new_name);
$data['image'] = $new_name;
#date operation
$data['start_date'] = strtotime($data['start_date']);
$data['end_date'] = strtotime($data['end_date']);
# Store Data
$op = tasks::create($data);
if($op){
$message = "task Created";
}else{
$message = "Error Try Again";
}
# Set Message To Session ....
session()->flash('Message',$message);
return redirect(url('/todo'));
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
$op = users::where('id',$id)->delete();
}
}
| true |
7ebd5fad5de33996bafd92bf1c1e90abbb8d0844 | PHP | alexdu98/Ambiguss | /src/AppBundle/Repository/HistoriqueRepository.php | UTF-8 | 2,395 | 2.5625 | 3 | [
"MIT"
] | permissive | <?php
namespace AppBundle\Repository;
use AppBundle\Entity\Membre;
use Doctrine\ORM\EntityRepository;
class HistoriqueRepository extends EntityRepository
{
/**
* Retourne le nombre d'historique
*
* @param Membre $membre
* @return mixed
* @throws \Doctrine\ORM\NoResultException
* @throws \Doctrine\ORM\NonUniqueResultException
*/
public function countAllByMembre(Membre $membre)
{
return $this->createQueryBuilder('h')
->select('count(h) nbHistorique')
->where('h.membre = :membre')->setParameter('membre', $membre)
->getQuery()->getOneOrNullResult()['nbHistorique'];
}
/**
* Retourne les lignes correspondantes aux différentes conditions (dataTable AJAX)
*
* @param $start Numéro de la première ligne retournée
* @param $length Nombre de ligne à retourner
* @param $orders Ordre du tri
* @param $search Recherche de caractère
* @param $columns Colonnes
* @param null $otherConditions Autres conditions
* @return array Tableau des données trouvées
* @throws \Doctrine\ORM\NonUniqueResultException
*/
public function getRequiredDTData($start, $length, $orders, $search, $columns, $otherConditions = null)
{
$query = $this->createQueryBuilder('h')
->where('h.membre = :membre')
->setParameters($otherConditions)
->orderBy('h.dateAction', $orders[0]['dir'])
->setFirstResult($start)
->setMaxResults($length);
$countQuery = $this->createQueryBuilder('h')
->select('COUNT(h)')
->where('h.membre = :membre')
->setParameters($otherConditions);
if(!empty($search['value'])){
$query
->andWhere('DATE_FORMAT(h.dateAction, \'%d/%m/%Y %H:%i\') like :search OR h.valeur like :search')
->setParameter('search', '%' . $search['value'] . '%');
$countQuery
->andWhere('DATE_FORMAT(h.dateAction, \'%d/%m/%Y %H:%i\') like :search OR h.valeur like :search')
->setParameter('search', '%' . $search['value'] . '%');
}
$res = array(
'results' => $query->getQuery()->getArrayResult(),
'countResult' => $countQuery->getQuery()->getSingleScalarResult()
);
return $res;
}
}
| true |
4581bb44724e3960458122a7dfc0f10af574bd05 | PHP | enimiste/colors-names | /src/W3SchoolColors.php | UTF-8 | 471 | 2.59375 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: e.nouni
* Date: 26/09/2016
* Time: 13:21
*/
namespace Com\NickelIT\Colors;
class W3SchoolColors
{
/**
* Returns a list of colors names mapped with its hex code.
* Ex: ['name' => 'AliceBlue', 'hex' => '#F0F8FF'],
*
* @return array
*/
public static function colors()
{
$path = __DIR__ . '/output/colors_names.php';
return file_exists($path) ? require $path : [];
}
} | true |
d395f1c4fd44b61118ab4bd2e0cc947e11ad8424 | PHP | nickdi2000/mountain | /application/controllers/Race.php | UTF-8 | 3,170 | 2.609375 | 3 | [
"MIT"
] | permissive | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Race extends MY_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->library('session');
$this->load->model(Array('racer_model', 'race_model'));
}
public function start()
{
// echo json_encode($_SESSION);die();
//$data['start_time'] = isset($_SESSION['start_time']) ? $_SESSION['start_time'] : null;
//$data['initials'] = isset($_SESSION['initials']) ? $_SESSION['initials'] : '';
//$data['racer_id'] = isset($_SESSION['racer_id']) ? $_SESSION['racer_id'] : 0;
//$data['status'] = isset($_SESSION['status']) ? $_SESSION['status'] : null;
//$data['duration'] = isset($_SESSION['duration']) ? $_SESSION['duration'] : null;
//$data['race_data'] = $this->race_model->get_race_data(1); //hardcode 1 until made into SaaS
$this->load->view('header');
$this->load->view('race/start');
$this->load->view('footer');
}
/* for axios */
//get the one race for the actual racing process
public function get_race_data($race_id){
//$race_id = 1; //hard-coded until SaaSified
echo json_encode($data['race_data'] = $this->race_model->get_race_data($race_id));
}
//get all races for user
public function get_races(){
$return = $this->get_all_races(); //parent method
echo json_encode($return);
}
public function get_racer_data(){
if(isset($_SESSION['racer_id'])){
$data['racer_data'] = $this->racer_model->get_racer_data($_SESSION['racer_id']);
}else{
$data['racer_id'] = 0;
}
$data['duration'] = isset($_SESSION['duration']) ? $_SESSION['duration'] : null;
echo json_encode($data);
}
public function create_racer($initials){
$racer_id = $this->racer_model->create_racer($initials);
if($racer_id){
$this->session->set_userdata('racer_id', $racer_id);
//$this->session->set_userdata('initials', $initials);
//$this->session->set_userdata('status', 'ready');
echo $racer_id;
}else{
echo 'errorr';
}
}
public function update_racer_status($status){
$this->session->set_userdata('status', $status);
echo $this->racer_model->update_status($status);
}
public function set_race($id = 0){
echo $this->session->set_userdata('current_race_id', $id);
}
public function set_time_started(){
$time = date(DATE_ISO8601);
$this->session->set_userdata('time_began', $time);
$this->racer_model->set_time_started($time);
echo (string) $time;
}
public function set_time_ended(){
$query = $this->racer_model->get_start_time();
$start_time = $query[0]['start_time'];
$end_time = date(DATE_ISO8601); //get current time Again
$seconds = strtotime($end_time) - strtotime($start_time);
$duration = gmdate("H:i:s", $seconds); //convert raw seconds (342) to time (3:23:32)
//write data
$this->session->set_userdata('time_ended', $end_time);
$this->session->set_userdata('duration', $duration);
$this->racer_model->set_time_ended($end_time);
$data['duration'] = $duration;
$data['end_time'] = $end_time;
echo json_encode($data);
}
}
| true |
3baffeeede446ce379575d5378bf447e9bc98018 | PHP | PaddyS/panic-lab-helper-core | /tests/Unit/Services/Hydrators/HydrationCollectorTest.php | UTF-8 | 3,653 | 2.59375 | 3 | [
"MIT"
] | permissive | <?php declare(strict_types=1);
namespace PanicLabCore\Tests\Unit\Services\Hydrators;
use PanicLabCore\Services\Exceptions\InvalidTileTypeException;
use PanicLabCore\Services\Hydrators\HydrationCollector;
use PanicLabCore\Services\Hydrators\HydratorInterface;
use PanicLabCore\Services\Hydrators\SwitchHydrator;
use PanicLabCore\Services\Validators\SwitchValidator;
use PanicLabCore\Structs\SwitchTile;
use PanicLabCore\Structs\Tile;
use PanicLabCore\Structs\VentTile;
use PHPUnit\Framework\TestCase;
class HydrationCollectorTest extends TestCase
{
public function testSupportsShouldAlwaysReturnTrue() : void
{
$hydrationCollector = $this->getInstance();
self::assertTrue($hydrationCollector->supports('foo'));
}
public function testHydrateRedirectsToProperHydrator() : void
{
$hydrationCollector = $this->getInstance();
$hydratedResult = $hydrationCollector->hydrate([
'type' => 'switch',
'additional' => [
'type' => 'color'
]
]);
self::assertInstanceOf(SwitchTile::class, $hydratedResult);
}
public function testHydrateSkipsInvalidHydrator() : void
{
$invalidHydrator = new InvalidHydratorMock();
$hydrationCollector = $this->getInstance([ $invalidHydrator ]);
$hydrationCollector->hydrate([
'type' => 'switch',
'additional' => [
'type' => 'color'
]
]);
self::assertTrue($invalidHydrator->supportChecked);
}
public function testHydrateShouldThrowExceptionInvalidTileType() : void
{
$hydrationCollector = $this->getInstance();
$this->expectException(InvalidTileTypeException::class);
$this->expectExceptionMessage('The provided type \'invalid\’ seems to be invalid. No matching hydrator found.');
$hydrationCollector->hydrate([
'type' => 'invalid'
]);
}
public function testHydrateThrowsExceptionTypeMissing() : void
{
$hydrationCollector = $this->getInstance();
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('Expected the key "type" to exist.');
$hydrationCollector->hydrate([
'notType' => 'invalid',
'additional' => [
'type' => 'color'
]
]);
}
public function testHydrateThrowsExceptionTileHydratorNoticesInvalidTile() : void
{
$hydrationCollector = $this->getInstance();
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('Expected one of: "color", "size", "style". Got: "foo"');
$hydrationCollector->hydrate([
'type' => 'switch',
'additional' => [
'type' => 'foo'
]
]);
}
private function getInstance(array $additionalHydrators = []): HydrationCollector
{
$hydrators = [
new SwitchHydrator(
new SwitchValidator(['color', 'size', 'style'])
)
];
$hydrators = array_merge($additionalHydrators, $hydrators);
return new HydrationCollector(
new \ArrayIterator($hydrators)
);
}
}
class InvalidHydratorMock implements HydratorInterface
{
public $supportChecked = false;
public function supports(string $type): bool
{
$this->supportChecked = true;
return false;
}
public function hydrate(array $tile): Tile
{
return new VentTile();
}
public function validate(array $tile): void
{
}
} | true |
a622bdd75080d19894bd4e6c49d1cdcc647a12aa | PHP | smallsee/kkzl | /app/Api/Transformers/AnimeTransformer.php | UTF-8 | 619 | 2.578125 | 3 | [
"MIT"
] | permissive | <?php
/**
* Created by PhpStorm.
* User: xiaohai
* Date: 17/8/4
* Time: 22:32
*/
namespace App\Api\Transformers;
use League\Fractal\TransformerAbstract;
class AnimeTransformer extends TransformerAbstract
{
public function transform($anime){
return [
'id' => $anime['id'],
'title' => $anime['title'],
'thumb' => $anime['thumb'],
'created_at' => $anime['created_at'],
'akira' => explode(',',str_replace(" ","",str_replace("\n","",$anime['akira']))),
'tag' => explode(',',$anime['tag']),
'see' => $anime['see'],
];
}
} | true |
1a1398b81e0ae081bb4456dfa325af1d750196f5 | PHP | zhalnin/service | /imei-service-edited/dmn/system_article/paragraph.php | UTF-8 | 11,382 | 2.53125 | 3 | [] | no_license | <?php
/**
* Created by JetBrains PhpStorm.
* User: zhalnin
* Date: 21.04.12
* Time: 22:19
* To change this template use File | Settings | File Templates.
*/
error_reporting(E_ALL & ~E_NOTICE);
// Устанавливаем соединение с базой данных
//require_once("../../config/config.php");
// Подключаем блок авторизации
require_once("../utils/security_mod.php");
// Подключаем классы
require_once("../../config/class.config.dmn.php");
// Навигационное меню
require_once("../utils/utils.navigation.php");
// Обработка текста перед выводом
require_once("../utils/utils.print_page.php");
// Защита от SQL-инъекции
$_GET['id_position'] = intval($_GET['id_position']);
$_GET['id_catalog'] = intval($_GET['id_catalog']);
//echo "<tt><pre>".print_r($_REQUEST, true)."</pre></tt>";
try
{
// Извлекаем информацию о разделе
$query = "SELECT * FROM $tbl_catalog
WHERE id_catalog = $_GET[id_catalog]
LIMIT 1";
$cat = mysql_query($query);
if(!$cat)
{
throw new ExceptionMySQL(mysql_error(),
$query,
"Ошибка при обращении
к каталогу");
}
$catalog = mysql_fetch_array($cat);
// Извлекаем информацию об элементе
$query = "SELECT * FROM $tbl_position
WHERE id_position=$_GET[id_position]";
$pos = mysql_query($query);
if(!$pos)
{
throw new ExceptionMySQL(mysql_error(),
$query,
"Ошибка при обращении
к позиции");
}
$position = mysql_fetch_array($pos);
$title = $titlepage = 'Позиция ('.$catalog['name'].
' - '.$position['name'].')';
$pageinfo = '<p class=help>Здесь осуществляется
администрирование позиции ('.$catalog['name'].
' - '.$position['name'].').
Параграф может представлять собой как обычный
текстовый абзац, так и заголовок. Возможно
использование шести уроней заголовков
(H1, H2, H3, H4, H5, H6), H1 - самый крупный
заголовок, применяемый обычно для названия
страниц; далее заголовки уменьшаются в
размере, то есть H6 - это самый мелкий заголовок.</p>';
// Количество ссылок в постраничной навигации
$page_link = 3;
// Количество элементов на странице
$pnumber = 10;
// Объявляем объект постраничной навигации
$obj = new PagerMysql($tbl_paragraph,
"WHERE id_position = $_GET[id_position] AND
id_catalog = $_GET[id_catalog]",
"ORDER BY pos",
$pnumber,
$page_link,
"&id_position=$_GET[id_position]&".
"id_catalog=$_GET[id_catalog]");
// Получаем содержимое текущей страницы
$paragraph = $obj->get_page();
//echo $_GET['id_position'];
// echo $_GET['id_catalog'];
// Включаем заголовок страницы
require_once("../utils/top.php");
// Если это не корневой раздел, выводим ссылки для возврата
// и для добавления подраздела
if($_GET['id_catalog'] != 0)
{
echo '<table cellpadding="0" cellspacing="0" border="0">
<tr valign="top">
<td height="25"><p>';
echo "<a class=menu href=index.php?id_parent=0>
Корневой каталог</a>->".
menu_navigation($_GET['id_catalog'],
"",
$tbl_catalog) .$position['name'];
echo "</td>
</tr>
</table>";
}
// Добавить параграф
echo "<form action=paradd.php>";
echo "<input class='button'
type='submit'
value='Добавить параграф'><br/><br/>";
echo "<input type='hidden' name='page' value='$_GET[page]'><br/><br/>";
// Выводим заголовок таблицы разделов
echo "<input type='hidden'
name='id_catalog'
value=$_GET[id_catalog]>";
echo "<input type='hidden'
name='id_position'
value=$_GET[id_position]>";
echo "<table width='100%'
class='table'
border='0'
cellpadding='0'
cellspacing='0'>
<tr class='header' align='center'>
<td width='20' align='center'>
<input type='radio' name='pos' value='-1' checked>
</td>
<td align='center'>Содержимое</td>
<td width='100' align='center'>Изображение<br/> и файлы</td>
<td width='100' align='center'>Тип</td>
<td width='20' align='center'>Поз.</td>
<td width='50'>Действия</td>
</tr>";
if(!empty($paragraph))
{
for($i = 0; $i < count($paragraph); $i++)
{
$url = "id_paragraph={$paragraph[$i][id_paragraph]}".
"&id_position=$_GET[id_position]&".
"id_catalog=$_GET[id_catalog]".
"&page=$_GET[page]";
// Выясняем тип параграфа
$type = "Параграф";
switch($paragraph[$i]['type'])
{
case 'text':
$type = 'Параграф';
break;
case 'title_h1':
$type = "Заголовок H1";
break;
case 'title_h2':
$type = "Заголовок H2";
break;
case 'title_h3':
$type = "Заголовок H3";
break;
case 'title_h4':
$type = "Заголовок H4";
break;
case 'title_h5':
$type = "Заголовок H5";
break;
case 'title_h6':
$type = "Заголовок H6";
break;
case 'list':
$type = "Список";
break;
}
// Выясняем тип выравнивания параграфа
$aligh = "";
switch($paragraph[$i]['align'])
{
case 'left':
$align = "align=left";
break;
case 'center':
$align = "align=center";
break;
case 'right':
$align = "align=right";
break;
}
// Выясняем скрыт раздел или нет
if($paragraph[$i]['hide'] == 'hide')
{
$strhide = "<a href=parshow.php?$url>Отобразить</a>";
$style="class=hidden";
}
else
{
$strhide = "<a href=parhide.php?$url>Скрыть</a>";
$style = "";
}
// Вычисляем, сколько изображений у данного элемента
$query = "SELECT COUNT(*) FROM $tbl_paragraph_image
WHERE id_paragraph = {$paragraph[$i][id_paragraph]} AND
id_position = $_GET[id_position] AND
id_catalog = $_GET[id_catalog]";
$tot = mysql_query($query);
if(!$tot)
{
throw new ExceptionMySQL(mysql_error(),
$query,
"Ошибка при подсчете
количества изображений");
}
$total_image = mysql_result($tot, 0);
if($total_image) $print_image = " ($total_image)";
else $print_image = "";
// echo "<tt><pre>".print_r($paragraph[$i]['name'], true)."</pre></tt>";
echo "<tr $style $class>
<td align=center>
<input type=radio name=pos value=".$paragraph[$i]['pos']." />
</td>
<td><p $align>".
nl2br(print_page($paragraph[$i]['name'])).
"</p></td>";
if( $total_image > 0 ) {
echo "<td align=center>
<a href=\"show.php?$url\">Изображения$print_image</a>
</td>";
} else {
echo "<td align=center>
<p>Изображений нет</p>
</td>";
}
echo "<td align=center>".print_page($type)."</td>
<td align=center>".$paragraph[$i]['pos']."</td>
<td>
<a href=parup.php?$url>Вверх</a><br>
$strhide<br>
<a href=paredit.php?$url>Редактировать</a><br>
<a href=# onClick=\"delete_position('pardel.php?$url',".
"'Вы действительно хотите удалить параграф');\">Удалить</a><br>
<a href=pardown.php?$url>Вниз</a></td>
</tr>";
}
}
echo "</table><br><br>";
echo "</form>";
// Выводим ссылки на другие страницы
echo $obj;
}
catch(ExceptionMySQL $exc)
{
require("../utils/exception_mysql.php");
}
// Включаем завершение страницы
require_once("../utils/bottom.php");
?>
<!--<script type="text/javascript" language="javascript">-->
<!-- <!---->
<!-- function delete_par(url)-->
<!-- {-->
<!-- if(confirm("Вы действительно хотите удалить параграф?"))-->
<!-- {-->
<!-- location.href=url;-->
<!-- }-->
<!-- return false;-->
<!-- }-->
<!-- //-->
<!--</script>-->
<script type="text/javascript">
<!--
function show_img(id_position, width, height)
{
var a;
var b;
var url;
vidWindowWidth = width;
vidWindowHeight = height;
a = (screen.height-vidWindowHeight)/5;
b = (screen.width-vidWindowWidth)/2;
features = "top="+a +",left="+b+
",width="+vidWindowWidth+
",height="+vidWindowHeight+
",toolbar=no,menubar=no,location=no,"+
"directories=no,scrollbars=no,resizable=no";
url = "../../show.php?id_position="+id_position;
window.open(url,'',features,true);
}
//-->
</script> | true |
b952c0350929921ef6a9a6528ca6a44a62d54016 | PHP | ki-ti/gs_kadai | /第9回課題/session_regenerate_id.php | UTF-8 | 235 | 2.671875 | 3 | [] | no_license | <?php
session_start();
$old_sessionid = session_id();
session_regenerate_id(true);
$new_sessionid = session_id();
echo "古いセッション: $old_sessionid<br />";
echo "新しいセッション: $new_sessionid<br />";
?> | true |
b731712ec58bdc3b729f4ad00e52931c3e758a4c | PHP | marthiam/Moovite | /web/index1.php | UTF-8 | 309 | 2.90625 | 3 | [] | no_license | <?php include("algo.php"); ?>
<!DOCTYPE html>
<html>
<head>
<title>Page test</title>
</head>
<body>
<h1>Test de l' algorithme</h1>
<?php
echo "le voyage".choix("brest","antibes",0,100,100, '2015-02-01');
?>
</body>
</html>
| true |
2db17ad14082acb2717c8747cb2475f86c8f0639 | PHP | botrelli/okoabundle | /src/Tg/OkoaBundle/Util/StringUtil.php | UTF-8 | 859 | 3.21875 | 3 | [
"MIT"
] | permissive | <?php
namespace Tg\OkoaBundle\Util;
/**
* String utility functions.
*/
class StringUtil
{
/**
* Very basic function that makes some english word plural.
* @param string $str
* @return string
*/
public static function pluralize($str)
{
if (strlen($str) > 0 && $str[strlen($str) - 1] === 's') {
return $str . 'es';
}
return $str . 's';
}
/**
* Very basic function that makes an english plural singular.
* @param string $str
* @return string
*/
public static function singular($str)
{
if (strlen($str) > 0 && $str[strlen($str) - 1] === 's') {
if (strlen($str) > 2 && substr($str, -3) == 'ses') {
return substr($str, 0, -2);
}
return substr($str, 0, -1);
}
return $str;
}
}
| true |
25996afbe81ec36455af845cba4e790f5d1c6d76 | PHP | frodcode/OperationsBundle | /Calculator/Operation/ApplyCalculator.php | UTF-8 | 434 | 2.546875 | 3 | [] | no_license | <?php
namespace Acme\OperationsBundle\Calculator\Operation;
/**
* @author odehnal@medio.cz
*/
class ApplyCalculator implements IOperationCalculator
{
public function calculate($doValue, $oldValue)
{
if ($oldValue !== NULL) {
throw new \Acme\OperationsBundle\Calculator\Exception\IllegalArgumentException('Old value for apply calculator is supposed to be NULL - it should be the very first operation');
}
return $doValue;
}
}
| true |
302407ce09a9843c677c519ae02cbdf5efd9cd2d | PHP | dalehurley/code-igniter-tools | /custom_db_drivers/example_mysql_model.php | UTF-8 | 1,155 | 2.640625 | 3 | [
"Unlicense"
] | permissive | <?php
// an example model using the additionnal mysql driver functions
class example_mysql_model extends CI_Model
{
public function add_or_replace()
{
// "REPLACE INTO table (foo) VALUES (bar)"
$this->insert_replace('table', array('foo' => 'bar'));
// you can also do
$this->replace();
$this->insert('table', array('foo' => 'bar'));
}
public function add_or_ignore()
{
// "INSERT IGNORE INTO table (foo) VALUES (bar)"
$this->insert_ignore('table', array('foo' => 'bar'));
// you can also do
$this->ignore();
$this->insert('table', array('foo' => 'bar'));
}
public function update_or_ignore()
{
// "UPDATE IGNORE table SET foo = bar WHERE hallo = world"
$this->update_ignore('table', array('foo' => 'bar'), array('hello' => 'world'));
// you can also do
$this->ignore();
$this->update('table', array('foo' => 'bar'), array('hello' => 'world'));
}
public function add_or_update()
{
// "INSERT INTO table (foo) VALUES (bar) ON DUPLICATE KEY UPDATE foo = foo + 1"
$this->on_duplicate_key('foo = foo + 1');
$this->insert('table', array('foo' => 'bar'));
}
}
| true |
097646d7eadebeabc50b10eae932cd199417ef7b | PHP | Samonzs/twa_project | /login.php | UTF-8 | 2,644 | 2.828125 | 3 | [] | no_license | <?php
require_once("nocache.php");
$errorMessage = '';
// check that the form has been submitted
if(isset($_POST['submit'])) {
if(empty($_POST['email']) || empty($_POST['password'])) {
$errorMessage = "A password or email is required";
}
else{
require_once("conn.php");
$email = $dbConn->escape_string($_POST['email']);
$password = $dbConn->escape_string($_POST['password']);
// hash the password so it can be compared with the db value
$hashedPassword = hash('sha256', $password);
// query the db
$sql = "select email, password from leagueAdmin where email = '$email' and password = '$hashedPassword'";
$results = $dbConn->query($sql);
// check number of rows in record set
if($results->num_rows) {
session_start();
// Store the user details in session variables
$user = $results->fetch_assoc();
$_SESSION['password'] = $user['password'];
// Redirect the user to the secure page
header('Location: scoreEntry.php');
}
else {
$errorMessage = "Invalid Username or Password";
}
}
}
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Login</title>
<link rel="stylesheet" href="css/projectMaster.css">
<script src = "javascript/loginValidation.js"></script>
</head>
<body>
<nav class="nav">
<div class ="homePage">
<a href="index.php">A-League</a> <br> <br>
</div>
<a href="ladder.php">Ladder</a>
<a href="fixtures.php">Fixtures </a>
<a href="scoreEntry.php">Enter Results</a>
<?php if (isset($_SESSION["password"])){?>
<a class = "logoff" href="logoff.php">Logoff</a>
<?php } else { ?>
<a class = "logoff" href="login.php">Login</a>
<?php } ?>
</nav>
<div class="loginBox">
<div class = "loginTitle">
<label>Admin Panel</label>
</div>
<section class="main">
<form method="post">
<div class="formClass">
<label class ="formLabel">EMAIL</label>
<input class="inputBox" name="email" type="text" placeholder="Email">
</div>
<div class="formClass">
<label class = "formLabel">PASSWORD</label>
<input class="inputBox" name ="password" type="password" placeholder="Password">
<p style="color:red;"><?php echo $errorMessage;?></p>
</div>
<button name= "submit" type="submit" class="submit">LOGIN</button>
</section>
</div>
</form>
</body>
</html>
| true |
0cc08e36da8121ca5807f8a8d21b858165a418c6 | PHP | frankmolenaar1986/funda-project | /php/client.php | UTF-8 | 2,813 | 2.640625 | 3 | [] | no_license | <?php
// Variable that could be set in JS or other calling resource, hardcoded for
// the assignment
$numerOfAgents = 10;
// Variable that could be set in JS or other calling resource, hardcoded for
// the assignment
$urlKey = "005e7c1d6f6c4f9bacac16760286e3cd";
// Base of the url to be added onto later
$urlBase = "http://partnerapi.funda.nl/feeds/Aanbod.svc/json/$urlKey/?type=koop&zo=/amsterdam/tuin/&page=1&pagesize=";
// Get the total number of houses from the API
$numberOfHouses = json_decode(file_get_contents("$urlBase"))->TotaalAantalObjecten;
// This does not seem to be working; I'm attempting to retrieve get all the
// houses in Amsterdam with a yard, based on the number previously
// retrieved, but I only seem to be able to retrieve 25 max. Technically i
// could loop using the page number, but that'd mean sending 1410 / 25
// (the $numberOfHouses at this time) = 56 requests to the api and since i'm
// i'd be locked out of the service after more than 100 per minute i left it
// like this for now.
$houses = json_decode(file_get_contents($urlBase.$numberOfHouses));
// Set an empty array and fill them with all the agents with houses
// containing the set options
$agents = [];
foreach ($houses->Objects as $arr)
{
array_push($agents, $arr->MakelaarId);
}
// Count the number of houses per agent
$agentsWithOccurences = array_count_values($agents);
// Sort the keys on amounts
arsort($agentsWithOccurences);
// Return an array of the agent id's
$agentIds = array_keys($agentsWithOccurences);
// Build tables sorted by the agents with the most houses in their
// portfolio. Normally I would always build a json string or different
// data object but for the sake of this assignment I figured this would
// do to demonstrate what i'm trying to do.
$htmlReturnString = "";
// Loop the array of houses once for every agent in the top 10
// The choice here was to loop the entire array
for ($i = 0; $i < $numerOfAgents; $i++)
{
$htmlReturnString .= "";
foreach ($houses->Objects as $arr)
{
if ($arr->MakelaarId == $agentIds[$i])
{
$htmlReturnString .= "<tr>";
$htmlReturnString .= "<td>".$arr->Adres."</td>";
$htmlReturnString .= "<td>".$arr->AangebodenSindsTekst."</td>";
$htmlReturnString .= "<td><img src='".$arr->FotoMedium."'/></td>";
$htmlReturnString .= "<td>".$arr->MakelaarNaam."</td>";
$htmlReturnString .= "</tr/>";
}
}
}
echo $htmlReturnString;
?> | true |
3d39407a176775d30887a0e52d9f3294f128f4a0 | PHP | HH8023/php-demo | /mine/mine/628/demo4.php | UTF-8 | 302 | 3.03125 | 3 | [] | no_license | <?php
/*
32位下整型的最大值,PHP_INT_MAX,21亿多;
最小值,PHP_INT_MIN -21亿多,PHP中新增的函数
*/
echo '32位软件下,PHP整型的最大值是:', PHP_INT_MAX, "<br>";
echo '32位软件下,PHP整型的最小的值是:', PHP_INT_MIN, "<br>";
var_dump(PHP_INT_MIN);
| true |
7345051a2d0f0c2cf2bf5168389b16af3911b6b6 | PHP | Ph3nol/Docker-Arch | /src/Application/TemplatedFileGenerator.php | UTF-8 | 1,191 | 2.71875 | 3 | [
"MIT"
] | permissive | <?php
namespace Ph3\DockerArch\Application;
use Ph3\DockerArch\Application\Twig\Extension\DockerfileExtension;
use Twig_Environment;
use Twig_Extension_Debug;
use Twig_Loader_Filesystem;
/**
* @author Cédric Dugat <cedric@dugat.me>
*/
class TemplatedFileGenerator implements TemplatedFileGeneratorInterface
{
/**
* @var Twig_Environment
*/
private $templateEngine;
/**
* Constructor.
*/
public function __construct()
{
$loader = new Twig_Loader_Filesystem(__DIR__.'/Resources/views');
$this->templateEngine = new Twig_Environment($loader, ['debug' => true]);
$this->templateEngine->addExtension(new Twig_Extension_Debug());
$this->templateEngine->addExtension(new DockerfileExtension());
}
/**
* @return Twig_Environment
*/
public function getTemplateEngine(): Twig_Environment
{
return $this->templateEngine;
}
/**
* @param string $viewPath
* @param array $parameters
*
* @return string
*/
public function render(string $viewPath, array $parameters = []): string
{
return $this->getTemplateEngine()->render($viewPath, $parameters);
}
}
| true |
5bec381429164502f09ceba346cb0a616ec6d5f4 | PHP | DonVit/cstmd | /common/NewsCategory.php | UTF-8 | 431 | 2.53125 | 3 | [] | no_license | <?php
class NewsCategory extends DBManager {
public $id;
public $name_ro;
public $name_ru;
public $name_en;
public $description_ro;
public $description_ru;
public $description_en;
public $order;
public $valid;
function getTableName(){
return "news_category";
}
function getName1(){
$fieldname="name_".$this->getLang()->name;
//echo $fieldname;
return $this->$fieldname;
//return "menu item";
}
}
?>
| true |
a2e89b329eebf794482f7e0abec867c3eb2ac818 | PHP | lees9/assignment4-part2 | /inventory.php | UTF-8 | 1,456 | 2.921875 | 3 | [] | no_license | <!-- Name: Sang Hoon Lee
Class: CS290 W15
Assignment: 4 part 2
Filename: inventory.php
Description: Contains the functions and method to filter by category,
add movies, and remove movies.
Date: 02/15/15
-->
<?php
include_once('sql.php');
//function to filter by category name
function getFilter() {
if (isset($_POST['value'])){
if ($_POST['value'] != "all"){
$categoryName = $_POST['value'];
return $categoryName;
}
}
return 'all';
}
//function to return post operation
function getOperation() {
if (isset($_POST['operation'])){
return $_POST['operation'];
}
return "index";
}
$sql = new Sql();
$categories = $sql->getCategories(); //get the distinct categories
//from post operations for adding movie, removing movie, check in and out
$op = getOperation();
if ($op === 'insert') {
$title = $_POST['title'];
$category = $_POST['category'];
$length = $_POST['length'];
$sql->newRecord($title, $category, $length);
} else if ($op === 'remove') {
$id = $_POST['id'];
$sql->removeOne($id);
} else if ($op === 'remove_all') {
$sql->removeAll();
} else if ($op === 'checkout' || $op === 'checkin') {
$id = $_POST['id'];
$sql->checkInOrOut($op, $id);
}
//get filter category
$filter = getFilter();
//call function to get filtered records and set to $filteredRecords to be printed
$filteredRecords = $sql->getFilteredRecords($filter);
include 'render.php';
?>
| true |
688a38da0c12c7b5b170fc109e1b219c16a3aae8 | PHP | skrishnamurthy2/hangman | /src/Service/Game.php | UTF-8 | 248 | 2.6875 | 3 | [] | no_license | <?php
namespace Hangman\Service;
use Hangman\Message\GameStateMessage;
interface Game
{
public function getGame(string $gameId): GameStateMessage;
public function guess (string $gameId, int $version, string $letter): GameStateMessage;
} | true |
77fe0c7017ca18c415e43953401e371d59bf397f | PHP | PT-Studios/rust-donation-credits-webcode | /includes/mysql/config/config.php | UTF-8 | 2,254 | 2.953125 | 3 | [] | no_license | <?php
require_once $_SERVER["DOCUMENT_ROOT"] . '/includes/app_config.php';
$hn = $GLOBALS['cfg']['hostname'];
$un = $GLOBALS['cfg']['username'];
$pw = $GLOBALS['cfg']['password'];
$db = $GLOBALS['cfg']['dbname'];
class ConnDB{
//Vars
protected $hostname;
protected $username;
protected $password;
protected $dbname;
private $stmt;
private $dbh;
private $error;
public function __construct(){
global $hn;
global $un;
global $pw;
global $db;
$this->hostname = $hn;
$this->username = $un;
$this->password = $pw;
$this->dbname = $db;
//Set connection
$dsn = 'mysql:host=' . $this->hostname . ';dbname=' . $this->dbname;
//Set Options (unused)
$options = array(
//PDO::ATTR_PERSISTENT => true,
//PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
//Create a PDO instance
try{
$this->dbh = new PDO($dsn, $this->username, $this->password, $options);
}
// Catch any errors
catch(PDOException $e){
$this->error = $e->getMessage();
}
}
public function query($query){
$this->stmt = $this->dbh->prepare($query);
}
public function bind($param, $value, $type = null){
if (is_null($type)){
switch (true) {
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
}
}
$this->stmt->bindValue($param, $value, $type);
}
public function execute(){
return $this->stmt->execute();
}
public function resultset(){
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}
public function single(){
$this->execute();
return $this->stmt->fetch(PDO::FETCH_ASSOC);
}
public function rowCount(){
return $this->stmt->rowCount();
}
public function beginTransaction(){
return $this->dbh->beginTransaction();
}
public function endTransaction(){
return $this->dbh->commit();
}
public function cancelTransaction(){
return $this->dbh->rollBack();
}
public function debugDumpParams(){
return $this->stmt->debugDumpParams();
}
public function lastInsertId(){
return $this->dbh->lastInsertId();
}
}
?>
| true |
be02d6e0a0bf68a434572c2c0119ff508cccece0 | PHP | luigif/WsdlToPhp | /samples/xignite-globalrealtime/Tick/XiGlobalrealtimeTypeTick.php | UTF-8 | 5,452 | 2.796875 | 3 | [] | no_license | <?php
/**
* Class file for XiGlobalrealtimeTypeTick
* @date 08/07/2012
*/
/**
* Class XiGlobalrealtimeTypeTick
* @date 08/07/2012
*/
class XiGlobalrealtimeTypeTick extends XiGlobalrealtimeWsdlClass
{
/**
* The Date
* Meta informations :
* - minOccurs : 0
* - maxOccurs : 1
* @var string
*/
public $Date;
/**
* The Time
* Meta informations :
* - minOccurs : 0
* - maxOccurs : 1
* @var string
*/
public $Time;
/**
* The UTCDate
* Meta informations :
* - minOccurs : 0
* - maxOccurs : 1
* @var string
*/
public $UTCDate;
/**
* The UTCTime
* Meta informations :
* - minOccurs : 0
* - maxOccurs : 1
* @var string
*/
public $UTCTime;
/**
* The Last
* Meta informations :
* - minOccurs : 1
* - maxOccurs : 1
* @var double
*/
public $Last;
/**
* The High
* Meta informations :
* - minOccurs : 1
* - maxOccurs : 1
* @var double
*/
public $High;
/**
* The Low
* Meta informations :
* - minOccurs : 1
* - maxOccurs : 1
* @var double
*/
public $Low;
/**
* The First
* Meta informations :
* - minOccurs : 1
* - maxOccurs : 1
* @var double
*/
public $First;
/**
* The Quantity
* Meta informations :
* - minOccurs : 1
* - maxOccurs : 1
* @var double
*/
public $Quantity;
/**
* The Trades
* Meta informations :
* - minOccurs : 1
* - maxOccurs : 1
* @var int
*/
public $Trades;
/**
* The TWAP
* Meta informations :
* - minOccurs : 1
* - maxOccurs : 1
* @var double
*/
public $TWAP;
/**
* The VWAP
* Meta informations :
* - minOccurs : 1
* - maxOccurs : 1
* @var double
*/
public $VWAP;
/**
* Constructor
* @param string Date
* @param string Time
* @param string UTCDate
* @param string UTCTime
* @param double Last
* @param double High
* @param double Low
* @param double First
* @param double Quantity
* @param int Trades
* @param double TWAP
* @param double VWAP
* @return XiGlobalrealtimeTypeTick
*/
public function __construct($_Date = null,$_Time = null,$_UTCDate = null,$_UTCTime = null,$_Last,$_High,$_Low,$_First,$_Quantity,$_Trades,$_TWAP,$_VWAP)
{
parent::__construct(array('Date'=>$_Date,'Time'=>$_Time,'UTCDate'=>$_UTCDate,'UTCTime'=>$_UTCTime,'Last'=>$_Last,'High'=>$_High,'Low'=>$_Low,'First'=>$_First,'Quantity'=>$_Quantity,'Trades'=>$_Trades,'TWAP'=>$_TWAP,'VWAP'=>$_VWAP));
}
/**
* Set Date
* @param string Date
* @return string
*/
public function setDate($_Date)
{
return ($this->Date = $_Date);
}
/**
* Get Date
* @return string
*/
public function getDate()
{
return $this->Date;
}
/**
* Set Time
* @param string Time
* @return string
*/
public function setTime($_Time)
{
return ($this->Time = $_Time);
}
/**
* Get Time
* @return string
*/
public function getTime()
{
return $this->Time;
}
/**
* Set UTCDate
* @param string UTCDate
* @return string
*/
public function setUTCDate($_UTCDate)
{
return ($this->UTCDate = $_UTCDate);
}
/**
* Get UTCDate
* @return string
*/
public function getUTCDate()
{
return $this->UTCDate;
}
/**
* Set UTCTime
* @param string UTCTime
* @return string
*/
public function setUTCTime($_UTCTime)
{
return ($this->UTCTime = $_UTCTime);
}
/**
* Get UTCTime
* @return string
*/
public function getUTCTime()
{
return $this->UTCTime;
}
/**
* Set Last
* @param double Last
* @return double
*/
public function setLast($_Last)
{
return ($this->Last = $_Last);
}
/**
* Get Last
* @return double
*/
public function getLast()
{
return $this->Last;
}
/**
* Set High
* @param double High
* @return double
*/
public function setHigh($_High)
{
return ($this->High = $_High);
}
/**
* Get High
* @return double
*/
public function getHigh()
{
return $this->High;
}
/**
* Set Low
* @param double Low
* @return double
*/
public function setLow($_Low)
{
return ($this->Low = $_Low);
}
/**
* Get Low
* @return double
*/
public function getLow()
{
return $this->Low;
}
/**
* Set First
* @param double First
* @return double
*/
public function setFirst($_First)
{
return ($this->First = $_First);
}
/**
* Get First
* @return double
*/
public function getFirst()
{
return $this->First;
}
/**
* Set Quantity
* @param double Quantity
* @return double
*/
public function setQuantity($_Quantity)
{
return ($this->Quantity = $_Quantity);
}
/**
* Get Quantity
* @return double
*/
public function getQuantity()
{
return $this->Quantity;
}
/**
* Set Trades
* @param int Trades
* @return int
*/
public function setTrades($_Trades)
{
return ($this->Trades = $_Trades);
}
/**
* Get Trades
* @return int
*/
public function getTrades()
{
return $this->Trades;
}
/**
* Set TWAP
* @param double TWAP
* @return double
*/
public function setTWAP($_TWAP)
{
return ($this->TWAP = $_TWAP);
}
/**
* Get TWAP
* @return double
*/
public function getTWAP()
{
return $this->TWAP;
}
/**
* Set VWAP
* @param double VWAP
* @return double
*/
public function setVWAP($_VWAP)
{
return ($this->VWAP = $_VWAP);
}
/**
* Get VWAP
* @return double
*/
public function getVWAP()
{
return $this->VWAP;
}
/**
* Method returning the class name
* @return string __CLASS__
*/
public function __toString()
{
return __CLASS__;
}
}
?> | true |
4810c7eb5c96c452fc4d398ffa8ea6b475ba66ad | PHP | charlesyu122/ANOW-php-repo | /get_events_with_changes.php | UTF-8 | 2,048 | 2.84375 | 3 | [] | no_license | <?php
// array for JSON response
$response = array();
// include db connect class
include '../ANowPhp/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
//receive POSTS
$today = $_POST['today'];
$userId = $_POST['user_id'];
$check = "false";
// get all attendance starting today
$result = mysql_query("SELECT * FROM attends where user_id = '$userId' AND attend_date >= '$today'");
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all events
$response["events"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$event = array();
// get necessary columns
$eventId = $row["event_id"];
$attendDate = $row["attend_date"];
$attendId = $row["attend_id"];
// query to events table
$result2 = mysql_query("SELECT * from events where event_id = '$eventId'");
if(mysql_num_rows($result2) == 1){
$row2 = mysql_fetch_assoc($result2);
if($attendDate < $row2["date_start"] || $attendDate > $row2["date_end"]){ // There are changes
$event["event_id"] = $row2["event_id"];
// push single event into final response array
array_push($response["events"], $event);
$check = "true";
// delete attendance
mysql_query("DELETE FROM attends WHERE attend_id = '$attendId'");
// query to update user's event_count
mysql_query("UPDATE Users SET event_count = event_count - 1 WHERE user_id ='$userId'");
}
}
}
if($check == "true"){
// success
$response["success"] = 1;
$response["message"] = "There are changes in event dates";
} else{
// no events found
$response["success"] = 0;
$response["message"] = "No changes found";
}
// echoing JSON response
echo json_encode($response);
} else {
// no events found
$response["success"] = 0;
$response["message"] = "No changes found";
// echo no JSON
echo json_encode($response);
}
?>
| true |
5be19a4295d372c7e9eae486abfdb71b1403f666 | PHP | easiestway/console-project | /src/Console/Config.php | UTF-8 | 1,369 | 3.03125 | 3 | [
"MIT"
] | permissive | <?php
/**
* Created by PhpStorm.
* @author d.shokel@gmail.com
*/
namespace Console;
use Symfony\Component\Yaml\Yaml;
class Config
{
const ENV_ALL = 'all';
protected $path;
protected $env;
protected $options = array();
function __construct($path, $env)
{
$this->path = $path;
$this->env = $env;
$this->init();
}
/**
* @return mixed
*/
public function getEnv()
{
return $this->env;
}
protected function init()
{
$config = Yaml::parse($this->path);
if (isset($config[static::ENV_ALL]) && is_array($config[static::ENV_ALL])) {
$this->options = $config[static::ENV_ALL];
}
if ($this->getEnv() && isset($config[$this->getEnv()]) && is_array($config[$this->getEnv()])) {
$this->add($config[$this->getEnv()]);
}
}
protected static function deepMerge(array $a, array $b)
{
$result = $a;
foreach($b as $key => $value)
{
if(isset($result[$key]) && is_array($result[$key]) && is_array($value))
{
$result[$key] = static::deepMerge($result[$key], $value);
} else {
$result[$key] = $value;
}
}
return $result;
}
public function add($options)
{
$this->options = static::deepMerge($this->options, $options);
}
public function get($name)
{
return isset($this->options[$name]) ? $this->options[$name] : null;
}
} | true |
445ebf74fc7ac301206a68d092c8c3f0a4491c4f | PHP | BartoszBartniczak/proophessor-do | /src/Model/Todo/TodoId.php | UTF-8 | 1,360 | 2.875 | 3 | [] | no_license | <?php
/**
* This file is part of prooph/proophessor-do.
* (c) 2014-2016 prooph software GmbH <contact@prooph.de>
* (c) 2015-2016 Sascha-Oliver Prolic <saschaprolic@googlemail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Prooph\ProophessorDo\Model\Todo;
use Prooph\ProophessorDo\Model\ValueObject;
use Rhumsaa\Uuid\Uuid;
/**
* Class TodoId
*
* @package Prooph\ProophessorDo\Model\Todo
* @author Alexander Miertsch <kontakt@codeliner.ws>
*/
final class TodoId implements ValueObject
{
/**
* @var Uuid
*/
private $uuid;
/**
* @return TodoId
*/
public static function generate()
{
return new self(Uuid::uuid4());
}
/**
* @param $todoId
* @return TodoId
*/
public static function fromString($todoId)
{
return new self(Uuid::fromString($todoId));
}
/**
* @param Uuid $uuid
*/
private function __construct(Uuid $uuid)
{
$this->uuid = $uuid;
}
/**
* @return string
*/
public function toString()
{
return $this->uuid->toString();
}
/**
* @param ValueObject $other
* @return bool
*/
public function sameValueAs(ValueObject $other)
{
return get_class($this) === get_class($other) && $this->uuid->equals($other->uuid);
}
}
| true |
52c383e8e3629cd384419201da93a89a786ff7b5 | PHP | saintdron/corporate.loc7.0 | /app/Repositories/PortfolioRepository.php | UTF-8 | 5,920 | 2.625 | 3 | [
"MIT"
] | permissive | <?php
namespace Corp\Repositories;
use Corp\Http\Requests\PortfolioRequest;
use Corp\Portfolio;
use Illuminate\Support\Facades\Gate;
use Image;
class PortfolioRepository extends Repository
{
public function __construct(Portfolio $model)
{
$this->model = $model;
}
public function get($select = '*', $take = false, $pagination = false, $where = false)
{
$portfolios = parent::get($select, $take, $pagination, $where);
if ($portfolios) {
$portfolios->load('filter');
}
return $portfolios;
}
public function one($alias, $select = '*', $needLoad = true)
{
$portfolio = parent::one($alias, $select);
if ($portfolio && $needLoad) {
$portfolio->load('filter');
}
return $portfolio;
}
public function addPortfolio(PortfolioRequest $request)
{
if (Gate::denies('create', $this->model)) {
$key = 'custom.CREATE_' . strtoupper(class_basename($this->model)) . 'S';
return ['error' => 'У вас нет прав на ' . mb_strtolower(trans($key))];
}
$data = $request->except('_token', 'image');
if (empty($data)) {
return ['error' => 'Нет данных'];
}
if (empty($data['alias'])) {
$data['alias'] = $this->transliterate($data['title']);
} else {
$data['alias'] = $this->transliterate($data['alias']);
}
$data['alias'] = chop(substr($data['alias'], 0, config('settings.portfolios_alias_length')), '-');
if ($this->one($data['alias'], ['alias'], false)) {
$request->merge(['alias' => $data['alias']]);
$request->flash();
return ['error' => 'Данный псевдоним уже используется'];
}
$image = $this->getImage($request);
if ($image) {
$data['img'] = $image;
}
//
// try {
// $this->model->save($data);
// return ['status' => 'Работа добавлена'];
// } catch (\Exception $e) {
// return ['error' => 'Не удалось сохранить работу'];
// }
if ($this->model->fill($data)->save()) {
return ['status' => 'Работа добавлена'];
} else {
return ['error' => 'Не удалось сохранить работу'];
}
}
public function updatePortfolio(PortfolioRequest $request, Portfolio $portfolio)
{
if (Gate::denies('update', $portfolio)) {
$key = 'custom.UPDATE_' . strtoupper(class_basename($portfolio)) . 'S';
return ['error' => 'У вас нет прав на ' . mb_strtolower(trans($key))];
}
$data = $request->except('_token', 'image', '_method');
if (empty($data)) {
return ['error' => 'Нет данных'];
}
if (empty($data['alias'])) {
$data['alias'] = $this->transliterate($data['title']);
} else {
$data['alias'] = $this->transliterate($data['alias']);
}
$data['alias'] = chop(substr($data['alias'], 0, config('settings.portfolios_alias_length')), '-');
$foundPortfolio = $this->one($data['alias'], ['id'], false);
if (!empty($foundPortfolio) && $foundPortfolio->id !== $portfolio->id) {
$request->merge(['alias' => $data['alias']]);
$request->flash();
return ['error' => 'Данный псевдоним уже используется'];
}
$image = $this->getImage($request);
if ($image) {
$data['img'] = $image;
}
if ($portfolio->update($data)) {
return ['status' => 'Работа обновлена'];
} else {
return ['error' => 'Не удалось обновить работу'];
}
}
public function deletePortfolio(Portfolio $portfolio)
{
if (Gate::denies('delete', $portfolio)) {
$key = 'custom.DELETE_' . strtoupper(class_basename($portfolio)) . 'S';
return ['error' => 'У вас нет прав на ' . mb_strtolower(trans($key))];
}
if ($portfolio->delete()) {
return ['status' => 'Работа удалена'];
} else {
return ['error' => 'Не удалось удалить работу'];
}
}
public function getImage(PortfolioRequest $request)
{
if ($request->hasFile('image')) {
$image = $request->file('image');
if ($image->isValid()) {
$str = str_random(8);
$obj = new \stdClass();
$obj->mini = $str . '_mini.jpg';
$obj->max = $str . '_max.jpg';
$obj->path = $str . '.jpg';
Image::make($image)->resize(config('settings.image')['width'], config('settings.image')['height'], function ($constraint) {
$constraint->upsize();
$constraint->aspectRatio();
})->save(public_path() . '/' . config('settings.theme') . '/images/' . config('settings.portfolios_path') . '/' . $obj->path);
Image::make($image)->fit(config('settings.portfolios_img')['max']['width'], config('settings.portfolios_img')['max']['height'])
->save(public_path() . '/' . config('settings.theme') . '/images/' . config('settings.portfolios_path') . '/' . $obj->max);
Image::make($image)->fit(config('settings.portfolios_img')['mini']['width'], config('settings.portfolios_img')['mini']['height'])
->save(public_path() . '/' . config('settings.theme') . '/images/' . config('settings.portfolios_path') . '/' . $obj->mini);
return json_encode($obj);
}
}
return null;
}
} | true |
3d5fed16a83399cd2544a68ecc1238502f7243e0 | PHP | NIZZOLA/CursoWeb3moduloDS | /aula4/listarClientes.php | UTF-8 | 1,083 | 2.546875 | 3 | [] | no_license | <!doctype html>
<html>
<head>
<!-- Place your kit's code here -->
<script src="https://kit.fontawesome.com/03a46de5f2.js" crossorigin="anonymous"></script>
</head>
<body>
<a href="formClientes.php"><i class="far fa-plus-square"></i></a>
<table border="1">
<thead>
<tr>
<th>Código</th>
<th>Nome</th>
<th>Cidade</th>
<th>Estado</th>
<th>Ações</th>
</tr>
</thead>
<?php
include "config.php";
include "funcoes.php";
include "class.Clientes.php";
$cliente = new Cliente();
$lista = $cliente->Listar();
foreach($lista as $obj ) {
echo "<tr><td>".$obj->getCodigo()."</td><td>". $obj->getNome()."</td><td>".$obj->getCidade()."</td><td>".$obj->getEstado()."</td>
<td><a href='editarClientes.php?codigo=".$obj->getCodigo()."' alt='Editar'><i class='far fa-edit'></i>
</a><a href='excluirCliente.php?codigo=".$obj->getCodigo()."' alt='Deletar'><i class='far fa-trash-alt'></i></a> </tr>";
}
?>
</table>
</body>
</html> | true |
f3448a4406c9a571d4afdbec813983ac99371190 | PHP | ccmorenosa/artemisa | /serviciosacademicos/Grados/entidades/DetalleRegistroGradoFolio.php | UTF-8 | 5,482 | 3.375 | 3 | [] | no_license | <?php
/**
* @author Carlos Alberto Suarez Garrido <suarezcarlos@unbosque.edu.co>
* @copyright Dirección de Tecnología - Universidad el Bosque
* @package entidades
*/
class DetalleRegistroGradoFolio{
/**
* @type int
* @access private
*/
private $idDetalleRegistroGradoFolio;
/**
* @type Folio
* @access private
*/
private $folio;
/**
* @type RegistroGrado
* @access private
*/
private $registroGrado;
/**
* @type int
* @access private
*/
private $estadoDetalleRegistroGradoFolio;
/**
* @type int
* @access private
*/
private $codigoTipoDetalleRegistroGradoFolio;
/**
* @type Singleton
* @access private
*/
private $persistencia;
/**
* Constructor
* @param Singleton $persistencia
*/
public function DetalleRegistroGradoFolio( $persistencia ){
$this->persistencia = $persistencia;
}
/**
* Modifica el id del detalle de registro de grado de folio
* @param int $idDetalleRegistroGradoFolio
* @access public
* @return void
*/
public function setIdDetalleRegistroGradoFolio( $idDetalleRegistroGradoFolio ){
$this->idDetalleRegistroGradoFolio = $idDetalleRegistroGradoFolio;
}
/**
* Retorna el id del detalle de registro de grado de folio
* @access public
* @return int
*/
public function getIdDetalleRegistroGradoFolio( ){
return $this->idDetalleRegistroGradoFolio;
}
/**
* Modifica el folio del detalle registro de grado de folio
* @param Folio $folio
* @access public
* @return void
*/
public function setFolio( $folio ){
$this->folio = $folio;
}
/**
* Retorna el folio del detalle registro de grado de folio
* @access public
* @return Folio
*/
public function getFolio( ){
return $this->folio;
}
/**
* Modifica el Registro de Grado del Folio
* @param RegistroGrado $registroGrado
* @access public
* @return void
*/
public function setRegistroGrado( $registroGrado ){
$this->registroGrado = $registroGrado;
}
/**
* Retorna el Registro de Grado del Folio
* @access public
* @return RegistroGrado
*/
public function getRegistroGrado( ){
return $this->registroGrado;
}
/**
* Modifica el estado del detalle registro de grado folio
* @param int $estadoDetalleRegistroGradoFolio
* @access public
* @return void
*/
public function setEstadoDetalleRegistroGradoFolio( $estadoDetalleRegistroGradoFolio ){
$this->estadoDetalleRegistroGradoFolio = $estadoDetalleRegistroGradoFolio;
}
/**
* Retorna el estado del detalle registro de grado folio
* @access public
* @return int
*/
public function getEstadoDetalleRegistroGradoFolio( ){
return $this->estadoDetalleRegistroGradoFolio;
}
/**
* Modifica el codigo tipo detalle registro grado folio
* @param int $codigoTipoDetalleRegistroGradoFolio
* @access public
* @return void
*/
public function setCodigoTipoDetalleRegistroGradoFolio( $codigoTipoDetalleRegistroGradoFolio ){
$this->codigoTipoDetalleRegistroGradoFolio = $codigoTipoDetalleRegistroGradoFolio;
}
/**
* Retorna el codigo tipo detalle registro grado folio
* @access public
* @return int
*/
public function getCodigoTipoDetalleRegistroGradoFolio( ){
return $this->codigoTipoDetalleRegistroGradoFolio;
}
/**
* Buscar Detalle RegistroGraduadoFolio
* @param int $txtCodigoIncentivo
* @access public
* @return String
*/
public function buscarDetalleRegistroGradoFolio( $txtIdRegistroGrado ){
$sql = "SELECT iddetalleregistrograduadofolio, idregistrograduadofolio
FROM detalleregistrograduadofolio
WHERE idregistrograduado = ?
AND codigoestado like '1%'";
$this->persistencia->crearSentenciaSQL( $sql );
$this->persistencia->setParametro( 0 , $txtIdRegistroGrado , false );
$this->persistencia->ejecutarConsulta( );
if( $this->persistencia->getNext( ) ){
$this->setIdDetalleRegistroGradoFolio( $this->persistencia->getParametro( "iddetalleregistrograduadofolio" ) );
$folio = new Folio( $this->persistencia );
$folio->setIdFolio( $this->persistencia->getParametro( "idregistrograduadofolio" ) );
$this->setFolio( $folio );
}
//echo $this->persistencia->getSQLListo( );
$this->persistencia->freeResult( );
}
/**
* Insertar PrevisualizacionFolioTemporal
* @param int txtNumeroFolio, $txtIdRegistroGrado
* @access public
* @return boolean
*/
public function insertarDetalleRegistroGradoFolio( $txtNumeroFolio , $txtIdRegistroGrado ){
$sql = "INSERT INTO detalleregistrograduadofolio (
idregistrograduadofolio,
idregistrograduado,
codigoestado,
codigotipodetalleregistrograduadofolio
)
VALUES
(?, ?, '100','100');
";
$this->persistencia->crearSentenciaSQL( $sql );
$this->persistencia->setParametro( 0 , $txtNumeroFolio, false );
$this->persistencia->setParametro( 1 , $txtIdRegistroGrado, false );
//echo $this->persistencia->getSQLListo( ).'<br>';
$estado = $this->persistencia->ejecutarUpdate( );
if( $estado )
$this->persistencia->confirmarTransaccion( );
else
$this->persistencia->cancelarTransaccion( );
/*Modified Diego Rivera <riveradiego@unbosque.edu.co>
*Se elimina funcion $this->persistencia->freeResult( ); esta provoca el error en el singleton
*Since Octuber 18 , 2017
*/
return $estado;
}
}
?> | true |
e7ed83debffa86df17b3206323aeaa958a7addf5 | PHP | ajaykandpal/Auto-Orienting-Images-Uploaded-online | /ajayk.php | UTF-8 | 2,437 | 2.9375 | 3 | [] | no_license | <html>
<head>
<title>PHP File Upload example</title>
</head>
<body>
<form action="max.php" enctype="multipart/form-data" method="post">
Select image :
<input type="file" name="file"><br/>
<input type="submit" value="Upload" name="Submit1"> <br/>
</form>
<?php
function correctImageOrientation($filename) {
if (function_exists('exif_read_data')) {
$exif = exif_read_data($filename);
if($exif && isset($exif['Orientation'])) {
$orientation = $exif['Orientation'];
if($orientation != 1){
$img = imagecreatefromjpeg($filename);
$deg = 0;
switch ($orientation) {
case 3:
$deg = 180;
break;
case 6:
$deg = 270;
break;
case 8:
$deg = 90;
break;
}
if ($deg) {
$img = imagerotate($img, $deg, 0);
}
// then rewrite the rotated image back to the disk as $filename
// imagejpeg($img, $filename, 95);
} // if there is some rotation necessary
} // if have the exif orientation info
} // if function exists
}
/*function imagecreatefromjpegexif($filename)
{
$img = imagecreatefromjpeg($filename);
$exif = exif_read_data($filename);
if ($img && $exif && isset($exif['Orientation']))
{
$ort = $exif['Orientation'];
if ($ort == 6 || $ort == 5)
$img = imagerotate($img, 270, null);
if ($ort == 3 || $ort == 4)
$img = imagerotate($img, 180, null);
if ($ort == 8 || $ort == 7)
$img = imagerotate($img, 90, null);
if ($ort == 5 || $ort == 4 || $ort == 7)
imageflip($img, IMG_FLIP_HORIZONTAL);
}
imagejpeg($img)
return $img;
}
*/
define ('SITE_ROOT', realpath(dirname(__FILE__)));
if(isset($_POST['Submit1']))
{
$filepath = SITE_ROOT."\images\\" . $_FILES["file"]["name"];
$path = $_FILES["file"]["name"];
if(move_uploaded_file($_FILES["file"]["tmp_name"], $filepath))
{
//echo "<img src='images/1.jpg' height=200 width=300 />";
//$new=imagecreatefromjpegexif($filepath);
correctImageOrientation($filepath);
//imagejpeg($new);
//echo '<img src="images/'. $path.'" height=200 width=300/>';
}
else
{
echo "Error !!";
}
}
?>
</body>
</html> | true |
598b45c005bf897cc4e4bd65d0678dfa0180b560 | PHP | CeusMedia/Cache | /src/CachePoolFactory.php | UTF-8 | 647 | 2.578125 | 3 | [] | no_license | <?php
declare(strict_types=1);
/**
* ....
* @category Library
* @package CeusMedia_Cache
* @author Christian Würker <christian.wuerker@ceusmedia.de>
*/
namespace CeusMedia\Cache;
/**
* ....
* @category Library
* @package CeusMedia_Cache
* @author Christian Würker <christian.wuerker@ceusmedia.de>
*/
class CachePoolFactory
{
/**
* ...
*
* @access public
* @static
* @param string $adapterType ...
* @param mixed $adapterResource ...
* @return CachePool
*/
public static function createPool( string $adapterType, $adapterResource ): CachePool
{
$adapter = SimpleCacheFactory::createStorage( $adapterType, $adapterResource );
return new CachePool( $adapter );
}
}
| true |
7dbf2639f8a3a1fad163a0f1787112862d84a5f1 | PHP | Arowne/Homemade_Framework | /Core/TemplateEngine.php | UTF-8 | 1,067 | 3.078125 | 3 | [] | no_license | <?php
class TemplateEngine
{
public function run($path)
{
$content = file_get_contents($path);
$content = preg_replace('/{{(.*)}}/', '<?= htmlentities($1);?>', $content);
$content = preg_replace('/{%(.*)%}/', '<?php htmlentities($1);?>', $content);
$content = preg_replace('/@if\((.*)\)/', '<?php if($1):?>', $content);
$content = preg_replace('/@elseif\((.*)\)/', '<?php elseif($1):?>', $content);
$content = preg_replace('/@else/', '<?php else:?>', $content);
$content = preg_replace('/@endif/', '<?php endif;?>', $content);
$content = preg_replace('/@foreach\((.*)\)/', '<?php foreach($1):?>', $content);
$content = preg_replace('/@endforeach/', '<?php endforeach;?>', $content);
$content = preg_replace('/@isset\((.*)\)/', '<?php if(isset($1)):?>', $content);
$content = preg_replace('/@endisset/', '<?php endif;?>', $content);
$content = preg_replace('/@empty\((.*)\)/', '<?php if(empty($1)):?>', $content);
$content = preg_replace('/@endempty/', '<?php endif;?>', $content);
return $content;
}
}
| true |
b90b687f7006426b1fddfa6a07391f9057f0b097 | PHP | Faryzal2020/e-jurnal | /ajax/getSelectJabatan.php | UTF-8 | 1,248 | 2.578125 | 3 | [] | no_license | <?php
session_start();
include("../config.php");
$atasan = $_POST['atasan'];
$i = $_POST['i'];
$value = $_POST['value'];
if($atasan == "n"){
$sql = "SELECT jabatan.id_jabatan, jabatan.nama_jabatan, jabatan.eselon, atasan.nama_jabatan, atasan.id_jabatan, atasan.eselon FROM jabatan LEFT JOIN jabatan as atasan ON atasan.id_jabatan = jabatan.atasan WHERE jabatan.eselon = 1";
} else {
$sql = "SELECT jabatan.id_jabatan, jabatan.nama_jabatan, jabatan.eselon, atasan.nama_jabatan, atasan.id_jabatan, atasan.eselon FROM jabatan LEFT JOIN jabatan as atasan ON atasan.id_jabatan = jabatan.atasan WHERE atasan.id_jabatan = '$atasan'";
}
$result = mysqli_query($db,$sql);
$x = $i+1;
$id = "pilih-" . $x;
$j = array("Deputi", "Biro", "Bagian", "SubBagian", "Staf");
$label = $j[$i];
if(mysqli_num_rows($result) > 0){
echo "<option id=\"$id\" value=\"0\">Pilih $label</option>";
while($data = mysqli_fetch_array($result)){
if($atasan == 'n'){
echo "<option value=\"$data[0]\">$data[1]</option>";
} else if($i+1 == $value){
echo "<option value=\"$data[0]\">$data[1]</option>";
} else {
$cont = explode(' ', $data[1], 2);
echo "<option value=\"$data[0]\">$cont[1]</option>";
}
}
} else {
echo "";
}
?>
| true |
ec879054c65251bd9ff1ed22c67143eb8502f2ab | PHP | kaelynx/web_basics | /art-store/lib/PaintingSubjectsCollection.class.php | UTF-8 | 533 | 3.25 | 3 | [] | no_license | <?php
class PaintingSubjectsCollection {
private $pSubjects = null;
private $ps = null;
public function __construct(){
$ps = new PaintingSubjectsDB();
$psEntries = $ps->getAll();
$this->pSubjects = array();
foreach($psEntries as $psc){
//use id as key
$this->pSubjects[$psc['PaintingSubjectID']] = new PaintingSubjects($psc);
}
}
public function getPaintingSubjects(){
return $this->pSubjects;
}
public function findPaintingSubjectsByID($id){
return $this->pSubjects[$id];
}
}
?> | true |
cdba4038d61580bddaa6957b3c429aef04443c90 | PHP | Luckyoula9034/courier | /getprice.php | UTF-8 | 678 | 2.515625 | 3 | [] | no_license | <?php
$q=$_GET["q"];
require_once('database.php');
mysql_select_db("tbl_payments", $con);
$sql="SELECT DISTINCT(weight_price)
FROM user WHERE id = '".$q."'";
$result = mysql_query($sql);
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td>" . $row['Hometown'] . "</td>";
echo "<td>" . $row['Job'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?> | true |
d41f0cbada03164efb471c06e22c62847ad84b03 | PHP | lealuo520/mellivora-logger-factory | /src/Processor/CostTimeProcessor.php | UTF-8 | 906 | 2.8125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | <?php
namespace Mellivora\Logger\Processor;
use Monolog\Logger;
/**
* 用于获取时间成本消耗
*/
class CostTimeProcessor
{
protected static $points = [];
protected $level;
public function __construct($level = Logger::DEBUG)
{
$this->level = Logger::toMonologLevel($level);
}
public function __invoke(array $record)
{
if ($record['level'] < $this->level) {
return $record;
}
$name = $record['channel'];
if (! isset(self::$points[$name])) {
self::$points[$name] = microtime(true);
$cost = 0.0;
} else {
$current = microtime(true);
$cost = round($current - self::$points[$name], 6);
self::$points[$name] = $current;
}
$record['extra']['cost'] = $cost;
return $record;
}
}
| true |
a6b95a6a2db47d24379fa44e35fca0a323287c95 | PHP | sadiayousafzai036/Wood | /top5reviews.php | UTF-8 | 1,925 | 2.78125 | 3 | [] | no_license | <html>
<head>
<title>Top 5 rated products based on best reviews</title>
</head>
<body>
<?php
ob_start();
$servername = "us-cdbr-iron-east-04.cleardb.net";
$username = "bbfde2f23076ea";
$password = "13418461";
$database = "heroku_9f74518f3cbe85c";
if (!($conn = mysqli_connect($servername, $username, $password,$database))){
echo "Could not connect to database";
die("ERROR: Could not connect to database");
}
//sentiment analysis initializer
include ('sentiment_analyser.php');
$sa = new SentimentAnalysis();
$sa->initialize();
$scores = array();
$sql = "select pdt_name,count(*) as count from products group by pdt_name";
$result = mysqli_query($conn,$sql);
if (!$result) {
echo "Error message: ".mysqli_error($conn);
}
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$eachscore = 0;
$name = $row["pdt_name"];
$count = $row["count"];
$query = "select review from products where pdt_name='$name'";
$reviews = mysqli_query($conn,$query);
if (!$reviews) {
echo "Error message: ".mysqli_error($conn);
}
//fetch review of each product
if ($reviews->num_rows > 0) {
while($eachreview = $reviews->fetch_assoc()) {
$product = $eachreview["review"];
$sa->analyse($product);
$eachscore += $sa->return_sentiment_rating();
}
$scores[$name] = round(($eachscore/$count),1);
}
}
} else {
echo "No reviews has been provided for any products"."<br>";
}
arsort($scores);
foreach (array_slice($scores,0,5) as $name => $value) {
echo $name." - ".$value."<br>";
}
mysqli_close($conn);
?>
<h3> please click <a href = "index.html"> here</a> to return to products page of Carved Creations</h3>
<h3> please click <a href="http://ganesh041152080.ipage.com/marketplace/homepage.php">here</a> to return to Marketplace home page</h3>
</html>
| true |
a0717d566211024067bbefa0bc359f33613286dd | PHP | vikas-srivastava/extensionmanager | /code/control/JsonHandler.php | UTF-8 | 14,132 | 2.765625 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
/**
* All task related to json file.
*
* Usage:
* <code>
* $json = new JsonReader();
* $json->cloneJson($url);
* $json->saveJson($url,$latestReleasePackage);
* </code>
*
* @package extensionmanager
*/
use Composer\Config;
use Composer\IO\NullIO;
use Composer\Factory;
use Composer\Repository\VcsRepository;
use Composer\Repository\RepositoryManager;
use Composer\package\Dumper\ArrayDumper;
use Composer\Json\JsonFile;
class JsonHandler extends Controller
{
public $url;
public $latestReleasePackage;
public $packages;
public $availableVersions;
public $repo;
public $errorInConstructer;
public $packageName;
public function __construct($url)
{
$this->url = $url;
$config = Factory::createConfig();
$this->repo = new VcsRepository(array('url' => $url, ''), new NullIO(), $config);
}
/**
* Convert a module url into json content
*
* @param string $url
* @return array $data
*/
public function cloneJson()
{
$jsonData = array();
try {
$this->packages = $this->repo->getPackages();
foreach ($this->packages as $package) {
$this->packageName = $package->getPrettyName();
if (!isset($this->packageName)) {
throw new InvalidArgumentException("The package name was not found in the composer.json at '"
.$this->url."' in '". $package->getPrettyVersion()."' ");
}
if (!preg_match('{^[a-z0-9]([_.-]?[a-z0-9]+)*/[a-z0-9]([_.-]?[a-z0-9]+)*$}i', $this->packageName)) {
throw new InvalidArgumentException(
"The package name '{$this->packageName}' is invalid, it should have a vendor name,
a forward slash, and a package name. The vendor and package name can be words separated by -, . or _.
The complete name should match '[a-z0-9]([_.-]?[a-z0-9]+)*/[a-z0-9]([_.-]?[a-z0-9]+)*' at "
.$this->url."' in '". $package->getPrettyVersion()."' ");
}
if (preg_match('{[A-Z]}', $this->packageName)) {
$suggestName = preg_replace('{(?:([a-z])([A-Z])|([A-Z])([A-Z][a-z]))}', '\\1\\3-\\2\\4', $this->packageName);
$suggestName = strtolower($suggestName);
throw new InvalidArgumentException(
"The package name '{$this->packageName}' is invalid,
it should not contain uppercase characters. We suggest using '{$suggestName}' instead. at '"
.$this->url."' in '". $package->getPrettyVersion()."' ");
}
}
$this->latestReleasePackage = $this->repo->findPackage($this->packageName, '9999999-dev');
} catch (Exception $e) {
$jsonData['ErrorMsg'] = $e->getMessage();
return $jsonData;
}
$jsonData['AllRelease'] = $this->packages;
$jsonData['LatestRelease'] = $this->latestReleasePackage;
return $jsonData;
}
/**
* Save json content in database
*
* @return boolean
*/
public function saveJson()
{
$ExtensionData = new ExtensionData();
$ExtensionData->SubmittedByID = Member::currentUserID();
$result = $this->dataFields($ExtensionData);
return $result ;
}
/**
* update json content in database
*
* @return boolean
*/
public function updateJson()
{
$ExtensionData = ExtensionData::get()->filter(array("Title" => $this->latestReleasePackage->getPrettyName()))->First();
if ($ExtensionData) {
$result = $this->dataFields($ExtensionData);
return $result ;
} else {
return ;
}
}
/**
* Save each property of json content
* in corresponidng field of database
*
* @param object $ExtensionData
* @return boolean
*/
public function dataFields($ExtensionData)
{
$saveDataFields = array();
try {
$ExtensionData->Url = $this->url;
if ($this->latestReleasePackage->getPrettyName()) {
list($vendorName, $extensionName) = explode("/", $this->latestReleasePackage->getPrettyName());
$ExtensionData->Title = $this->latestReleasePackage->getPrettyName();
$ExtensionData->VendorName = $vendorName;
$ExtensionData->Name = $extensionName;
} else {
throw new InvalidArgumentException("We could not find Name field in composer.json at'"
.$this->url."' ");
}
if ($this->latestReleasePackage->getDescription()) {
$ExtensionData->Description = $this->latestReleasePackage->getDescription();
} else {
throw new InvalidArgumentException("We could not find Description field in composer.json at'"
.$this->url."' ");
}
if ($this->latestReleasePackage->getPrettyVersion()) {
$ExtensionData->Version = $this->latestReleasePackage->getPrettyVersion();
}
if ($this->latestReleasePackage->getType()) {
$type = $this->latestReleasePackage->getType() ;
if (preg_match("/\bmodule\b/i", $type)) {
$ExtensionData->Type = 'Module';
} elseif (preg_match("/\btheme\b/i", $type)) {
$ExtensionData->Type = 'Theme';
} elseif (preg_match("/\bwidget\b/i", $type)) {
$ExtensionData->Type = 'Widget';
} else {
throw new InvalidArgumentException("We could not find 'Type' field in composer.json at'"
.$this->url."' ");
}
}
if ($this->latestReleasePackage->getHomepage()) {
$ExtensionData->Homepage = $this->latestReleasePackage->getHomepage();
}
if ($this->latestReleasePackage->getReleaseDate()) {
$ExtensionData->ReleaseTime = $this->latestReleasePackage->getReleaseDate()->format('Y-m-d H:i:s');
}
if ($this->latestReleasePackage->getLicense()) {
$licence = $this->latestReleasePackage->getLicense();
if (array_key_exists('type', $licence)) {
$ExtensionData->LicenceType = $licence['type'];
}
if (array_key_exists('description', $licence)) {
$ExtensionData->LicenceDescription = $licence['description'];
}
}
if ($this->latestReleasePackage->getSupport()) {
$supportData = $this->latestReleasePackage->getSupport() ;
if (array_key_exists('email', $supportData)) {
$ExtensionData->SupportEmail = $supportData['email'];
}
if (array_key_exists('issues', $supportData)) {
$ExtensionData->SupportIssues = $supportData['issues'];
}
if (array_key_exists('forum', $supportData)) {
$ExtensionData->SupportForum = $supportData['forum'];
}
if (array_key_exists('wiki', $supportData)) {
$ExtensionData->SupportWiki = $supportData['wiki'];
}
if (array_key_exists('irc', $supportData)) {
$ExtensionData->SupportIrc = $supportData['irc'];
}
if (array_key_exists('source', $supportData)) {
$ExtensionData->SupportSource = $supportData['source'];
}
}
if ($this->latestReleasePackage->getTargetDir()) {
$ExtensionData->TargetDir = $this->latestReleasePackage->getTargetDir();
}
if ($this->latestReleasePackage->getRequires()) {
$requires = $this->latestReleasePackage->getRequires();
$allRequirePackage = array();
foreach ($requires as $requirePackage) {
$allRequirePackage[$requirePackage->getTarget()] = $requirePackage->getPrettyConstraint();
if ($requirePackage->getTarget() == 'silverstripe/framework') {
$ExtensionData->CompatibleSilverStripeVersion = $requirePackage->getPrettyConstraint();
}
}
$ExtensionData->Require = serialize($allRequirePackage);
} else {
throw new InvalidArgumentException("We could not find 'require' field in composer.json at'"
.$this->url."' ");
}
if ($this->latestReleasePackage->getDevRequires()) {
$ExtensionData->RequireDev = serialize($this->latestReleasePackage->getDevRequires());
}
if ($this->latestReleasePackage->getConflicts()) {
$ExtensionData->Conflict = serialize($this->latestReleasePackage->getConflicts());
}
if ($this->latestReleasePackage->getReplaces()) {
$ExtensionData->Replace = serialize($this->latestReleasePackage->getReplaces());
}
if ($this->latestReleasePackage->getProvides()) {
$ExtensionData->Provide = serialize($this->latestReleasePackage->getProvides());
}
if ($this->latestReleasePackage->getSuggests()) {
$ExtensionData->Suggest = serialize($this->latestReleasePackage->getSuggests());
}
if ($this->latestReleasePackage->getExtra()) {
$ExtensionData->Extra = serialize($this->latestReleasePackage->getExtra());
$extra = $this->latestReleasePackage->getExtra();
if (array_key_exists('snapshot', $extra)) {
$ExtensionData->ThumbnailID = ExtensionSnapshot::save_snapshot($extra['snapshot'], $this->latestReleasePackage->getPrettyName());
}
}
if ($this->latestReleasePackage->getRepositories()) {
$ExtensionData->Repositories = serialize($this->latestReleasePackage->getRepositories());
}
if ($this->latestReleasePackage->getIncludePaths()) {
$ExtensionData->IncludePath = serialize($this->latestReleasePackage->getIncludePaths());
}
if ($this->latestReleasePackage->getAuthors()) {
ExtensionAuthorController::store_authors_info($this->latestReleasePackage->getAuthors(), $ExtensionData->ID);
} else {
throw new InvalidArgumentException("We could not find Author Info field in composer.json at'"
.$this->url."' ");
}
if ($this->latestReleasePackage->getKeywords()) {
ExtensionKeywords::save_keywords($this->latestReleasePackage->getKeywords(), $ExtensionData->ID);
} else {
throw new InvalidArgumentException("We could not find Keywords field in composer.json at'"
.$this->url."' ");
}
} catch (Exception $e) {
$saveDataFields['ErrorMsg'] = $e->getMessage();
return $saveDataFields;
}
$ExtensionData->write();
$saveDataFields['ExtensionID'] = $ExtensionData->ID;
return $saveDataFields;
}
/**
* Save Version related data of Extension
*
* @param int $id
* @return boolean
*/
public function saveVersionData($id)
{
foreach ($this->packages as $package) {
$version = new ExtensionVersion();
$version->ExtensionDataID = $id;
$result = $this->versionDataField($version, $package);
}
return $result ;
}
/**
* Delete old version of extension
*
* @param int $id
* @return boolean
*/
public function deleteVersionData($id)
{
return ExtensionVersion::get()->filter('ExtensionDataID', $id)->removeAll();
}
/**
* Save each version related property of json content
*
* @param object $version, object $Data
* @return boolean
*/
public function versionDataField($version, $data)
{
if ($data->getSourceType()) {
$version->SourceType = $data->getSourceType();
}
if ($data->getSourceUrl()) {
$version->SourceUrl = $data->getSourceUrl();
}
if ($data->getSourceReference()) {
$version->SourceReference = $data->getSourceReference();
}
if ($data->getDistType()) {
$version->DistType = $data->getDistType();
}
if ($data->getDistUrl()) {
$version->DistUrl = $data->getDistUrl();
}
if ($data->getDistReference()) {
$version->DistReference = $data->getDistReference();
}
if ($data->getDistSha1Checksum()) {
$version->DistSha1Checksum = $data->getDistSha1Checksum();
}
if ($data->getVersion()) {
$version->Version = $data->getVersion();
}
if ($data->getPrettyVersion()) {
$version->PrettyVersion = $data->getPrettyVersion();
}
if ($data->getReleaseDate()) {
$version->ReleaseDate = $data->getReleaseDate()->format('Y-m-d H:i:s');
}
if ($data->getRequires()) {
$requires = $this->latestReleasePackage->getRequires();
foreach ($requires as $requirePackage) {
if ($requirePackage->getTarget() == 'silverstripe/framework') {
$version->CompatibleSilverStripeVersion = $requirePackage->getPrettyConstraint();
}
}
} else {
throw new InvalidArgumentException("We could not find 'require' field in composer.json at'"
.$this->url."' ");
}
$version->write();
return true;
}
}
| true |
7a811bbced750cb98ed5bf2f5e658b9df7687086 | PHP | ARMA-EGY/clinic | /app/Http/Requests/Patients/AddRequest.php | UTF-8 | 1,275 | 2.640625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Requests\Patients;
use Illuminate\Foundation\Http\FormRequest;
class AddRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'name' => 'required',
'phone' => 'required',
'identifiation' => 'required',
'dateofbirth' => 'required',
'age' => 'required',
'gender' => 'required',
'nationality' => 'required',
];
}
public function messages()
{
return [
'name.required' => 'Patient Name is required.',
'name.unique' => 'This Patient Name is Already Exist.',
'phone.unique' => 'This Phone Number is Already Exist.',
'phone.required' => 'Phone is required.',
'identifiation.required' => 'Identifiation is required.',
'dateofbirth.required' => 'Date of Birth is required.',
'age.required' => 'Age is required.',
'gender.required' => 'Gender is required.',
'nationality.required' => 'Nationality is required.',
];
}
public function attributes()
{
return [
'name' => 'Patient Name',
];
}
}
| true |
95a748f2aab0d1537364bb3e5c1f25c48255034a | PHP | yannis-staali/lpb | /Model/ModelAdminUser.php | UTF-8 | 1,286 | 2.84375 | 3 | [] | no_license | <?php
require_once 'Model/ModelAdmin.php';
class adminUser extends admin
{
protected $pdo;
//SELECT ALL USER
public function selectalluser(){
$sql = "SELECT id, login, email, password, id_droits FROM utilisateurs";
$stmt = $this->pdo->prepare($sql);
$stmt->execute();
while($user = $stmt->fetchAll(PDO::FETCH_ASSOC)){
return $user;
}
}
//SELECT USER VIA ID
public function selectViaId($id){
$sql = "SELECT id, login, email, password, id_droits FROM utilisateurs WHERE id = :id";
$stmt = $this->pdo->prepare($sql);
$stmt->execute([
'id' => $id
]);
$userid = $stmt->fetch(PDO::FETCH_ASSOC);
if(!$userid)
{
return false;
}
else
{
return $userid;
}
}
//DELETE USER VIA ID
public function deleteUser($id){
$sql = "DELETE FROM utilisateurs WHERE id = :id";
$stmt= $this->pdo->prepare($sql);
$stmt->execute([
'id' => $id
]);
}
//UPDATE USER VIA ID
public function updateUser($login, $email, $password, $id_droits, $id){
$sql = "UPDATE utilisateurs SET login=:login, email=:email, password=:password, id_droits=:id_droits WHERE id=:id";
$stmt= $this->pdo->prepare($sql);
$stmt->execute(['login' => $login, 'password' => $password, 'email' => $email, 'id_droits' => $id_droits, 'id' => $id]);
}
} | true |
5eb52d3737c281e0affee368aee8e9c17fb50175 | PHP | rciam/perun-simplesamlphp-module | /lib/Auth/Process/ProxyFilter.php | UTF-8 | 8,704 | 2.5625 | 3 | [
"BSD-2-Clause"
] | permissive | <?php
declare(strict_types=1);
namespace SimpleSAML\Module\perun\Auth\Process;
use SimpleSAML\Configuration;
use SimpleSAML\Error\Exception;
use SimpleSAML\Logger;
/**
* Class sspmod_perun_Auth_Process_ProxyFilter.
*
* This filter allows to disable/enable nested filters for particular SP or for users with one of (black/white)listed
* attribute values. Based on the mode of operation, the nested filters ARE (whitelist) or ARE NOT (blacklist) run when
* any of the attribute values matches. SPs are defined by theirs entityID in property 'filterSPs'. User attributes are
* defined as a map 'attrName'=>['value1','value2'] in property 'filterAttributes'. Nested filters are defined in the
* authproc property in the same format as in config. If only one filter is needed, it can be specified in the config
* property.
*
* example usage:
*
* 10 => [ 'class' => 'perun:ProxyFilter', 'filterSPs' => ['disableSpEntityId01', 'disableSpEntityId02'],
* 'filterAttributes' => [ 'eduPersonPrincipalName' => ['test@example.com'], 'eduPersonAffiliation' =>
* ['affiliate','member'], ], 'config' => [ 'class' => 'perun:NestedFilter', // ... ], ], 20 => [ 'class' =>
* 'perun:ProxyFilter', 'mode' => 'whitelist', 'filterSPs' => ['enableSpEntityId01', 'enableSpEntityId02'], 'authproc'
* => [ [ 'class' => 'perun:NestedFilter1', // ... ], [ 'class' => 'perun:NestedFilter2', // ... ], ], ],
*/
class ProxyFilter extends \SimpleSAML\Auth\ProcessingFilter
{
public const MODE_BLACKLIST = 'blacklist';
public const MODE_WHITELIST = 'whitelist';
public const MODES = [self::MODE_BLACKLIST, self::MODE_WHITELIST];
private $authproc;
private $nestedClasses;
private $filterSPs;
private $filterAttributes;
private $mode;
private $reserved;
public function __construct($config, $reserved)
{
parent::__construct($config, $reserved);
$conf = Configuration::loadFromArray($config);
$this->filterSPs = $conf->getArray('filterSPs', []);
$this->filterAttributes = $conf->getArray('filterAttributes', []);
$this->mode = $conf->getValueValidate('mode', self::MODES, self::MODE_BLACKLIST);
$this->authproc = $conf->getArray('authproc', []);
$this->authproc[] = $conf->getArray('config', []);
$this->authproc = array_filter($this->authproc);
$this->nestedClasses = implode(',', array_map(
function ($config) {
return is_string($config) ? $config : $config['class'];
},
$this->authproc
));
$this->reserved = (array) $reserved;
}
public function process(&$request)
{
assert(is_array($request));
$default = $this->mode === self::MODE_BLACKLIST;
$shouldRun = $this->shouldRunForSP($request['Destination']['entityid'], $default);
if ($shouldRun === $default) {
$shouldRun = $this->shouldRunForAttribute($request['Attributes'], $default);
}
if ($shouldRun) {
$this->processState($request);
} elseif ($this->mode === self::MODE_WHITELIST) {
Logger::info(
sprintf(
'perun.ProxyFilter: Not running filter %s for SP %s',
$this->nestedClasses,
$request['Destination']['entityid']
)
);
}
}
private function shouldRunForSP($currentSp, $default)
{
foreach ($this->filterSPs as $sp) {
if ($sp === $currentSp) {
$shouldRun = !$default;
Logger::info(
sprintf(
'perun.ProxyFilter: %s filter %s for SP %s',
$shouldRun ? 'Running' : 'Filtering out',
$this->nestedClasses,
$currentSp
)
);
return $shouldRun;
}
}
return $default;
}
private function shouldRunForAttribute($attributes, $default)
{
foreach ($this->filterAttributes as $attr => $values) {
if (isset($attributes[$attr]) && is_array($attributes[$attr])) {
foreach ($values as $value) {
if (in_array($value, $attributes[$attr], true)) {
$shouldRun = !$default;
Logger::info(
sprintf(
'perun.ProxyFilter: %s filter %s because %s contains %s',
$shouldRun ? 'Running' : 'Filtering out',
$this->nestedClasses,
$attr,
$value
)
);
return $shouldRun;
}
}
}
}
return $default;
}
/**
* Parse an array of authentication processing filters.
*
* @see https://github.com/simplesamlphp/simplesamlphp/blob/simplesamlphp-1.17/lib/SimpleSAML/Auth/ProcessingChain.php
*
* @param array $filterSrc array with filter configuration
*
* @return array array of ProcessingFilter objects
*/
private static function parseFilterList($filterSrc)
{
assert(is_array($filterSrc));
$parsedFilters = [];
foreach ($filterSrc as $priority => $filter) {
if (is_string($filter)) {
$filter = [
'class' => $filter,
];
}
if (!is_array($filter)) {
throw new \Exception(
'Invalid authentication processing filter configuration: ' . 'One of the filters wasn\'t a string or an array.'
);
}
$parsedFilters[] = self::parseFilter($filter, $priority);
}
return $parsedFilters;
}
/**
* Parse an authentication processing filter.
*
* @see https://github.com/simplesamlphp/simplesamlphp/blob/simplesamlphp-1.17/lib/SimpleSAML/Auth/ProcessingChain.php
*
* @param array $config array with the authentication processing filter configuration
* @param int $priority The priority of the current filter, (not included in the filter
* definition.)
*
* @return ProcessingFilter the parsed filter
*/
private static function parseFilter($config, $priority)
{
assert(is_array($config));
if (!array_key_exists('class', $config)) {
throw new \Exception('Authentication processing filter without name given.');
}
$className = \SimpleSAML\Module::resolveClass(
$config['class'],
'Auth\Process',
'\SimpleSAML\Auth\ProcessingFilter'
);
$config['%priority'] = $priority;
unset($config['class']);
return new $className($config, null);
}
/**
* Process the given state.
*
* @see https://github.com/simplesamlphp/simplesamlphp/blob/simplesamlphp-1.17/lib/SimpleSAML/Auth/ProcessingChain.php
*
* This function will only return if processing completes. If processing requires showing
* a page to the user, we will not be able to return from this function. There are two ways
* this can be handled:
* - Redirect to a URL: We will redirect to the URL set in $state['ReturnURL'].
* - Call a function: We will call the function set in $state['ReturnCall'].
*
* If an exception is thrown during processing, it should be handled by the caller of
* this function. If the user has redirected to a different page, the exception will be
* returned through the exception handler defined on the state array. See
* State for more information.
* @see State
* @see State::EXCEPTION_HANDLER_URL
* @see State::EXCEPTION_HANDLER_FUNC
*
* @param array $state the state we are processing
*/
private function processState(&$state)
{
$filters = self::parseFilterList($this->authproc);
try {
while (count($filters) > 0) {
$filter = array_shift($filters);
$filter->process($state);
}
} catch (\SimpleSAML\Error\Exception $e) {
// No need to convert the exception
throw $e;
} catch (\Exception $e) {
/*
* To be consistent with the exception we return after an redirect,
* we convert this exception before returning it.
*/
throw new \SimpleSAML\Error\UnserializableException($e);
}
// Completed
}
}
| true |
b24c1f9e2ac0f3b10fd18b396ff34a545793bf3d | PHP | bparks/pails-auth | /views/account/forgot.php | UTF-8 | 5,275 | 2.90625 | 3 | [] | no_license | <?php
/*
Below is a very simple example of how to process a lost password request
We'll deal with a request in two stages, confirmation or deny then proccess
This file handles 3 tasks.
1. Construct new request.
2. Confirm request. - Generate new password, update the db then email the user
3. Deny request. - Close the request
*/
$errors = array();
$success_message = "";
//User has confirmed they want their password changed
//----------------------------------------------------------------------------------------------
if(!empty($_GET["confirm"]))
{
$token = trim($_GET["confirm"]);
if($token == "" || !validateactivationtoken($token,TRUE))
{
$errors[] = lang("FORGOTPASS_INVALID_TOKEN");
}
else
{
$rand_pass = getUniqueCode(15);
$secure_pass = generateHash($rand_pass);
$userdetails = fetchUserDetails(NULL,$token);
try {
$mail = AuthMailer::lost_password($userdetails, $rand_pass);
$mail->deliver();
if(!updatepasswordFromToken($secure_pass,$token))
{
$errors[] = lang("SQL_ERROR");
}
else
{
//Might be wise if this had a time delay to prevent a flood of requests.
flagLostpasswordRequest($userdetails->username_clean,0);
$success_message = lang("FORGOTPASS_NEW_PASS_EMAIL");
}
} catch (Exception $e) {
$errors[] = lang("MAIL_ERROR");
}
}
}
//----------------------------------------------------------------------------------------------
//User has denied this request
//----------------------------------------------------------------------------------------------
if(!empty($_GET["deny"]))
{
$token = trim($_GET["deny"]);
if($token == "" || !validateactivationtoken($token,TRUE))
{
$errors[] = lang("FORGOTPASS_INVALID_TOKEN");
}
else
{
$userdetails = fetchUserDetails(NULL,$token);
flagLostpasswordRequest($userdetails->username_clean,0);
$success_message = lang("FORGOTPASS_REQUEST_CANNED");
}
}
//----------------------------------------------------------------------------------------------
//Forms posted
//----------------------------------------------------------------------------------------------
if(!empty($_POST))
{
$email = $_POST["email"];
$username = $_POST["username"];
//Perform some validation
//Feel free to edit / change as required
if(trim($email) == "")
{
$errors[] = lang("ACCOUNT_SPECIFY_EMAIL");
}
//Check to ensure email is in the correct format / in the db
else if(!isValidemail($email) || !emailExists($email))
{
$errors[] = lang("ACCOUNT_INVALID_EMAIL");
}
if(trim($username) == "")
{
$errors[] = lang("ACCOUNT_SPECIFY_USERNAME");
}
else if(!usernameExists($username))
{
$errors[] = lang("ACCOUNT_INVALID_USERNAME");
}
if(count($errors) == 0)
{
//Check that the username / email are associated to the same account
if(!emailusernameLinked($email,$username))
{
$errors[] = lang("ACCOUNT_USER_OR_EMAIL_INVALID");
}
else
{
//Check if the user has any outstanding lost password requests
$userdetails = fetchUserDetails($username);
if($userdetails->lostpasswordrequest == 1)
{
$errors[] = lang("FORGOTPASS_REQUEST_EXISTS");
}
else
{
//email the user asking to confirm this change password request
//We can use the template builder here
//We use the activation token again for the url key it gets regenerated everytime it's used.
$confirm_url = 'http://'.$_SERVER['HTTP_HOST']."/account/forgot?confirm=".$userdetails->activationtoken;
$deny_url = 'http://'.$_SERVER['HTTP_HOST']."/account/forgot?deny=".$userdetails->activationtoken;
try {
$mail = AuthMailer::lost_password_request($userdetails, $confirm_url, $deny_url);
$mail->deliver();
$success_message = lang("FORGOTPASS_REQUEST_SUCCESS");
} catch (Exception $e) {
$errors[] = lang("MAIL_ERROR");
}
}
}
}
}
//----------------------------------------------------------------------------------------------
?>
<div class="modal-ish">
<div class="modal-header">
<h2>Password Reset</h2>
</div>
<div class="modal-body">
<br>
<?php
if(!empty($_POST) || !empty($_GET)):
if(count($errors) > 0):
?>
<div id="errors">
<?php errorBlock($errors); ?>
</div>
<?
else:
?>
<div id="success">
<p><?php echo $success_message; ?></p>
</div>
<?php
endif;
endif;
?>
<div id="regbox">
<form name="newLostPass" action="/account/forgot" method="post">
<p>
<label>Username:</label>
<input type="text" name="username" />
</p>
<p>
<label>Email:</label>
<input type="text" name="email" />
</p>
<input type="submit" class="btn btn-primary" name="new" id="newfeedform" value="Reset Your Password" />
</form>
</div>
</div>
</div>
| true |
9d4bd4772227071c766aa7f5cfcbdae8088b26ba | PHP | issaqsyed/APIOrdermanagement | /module/OrderManagement/src/OrderManagement/Controller/OrderManagementController.php | UTF-8 | 9,970 | 2.625 | 3 | [] | no_license | <?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/ for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Ordermanagement\Controller;
use Application\Entity\Orders;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\Http\Client;
use Zend\Http\Request;
use Zend\Http\Response;
class OrdermanagementController extends AbstractActionController
{
/**
* Handler 404
*
* This method is used to handle 404.
*
* @author Syed Ishaq <smishaq@stc.in .... syedissaq918@gmail.com>
*
* @since -- Added the handler404() method
*
* @return 404 Page Not Found
* @throws Does not throw any exception
* @access public
*/
public function handler404()
{
$this->getResponse()->setStatusCode(404);
return;
}
/**
* Doctrine Object Manager
*
* This method is used to get Doctrine connection object.
*
* @author Syed Ishaq <smishaq@stc.in .... syedissaq918@gmail.com>
*
* @since -- Added the getConnection() method
*
* @return object $entityManager Doctrine Object Manager
* @throws Does not throw any exception
* @access public
*/
public function getConnection()
{
$eManager = $this->getServiceLocator();
$entityManager = $eManager->get('doctObjMngr');
return $entityManager;
}
/**
* Entity Hydrator
*
* This method is used to set data in entity.
*
* @author Syed Ishaq <smishaq@stc.in .... syedissaq918@gmail.com>
*
* @since -- Added the entityHydrator() method
* @since -- Added the $dataArr argument
* @since -- Added the $entity argument
*
* @param array $dataArr Will receive data values
* @param object $entity Will receive an entity
*
* @return object $hydrator
* @throws Does not throw any exception
* @access public
*/
public function entityHydrator( $dataArr, $entity )
{
$hydrator = $this->getServiceLocator()->get('hydrateEntity');
$hydrator( $dataArr , $entity );
return $hydrator;
}
/**
* indexAction
* This method calls API and get all Orders from order-rest API
* This method is used getting All Orders
*
* @author SM Ishaq <smishaq@stc.in / issaqsyed918@gmail.com>
*
* @since 1.0 Added indexAction() method
*
*
* @param will not receive any argument
*
* @return will return a connection
* @throws Does not throws any exception
* @access public
*/
public function indexAction()
{
$viewobjmodel = new ViewModel();
$client = new Client();
$ServerPort ="";
if($_SERVER['SERVER_PORT']){
$ServerPort = ':'.$_SERVER['SERVER_PORT'];
}
$client->setUri('http://'.$_SERVER['SERVER_NAME'].$ServerPort.'/order-rest');
$client->setOptions(array(
'maxredirects' => 0,
'timeout' => 30
));
$response = $client->send();
if ($response->isSuccess()) {
$result = json_decode( $response->getContent() , true);
}
if(count($result)){
$viewobjmodel->setVariable('result', $result);
}
return $viewobjmodel;
}
/**
* getordersAction
* This method calls API and get Particular Orders based on Orderid that we sent to api from order-rest API
* This method is used getting Single Orders
*
* @author SM Ishaq <smishaq@stc.in / issaqsyed918@gmail.com>
*
* @since 1.0 Added getordersAction() method
*
*
* @param will not receive any argument
*
* @return will return a connection
* @throws Does not throws any exception
* @access public
*/
public function getordersAction()
{
$id = 9;
$viewobjmodel = new ViewModel();
$client = new Client();
$ServerPort ="";
if($_SERVER['SERVER_PORT']){
$ServerPort = ':'.$_SERVER['SERVER_PORT'];
}
$client->setUri('http://'.$_SERVER['SERVER_NAME'].$ServerPort.'/order-rest/'.$id);
// $client->setUri('http://localhost:9015/order-rest/'.$id);
$client->setOptions(array(
'maxredirects' => 0,
'timeout' => 30
));
$response = $client->send();
if ($response->isSuccess()) {
$result = json_decode( $response->getContent() , true);
}
if(count($result)){
$viewobjmodel->setVariable('result', $result);
}
return $this->redirect()->toRoute('ordermanagement', array('action' => 'index') );
}
/**
* createAction
* // This method calls API and send POST Data and Save order Details in orderstable and orderitems table
* This method is used getting Single Orders
*
* @author SM Ishaq <smishaq@stc.in / issaqsyed918@gmail.com>
*
* @since 1.0 Added createAction() method
*
*
* @param will not receive any argument
*
* @return will return a connection
* @throws throws exception
* @access public
*/
public function createAction(){
$nameArr= [1,2];
$priceArr=[10,12];
$qtyArr=[2,1];
$data = [ [
'emailid' => 'issaqsyed918@gmail.com',
'status' => 'created'
] , 'nameArr' => $nameArr , 'priceArr' => $priceArr ,'qtyArr' => $qtyArr ];
$client = new Client();
$ServerPort ="";
if($_SERVER['SERVER_PORT']){
$ServerPort = ':'.$_SERVER['SERVER_PORT'];
}
$client->setUri('http://'.$_SERVER['SERVER_NAME'].$ServerPort.'/order-rest');
// $client->setUri('http://localhost:9015/order-rest');
$client->setOptions(array(
'maxredirects' => 5,
'timeout' => 30
));
$client->setParameterPost(
$data
);
$client->setMethod( Request::METHOD_POST );
$response = $client->send();
if ($response->isSuccess()) {
$result = json_decode( $response->getContent() , true);
}
return $this->redirect()->toRoute('ordermanagement', array('action' => 'index') );
}
/**
* deleteAction
* This method is used to delete single order by passing orderid and using delete method
* @author SM Ishaq <smishaq@stc.in / issaqsyed918@gmail.com>
*
* @since 1.0 Added deleteAction() method
*
*
* @param will not receive any argument
*
* @return will return a connection
* @throws Does not throws any exception
* @access public
*/
public function deleteAction(){
$id = $this->params('id');
$client = new Client();
$ServerPort ="";
if($_SERVER['SERVER_PORT']){
$ServerPort = ':'.$_SERVER['SERVER_PORT'];
}
$client->setUri('http://'.$_SERVER['SERVER_NAME'].$ServerPort.'/order-rest/'.$id);
$client->setOptions(array(
'maxredirects' => 5,
'timeout' => 30
));
$client->setMethod( Request::METHOD_DELETE );
$response = $client->send();
if ($response->isSuccess()) {
$result = json_decode( $response->getContent() , true);
}
return $this->redirect()->toRoute('ordermanagement', array('action' => 'index') );
}
/**
* todayAction
* This method fetches all today orders using API and POST Data today
* @author SM Ishaq <smishaq@stc.in / issaqsyed918@gmail.com>
*
* @since 1.0 Added todayAction() method
*
*
* @param will not receive any argument
*
* @return will return a connection
* @throws Does not throws any exception
* @access public
*/
public function todayAction(){
$data = [ 'today' => 'today' ];
$client = new Client();
$ServerPort ="";
if($_SERVER['SERVER_PORT']){
$ServerPort = ':'.$_SERVER['SERVER_PORT'];
}
$client->setUri('http://'.$_SERVER['SERVER_NAME'].$ServerPort.'/order-rest');
$client->setOptions(array(
'maxredirects' => 5,
'timeout' => 30
));
$client->setParameterPost(
$data
);
$client->setMethod( Request::METHOD_POST );
$response = $client->send();
if ($response->isSuccess()) {
$result = json_decode( $response->getContent() , true);
}
return $this->redirect()->toRoute('ordermanagement', array('action' => 'index') );
}
/**
* searchuserAction
* This method fetches order by users id using API and POST Data search and id of user
* @author SM Ishaq <smishaq@stc.in / issaqsyed918@gmail.com>
*
* @since 1.0 Added searchuserAction() method
*
*
* @param will not receive any argument
*
* @return will return a connection
* @throws Does not throws any exception
* @access public
*/
public function searchuserAction(){
$data = [ 'search' => 'search' , 'id' => 1 ];
$client = new Client();
$ServerPort ="";
if($_SERVER['SERVER_PORT']){
$ServerPort = ':'.$_SERVER['SERVER_PORT'];
}
$client->setUri('http://'.$_SERVER['SERVER_NAME'].$ServerPort.'/order-rest');
$client->setOptions(array(
'maxredirects' => 5,
'timeout' => 30
));
$client->setParameterPost(
$data
);
$client->setMethod( Request::METHOD_POST );
$response = $client->send();
if ($response->isSuccess()) {
$result = json_decode( $response->getContent() , true);
}
return $this->redirect()->toRoute('ordermanagement', array('action' => 'index') );
}
}
| true |
de61e77dae7278df044a9bfb9df51c88e9a6fef3 | PHP | pegam/PHPMan | /Man.php | UTF-8 | 855 | 3.640625 | 4 | [] | no_license | <?php
/**
* Class Man
*/
class Man implements SleepInterface, EatInterface, WorkInterface {
/** @var int */
private $birth;
/** @var int */
private $happiness;
/** @var int */
private $energy;
public function __construct() {
$this->birth = time();
$this->happiness = 50;
$this->energy = 50;
}
/**
* Sleep
*
* @param int $seconds
* @return void
*/
public function sleep($seconds) {
// chnages happines and energy
}
/**
* Eat
*
* @param array $food
* @return void
*/
public function eat(array $food) {
// chnages happines and energy
}
/**
* Work
*
* @param int $seconds
* @return void
*/
public function work($seconds) {
// chnages happines and energy
}
} | true |
cbf1994dcd941b4e133bca52f9d609a4830274dc | PHP | evillemez/AyamelResourceApiServer | /src/Ayamel/ResourceBundle/Document/ContentCollection.php | UTF-8 | 3,828 | 2.78125 | 3 | [
"MIT"
] | permissive | <?php
namespace Ayamel\ResourceBundle\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
use JMS\Serializer\Annotation as JMS;
use AC\ModelTraits\AutoGetterSetterTrait;
/**
* Content container object, contains several types of fields for referencing the content of a resource object
*
* @MongoDB\EmbeddedDocument
*
*/
class ContentCollection
{
use AutoGetterSetterTrait;
/**
* @MongoDB\String
* @JMS\SerializedName("canonicalUri")
* @JMS\Type("string")
*/
protected $canonicalUri;
/**
* Note that for now this is just a hash, in the future there will probably be a legitimate document.
*
* @MongoDB\EmbedOne(targetDocument="Ayamel\ResourceBundle\Document\OEmbed")
* @JMS\Type("Ayamel\ResourceBundle\Document\OEmbed")
*/
protected $oembed;
/**
* Array of FileReference objects.
*
* @MongoDB\EmbedMany(targetDocument="Ayamel\ResourceBundle\Document\FileReference")
* @JMS\Type("array<Ayamel\ResourceBundle\Document\FileReference>")
*/
protected $files = [];
/**
* Set oembed fields
*
* @param hash $oembed
*/
public function setOembed(OEmbed $oembed)
{
$this->oembed = $oembed;
}
/**
* Set specific oembed field
*
* @param string $key
* @param mixed $val
* @return self
*/
public function setOembedKey($key, $val)
{
$this->oembed[$key] = $val;
return $this;
}
/**
* Get value for specific Oembed field, returning default if it doesn't exist
*
* @param string $key
* @param mixed $default
* @return mixed
*/
public function getOembedKey($key, $default = null)
{
return isset($this->oembed[$key]) ? $this->oembed[$key] : $default;
}
/**
* Remove a specific Oembed field if it's set
*
* @param string $key
* @return self
*/
public function removeOembedKey($key)
{
if (isset($this->oembed[$key])) {
unset($this->oembed[$key]);
}
return $this;
}
/**
* Return true/false if specific oembed field exists
*
* @param string $key
* @return boolean
*/
public function hasOembedKey($key)
{
return isset($this->oembed[$key]);
}
/**
* Set files
*
* @param array Ayamel\ResourceBundle\Document\FileReference $files
* @return self
*/
public function setFiles(array $files = null)
{
$this->files = [];
if (!is_null($files)) {
foreach ($files as $file) {
$this->addFile($file);
}
}
return $this;
}
/**
* Add a relation
*
* @param Ayamel\ResourceBundle\Document\Relation $file
* @return self
*/
public function addFile(FileReference $file)
{
$this->files[] = $file;
return $this;
}
/**
* Remove an instance of a relation
*
* @param FileReference $file
* @return self
*/
public function removeFile(FileReference $file)
{
$new = [];
//TODO: this... not so efficient, can be refactored later
foreach ($this->files as $instance) {
if (!$instance->equals($file)) {
$new[] = $instance;
}
}
$this->setFiles($new);
return $this;
}
/**
* Return boolean if a given file reference is contained in this content collection
*
* @param FileReference $ref
* @return booleah
*/
public function hasFile(FileReference $ref)
{
foreach ($this->files as $file) {
if ($ref->equals($file)) {
return true;
}
}
return false;
}
}
| true |
9ffda180c8f19e2b6975d96a12fe332f32bf07b4 | PHP | nucknine/PHP-Projects | /4-9_Namespaces/uqn/global.php | UTF-8 | 154 | 2.5625 | 3 | [] | no_license | <?
include 'project.php';
class Connection{
function __construct(){
echo __CLASS__.'<br>';
}
}
echo 'Из GLOBAL:<br>';
$obj = new Connection;
?> | true |
5928f623ca5e012277ca3b7f63e766d9c86fe564 | PHP | CALauer/KinderMission | /includes/login_inc.php | UTF-8 | 1,598 | 2.578125 | 3 | [] | no_license | <?php
if(isset($_POST['Login'])) {
require 'config.php';
$emailUsername = $_POST['emailUsername'];
$password = $_POST['password'];
if (empty($emailUsername) || empty(password)) {
header ('Location: ../view/index.php?error=EmptyFields');
exit();
}
else {
$sql = "SELECT * FROM users WHERE username=? OR email=? ";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header ('Location: ../view/index.php?error=sqlError');
exit();
}
else {
mysqli_stmt_bind_param($stmt, "ss", $emailUsername, $emailUsername);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($result)) {
$passwordCheck = password_verify($password, $row['password']);
if ($passwordCheck == false) {
header ('Location: ../view/index.php?error=wrongPassword');
exit();
}
else if ($passwordCheck == true) {
session_start();
$_SESSION['id'] = $row['id'];
$_SESSION['username'] = $row['username'];
$_SESSION['title'] = $row['title'];
header ('Location: ../view/index.php?login=success');
exit();
}
}
else {
header ('Location: ../view/index.php?error=noRegisteredUsers');
exit();
}
}
}
} | true |