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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
485143f2f99c5e7a6c9a7024c8a7b1243048f243 | PHP | requtize/routing | /tests/unit/Routing/RouteCollectionTest.php | UTF-8 | 14,912 | 2.65625 | 3 | [
"MIT"
] | permissive | <?php
use Requtize\Routing\RouteCollection;
use Requtize\Routing\Route;
class RouteCollectionTest extends PHPUnit_Framework_TestCase
{
protected $collection;
protected function setUp()
{
$this->collection = new RouteCollection;
}
protected function tearDown()
{
$this->collection = null;
}
/**
* Add route as object, and check if is in collection.
*/
public function testAddRouteAsObject()
{
$this->collection->add(new Route('name', '/', 'action'));
$this->collection->compile();
$this->assertCount(1, $this->collection->all());
}
/**
* Add route as shorthand method, with GET method
* and check if exists and if has GET method.
*/
public function testAddRouteShorthandMethodGet()
{
$this->collection->get('name', '/', 'action');
$this->assertCount(1, $this->collection->all());
$routes = $this->collection->all();
$this->assertArrayHasKey('0', $routes);
$this->assertContains('GET', $routes[0]->getMethods());
}
/**
* Add route as shorthand method, with POST method
* and check if exists and if has POST method.
*/
public function testAddRouteShorthandMethodPost()
{
$this->collection->post('name', '/', 'action');
$this->assertCount(1, $this->collection->all());
$routes = $this->collection->all();
$this->assertArrayHasKey('0', $routes);
$this->assertContains('POST', $routes[0]->getMethods());
}
/**
* Add route as shorthand method, with PUT method
* and check if exists and if has PUT method.
*/
public function testAddRouteShorthandMethodPut()
{
$this->collection->put('name', '/', 'action');
$this->assertCount(1, $this->collection->all());
$routes = $this->collection->all();
$this->assertArrayHasKey('0', $routes);
$this->assertContains('PUT', $routes[0]->getMethods());
}
/**
* Add route as shorthand method, with DELETE method
* and check if exists and if has GET DELETE.
*/
public function testAddRouteShorthandMethodDelete()
{
$this->collection->delete('name', '/', 'action');
$this->assertCount(1, $this->collection->all());
$routes = $this->collection->all();
$this->assertArrayHasKey('0', $routes);
$this->assertContains('DELETE', $routes[0]->getMethods());
}
/**
* Add route as shorthand method, with PATCH method
* and check if exists and if has PATCH method.
*/
public function testAddRouteShorthandMethodPatch()
{
$this->collection->patch('name', '/', 'action');
$this->assertCount(1, $this->collection->all());
$routes = $this->collection->all();
$this->assertArrayHasKey('0', $routes);
$this->assertContains('PATCH', $routes[0]->getMethods());
}
/**
* Add route as shorthand method, with OPTIONS method
* and check if exists and if has GET OPTIONS.
*/
public function testAddRouteShorthandMethodOptions()
{
$this->collection->options('name', '/', 'action');
$this->assertCount(1, $this->collection->all());
$routes = $this->collection->all();
$this->assertArrayHasKey('0', $routes);
$this->assertContains('OPTIONS', $routes[0]->getMethods());
}
/**
* Add route as shorthand method, with HEAD method
* and check if exists and if has HEAD method.
*/
public function testAddRouteShorthandMethodHead()
{
$this->collection->head('name', '/', 'action');
$this->assertCount(1, $this->collection->all());
$routes = $this->collection->all();
$this->assertArrayHasKey('0', $routes);
$this->assertContains('HEAD', $routes[0]->getMethods());
}
/**
* Add route as create() method call, with POST method
* and check if exists and if has POST method.
*/
public function testAddRouteCreateMethodPostMethod()
{
$this->collection->create('POST', 'name', '/', 'action');
$this->assertCount(1, $this->collection->all());
$routes = $this->collection->all();
$this->assertArrayHasKey('0', $routes);
$this->assertContains('POST', $routes[0]->getMethods());
}
/**
* Create two collections, merge it and checks if base collection
* has two routes.
*/
public function testMerge()
{
$this->collection->get('current', '/current', 'actionCurrent');
$newCollection = new RouteCollection;
$newCollection->get('new', '/', 'action');
$this->collection->mergeWith($newCollection);
$routes = $this->collection->all();
$this->assertCount(2, $routes);
$this->assertArrayHasKey('0', $routes);
$this->assertArrayHasKey('1', $routes);
$this->assertEquals('current', $routes[0]->getName());
$this->assertEquals('/current', $routes[0]->getSourceRoute());
$this->assertEquals('new', $routes[1]->getName());
$this->assertEquals('/', $routes[1]->getSourceRoute());
}
/**
* Sets name and path prefix, add route to collection and
* check if route name and path has prefixes at the beginning of each.
*/
public function testAddRouteAndCheckPrefix()
{
$this->collection->setPrefix('name-prefix.', '/path-prefix');
$this->collection->get('name', '/path', 'action');
$this->assertCount(1, $this->collection->all());
$routes = $this->collection->all();
$this->assertArrayHasKey('0', $routes);
$this->assertEquals('name-prefix.name', $routes[0]->getName());
$this->assertEquals('/path-prefix/path', $routes[0]->getSourceRoute());
}
/**
* Create group with "blog" prefix, and add one route in group,
* and one route outside group.
*/
public function testCreateGroup()
{
$this->collection->get('name', '/path', 'action');
$this->collection->group('blog.', '/blog', function($collection) {
$collection->get('name', '/path', 'action');
});
$routes = $this->collection->all();
$this->assertCount(2, $routes);
$this->assertArrayHasKey('0', $routes);
$this->assertArrayHasKey('1', $routes);
$this->assertEquals('name', $routes[0]->getName());
$this->assertEquals('/path', $routes[0]->getSourceRoute());
$this->assertEquals('blog.name', $routes[1]->getName());
$this->assertEquals('/blog/path', $routes[1]->getSourceRoute());
}
/**
* Add three routes, and find for the second by Name.
*/
public function testFindByName()
{
// Protect to search only first index
$this->collection->get('first', '/first', 'action');
$this->collection->get('second', '/second', 'action');
// protect to search only in last index.
$this->collection->get('third', '/third', 'action');
$route = $this->collection->findByName('second');
$this->assertInstanceOf('Requtize\Routing\Route', $route);
$this->assertEquals('/second', $route->getSourceRoute());
}
/**
* Create three routes, one with callback action, two with string actions.
* Should export only these two with string actions.
*/
public function testExportToArray()
{
$this->collection->get('first', '/first', 'action');
$this->collection->get('second', '/second', function() {});
$this->collection->get('third', '/third', 'action');
$this->collection->compile();
$exported = $this->collection->exportToArray();
$this->assertCount(2, $exported);
$this->assertArrayHasKey('0', $exported);
$this->assertArrayHasKey('1', $exported);
$this->assertEquals('first', $exported[0]['name']);
$this->assertEquals('/first', $exported[0]['sourceRoute']);
$this->assertEquals('third', $exported[1]['name']);
$this->assertEquals('/third', $exported[1]['sourceRoute']);
}
/**
* Create array with full functionality, and try to import it - then check if
* all functionality is in imported route.
*
* @dataProvider importArrayBeforeCompile
*/
public function testImportBeforeCompile($data)
{
$import = [];
foreach($data as $field)
{
$import[$field['name']] = $field['value'];
}
$this->collection->importFromArray([$import]);
$routes = $this->collection->all();
$this->assertCount(1, $routes);
foreach($data as $field)
{
$this->assertEquals($field['value'], $routes[0]->{$field['method']}(), $field['name']);
}
}
public function importArrayBeforeCompile()
{
return [
[
[
[
'method' => 'getName',
'name' => 'name',
'value' => 'simple'
],
[
'method' => 'getAction',
'name' => 'action',
'value' => 'Controller:action'
],
[
'method' => 'getMethods',
'name' => 'methods',
'value' => ['GET', 'POST']
],
[
'method' => 'getRules',
'name' => 'rules',
'value' => ['first-token' => '[a-z]+', 'second-token' => '\/[^\/]+']
],
[
'method' => 'getRoute',
'name' => 'route',
'value' => '/source/route/([a-z]+)(\/[^\/]+)'
],
[
'method' => 'getSourceRoute',
'name' => 'sourceRoute',
'value' => '/source/route/{first-token}/{second-token}'
],
[
'method' => 'getArguments',
'name' => 'arguments',
'value' => ['first-argument' => '1', 'second-argument' => '2']
],
[
'method' => 'getDefaults',
'name' => 'defaults',
'value' => ['first-token' => 'default', 'second-token' => '/wild/card']
],
[
'method' => 'getExtras',
'name' => 'extras',
'value' => ['first-extra', 'second-extra']
],
[
'method' => 'getTokens',
'name' => 'tokens',
'value' => [
[
'name' => 'first-token',
'optional' => false,
'wildcard' => false,
'pattern' => '[a-z]+'
],
[
'name' => 'second-token',
'optional' => false,
'wildcard' => true,
'pattern' => '\/[^\/]+'
]
]
]
]
]
];
}
/**
* Create array with full functionality, and try to import it - then check if
* all functionality is in imported route.
*
* @dataProvider importArrayAfterCompile
*/
public function testImportAfterCompile($data)
{
$import = [];
foreach($data as $field)
{
$import[$field['name']] = $field['value'];
}
$this->collection->importFromArray([$import]);
$this->collection->compile();
$routes = $this->collection->all();
$this->assertCount(1, $routes);
foreach($data as $field)
{
$this->assertEquals($field['value'], $routes[0][$field['name']], $field['name']);
}
}
public function importArrayAfterCompile()
{
return [
[
[
[
'name' => 'name',
'value' => 'simple'
],
[
'name' => 'action',
'value' => 'Controller:action'
],
[
'name' => 'methods',
'value' => ['GET', 'POST']
],
[
'name' => 'rules',
'value' => ['first-token' => '[a-z]+', 'second-token' => '\/[^\/]+']
],
[
'name' => 'route',
'value' => '/^\/source\/route\/{first-token}\/{second-token}$/'
],
[
'name' => 'sourceRoute',
'value' => '/source/route/{first-token}/{second-token}'
],
[
'name' => 'arguments',
'value' => ['first-argument' => '1', 'second-argument' => '2']
],
[
'name' => 'defaults',
'value' => ['first-token' => 'default', 'second-token' => '/wild/card']
],
[
'name' => 'extras',
'value' => ['first-extra', 'second-extra']
],
[
'name' => 'tokens',
'value' => []
]
]
]
];
}
/**
* Add two simple routes, compile them and check if all exists.
*/
public function testCompile()
{
$this->collection->get('first', '/first', 'action');
$this->collection->get('second', '/second', function() {});
$this->collection->compile();
$routes = $this->collection->all();
$this->assertCount(2, $routes);
$this->assertArrayHasKey('0', $routes);
$this->assertArrayHasKey('1', $routes);
$this->assertEquals('first', $routes[0]['name']);
$this->assertEquals('/^\/first$/', $routes[0]['route']);
$this->assertEquals('second', $routes[1]['name']);
$this->assertEquals('/^\/second$/', $routes[1]['route']);
}
}
| true |
9e65fce5f5dbd36253b89bbb2962c3def77b59d5 | PHP | phoebius/proof-of-concept | /lib/Cache/Cache.class.php | UTF-8 | 2,410 | 2.6875 | 3 | [] | no_license | <?php
/* ***********************************************************************************************
*
* Phoebius Framework
*
* **********************************************************************************************
*
* Copyright (c) 2009 phoebius.org
*
* This program is free software; you can redistribute it and/or modify it under the terms
* of the GNU Lesser General Public License as published by the Free Software Foundation;
* either version 3 of the License, or (at your option) any later version.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program; if not, see <http://www.gnu.org/licenses/>.
*
************************************************************************************************/
/**
* @ingroup Cache
*/
final class Cache extends Pool
{
private $peers = array();
private $default;
/**
* @return Cache
*/
static function getInstance()
{
return LazySingleton::instance(__CLASS__);
}
/**
* @return CachePeer
*/
static function getDefault()
{
return self::getInstance()->getDefaultPeer();
}
/**
* @return Cache
*/
static function setAsDefault()
{
return self::getInstance()->setLastPeerAsDefault();
}
/**
* @return Cache
*/
static function add($peerId, CachePeer $peer)
{
self::getInstance()->addPeer($peerId, $peer);
}
/**
* @return CachePeer
*/
static function get($peerId)
{
return self::getInstance()->getPeer($peerId);
}
/**
* @return Cache
*/
function addPeer($peerId, CachePeer $peer)
{
Assert::isTrue(
!isset($this->peers[$peerId]),
"cache peer identified by {$peerId} already defined"
);
$this->peers[$peerId] = $peer;
if (!$this->default)
{
$this->default = $peer;
}
return $this;
}
/**
* @return CachePeer
*/
function getDefaultPeer()
{
Assert::isTrue(
sizeof($this->peers) > 0,
'no peers defined, so no default peer inside'
);
return $this->default;
}
/**
* @return Cache
*/
function setLastPeerAsDefault()
{
Assert::isTrue(
sizeof($this->peers) > 0,
'no peers defined, so no default peer inside'
);
$this->default = end($this->peers);
return $this;
}
/**
* @return CachePeer
*/
function getPeer($peerId)
{
Assert::isTrue(
isset($this->peers[$peerId]),
"unknown cache peer identified by {$peerId}"
);
return $this->peers[$peerId];
}
}
?> | true |
6d302f05ab9cefc1555646bbf2112d8af13ad986 | PHP | mafd16/curious-george | /src/Pages/PagesController.php | UTF-8 | 6,077 | 2.71875 | 3 | [
"MIT"
] | permissive | <?php
namespace Mafd16\Pages;
use \Anax\Configure\ConfigureInterface;
use \Anax\Configure\ConfigureTrait;
use \Anax\DI\InjectionAwareInterface;
use \Anax\DI\InjectionAwareTrait;
use DateTime;
/**
* A controller class for the main pages.
*/
class PagesController implements
ConfigureInterface,
InjectionAwareInterface
{
use ConfigureTrait,
InjectionAwareTrait;
/**
* @var $data description
*/
//private $data;
/**
* Show the index page.
*
* @return void
*/
public function getIndex()
{
$title = "Curious Walt";
$view = $this->di->get("view");
$pageRender = $this->di->get("pageRender");
// Get the latest questions
$ques = $this->di->get("questionModel")->getQuestions();
uasort($ques, function ($queA, $queB) {
if ($queA->created == $queB->created) {
return 0;
}
return ($queA->created < $queB->created) ? 1 : -1;
});
$questions = array_slice($ques, 0, 5);
// Get number of answers
$answers = [];
foreach ($questions as $question) {
$ans = $this->di->get("answerModel")->getAnswersWhere("questionId", $question->id);
$answers[$question->id] = count($ans);
}
// Get the most popular tags
$tags = $this->di->get("tagModel")->getAllTags();
uasort($tags, function ($tagA, $tagB) {
if ($tagA->rank == $tagB->rank) {
return 0;
}
return ($tagA->rank < $tagB->rank) ? 1 : -1;
});
$tags = array_slice($tags, 0, 9);
// Get the most active users
$users = $this->di->get("user")->getAllUsers();
uasort($users, function ($userA, $userB) {
if ($userA->entries == $userB->entries) {
return 0;
}
return ($userA->entries < $userB->entries) ? 1 : -1;
});
$users = array_slice($users, 0, 6);
$data = [
"questions" => $questions,
"tags" => $tags,
"users" => $users,
"noOfAnswers" => $answers,
];
$view->add("pages/index", $data);
$pageRender->renderPage(["title" => $title]);
}
/**
* Show the questions page.
*
* @return void
*/
public function getQuestions()
{
$title = "Questions";
$subtitle = "Here you will find all the questions!";
$view = $this->di->get("view");
$pageRender = $this->di->get("pageRender");
// Get all the questions
$questions = $this->di->get("questionModel")->getQuestions();
// Get number of answers
$answers = [];
foreach ($questions as $question) {
$ans = $this->di->get("answerModel")->getAnswersWhere("questionId", $question->id);
$answers[$question->id] = count($ans);
}
$data = [
"questions" => $questions,
"subtitle" => $subtitle,
"noOfAnswers" => $answers,
];
$view->add("pages/questions", $data);
$pageRender->renderPage(["title" => $title]);
}
/**
* Show the tags page.
*
* @return void
*/
public function getTags()
{
$title = "Tags";
$view = $this->di->get("view");
$pageRender = $this->di->get("pageRender");
// Get all the tags from db
$tags = $this->di->get("tagModel")->getAllTags();
$data = [
//"items" => $book->findAll(),
"tags" => $tags,
];
$view->add("pages/tags", $data);
//$view->add("blocks/footer", $data);
$pageRender->renderPage(["title" => $title]);
}
/**
* Show the users page.
*
* @return void
*/
public function getUsers()
{
$title = "Users";
$view = $this->di->get("view");
$pageRender = $this->di->get("pageRender");
// Get all the users from db
$users = $this->di->get("user")->getAllUsers();
$data = [
//"items" => $book->findAll(),
"users" => $users,
];
$view->add("pages/users", $data);
//$view->add("blocks/footer", $data);
$pageRender->renderPage(["title" => $title]);
}
/**
* Show a users public page.
*
* @param int $id The users id
*
* @return void
*/
public function getUserPublic($id)
{
$view = $this->di->get("view");
$pageRender = $this->di->get("pageRender");
// Get the user from db
$user = $this->di->get("user")->getUserFromDatabase("id", $id);
// Get the users questions
$askedQuestions = $this->di->get("questionModel")->getQuestionsWhere("userId", $user->id);
// Get the users answers
$answers = $this->di->get("answerModel")->getAnswersWhere("userId", $user->id);
// Get questions answered by user
$answeredQuestions = $this->di->get("questionModel")->getQuestionsAnsweredByUser($answers);
// Get the users comments
$comments = $this->di->get("com")->getCommentsWhere("userId", $user->id);
// Construct the title
$title = "User $user->acronym";
// Calculate age for user
$from = new DateTime($user->birth);
$too = new DateTime('today');
$age = $from->diff($too)->y;
// Collect the user statistics
$stats = (object) [
"questions" => count($askedQuestions),
"answers" => count($answers),
"comments" => count($comments),
];
$data = [
"user" => $user,
"askedQuestions" => $askedQuestions,
"answeredQuestions" => $answeredQuestions,
"stats" => $stats,
"answers" => $answers,
"age" => $age,
];
$view->add("pages/user", $data);
$pageRender->renderPage(["title" => $title]);
}
}
| true |
3c645833ca46804e95f3c8be5bbddccbaae4b25b | PHP | MazurekPiotr/web-backend-oplossingen | /Opdracht-CRUD-queryorderby/index.php | UTF-8 | 2,309 | 2.953125 | 3 | [] | no_license | <?php
try{
if(isset($_GET['order_by']))
{
$orderArray = explode('-', $_GET['order_by']);
$orderColumn = $orderArray[0];
$order = $orderArray[1];
}
$db = new PDO('mysql:host=localhost;dbname=bieren', 'root', 'rtoip3107');
$order = 'ASC';
$orderColumn = 'biernr';
$string = 'SELECT bieren.biernr,
bieren.naam,
brouwers.brnaam,
soorten.soort,
bieren.alcohol
FROM bieren
INNER JOIN brouwers
ON bieren.brouwernr = brouwers.brouwernr
INNER JOIN soorten
ON bieren.soortnr = soorten.soortnr
ORDER BY '.$orderColumn .' '.$order;
$statement = $db->prepare($string);
$statement->execute();
$fetchArray = array();
while ($row = $statement->fetch(PDO::FETCH_ASSOC))
{
$fetchArray[] = $row;
}
$names = array();
foreach ($fetchArray[0] as $key => $value) {
$names[] = $key;
}
}
catch(PDOException $e)
{
$message = "Er ging iets mis: " . $e->getMessage();
}
?>
<!doctype html>
<html>
<head>
<style type="text/css">
tr:nth-child(even){
background-color: lightgrey
}
</style>
</head>
<body>
<table>
<thead>
<?php foreach ($names as $value): ?>
<th class="order "><a href="index.php?order_by=<?= $value ?>-<?= ($order == 'ASC' && $orderColumn == $value)? 'DESC' : 'ASC'?>"><?= $value ?></a></th>
<?php endforeach ?>
</thead>
<?php foreach ($fetchArray as $key => $bieren): ?>
<tr>
<?php foreach ($bieren as $bierkey => $value): ?>
<td><?= $value ?></td>
<?php endforeach ?>
</tr>
<?php endforeach ?>
</table>
<?php var_dump($fetchArray) ?>
</body>
</html> | true |
a7b48b9645f905d812e6ee2c3a7198a8cbe51a0e | PHP | katheroine/languagium | /php/arrays/operations_on_elements/prepending_elements.php | UTF-8 | 373 | 2.921875 | 3 | [] | no_license | #!/usr/bin/php8.0
<?php
$array = [2, 4, 6];
print("Initial state:\n\n");
print_r($array); print("\n");
// array_unshift
array_unshift($array, 0);
print("After prepend by array_unshift(\$array, 0):\n\n");
print_r($array); print("\n");
array_unshift($array, -6, -4, -2);
print("After prepend by array_unshift(\$array, -6, -4, -2):\n\n");
print_r($array); print("\n");
| true |
ca84a5228ddadbb4ee12c85f51e1b3cc89ecd2a0 | PHP | huntercasteel/MyHealth-Portal | /patient-services.php | UTF-8 | 10,490 | 2.796875 | 3 | [] | no_license | <?php
session_start();
error_reporting(0);
include 'includes/dbconn.php';
$conn = new mysqli($servername, $username, "", "db1", $sqlport, $socket);
if($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$patientID = $_SESSION['PATIENT_ID'];
$patient = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM Patients WHERE PatientID = '$patientID'"));
$currentDate = mysqli_fetch_assoc(mysqli_query($conn, "SELECT CURDATE()"))["CURDATE()"];
$serviceInput = '';
$doctorInput = $patient['DoctorID'];
$dateInput = '';
$timeInput = '';
$errorMessage = '';
$detailsMessage = '';
if(isset($_POST['viewDetailsButton']))
{
$serviceInput = $_POST['serviceInput'];
$doctorInput = $_POST['doctorInput'];
$dateInput = $_POST['dateInput'];
$timeInput = $_POST['timeInput'];
if(empty($serviceInput))
{
$errorMessage = "*First two fields required. Please select a service.";
}
else if(empty($doctorInput))
{
$errorMessage = "*First two fields required. Please select a doctor.";
}
else
{
$service = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM Services WHERE ServiceID = '$serviceInput'"));
$doctor = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM Doctors WHERE DoctorID = '$doctorInput'"));
$doctorAddress = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM Addresses WHERE AddressID = '" . $doctor['AddressID'] . "'"));
$hospital = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM Hospitals WHERE HospitalID = '" . $doctor['HospitalID'] . "'"));
$hospitalAddress = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM Addresses WHERE AddressID = '" . $hospital['AddressID'] . "'"));
$detailsMessage = "<div class = \"infoBox patient\">
<section class = infoHeader>
<h3>" . $service['Name'] . " Details</h3>
</section>
<section class = infoFields>
<legend>Cost</legend>
<span>$" . $service['Cost'] . "</span>
</section>
</br>
<section class = infoHeader>
<h3>" . $doctor['FirstName'] . " " . $doctor['LastName'] . " Details</h3>
</section>
<table class = infoFields>
<tr>
<td>
<legend>Email Address</legend>
<span>" . $doctor['EmailAddress'] . "</span>
</td>
<td>
<legend>Phone Number</legend>
<span>" . $doctor['PhoneNumber'] . "</span>
</td>
</tr>
<tr>
<td>
<legend>Street Address</legend>
<span>" . $doctorAddress['Street'] . "</span>
</br>
<span>" . $doctorAddress['City'] . "</span>
</br>
<span>" . $doctorAddress['StateCode'] . " " . $doctorAddress['ZipCode'] . "</span>
</td>
</tr>
</table>
</br>
<section class = infoHeader>
<h3>" . $hospital['Name'] . " Details</h3>
</section>
<table class = infoFields>
<tr>
<td>
<legend>Email Address</legend>
<span>" . $hospital['EmailAddress'] . "</span>
</td>
<td>
<legend>Phone Number</legend>
<span>" . $hospital['PhoneNumber'] . "</span>
</td>
</tr>
<tr>
<td>
<legend>Street Address</legend>
<span>" . $hospitalAddress['Street'] . "</span>
</br>
<span>" . $hospitalAddress['City'] . "</span>
</br>
<span>" . $hospitalAddress['StateCode'] . " " . $hospitalAddress['ZipCode'] . "</span>
</td>
</tr>
</table>
</div>";
}
}
if(isset($_POST['scheduleButton']))
{
$serviceInput = $_POST['serviceInput'];
$doctorInput = $_POST['doctorInput'];
$dateInput = $_POST['dateInput'];
$timeInput = $_POST['timeInput'];
if(empty($serviceInput))
{
$errorMessage = "*All fields required. Please select a service.";
}
else if(empty($doctorInput))
{
$errorMessage = "*All fields required. Please select a doctor.";
}
else if(empty($dateInput))
{
$errorMessage = "*All fields required. Please select a date.";
}
else if(empty($timeInput))
{
$errorMessage = "*All fields required. Please select a time.";
}
else
{
$query = mysqli_query($conn, "INSERT INTO ServiceAppointments (PatientID, ServiceID, DoctorID, AppointmentDate, AppointmentTime) VALUES ('$patientID','$serviceInput','$doctorInput','$dateInput','$timeInput')");
$serviceInput = '';
$doctorInput = $patient['DoctorID'];
$dateInput = '';
$timeInput = '';
}
}
$query = mysqli_query($conn, "SELECT * FROM ServiceAppointments WHERE PatientID = '$patientID' AND AppointmentDate >= CURDATE() ORDER BY AppointmentDate, AppointmentTime");
$result = mysqli_fetch_assoc($query);
$cancelButtons = [];
while($result)
{
$cancelButtons[] = $result['ServiceAppointmentID'];
$result = mysqli_fetch_assoc($query);
}
foreach($cancelButtons as $cancel)
{
if(isset($_POST["$cancel"]))
{
$query = mysqli_query($conn, "DELETE FROM ServiceAppointments WHERE ServiceAppointmentID = '$cancel'");
}
}
?>
<html>
<head>
<title>MyHealth Portal</title>
<link href = 'style.css' rel = 'stylesheet'>
</head>
<body>
<?php require "patient-header.php" ?>
<form name = "scheduleServicesForm" class = "patient" action = "patient-services.php" method = "post">
<section class = "formHeader">
<h3>Schedule Services</h3>
</section>
<?php echo "<span class = errorMessage>$errorMessage</span>" ?>
<section class = "formFields">
<legend>Service</legend>
<select name = "serviceInput" class = "formElement">
<option value = "0" disabled selected>Select Service</option>
<?php
$query = mysqli_query($conn, "SELECT * FROM Services");
$result = mysqli_fetch_assoc($query);
while($result)
{
echo "<option value = \"" . $result['ServiceID'] . "\"";
if($result['ServiceID'] == $serviceInput)
{
echo " selected";
}
echo ">" . $result['Name'] . "</option>";
$result = mysqli_fetch_assoc($query);
}
?>
</select>
</br>
<legend>Doctor</legend>
<select name = "doctorInput" class = "formElement">
<option value = "0" disabled selected>Select Doctor</option>
<?php
$query = mysqli_query($conn, "SELECT * FROM Doctors");
$result = mysqli_fetch_assoc($query);
while($result)
{
echo "<option value = \"" . $result['DoctorID'] . "\"";
if($result['DoctorID'] == $doctorInput)
{
echo " selected";
}
echo ">" . $result['FirstName'] . " " . $result['LastName'] . "</option>";
$result = mysqli_fetch_assoc($query);
}
?>
</select>
</br>
<legend>Appointment Date</legend>
<input name="dateInput" class = "formElement" type="date" value = "<?php echo $currentDate ?>" min = "<?php echo $currentDate ?>"/>
</br>
<legend>Appointment Time</legend>
<select name = "timeInput" class = "formElement">
<option value="0" disabled selected>Select Time</option>
<?php
$timeStart = 8;
$timeEnd = 16;
for($i = $timeStart; $i <= $timeEnd; $i++)
{
if($i > 12)
{
$temp = $i - 12;
}
else
{
$temp = $i;
}
if($i > 11 && $i < 24)
{
$midday = "PM";
}
else
{
$midday = "AM";
}
echo "<option value = \"$i\"";
if($i == $timeInput)
{
echo " selected";
}
echo ">$temp $midday</option>";
}
?>
</select>
</section>
</br>
<section class "formButtons">
<input name = "viewDetailsButton" class = "button blue" type = "submit" value = "View Details"/>
<input name = "scheduleButton" class = "button green" type = "submit" value = "Schedule"/>
</section>
</form>
<?php
echo $detailsMessage;
echo "<h2>Service Appointments</h2>";
$query = mysqli_query($conn, "SELECT * FROM ServiceAppointments WHERE PatientID = '$patientID' AND AppointmentDate >= CURDATE() ORDER BY AppointmentDate, AppointmentTime");
$result = mysqli_fetch_assoc($query);
if(!$result)
{
echo "<div class = \"infoBox patient\">
<span>You don't have any service appointments.</span>
</div>";
}
else
{
while($result)
{
$service = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM Services WHERE ServiceID = '" . $result['ServiceID'] . "'"));
$doctor = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM Doctors WHERE DoctorID = '" . $result['DoctorID'] . "'"));
$hospital = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM Hospitals WHERE HospitalID = '" . $doctor['HospitalID'] . "'"));
if($result['AppointmentTime'] > 12)
{
$temp = $result['AppointmentTime'] - 12;
}
else
{
$temp = $result['AppointmentTime'];
}
if($result['AppointmentTime'] > 11 && $result['AppointmentTime'] < 24)
{
$midday = "PM";
}
else
{
$midday = "AM";
}
echo "<form name = cancelServiceAppointmentsForm class = patient action = patient-services.php method = post>
<section class = formHeader>
<h3>" . $service['Name'] . " Appointment Details</h3>
</section>
<table class = infoFields>
<tr>
<td>
<legend>Doctor</legend>
<span>" . $doctor['FirstName'] . " " . $doctor['LastName'] . "</span>
</td>
<td>
<legend>Hospital</legend>
<span>" . $hospital['Name'] . "</span>
</td>
</tr>
<tr>
<td>
<legend>Appointment Date</legend>
<span>" . $result['AppointmentDate'] . "</span>
</td>
<td>
<legend>Appointment Time</legend>
<span>$temp $midday</span>
</td>
</tr>
</table>
</br>
<section class = formButtons>
<input name = " . $result['ServiceAppointmentID'] . " class = \"button red\" type = submit value = Cancel />
</section>
</form>";
$result = mysqli_fetch_assoc($query);
}
}
?>
</body>
</html> | true |
ba4109a7dbd689f425156a68cbf2749d01e41c50 | PHP | wuyonghui666/PMPDailyTest | /day24.php | UTF-8 | 214 | 3.28125 | 3 | [] | no_license | <?php
function Add($num1, $num2)
{
if($num1 == 0)
{
return $num2;
}
if($num2 == 2)
{
return $num1;
}
$num1 = array_sum($num1,$num2);
return $num1;
}
echo Add(0,1); | true |
6774e7bff5dfd1db1852373398ed2b8e555a69a1 | PHP | 04andresdiaz/sisadmin | /consultas/consulta_reserva_usuarios.php | UTF-8 | 881 | 2.515625 | 3 | [] | no_license | <?php
require ("../global/conexion.php");
session_start();
if (isset($_SESSION['id_usuario'])) {
$id_usuario = $_SESSION['id_usuario'];
$consulta = $conexion -> query("SELECT * FROM reservas ");
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="../css/css_estilos_tablas.css">
</head>
<body>
<div class="Tabla">
<table class="Tabla" id="buscar">
<tr>
<td>Fecha</td>
<td>Hora inicio</td>
<td>Hora de Entrega</td>
<td>Motivo</td>
<td>Casa</td>
<td>Respuesta</td>
</tr>
</div>
<tr>
<?php
while ($res = mysqli_fetch_row($consulta)) {
echo "
<td>$res[1]</td>
<td>$res[2]</td>
<td>$res[3]</td>
<td>$res[4]</td>
<td>$res[5]</td>
<td>$res[6]</td>
</tr>
";
}
?>
</table>
</body>
</html>
<?php
}else{
header('Location: ../index.php');
}
?>
| true |
c467a58f49cce8f5026eeaf2de719b083b4bf5cc | PHP | rizkiaprilan/Laravel---Student-Management | /database/seeds/StudentSeeder.php | UTF-8 | 680 | 2.703125 | 3 | [] | no_license | <?php
use Illuminate\Database\Seeder;
use Faker\factory as Faker;
class StudentSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$data = [
['majority_id'=>1],
['majority_id'=>2],
['majority_id'=>3],
['majority_id'=>4],
['majority_id'=>5],
];
$faker = Faker::create();
foreach($data as $d){
DB::table('students')->insert([
'name' => $faker->name,
'majority_id' => $d['majority_id'],
'address' => $faker->address,
]);
}
}
}
| true |
351c8f41dfb89a2833a01cad05d2df984156f916 | PHP | amarzora/banana | /app/Http/Requests/MoviesRequest.php | UTF-8 | 1,915 | 2.796875 | 3 | [
"MIT"
] | permissive | <?php
/**
* Created by PhpStorm.
* User: machine
* Date: 10/03/16
* Time: 16:51
*/
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
/**
* Class CategoriesRequest
* @package App\Http\Requests
* @package App\Http\Requests
*/
class MoviesRequest extends FormRequest
{
/**
* crration de validation par champs
*/
public function rules(){
return [
'title' => 'required|min:10|regex:/^[A-Za-z0-9]+$/|unique:movies',
'description' => 'required|min:10|max:250',
'language' => 'required|in:fr,en,es',
'annee' => 'required|date_format:Y|after:now',
'budget' => 'required|integer',
'BO' => 'required|in:Vo,vost,vostfr'
/*
* date_format: d/m/y
* digits:4 on peut utilise pour les dates
* pour after on peut choisir date exemple after:10/01/2015 n'accept pas date avant
* before avant
*/
];
}
/**
* Personnalise chaque message d'erreur
*/
public function messages()
{
return [
/*
* required parmet de grouper tout les champs
*/
'required' => 'champs obligatoire',
'title.required' => 'Le titre est obligatoire',
'description.required' => 'La description est obligatoire',
'title.min' => 'Le titre est trop court',
'title.max' => 'Le titre est trop long',
'description.min' => 'La description est trop courte',
'description.max' => 'La description est trop longue',
'title.regex' => 'le titre est mauvais format',
'title.unique' => 'Le titre est déja pris',
'langue.in' => '',
'annee' => 'Le format de l année est incorect',
];
}
public function authorize(){
return true;
}
} | true |
67915e69950e090228cd1316de3a0f4a0249bc4e | PHP | jgthms/forest | /madeleine/admin/widgets/videos-widget.php | UTF-8 | 4,119 | 2.5625 | 3 | [] | no_license | <?php
/*-----------------------------------------------------------------------------------
Plugin Name: Madeleine videos Widget
Plugin URI: http://haxokeno.com
Description: A widget that displays a list of your latest videos, with a pagination
Version: 1.0
Author: Haxokeno
Author URI: http://haxokeno.com
-----------------------------------------------------------------------------------*/
// Register the widget
if ( !function_exists( 'madeleine_register_videos_widget' ) ) {
function madeleine_register_videos_widget() {
register_widget( 'madeleine_videos_widget' );
}
}
add_action( 'widgets_init', 'madeleine_register_videos_widget' );
// Create the widget
class madeleine_videos_widget extends WP_Widget {
// Set widget options
function madeleine_videos_widget() {
$widget_ops = array(
'classname' => 'madeleine-videos-widget',
'description' => __( 'A list of your latest videos, with a pagination', 'madeleine' )
);
$control_ops = array(
'width' => 300,
'height' => 350,
'id_base' => 'madeleine_videos_widget'
);
$this->WP_Widget( 'madeleine_videos_widget', 'Madeleine Videos', $widget_ops, $control_ops );
}
// Display the widget
function widget( $args, $instance ) {
extract( $args );
$title = apply_filters('widget_title', $instance['title'] );
$total = $instance['total'];
$args = array(
'post_type' => 'post',
'posts_per_page' => $total,
'tax_query' => array(
array(
'taxonomy' => 'post_format',
'field' => 'slug',
'terms' => array( 'post-format-video' )
)
)
);
$title = 'videos';
$cat = get_query_var('cat'); // If we're in a category archive, only display the videos of that category
if ( $cat != '' ):
$category = get_category( $cat );
$title = $category->name . ' ' . $title;
$args['cat'] = get_query_var('cat');
endif;
$query = new WP_Query( $args );
if ( $query->have_posts() ):
echo $before_widget;
echo '<div id="videos">';
echo $before_title . $title . $after_title;
echo '<ul>';
while ( $query->have_posts() ) {
$query->the_post();
$categories = get_the_category( get_the_ID() );
$category = get_category( madeleine_top_category( $categories[0] ) );
echo '<li class="post format-video category-' . $category->category_nicename . '">';
madeleine_entry_thumbnail( 'medium' );
echo '<p class="entry-title">' . get_the_title() . '</p>';
echo '</li>';
}
echo '</ul>';
echo '<div style="clear: left;"></div>';
if ( $query->post_count > 1 ):
echo '<div id="videos-dots" class="dots">';
echo str_repeat( '<span></span>', $query->post_count );
echo '</div>';
endif;
echo '</div>';
echo $after_widget;
endif;
wp_reset_postdata();
}
// Update the widget when we save it
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance['title'] = strip_tags( $new_instance['title'] );
$instance['total'] = $new_instance['total'];
return $instance;
}
// Display the form in the widgets panel
function form( $instance ) {
// Setup the default values for the widget
$defaults = array(
'title' => __( 'Videos', 'madeleine' ),
'total' => 6,
);
$instance = wp_parse_args( (array) $instance, $defaults );
// Possible options for the select menu
$total_values = array(3, 5, 7);
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:', 'madeleine' ) ?></label>
<input class="widefat" type="text" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo $instance['title']; ?>">
</p>
<p>
<?php _e( 'Display a total of', 'madeleine' ) ?>
<select id="<?php echo $this->get_field_id( 'total' ); ?>" name="<?php echo $this->get_field_name( 'total' ); ?>">
<?php
foreach ( $total_values as $value ):
echo '<option value="' . $value . '"';
if ( $value == $instance['total'] )
echo ' selected="selected"';
echo '">' . $value . '</option>';
endforeach;
?>
</select>
videos
</p>
<?php
}
}
?> | true |
82ebe6d7d335f2985d873a69f22f5958acd7ed9b | PHP | yijie8/shopForSwoft | /app/Services/UtilService.php | UTF-8 | 4,359 | 2.65625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | <?php
namespace App\Services;
use Swoft\Http\Message\Request;
class UtilService
{
/**
* 获取POST请求的数据
* @param $params
* @param null $request
* @param bool $suffix
* @return array
*/
public static function postMore($params, $request = null, $suffix = false)
{
if ($request === null) $request = request();
$p = [];
$i = 0;
foreach ($params as $param) {
if (!is_array($param)) {
$p[$suffix == true ? $i++ : $param] = $request->post($param);
} else {
if (!isset($param[1])) $param[1] = null;
if (!isset($param[2])) $param[2] = '';
$name = is_array($param[1]) ? $param[0] . '/a' : $param[0];
$p[$suffix == true ? $i++ : (isset($param[3]) ? $param[3] : $param[0])] = $request->post($name, $param[1], $param[2]);
}
}
return $p;
}
/**
* 获取请求的数据
* @param $params
* @param null $request
* @param bool $suffix
* @return array
*/
public static function getMore($params, $request = null, $suffix = false)
{
if ($request === null) $request = request();
$p = [];
$i = 0;
foreach ($params as $param) {
if (!is_array($param)) {
$p[$suffix == true ? $i++ : $param] = $request->post($param);
} else {
if (!isset($param[1])) $param[1] = null;
if (!isset($param[2])) $param[2] = '';
$name = is_array($param[1]) ? $param[0] . '/a' : $param[0];
$p[$suffix == true ? $i++ : (isset($param[3]) ? $param[3] : $param[0])] = $request->post($name, $param[1], $param[2]);
}
}
return $p;
}
public static function encrypt($string, $operation = false, $key = '', $expiry = 0)
{
// 动态密匙长度,相同的明文会生成不同密文就是依靠动态密匙
$ckey_length = 6;
// 密匙
$key = md5($key);
// 密匙a会参与加解密
$keya = md5(substr($key, 0, 16));
// 密匙b会用来做数据完整性验证
$keyb = md5(substr($key, 16, 16));
// 密匙c用于变化生成的密文
$keyc = $ckey_length ? ($operation == false ? substr($string, 0, $ckey_length) :
substr(md5(microtime()), -$ckey_length)) : '';
// 参与运算的密匙
$cryptkey = $keya . md5($keya . $keyc);
$key_length = strlen($cryptkey);
// 明文,前10位用来保存时间戳,解密时验证数据有效性,10到26位用来保存$keyb(密匙b),
//解密时会通过这个密匙验证数据完整性
// 如果是解码的话,会从第$ckey_length位开始,因为密文前$ckey_length位保存 动态密匙,以保证解密正确
$string = $operation == false ? base64_decode(substr($string, $ckey_length)) :
sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
$string_length = strlen($string);
$result = '';
$box = range(0, 255);
$rndkey = array();
// 产生密匙簿
for ($i = 0; $i <= 255; $i++) {
$rndkey[$i] = ord($cryptkey[$i % $key_length]);
}
// 用固定的算法,打乱密匙簿,增加随机性,好像很复杂,实际上对并不会增加密文的强度
for ($j = $i = 0; $i < 256; $i++) {
$j = ($j + $box[$i] + $rndkey[$i]) % 256;
$tmp = $box[$i];
$box[$i] = $box[$j];
$box[$j] = $tmp;
}
// 核心加解密部分
for ($a = $j = $i = 0; $i < $string_length; $i++) {
$a = ($a + 1) % 256;
$j = ($j + $box[$a]) % 256;
$tmp = $box[$a];
$box[$a] = $box[$j];
$box[$j] = $tmp;
// 从密匙簿得出密匙进行异或,再转成字符
$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
}
if ($operation == false) {
// 验证数据有效性,请看未加密明文的格式
if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) &&
substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)
) {
return substr($result, 26);
} else {
return '';
}
} else {
// 把动态密匙保存在密文里,这也是为什么同样的明文,生产不同密文后能解密的原因
// 因为加密后的密文可能是一些特殊字符,复制过程可能会丢失,所以用base64编码
return $keyc . str_replace('=', '', base64_encode($result));
}
}
}
| true |
f75b8f49b47923602232107c7f7f9708120f0514 | PHP | Zhouxiaoqing/zphp | /classes/Common/ClassLocator.php | UTF-8 | 364 | 2.578125 | 3 | [] | no_license | <?php
namespace common;
use framework\util\Singleton;
/**
* 获取class实例的工具类
*
* @package service
*
*/
class ClassLocator {
public static function getService($service) {
return Singleton::get("service\\{$service}Service");
}
public static function getDao($dao) {
return Singleton::get("dao\\{$dao}Dao");
}
}
| true |
2f546fad4a7f8d39fa2412783f13620869ef5ea4 | PHP | BreizhTek/IntranetCesi | /controller/ControllerLogin.php | UTF-8 | 1,765 | 2.765625 | 3 | [] | no_license | <?php
//require '/path/to/FlashMessages.php';
require_once "ressources/modele/ModelLogin.php";
class ControllerLogin {
public function index(){
require "./view/login.php";
}
/**
* Function which chek email and password
*/
public function authentification(){
$mail = $_POST['email'];
$password = $_POST['password'];
$checkPass = $this->checkPassword($mail, $password);
//check if email and password are corrects
if ($checkPass){
require_once 'ressources/modele/ModelLogin.php';
$modelLogin = new ModelLogin();
$user_check = $modelLogin->getUserByEmail($mail);
while($row = $user_check->fetch()) {
// redirect to layout with her Identifiant and Level and check if an user's birthday
//Create SESSION
$_SESSION['User_ID'] = $row['Id'];
$_SESSION['Level'] = $row['Level'];
$_SESSION['Last_name'] = $row['Last_name'];
$_SESSION['First_name'] = $row['First_name'];
}
header('Location: /');
exit();
} else {
header('Location: /login');
exit();
}
}
protected function checkPassword($email, $password){
require_once 'ressources/modele/ModelLogin.php';
$modelLogin = new ModelLogin();
$result = $modelLogin->getUserByEmail($email);
// $result = ModelLogin::getUserByEmail($email);
$dbPassword = $result->fetch()['Password'];
if (password_verify($password ,$dbPassword)) {
return true;
} else {
return false;
}
}
} | true |
470b39dae2a9c023c2729a8ddd112b5b99557310 | PHP | ps7is/PokemonGoAPI-PHP | /res/POGOProtos/Networking/Requests/Messages/GetGymDetailsMessage.php | UTF-8 | 6,426 | 2.796875 | 3 | [
"BSD-2-Clause"
] | permissive | <?php
// Generated by https://github.com/bramp/protoc-gen-php// Please include protocolbuffers before this file, for example:
// require('protocolbuffers.inc.php');
// require('POGOProtos/Networking/Requests/Messages/GetGymDetailsMessage.php');
namespace POGOProtos\Networking\Requests\Messages {
use Protobuf;
use ProtobufEnum;
use ProtobufIO;
use ProtobufMessage;
// message POGOProtos.Networking.Requests.Messages.GetGymDetailsMessage
final class GetGymDetailsMessage extends ProtobufMessage {
private $_unknown;
private $gymId = ""; // optional string gym_id = 1
private $playerLatitude = 0; // optional double player_latitude = 2
private $playerLongitude = 0; // optional double player_longitude = 3
private $gymLatitude = 0; // optional double gym_latitude = 4
private $gymLongitude = 0; // optional double gym_longitude = 5
public function __construct($in = null, &$limit = PHP_INT_MAX) {
parent::__construct($in, $limit);
}
public function read($fp, &$limit = PHP_INT_MAX) {
$fp = ProtobufIO::toStream($fp, $limit);
while(!feof($fp) && $limit > 0) {
$tag = Protobuf::read_varint($fp, $limit);
if ($tag === false) break;
$wire = $tag & 0x07;
$field = $tag >> 3;
switch($field) {
case 1: // optional string gym_id = 1
if($wire !== 2) {
throw new \Exception("Incorrect wire format for field $field, expected: 2 got: $wire");
}
$len = Protobuf::read_varint($fp, $limit);
if ($len === false) throw new \Exception('Protobuf::read_varint returned false');
$tmp = Protobuf::read_bytes($fp, $len, $limit);
if ($tmp === false) throw new \Exception("read_bytes($len) returned false");
$this->gymId = $tmp;
break;
case 2: // optional double player_latitude = 2
if($wire !== 1) {
throw new \Exception("Incorrect wire format for field $field, expected: 1 got: $wire");
}
$tmp = Protobuf::read_double($fp, $limit);
if ($tmp === false) throw new \Exception('Protobuf::read_double returned false');
$this->playerLatitude = $tmp;
break;
case 3: // optional double player_longitude = 3
if($wire !== 1) {
throw new \Exception("Incorrect wire format for field $field, expected: 1 got: $wire");
}
$tmp = Protobuf::read_double($fp, $limit);
if ($tmp === false) throw new \Exception('Protobuf::read_double returned false');
$this->playerLongitude = $tmp;
break;
case 4: // optional double gym_latitude = 4
if($wire !== 1) {
throw new \Exception("Incorrect wire format for field $field, expected: 1 got: $wire");
}
$tmp = Protobuf::read_double($fp, $limit);
if ($tmp === false) throw new \Exception('Protobuf::read_double returned false');
$this->gymLatitude = $tmp;
break;
case 5: // optional double gym_longitude = 5
if($wire !== 1) {
throw new \Exception("Incorrect wire format for field $field, expected: 1 got: $wire");
}
$tmp = Protobuf::read_double($fp, $limit);
if ($tmp === false) throw new \Exception('Protobuf::read_double returned false');
$this->gymLongitude = $tmp;
break;
default:
$limit -= Protobuf::skip_field($fp, $wire);
}
}
}
public function write($fp) {
if ($this->gymId !== "") {
fwrite($fp, "\x0a", 1);
Protobuf::write_varint($fp, strlen($this->gymId));
fwrite($fp, $this->gymId);
}
if ($this->playerLatitude !== 0) {
fwrite($fp, "\x11", 1);
Protobuf::write_double($fp, $this->playerLatitude);
}
if ($this->playerLongitude !== 0) {
fwrite($fp, "\x19", 1);
Protobuf::write_double($fp, $this->playerLongitude);
}
if ($this->gymLatitude !== 0) {
fwrite($fp, "!", 1);
Protobuf::write_double($fp, $this->gymLatitude);
}
if ($this->gymLongitude !== 0) {
fwrite($fp, ")", 1);
Protobuf::write_double($fp, $this->gymLongitude);
}
}
public function size() {
$size = 0;
if ($this->gymId !== "") {
$l = strlen($this->gymId);
$size += 1 + Protobuf::size_varint($l) + $l;
}
if ($this->playerLatitude !== 0) {
$size += 9;
}
if ($this->playerLongitude !== 0) {
$size += 9;
}
if ($this->gymLatitude !== 0) {
$size += 9;
}
if ($this->gymLongitude !== 0) {
$size += 9;
}
return $size;
}
public function clearGymId() { $this->gymId = ""; }
public function getGymId() { return $this->gymId;}
public function setGymId($value) { $this->gymId = $value; }
public function clearPlayerLatitude() { $this->playerLatitude = 0; }
public function getPlayerLatitude() { return $this->playerLatitude;}
public function setPlayerLatitude($value) { $this->playerLatitude = $value; }
public function clearPlayerLongitude() { $this->playerLongitude = 0; }
public function getPlayerLongitude() { return $this->playerLongitude;}
public function setPlayerLongitude($value) { $this->playerLongitude = $value; }
public function clearGymLatitude() { $this->gymLatitude = 0; }
public function getGymLatitude() { return $this->gymLatitude;}
public function setGymLatitude($value) { $this->gymLatitude = $value; }
public function clearGymLongitude() { $this->gymLongitude = 0; }
public function getGymLongitude() { return $this->gymLongitude;}
public function setGymLongitude($value) { $this->gymLongitude = $value; }
public function __toString() {
return ''
. Protobuf::toString('gym_id', $this->gymId, "")
. Protobuf::toString('player_latitude', $this->playerLatitude, 0)
. Protobuf::toString('player_longitude', $this->playerLongitude, 0)
. Protobuf::toString('gym_latitude', $this->gymLatitude, 0)
. Protobuf::toString('gym_longitude', $this->gymLongitude, 0);
}
// @@protoc_insertion_point(class_scope:POGOProtos.Networking.Requests.Messages.GetGymDetailsMessage)
}
} | true |
e80a80021a85cd6ccc50c55d0901e82f48036144 | PHP | DanielCsonka987/WFAThesisProject | /WFAThesisProject/ThesisChemoSafeStore/php/logingIn/passwordTester.php | UTF-8 | 565 | 3.1875 | 3 | [] | no_license | <?php
class passwordRevise{
private $writtenPassword;
private $hashedPassword;
public function setPasswordDatas($norm, $hashed){
$this -> writtenPassword = $norm;
$this -> hashedPassword = $hashed;
}
public function verifyPassword(){
if ($this -> writtenPassword == "" || $this -> hashedPassword == ""){
return false;
}
if(password_verify($this -> writtenPassword, $this -> hashedPassword)){
return true;
}else{
return false;
}
}
}
| true |
addd1ca60835cef0fc290828dbbae2002b87c527 | PHP | Sohrab-hossain/Training-Center-Management-System | /client/student_course.php | UTF-8 | 1,810 | 2.53125 | 3 | [] | no_license | <div class="links">
<a href="?p=student_course_new">Enter New Student Course</a>
</div>
<?php
$cn = mysqli_connect("localhost", "root", "", "dbuscoaching");
if(isset($_GET['student']) && isset($_GET['course']))
{
$sql = "delete from student_course where studentId = ".mysqli_real_escape_string($cn, base64_decode($_GET['student'])). " and courseId = ".mysqli_real_escape_string($cn, base64_decode($_GET['course'])) ;
if(mysqli_query($cn, $sql))
{
print '<span class = "successMessage">Student Course Deleted Successfully</span>';
}
else{
print '<span class = "errorMessage">'.mysqli_error($cn).'</span>';
}
}
$sql = " select sc.studentId,sc.courseId, s.name as student, s.email, c.name as course, sc.date, sc.remarks
from student_course as sc
left join student as s on sc.studentId = s.id
left join course as c on sc.courseId = c.id ";
$table = mysqli_query($cn,$sql);
print '<table>';
print '<tr><th>Student</th><th>Email</th><th>Course</th><th>Date</th><th>Remarks</th> <th>#</th></tr>';
while($row = mysqli_fetch_assoc($table))
{
print '<tr>';
print '<td>'.htmlentities($row["student"]).'</td>';
print '<td>'.htmlentities($row["email"]).'</td>';
print '<td>'.htmlentities($row["course"]).'</td>';
print '<td>'.htmlentities($row["date"]).'</td>';
print '<td>'.htmlentities($row["remarks"]).'</td>';
print '<td><a href="?p=student_course_edit&student='.base64_encode($row["studentId"]).'&course='.base64_encode($row["courseId"]).'"><img src="images/edit.png" height="20" title="Edit" alt="Edit"/></a>
|
<a href="?p='.$_GET['p'].'&student='.base64_encode($row["studentId"]).'&course='.base64_encode($row["courseId"]).'"><img src="images/delete01.png" height="20" title="Delete" alt="Delete"></a></td>';
print '</tr>';
}
print '</table>';
?> | true |
890c0ea85f79fa228f5a55c1e45c5ca42b99d091 | PHP | renegare/skip_php_framework | /tests/Skip/Tests/Dummy/TestModel.php | UTF-8 | 286 | 2.734375 | 3 | [] | no_license | <?php
namespace Skip\Tests\Dummy;
class TestModel {
// stub
public function getData() {}
public function setDummyService( TestModel $service ) {
// just called so this can be tested!
$service->getData();
}
} | true |
7b712920fa508dcfc5952193920f18b40663b3cf | PHP | AlejandraGomez1994/SGV | /Modelo/ModEspecieID.php | UTF-8 | 1,715 | 3.015625 | 3 | [
"MIT",
"LicenseRef-scancode-free-unknown"
] | permissive | <?php
class EspecieID
{
private $id;
private $descripcion;
public function __construct($id,$descripcion)
{
$this->descripcion=$descripcion;
$this->id=$id;
}
public function setId($id)
{
$this->id=$id;
}
public function setDescripcion($descripcion)
{
$this->descripcion=$descripcion;
}
public function getId()
{
return $this->id;
}
public function getDescripcion()
{
return $this->descripcion;
}
public static function ListarEspecieID()
{
$listaEspecie =[];
$db=Db::getConnect();
$sql=$db->query('SELECT * FROM especie');
foreach ($sql->fetchAll() as $especie) {
$listaEspecie[]= new EspecieID($especie['id_especie'],$especie['descripcion']);
}
return $listaEspecie;
}
public static function RegistrarTiempo($tiempo)
{
try{
$db=Db::getConnect();
$insert=$db->prepare("INSERT INTO tiempo (descripcion) VALUES('$tiempo->descripcion')");
if($insert->execute())
{
}
else
{
echo "<script language='javascript'>alert('Los cambios no se guardaron')</script>";
}
}catch (Exception $e)
{
echo $e->getmessage();
}
}
public static function BuscarEspecie($id)
{
$listaEspecie=[];
$db=Db::getConnect();
$sql=$db->query("SELECT * FROM especie WHERE =$id");
//asignarlo al objeto producto
$especie=$sql->fetch();
$listaEspecie[]= new EspecieID($especie['id_especie'],$especie['descripcion']);
return $listaEspecie;
}
}
?>
| true |
a44695d08100ab924d24e64bcbd053fb6e4a4ff8 | PHP | vargasgabriel/exercism-tracks | /php/gigasecond/gigasecond.php | UTF-8 | 128 | 2.65625 | 3 | [] | no_license | <?php
function from($date)
{
$new_date = clone($date);
return $new_date->add(new DateInterval('PT1000000000S'));
} | true |
526768f0e8b2daf74fdfa4cec59fc36f3105faaa | PHP | Besmerch123/phone.book | /application/libraries/IDriver.php | UTF-8 | 431 | 2.765625 | 3 | [] | no_license | <?php
namespace application\libraries;
interface IDriver
{
public function __construct($host, $database, $user, $password, $port, $charset);
public function getConnection();
public function find($table, $id = null);
public function insert($table, $data);
public function update($table, $data, $condition, $comparator = 'AND');
public function delete($table, $id);
public function __destruct();
} | true |
a8d4eeb5046929c6e65bd091fa080ba6c5195b5e | PHP | wascasla/voley7 | /app/models/Partido.php | UTF-8 | 2,299 | 2.953125 | 3 | [
"MIT"
] | permissive | <?php
class Partido extends Eloquent { //Todos los modelos deben extender la clase Eloquent
protected $table = 'partido';
protected $fillable = array("fechaPartido","horaPartido","datosPartido","fecha_id","equipoLocal","equipoVisitante","golEquipoLocal","golEquipoVisitante","cargado");
//un partido pertenece a una fecha
public function fecha()
{
return $this->belongsTo('Fecha');
}
public function equipoLocal()
{
return $this->belongsTo('equipo','equipoLocal');//c_id - customer id
}
public function equipoVisitante()
{
return $this->belongsTo('equipo','equipoVisitante');//s_id - staff id
}
public static function agregarPartido($input){
$respuesta = array();
$reglas = array(
'fecha_id' => 'required',
//'nombre' => array('required', 'max:255'),
'equipoLocal' => 'required',
'equipoVisitante' => 'required',
);
$validator = Validator::make($input, $reglas);
if ($validator->fails()){
$respuesta['mensaje'] = $validator;
$respuesta['error'] = true;
}else{
$partido = static::create($input);
$respuesta['mensaje'] = 'Partido creado!';
$respuesta['error'] = false;
$respuesta['data'] = $partido;
}
return $respuesta;
}
public $errors;
//metodos para validar y guardar el partido
public function isValid($data)
{
$rules = array(
'fechaPartido'=> 'required',
'fecha_id' => 'required'
);
$validator = Validator::make($data, $rules);
if ($validator->passes())
{
return true;
}
$this->errors = $validator->errors();
return false;
}
public function validAndSave($data)
{
// Revisamos si la data es válida
if ($this->isValid($data))
{
// Si la data es valida se la asignamos al usuario
$this->fill($data);
// Guardamos la fecha
$this->save();
return true;
}
return false;
}
}
?> | true |
81930df36a8fbc2ddbb65ebc2b32e3145a68345a | PHP | MatheusOliveira10/tccMatheus_Bruno | /controller/LeituraController.php | UTF-8 | 2,077 | 2.515625 | 3 | [] | no_license | <?php
//require "model/query.php";
class LeituraController
{
public function view()
{
$qry = "SELECT assentos.id, passageiros.nome, assentos.posicao, passagens.preco, assentos.PCD, assentos.overbooking FROM assentos INNER JOIN passagens on assentos.id_passagem = passagens.id ";
$qry .= "INNER JOIN passageiros on passagens.id_passageiro = passageiros.id ";
$qry .= " WHERE assentos.id_passagem IS NOT NULL";
$qry .= " ORDER BY assentos.id";
$pdo = new Query();
$reservas = $pdo->select($qry);
include "view/reservas/view.php";
}
public function cadastro()
{
$qry = "SELECT id_passagem FROM assentos ORDER BY id";
$pdo = new Query();
$assentos = $pdo->select($qry);
$qry = "SELECT * FROM passageiros";
$passageiros = $pdo->select($qry);
include "view/reservas/cadastro.php";
}
public function save($request)
{
for ($i = 1; $i <= 26; $i++) {
foreach (range('A', 'D') as $j) {
$cadeira = $i . $j;
if (isset($request[$cadeira])) {
$qry = "INSERT INTO passagens(id_passageiro, preco, pago, data) VALUES (";
$qry .= "'" . $request["passageiro"] . "'";
$qry .= ",";
$qry .= "'" . $request["preco"] . "'";
$qry .= ",";
$qry .= "'N'";
$qry .= ",";
$qry .= "'" . date('yy-m-d') . "'";
$qry .= ")";
$pdo = new Query();
$pdo->insert($qry);
$qry = "SELECT MAX(id) from passagens";
$id = $pdo->select($qry);
$qry = "UPDATE assentos SET id_passagem = " . $id[0][0];
$qry .= " WHERE posicao = '" . $cadeira . "'";
$pdo = new Query();
$pdo->insert($qry);
}
}
}
header("Location: /reserva");
}
}
| true |
e75e8575488e3c8bcd4aac8e5d697aa90b270adf | PHP | Nza6920/FinancialSystem | /app/Http/Requests/AddIncomeRequest.php | UTF-8 | 1,008 | 2.671875 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class AddIncomeRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'money' => 'required|numeric|regex:/^[0-9]+\.?[0-9]{0,9}$/',
'time' => 'required|date_format:Y-m-d',
'address' => 'required',
'type' => 'required',
];
}
public function messages()
{
return [
'money.required' => '金额是必填项.',
'money.numeric' => '金额必须是数字.',
'money.regex' => '金额必须是正数.',
'time.required' => '时间是必填的.',
'time.date_format' => '时间的格式必须是 年-月-日(2018-11-11)',
'address.required' => '地址是必填项.',
'type.required' => '类型是必选项.'
];
}
}
| true |
8181360ae98316942f1705c4999a953eb2b1fc4a | PHP | caduzindev/imoveisBackend | /app/helpers.php | UTF-8 | 431 | 2.59375 | 3 | [] | no_license | <?php
use Image;
use Illuminate\Support\Facades\Storage;
function SaveImageDir($file,$dimension,$dir): string{
$img = Image::make($file);
$resize = $img->fit($dimension)->encode($file->extension());
$hash = md5($resize->__toString().now());
$path = $dir.'/'.$hash.'.'.$file->extension();
$path_file = Storage::disk('public')->put($path,$resize->__toString());
return $hash.'.'.$file->extension();
} | true |
f7e82fa1f249c3b450655dec91e33b66b5dead53 | PHP | munizeverton/crud | /app/View/Funcionarios/index.ctp | UTF-8 | 1,072 | 2.546875 | 3 | [] | no_license | <h1>Funcionários Cadastrados</h1>
<table>
<tr>
<th></th>
<th>Nome</th>
<th>Email</th>
<th>Ação</th>
</tr>
<?php
$cont = 1;
foreach ($funcionarios as $funcionario){ ?>
<tr>
<td><?php echo $cont; $cont++ ?></td>
<td>
<?php echo $this->Html->link($funcionario['Funcionario']['nome'], array('action' => 'view', $funcionario['Funcionario']['id']));?>
</td>
<td><?php echo $funcionario['Funcionario']['email']; ?></td>
<td>
<?php echo $this->Form->postLink(
'Apagar',
array('action' => 'delete', $funcionario['Funcionario']['id']),
array('confirm' => 'Você tem certeza?')
)?>
<?php echo $this->Html->link('Editar', array('action' => 'edit', $funcionario['Funcionario']['id']));?>
</td>
</tr>
<?php }; ?>
</table>
<?php echo $this->Html->link('Cadastrar Funcionário', array('controller' => 'funcionarios', 'action' => 'add')); ?> | true |
8411a71812288cd40fe93c302230f891f0a67c45 | PHP | a285577011/Laravel | /goWhere/02Source/app/Models/FairReservation.php | UTF-8 | 1,308 | 2.59375 | 3 | [] | no_license | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class FairReservation extends Model
{
protected $table = 'fair_reservations';
public $timestamps = false;
/**
* 定义与fair表的关系
*/
public function fairs()
{
return $this->belongsTo('\App\Models\Fair', 'fair_id');
}
/**
* 为指定的展会插入一条预订记录
* @param object $fair
* @param object $request
* @return int
*/
public static function saveReservation($fair, $request)
{
$reservation = new \App\Models\FairReservation();
$reservation->name = \trim($request->input('name'));
$reservation->phone = \trim($request->input('phone'));
$reservation->address = \trim($request->input('address'));
$reservation->email = \trim($request->input('email'));
$reservation->company = \trim($request->input('company'));
$reservation->company_addr = \trim($request->input('company_addr'));
$reservation->num = \intval($request->input('num'));
$reservation->needs = \trim($request->input('needs'));
$reservation->services = \trim($request->input('service'));
$reservation = $fair->fairReservation()->save($reservation);
return $reservation->id;
}
}
| true |
3ae2fff53157f8236be6971217ff943822a039bd | PHP | nathanlesage/Zettlr_old | /app/Http/Controllers/ReferenceController.php | UTF-8 | 9,121 | 2.546875 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Collection;
use App\Http\Requests;
use App\Reference;
use App\Note;
use Validator;
use Storage;
use Illuminate\View\View;
use OpenJournalSoftware\BibtexBundle\Helper\Bibtex;
class ReferenceController extends Controller
{
/**
* Create a new controller instance.
* Use "auth" middleware.
*
* @return void
*/
public function __construct()
{
// Require the user to be logged in
// for every action this controller does
$this->middleware('auth');
}
/**
* Displays an index of all references
*
* @return View List template for references
*/
public function index()
{
$references = Reference::orderBy('author_last', 'asc')->get();
return view('references.list', compact('references'));
}
/**
* Displays a form to create a new reference
*
* @return View Form for adding a new reference
*/
public function getCreate()
{
return view('references.create');
}
/**
* Inserts a new reference
*
* @param Request $request The posted data
* @return RedirectResponse Redirects to reference index
*/
public function postCreate(Request $request)
{
$validator = Validator::make($request->all(), [
'title' => 'required|max:255',
'author_first' => 'required|min:3|max:255',
'author_last' => 'required|min:3|max:255',
'year' => 'required|numeric'
]);
if ($validator->fails()) {
return redirect('/references/create')
->withErrors($validator)
->withInput();
}
// Begin insertion
$reference = new Reference();
$reference->title = $request->title;
$reference->author_first = $request->author_first;
$reference->author_last = $request->author_last;
$reference->year = $request->year;
$reference->reference_type = $request->reference_type;
$reference->save();
return redirect('/references/index');
}
/**
* Displays a form with the reference data prefilled
*
* @param integer $id Corresponds to the database column id
* @return View Returns a view with reference data
*/
public function getEdit($id)
{
if(!$id || $id <= 0)
return redirect(url('/references/index'));
$reference = Reference::find($id);
return view('references.edit', compact('reference'));
}
/**
* Updates a reference in the database
*
* @param Request $request Data to be updated
* @param integer $id Corresponds to the database column id
* @return RedirectResponse Redirects depending on validation
*/
public function postEdit(Request $request, $id)
{
if(!$id || $id <= 0)
return redirect(url('/references/index'));
$validator = Validator::make($request->all(), [
'title' => 'required|max:255',
'author_first' => 'required|min:3|max:255',
'author_last' => 'required|min:3|max:255',
'year' => 'required|numeric'
]);
if ($validator->fails()) {
return redirect('/references/edit/'.$id)
->withErrors($validator)
->withInput();
}
$reference = Reference::find($id);
$reference->title = $request->title;
$reference->author_first = $request->author_first;
$reference->author_last = $request->author_last;
$reference->year = $request->year;
$reference->reference_type = $request->reference_type;
$reference->save();
return redirect('/references/index');
}
/**
* Removes a record from the database table
*
* @param integer $id Corresponds to the id-column
* @return RedirectResponse Redirects
*/
public function delete($id)
{
if(!$id || $id <= 0)
return redirect(url('/references/index'));
$ref = Reference::find($id);
$ref->notes()->detach();
$ref->outlines()->detach();
$ref->delete();
return redirect('/references/index');
}
/**
* Displays a form to import references from a *.bib-file
*
* @return View Returns an empty form
*/
public function getImport()
{
// Display a view and let the Ajax-controller again handle the file collection
$dummyRef = new Reference();
return view('references.form', ["types" => $dummyRef->getTypes()]);
}
/**
* Displays a results page to check the import status
*
* @return mixed Depending on validation redirects or view
*/
public function getConfirm()
{
// Check if files have been uploaded
$store = Storage::disk('local');
$files = $store->files('bibtex');
if(count($files) <= 0)
return redirect('/references/import')->withErrors(['content' => 'Please upload something to import!']);
// Now loop through all found files and extract the notes
$references = new Collection();
$bibtex = new Bibtex();
$omitted = [];
foreach($files as $file)
{
$filecontents = $store->get($file);
$ret = $bibtex->loadString($store->get($file));
$bibtex->parse();
// Okay, the bibtex-data looks nice. So for now let's only fill the
// already migrated fields: title, year, author_last, author_first, reference_type
foreach($bibtex->data as $index => $entry)
{
$ref = new Reference();
// Convert entryTypes if necessary
switch($entry['entryType'])
{
case "article": $entry['entryType'] = "journal article"; break;
case "conference": $entry['entryType'] = "conference paper"; break;
case "inbook": $entry['entryType'] = "book section"; break;
case "masterthesis": $entry['entryType'] = "thesis"; break;
case "phdthesis": $entry['entryType'] = "thesis"; break;
case "techreport": $entry['entryType'] = "report"; break;
}
// Can we store this datatype?
if(!$ref->typeAllowed($entry['entryType']))
{
$omitted[$index]['reason'] = 'Entry type incompatible with database';
continue;
}
// Is anything empty? Then also omit
if(!isset($entry['title']) || strlen($entry['title']) <= 0)
{
$omitted[$index]['reason'] = 'Title missing';
continue;
}
if(!isset($entry['year']) || strlen($entry['year']) <= 0)
{
$omitted[$index]['reason'] = 'Year missing';
continue;
}
if(!isset($entry['author']) || strlen($entry['author'][0]['last']) <= 0)
{
$omitted[$index]['reason'] = 'Author last name missing';
continue;
}
if(!isset($entry['author']) || strlen($entry['author'][0]['first']) <= 0)
{
$omitted[$index]['reason'] = 'Author first name missing';
continue;
}
$entry['title'] = str_replace(["{", "}"], "", $entry['title']);
$bibtex->data[$index]['title'] = $entry['title'];
$ref->title = $entry['title'];
$ref->year = $entry['year'];
$ref->author_last = $entry['author'][0]['last'];
$ref->author_first = $entry['author'][0]['first'];
$ref->reference_type = $ref->getTypeKey($entry['entryType']);
// Create or, if it exists, omit
Reference::firstOrCreate($ref->toArray());
/*
* Accordding to the BibTex people these entries are allowed:
* Everything with NULL hasn't been implemented yet
* 'article', -> "journal article"
* 'book', -> book
* 'booklet', -> NULL
* 'confernce', -> conference paper
* 'inbook', -> book section
* 'incollection', -> NULL
* 'inproceedings', -> NULL
* 'manual', -> NULL
* 'mastersthesis', -> thesis
* 'misc', -> NULL
* 'phdthesis', -> thesis
* 'proceedings', -> NULL
* 'techreport', -> report
* 'unpublished' -> NULL
*/
}
}
// Clear the uploaded files before exiting
$store->delete($files);
return view('references.confirm', ['bibtex' => $bibtex->data, 'omitted' => $omitted]);
}
}
| true |
50cf71cafec3df1d236d887bbbeb38f1383b40ac | PHP | DeepakZelite/Research | /app/Repositories/Company/EloquentCompany.php | UTF-8 | 7,150 | 2.546875 | 3 | [] | no_license | <?php
namespace Vanguard\Repositories\Company;
use Vanguard\Company;
use Carbon\Carbon;
class EloquentCompany implements CompanyRepository
{
public function __construct()
{
}
/**
* {@inheritdoc}
*/
public function find($id)
{
return Company::find($id);
}
/*public function findByBatch($batch_id)
{
return Company::find($batch_id);
}
/**
* {@inheritdoc}
*/
public function findByName($name)
{
return Company::where('name', $name)->first();
}
/**
* {@inheritdoc}
*/
public function create(array $data)
{
return Company::create($data);
}
/**
* {@inheritdoc}
*/
public function paginate($perPage, $search = null, $parentId = null)
{
$query = Company::query();
if ($search) {
$query->where(function ($q) use($search) {
$q->where('company_name', "like", "%{$search}%");
});
}
$result = $query->where("parent_id", "=", $parentId)->paginate($perPage);
if ($search) {
$result->appends(['search' => $search]);
}
$result->appends(['parent_id' => $parentId]);
return $result;
}
/**
* {@inheritdoc}
*/
public function update($id, array $data)
{
return $this->find($id)->update($data);
}
/**
* {@inheritdoc}
*/
public function delete($id)
{
$company = $this->find($id);
return $company->delete();
}
/**
* {@inheritdoc}
*/
public function count()
{
return Company::count();
}
/**
* {@inheritdoc}
*/
public function getUnAssignedCount($batchId)
{
$query = Company::query();
if ($batchId != 0) {
$query->where(function ($q) use($batchId) {
$q->where('companies.batch_id', "=", "{$batchId}")
->whereNull('sub_batch_id');
});
} else {
return 0;
}
$result = $query->count();
return $result;
}
/**
* {@inheritdoc}
*/
public function getTotalCompanyCount($batchId)
{
$query = Company::query();
if ($batchId != 0) {
$query->where(function ($q) use($batchId) {
$q->where('companies.batch_id', "=", "{$batchId}");
});
} else {
return 0;
}
$result = $query->count();
return $result;
}
/**
* {@inheritdoc}
*/
public function lists($column = 'name', $key = 'id')
{
return Company::lists($column, $key);
}
/**
* {@inheritdoc}
*/
public function newCompanysCount()
{
return Company::whereBetween('created_at', [Carbon::now()->firstOfMonth(), Carbon::now()])
->count();
}
/**
* {@inheritdoc}
*/
public function latest($count = 20)
{
return Company::orderBy('created_at', 'DESC')
->limit($count)
->get();
}
/**
* {@inheritdoc}
*/
public function getCompanyRecord($subBatchId, $userId)
{
$query = Company::query();
if ($subBatchId != 0) {
$query = $query->where(function ($q) use($subBatchId, $userId) {
$q->where('companies.sub_batch_id', "=", "{$subBatchId}")
->where('companies.user_id', "=", "{$userId}")
->where('companies.status', "=", "Assigned");
});
} else {
return 0;
}
$result = $query->orderBy('companies.updated_at', 'desc')->limit(1)->get();
//$result = $query->orderBy('companies.parent_id', 'desc')->limit(1)->get();
return $result;
}
/**
* {@inheritdoc}
*/
public function getCompaniesForBatch($batchId, $limit)
{
$query = Company::query();
if ($batchId != 0) {
$query->where(function ($q) use($batchId) {
$q->where('companies.batch_id', "=", "{$batchId}")
->where('companies.status', "=", "UnAssigned")
->orderBy('id', 'ASC');
});
} else {
return 0;
}
$result = $query->limit($limit)->get();
return $result;
}
/**
* {@inheritdoc}
* /
*/
public function getCompaniesForSubBatchDelete($batchId)
{
$query = Company::query();
if ($batchId != 0) {
$query->where(function ($q) use($batchId) {
$q->where('companies.sub_batch_id', "=", "{$batchId}")
->orderBy('id', 'ASC');
});
} else {
return 0;
}
$result = $query->get();
return $result;
}
/**
* {@inheritdoc}
*/
public function getSubmittedCompanyCount($batchId)
{
$query = Company::query();
if ($batchId != 0) {
$query->where(function ($q) use($batchId) {
$q->where('companies.batch_id', "=", "{$batchId}");
$q->where('companies.status',"=","Submitted");
});
} else {
return 0;
}
$result = $query->count();
return $result;
}
/**
* {@inheritDoc}
* @see \Vanguard\Repositories\Company\CompanyRepository::getTotalCompany()
*/
public function getTotalCompany($batchId)
{
$query = Company::query();
$result = $query
->leftjoin('contacts', 'companies.id', '=', 'contacts.company_id')
->select('companies.*','contacts.*','contacts.additional_info1 as info1','contacts.additional_info2 as info2','contacts.additional_info3 as info3','contacts.additional_info4 as info4');
if ($batchId != 0) {
$query->where(function ($q) use($batchId) {
$q->where('companies.batch_id', "=", "{$batchId}");
});
} else {
return 0;
}
$result = $query->get();
return $result;
}
/**
*
* {@inheritDoc}
* @see \Vanguard\Repositories\Company\CompanyRepository::getChildCompanies()
*/
public function getChildCompanies($parentId)
{
return Company::where('parent_id', $parentId)->get();//lists('company_name','id');
}
public function getcompanies($batchId)
{
$query = Company::query();
if ($batchId != 0) {
$query->where(function ($q) use($batchId) {
$q->where('companies.batch_id', "=", "{$batchId}");
});
} else {
return 0;
}
$result = $query->select('id')->get();
return $result;
}
public function getCompaniesForProductivityReport($vendorId = null,$userId = null)
{
$query = Company::query();
if($vendorId)
{
$query->where('companies.vendor_id',"=","{$vendorId}");
}
if($userId)
{
$query->where('companies.user_id',"=","{$userId}");
}
$result=$query->where('status',"=","Submitted")
->count();
return $result;
}
public function getcompaniesforReport($vendorId = null,$userId = null)
{
$query = Company::query();
if ($vendorId)
{
$query->where('companies.vendor_id', "=", "{$vendorId}");
}
if($userId)
{
$query->where('$companies.user_id',"=","{$userId}");
}
$result = $query->select('id')->get();
return $result;
}
} | true |
f960a04ab2be1b66aa0aef487b5e8cf2ec54f8cb | PHP | AyakaNomura/tourapps | /app/User.php | UTF-8 | 1,866 | 2.59375 | 3 | [
"MIT"
] | permissive | <?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
public function tours()
{
return $this->belongsToMany(Tour::class, 'user_tours', 'user_id', 'tour_id')->withPivot('type')->withTimestamps();
}
public function join_tours()
{
return $this->tours()->where('type', 'join');
}
public function join($tourId)
{
// 既に 参加 しているかの確認
$exist = $this->is_joining($tourId);
if ($exist) {
// 既に 参加 していれば何もしない
return false;
} else {
// 未 参加 であれば 参加 する
$this->tours()->attach($tourId, ['type' => 'join']);
return true;
}
}
public function dont_join($tourId)
{
// 既に 参加 しているかの確認
$exist = $this->is_joining($tourId);
if ($exist) {
// 既に 参加 していれば 参加 を外す
\DB::delete("DELETE FROM user_tours WHERE user_id = ? AND tour_id = ? AND type = 'join'", [\Auth::user()->id, $tourId]);
} else {
// 未 参加 であれば何もしない
return false;
}
}
public function is_joining($tourId)
{
$user = \App\User::find($tourId);
return $this->tours()->where('tour_id', $tourId)->exists();
return $user;
}
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
| true |
79f6ab96eeff4b1a003cc61dc68a48a4cfa9e997 | PHP | bernardxf/wodstormapp | /src/Crossfit/Dados/AgrupadorFinanceiro.php | UTF-8 | 503 | 2.5625 | 3 | [] | no_license | <?php
namespace Crossfit\Dados;
use Crossfit\Conexao;
use Crossfit\App;
class AgrupadorFinanceiro
{
public static function retornaTodos()
{
$sql = "SELECT * from agrupador_financeiro where id_organizacao = ?";
$resultado = Conexao::get()->fetchAll($sql, array(App::getSession()->get('organizacao')));
return $resultado;
}
public static function salvaAgrupador($agrupadorDataset)
{
$resultado = Conexao::get()->insert('agrupador_financeiro', $agrupadorDataset);
return $resultado;
}
} | true |
596666b19c1b1af76ff3394499155be5653398a2 | PHP | BackupYM/MyRepositoryGit | /includes/pages/user/registerUser.php | UTF-8 | 2,754 | 2.71875 | 3 | [] | no_license | <?php
//Vérifie qu'il est administrateur
confirm_is_admin();
if (isset($_POST['submit']))
{
$name = $_POST['name'];
$first_name = $_POST['first_name'];
$username = $_POST['username'];
$password = $_POST['password'].'?$#à9';
$query = "INSERT INTO users (user_name, user_firstname, username, password) VALUES (?, ?, ?, SHA(?))";
$statement = $databaseConnection->prepare($query);
$statement->bind_param('ssss', $name, $first_name, $username, $password);
$statement->execute();
$statement->store_result();
$creationWasSuccessful = $statement->affected_rows == 1 ? true : false;
if ($creationWasSuccessful)
{
$userId = $statement->insert_id;
$addToUserRoleQuery = "INSERT INTO users_in_roles (user_id, role_id) VALUES (?, ?)";
$addUserToUserRoleStatement = $databaseConnection->prepare($addToUserRoleQuery);
// TODO: Extract magic number for the 'user' role ID.
$userRoleId = 2;
$addUserToUserRoleStatement->bind_param('dd', $userId, $userRoleId);
$addUserToUserRoleStatement->execute();
$addUserToUserRoleStatement->close();
header ("Location:".$_SESSION['pageBefor']);
}
else
{
echo "Failed registration";
}
}
?>
<!-- HTML -->
<div id="main">
<h2>Register an account</h2>
<form action="<?php echo $_SERVER['REQUEST_URI'];?>" method="post">
<fieldset>
<legend>Register an account</legend>
<ol>
<li>
<label for="name">Name:</label>
<input type="text" name="name" value="" id="name" />
</li>
<li>
<label for="first_name">First name:</label>
<input type="text" name="first_name" value="" id="first_name" />
</li>
<li>
<label for="username">Username:</label>
<input type="text" name="username" value="" id="username" />
</li>
<li>
<label for="password">Password:</label>
<input type="password" name="password" value="" id="password" />
</li>
</ol>
<input type="submit" name="submit" value="Submit" />
<p>
<a href="<?php echo $_SESSION['pageBefor']; ?>">Cancel</a>
</p>
</fieldset>
</form>
</div>
</div> <!-- End of outer-wrapper which opens in header.php --> | true |
7e9b7ec4ec836b4bb4c388a863b61b114f7f57d7 | PHP | 00F100/fcphp-shttp | /src/SEntity.php | UTF-8 | 7,128 | 3.140625 | 3 | [
"MIT"
] | permissive | <?php
namespace FcPhp\SHttp
{
use FcPhp\SHttp\Interfaces\ISEntity;
class SEntity implements ISEntity
{
/**
* @var array Types available to login
*/
private $types = [
null => 'guest',
1 => 'admin',
2 => 'user',
];
/**
* @var string Id of login
*/
private $id = null;
/**
* @var string Name of login
*/
private $name = null;
/**
* @var string E-mail of login
*/
private $email = null;
/**
* @var string User name of login
*/
private $username = null;
/**
* @var string Type of login
*/
private $type = null;
/**
* @var string Permissions of login
*/
private $permissions = [];
/**
* @var string Custom data of login
*/
private $customData = [];
/**
* @var string Errors of login
*/
private $error = [];
/**
* @var strint Timestamp created
*/
private $created;
/**
* @var int Timestamp expires
*/
private $expires;
/**
* Method to construct instance of Security Entity
*
* @param int $expires Timestamp expires Security Entity
* @return void
*/
public function __construct(int $expires = 84000)
{
$this->created = time();
$this->expires = $expires;
$this->expires = $this->created + $this->expires;
}
/**
* Method to set Id of login
*
* @param string $id Id of login
* @return cPhp\SHttp\Interfaces\ISEntity
*/
public function setId(string $id) :ISEntity
{
$this->id = $id;
return $this;
}
/**
* Method to get Id of login
*
* @return string|null
*/
public function getId()
{
return $this->id;
}
/**
* Method to set Name of login
*
* @param string $name Name of login
* @return cPhp\SHttp\Interfaces\ISEntity
*/
public function setName(string $name) :ISEntity
{
$this->name = $name;
return $this;
}
/**
* Method to get Name of login
*
* @return string|null
*/
public function getName()
{
return $this->name;
}
/**
* Method to set E-mail of login
*
* @param string $email E-mail of login
* @return cPhp\SHttp\Interfaces\ISEntity
*/
public function setEmail(string $email) :ISEntity
{
$this->email = $email;
return $this;
}
/**
* Method to get E-mail of login
*
* @return string|null
*/
public function getEmail()
{
return $this->email;
}
/**
* Method to set User name of login
*
* @param string $username User name of login
* @return cPhp\SHttp\Interfaces\ISEntity
*/
public function setUsername(string $username) :ISEntity
{
$this->username = $username;
return $this;
}
/**
* Method to get User name of login
*
* @return string|null
*/
public function getUsername()
{
return $this->username;
}
/**
* Method to set Type of login
*
* @param string|int $type Type of login
* @return cPhp\SHttp\Interfaces\ISEntity
*/
public function setType($type) :ISEntity
{
array_walk($this->types, function($name, $index) use ($type) {
if($type === $name){
$this->type = $index;
}
});
if(is_null($this->type)) {
if(isset($this->types[$type])) {
$this->type = $type;
}
}
return $this;
}
/**
* Method to get Type of login
*
* @return string
*/
public function getType() :string
{
return $this->types[$this->type];
}
/**
* Method to set Permissions of login
*
* @param array $permissions Permissions of login
* @return cPhp\SHttp\Interfaces\ISEntity
*/
public function setPermissions(array $permissions) :ISEntity
{
$this->permissions = $permissions;
return $this;
}
/**
* Method to get Permissions of login
*
* @return array
*/
public function getPermissions() :array
{
return $this->permissions;
}
/**
* Method to set Custom data of login
*
* @param string $key Key to save content
* @param array|string $customData Data to save
* @return cPhp\SHttp\Interfaces\ISEntity
*/
public function setCustomData(string $key, $customData) :ISEntity
{
array_dot($this->customData, $key, $customData);
return $this;
}
/**
* Method to get Custom data of login
*
* @param string|null $key Key to find content
* @return array|null
*/
public function getCustomData(string $key = null)
{
return array_dot($this->customData, $key);
}
/**
* Method to check if have access to permission
*
* @param string $permission Permission to check
* @return bool
*/
public function check(string $permission) :bool
{
return ('admin' === $this->types[$this->type] || in_array($permission, $this->permissions));
}
/**
* Method to set Errors of login
*
* @param string $message Message of error
* @return cPhp\SHttp\Interfaces\ISEntity
*/
public function setError(string $message) :ISEntity
{
$this->error[] = $message;
return $this;
}
/**
* Method to get Errors of login
*
* @return array
*/
public function getError() :array
{
return $this->error;
}
/**
* Method to check if have errors in login
*
* @return bool
*/
public function haveErrors() :bool
{
return count($this->error) > 0;
}
/**
* Method to check if this Security Entity has expired
*
* @return bool
*/
public function isExpired() :bool
{
return ($this->expires < time());
}
}
} | true |
a1dc1d8e1ce23aae6c7695e885d308c33c8b8cdf | PHP | flamisz/music-streaming | /app/DataTransferObjects/StoreLikesData.php | UTF-8 | 681 | 2.65625 | 3 | [] | no_license | <?php
namespace App\DataTransferObjects;
use App\Actions\DeleteOldLikesAction;
use App\DataTransferObjects\LikeData;
use App\Http\Requests\StoreLikeRequest;
use Spatie\DataTransferObject\DataTransferObject;
class StoreLikesData extends DataTransferObject
{
/** @var \App\DataTransferObjects\LikeData[] */
public array $likes = [];
public static function fromRequest(StoreLikeRequest $request): StoreLikesData
{
$likesArray = $request->input('likes');
$likes = [];
foreach ($likesArray as $like) {
$likes[] = LikeData::fromArray($like);
}
return new self([
'likes' => $likes,
]);
}
}
| true |
41eb0c53ce88c60df23b982b2c628eaf0850ba15 | PHP | hynner/glotr-sync | /services/users.php | UTF-8 | 1,815 | 2.828125 | 3 | [
"MIT"
] | permissive | <?php
class users extends base
{
protected $tblName = "users";
protected $idField = "id_user";
public function login($name, $password)
{
$name = $this->container["database"]->escape($name);
$ret = $this->container["database"]->queryAndFetch("select * from $this->tblName where username = '$name' and active = 1");
if(empty($ret))
return false;
else
{
$usr = $ret[0];
if($usr["password"] == crypt($password, $usr["password"]))
{
unset($usr["password"]);
$this->container["user"] = $usr;
$this->container["persistent"]["user_logged"] = $usr["id_user"];
return true;
}
return false;
}
}
public function logout()
{
$this->container["user"] = false;
$this->container["persistent"]["user_logged"] = false;
}
public function register($name, $passwd, $passwd2)
{
$error = false;
if($passwd != $passwd2)
return "Passwords don´t match!";
$count = (int) $this->count();
if($count === 0)
{
$active = "1";
}
else
{
$active = "0";
}
$name = $this->container["database"]->escape($name);
$res = $this->container["database"]->query("insert into $this->tblName set username = '$name', password='".crypt($passwd)."', active = $active");
if($res === TRUE)
return $error;
return "Username already exists!";
}
public function toggleActive($id_user)
{
$id_user = (int) $id_user;
return $this->container["database"]->query("update $this->tblName set active = ABS(active-1) where $this->idField = $id_user");
}
}
| true |
6944a688af4a7ce4f4528d9874d34b92d5510197 | PHP | djkost85/ngn | /ngn/lib/more/stm/StmDataManager.class.php | UTF-8 | 5,458 | 2.5625 | 3 | [] | no_license | <?php
class StmDataManager extends DataManagerAbstract {
/**
* type - для имен классов
* subType - для папок
*/
protected $requiredOptions = array('type', 'subType', 'location');
public function __construct(array $options = array()) {
$this->setOptions($options);
parent::__construct(new Form(
new Fields($this->convertFields()),
array('filterEmpties' => true)
));
}
/**
* @return StmData
*/
public function getStmData(array $options = array()) {
// здесь нужен ID
return O::get(
'Stm'.ucfirst($this->options['type']).'Data',
O::get(
'StmDataSource',
$this->options['location']
),
array_merge($this->options, $options)
);
}
protected function convertFields() {
$fields = array();
$names = array();
foreach ($this->getStmData()->getStructure()->str['fields'] as $v) {
if (!isset($v['name']) and isset($v['s'])) {
if (empty($v['p'])) throw new EmptyException('$v[p]');
$v['name'] = $this->getFieldNameByCssData($v);
if (in_array($v['name'], $names))
throw new NgnException("{$v['name']} alredy in use. v: ".getPrr($v));
$names[] = $v['name'];
}
$fields[] = $v;
}
return $fields;
}
protected function convertCssDataToFormFormat(array $data) {
$r = array();
foreach ($data as $v) {
if (!is_array($v) or !isset($v['s'])) continue;
$r[$this->getFieldNameByCssData($v)] =
str_replace(' !important', '', $v['v']);
}
return $r;
}
const PARAMS_DELIMITER = ' & ';
protected function getFieldNameByCssData(array $v) {
if (!empty($v['pGroup'])) {
$pp = $v['pGroup'];
} else {
// Если параметр групповой, берём для имени только первый
$params = explode(self::PARAMS_DELIMITER, $v['p']);
$pp = $params[0];
}
return Misc::parseId($v['s']).'_'.Misc::parseId($pp);
}
protected function getItem($id) {
return $this->getStmData(array('id' => $id))->data;
}
protected function beforeCreate() {
$this->data = array_merge(array(
'siteSet' => $this->options['siteSet'],
'design' => $this->options['design']
), $this->data);
}
protected function _create() {
return $this->getStmData(array_merge($this->options, array('new' => true)))->
setData($this->data)->save()->id;
}
protected function beforeUpdate() {
$o = $this->getStmData(array('id' => $this->id));
$this->data = array_merge(array(
'siteSet' => $o->data['siteSet'],
'design' => $o->data['design']
), $this->data);
}
protected function _update() {
$this->getStmData(array('id' => $this->id))->setData($this->data)->save();
}
protected function _delete() {
$this->getStmData(array('id' => $this->id))->delete();
}
protected function source2formFormat() {
$this->defaultData = array_merge(
$this->convertCssDataToFormFormat(empty($this->defaultData['cssData']) ?
array() : $this->defaultData['cssData']
),
empty($this->defaultData['data']) ? array() : $this->defaultData['data']
);
}
protected function form2sourceFormat() {
$r = array();
foreach ($this->data as $name => $v) {
if (empty($this->oForm->getElement($name)->options['s'])) {
$r['data'][$name] = $v;
} else {
$el = $this->oForm->getElement($name);
$params = explode(self::PARAMS_DELIMITER, $el->options['p']);
if (count($params) > 1) {
$pGroup = $params[0];
foreach ($params as $p) {
$r['cssData'][] = array(
's' => $el->options['s'],
'p' => $p,
'pGroup' => $pGroup,
'v' => $v.(!empty($el->options['important']) ? ' !important' : '')
);
}
} else {
$r['cssData'][] = array(
's' => $el->options['s'],
'p' => $params[0],
'v' => $v.(!empty($el->options['important']) ? ' !important' : '')
);
}
}
}
$this->data = $r;
}
public function updateField($id, $fieldName, $value) {
if ($this->oForm->oFields->isFileType($fieldName)) $value = basename($value); // подстановка путей происходит динамически
$o = $this->getStmData(array('id' => $id));
$o->data['data'][$fieldName] = $value;
$o->save();
}
public function setDataValue($bracketName, $value) {
BracketName::setValue($this->data['data'], $bracketName, $value);
}
public function updateFileCurrent($file, $fieldName) {
$attachePath = $this->getAttachePath();
$filename = $this->getAttacheFilename($fieldName);
Dir::make($attachePath);
copy($file, $attachePath.'/'.$filename);
$this->updateField($this->options['id'], $fieldName, $filename);
}
public function requestUpdateCurrent() {
return $this->requestUpdate($this->options['id']);
}
public function getAttacheFolder() {
return $this->getStmData()->getThemeWpath().'/'.StmCss::FOLDER_NAME.'/'.
$this->getStmData()->getName();
}
public function getAttachePath() {
return $this->getStmData()->getThemePath().'/'.StmCss::FOLDER_NAME.'/'.
$this->getStmData()->getName();
}
protected function afterUpdate() {
SFLM::clearJsCssCache();
}
}
| true |
89b66a2ec6298e03b9f1977b1ab6f5bce980a10f | PHP | antonday07/1909ePHP | /Day15(PHP)/001/index3.php | UTF-8 | 726 | 3.3125 | 3 | [] | no_license | <!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Php first 1</title>
</head>
<body>
<pre>
Học về biến (variables) trong PHP
trong PHP nối chuối dùng dấu chấm
</pre>
<?php
/**
* Created by PhpStorm.
* User: FR
* Date: 11/21/2019
* Time: 6:35 PM
*/
$a = 5;
$b = 2;
echo "<br> Tổng: " . ($a + $b);
echo "<br> Hiệu: " . ($a - $b);
echo "<br> Tích: " . ($a * $b);
echo "<br> Thương: " . ($a / $b);
echo "<br> Dư: " . ($a % $b);
?>
</body>
</html>
| true |
700b25ca4ecd6e085ff2c2065cad73c32fef3c9e | PHP | symplely/http2 | /src/UpgradeStream.php | UTF-8 | 2,068 | 2.796875 | 3 | [
"MIT"
] | permissive | <?php
/*
* This file is part of Concurrent PHP HTTP.
*
* (c) Martin Schröder <m.schroeder2007@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types = 1);
namespace Concurrent\Http;
use Concurrent\Network\SocketStream;
use Concurrent\Stream\ReadableStream;
use Concurrent\Stream\WritableStream;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
class UpgradeStream implements ReadableStream, WritableStream
{
protected $request;
protected $response;
protected $socket;
protected $buffer;
public function __construct(RequestInterface $request, ResponseInterface $response, SocketStream $socket, string $buffer = '')
{
$this->request = $request;
$this->response = $response;
$this->socket = $socket;
$this->buffer = $buffer;
}
public function __destruct()
{
$this->socket->close();
}
public function getProtocol(): string
{
return \strtolower($this->response->getHeaderLine('Upgrade'));
}
public function getResponse(): ResponseInterface
{
return $this->response;
}
public function getSocket(): SocketStream
{
return $this->socket;
}
/**
* {@inheritdoc}
*/
public function close(?\Throwable $e = null): void
{
$this->socket->close($e);
$this->buffer = '';
}
/**
* {@inheritdoc}
*/
public function read(?int $length = null): ?string
{
if ($this->buffer === '') {
$this->buffer = $this->socket->read();
if ($this->buffer === '') {
return null;
}
}
$chunk = \substr($this->buffer, 0, $length ?? 8192);
$this->buffer = \substr($this->buffer, \strlen($chunk));
return $chunk;
}
/**
* {@inheritdoc}
*/
public function write(string $data): void
{
$this->socket->write($data);
}
}
| true |
6185b225de6c6a9114143d64163446c3d42f30cd | PHP | Joker-Peng/TheDocsOfJob | /algorithm/selection_sort.php | UTF-8 | 1,251 | 3.734375 | 4 | [] | no_license | <?php
/**
* 选择排序
* @authors Joker (njfupl@foxmail.com)
* @date 2017-10-22 11:48:15
*
* 一种简单直观的排序算法。它的工作原理是每一次从待排序的数据元素中选出最小(或最大)的一个元素,存放在序列的起始位置,
* 然后,再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。
* 以此类推,直到全部待排序的数据元素排完。
* 选择排序是不稳定的排序方法。
*
* 时间复杂度: O(n*n)
*
* 实现数组的升序
*/
echo "<pre>";
function selectionSort(&$arr){
for ($i=0; $i < count($arr)-1; $i++) {
$min = $arr[$i];// 数组最小的元素
$minIndex = $i;// 数组最小的元素下标
for ($j=$i+1; $j <count($arr) ; $j++) {
if ($arr[$j]<$min) {
$min = $arr[$j];// 找出最小的元素
$minIndex = $j;// 最小元素的下标
}
}
list($arr[$i],$arr[$minIndex]) = [$min,$arr[$i]];
// $tmp = $arr[$i];
// $arr[$i] = $min; // 之前的$arr[$i]要重新赋值
// $arr[$minIndex] = $tmp; // 之前的$arr[$j]也要重新赋值;
}
}
$arr = [1,4,3,2,3,4,6,7,3,5,7,4,7,1];
selectionSort($arr);
var_dump($arr);
| true |
ec84cae569c99fa6ab067d3a0e23c248fcd40483 | PHP | Shamyyoun/GPSTrackingAPIs | /get_vehicles.php | UTF-8 | 1,335 | 2.8125 | 3 | [] | no_license | <?php
require_once 'connection.php';
// change content type to json
header('Content-type: application/json');
if (isset($_GET['username'])) {
// escape sql statements from parameters
$username = mysql_real_escape_string($_GET['username']);
// validate required inputs
if (empty($username)) {
echo "error";
return;
}
// inputs in final form
$username = strip_tags($username);
// prepare sql statement
$sql = "SELECT * FROM vehicles WHERE user_id = '$username'";
// execute query
$result = mysql_query($sql);
mysql_close($con);
// get vehicles
$vehicles = array();
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$vehicle = array(
'id' => $row['id'],
'password' => $row['password'],
'name' => $row['name'],
'purpose' => $row['purpose'],
'licence_number' => intval($row['licence_number']),
'number' => intval($row['number']),
'color' => $row['color'],
'year' => intval($row['year']),
'model' => $row['model'],
'brand' => $row['brand'],
'lat' => doubleval($row['lat']),
'lng' => doubleval($row['lng']),
'trip_status' => intval($row['trip_status'])
);
$vehicles[] = $vehicle;
}
}
echo json_encode($vehicles);
} else {
echo "error";
}
?> | true |
d5d113d349060be4abb02d62fe236172a9f4af25 | PHP | hoanganf/pos-local-api | /src/models/dao/OrderDAO.php | UTF-8 | 2,910 | 2.625 | 3 | [] | no_license | <?php
class OrderDAO extends BaseDAO{
function __construct(){
parent::__construct("`order`");
}
//getOrderListByArea
function getOrderListGroupByTableInArea($area_id=-1){
$sql=null;
if($area_id>0){
$sql='SELECT o.*,t.name as table_name, sum(o.count) as count_sum,sum(o.price) as price_sum FROM `order` o INNER JOIN `table` t ON t.id = o.table_id WHERE t.area_id='.$area_id.' GROUP BY o.number_id ORDER BY o.order_time DESC';
}else{
//get all
$sql='SELECT o.*, t.name as table_name, sum(o.count) as count_sum,sum(o.price) as price_sum FROM `order` o INNER JOIN `table` t ON t.id = o.table_id WHERE t.area_id='.$area_id.' GROUP BY o.number_id ORDER BY o.order_time DESC';
}
return $this->getAllQuery($sql);
}
function createOrder($order,$requester,$numberId){//if put connection mean transaction
$sql='';
//status==0 mean have to cook and else will finish now status will be send
$finish_time=$order->status==0 ? '\'0000-00-00 00:00:00\'' :'now()';
$sql = 'INSERT INTO `order` (waiter_id,chef_id, number_id, table_id, product_id,bill_detail_id, count, comments, order_time, finish_time, status, price) VALUES ';
$sql.= '(\''.$requester.'\',\'\','.$numberId.', '.$order->table_id.', '.$order->product_id.',-1,'.$order->count.',\''.$order->comments.'\', now(), '.$finish_time.', \''.$order->status.'\', '.$order->price.');';
//echo $sql;
if(isset($this->connection)){
return $this->queryNotAutoClose($sql);
}else{
return $this->query($sql);
}
}
function updateOrder($order,$requester){//if put connection mean transaction
$sql='';
$sql = 'UPDATE `order` SET waiter_id=\''.$requester.'\',';
$sql.='comments=\''.$order->comments.'\',order_time=now() WHERE id='.$order->id;
if(isset($this->connection)){
return $this->queryNotAutoClose($sql);
}else{
return $this->query($sql);
}
//TODO log this action to file for know who edit
}
/*
return number of delete: -1 if error,0 if delete all, 1 if delete any
*/
function removeOrderNotIn($orders,$numberId,$requester){//if put connection mean transaction
$notInList='';
$count=0;
foreach( $orders as $order){
if(isset($order->id)){//has id to delete
$count++;
if(empty($notInList)) {
$notInList.='('.$order->id;
}else{
$notInList.=','.$order->id;
}
}
}
if(!empty($notInList)) {
$notInList.=')';
$sql='DELETE FROM `order` WHERE number_id='.$numberId.' AND id NOT IN '.$notInList;
}else{
$sql='DELETE FROM `order` WHERE number_id='.$numberId;
}
if(isset($this->connection)){
if($this->queryNotAutoClose($sql)) return $count;
else return -1;
}else{
if($this->query($sql)) return $count;
else return -1;
}
//TODO log this action to file for know who delete
}
}
?>
| true |
594bb4d962449f6e48e524b2b51cbdfa89cad786 | PHP | kuzovkov/webcam | /app/include/module/MySQL.class.php | UTF-8 | 12,746 | 3.21875 | 3 | [] | no_license | <?php
/**
* Класс для работы с СУБД MySQL
*/
class MySQL implements Db{
private $DB_CHARSET = 'utf8';
private static $instance = null;
private $db_host = null;
private $db_user = null;
private $db_pass = null;
private $db_name = null;
private $tables = array();
private $schema = SCHEMA_FILE;
private $db = null;
public static function get_instance(){
if (self::$instance == null){
self::$instance = new MySQL(DB_HOST, DB_USER, DB_PASS, DB_NAME);
}
return self::$instance;
}
private function __construct($db_host, $db_user, $db_pass, $db_name){
$this->db_host = $db_host;
$this->db_user = $db_user;
$this->db_pass = $db_pass;
$this->db_name = $db_name;
$this->_connect_db();
$this->create_tables();
}
private function _connect_db(){
$this->db = mysqli_connect($this->db_host, $this->db_user, $this->db_pass, $this->db_name);
if (!$this->db) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
return $this->db;
}
/**
* выполнение запроса к БД
* @param $sql
* @param $db объект MySQLi
* @return array|bool|mysqli_result
*/
public function query($sql){
$db = $this->_connect_db();
$db->set_charset($this->DB_CHARSET);
$mysql_res = mysqli_query($this->db, $sql);
if (mysqli_errno($this->db) == 0){
if (is_object($mysql_res)){
$result = array();
while($row = mysqli_fetch_assoc ($mysql_res))
$result[] = $row;
mysqli_free_result($mysql_res);
}else{
$result = $mysql_res;
}
}else{
echo mysqli_error($this->db);
$result = false;
}
mysqli_close($this->db);
return $result;
}
/**
* получение записей из таблицы по условию
* @param $table
* @param array $conditions
* @param tail the tail of query
* @return array|bool|mysqli_result
* @throws Exception
*/
public function get($table, $conditions = array(), $tail = ''){
$db = $this->_connect_db();
$condition_strings = array();
foreach ($conditions as $field => $value){
if (is_int($value) || is_float($value)){
$condition_strings[] = strval($field) . strval($value);
}elseif(is_null($value)){
$condition_strings[] = strval($field) . ' NULL';
}elseif(is_string($value)){
$condition_strings[] = strval($field) . "'".$db->real_escape_string($value)."'";
}else{
throw new Exception(__CLASS__ . __METHOD__ . 'Bad field value');
}
}
$where_str = (count($condition_strings))? implode(' AND ', $condition_strings) : 1;
$sql = "SELECT * FROM $table WHERE {$where_str} $tail" ;
return $this->query($sql);
}
/**
* получение всех записей из таблицы
* @param $table
* @param array $conditions
* @return array|bool|mysqli_result
* @throws Exception
*/
public function get_list($table){
$sql = "SELECT * FROM $table";
return $this->query($sql);
}
/**
* Обновление записей в таблице
* @param $table
* @param array $data
* @param array $conditions
* @return array|bool|mysqli_result
* @throws Exception
*/
public function update($table, Array $data, $conditions = array()){
$db = $this->_connect_db();
$set_strings = array();
$conditions_string = array();
if (!is_array($data) || !count($data))
throw new Exception(__CLASS__ . __METHOD__ . 'Dataset must be array');
foreach ($data as $field => $value){
if (is_int($value) || is_float($value)){
$set_strings[] = '`'.strval($field).'`' . '=' . strval($value);
}elseif(is_null($value)){
$set_strings[] = '`'.strval($field).'`' . '=NULL';
}elseif(is_string($value)){
$set_strings[] = '`'.strval($field).'`' . "='" . $db->real_escape_string($value) ."'";
}else{
throw new Exception(__CLASS__ . __METHOD__ . 'Bad field value');
}
}
foreach ($conditions as $field => $value){
if (is_int($value) || is_float($value)){
$conditions_string[] = strval($field) . strval($value);
}elseif(is_null($value)){
$conditions_string[] = strval($field) . ' NULL';
}elseif(is_string($value)){
$conditions_string[] = strval($field) . "'" . $db->real_escape_string($value) ."'";
}else{
throw new Exception(__CLASS__ . __METHOD__ . 'Bad field value');
}
}
$where_str = (count($conditions_string))? implode(' AND ', $conditions_string) : 1;
$sql = "UPDATE $table SET " . implode(',', $set_strings) . ' WHERE ' . $where_str;
return $this->query($sql);
}
/**
* удаление записи в таблице
* @param $table
* @param array $conditions
* @return array|bool|mysqli_result
* @throws Exception
*/
public function delete($table, $conditions = array()){
$db = $this->_connect_db();
$set_strings = array();
$conditions_string = array();
foreach ($conditions as $field => $value){
if (is_int($value) || is_float($value)){
$conditions_string[] = strval($field) . strval($value);
}elseif(is_null($value)){
$conditions_string[] = strval($field) . ' NULL';
}elseif(is_string($value)){
$conditions_string[] = strval($field) . "'".$db->real_escape_string($value)."'";
}else{
throw new Exception(__CLASS__ . __METHOD__ . 'Bad field value');
}
}
$where_str = (count($conditions_string))? implode(' AND ', $conditions_string) : 1;
$sql = "DELETE FROM $table WHERE " . $where_str;
return $this->query($sql);
}
/**
* добавление записей в таблицу
* @param $table
* @param array $data
* @return array|bool|mysqli_result
* @throws Exception
*/
public function insert($table, Array $data){
$db = $this->_connect_db();
if (!is_array($data))
throw new Exception(__CLASS__ . __METHOD__ . 'Dataset must be array');
if (!count($data))
return false;
$fields_str = array();
$value_str = array();
$queries = array();
if (isset($data[0]) && is_array($data[0])){
foreach ($data[0] as $field => $value){
$fields_str[] = "`{$field}`";
}
foreach($data as $row){
$value_str = array();
foreach ($row as $field => $value){
//echo gettype($value);
if (is_int($value) || is_float($value)){
$value_str[] = strval($value);
}elseif(is_null($value)){
$value_str[] = ' NULL';
}elseif(is_string($value)){
$value_str[] = "'".$db->real_escape_string($value)."'";
}else{
throw new Exception(__CLASS__ . __METHOD__ . 'Bad field value');
}
}
$sql = "INSERT INTO `{$table}` (" . implode(',',$fields_str) . ") VALUES (" . implode(',',$value_str) . ")";
$queries[] = $sql;
}
$this->transaction($queries);
}else{
foreach ($data as $field => $value){
$fields_str[] = "`{$field}`";
}
foreach ($data as $field => $value){
if (is_int($value) || is_float($value)){
$value_str[] = strval($value);
}elseif(is_null($value)){
$value_str[] = ' NULL';
}elseif(is_string($value)){
$value_str[] = "'".$db->real_escape_string($value)."'";
}else{
throw new Exception(__CLASS__ . __METHOD__ . 'Bad field value');
}
}
$sql = "INSERT INTO `{$table}` (" . implode(',',$fields_str) . ") VALUES (" . implode(',',$value_str) . ")";
return $this->query($sql);
}
}
/**
* выполнение транзакции
* @param array $queries
* @throws Exception
*/
public function transaction(Array $queries){
if (!is_array($queries) || !count($queries))
throw new Exception(__CLASS__ . __METHOD__ . 'Queries must be array');
$db = mysqli_connect($this->db_host, $this->db_user, $this->db_pass, $this->db_name);
if (!$db) {
die('Ошибка подключения (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
mysqli_query($db, "BEGIN");
foreach($queries as $sql){
mysqli_query($db, $sql);
}
mysqli_query($db, "COMMIT");
}
/**
* возвращает имя базы данных
* @return null
*/
public function get_db_name(){
return $this->db_name;
}
/**
* Создание таблиц в БД
* @param null $schema
* @throws Exception
*/
public function create_tables(){
$db = $this->_connect_db();
$schema = __DIR__ . DIRECTORY_SEPARATOR . $this->schema;
if (!file_exists($schema)){
throw new Exception("Config-file $schema not exists!");
}
$tables = parse_ini_file ($schema, true, INI_SCANNER_RAW);
foreach($tables as $table=>$rows){
$fls = array();
$primary_key = false;
foreach($rows as $field=>$params_str){
$fparams = explode(' ', $params_str);
$ftype = trim($fparams[0]);
$fsize = (isset($fparams[1]))? trim($fparams[1]) : 255;
if (count($fparams) > 2){
$fdef = trim($fparams[2]);
if (in_array($fdef, array('null','NULL','None','NONE'))) {
$fdef = ' DEFAULT NULL ';
}elseif(in_array($fdef, array("''", '""', 'empty_str'))){
$fdef = " DEFAULT '' ";
}elseif(in_array($fdef, array('ai', 'AI', 'auto_increment'))){
$fdef = ' AUTO_INCREMENT';
}elseif(in_array($fdef, array('aip', 'AIP', 'auto_increment_primary'))){
$fdef = ' AUTO_INCREMENT';
$primary_key = $field;
}elseif(is_numeric($fdef)) {
$fdef = ' DEFAULT ' . $fdef;
}else{
$fdef = ' DEFAULT ' . "'" . $db->real_escape_string($fdef) . "'";
}
}else{
$fdef = '';
}
if ($ftype == 'int'){
$fls[] = implode('', array('`',$field, '`', ' INT(', $fsize, ')', $fdef));
}elseif($ftype == 'float') {
$fls[] = implode('', array('`', $field, '`', ' REAL(', $fsize, ')', $fdef));
}elseif($ftype == 'text'){
$fls[] = implode('', array('`', $field, '`', ' TEXT ', $fdef));
}elseif($ftype == 'datetime') {
$fls[] = implode('', array('`', $field, '`', ' DATETIME ', $fdef));
}else{
$fls[] = implode('', array('`',$field, '`', ' varchar(', $fsize, ')', $fdef));
}
}
if($primary_key){
$fls[] = " PRIMARY KEY (`{$primary_key}`) ";
}
$sql = implode(' ', array('CREATE TABLE IF NOT EXISTS ', $table,'(', implode(',',$fls), ')', ' ENGINE=InnoDB DEFAULT CHARSET=utf8'));
$this->query($sql);
}
}
/**
* удаление таблиц в БД
*/
public function delete_tables(){
$res = $this->query("SHOW TABLES");
foreach($res as $row){
$table = $row['Tables_in_' . $this->get_db_name()];
$sql = "DROP TABLE IF EXISTS `{$table}`";
$this->query($sql);
}
}
} | true |
80f685f44c762bacefe174baaab626743aa59c0c | PHP | pwsdotru/dbdesc | /dbdesc.php | UTF-8 | 3,739 | 2.90625 | 3 | [] | no_license | <?php
/**
* Script for builde description of database structure
* Author: Aleksandr Novikov, pwsdotru@gmail.com, http://pws.ru
*/
set_time_limit(0);
error_reporting(E_ALL);
ini_set("display_errors", 1);
$run_params = array(
"host" => "localhost",
"user" => "root",
"password" => "",
"base" => "",
"out" => "",
);
/*
* Read configuration from command string
*/
if ( isset($argv) && is_array($argv) && count($argv) > 1 ) {
foreach ( $argv AS $param ) {
if ( substr($param, 0, 2) == "--" ) {
$temp = explode("=", substr($param, 2), 2);
$param_key = trim($temp[0]);
if ( isset($temp[1]) && isset($run_params[$param_key]) ) {
$run_params[$param_key] = trim($temp[1]);
}
}
}
} else {
command_line_banner();
exit(1);
}
/*
* Check configuration
*/
if ( $run_params["base"] == "" ) {
command_line_banner("Error: You should set database name");
exit(1);
}
if ( $run_params["out"] == "" ) {
$run_params["out"] = $run_params["base"].".html";
}
$cn = mysqli_connect($run_params["host"], $run_params["user"], $run_params["password"]);
if ( !$cn ) {
echo mysqli_error($cn)."\n";
exit(1);
}
if ( !mysqli_select_db($cn, $run_params["base"]) ) {
echo mysqli_error($cn)."\n";
exit(1);
}
$out = fopen($run_params["out"], "w");
if ( !$out ) {
echo "Can't open file '" . $run_params["out"] . " for output\n";
exit();
}
$tables = mysqli_query($cn, "SHOW TABLES");
if ( !$tables ) {
echo "Can't get tables list:" . mysqli_error($cn)."\n";
exit(1);
}
fwrite($out, "<html>\n<head>\n<title>Database \"" . $run_params["base"] . "\"</title>\n</head>\n");
fwrite($out, "<body>\n<a name=\"top\"></a>\n<h1>Database \"". $run_params["base"] . "\"</h1>\n\n<ul>\n");
$tables_text = "";
while ( $table_info = mysqli_fetch_array($tables) ) {
if ( isset($table_info[0]) && $table_info[0] != "" ) {
$table_name = trim($table_info[0]);
$table_desc = mysqli_query($cn, "DESC ".$table_name);
if ( !$table_desc ) {
echo "Can't get table '" . $table_name . "' info:" . mysqli_error($cn)."\n";
continue;
}
$table_fields = array();
while ( $fields = mysqli_fetch_assoc($table_desc) ) {
$table_fields[] = $fields;
}
if ( count($table_fields) > 0 ) {
fwrite($out, buidContextEntry($table_name));
$tables_text .= buildTableEntry($table_name, $table_fields);
}
mysqli_free_result($table_desc);
}
}
mysqli_free_result($tables);
mysqli_close($cn);
fwrite($out, "</ul>\n".$tables_text);
fwrite($out, "\n</body>\n</html>\n");
fclose($out);
exit();
function command_line_banner( $message = "" ) {
echo "Script build description of all tables for MySQL database in HTML file\n";
if ( $message != "" ) {
echo $message."\n";
}
echo "Usage: ".basename(__FILE__)." --host=db_host --user=db_user --password=db_password --base=db_name --out=outputfile.html\n";
}
function buidContextEntry($name) {
$res = "<li><a href=\"#" . $name . "\">" . $name . "</a>\n - \n</li>\n";
return $res;
}
function buildTableEntry($name, $fields) {
$res = "\n<a name=\"" . $name . "\"></a>\n<h3>" . $name . "</h3>\n<p>\n\n</p>\n\n";
$res .= "<table border=\"1\">\n";
$res .= "<tr><th>Field</th><th>Type</th><th>Default</th><th>Null</th><th>Key</th><th>Description</th></tr>\n";
foreach ( $fields as $fld ) {
$res .= "<tr>\n";
$res .= "\t<td>".$fld["Field"]."</td>\n";
$res .= "\t<td>".$fld["Type"]."</td>\n";
$res .= "\t<td>".($fld["Default"] == "" ? " " : $fld["Default"])."</td>\n";
$res .= "\t<td>".$fld["Null"]."</td>\n";
$res .= "\t<td>".($fld["Key"] == "" ? " " : $fld["Key"])."</td>\n";
$res .= "\t<td>\n\t\t".($fld["Extra"] == "" ? $fld["Field"] : $fld["Extra"])."\n\t</td>\n";
$res .= "</tr>\n";
}
$res .= "</table>\n";
$res .= "<p><a href=\"#top\">top</a></p>\n";
return $res;
}
?>
| true |
b5c975a61ac8e191f74afeea5e6420b907e1ae72 | PHP | Iadergunov/ShortLink | /store.php | UTF-8 | 739 | 2.578125 | 3 | [] | no_license | <?php
$loader = require_once __DIR__.'/vendor/autoload.php';
use MyClasses\Link;
$received_link = $_POST['link'];
//Убираем возможные http и https префиксы
$formatted_link = Link::formatLink($received_link);
$link = new Link($formatted_link);
$link->store();
?>
<html>
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<title>ShortLink</title>
</head>
<body>
<div class="container">
<div class="panel panel-default">
<?php
$test = $_GET['link'];
die("<p>Ваша ссылка: <a href='http://wlp.icescroll.ru/$link->short_link'>wlp.icescroll.ru/$link->short_link</a></p>");
?>
</div>
</div>
</body>
</html> | true |
b2094efd9dce97e171fffadf6b267410522adac5 | PHP | zhiyb/vocab | /set/session_update.php | UTF-8 | 1,142 | 2.6875 | 3 | [] | no_license | <?php
$uid = $_GET['uid'];
$index = $_GET['index'];
if ($uid == null) {
http_response_code(400);
die();
}
$data = null;
$post = $_SERVER["REQUEST_METHOD"] == "POST";
if ($post)
$data = file_get_contents("php://input");
if ($index == null && !$post) {
http_response_code(400);
die();
}
require '../dbconf.php';
$db = new mysqli($dbhost, $dbuser, $dbpw, $dbname);
if ($db->connect_error) {
http_response_code(500);
die("Connection failed: " . $db->connect_error . "\n");
}
$db->set_charset('utf8mb4');
if ($index != null) {
$stmt = $db->prepare("INSERT INTO `session` (`uid`, `index`) VALUES (UNHEX(?), ?) ON DUPLICATE KEY UPDATE `index` = VALUES(`index`)");
$stmt->bind_param('si', $uid, $index);
if ($stmt->execute() !== true) {
http_response_code(500);
die($stmt->error);
}
}
if ($post) {
$stmt = $db->prepare("INSERT INTO `session` (`uid`, `data`) VALUES (UNHEX(?), ?) ON DUPLICATE KEY UPDATE `data` = VALUES(`data`)");
$stmt->bind_param('ss', $uid, $data);
if ($stmt->execute() !== true) {
http_response_code(500);
die($stmt->error);
}
}
?>
| true |
214fe4c0b18c0532b1a428de08c9f302869f502d | PHP | salahuiste/exercice_dashboard | /includes/transaction_class.php | UTF-8 | 1,861 | 3.359375 | 3 | [] | no_license | <?php
/*la classe ci-dessous représente une transaction*/
class Transaction{
private $transaction_id;
private $date_transaction;
private $account_id;
private $total_transaction;
private $currency;
private $type;
//status == -1 ==>Canceled,status == 0 ==> Pending, status==1 ==> Confirmed
private $status;
function __construct($transaction,$acc_id){
$this->transaction_id=$transaction["id"];
$this->date_transaction=$transaction["date"];
$this->account_id=$acc_id;
$this->total_transaction=$transaction["total"];
$this->currency=$transaction["currency"];
$this->type=$transaction["type"];
$this->status=$transaction["status"];
}
//les getters
public function getTransactionId() {
return $this->transaction_id;
}
public function getDateTransaction() {
return $this->date_transaction;
}
public function getAccountId() {
return $this->account_id;
}
public function getTotalTransaction() {
return $this->total_transaction;
}
public function getCurrency() {
return $this->currency;
}
public function getType() {
return $this->type;
}
public function getStatus(){
return $this->status;
}
//les setters
public function setTransactionId($transactionId){
$this->transaction_id=$transactionId;
}
public function setDateTransaction($dateTransaction){
$this->date_transaction=$dateTransaction;
}
public function setAccountId($accountid){
$this->account_id=$accountid;
}
public function setTotalTransaction($total_transaction){
$this->total_transaction=$total_transaction;
}
public function setCurrency($currency){
$this->currency=$currency;
}
public function setType($type){
$this->type=$type;
}
public function setStatus($status){
$this->status=$status;
}
}
?> | true |
d3bbc35fb6e407c04d8f3b7f5c4b876f6b78b22d | PHP | yitznewton/2048 | /src/Yitznewton/TwentyFortyEight/Output/Output.php | UTF-8 | 482 | 3.015625 | 3 | [] | no_license | <?php
namespace Yitznewton\TwentyFortyEight\Output;
use Yitznewton\TwentyFortyEight\Grid;
interface Output
{
/**
* @param Grid $grid
* @param int $score
* @return void
*/
public function renderBoard(Grid $grid, $score);
/**
* @param int $score
* @return void
*/
public function renderGameOver($score);
/**
* @param int $winningTileValue
* @return void
*/
public function renderWin($winningTileValue);
}
| true |
23a0d7be37393d94e976c476fadde392ca61f04c | PHP | arahim56/std | /Admin/student_new.php | UTF-8 | 2,265 | 2.953125 | 3 | [] | no_license | <?php
$name = "";
$contact = "";
$email = "";
$dateofbirth = "";
$gender = "";
$address = "";
$city = "0";
$cv["name"] = "";
if(isset($_POST['submit']))
{
$name = $_POST['name'];
$contact = $_POST['contact'];
$email = $_POST['email'];
$dateofbirth = $_POST['dateofbirth'];
$gender = $_POST['gender'];
$address = $_POST['address'];
$city = $_POST['city'];
$cv = $_FILES['cv'];
$a = explode(".", $cv["name"]);
$ext = $a[count($a) - 1];
$sql = "insert into student(name, contact, email, dateofbirth, gender,
address, cityId, cv) values(
'".ms($name)."', '".ms($contact)."', '".ms($email)."',
'".ms($dateofbirth)."', ".ms($gender).", '".ms($address)."',
".ms($city)." , '".ms($ext)."')";
if(mysql_query($sql))
{
$sp = $cv['tmp_name'];
$dp = "CVS/".mysql_insert_id().".".$ext;
move_uploaded_file($sp, $dp);
print '<span class="success">Data Saved</span>';
$name = "";
$contact = "";
$email = "";
$dateofbirth = "";
$gender = "";
$address = "";
$city = "0";
$cv["name"] = "";
}
else
{
print '<span class="error">'.mysql_error().'</span>';
}
}
?>
<form method="post" enctype="multipart/form-data" action="">
Name<br><input type="text" name="name" value="<?php print $name; ?>" required /><br /><br />
Contact<br><input type="text" name="contact" value="<?php print $contact; ?>" required /><br /><br />
Email<br><input type="text" name="email" value="<?php print $email; ?>" required /><br /><br />
Date Of Birth<br><input type="text" name="dateofbirth" value="<?php print $dateofbirth; ?>" required /><br /><br />
Gender<br>
<input type="radio" name="gender" value="0" />Male
<input type="radio" name="gender" value="1" />Female<br />
<br />
Address<br>
<textarea name="address"><?php print $address;?></textarea><br><br>
City<br>
<select name="city">
<option value="0">Select</option>
<?php
$sql = "select id, name from city";
$r = mysql_query($sql);
while($s = mysql_fetch_row($r))
{
if($s[0] == $city)
{
print '<option value="'.$s[0].'" selected>'.$s[1].'</option>';
}
else
{
print '<option value="'.$s[0].'" >'.$s[1].'</option>';
}
}
?>
</select><br><br>
Select CV<br><input type="file" name="cv" required /><br>
<br>
<input type="submit" name="submit" value="Submit"/>
</form> | true |
f994c19383f926be87322ca420d6259cd29c3bbb | PHP | pherapeutic/MVP | /backend_pherapeutic/app/Http/Controllers/Admin/LanguagesController.php | UTF-8 | 5,302 | 2.546875 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Languages;
use Validator;
class LanguagesController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* @return \Illuminate\Contracts\Support\Renderable
*/
public function index(Request $request, Languages $languages)
{
if ($request->ajax()) {
$languagesColl = $languages->getAllLanguages();
return datatables()->of($languagesColl)
->addIndexColumn()
->addColumn('id', function ($languages) {
return $languages->id;
})
->addColumn('title', function ($languages) {
return ($languages->title) ? ($languages->title) : 'N/A';
})
->addColumn('action', function ($languages) {
$btn = '';
$btn = '<a href="languages/'.$languages->id.'/edit" title="Edit"><i class="fas fa-edit mr-1"></i></a>';
$btn .='<a href="javascript:void(0);" data-id="'.$languages->id.'" class="text-danger delete-datatable-record" title="Delete"><i class="fas fa-trash ml-1"></i></a>';
return $btn;
})
->rawColumns(['action'])
->make(true);
}
return view('admin.languages.index');
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('admin.languages.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request, Languages $languages)
{
//echo"<pre>";print_r($request->all());die;
$rules = [
'title' => 'required'
];
$input = $request->all();
$validator = Validator::make($input, $rules);
if ($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput();
}else{
$inputArr = $request->except(['_token']);
$languagesObj = $languages->saveLanguages($inputArr);
if(!$languagesObj){
return redirect()->back()->with('error', 'Unable to add language. Please try again later.');
}
return redirect()->route('languages.index')->with('success', 'Language account added successfully.');
}
}
/**
* 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, Languages $languages)
{
$languages = $languages->getLanguageById($id);
if(!$languages){
return redirect()->back()->with('error', 'Language does not exist');
}
return view('admin.languages.edit', compact('languages'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//echo"<pre>";print_r($request->all());die;
$rules = [
'title' => 'required'
];
$input = $request->all();
$validator = Validator::make($input, $rules);
if ($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput();
}else{
$languages = new Languages();
$languages = $languages->getLanguageById($id);
if(!$languages){
return redirect()->back()->with('error', 'This language does not exist');
}
$inputArr = $request->except(['_token', 'language_id', '_method']);
$hasUpdated = $languages->updateLanguage($id, $inputArr);
if($hasUpdated){
return redirect()->route('languages.index')->with('success', 'Language type updated successfully.');
}
return redirect()->back()->with('error', 'Unable to update language. Please try again later.');
}
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id, Languages $languages)
{
$languagesObj = $languages->getLanguageById($id);
if(!$languagesObj){
return returnNotFoundResponse('This language does not exist');
}
$hasDeleted = $languagesObj->delete();
if($hasDeleted){
return returnSuccessResponse('language deleted successfully');
}
return returnErrorResponse('Something went wrong. Please try again later');
}
}
| true |
490efe17bccbacf459ad78e314623669fdb1690d | PHP | ihsanfikri12/nilaikelompok | /backend/app/Http/Controllers/SkorPoint.php | UTF-8 | 4,349 | 2.578125 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client;
class SkorPoint extends Controller
{
//show all skor point
public function index()
{
$client = new Client(['base_uri' => 'http://127.0.0.1:8000/api/skorpoint']);
$request = $client->request('GET');
// $response = json_decode($request->getBody());
// echo $response[0]->id;
$response = $request->getBody();
return $response;
}
public function tambahPoint()
{
return view('pages.formPoint');
}
// Tambah nilai point
public function create(Request $request)
{
// $point = $request->point;
$status = $request->status;
$point = 0;
if($status == "penambahan") {
$point = 2.5;
} else if ($status == "pengurangan") {
$point = -2.5;
}
$keterangan = $request->keterangan;
$sprint = $request->sprint;
$idUser = $request->idUser;
$idTim = $request->idTim;
// $idSkorSprint = $request->idSkorSprint;
$client = new \GuzzleHttp\Client();
$response = $client->request('POST', "http://127.0.0.1:8000/api/skorpoint", [
'form_params' => [
'point' => $point,
'status' => $status,
'keterangan' => $keterangan,
'sprint' => $sprint,
'idUser' => $idUser,
'idTim' => $idTim,
// 'idSkorSprint' => $idSkorSprint,
]]);
// echo $status;
return redirect("/skorpoint/$idTim/$idUser");
// return $point;
}
//show skor point by id
public function show($id,$sprint)
{
$client = new Client(['base_uri' => "http://127.0.0.1:8000/api/skorpoint/detail/$id/$sprint"]);
$request = $client->request('GET');
$response = $request->getBody();
$data = json_decode($response);
// return $data->point;
return view('pages.detailPoint',['data'=>$data]);
// return $response;
}
public function show2($id,$idUser)
{
$client = new Client(['base_uri' => "http://127.0.0.1:8000/api/skorpoint/$id/$idUser"]);
$request = $client->request('GET');
$response = $request->getBody();
$data = json_decode($response);
// // return $data->point;
return view('pages.tablesPointAll',['data'=>$data, 'id'=>$id, 'idUser'=>$idUser]);
// return $response;
}
public function ubahNilai($id)
{
$client = new Client(['base_uri' => "http://127.0.0.1:8000/api/skorpoint/$id"]);
$request = $client->request('GET');
$response = $request->getBody();
$data = json_decode($response);
// return view('pages.editPoint');
return view('pages.editPoint', ['data'=>$data]);
}
/**
* Show the form for editing the specified resource.
*
* @param \App\r $r
* @return \Illuminate\Http\Response
*/
//update point
public function update(Request $request, $id)
{
$point = $request->point;
$status = $request->status;
$keterangan = $request->keterangan;
$sprint = $request->sprint;
$idUser = $request->idUser;
$idTim = $request->idTim;
$idSkorSprint = $request->idSkorSprint;
$client = new \GuzzleHttp\Client();
$response = $client->request('PUT', "http://127.0.0.1:8000/api/skorpoint/$id", [
'form_params' => [
'point' => $point,
'status' => $status,
'keterangan' => $keterangan,
'sprint' => $sprint,
'idUser' => $idUser,
'idTim' => $idTim,
'idSkorSprint' => $idSkorSprint,
]]);
return redirect("/skorpoint/$idTim/$idUser/$sprint");
// return $idUser;
}
public function delete ($id) {
$client = new Client(['base_uri' => "http://127.0.0.1:8000/api/skorpoint/$id"]);
$request = $client->request('DELETE');
$response = $request->getBody();
$data = json_decode($response);
return redirect("/skorpoint/$data->idTim/$data->idUser");
}
}
| true |
665cc4ec1f419b23ce205572a4a5818096857406 | PHP | dexteryam/rmdb | /peoplePage.php | UTF-8 | 4,064 | 2.796875 | 3 | [] | no_license | <?php
include_once("include/header.php");
echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"css/mp.css\">";
?>
<div class="frame group">
<div>
<?php
$people_id = $_GET['id'];
if(isset($_POST['submit'])){
$date = $_POST['birthday'];
if (!preg_match ("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $date, $parts)){
die("Error: Incorrect birthdate format (YYYY-MM-DD) <a href =\"peoplePage.php?id=$people_id\"> Back </a>");
}
$query = "UPDATE cast SET birth_date = '$date' WHERE actor_id = $people_id";
mysql_query($query);
}
//Viewcount
date_default_timezone_set('America/Los_Angeles');
$date = date("Y-m-d");
$result = mysql_query("SELECT * FROM cast WHERE (actor_id = $people_id)");
while($row = mysql_fetch_array($result)){
$birthday = $row['birth_date'];
$bd_month = substr($birthday,5,2);
$bd_day = substr($birthday,8,2);
if(date("m") == $bd_month && date("d") == $bd_day){
echo "<h3> Happy Birthday to ".$row['name']."! </h3>";
}
}
$query = "SELECT * FROM people_popularity WHERE date = '$date' AND people_id ='$people_id'";
$result = Db::query_row($query);
if($result){
$views = $result['views'];
$views+=1;
echo "Pageviews: ".$views;
$query = "UPDATE people_popularity SET views = '$views' WHERE people_id='$people_id' AND date='$date'";
$result = mysql_query($query);
}
else{
$query = "INSERT INTO people_popularity VALUES ('$people_id',1,'$date')";
$result = mysql_query($query);
echo "Pageviews: 1";
}
$type;
function people_basics()
{
global $type;
$people_id = $_GET['id'];
$result = mysql_query("SELECT * FROM cast WHERE (actor_id = $people_id)");
while($row = mysql_fetch_array($result))
{
//$type = $row['type'];
//$rDate=$row['release_date'];
echo "<h1 id=\"full_width_title_bar\">" . $row['name'] . "</h1>";
echo "<div class=\"group\">";
// echo "<img class=\"left mainImg\" src=\"" . $row['url'] . "\"/>";
if($row['birth_date']=="0000-00-00"){
echo"No birthdate found. Enter birthdate<br><form method = \"POST\" action = \"peoplePage.php?id=$people_id\">
Submit Birthdate (YYYY-MM-DD): <input type = \"text\" name = \"birthday\">
<input type = \"submit\" value = \"Submit\" name =\"submit\">
";
}
else{
echo "<p class=\"textLeft\">Date of Birth: ". $row['birth_date'] ." </p>";
}
// echo "<p class=\"textLeft\">Created by: " . $row['studio'] . "</p>";
echo "</div>";
}
}
$people_id = $_GET['id'];
people_basics();
?>
</div>
<div class="comments">
</div>
<div>
<h2 class="textLeft">Movies:</h2>
<?php
$result = mysql_query("SELECT * FROM cast WHERE (actor_id = $people_id)");
while($row = mysql_fetch_array($result))
{
$show_id = $row['show_id'];
$result2 = mysql_query("SELECT * FROM shows WHERE (id = $show_id) AND (type = 'MOVIE')");
$show = mysql_fetch_array($result2);
echo "<p class=\"reset textLeft\"><a href = http://localhost/showPage.php?id=".$show_id.">" . $show['name'] . "</a></p>";
}
?>
<h2 class="textLeft">Television:</h2>
<?php
$result = mysql_query("SELECT * FROM cast WHERE (actor_id = $people_id)");
while($row = mysql_fetch_array($result))
{
$show_id = $row['show_id'];
$result2 = mysql_query("SELECT * FROM shows WHERE (id = $show_id) AND (type = 'TV')");
$show = mysql_fetch_array($result2);
echo "<p class=\"reset textLeft\"><a href = http://localhost/showPage.php?id=".$show_id.">" . $show['name'] . "</a></p>";
}
$pid = $_GET['id'];
echo "</div><div class=\"lowNav\">";
echo "<a href=\"quotesCeleb.php?id=" . $pid . "\">Quotes</a>" .
" | <a href=\"goofsCeleb.php?id=" . $pid . "\">Goofs</a>" .
" | <a href=\"triviaCeleb.php?id=" . $pid . "\">Trivia</a>";
echo "| <a name=\"fb_share\" share_url=\"localhost/peoplePage.php?id=".$pid."\">Share</a>";
?>
</p>
</div>
</div>
</div>
<?php
include_once("include/footer.php");
?>
| true |
8360f93203853da47448670c6bc8ba9ed6c66948 | PHP | AgenziaXilweb/passalibro | /includes/actions/demands.php | UTF-8 | 1,866 | 2.53125 | 3 | [] | no_license | <?php
if ($_REQUEST['azione'] == 'email') {
$busto = 'marco.lilly@email.it';
$sesto = 'marco@ingruppo-ict.com';
$milano = 'marco@carryexpress.it';
$sassuolo = '';
$incopia = 'marco@ingruppo-ict.com';
if ($_SESSION['mailsede'] = 1) {
$destinatario = $busto;
} elseif ($_SESSION['mailsede'] = 2) {
$destinatario = $sesto;
} elseif ($_SESSION['mailsede'] = 3) {
$destinatario = $milano;
} elseif ($_SESSION['mailsede'] = 4) {
$destinatario = $sassuolo;
}
$query_cliente = mysql_query("SELECT customers_email_address FROM passalibro_web.customers WHERE customers_id = " .
tep_session_is_registered('customer_id') . "");
$cliente = mysql_fetch_array($query_cliente);
$oggetto = "Test Richieste";
$header = "From: " . $cliente['customers_email_address'] . "\n";
$header .= "CC: " . $incopia . "\n";
$header .= "X-Mailer: Il nostro Php\n";
$header .= "MIME-Version: 1.0\n";
$header .= "Content-Type: text/html; charset=\"iso-8859-1\"\n";
$header .= "Content-Transfer-Encoding: 7bit\n\n";
$selezione = $_POST['inserito'];
$corpo = "<table width='100%'><tr>
<td><b>Codice</b></td>
<td><b>ISBN</b></td>
<td><b>Descrizione</b></td>
<td><b>Prezzo Euro</b></td></tr>";
foreach ($selezione as $messaggio) {
$corpo .= "<tr><td>" . str_replace(' - ', "</td><td>", strtoupper($messaggio)) .
"</td></tr>";
}
$corpo .= "</table>";
$message = $corpo;
session_start();
$_SESSION['stampa'] = $corpo;
if (@mail($destinatario, $oggetto, $message, $header))
echo "<center><h1>e-mail inviata con successo!</h1><br>";
$targetUrl = "stampe.php?" . $message;
echo "<div align='center' class='styled-input'><a href='" . $targetUrl . "'><br><br>Stampa</a></div>";
} else {
echo "<center><h1>errore nell'invio dell'e-mail!</h1></center>";
}
?> | true |
c1dfd3f043e500a39da07829de005692c01886e2 | PHP | wol-soft/php-json-schema-model-generator | /src/Model/Property/CompositionPropertyDecorator.php | UTF-8 | 1,885 | 2.765625 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types = 1);
namespace PHPModelGenerator\Model\Property;
use PHPModelGenerator\Exception\SchemaException;
use PHPModelGenerator\Model\SchemaDefinition\JsonSchema;
use PHPModelGenerator\Model\SchemaDefinition\ResolvedDefinitionsCollection;
/**
* Class CompositionPropertyDecorator
*
* @package PHPModelGenerator\Model\Property
*/
class CompositionPropertyDecorator extends PropertyProxy
{
private const PROPERTY_KEY = 'composition';
/**
* Store all properties from nested schemas of the composed property validator. If the composition validator fails
* all affected properties must be set to null to adopt only valid values in the base model.
*
* @var PropertyInterface[]
*/
protected $affectedObjectProperties = [];
/**
* CompositionPropertyDecorator constructor.
*
* @param string $propertyName
* @param JsonSchema $jsonSchema
* @param PropertyInterface $property
*
* @throws SchemaException
*/
public function __construct(string $propertyName, JsonSchema $jsonSchema, PropertyInterface $property)
{
parent::__construct(
$propertyName,
$jsonSchema,
new ResolvedDefinitionsCollection([self::PROPERTY_KEY => $property]),
self::PROPERTY_KEY
);
$property->onResolve(function (): void {
$this->resolve();
});
}
/**
* Append an object property which is affected by the composition validator
*
* @param PropertyInterface $property
*/
public function appendAffectedObjectProperty(PropertyInterface $property)
{
$this->affectedObjectProperties[] = $property;
}
/**
* @return PropertyInterface[]
*/
public function getAffectedObjectProperties(): array
{
return $this->affectedObjectProperties;
}
}
| true |
ca560a140db089a4d2c49a11fb98ba45d0812482 | PHP | designwebvn/annuaire_audition | /trunk/protected/modules/site/controllers/CronController.php | UTF-8 | 1,602 | 2.625 | 3 | [] | no_license | <?php
class CronController extends BaseController {
//check if has end auction, and set end
//update backcash, ...
//it will run every minutes and 1st second
public function actionIndex() {
//check
$current = time()-1;
$conditions = "start_time <= NOW() AND bid_quote = 0 AND(end_time IS NULL OR end_time = '0000-00-00 00:00:00')";
$auctions = Auctions::model()->findAll($conditions);
if ($auctions){
foreach ($auctions as $auction){
$tmp = explode(':', $auction->countdown);
$countdown = $tmp[0]*3600 + $tmp[1]*60;
$end_time = strtotime($auction->start_time) + $countdown;
$loop_times = ($end_time - $current)/$countdown;
if (intval($loop_times) == $loop_times)
$auction->setEnd();
}
}
// 1st place
$conditions = "start_time <= NOW() AND bid_quote > 0 AND(end_time IS NULL OR end_time = '0000-00-00 00:00:00')";
$auctions = Auctions::model()->findAll($conditions);
if ($auctions){
foreach ($auctions as $auction){
$tmp = explode(':', $auction->countdown);
$countdown = $tmp[0]*3600 + $tmp[1]*60;
$end_time = strtotime($auction->start_time) + $countdown;
$loop_times = ($end_time - $current)/$countdown;
if (intval($loop_times) == $loop_times){
$auction->set1stPlace($auction['id']);
}
}
}
}
}
| true |
9eb56dc144ac261e11e12ea9f25f3fae816b84a2 | PHP | drpremo/cis355 | /fitness355/activity/read.php | UTF-8 | 2,142 | 2.625 | 3 | [] | no_license | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<?php
session_start();
if (empty($_SESSION['user'])) {
header("location:../login.php");
} else {
echo '<title>Fitness355 - ' . $_SESSION['user'] . '</title>';
}
require '../Template.php';
Template::sources("../");
require '../Database.php';
$Id = null;
if ( !empty($_GET['Id'])) {
$Id = $_REQUEST['Id'];
}
if (null == $Id) {
header("Location: .");
} else {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT *
FROM Activity
WHERE IdA = ?";
$q = $pdo -> prepare($sql);
$q -> execute(array($Id));
$data = $q -> fetch(PDO::FETCH_ASSOC);
Database::disconnect();
}
?>
</head>
<body style="background-color:LightGreen">
<?php
Template::navigation("../");
?>
<div class="container">
<div class="span10 offset1">
<div class="row">
<h3>Read a Activity</h3>
</div>
<div class="row">
<div class="col-lg-2 col-md-3 col-sm-3 col-xs-4">
<label>ID</label>
<div class="text-right"><?php echo $data['IdA'];?></div>
<br/>
<label>Name</label>
<div class="text-right"><?php echo $data['Name'];?></div>
<br/>
<label>Intensity</label>
<div class="text-right"><?php echo $data['Intensity'];?></div>
</div>
<div class="col-lg-1 col-md-1 col-sm-1 col-xs-1">
</div>
<div class="col-lg-2 col-md-3 col-sm-3 col-xs-4">
<label>Has Distance?</label>
<div class="text-right"><?php echo ($data['HasDistance'])?'Yes':'No';?></div>
<br/>
<label>Has Resistance?</label>
<div class="text-right"><?php echo ($data['HasResistance'])?'Yes':'No';?></div>
<br/>
<label>Has Repititions?</label>
<div class="text-right"><?php echo ($data['HasRepititions'])?'Yes':'No';?></div>
</div>
</div>
<hr/>
<a class="btn btn-default" href=".">Back</a>
</div>
</div> <!-- /container -->
</body>
</html> | true |
b2fe79b57b191ace82eb5fff5ee1edbbf957ef63 | PHP | alex-eberly/JagWarz2017 | /assets/utilities/class-generator/handlers/download.php | UTF-8 | 574 | 2.78125 | 3 | [] | no_license | <?php include("../includes/dataObjects.php"); ?>
<?php
$filename = "";
if (isset($_GET["filename"]))
{
$filename = $_GET["filename"];
}
$file = "../temp/" . $filename;
if(!file_exists($file))
{
// File doesn't exist, output error
die('File not found');
}
else
{
// Set headers
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$filename");
header("Content-Type: text/php");
header("Content-Transfer-Encoding: binary");
// Read the file from disk
readfile($file);
unlink($file);
}
?> | true |
aaaa870a3294290368cb84c8676bc613d655c7ff | PHP | burdiuz/php-callbacks | /tests/aw/CallableSequenceTest.php | UTF-8 | 1,286 | 3.015625 | 3 | [
"MIT"
] | permissive | <?php
/**
* Created by Oleg Galaburda on 03.12.15.
*/
namespace aw {
use \PHPUnit_Framework_TestCase as TestCase;
class CallableSequenceTest extends TestCase {
public $collection;
public $handler1;
public $handler2;
public $handler3;
public $handlerArgs1;
public $handlerArgs3;
public function setUp() {
$this->collection = new CallableSequence();
$this->handler1 = function (...$args) {
$this->handlerArgs1 = $args;
return 1;
};
$this->collection->addItem($this->handler1);
$this->handler2 = function (&$arg1, &$arg2) {
$arg1 += 20;
$arg2 .= 'YZ';
return 2;
};
$this->collection->addItem($this->handler2);
$this->handler3 = function (...$args) {
$this->handlerArgs3 = $args;
return 3;
};
$this->collection->addItem($this->handler3);
}
public function test() {
$collection = $this->collection;
$this->assertEquals(3, $collection(5, 'AB'));
$this->assertEquals([5, 'AB'], $this->handlerArgs1);
$this->assertEquals([25, 'ABYZ'], $this->handlerArgs3);
$collection->removeItemAt(1);
$this->assertEquals(3, $collection(5, 'AB'));
$this->assertEquals([5, 'AB'], $this->handlerArgs3);
}
}
} | true |
9c95be0b3ade1631a8be9ad031df70e27242ba2e | PHP | Ilya-lab/cliga-php | /app/Sport/BidPlayer.php | UTF-8 | 2,175 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Sport;
use Illuminate\Database\Eloquent\Model;
class BidPlayer extends Model
{
use \Awobaz\Compoships\Compoships;
protected $table = 'sport.tb_bidplayer';
/**
* За конкретную заявку
* @param $query
* @param $bid - идентификатор заявочного окна
*/
public function scopeBid($query, $bid) {
$query->where('bid_id', $bid);
}
/**
* Отзаявленные игроки
* @param $query
* @param $bid - идентификатор заявочного окна
*/
public function scopeUnbid($query, $bid) {
$query->where('unbid_id', $bid);
}
/**
* @param $query
* @param $team - идентификатор команды в заявке на турнир
*/
public function scopeTeam($query, $team) {
$query->where('team_id', $team);
}
/**
* Свзяать с позицией игрока
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function position()
{
return $this->belongsTo('App\Classif\Position', 'position_id', 'id');
}
/**
* Ссылка на фотографию в заявке
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function photo()
{
return $this->belongsTo('App\Images\Images', 'photo_id', 'id');
}
/**
* Ссылка на человека
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function person()
{
return $this->belongsTo('App\Sport\Person', 'person_id', 'id');
}
/**
* ссылка на принадлежность к капитану
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function captain()
{
return $this->belongsTo('App\Classif\Captain', 'captain_id', 'id');
}
public function bid()
{
return $this->belongsTo('App\Sport\TournBids', 'bid_id', 'id');
}
public function team()
{
return $this->belongsTo('App\Sport\TournTeams', 'team_id', 'id');
}
}
| true |
1611fbcef9dbef3701ebc130b7f78b76ca5de3db | PHP | ahmed-debbech/uno_online | /core/game/ajax/update_table.php | UTF-8 | 2,763 | 2.703125 | 3 | [
"Unlicense"
] | permissive | <?php
include("../../../keys.php");
function setColors($text){
$colo = $text[strlen($text)-1];
switch($colo){
case 'r': return "ff4747"; break;
case 'g': return "6fc763"; break;
case 'b': return "5496ff"; break;
case 'y': return "eddc1c"; break;
default: return "grey"; break;
}
}
function loadCard($content){
$card = "";
if($content[0] >= '0' && $content[0] <= '9'){
$col = setColors($content);
include_once("../../../assets/cards_templates/number_card.php");
$card = numbercard($content, "#".$col);
}else{
if(stristr($content, "wc") == true){
include_once("../../../assets/cards_templates/wildcard.php");
$card = wildcard();
}else{
if(stristr($content, "+2") == true){
$col = setColors($content);
include_once("../../../assets/cards_templates/plustwo.php");
$card = plustwo($content, "#".$col);
}else{
if(stristr($content, "+4") == true){
include_once("../../../assets/cards_templates/plusfour.php");
$card = plusfour();
}else{
if(stristr($content, "inv") == true){
$col = setColors($content);
include_once("../../../assets/cards_templates/inverse.php");
$card = inverse($content, "#".$col);
}else{
if(stristr($content, "blo") == true){
$col = setColors($content);
include_once("../../../assets/cards_templates/block.php");
$card = block($content, "#".$col);
}
}
}
}
}
}
return $card;
}
$link = mysqli_connect($serverIp, $username, $pass, $dbName);
$sql = "select * from room where roomCode='".$_GET["room-code"]."'";
$res = mysqli_query($link,$sql);
$list = mysqli_fetch_array($res, MYSQLI_ASSOC);
mysqli_close($link);
$cardOnTable = $list['cardOnTable'];
$ret = loadCard($cardOnTable);
// encoding array in JSON format
$return_arr = array();
$link = mysqli_connect($serverIp, $username, $pass, $dbName);
$sql = "select color from room where roomCode='".$_GET["room-code"]."'";
$res = mysqli_query($link,$sql);
$row1 = mysqli_fetch_array($res, MYSQLI_ASSOC);
mysqli_close($link);
$x="";
switch($row1['color']){
case 'r': $x ="Red"; break;
case 'g': $x = "Green"; break;
case 'y': $x = "Yellow"; break;
case 'b': $x = "Blue"; break;
}
$return_arr[] = array("cardOnTable" => $cardOnTable, "cardTemp" => $ret, "colorInd" => $x);
echo json_encode($return_arr);
?> | true |
ae08643f9413c59afeae617fe20918034d8cc9d2 | PHP | soomahouraiby/projects | /database/migrations/2021_04_08_221446_create_effective_material_table.php | UTF-8 | 727 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateEffectiveMaterialTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('effective_material', function (Blueprint $table) {
$table->id('material_no');
$table->string('material_name',30);
$table->longText('indications_for_use');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('effective_material');
}
}
| true |
6f16506239563c2aed51ac44717a3ae319142d73 | PHP | mindofmicah/filters | /src/mindofmicah/Filters/EqualFormatter.php | UTF-8 | 301 | 2.828125 | 3 | [] | no_license | <?php
namespace mindofmicah\Filters;
class EqualFormatter implements FormatableInterface
{
public function formatAsSQL()
{
return trim(preg_replace('%\s*=\s*%', '=', $this->orig, 1));
}
public function __construct($argument1)
{
$this->orig = $argument1;
}
}
| true |
81e2c8223a0a8f040dd49427adbb38806f790ed2 | PHP | hamidkom/appinjaz | /app/Http/Controllers/API/registerController.php | UTF-8 | 1,712 | 2.578125 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Controllers\API\BassController as BassController;
use App\Models\User;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
use Laravel\Passport\HasApiTokens;
class registerController extends BassController
{
use HasApiTokens;
//for register
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email',
'password' => 'required',
'c_password' => 'required|same:password',
]);
if ($validator->fails()) {
return $this->sendError('Your information is not correct', $validator->errors());
}
$input = $request->all();
$input['password'] = Hash::make($input['password']);
$user = User::create($input);
$success['token'] = $user->createToken('fatimah')->accessToken;
$success['name'] = $user->name;
return $this->sendResponse($success, 'You registered successfully');
}
//for login
public function login(Request $request)
{
if (Auth::attempt(['email' => $request->email, 'password' => $request->password])) {
$user = Auth::user();
$success['token'] = $user->createToken('fatimah')->accessToken;
$success['name'] = $user->name;
return $this->sendResponse($success, 'You logged in successfully');
} else {
return $this->sendError('Unauthorised', ['error', 'Unauthorised']);
}
}
}
| true |
acdd199ba4ec4b0ceac1973b8e010a64a58c9acf | PHP | achton/nordea-payment | /src/TransactionInformation/BankCreditTransfer.php | UTF-8 | 2,623 | 2.90625 | 3 | [
"MIT"
] | permissive | <?php
namespace NordeaPayment\TransactionInformation;
use DOMDocument;
use InvalidArgumentException;
use NordeaPayment\AccountInterface;
use NordeaPayment\BIC;
use NordeaPayment\FinancialInstitutionInterface;
use NordeaPayment\IID;
use NordeaPayment\Money;
use NordeaPayment\PaymentInformation\PaymentInformation;
use NordeaPayment\PostalAddressInterface;
/**
* BankCreditTransfer contains all the information about a type 3 transaction.
*/
class BankCreditTransfer extends CreditTransfer
{
/**
* @var IBAN|BBAN
*/
protected $creditorAccount;
/**
* @var FinancialInstitutionInterface
*/
protected $creditorAgent;
/**
* {@inheritdoc}
*
* @param IBAN|BBAN $creditorAccount IBAN or BBAN from creditor.
* @param BIC|IID $creditorAgent BIC or IID of the creditor's financial institution
*
* @throws \InvalidArgumentException When the amount is not in EUR or DKK or when
* the creditor agent is not BIC or IID.
*/
public function __construct($endToEndId, Money\Money $amount, $creditorName, PostalAddressInterface $creditorAddress, AccountInterface $creditorAccount, FinancialInstitutionInterface $creditorAgent)
{
if (!$amount instanceof Money\EUR && !$amount instanceof Money\DKK) {
throw new InvalidArgumentException(sprintf(
'The amount must be an instance of Money\EUR or Money\DKK (instance of %s given).',
get_class($amount)
));
}
if (!$creditorAgent instanceof BIC && !$creditorAgent instanceof IID) {
throw new InvalidArgumentException('The creditor agent must be an instance of BIC or IID.');
}
parent::__construct($endToEndId, $amount, $creditorName, $creditorAddress);
$this->creditorAccount = $creditorAccount;
$this->creditorAgent = $creditorAgent;
}
/**
* {@inheritdoc}
*/
public function asDom(DOMDocument $doc, PaymentInformation $paymentInformation)
{
$root = $this->buildHeader($doc, $paymentInformation);
$creditorAgent = $doc->createElement('CdtrAgt');
$creditorAgent->appendChild($this->creditorAgent->asDom($doc));
$root->appendChild($creditorAgent);
$root->appendChild($this->buildCreditor($doc));
$creditorAccount = $doc->createElement('CdtrAcct');
$creditorAccount->appendChild($this->creditorAccount->asDom($doc));
$root->appendChild($creditorAccount);
$this->appendPurpose($doc, $root);
$this->appendRemittanceInformation($doc, $root);
return $root;
}
}
| true |
e3c1003a82fd85ce6f00c80713611cb78a857f17 | PHP | bibleexchange/church | /app/Repository/Report/EloquentRepository.php | UTF-8 | 3,724 | 2.65625 | 3 | [
"MIT"
] | permissive | <?php namespace App\Repository\Report;
use \Illuminate\Database\Eloquent\Model as Model;
use \App\Repository\Base\EloquentRepository as BaseRepository;
use \App\Repository\Query\EloquentQueryRepository as QueryRepository;
use \Locker\XApi\Helpers as XAPIHelpers;
use \App\Helpers\Helpers as Helpers;
class EloquentRepository extends BaseRepository implements Repository {
protected $model = '\App\Report';
protected $defaults = [
'name' => 'New report',
'description' => '',
'query' => [],
'since' => null,
'until' => null
];
/**
* Validates data.
* @param [String => Mixed] $data Properties to be changed on the model.
* @throws \Exception
*/
protected function validateData(array $data) {
if (isset($data['name'])) XAPIHelpers::checkType('name', 'string', $data['name']);
if (isset($data['description'])) XAPIHelpers::checkType('description', 'string', $data['description']);
if (isset($data['query'])) XAPIHelpers::checkType('query', 'array', $data['query']);
if (isset($data['since'])) XAPIHelpers::checkType('since', 'string', $data['since']);
if (isset($data['until'])) XAPIHelpers::checkType('until', 'string', $data['until']);
}
protected function format(Model $model) {
$model->query = Helpers::replaceHtmlEntity($model->query);
return $model;
}
/**
* Constructs a store.
* @param Model $model Model to be stored.
* @param [String => Mixed] $data Properties to be used on the model.
* @param [String => Mixed] $opts
* @return Model
*/
protected function constructStore(Model $model, array $data, array $opts) {
// Merges and validates data with defaults.
$data = array_merge($this->defaults, $data);
$this->validateData($data);
// Sets properties on model.
$model->name = $data['name'];
$model->description = $data['description'];
$model->lrs_id = $opts['lrs_id'];
$model->query = Helpers::replaceFullStop($data['query']);
$model->since = $data['since'];
$model->until = $data['until'];
return $model;
}
/**
* Constructs a update.
* @param Model $model Model to be updated.
* @param [String => Mixed] $data Properties to be changed on the model.
* @param [String => Mixed] $opts
* @return Model
*/
protected function constructUpdate(Model $model, array $data, array $opts) {
$this->validateData($data);
// Sets properties on model.
if (isset($data['name'])) $model->name = $data['name'];
if (isset($data['description'])) $model->description = $data['description'];
if (isset($data['query'])) $model->query = Helpers::replaceFullStop($data['query']);
if (isset($data['since'])) $model->since = $data['since'];
if (isset($data['until'])) $model->until = $data['until'];
return $model;
}
/**
* Sets the query.
* @param [type] $lrs [description]
* @param [type] $query [description]
* @param [type] $field [description]
* @param [type] $wheres [description]
*/
public function setQuery($lrs_id, $query, $field, $wheres) {
return \Statement::select($field)
->where('lrs_id', new \MongoId($lrs_id))
->where($wheres, 'like', '%'.$query.'%')
->distinct()
->get()
->take(6);
}
/**
* Gets the statements selected by the report with the given ID and options.
* @param String $id ID to match.
* @param [String => Mixed] $opts
* @return [[String => Mixed]] Statements selected by the report.
*/
public function statements($id, array $opts) {
$report = $this->show($id, $opts);
return (new QueryRepository)->where(
$report->lrs_id,
Helpers::replaceHtmlEntity($report->where)
)->orderBy('stored', 'DESC');
}
} | true |
f21dfebe963c89f1bfdf4d4a2f524683127c1960 | PHP | Izaack-B97/Manejador-de-Contenido---Periodico | /public/staff/articulos/index.php | UTF-8 | 1,889 | 2.546875 | 3 | [] | no_license | <?php require_once('../../../private/initialize.php'); ?>
<?php
$articulos_set = find_all_articulos();
?>
<?php $page_title = 'Articulos'; ?>
<!-- Importamos el header con sus respectivas funciones -->
<?php include(SHARED_PATH . '/staff_header.php'); ?>
<br>
<h3>Listado de Articulos</h3>
<a class="btn btn-success mt-2 mb-4" href="<?php echo url_for('/staff/articulos/new.php')?>">Crear Artículo</a>
<div id="content-articulos" class="content">
<table class="table table-bordered table-hover table-sm" style="width:88%;">
<thead class="text-center">
<tr>
<th scope="col" class="text-left">#</th>
<th scope="col">Título</th>
<th scope="col">Actualización</th>
<th scope="col" class="text-right">Operaciones
<i class="fa fa-cogs"></i>
</th>
</tr>
</thead>
<tbody>
<?php while($articulo = mysqli_fetch_assoc($articulos_set)){ ?>
<tr>
<td scope="row"><?php echo h($articulo['id']); ?></td>
<td class="text-center"><?php echo h($articulo['titulo']); ?></td>
<td class="text-center"><?php echo date("H:ma - d/m/Y", strtotime(h($articulo['update_at']))); ?></td>
<td class="text-right">
<a href="<?php echo url_for('/staff/articulos/show.php?id=' . h($articulo['id'])); ?>" role="button" class="btn btn-outline-primary">Ver</a>
<a href="<?php echo url_for('/staff/articulos/edit.php?id=' . h($articulo['id'])); ?>" role="button" class="btn btn-outline-success">Editar</a>
<a href="<?php echo url_for('/staff/articulos/delete.php?id=' . h($articulo['id'])); ?>" role="button" class="btn btn-outline-danger">Eliminar</button>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<br>
<!-- Importamos el footer con sus funciones cargadas -->
<?php include(SHARED_PATH . '/staff_footer.php'); ?> | true |
7ac4126785042144731fca824f0412c5b3c83c65 | PHP | traedamatic/AppTemplateCakePHP | /Controller/Component/UploadfileComponent.php | UTF-8 | 4,841 | 2.84375 | 3 | [
"MIT"
] | permissive | <?php
class UploadfileComponent extends Component {
/**
* @var string name
*/
public $name = 'Uploadfile';
/**
* @var components settings
*/
public $settings = null;
/**
* @var lastfile name saved
*/
public $lastFileUploaded = null;
/**
*
*/
public $supportedFileExtensions = array(
'image/jpeg' => 'jpeg',
'image/png' => 'png',
'image/gif' => 'gif'
);
public function initialize(Controller $controller) {
parent::initialize($controller);
$defaultSettings = array(
'uploadPath' => APP . 'media' . DS,
'desired_width' => 100
);
if(!empty($this->settings))
$this->settings = array_merge($defaultSettings,$this->settings);
}
/**
*
* uploadFile - upload the form submit file
*
* @params array $file submitted file
* @params string $path path to folder
*/
public function upload($file,$addonPath = false) {
$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$filename = basename($file['name'],$ext);
$fileNameMd5 = hash("sha1",$filename.uniqid().time()).'.'.$ext;
$uploadPath = $this->settings['uploadPath'].DS.$fileNameMd5;
if($addonPath !== false) {
$uploadPath = $this->settings['uploadPath'].DS.$addonPath.DS.$fileNameMd5;
}
if (move_uploaded_file($file['tmp_name'], WWW_ROOT.DS.$uploadPath)) {
$this->lastFileUploaded = $fileNameMd5;
return true;
}
return false;
}
public function uploadImageWithThumb($file,$addonPath = false) {
$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$filename = basename($file['name'],$ext);
$fileNameMd5NoExt = hash("sha1",$filename.uniqid().time());
$fileNameMd5WithExt = hash("sha1",$filename.uniqid().time()).'.'.$ext;
$uploadPath = $this->settings['uploadPath'].DS.$fileNameMd5WithExt;
$uploadPathThumb = $this->settings['uploadPath'].DS."t_".$fileNameMd5WithExt;
if($addonPath !== false) {
$uploadPath = $this->settings['uploadPath'].DS.$addonPath.DS.$fileNameMd5WithExt;
$uploadPathThumb = $this->settings['uploadPath'].DS.$addonPath.DS."t_".$fileNameMd5WithExt;
}
if (move_uploaded_file($file['tmp_name'], $uploadPath)) {
$this->lastFileUploaded = $fileNameMd5WithExt;
$mimeType = mime_content_type($uploadPath);
if(key_exists($mimeType,$this->supportedFileExtensions)) {
if($this->makeThumbnail($uploadPath,$uploadPathThumb,$this->supportedFileExtensions[$mimeType])) {
return true;
} else {
return false;
}
}
return false;
}
return false;
}
/***
*
* the create thumbnail function
* a lot taken from http://davidwalsh.name/create-image-thumbnail-php
*
*/
private function makeThumbnail($source = null,$dest = null , $ext = null){
if(is_null($source) || is_null($ext)) {
}
$sourceImage = false;
$desired_width = $this->settings['desired_width'];
switch($ext) {
case "jpeg":
$sourceImage = imagecreatefromjpeg($source);
break;
case "gif":
$sourceImage = imagecreatefromgif($source);
break;
case "png":
$sourceImage = imagecreatefrompng($source);
break;
default:
break;
}
if($sourceImage === false) return false;
/* read the source image */
$width = imagesx($sourceImage);
$height = imagesy($sourceImage);
/* find the "desired height" of this thumbnail, relative to the desired width */
$desired_height = floor($height * ($desired_width / $width));
/* create a new, "virtual" image */
$virtual_image = imagecreatetruecolor($desired_width, $desired_height);
/* copy source image at a resized size */
imagecopyresampled($virtual_image, $sourceImage, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);
switch($ext) {
case "jpeg":
$result = imagejpeg($virtual_image, $dest);
break;
case "gif":
$result = imagegif($virtual_image, $dest);
break;
case "png":
$result = imagepng($virtual_image, $dest);
break;
default:
break;
}
/* create the physical thumbnail image to its destination */
return $result;
}
public function uploadMultipleFiles($files) {
foreach ($files as $index => $file) {
$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$filename = basename($file['name'],$ext);
$fileNameMd5 = md5($filename).'.'.$ext;
$uploadPath = $this->settings['uploadPath'].$fileNameMd5;
if (move_uploaded_file($file['tmp_name'], $uploadPath)) {
$error[$fileName] = false;
} else {
$error[$fileName] = true;
}
}
return $error;
}
} | true |
530b6580084aa20a6384fd24afdaf0d6b4007a5e | PHP | ralf000/mvc | /app/models/CRUDInterface.php | UTF-8 | 151 | 2.71875 | 3 | [] | no_license | <?php
namespace app\models;
interface CRUDInterface {
public static function findById($id);
public static function findAll();
}
| true |
6492f7198663ce5489cea3017c9214cb37407bef | PHP | antoniocarlosmjr/pagamento-simplificado | /src/app/Exceptions/TransacaoException.php | UTF-8 | 647 | 2.71875 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Exceptions;
use Exception;
use Illuminate\Http\JsonResponse;
use Throwable;
/**
* Class TransacaoException
* @package App\Exceptions
* @author Antonio Martins
*/
class TransacaoException extends Exception
{
/**
* TransacaoException constructor.
* @param string $message
* @param int $code
* @param Throwable|null $previous
*/
public function __construct(
string $message = 'Erro ao realização ação em transação',
int $code = JsonResponse::HTTP_UNPROCESSABLE_ENTITY,
Throwable $previous = null
) {
parent::__construct($message, $code, $previous);
}
}
| true |
534c497fd750fdd5ec8789ea8d5d6c3412371531 | PHP | SergioGomez24/asignaciones | /database/seeds/CampusTableSeeder.php | UTF-8 | 445 | 2.71875 | 3 | [] | no_license | <?php
use Illuminate\Database\Seeder;
use App\Campus;
class CampusTableSeeder extends Seeder
{
private function seedCampus(){
DB::table('campus')->delete();
$c = new Campus;
$c->name = 'Campus de Puerto Real';
$c->save();
}
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
self::seedCampus();
$this->command->info('Tabla campus inicializada con datos!');
}
}
| true |
0511853915ad34e6eec9386991d554c7139852ed | PHP | khoipv-1315/designPattern | /SingletonPattern/index.php | UTF-8 | 536 | 2.984375 | 3 | [] | no_license | <?php
require('Database.php');
require('SingletonDatabase.php');
// get a instance database
$database = new Database('product');
print_r($database->getName());
print_r('</br>');
$database = new Database('product_b');
print_r($database->getName());
print_r('</br>');
// get a instance database with singleton
$databaseSingleton = SingletonDatabase::getInstance('prod');
print_r($databaseSingleton->getName());
print_r('</br>');
$databaseSingleton = SingletonDatabase::getInstance('prod_b');
print_r($databaseSingleton->getName());
| true |
a2c22d64d1f6849fa5ac476c066a0265fcc95f81 | PHP | toddpan/sooncore-admin | /application/libraries/Account/AccountUpload/SitePowerChangeUploadImpl.php | UTF-8 | 1,216 | 2.515625 | 3 | [] | no_license | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* 站点权限变更
* @file SitePowerChangeUploadImpl.php
* @author caohongliang <hongliang.cao@quanshi.com>
* @copyright Copyright (c) UC
* @version: v1.0
*/
require_once(__DIR__.DIRECTORY_SEPARATOR.'AccountUploadInterface.php');
class SitePowerChangeUploadImpl extends AccountUploadInterface{
public function __construct(){
parent::__construct();
}
/**
* @brief站点权限变更
*
* @detail
* -参数校验
* -遍历该站点组织下所有的组织以及用户(过滤掉已经自定义了权限的组织或者用户)
* -组织boss数据
* -分批发送请求
*/
public function process($value){
//参数校验
$required = array('customer_code', 'site_id', 'org_id');
$optional = array('sellingProducts');
list($valid, $msg) = $this->checkParam($value, $required, $optional);
if(!$valid){
throw new Exception($msg);
}
$uc = &$msg;
//获取站点url作为templateUUID
$site_url = $this->ci->account_model->getSiteUrl($uc['site_id']);
//权限变更
return $this->powerChange($uc['customer_code'], $uc['site_id'], $uc['org_id'], $site_url);
}
}
| true |
89e2113e623af7b2882d909a4f5bae5a45ee7cd3 | PHP | 10degrees/10degrees-base | /app/Boot/GoogleMapsAPIIntegration.php | UTF-8 | 2,009 | 2.53125 | 3 | [] | no_license | <?php
namespace App\Boot;
/**
* Google Maps API Instructions
*
* 1. Make sure you're logged in as support@10degrees.uk
* 2. Go to https://developers.google.com/maps/documentation/javascript/
* 3. Click "Get a key"
* 4. Create a key
* 5. Name the project as per the domain, using spaces, .e.g. domain-co-uk
* 6. Ensure you add these domains as authorised: *.domain.dev, *.domain.co.uk, domain.wpengine.com, domain.staging.wpengine.com
* 7. Replace YOUR_API_KEY in wp_enqueue_script call below
*
* @category Theme
* @package TenDegrees/10degrees-base
* @author 10 Degrees <wordpress@10degrees.uk>
* @license https://www.gnu.org/licenses/old-licenses/gpl-2.0.en.html GPL-2.0+
* @link https://github.com/10degrees/10degrees-base
* @since 2.0.0
*/
class GoogleMapsAPIIntegration
{
/**
* Set this to true if using Google Maps
*
* @var boolean
*/
protected $enableGoogleMaps = false;
/**
* Paste your Google Maps API Key here
*
* @var string
*/
protected $apiKey = '';
/**
* If Google Maps is enabled, register the API key and enqueue the javascript file.
*/
public function __construct()
{
if (!$this->enableGoogleMaps) {
return;
}
add_action('acf/init', [$this, 'registerAPIKey']);
add_action('wp_enqueue_scripts', [$this, 'enqueue'], 100);
}
/**
* Registers the Google Maps API Key in the ACF Settings
*
* @return void
*/
public function registerAPIKey()
{
acf_update_setting('google_api_key', $this->apiKey);
}
/**
* Enqueues the Google Maps API JS with your API key. Feel free to
* add conditionals here if only required on specific page
* templates or custom post types.
*
* @return void
*/
public function enqueue()
{
wp_enqueue_script('google-maps', '//maps.googleapis.com/maps/api/js?key=' . $this->apiKey, array(), '3', true);
wp_enqueue_script('google-map-init');
}
}
| true |
2f7d13439afa2cd182f4a8719248b701b3412607 | PHP | ecjia/ecjia-daojia | /vendor/classpreloader/classpreloader/src/Factory.php | UTF-8 | 2,326 | 2.890625 | 3 | [
"MIT"
] | permissive | <?php
/*
* This file is part of Class Preloader.
*
* (c) Graham Campbell <graham@alt-three.com>
* (c) Michael Dowling <mtdowling@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace ClassPreloader;
use ClassPreloader\Parser\DirVisitor;
use ClassPreloader\Parser\FileVisitor;
use ClassPreloader\Parser\NodeTraverser;
use ClassPreloader\Parser\StrictTypesVisitor;
use PhpParser\Lexer;
use PhpParser\Parser;
use PhpParser\ParserFactory;
use PhpParser\PrettyPrinter\Standard as PrettyPrinter;
/**
* This is the class preloader factory class.
*
* This class is a simple way to create a class preloader instance.
*/
class Factory
{
/**
* Create a new class preloader instance.
*
* Any options provided determine how the node traverser is setup.
*
* @param bool[] $options
*
* @return \ClassPreloader\ClassPreloader
*/
public function create(array $options = [])
{
$printer = new PrettyPrinter();
$parser = $this->getParser();
$options = array_merge(['dir' => true, 'file' => true, 'skip' => false, 'strict' => false], $options);
$traverser = $this->getTraverser($options['dir'], $options['file'], $options['skip'], $options['strict']);
return new ClassPreloader($printer, $parser, $traverser);
}
/**
* Get the parser to use.
*
* @return \PhpParser\Parser
*/
protected function getParser()
{
if (class_exists(ParserFactory::class)) {
return (new ParserFactory())->create(ParserFactory::PREFER_PHP7);
}
//return new Parser(new Lexer());
}
/**
* Get the node traverser to use.
*
* @param bool $dir
* @param bool $file
* @param bool $skip
* @param bool $strict
*
* @return \ClassPreloader\Parser\NodeTraverser
*/
protected function getTraverser($dir, $file, $skip, $strict)
{
$traverser = new NodeTraverser();
if ($dir) {
$traverser->addVisitor(new DirVisitor($skip));
}
if ($file) {
$traverser->addVisitor(new FileVisitor($skip));
}
if (!$strict) {
$traverser->addVisitor(new StrictTypesVisitor());
}
return $traverser;
}
}
| true |
c88165adc9827b9a7bccd46423b758ed4e47caf9 | PHP | kentprojects/api | /admin/classes/session.php | UTF-8 | 1,682 | 3.140625 | 3 | [
"MIT"
] | permissive | <?php
/**
* @author: James Dryden <james.dryden@kentprojects.com>
* @license: Copyright KentProjects
* @link: http://kentprojects.com
*
* Class Session
* Sessions hold data that is meant to surpass a single page.
*/
class Session
{
/**
* Delete a (range of) Session key(s).
*
* @param string $key
* [ @param string $key ] Delete as many at once as required.
* @return void
*/
public static function delete($key)
{
foreach (func_get_args() as $key)
{
unset($_SESSION[(string)$key]);
}
}
/**
* Destroys the session.
* This action is irreversible. Are you sure you wish to continue? [Y/n]
* @return void
*/
public static function destroy()
{
session_destroy();
}
/**
* Get session data.
*
* @param string $key
* @param mixed $default (defaults to null)
* @return mixed
*/
public static function get($key, $default = null)
{
return (static::has($key))
? unserialize($_SESSION[(string)$key])
: $default;
}
/**
* Get session data and remove it afterwards.
*
* @param string $key
* @param mixed $default (defaults to null)
* @return mixed
*/
public static function getOnce($key, $default = null)
{
$value = static::get($key, $default);
static::delete($key);
return $value;
}
/**
* Check to see if we have session data under a certain key.
*
* @param string $key
* @return boolean
*/
public static function has($key)
{
return (isset($_SESSION[(string)$key]));
}
/**
* Set some session data.
*
* @param string $key
* @param mixed $value
* @return void
*/
public static function set($key, $value)
{
$_SESSION[(string)$key] = serialize($value);
}
}
session_name("session");
session_start(); | true |
eda5638ecf910f56fc57460492b386714bedbc85 | PHP | lausek/inf19bot | /src/cmds/help.php | UTF-8 | 726 | 2.875 | 3 | [] | no_license | <?php
require_once __DIR__ . '/../../vendor/autoload.php';
// Display all commands that implement `HasHelp`.
class HelpCommand extends Command implements HasHelp
{
function help() : string
{
return Language::get('CMD_HELP_HELP');
}
function run(Response $response, $update = null)
{
$output = Language::get('CMD_HELP_GREET') . "\n\n";
foreach (self::get_all() as $name => $classname)
{
$cmd = new $classname;
if ($cmd instanceof HasHelp)
{
$output .= "- /$name: " . $cmd->help() . "\n";
}
}
$output .= "\n" . Language::get('CMD_HELP_END');
$response->add_message($output);
}
}
| true |
7925dfc48154ace8ea8119426a69a575781033b7 | PHP | UCLComputerScience/COMP0034-PHPBasics | /databasePhp/phpGetUsers.php | UTF-8 | 1,374 | 3.265625 | 3 | [] | no_license | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="../css/bootstrap.css">
<title>List of users</title>
</head>
<body>
<div class="container">
<h3>List of users in the database</h3>
<br>
<?php
require_once 'phpDatabaseConnection.php';
// Connect to the database
$connection = connectToDb();
// Build the query statement, shown in two steps as you might need this for your coursework
$query = "SELECT firstName, familyName FROM Users ";
$query .= "ORDER BY familyName DESC";
// Execute the query and retrieve the results
$result = mysqli_query($connection, $query);
// Display all the users in a table format
?>
<table class="table">
<tr>
<th>First name</th>
<th>Family name</th>
</tr>
<?php while ($user = mysqli_fetch_array($result)) { ?>
<tr>
<td><?php echo $user['firstName'] ?></td>
<td><?php echo $user['familyName'] ?></td>
</tr>
<?php } ?>
</table>
<?php
// Free the results from memory
mysqli_free_result($result_set);
// Close the connection
closeDb($connection);
?>
</div>
</body>
</html> | true |
40defa44251e2f2e24d795aa7986ff350b3d2477 | PHP | tiagofinger/boardingpass | /tests/CityTest.php | UTF-8 | 692 | 2.953125 | 3 | [] | no_license | <?php
use PHPUnit\Framework\TestCase;
use \App\Classes\City;
class CityTest extends TestCase
{
public function testOK()
{
$city1 = new City('Roma');
$city2 = new City('Roma');
$this->assertEquals($city1, $city2);
}
public function testNotOK()
{
$city1 = new City('London');
$city2 = new City('Zurich');
$this->assertNotEquals($city1, $city2);
}
public function testEmpty()
{
$city = new City();
$this->assertEmpty($city->getName());
}
public function testNotEmpty()
{
$city = new City('São Paulo');
$this->assertNotEmpty($city->getName());
}
}
| true |
f1311b7f72a0fbe8dff867af457b732b8a9e7db3 | PHP | maxiatanasio/curso-php-oop | /clase2/2-mysql/index.php | UTF-8 | 748 | 2.84375 | 3 | [] | no_license | <?php
require __DIR__ . '/classes/MysqlConnection.php';
// require( __DIR__ . '/mySQLExtend.class.php');
$operation = $_GET['action'] ?? 'get';
try {
$mysql = new MySQLConnection("localhost", "notesdb", "root", "");
switch($operation) {
case 'get' :
$mysql->query('select * from notes');
print_r($mysql->arrayFromResult());
var_dump($mysql->getRowsNum());
break;
case 'add' :
$randomNumber = rand(0,1000);
$mysql->query("insert into notes (title, body) values ('Titulo - {$randomNumber}','Cuerpo de la nota')");
echo "Note $randomNumber added";
break;
default:
}
} catch (DatabaseException $e) {
echo $e->get();
} | true |
b859b4e36e8d7e4b9175469c98b040c6bb377fc0 | PHP | Aggie21/TestCase | /application/library/Models/Excel/GameVersionDB.php | UTF-8 | 665 | 2.640625 | 3 | [] | no_license | <?php
class Models_Excel_GameVersionDB{
public function getAllGameVersion(){
}
/**
* 获取游戏的版本
* @param unknown_type $gameId
* @return multitype:multitype:unknown
*/
public function getGameVersionByGameId($gameId){
$db = new DBTool_DB();
$sql = "select * from tc_game_v where game_id = ?";
$params = array("i",$gameId);
$gameversions = $db->query($sql, $params);
return $gameversions;
}
public function getGameVersionById($game_v_id){
$db = new DBTool_DB();
$sql = "select * from tc_game_v where game_v_id = ?";
$params = array("i",$game_v_id);
$gameversion = $db->query($sql, $params);
return $gameversion;
}
} | true |
ffa001add5b99a96f15d0e50d65bb04ae71abd0f | PHP | Gouga34/SiteSPA | /SPA-beziers/models/Utilisateur.php | UTF-8 | 1,078 | 2.703125 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
namespace app\models;
use Yii;
/**
* This is the model class for table "utilisateur".
*
* @property string $type
* @property string $mdp
* @property string $nom
* @property string $prenom
* @property string $mail
* @property integer $telephone
*/
class Utilisateur extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'utilisateur';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['type', 'mdp', 'nom', 'prenom', 'mail', 'telephone'], 'required'],
[['type'], 'string'],
[['telephone'], 'integer'],
[['mdp', 'nom', 'prenom', 'mail'], 'string', 'max' => 100]
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'type' => 'Type',
'mdp' => 'Mot De Passe',
'nom' => 'Nom',
'prenom' => 'Prénom',
'mail' => 'Mail',
'telephone' => 'Téléphone',
];
}
}
| true |
10bb73a36cb34ba399fb82e3948e8e6c8ea166f4 | PHP | fullstackbelgium/fullstackbelgium.be | /app/Console/Commands/SendScheduledTweetsCommand.php | UTF-8 | 578 | 2.546875 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Console\Commands;
use App\Models\ScheduledTweet;
use Illuminate\Console\Command;
class SendScheduledTweetsCommand extends Command
{
protected $signature = 'fullstack:send-scheduled-tweets';
protected $description = 'Send scheduled tweets';
public function handle()
{
$this->info('Sending scheduled tweets');
$events = ScheduledTweet::shouldBeSent()
->get()
->each
->send();
$this->info("{$events->count()} scheduled tweets sent!");
$this->info('All done!');
}
}
| true |
40cb9abf6e564714a5da7c831377e909bfbe108a | PHP | 329944908/blog | /model/BlogModel.class.php | UTF-8 | 953 | 2.8125 | 3 | [] | no_license | <?php
class BlogModel{
public $mysqli;
function __construct(){
$this->mysqli = new mysqli("localhost","root","123456","blog");
$this->mysqli->query('set names utf8');
}
public function add($data){
$createtime = date("Y-m-d H:i:s");
$sql = "insert into blog(title,content,image,classify_id,createtime) values('{$data['title']}','{$data['content']}','{$data['image']}',{$data['classify_id']},'{$createtime}')";
$this->mysqli->query($sql);
}
function getBlogLists($offset=0,$pageSize=20,$order ='id asc',$where='1'){
$sql = "select * from blog where {$where} order by {$order} limit {$offset},{$pageSize}";
$res = $this->mysqli->query($sql);
$data = $res->fetch_all(MYSQLI_ASSOC);
return $data;
}
function getBlogInfo($id){
$sql = "select * from blog where id = {$id}";
$res = $this->mysqli->query($sql);
$data = $res->fetch_all(MYSQLI_ASSOC);
return isset($data[0]) ? $data[0] : array();
}
} | true |
4ddd01a03a19e14619c1c499ea8f80f29716a0c2 | PHP | mithunmo/phpsample | /libraries/cli/command/serialise.class.php | UTF-8 | 1,820 | 3.390625 | 3 | [] | no_license | <?php
/**
* cliCommandSerialise Class
*
* Stored in cliCommandSerialise.class.php
*
* @author Dave Redfern
* @copyright Dave Redfern (c) 2007-2010
* @package scorpio
* @subpackage cli
* @category cliCommandSerialise
* @version $Rev: 707 $
*/
/**
* cliCommandSerialise class
*
* Utility command that simple passes the input into the PHP serialize
* function and outputs it. Useful if you have to hack a database record
* that is a serialised string of text for instance.
*
* A specific example: the baseTableParamSet stores all properties as
* serialised strings by default. This command can be used to replace an
* existing entry in a param set.
*
* <code>
* // just serialises whatever you pass on the CLI
* $oApp = new cliApplication('example', 'A simple example.');
* $oRequest = cliRequest::getInstance()->setApplication($oApp);
* $oApp->getCommandChain()
* ->addCommand(new cliCommandSerialise($oRequest))
* $oApp->execute($oRequest);
* </code>
*
* @package scorpio
* @subpackage cli
* @category cliCommandSerialise
*/
class cliCommandSerialise extends cliCommand {
const COMMAND = 'serialise';
/**
* Creates a new command
*
* @param cliRequest $inRequest
*/
function __construct(cliRequest $inRequest) {
parent::__construct($inRequest, self::COMMAND);
$this->setCommandHelp('Serialises the command line string, useful for updating strings in the database');
$this->setCommandRequiresValue(true);
}
/**
* Executes the command
*
* @return void
*/
function execute() {
$this->getRequest()->getApplication()->getResponse()
->addResponse("Serialising: ",$this->getRequest()->getParam(self::COMMAND))
->addResponse(serialize($this->getRequest()->getParam(self::COMMAND)));
}
} | true |
560c65fccc4ca44b24691c9469bbb8028ebe86b5 | PHP | Bagro/tvcenter | /application/helpers/auth_helper.php | UTF-8 | 984 | 2.609375 | 3 | [] | no_license | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if ( ! function_exists('is_logged_in'))
{
function is_logged_in()
{
$CI =& get_instance();
$isloggedin = $CI->session->userdata('isloggedin');
if(isset($isloggedin))
return $isloggedin;
return false;
}
}
if ( ! function_exists('current_userid'))
{
function current_userid()
{
$CI =& get_instance();
$userId = $CI->session->userdata('userid');
if(isset($userId))
return $userId;
return 0;
}
}
if ( ! function_exists('is_in_group'))
{
function is_in_group($groupId)
{
$CI =& get_instance();
$usrGroupId = $CI->session->userdata("groupid");
if(isset($usrGroupId) && $usrGroupId == $groupId)
return true;
return false;
}
}
if ( ! function_exists('current_sessionId'))
{
function current_sessionId(){
$CI =& get_instance();
$sessionId = $CI->session->userdata('session_id');
if(isset($sessionId))
return $sessionId;
return false;
}
}
?> | true |
c9ebd6dc793ffaba7d8c227e9641ab9029b2bb92 | PHP | happyabbi/excelsparser | /app/models/Autoencode.php | UTF-8 | 1,188 | 2.625 | 3 | [] | no_license | <?php
class Autoencode extends \Phalcon\Mvc\Model
{
/**
*
* @var string
*/
public $code_type;
/**
*
* @var integer
*/
public $code_max;
/**
*
* @var integer
*/
public $code_count;
/**
*
* @var string
*/
public $code_head;
/**
* Independent Column Mapping.
*/
public function columnMap()
{
return array(
'code_type' => 'code_type',
'code_max' => 'code_max',
'code_count' => 'code_count',
'code_head' => 'code_head'
);
}
public static function generateAutoEncode($type){
$autoencode=Autoencode::findFirst("code_type='{$type}'");
if (!$autoencode)
throw new \Phalcon\Exception('no data');
$codeMax=$autoencode->code_max;
$codeCount = $autoencode->code_count + 1;
$codeHead = $autoencode->code_head;
$value = str_pad($codeCount, $codeMax-strlen($codeHead), '0', STR_PAD_LEFT); //補零
$value = $codeHead . $value;
$autoencode->code_count = $codeCount;
$autoencode->save();
return $value;
}
}
| true |
dc000793b0ebf29cb779efc31a7e20197e7e115f | PHP | BGCX262/zweer-reload-svn-to-git | /trunk/library/Zwe/Model/Page/Messages.php | UTF-8 | 3,462 | 2.796875 | 3 | [] | no_license | <?php
/**
* @file library/Zwe/Model/Page/Messages.php
* Il modello della pagina dei messaggi.
*
* @category Zwe
* @package Zwe_Model
* @subpackage Zwe_Model_Page
* @version $Id: Messages.php 112 2011-08-01 14:57:36Z flicofloc@gmail.com $
*/
/**
* Il modello della pagina dei messaggi.
* E' una pagina fissa, quindi non può pescare le informazioni dal database.
* Per compatibilità vengono settate a mano tutte le informazioni.
*
* @uses Zwe_Model_Page
* @category Zwe
* @package Zwe_Model
* @subpackage Zwe_Model_Page
*/
class Zwe_Model_Page_Messages extends Zwe_Model_Page
{
/**
* I messaggi da visualizzare
*
* @var array
*/
protected $_messages = array();
/**
* L'uri della pagina dei messaggi.
*
* @var string
*/
const MESSAGES_URL = '/messages';
/**
* Quante conversazioni stanno in una pagina.
*
* @var int
*/
const CONVERSATIONS_PER_PAGE = 20;
public static function getConversations($IDUser, $Page = 0)
{
$Message = new Zwe_Model_Message();
$Select = $Message->select()->join(array('mm' => 'message'), 'message.IDMessage = mm.IDLastMessage', array())
->join(array('r' => 'message_receiver'), 'mm.IDMessage = r.IDMessage', 'IDUser')
->where("IDUser = '$IDUser' AND mm.IDParent = mm.IDMessage AND Deleted = '0'")
->order("mm.DateLastMessage DESC")
->limitPage($Page + 1, self::CONVERSATIONS_PER_PAGE);
$RowConversations = $Message->fetchAll($Select);
$Conversations = array();
if($RowConversations)
{
foreach($RowConversations as $RowConversation)
{
$M = new Zwe_Model_Message();
$Conversations[] = $M->copyFromDb($RowConversation);
}
}
return $Conversations;
}
public static function getConversation($IDConversation)
{
$TheMessage = new Zwe_Model_Message();
$Select = $TheMessage->select()->where("IDParent = '$IDConversation'")
->order("Date");
$Conversation = $TheMessage->fetchAll($Select);
$Messages = array();
if($Conversation)
{
foreach($Conversation as $Message)
{
$M = new Zwe_Model_Message();
$Messages[] = $M->copyFromDb($Message);
}
}
return $Messages;
}
/**
* L'inizializzazione dell'oggetto.
* Si assegna il titolo della pagina a mano.
*
* @param array $config
*/
public function __construct($config = array())
{
parent::__construct($config);
$this->Title = 'Messages';
}
public function __get($Name)
{
if('Messages' == $Name)
return $this->_messages;
else
return parent::__get($Name);
}
public function __set($Name, $Value)
{
if('Messages' == $Name)
{
if(is_array($Value))
$this->_messages = $Value;
else
throw new Exception('$Value must be an array');
}
else
parent::__set($Name, $Value);
}
}
?> | true |
253b53e810305b55171c102e42ffa1928f030c08 | PHP | master4eg/Vostok_Laravel | /app/Http/Controllers/UsersController.php | UTF-8 | 2,718 | 2.71875 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
class UsersController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$users = User::get();
$count = $users->count();
return view('users.index', compact('users', 'count'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('users.form');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$user = $request->only('firstName', 'secondName', 'middleName', 'debt');
$stateFee = $this->calcStateFee($user['debt']);
$user['stateFee'] = $stateFee;
//dd($user);
User::create($user);
return redirect()->route('users.index');
}
/**
* Display the specified resource.
*
* @param \App\Models\User $user
* @return \Illuminate\Http\Response
*/
public function show(User $user)
{
return view('users.show', compact('user'));
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\User $user
* @return \Illuminate\Http\Response
*/
public function edit(User $user)
{
return view('users.form', compact('user'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\User $user
* @return \Illuminate\Http\Response
*/
public function update(Request $request, User $user)
{
$newUserData = $request->only(['firstName', 'secondName', 'middleName', 'debt']);
$stateFee = $this->calcStateFee($newUserData['debt']);
$newUserData['stateFee'] = $stateFee;
$user->update($newUserData);
return redirect()->route('users.index');
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\User $user
* @return \Illuminate\Http\Response
*/
public function destroy(User $user)
{
$user->delete();
return redirect()->route('users.index');
}
/**
* Calc stateFee of debt sum.
*
* @param float $debt
* @return float
*/
protected function calcStateFee(float $debt = 0)
{
$stateFee = $debt / 100 * 13;
$stateFee = number_format($stateFee,2,'.','');
return $stateFee;
}
}
| true |
7a071e5ccd45025f34a97c8effa78d50706be79a | PHP | filipe-ferraz/CeL | /instalacaoCEL/cel/aplicacao/script_bd.php | WINDOWS-1252 | 3,918 | 2.671875 | 3 | [] | no_license | <html>
<head>
<title></title>
</head>
<body>
<?php
include_once("bd.inc") ;
include_once("CELConfig/CELConfig.inc");
$link = bd_connect() or die("Erro na conexo BD : " . mysql_error() . __LINE__);
if ( $link && mysql_select_db(CELConfig_ReadVar("BD_database") ))
echo "SUCESSO NA CONEXO BD <br>";
else
echo "ERRO NA CONEXO BD <br>";
/* query para a adio do campo tipo na tabela de lexicos*/
/*
$query = "alter table lexico add tipo varchar(15) NULL after nome;";
$result = mysql_query($query) or die("A consulta BD falhou : " . mysql_error() . __LINE__);
*/
/* query pra tirar o campo impacto da tabela lexico */
/*
$query = "alter table lexico drop impacto;";
$result = mysql_query($query) or die("A consulta BD falhou : " . mysql_error() . __LINE__);
*/
/* query pra criar a tabela de impactos */
/*
$query = "create table impacto (id_impacto int(11) not null AUTO_INCREMENT,
id_lexico int(11) not null ,
impacto varchar(250) not null,
unique key(id_impacto),
primary key(id_lexico, impacto)
);";
$result = mysql_query($query) or die("A consulta BD falhou : " . mysql_error() . __LINE__);
$query = "insert into impacto (id_impacto, id_lexico, impacto) VALUES (0,0, 'TESTE');";
$result = mysql_query($query) or die("A consulta BD falhou : " . mysql_error() . __LINE__);
$query = "delete from impacto;";
$result = mysql_query($query) or die("A consulta BD falhou : " . mysql_error() . __LINE__);
*/
// query para criar tabela de conceitos. __JERONIMO__
$query = "create table conceito (id_conceito int(11) not null AUTO_INCREMENT,
nome varchar(250) not null ,
descricao varchar(250) not null,
pai int(11),
unique key(nome),
primary key(id_conceito)
);";
$result = mysql_query($query) or die("A consulta BD falhou : " . mysql_error() . __LINE__);
$query = "create table relacao_conceito (id_conceito int(11) not null,
id_relacao int(11) not null,
predicado varchar(250) not null
);";
$result = mysql_query($query) or die("A consulta BD falhou : " . mysql_error() . __LINE__);
$query = "create table relacao (id_relacao int(11) not null AUTO_INCREMENT,
nome varchar(250) not null ,
unique key(nome),
primary key(id_relacao)
);";
$result = mysql_query($query) or die("A consulta BD falhou : " . mysql_error() . __LINE__);
$query = "create table axioma (id_axioma int(11) not null AUTO_INCREMENT,
axioma varchar(250) not null ,
unique key(axioma),
primary key(id_axioma)
);";
$result = mysql_query($query) or die("A consulta BD falhou : " . mysql_error() . __LINE__);
$query = "create table algoritmo (id_variavel int(11) not null AUTO_INCREMENT,
nome varchar(250) not null ,
valor varchar(250) not null ,
unique key(nome),
primary key(id_variavel)
);";
$result = mysql_query($query) or die("A consulta BD falhou : " . mysql_error() . __LINE__);
mysql_close($link);
?>
</body>
</html>
| true |
5e87e533e810e95f018eb8f053f712f0895444bd | PHP | eujoanderson/twiter_clone | /vendor/MF/Init/BootStrap.php | UTF-8 | 1,201 | 3.140625 | 3 | [] | no_license | <?php
namespace MF\Init;
abstract class Bootstrap{
protected $routes;
abstract protected function initRoutes(); //contrato
public function __construct() {
$this->initRoutes();
$this->run($this->getUrl());
} //Recebe no contructor o array e a url passada pelo Cliente
public function getRoutes() {
return $this->routes;
} //Retorna o atributo privado
public function setRoutes(array $routes) {
$this->routes = $routes;
}//Seta o array dentro do atributo privado
protected function run($url) {
foreach ($this->getRoutes() as $key => $route) {
if($url == $route['route']) {
$classe = "App\\Controllers\\".ucfirst($route['controller']);//instancia de indexController.php
$controller = new $classe;
$action = $route['action'];
$controller->$action();
}
}
} //-|||percorrendo o array e seus respesctivos índices
//-||| criação de um operarador condicional onde $url == $url['route']
//-||| instancia da class atráves dos namespaces
protected function getUrl() {
return parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); //retorna a URL parse_url(path)
}//retorna a requisição feita através do GET da Página
}
?> | true |
cee78ae94d1bff81079dbf4e1e6125cd00dfb58d | PHP | solale-dev/MVC_todo | /Models/AnmeldungModel.php | UTF-8 | 1,561 | 2.828125 | 3 | [] | no_license | <?php
class AnmeldungModel extends Model
{
public function create($Anmeldename, $Password, $KundenID)
{
$sql = "INSERT INTO anmeldungen (Anmeldename, Password, KundenID) VALUES (:Anmeldename, :Password, :KundenID)";
$req = Database::getBdd()->prepare($sql);
return $req->execute([
'Anmeldename' => $Anmeldename,
'Password' => $Password,
'KundenID' => $KundenID
]);
}
public function showAnmeldung($Anmeldename)
{
$sql = "SELECT * FROM anmeldungen WHERE Anmeldename = ?";
$req = Database::getBdd()->prepare($sql);
$req->execute([$Anmeldename]);
return $req->fetch();
}
public function showAllAnmeldungen()
{
$sql = "SELECT * FROM anmeldungen";
$req = Database::getBdd()->prepare($sql);
$req->execute();
return $req->fetchAll();
}
public function edit($Anmeldename, $Password, $neuesPassword)
{
$passwordhash = password_hash($neuesPassword, PASSWORD_DEFAULT);
$sql = "UPDATE anmeldungen SET Password = :passwordhash WHERE Anmeldename = :Anmeldename";
$req = Database::getBdd()->prepare($sql);
return $req->execute([
'Anmeldename' => $Anmeldename,
'passwordhash' => $passwordhash
]);
}
public function delete($Anmeldename)
{
$sql = 'DELETE FROM anmeldungen WHERE Anmeldename = ?';
$req = Database::getBdd()->prepare($sql);
return $req->execute([$Anmeldename]);
}
}
?> | true |
ba390d1a42f660e490efd78e0e538cffe2a2cb6c | PHP | chiubor/PHP_Homework | /homework/3_1.php | UTF-8 | 762 | 3.296875 | 3 | [] | no_license | <!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<h3>將 images 底下的圖片全部存成 base64的格式到陣列中,<br>
接著將陣列中圖片全部顯示出現</h3>
<?php
if ($handle = opendir('images')) {
$fileArray = [];
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$path = "images/$file";
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
array_push($fileArray, $base64);
}
}
closedir($handle);
foreach ($fileArray as $file) {
echo "<img src='$file' width=400><br>";
}
}
?>
</body> | true |
1111b4b35eab882f03bf1a00bd7b22c8c70a1110 | PHP | phalapi/phalapi | /vendor/phalapi/kernal/src/Error.php | UTF-8 | 716 | 2.75 | 3 | [
"GPL-3.0-only",
"Apache-2.0"
] | permissive | <?php
namespace PhalApi;
/**
* 错误类
*
* @package PhalApi\Error
* @license http://www.phalapi.net/license GPL 协议 GPL 协议
* @link http://www.phalapi.net/
* @author dogstar <chanzonghuang@gmail.com> 2020-03-25
*/
interface Error {
/**
* 自定义的错误处理函数
* @param int $errno 包含了错误的级别,是一个 integer
* @param string $errstr 包含了错误的信息,是一个 string
* @param string $errfile 可选的,包含了发生错误的文件名,是一个 string
* @param int $errline 可选项,包含了错误发生的行号,是一个 integer
*/
public function handleError($errno, $errstr, $errfile = '', $errline = 0);
}
| true |
afd0b5d2231a9f462309ec06f5d0bb034e6422fb | PHP | 89Omer/classifiedmarkaz | /app/Http/Controllers/Api/SubCategoryController.php | UTF-8 | 1,807 | 2.5625 | 3 | [] | no_license | <?php
namespace App\Http\Controllers\Api;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\SubCategory;
class SubCategoryController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
try {
$subcategory = SubCategory::all();
$data['success'] = 'true';
$data['message'] = '';
$data['data'] = $subcategory;
$data['error'] = 'false';
return response()->json(['success'=>$data],200);
} catch (Exception $ex) { // Anything that went wrong
$data['success'] = 'false';
$data['message'] = '';
$data['data'] = $ex->getMessage();
$data['error'] = 'true';
return response()->json(['error'=>$data],401);
}
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($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)
{
//
}
}
| true |
6ccf0df41ec6579feaf12e6966cbabd44d74a910 | PHP | francoisauclair911/stripe-mock-example | /app/Models/Charge.php | UTF-8 | 457 | 2.765625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
/**
* Class Charge
* @package App\Models
*
* @property float $amount
* @property string $currency
* @property string $type
*/
class Charge extends Model
{
protected $fillable = [
'amount',
'currency',
'type',
'stripe_id',
];
public function getAmountAttribute(): float
{
return $this->attributes['amount'] / 100;
}
}
| true |
5b75b7e49dc8a04c3b0442adf30875103e96e33c | PHP | ANDERSOUNDZ/LaravelFinal | /database/seeds/UserTableSeeder.php | UTF-8 | 709 | 2.609375 | 3 | [
"MIT"
] | permissive | <?php
use Illuminate\Database\Seeder;
class UserTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$user = new \App\User();
$user -> name = 'Daniel Romero';
$user -> email = 'daniel@ed.team';
$user -> password = bcrypt('secret');
$user -> save();
for ($i = 0; $i< 50; $i++){
$user->movements()->save(factory(App\Movement::class)->make());
}
factory(App\User::class, 10)->create()->each(function($u){
for ($i = 0; $i< 100; $i++){
$u->movements()->save(factory(App\Movement::class)->make());
}
});
}
}
| true |
2a749e5b5a5a34e5f4c852da6357fef471904bf6 | PHP | AbdullahNassar/Brilliance | /app/Helpers/Uploader.php | UTF-8 | 417 | 2.796875 | 3 | [] | no_license | <?php
namespace App\Helpers;
use Illuminate\Support\Str;
class Uploader
{
public static function upload($file,$path)
{
$extension = $file->getClientOriginalExtension();
$oldFileName = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
$fileName = $oldFileName .'-'. Str::random(10).'.'.$extension;
$file->move($path,$fileName);
return $fileName;
}
} | true |
61b96836ea770e0b469646bb676fbf816f89a224 | PHP | tuxpoll/chirp | /src/Chirp.php | UTF-8 | 9,155 | 2.859375 | 3 | [
"MIT"
] | permissive | <?php
/**
* This file is part of Chirp package
*
* Copyright (c) 2015 Alberto Pagliarini
*
* Licensed under the MIT license
* https://github.com/batopa/chirp/blob/master/LICENSE
*/
namespace Bato\Chirp;
use Bato\Chirp\Utility\Parser;
use MongoDB\Client;
use Abraham\TwitterOAuth\TwitterOAuth;
/**
* Chirp Class
*
* Help to create a cache for Twitter using MongoDB
*
*/
class Chirp
{
/**
* The Database object
*
* @var \MongoDB\Database
*/
private $db = null;
/**
* The instance of TwitterOAuth
*
* @var \Abraham\TwitterOAuth\TwitterOAuth
*/
private $twitter;
/**
* Constructor
*
* Passing $twitterAuthConf and/or $mongoConf it tries to setup them
*
* $twitterAuthConf must contain
* - consumer_key
* - consumer_secret
* - oauth_access_token
* - oauth_access_token_secret
*
* $mongoConf must contain
* - db: the name of mongo database to use
*
* and can contain
* - uri
* - uriOptions
* - driverOptions
*
* used for MongoDB connection
*
* @see \MongoDB\Client for $mongoConf
* @param array $twitterAuthConf
* @param array $mongoDbConf
*/
public function __construct(array $twitterAuthConf = array(), array $mongoDbConf = array())
{
if (!empty($twitterAuthConf)) {
$this->setupTwitter($twitterAuthConf);
}
if (!empty($mongoDbConf)) {
$this->setupMongoDb($mongoDbConf);
}
}
/**
* Setup TwitterOAuth
*
* $twitterAuthConf must contain
* - consumer_key
* - consumer_secret
* - oauth_access_token
* - oauth_access_token_secret
*
* @param array $twitterAuthConf
* @return $this
*/
public function setupTwitter(array $twitterAuthConf)
{
$twitterAuthConf += [
'consumer_key' => null,
'consumer_secret' => null,
'oauth_access_token' => null,
'oauth_access_token_secret' => null
];
$this->twitter = new TwitterOAuth(
$twitterAuthConf['consumer_key'],
$twitterAuthConf['consumer_secret'],
$twitterAuthConf['oauth_access_token'],
$twitterAuthConf['oauth_access_token_secret']
);
$this->twitter->setDecodeJsonAsArray(true);
return $this;
}
/**
* Setup MongoDB connection
*
* $mongoDbConf must contain
* - db: the name of mongo database to use
*
* and can contain
* - uri
* - uriOptions
* - driverOptions
*
* @see \MongoDB\Client for $mongoConf
* @param array $mongoDbConf
* @return $this
*/
public function setupMongoDb(array $mongoDbConf)
{
$mongoDbConf += [
'uri' => 'mongodb://localhost:27017',
'uriOptions' => [],
'driverOptions' => [],
'db' => ''
];
$client = new Client($mongoDbConf['uri'], $mongoDbConf['uriOptions'], $mongoDbConf['driverOptions']);
$this->db = $client->selectDatabase($mongoDbConf['db']);
return $this;
}
/**
* Return TwitterOAuth instance
*
* @return \Abraham\TwitterOAuth\TwitterOAuth
*/
public function getTwitter()
{
if (empty($this->twitter)) {
throw new \RuntimeException(
'You have to setup twitter before use it. See \Bato\Chirp\Chirp::setupTwitter()'
);
}
return $this->twitter;
}
/**
* Return the instance of MongoDB database
*
* @return \MongoDB\Database
*/
public function getDb()
{
if (empty($this->db)) {
throw new \RuntimeException(
'You have to setup MongoDB connection before use it. See \Bato\Chirp\Chirp::setupMongoDb()'
);
}
return $this->db;
}
/**
* Starting from twitter endpoint return the related collection
* It replaces "/" with "-" after removing trailing "/", for example:
*
* endpoint "statuses/user_timeline" corresponds to "statuses-user_timeline" collection
*
* @param string $endpoint [description]
* @return \MongoDB\Collection
*/
public function getCollection($endpoint)
{
$name = Parser::normalize($endpoint);
return $this->getDb()
->selectCollection($name);
}
/**
* Perform a Twitter request
*
* @param string $endpoint the endpoint for example 'statuses/user_timeline'
* @param array $query an array that specify query string to use with the endpoint
* @param string $requestMethod the http request method
* @return array
*/
public function request($endpoint, $query = [], $requestMethod = 'get')
{
$validMethods = ['get', 'post', 'put', 'delete'];
$requestMethod = strtolower($requestMethod);
if (!in_array($requestMethod, $validMethods)) {
throw new \UnexpectedValueException('Unsupported http request method ' . $requestMethod);
}
$response = $this->getTwitter()
->{$requestMethod}($endpoint, $query);
return $response;
}
/**
* Read results from a collection (default self::collection)
* using $filter to filter results
*
* If $options['limit'] = 1 return a \MongoDB\BSONDocument object
* else return an array or a cursor depending from $options['returnType']
*
* @param string $endpoint
* @param array $filter
* @param array $options
* @return object|array
*/
public function read($endpoint, array $filter = [], array $options = [])
{
$options += ['returnType' => 'array'];
$collection = $this->getCollection($endpoint);
// delegate to MongoDB\Collection::findOne()
if (isset($options['limit']) && $options['limit'] === 1) {
return $collection->findOne($filter, $options);
}
$cursor = $collection->find($filter, $options);
return ($options['returnType'] == 'array') ? iterator_to_array($cursor) : $cursor;
}
/**
* Perform twitter request and save results in db.
*
* Possible $options are:
* - query: an array used for compose query string
* - grep: an array used for look up. Results matching the grep criteria will be saved.
* Example
* ```
* [
* 'key_to_look_up' => ['match1', 'match2'],
* 'other_key_to_look_up' => ['match3']
* ]
* ```
* - require: an array of string of keys required.
* Only results with those fields will be saved.
* Use point separtated string to go deep in results, for example
* `'key1.key2.key3'` checks against`[ 'key1' => ['key2' => ['key3' => 'some_value']]] `
*
* @param string $endpoint the twitter endpoint for example 'statuses/user_timeline'
* @param array $options
* @return array
*/
public function write($endpoint, array $options = [])
{
$options = $this->prepareWriteOptions($options);
$response = $this->request($endpoint, $options['query']);
if (empty($response)) {
return ['saved' => [], 'read'=> []];
}
if (array_key_exists('errors', $response)) {
return $response;
}
$collection = $this->getCollection($endpoint);
$tweets = $this->filterToSave($response, $collection, $options);
if (!empty($tweets)) {
$collection->insertMany($tweets);
}
return [
'saved' => $tweets,
'read'=> $response
];
}
/**
* Check and return $options to be used in self::write()
*
* @param array $options
* @return array
*/
private function prepareWriteOptions($options)
{
$options += [
'query' => [],
'grep' => [],
'require' => []
];
foreach (['query', 'grep', 'require'] as $test) {
if (!is_array($options[$test])) {
throw new \UnexpectedValueException('"' . $test . '" option must be an array');
}
}
$options['query'] = array_filter($options['query']);
return $options;
}
/**
* Given an array of tweets and a collection
* return the tweets that missing from the collection
*
* @see self::write() for $options
* @param array $tweets
* @param \MongoDB\Collection $collection
* @param array $options
* @return array
*/
private function filterToSave(array $tweets, \MongoDB\Collection $collection, array $options)
{
$toSave = [];
foreach ($tweets as $key => $tweet) {
if (!Parser::match($tweet, $options)) {
continue;
}
$countTweets = $collection->count(['id_str' => $tweet['id_str']]);
if ($countTweets === 0) {
$toSave[] = $tweet;
}
}
return $toSave;
}
}
| true |
9e513cf3b1e16ed756f48c28a52156656345ed4f | PHP | ozdemirmehmet/php-notes | /Public Chat GCM/register.php | UTF-8 | 1,585 | 2.6875 | 3 | [] | no_license | <?php
require_once("baglan.php");//veritabanı bağlantısı
if (isset($_POST["regId"]) & isset($_POST["androidId"]) & isset($_POST["language"]) & isset($_POST["appVersion"])) { //Kontrol
//POST ile gelen verileri aldık
$regId = $_POST['regId'];
$androidId = $_POST['androidId'];
$language = $_POST['language'];
$appVersion = $_POST['appVersion'];
//Öncelikle o android id de bir kayıt olup olmadığını kontrol ediyoruz.
$sql1 = "SELECT regId FROM userss WHERE androidId = '$androidId'";
$result = $con->query($sql1);
if($result->num_rows > 0){//Cihaz önceden kayıt edilmişse burası çalışacak
$row = $result->fetch_assoc();
if($row['regId'] != $regId){//Cihaz önceden kaydedilmiş fakat uygulama güncellenmiş olduğu için regId de güncellenecek
$sql = "UPDATE userss SET regId='$regId' WHERE androidId='$androidId'";
if(!mysqli_query($con, $sql)){//sorguyu çalýþtýrdýk
die('MySQL query failed'.mysqli_error($con));
}
else{//Kayıt başarılı
echo "OK";
}
}
}
else{//Cihaz önceden kayıt edilmemiş yeni kayıt gerçekleştirilecek
$sql = "INSERT INTO userss (regId,language,appVersion,androidId) values ('$regId','$language','$appVersion','$androidId')"; //regId yi database kaydedicek sorgu
if(!mysqli_query($con, $sql)){//sorguyu çalýþtýrdýk
die('MySQL query failed'.mysqli_error($con));
}
else{//Kayıt başarılı
echo "OK";
}
}
}
else{
echo "Giriş engellendi";
}
mysqli_close($con);//veritabanı bağlantısı kapatıldı
?> | true |
55c528daff9234db3987ebc1b1cfe1a7d273d765 | PHP | szymonsniadach/PHP-CRUD | /delete-user.php | UTF-8 | 296 | 2.515625 | 3 | [] | no_license | <?php
require 'mysqli.php';
$id = $_GET['id'];
$query = "DELETE FROM `users` WHERE id='$id'";
if ($result = $mysqli->query($query)) {
echo "<p style='color: green;'>Success delete user! :)</p>";
}else{
echo "oh no, problem with delete user :(";
}
$mysqli->close();
?> | true |
99daa81febcff05f7fa5ac023854a6001b8ef2d1 | PHP | Kelvin52/Integrated-Display-System | /DPS/WebApp/login.php | UTF-8 | 1,543 | 2.6875 | 3 | [] | no_license | <!DOCTYPE html>
<?php session_start(); ?>
<?php
/* $serverName = "BammBamm";
$uid = "Timetable";
$pwd = "a%89UIes";
$databaseName = "TestDB";
$connectionInfo = array("Database"=>$databaseName,
"UID"=>$uid,
"PWD"=>$pwd);
$conn = sqlsrv_connect( $serverName, $connectionInfo) or die(sqlsrv_errors());
if( $conn ) {
echo "Connection established.<br />";
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
} */
?>
<link href="themes/Navbar.css" rel="stylesheet" type="text/css">
<meta charset="utf-8" />
<body>
<?php if(!isset($_SESSION['user_id']) || !isset($_SESSION['user_name'])) { ?>
<form method='post' class="modal-content animate" action="login_ok.php">
<div class="container">
<label for="user_id"><b>Username</b></label>s
<input type="text" placeholder="Enter Username" name="user_id" require>
<label for="user_pw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="user_pw" require>
<button class="login" type="submit">login</button>
</form>
<?php } else {
$user_id = $_SESSION['user_id'];
$user_name = $_SESSION['user_name'];
echo "<p>($user_id), you are already logged in.";
echo "<a href=\"timetable.php\">[Back]</a> ";
echo "<a href=\"logout.php\">[Logout]</a></p>";
} ?>
</div>
</body>
| true |