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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
478fd794375e313de9c61379595aa2da19945471 | PHP | salomalo/naked | /wp-content/mu-plugins/includes/support/info/wp-support-php_info.php | UTF-8 | 2,686 | 2.609375 | 3 | [] | no_license | <?php
if (!defined('ABSPATH'))
exit;
// Добавление поддержки вывода информации о PHP
add_action('admin_menu', '_wp_render_menu_php_info');
/**
* Добавляет новый пункт меню "Версия PHP".
*/
function _wp_render_menu_php_info() {
// Добавление нового пункта меню в раздел "Инструменты"
add_management_page(
'PHP ' . phpversion(),
__('Версия PHP', 'naked'),
'manage_options',
'php_info',
'_wp_php_info_callback',
4
);
}
/**
* Обрабатывает вывод содержимого страницы "Версия PHP".
*/
function _wp_php_info_callback() {
// Получение всей информации о PHP
ob_start();
phpinfo();
$php_info = ob_get_contents();
ob_end_clean();
// Получение только содержимого элемента "<body>"
$php_info = preg_replace('%^.*<body>(.*)</body>.*$%ms', '$1', $php_info);
?>
<style>
#php-info { color: #222222; font-size: 16px; }
#php-info pre { margin: 0; font-family: monospace; }
#php-info a { color: #222222; }
#php-info a:link { color: #000099; text-decoration: none; background-color: #ffffff; }
#php-info a:hover { text-decoration: underline; }
#php-info table { border-collapse: collapse; border: 0; max-width: 934px; width: 100%; box-shadow: 1px 2px 3px #cccccc; }
#php-info .center { text-align: center; }
#php-info .center table { margin: 1em auto; text-align: left; }
#php-info .center th { text-align: center !important; }
#php-info td,
#php-info th { border: 1px solid #666666; font-size: 75%; vertical-align: baseline; padding: 4px 5px; }
#php-info th { position: sticky; top: 0; background: inherit; }
#php-info h1 { font-size: 200%; font-weight: bold; }
#php-info h2 { font-size: 125%; font-weight: bold; }
#php-info .p { font-size: 250%; text-align: left;}
#php-info .e { background-color: #ccccff; width: 300px; font-weight: bold; }
#php-info .h { background-color: #9999cc; font-weight: bold; }
#php-info .v { background-color: #dddddd; max-width: 300px; overflow-x: auto; word-wrap: break-word; }
#php-info .v i { color: #999999; }
#php-info img { display: block; float: right; border: 0; }
#php-info hr { max-width: 934px; width: 100%; background-color: #cccccc; border: 0; height: 1px; }
</style>
<div id="php-info" class="wrap">
<?php echo $php_info; ?>
</div>
<?php
}
| true |
3ae47dd5b283084c66c36d42f3010491acd8b754 | PHP | joachimdieterich/curriculum | /share/classes/country.class.php | UTF-8 | 2,828 | 2.734375 | 3 | [
"MIT"
] | permissive | <?php
/**
* This file is part of curriculum - http://www.joachimdieterich.de
*
* @package core
* @filename country.class.php
* @copyright 2013 Joachim Dieterich
* @author Joachim Dieterich
* @date 2013.03.24 11:36
* @license:
*
* The MIT License (MIT)
* Copyright (c) 2012 Joachim Dieterich http://www.curriculumonline.de
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
* THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
class Country {
/**
* id of country, default null
* @var int
*/
public $id;
/**
* internation country code
* @var string
*/
public $code = null;
/**
* english country name
* @var string
*/
public $en;
/**
* german country name
* @var string
*/
public $de;
/**
* load countries
* @param int $id
* @return array
*/
public function load($id) {
$countries = array();
$db = DB::prepare('SELECT * FROM countries WHERE id = ? ORDER BY de ASC');
$db->execute(array($id));
while($result = $db->fetchObject()) {
$this->id = $result->id;
$this->code = $result->code;
$this->en = $result->en;
$this->de = $result->de;
$countries[] = clone $this;
}
return $countries;
}
/**
* returns array of countries
* @return array
*/
public function getCountries(){
$countries = array();
$db = DB::prepare('SELECT * FROM countries ORDER BY de ASC');
$db->execute();
while($result = $db->fetchObject()) {
$this->id = $result->id;
$this->code = $result->code;
$this->en = $result->en;
$this->de = $result->de;
$countries[] = clone $this;
}
return $countries;
}
} | true |
f59b7284f26e67b67fccf22222ad2c8161037070 | PHP | anthonytam/MTA-Roleplay | /external-webserver/includes/mail_class.php | UTF-8 | 3,155 | 2.578125 | 3 | [] | no_license | <?php
function EMAIL_tc($e_to,$e_to_name,$e_subject,$e_in_subject,$e_body){
// Create the mail transport configuration
$transport = Swift_MailTransport::newInstance();
// Create the message
$message = Swift_Message::newInstance();
$message->setTo(array(
$e_to => $e_to_name
));
$message->setSubject($e_subject . " - UnitedGaming");
$message->setBody(
'<html>
<link href=\'http://fonts.googleapis.com/css?family=Source+Sans+Pro\' rel=\'stylesheet\' type=\'text/css\'>
<table border="0" align="center" width="99%">
<tr>
<td><a href="http://unitedgaming.org" target="_blank" title="UnitedGaming" alt="UnitedGaming"><img src="http://unitedgaming.org/mainlogo.png" alt="UnitedGaming" border="0"/></td>
<td><span style="font-family: \'Source Sans Pro\', sans-serif;"><font size="6px" color="#BD3538">'.$e_in_subject.'</font></span></td>
</tr>'
.
'<br/><br /><br/><tr>
<td colspan="2"><font size="3px" color="#303030">'.$e_body.'
</td></tr><tr><td><br/><span style="font-family: \'Source Sans Pro\', sans-serif;"><font size="2px">Kind Regards,<br/>Chuevo</font></span></td><td></td></tr></table></html>
');
$message->setFrom("chuevo@unitedgaming.org", "UnitedGaming");
$type = $message->getHeaders()->get('Content-Type');
$type->setValue('text/html');
$type->setParameter('charset', 'utf-8');
//echo $type->toString();
/*
Content-Type: text/html; charset=utf-8
*/
// Send the email
$mailer = Swift_Mailer::newInstance($transport);
$mailer->send($message);
}
//testing email function template
function EMAIL_test($e_to,$e_to_name,$e_subject,$e_in_subject,$e_body){
// Create the mail transport configuration
$transport = Swift_MailTransport::newInstance();
// Create the message
$message = Swift_Message::newInstance();
$message->setTo(array(
$e_to => $e_to_name
));
$message->setSubject($e_subject . " - UnitedGaming");
$message->setBody(
'<html>
<link href="http://fonts.googleapis.com/css?family=Source+Sans+Pro:400,700" rel="stylesheet" type="text/css"/>
<table border="0" align="center">
<tr>
<td><a href="http://unitedgaming.org" target="_blank" title="UnitedGaming" alt="UnitedGaming"><img src="http://unitedgaming.org/mainlogo.png" alt="UnitedGaming" border="0"/></td>
<td><font face="Source Sans Pro" size="6px" color="#BD3538">'.$e_in_subject.'</font></td>
</tr>'
.
'<br/><br /><br/><tr>
<td colspan="2"><font face="Arial" size="3px" color="#303030">'.$e_body.'
</td></tr><tr><td><br/><font face="Source Sans Pro" size="2px">Kind Regards,<br/>Chuevo</font></td><td></td></tr></table></html>
');
$message->setFrom("chuevo@unitedgaming.org", "UnitedGaming");
$type = $message->getHeaders()->get('Content-Type');
$type->setValue('text/html');
$type->setParameter('charset', 'utf-8');
//echo $type->toString();
/*
Content-Type: text/html; charset=utf-8
*/
// Send the email
$mailer = Swift_Mailer::newInstance($transport);
$mailer->send($message);
}
?> | true |
657e712212b30d7b10b3b826ace1ae5452862f51 | PHP | nowa75/L5Blog | /app/Tag.php | UTF-8 | 563 | 2.640625 | 3 | [
"MIT"
] | permissive | <?php namespace App;
use Illuminate\Database\Eloquent\Model;
/**
* App\Tag
*
* @property-read \Illuminate\Database\Eloquent\Collection|\App\Article[] $article
*/
class Tag extends Model {
/**
* Fillable fields for a tags
*
* @var array
*/
protected $fillable = [
'name'
];
/**
* Get the articles associated with given tag
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function articles()
{
return $this->belongsToMany( 'App\Article' );
}
}
| true |
e2f96707bb85f7cd4bd723f17171a2c946801b50 | PHP | peter279k/JOM | /src/ArrayNode.php | UTF-8 | 7,583 | 2.828125 | 3 | [
"MIT"
] | permissive | <?php declare(strict_types=1);
namespace DaveRandom\Jom;
use DaveRandom\Jom\Exceptions\EmptySubjectNodeListException;
use DaveRandom\Jom\Exceptions\InvalidKeyException;
use DaveRandom\Jom\Exceptions\InvalidReferenceNodeException;
use DaveRandom\Jom\Exceptions\WriteOperationForbiddenException;
use DaveRandom\Jom\Exceptions\InvalidSubjectNodeException;
final class ArrayNode extends VectorNode
{
private function incrementKeys(?Node $current, int $amount = 1): void
{
while ($current !== null) {
$current->key += $amount;
$this->children[$current->key] = $current;
$current = $current->nextSibling;
}
}
private function decrementKeys(?Node $current): void
{
while ($current !== null) {
unset($this->children[$current->key]);
$this->children[--$current->key] = $current;
$current = $current->nextSibling;
}
}
private function normalizeIndex($index): int
{
if (!\is_int($index) && !\ctype_digit($index)) {
throw new \TypeError('Index must be an integer');
}
return (int)$index;
}
/**
* @param int|string|null Array index or null to push new element
* @throws EmptySubjectNodeListException
* @throws InvalidKeyException
* @throws InvalidReferenceNodeException
* @throws InvalidSubjectNodeException
* @throws WriteOperationForbiddenException
*/
private function setNodeAtIndex($index, Node $node): void
{
if ($index === null || $this->normalizeIndex($index) === \count($this->children)) {
$this->push($node);
return;
}
if (isset($this->children[$index])) {
$this->replaceNode($node, $this->children[$index]);
return;
}
throw new InvalidKeyException("Index '{$index}' is outside the bounds of the array");
}
/**
* @param Node[] $nodes
* @throws EmptySubjectNodeListException
*/
private function assertNodeListNotEmpty(array $nodes): void
{
if (empty($nodes)) {
throw new EmptySubjectNodeListException("List of nodes to add must contain at least one node");
}
}
/**
* @throws InvalidSubjectNodeException
*/
public function __construct(?array $children = [], ?Document $ownerDocument = null)
{
parent::__construct($ownerDocument);
try {
$i = 0;
foreach ($children ?? [] as $child) {
$this->appendNode($child, $i++);
}
} catch (InvalidSubjectNodeException $e) {
throw $e;
//@codeCoverageIgnoreStart
} catch (\Exception $e) {
throw unexpected($e);
}
//@codeCoverageIgnoreEnd
}
/**
* @throws InvalidKeyException
*/
public function item(int $index): Node
{
return $this->offsetGet($index);
}
/**
* @throws WriteOperationForbiddenException
* @throws InvalidSubjectNodeException
* @throws EmptySubjectNodeListException
*/
public function push(Node ...$nodes): void
{
$this->assertNodeListNotEmpty($nodes);
foreach ($nodes as $node) {
$this->appendNode($node, \count($this->children));
}
}
/**
* @throws WriteOperationForbiddenException
*/
public function pop(): ?Node
{
$node = $this->lastChild;
if ($node === null) {
return null;
}
try {
$this->remove($node);
} catch (WriteOperationForbiddenException $e) {
throw $e;
//@codeCoverageIgnoreStart
} catch (\Exception $e) {
throw unexpected($e);
}
//@codeCoverageIgnoreEnd
return $node;
}
/**
* @throws WriteOperationForbiddenException
* @throws InvalidSubjectNodeException
* @throws EmptySubjectNodeListException
*/
public function unshift(Node ...$nodes): void
{
$this->assertNodeListNotEmpty($nodes);
try {
$beforeNode = $this->firstChild;
foreach ($nodes as $key => $node) {
$this->insertNode($node, $key, $beforeNode);
}
$this->incrementKeys($beforeNode, \count($nodes));
} catch (WriteOperationForbiddenException | InvalidSubjectNodeException $e) {
throw $e;
//@codeCoverageIgnoreStart
} catch (\Exception $e) {
throw unexpected($e);
}
//@codeCoverageIgnoreEnd
}
/**
* @throws WriteOperationForbiddenException
*/
public function shift(): ?Node
{
$node = $this->firstChild;
if ($node === null) {
return null;
}
try {
$this->remove($node);
} catch (WriteOperationForbiddenException $e) {
throw $e;
//@codeCoverageIgnoreStart
} catch (\Exception $e) {
throw unexpected($e);
}
//@codeCoverageIgnoreEnd
return $node;
}
/**
* @throws WriteOperationForbiddenException
* @throws InvalidSubjectNodeException
* @throws InvalidReferenceNodeException
*/
public function insert(Node $node, ?Node $beforeNode): void
{
if ($beforeNode === null) {
$this->appendNode($node, \count($this->children));
return;
}
$key = $beforeNode !== null
? $beforeNode->key
: \count($this->children);
$this->insertNode($node, $key, $beforeNode);
$this->incrementKeys($beforeNode);
}
/**
* @param Node|int $nodeOrIndex
* @throws InvalidKeyException
* @throws InvalidReferenceNodeException
* @throws InvalidSubjectNodeException
* @throws WriteOperationForbiddenException
*/
public function replace(Node $newNode, $nodeOrIndex): void
{
$this->replaceNode($newNode, $this->resolveNode($nodeOrIndex));
}
/**
* @throws WriteOperationForbiddenException
* @throws InvalidSubjectNodeException
*/
public function remove(Node $node): void
{
$next = $node->nextSibling;
$this->removeNode($node);
$this->decrementKeys($next);
}
/**
* @param int|string $index
* @throws InvalidKeyException
*/
public function offsetGet($index): Node
{
$index = $this->normalizeIndex($index);
if (!isset($this->children[$index])) {
throw new InvalidKeyException("Index '{$index}' is outside the bounds of the array");
}
return $this->children[$index];
}
/**
* @param int|string $index
* @param Node $value
* @throws WriteOperationForbiddenException
* @throws InvalidSubjectNodeException
* @throws InvalidKeyException
*/
public function offsetSet($index, $value): void
{
try {
$this->setNodeAtIndex($index, $value);
} catch (WriteOperationForbiddenException | InvalidSubjectNodeException | InvalidKeyException $e) {
throw $e;
//@codeCoverageIgnoreStart
} catch (\Exception $e) {
throw unexpected($e);
}
//@codeCoverageIgnoreEnd
}
public function getValue(): array
{
$result = [];
foreach ($this as $value) {
$result[] = $value->getValue();
}
return $result;
}
public function toArray(): array
{
return $this->getValue();
}
}
| true |
1bf0928b1f5e4cfe52fb8ba6473c3692ed2949e1 | PHP | WirVsVirusHackathonLebensmittelMatching/shop4me | /app/City.php | UTF-8 | 1,045 | 2.546875 | 3 | [] | no_license | <?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class City extends Model {
protected $fillable = [
'country_code',
'city_name',
'zip_code',
'state',
'state_code',
'province',
'owner_id',
'city_team_id',
'province_code',
'lat',
'lng',
];
protected $table = 'cities';
/**
* @return BelongsTo
*/
public function owner(): BelongsTo
{
return $this->belongsTo(User::class, 'owner_id');
}
/**
* @return BelongsTo
*/
public function city_team(): BelongsTo
{
return $this->belongsTo(CityTeam::class, 'city_team_id');
}
/**
* @return bool
*/
public function hasOwner()
{
$readableAttribute = [0 => 'Ja', 1 => 'Nein'];
$isEmpty = $this->getAttribute('city_team_id') > 0;
if ($isEmpty)
{
return 'Ja';
}
return 'Nein';
}
}
| true |
bd1eb078a275f2e2e28517c9155bfe4d00af9fa2 | PHP | horaklukas/posterator | /backend/get-data.php | UTF-8 | 1,821 | 2.734375 | 3 | [] | no_license | <?php
# relative path into `posters` directory from `public` directory
define('REL_POSTERS_PATH', './posters');
# path to file containing posters meta data
define('POSTERS_METAFILE_PATH', __DIR__.'/../public/posters/posters-meta.json');
# path to file containing titles data
define('POSTERS_TITLES_PATH', __DIR__.'/../public/user-data/titles.json');
function getUrlParameter($name) {
return isset($_GET[$name]) ? $_GET[$name] : null;
}
function getFileContent($filename) {
if(!file_exists($filename)) {
throw new Exception('Unknown path to file: `'.$filename.'`');
}
$handle = fopen($filename, 'r');
if($handle === FALSE) {
throw new Exception('Cannot read file.');
} else {
$content = stream_get_contents($handle);
fclose($handle);
return $content;
}
}
try{
$type = getUrlParameter('type');
switch ($type) {
case 'posters':
$posters = getFileContent(POSTERS_METAFILE_PATH);
$data = json_decode($posters);
foreach ($data as $key => $poster) {
if(isset($poster->url)) {
$poster->url = REL_POSTERS_PATH.'/'.$poster->url;
}
}
break;
case 'titles':
$posterId = getUrlParameter('poster');
if(!$posterId) { throw new Exception('Poster id not defined.'); }
$postersTitles = getFileContent(POSTERS_TITLES_PATH);
$postersTitles = json_decode($postersTitles, TRUE);
if(isset($postersTitles[$posterId])) {
$data = $postersTitles[$posterId];
} else {
throw new Exception('Poster titles not found.');
}
break;
default:
throw new Exception("Unknow data type to get: $type");
break;
}
header('Content-Type: application/json');
echo json_encode($data);
} catch(Exception $e) {
header('HTTP', true, 500);
echo($e->getMessage());
}
?> | true |
5e6a322fdbe04dadf9d008a5c311c246e977d9cb | PHP | missinglink/Insomnia | /Community/Module/RequestValidator/Request/InputSanitiser.php | UTF-8 | 951 | 3.09375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | <?php
namespace Community\Module\RequestValidator\Request;
/**
* A simple class to prevent HTML injection attacks
*/
class InputSanitiser
{
/**
* @var string
*/
private $value = '';
/**
* @param string $uncleanValue
*/
public function __construct( $uncleanValue )
{
$this->value = $uncleanValue;
}
/**
* @return InputSanitiser
*/
public function stripTags()
{
$this->value = strip_tags( $this->value );
return $this;
}
/**
* @param string $htmlTag
* @return InputSanitiser
*/
public function removeTagBody( $htmlTag )
{
$this->value = preg_replace( '/<'.preg_quote($htmlTag).'\b[^>]*>(.*?)<\/'.preg_quote($htmlTag).'>/i', '', $this->value );
return $this;
}
/**
* @return type
*/
public function getValue()
{
return $this->value;
}
} | true |
8b46d8d652e4187f3eb2659acf146a8405c56b3c | PHP | Selim-Reza-Swadhin/cookie_php | /reserve_cookie_data.php | UTF-8 | 3,842 | 3.125 | 3 | [] | no_license | <?php
//read cookie and assign cookie values
//to PHP variable
if (isset($_POST['submit'])){
//delete previous cookie
setcookie('shirt_color', '', -1, '/');
setcookie('size', '', -1, '/');
setcookie('brand', '', -1, '/');
setcookie('type', '', -1, '/');
$ret1 = (isset($_POST['shirt_color'])) ? setcookie('shirt_color', $_POST['shirt_color'], time()+60, '/') : null;
$ret2 = (isset($_POST['size'])) ? setcookie('size', $_POST['size'], time()+60, '/') : null;//60s
$ret3 = (isset($_POST['brand'])) ? setcookie('brand', $_POST['brand'], time()+60, '/') : null;
$ret4 = (isset($_POST['type'])) ? setcookie('type', $_POST['type'], time()+60, '/') : null;
}
$shirt_color = isset($_COOKIE['shirt_color']) ? $_COOKIE['shirt_color'] : array();
$size = isset($_COOKIE['size']) ? $_COOKIE['size'] : array();
$brand = isset($_COOKIE['brand']) ? $_COOKIE['brand'] : '';
$type = isset($_COOKIE['type']) ? $_COOKIE['type'] : array();
?>
<!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>Your Shirt Selection</title>
</head>
<body>
<h2>Saving and Restoring Buyer Choice</h2>
<h3>Set Your Preference</h3>
<?php
//if form submitted
//display success message
if (isset($_POST['submit'])){?>
Thank you for your submission.
<br>
<br>
<br>
Your Shirt Preferences:
<br>
<ul>
<li>Shirt Color : <b><?php echo isset($_COOKIE['shirt_color']) ? ucfirst($_COOKIE['shirt_color']) : ''; ?></b></li>
<li>Shirt Size : <b><?php echo isset($_COOKIE['size']) ? ucfirst($_COOKIE['size']) : ''; ?></b></li>
<li>Shirt Brand : <b><?php echo isset($_COOKIE['brand']) ? ucfirst($_COOKIE['brand']) : ''; ?></b></li>
<li>Sleeve Type : <b><?php echo isset($_COOKIE['type']) ? ucfirst($_COOKIE['type']) : ''; ?></b></li>
</ul>
<br>
<hr>
<a href="">Back to Form</a>
<?php
//if form not submitted display form
}else{
$shirt_color = isset($_COOKIE['shirt_color']) ? $_COOKIE['shirt_color'] : array();
$size = isset($_COOKIE['size']) ? $_COOKIE['size'] : array();
$brand = isset($_COOKIE['brand']) ? $_COOKIE['brand'] : '';
$type = isset($_COOKIE['type']) ? $_COOKIE['type'] : array();
?>
<form action="" method="post">
Shirt Color : <br>
<input type="radio" name="shirt_color" value="red" <?php echo ($shirt_color == 'red') ? 'checked' : '';?> > Red
<input type="radio" name="shirt_color" value="blue" <?php echo ($shirt_color == 'blue') ? 'checked' : '';?> > Blue
<input type="radio" name="shirt_color" value="black" <?php echo ($shirt_color == 'black') ? 'checked' : '';?> > Black
<input type="radio" name="shirt_color" value="white" <?php echo ($shirt_color == 'white') ? 'checked' : '';?> > White
<p>
Shirt Size : <br>
<input type="radio" name="size" value="s" <?php echo ($size == 's') ? 'checked' : '';?> > S
<input type="radio" name="size" value="m" <?php echo ($size == 'm') ? 'checked' : '';?> > M
<input type="radio" name="size" value="l" <?php echo ($size == 'l') ? 'checked' : '';?> > L
</p>
<p>
Shirt Brand : <br>
<input type="text" size="20" name="brand" value="<?php echo $brand; ?>">
</p>
<p>
Sleeve Type : <br>
<input type="radio" name="type" value="half" <?php echo ($type == 'half') ? 'checked' : '';?> > Half
<input type="radio" name="type" value="full" <?php echo ($type == 'full') ? 'checked' : '';?> > Full
</p>
<input type="submit" name="submit" value="Submit">
</form>
<?php } ?>
</body>
</html>
| true |
32cf67833f2e33c7f925e3dcf753b4338e1b2635 | PHP | djgogo/CPCII | /Address/src/Controllers/LogoutController.php | UTF-8 | 874 | 2.734375 | 3 | [] | no_license | <?php
namespace Address\Controllers {
use Address\Http\Request;
use Address\Http\Response;
/**
* @codeCoverageIgnore
*/
class LogoutController implements ControllerInterface
{
public function execute(Request $request, Response $response)
{
/**
* Delete all Session Data
*/
session_destroy();
/**
* Delete Session-Cookie (PHPSESSID)
*/
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), "", 1); // Ensures that cookie expires in browser
setcookie(session_name(), false); // Removes the cookie
unset($_COOKIE[session_name()]); // Removes the cookie from the application
}
$response->setRedirect('/');
return;
}
}
}
| true |
08e2fd88bb7d4a0bd1747ba46f7d21d55cbb286e | PHP | Retr01234/JobLister | /lib/Job.php | UTF-8 | 3,940 | 3.296875 | 3 | [
"MIT"
] | permissive | <?php
class Job{
private $db;
public function __construct(){
$this->db = new Database;
}
// Get All Jobs
public function getAllJobs(){
$this->db->query("SELECT jobs.*, categories.name AS cname FROM jobs INNER JOIN categories ON jobs.category_id = categories.id ORDER BY post_date DESC");
//Assign Results Set
$results = $this->db->resultSet();
return $results;
}
// Get Categories
public function getCategories(){
$this->db->query("SELECT * FROM categories"); // Select all from Categories
$results = $this->db->resultSet();
return $results;
}
// Get Jobs by Category
public function getByCategory($category){
$this->db->query("SELECT jobs.*, categories.name AS cname FROM jobs INNER JOIN categories ON jobs.category_id = categories.id WHERE jobs.category_id = $category ORDER BY post_date DESC");
$results = $this->db->resultSet();
return $results;
}
// Get Category
public function getCategory($category_id){
$this->db->query("SELECT * FROM categories WHERE id = :category_id"); // :category_id is a placeholder and needs to be binded
$this->db->bind(':category_id', $category_id); // :bind is an alternative way to pass data to the DB
// Assign Row
$row = $this->db->single(); // single is used to query a single value from a table
return $row;
}
// Get Job
public function getJob($id){
$this->db->query("SELECT * FROM jobs WHERE id = :id");
$this->db->bind(':id', $id);
// Assign Row
$row = $this->db->single();
return $row;
}
// Create Job
public function create($data){
// Insert Query
$this->db->query("INSERT INTO jobs (category_id, company, job_title, description, salary, location, contact_user, contact_email) VALUES (:category_id, :company, :job_title, :description, :salary, :location, :contact_user, :contact_email)");
// Binding Data
$this->db->bind(':category_id', $data['category_id']);
$this->db->bind(':company', $data['company']);
$this->db->bind(':job_title', $data['job_title']);
$this->db->bind(':description', $data['description']);
$this->db->bind(':salary', $data['salary']);
$this->db->bind(':location', $data['location']);
$this->db->bind(':contact_user', $data['contact_user']);
$this->db->bind(':contact_email', $data['contact_email']);
// All the fields up there, we are binding to the data array down here
// Execute
if ($this->db->execute()) {
return true;
} else {
return false;
}
}
// Delete Job
public function delete($id){
// Insert Query
$this->db->query("DELETE FROM jobs WHERE id = $id");
// Execute
if ($this->db->execute()) {
return true;
} else {
return false;
}
}
// Update Job
public function update($id, $data){
// Insert Query
$this->db->query("UPDATE jobs SET
category_id = :category_id,
company = :company,
job_title = :job_title,
description = :description,
salary = :salary,
location = :location,
contact_user = :contact_user,
contact_email = :contact_email WHERE id = $id");
// Binding Data
$this->db->bind(':category_id', $data['category_id']);
$this->db->bind(':company', $data['company']);
$this->db->bind(':job_title', $data['job_title']);
$this->db->bind(':description', $data['description']);
$this->db->bind(':salary', $data['salary']);
$this->db->bind(':location', $data['location']);
$this->db->bind(':contact_user', $data['contact_user']);
$this->db->bind(':contact_email', $data['contact_email']);
// All the fields up there, we are binding to the data array down here
// Execute
if ($this->db->execute()) {
return true;
} else {
return false;
}
}
} | true |
b75c4817b5fc29cbb1a9f1489a4caf03db2b64e5 | PHP | shail5788/social-network | /library/twitterLibrary.php | UTF-8 | 2,847 | 2.875 | 3 | [] | no_license | <?php
error_reporting(E_ALL);
class twitterClass {
public $consumer_key;
public $consumer_secret_key;
public $token;
public $token_secret;
public $apiUrl;
public function __construct($consumer_key,$consumer_secret_key,$token,
$token_secret){
$this->consumer_key=$consumer_key;
$this->consumer_secret_key=$consumer_secret_key;
$this->token=$token;
$this->token_secret=$token_secret;
$this->apiUrl="https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=snap";
}
public function buildBaseString($baseURI, $method, $params)
{
$r = array();
ksort($params);
foreach($params as $key=>$value){
$r[] = "$key=" . rawurlencode($value);
}
return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
}
public function buildAuthorizationHeader($oauth)
{
$r = 'Authorization: OAuth ';
$values = array();
foreach($oauth as $key=>$value)
$values[] = "$key='" . rawurlencode($value) . "'";
$r .= implode(', ', $values);
return $r;
}
public function the_nonce(){
$nonce = base64_encode(uniqid());
$nonce = preg_replace('~[\W]~','',$nonce);
return $nonce;
}
public function create_url(){
return $this->url."/?access_token=".$this->access_token;
}
public function get_twittes(){
$url=$this->apiUrl;
$oauth_access_token =$this->token;
$oauth_access_token_secret =$this->token_secret;
$consumer_key = $this->consumer_key;
$consumer_secret =$this->consumer_secret_key;
$oauth = array( 'oauth_consumer_key' => $consumer_key,
'oauth_nonce' => time(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_token' => $oauth_access_token,
'oauth_timestamp' => time(),
'oauth_version' => '1.0');
$base_info = $this->buildBaseString($url, 'GET', $oauth);
$composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$oauth['oauth_signature'] = $oauth_signature;
$header = array($this->buildAuthorizationHeader($oauth), 'Expect:');
$options = array( CURLOPT_HTTPHEADER => $header,
CURLOPT_HEADER => false,
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false);
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
$twitter_data = json_decode($json);
print_r($twitter_data);
}
}
?>
| true |
f39c5910c8c876b7d818c9a8dd8b353ea3523a60 | PHP | kutny/datetime-bundle | /tests/DateTimeFactoryTest.php | UTF-8 | 7,856 | 2.609375 | 3 | [] | no_license | <?php
namespace Kutny\DateTimeBundle;
use Kutny\DateTimeBundle\Date\Date;
use Kutny\DateTimeBundle\Time\Time;
use PHPUnit\Framework\TestCase;
class DateTimeFactoryTest extends TestCase
{
const TIMEZONE_GMT = 'GMT';
const TIMEZONE_PRAGUE = 'Europe/Prague';
const TIMEZONE_LOS_ANGELES = 'America/Los_Angeles';
/** @var DateTimeFactory */
private $dateTimeFactory;
protected function setUp()
{
$this->dateTimeFactory = new DateTimeFactory(self::TIMEZONE_GMT);
}
/** @test */
public function fromFormat_validSameTimezone()
{
$dateTime = $this->dateTimeFactory->fromFormatDateTime('1987-07-31 11:19:59');
$this->assertSame(1987, $dateTime->getDate()->getYear());
$this->assertSame(7, $dateTime->getDate()->getMonth());
$this->assertSame(31, $dateTime->getDate()->getDay());
$this->assertSame(11, $dateTime->getTime()->getHour());
$this->assertSame(19, $dateTime->getTime()->getMinute());
$this->assertSame(59, $dateTime->getTime()->getSecond());
}
/** @test */
public function fromFormat_validDifferentTimezone()
{
$dateTime = $this->dateTimeFactory->fromFormatDateTime('1987-07-31 11:19:59', self::TIMEZONE_PRAGUE);
$this->assertSame(1987, $dateTime->getDate()->getYear());
$this->assertSame(7, $dateTime->getDate()->getMonth());
$this->assertSame(31, $dateTime->getDate()->getDay());
$this->assertSame(9, $dateTime->getTime()->getHour());
$this->assertSame(19, $dateTime->getTime()->getMinute());
$this->assertSame(59, $dateTime->getTime()->getSecond());
}
/** @test */
public function fromFormat_validDateOnly()
{
$date = $this->dateTimeFactory->fromFormatDate('1987-07-31');
$this->assertSame(1987, $date->getYear());
$this->assertSame(7, $date->getMonth());
$this->assertSame(31, $date->getDay());
}
/** @test */
public function fromFormat_timezoneInFormat()
{
$dateTime = $this->dateTimeFactory->fromFormat('H:i:s M d, Y T', '06:00:09 Dec 24, 2014 PST', self::TIMEZONE_LOS_ANGELES);
$this->assertSame(2014, $dateTime->getDate()->getYear());
$this->assertSame(12, $dateTime->getDate()->getMonth());
$this->assertSame(24, $dateTime->getDate()->getDay());
$this->assertSame(14, $dateTime->getTime()->getHour());
$this->assertSame(0, $dateTime->getTime()->getMinute());
$this->assertSame(9, $dateTime->getTime()->getSecond());
}
/** @test */
public function fromFormat_timezoneInFormatInvalid()
{
try {
$this->dateTimeFactory->fromFormat('H:i:s M d, Y T', '06:00:09 Dec 24, 2014 PST', self::TIMEZONE_GMT);
$this->fail('Exception must be thrown here');
}
catch (\InvalidArgumentException $e) {
// PST != London timezone
$this->assertSame('dateTime timezone do NOT match sourceTimezone', $e->getMessage());
}
}
/** @test */
public function fromFormat_timezoneInFormatIso8601_winterTime()
{
$dateTime = $this->dateTimeFactory->fromFormat(DATE_ISO8601, '2017-11-15T04:10:30+01:00', self::TIMEZONE_PRAGUE);
$this->assertSame(2017, $dateTime->getDate()->getYear());
$this->assertSame(11, $dateTime->getDate()->getMonth());
$this->assertSame(15, $dateTime->getDate()->getDay());
$this->assertSame(3, $dateTime->getTime()->getHour());
$this->assertSame(10, $dateTime->getTime()->getMinute());
$this->assertSame(30, $dateTime->getTime()->getSecond());
}
/** @test */
public function fromFormat_timezoneInFormatIso8601_summerTime()
{
$dateTime = $this->dateTimeFactory->fromFormat(DATE_ISO8601, '2017-06-15T04:10:30+02:00', self::TIMEZONE_PRAGUE);
$this->assertSame(2017, $dateTime->getDate()->getYear());
$this->assertSame(6, $dateTime->getDate()->getMonth());
$this->assertSame(15, $dateTime->getDate()->getDay());
$this->assertSame(2, $dateTime->getTime()->getHour());
$this->assertSame(10, $dateTime->getTime()->getMinute());
$this->assertSame(30, $dateTime->getTime()->getSecond());
}
/** @test */
public function fromFormat_timezoneInFormatIso8601Invalid()
{
try {
$this->dateTimeFactory->fromFormat(DATE_ISO8601, '2015-11-15T04:10:30+01:00', self::TIMEZONE_GMT);
$this->fail('Exception must be thrown here');
}
catch (\InvalidArgumentException $e) {
// PST != London timezone
$this->assertSame('dateTime timezone do NOT match sourceTimezone', $e->getMessage());
}
}
/** @test */
public function fromFormat_timezoneInFormatIso8601v2()
{
$dateTime = $this->dateTimeFactory->fromFormat(DATE_ISO8601, '2012-01-02T13:30:56Z', self::TIMEZONE_GMT);
$this->assertSame(2012, $dateTime->getDate()->getYear());
$this->assertSame(1, $dateTime->getDate()->getMonth());
$this->assertSame(2, $dateTime->getDate()->getDay());
$this->assertSame(13, $dateTime->getTime()->getHour());
$this->assertSame(30, $dateTime->getTime()->getMinute());
$this->assertSame(56, $dateTime->getTime()->getSecond());
}
/** @test */
public function fromFormat_invalidWithTime()
{
try {
$this->dateTimeFactory->fromFormatDate('1987-07-31 11:19:59');
$this->fail('Exception must be thrown here');
}
catch (\InvalidArgumentException $e) {
$this->assertTrue(true);
}
}
/** @test */
public function fromFormat_invalid()
{
try {
$this->dateTimeFactory->fromFormatDateTime('Yvonne Strahovski');
$this->fail('Exception must be thrown here');
}
catch (\InvalidArgumentException $e) {
$this->assertTrue(true);
}
}
/** @test */
public function fromFormatWithTimezone_winterTime()
{
$dateTime = $this->dateTimeFactory->fromFormatWithTimezone(DATE_ISO8601, '2015-11-15T04:10:30+01:00');
$this->assertSame(2015, $dateTime->getDate()->getYear());
$this->assertSame(11, $dateTime->getDate()->getMonth());
$this->assertSame(15, $dateTime->getDate()->getDay());
$this->assertSame(3, $dateTime->getTime()->getHour());
$this->assertSame(10, $dateTime->getTime()->getMinute());
$this->assertSame(30, $dateTime->getTime()->getSecond());
}
/** @test */
public function fromFormatWithTimezone_summerTime()
{
$dateTime = $this->dateTimeFactory->fromFormatWithTimezone(DATE_ISO8601, '2017-05-06T11:12:31+01:00');
$this->assertSame(2017, $dateTime->getDate()->getYear());
$this->assertSame(5, $dateTime->getDate()->getMonth());
$this->assertSame(6, $dateTime->getDate()->getDay());
$this->assertSame(10, $dateTime->getTime()->getHour());
$this->assertSame(12, $dateTime->getTime()->getMinute());
$this->assertSame(31, $dateTime->getTime()->getSecond());
}
/** @test */
public function fromFormatWithTimezone_noTimezoneGiven()
{
try {
$this->dateTimeFactory->fromFormatWithTimezone('Y-m-d\TH:i:s', '2015-11-15T04:10:30');
$this->fail('Exception must be thrown here');
}
catch (\InvalidArgumentException $e) {
$this->assertSame('No timezone given in $dateTimeString', $e->getMessage());
}
}
/** @test */
public function fromTimestamp()
{
$expectedDateTime = new DateTime(new Date(2009, 2, 13), new Time(23, 31, 30));
$dateTime = $this->dateTimeFactory->fromTimestamp(1234567890, self::TIMEZONE_GMT);
$this->assertEquals($expectedDateTime, $dateTime);
}
}
| true |
4532507c1524d74df6ae0b7a56c1992fd044343e | PHP | ntkurapati/navidile-player | /alerts.php | UTF-8 | 1,655 | 2.59375 | 3 | [] | no_license | <?php
ini_set('display_errors',1);
error_reporting(E_ALL);
$username = "navidileappphp";
$password = ini_get("mysqli.default_pw");
$hostname = "localhost";
$mysqli = new mysqli($hostname, $username, $password, "pittmedstech_nav");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$pw=$_GET['pw'];
$statement = $mysqli->prepare("SELECT `email_addr`, `subscriptions` FROM subscribers WHERE `password` = ?");
if($statement){
$statement->bind_param('s', $pw);
$statement->execute();
$statement->bind_result($email_addr, $subscriptions);
while($statement->fetch())
{
}
$statement->free_result();
echo("your subscriptions for ".$email_addr. " are: ". $subscriptions . "<br>");
$alert = $_GET['alert'];
$action = $_GET['action'];
echo("Your alert to " . $action . " is " . $alert . "<br>");
if($alert and $action ) {
if($action == "unsubscribe"){
$newsubs = str_replace( $alert, '', $subscriptions);
}
if ($action == 'subscribe') {
$newsubs = $alert . ',' . $subscriptions;
}
echo('<br>subscription change: ' . $subscriptions . '-->' . $newsubs);
if($statement2 = $mysqli->prepare("UPDATE subscribers SET `subscriptions`= ? WHERE `password` = ? "))
{
$statement2->bind_param('ss', $newsubs, $pw);
$statement2->execute();
print '<br>Success!!';
}
else {
print 'Error : ('. $mysqli->errno .') '. $mysqli->error;
}
}
}
else{
echo("i didn't find you in the db");
}
?> | true |
5a180124d8b1cda318363ee2b2ced8bf00141f8e | PHP | budyfriend/oop | /namespace/index.php | UTF-8 | 554 | 2.625 | 3 | [] | no_license | <?php
require_once 'App/init.php';
// $produk1 = new Komik(
// "Naruto",
// "Masashi Kishimoto",
// "Shonen Jump",
// 30000,
// 100
// );
// $produk2 = new Game(
// "Uncharted",
// "Neil Druckmann",
// "Sony Computer",
// 250000,
// 50
// );
// $cetakProduk = new cetakInfoProduk();
// $cetakProduk->tambahProduk($produk1);
// $cetakProduk->tambahProduk($produk2);
// echo $cetakProduk->cetak();
// echo "<hr>";
use App\Service\User as ServiceUser;
use App\Produk\User as ProdukUser;
new ServiceUser();
echo "<hr>";
new ProdukUser();
| true |
ce4f2cfe970634f2505b8ad5fbbb57563072537b | PHP | GreenCape/coding-standards | /tests/Standards/WordPress/VIP/RestrictedFunctions.inc | UTF-8 | 910 | 2.5625 | 3 | [] | no_license | <?php
switch_to_blog( $blogid ); // bad
eval( 'some_code' ); // bad
create_function( 'foo', 'bar(foo);' ); // bad
file_get_contents( $url ); // bad
vip_wp_file_get_contents( $url ); // bad
wp_remote_get( $url ); // bad
$ch = curl_init(); // bad
curl_close( $ch ); // bad
extract( array( 'a' => 1 ) ); // bad
add_role( 'test' ); // bad
array_pop( $array ); // ok
class Foo {
function add_role() {} // ok
}
class Bar {
static function add_role() {} // ok
}
$x = new Foo();
$x->add_role(); // ok
$y = Bar::add_role(); // ok
\SomeNamespace\add_role(); // ok
\add_role(); // bad
get_term_link( $term ); // bad
get_page_by_path( $path ); // bad
get_page_by_title( $page_title ); // bad
get_term_by( $field, $value, $taxonomy ); // bad
get_category_by_slug( $slug ); // bad
url_to_postid( $url ); // bad
attachment_url_to_postid( $url ); // bad
wpcom_vip_attachment_url_to_postid( $url ); // ok
| true |
d84064f3442da507a8d45b77dd511d3871ee6107 | PHP | luger888/aimya | /library/Aimya/PayPal/Paypal.php | UTF-8 | 7,949 | 2.703125 | 3 | [] | no_license | <?php
class Aimya_PayPal_Paypal
{
private $VARS;
private $button;
private $logFile;
private $isTest=true;
/* Print Form as Link */
function getLink()
{
$url = $this->getPaypal();
$link = 'https://'.$url.'/cgi-bin/webscr?';
foreach($this->VARS as $item => $sub){
$link .= $sub[0].'='.$sub[1].'&';
}
return $link;
}
/* Print Form */
function showForm()
{
$url = $this->getPaypal();
$FORM = '<form action="https://'.$url.'/cgi-bin/webscr" method="post" target="_blank" style="display:inline;">'."\n";
foreach($this->VARS as $item => $sub){
$FORM .= '<input type="hidden" name="'.$sub[0].'" value="'.$sub[1].'">'."\n";
}
$FORM .= $this->button;
$FORM .= '</form>';
echo $FORM;
}
/* Add variable to form */
function addVar($varName,$value)
{
$this->VARS[${'varName'}][0] = $varName;
$this->VARS[${'varName'}][1] = $value;
}
/* Add button Image */
function addButton($type,$image = NULL)
{
switch($type)
{
/* Buy now */
case 1:
$this->button = '<input type="image" height="21" style="width:86;border:0px;"';
$this->button .= 'src="https://www.paypal.com/en_US/i/btn/btn_paynow_SM.gif" border="0" name="submit" ';
$this->button .= 'alt="PayPal - The safer, easier way to pay online!">';
break;
/* Add to cart */
case 2:
$this->button = '<input type="image" height="26" style="width:120;border:0px;"';
$this->button .= 'src="https://www.paypal.com/en_US/i/btn/btn_cart_LG.gif" border="0" name="submit"';
$this->button .= 'alt="PayPal - The safer, easier way to pay online!">';
break;
/* Donate */
case 3:
$this->button = '<input type="image" height="47" style="width:122;border:0px;"';
$this->button .= 'src="https://www.paypal.com/en_US/i/btn/btn_donateCC_LG.gif" border="0" name="submit"';
$this->button .= 'alt="PayPal - The safer, easier way to pay online!">';
break;
/* Gift Certificate */
case 4:
$this->button = '<input type="image" height="47" style="width:179;border:0px;"';
$this->button .= 'src="https://www.paypal.com/en_US/i/btn/btn_giftCC_LG.gif" border="0" name="submit"';
$this->button .= 'alt="PayPal - The safer, easier way to pay online!">';
break;
/* Subscribe */
case 5:
$this->button = '<input type="image" height="47" style="width:122;border:0px;"';
$this->button .= 'src="https://www.paypal.com/en_US/i/btn/btn_subscribeCC_LG.gif" border="0" name="submit"';
$this->button .= 'alt="PayPal - The safer, easier way to pay online!">';
break;
/* Custom Button */
default:
$this->button = '<input type="image" src="'.$image.'" border="0" name="submit"';
$this->button .= 'alt="PayPal - The safer, easier way to pay online!">';
}
$this->button .= "\n";
}
/* Set log file for invalid requests */
function setLogFile($logFile)
{
$this->logFile = $logFile;
}
/* Helper function to actually write to logfile */
private function doLog($data)
{
/*ob_start();
echo '<pre>'; print_r($_POST); echo '</pre>';
$logInfo = ob_get_contents();
ob_end_clean();
$file = fopen($this->logFile,'a');
fwrite($file,$logInfo);
fclose($file);*/
if( $fh = @fopen("./img/paypal.txt", "a+") )
{
$data = print_r($data, 1);
fwrite($fh, $data);
fclose( $fh );
return( true );
}
else
{
return( false );
}
}
/* Check payment */
function checkPayment($data = array())
{
/* read the post from PayPal system and add 'cmd' */
// $req = 'cmd=_notify-validate';
//
// /* Get post values and store them in req */
// foreach ($data as $key => $value) {
// $value = urlencode(stripslashes($value));
// $req .= "&$key=$value";
// }
$validate_request = 'cmd=_notify-validate';
foreach ($data as $key => $value)
{
$validate_request .= "&" . $key . "=" . urlencode(stripslashes($value));
}
$url = $this->getPaypal();
// Validate PayPal data to ensure it actually originated from PayPal
$curl_result = '';
$curl_err = '';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $validate_request);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded", "Content-Length: " . strlen($validate_request)));
curl_setopt($ch, CURLOPT_HEADER , 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$curl_result = curl_exec($ch);
$curl_err = curl_error($ch);
curl_close($ch);
/* post back to PayPal system to validate */
// $header = "";
// $header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
// $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
// $header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
// $fp = fsockopen ('ssl://'.$url, 443, $errno, $errstr, 30);
/*
If ssl access gives you problem. try regular port:
$fp = fsockopen ($url, 80, $errno, $errstr, 30);
*/
if (strpos($curl_result, "VERIFIED")!==false) {
$this->doLog($curl_result);
return true;
}
elseif(strpos($curl_result, "INVALID")!==false) {
//$this->doLog("bla bla bla");
$this->doLog($curl_result);
return false;
} else {
//$this->doLog("lab lab lab");
$this->doLog($curl_result);
return false;
}
// if (!$fp) {
// /* HTTP ERROR */
// return false;
// } else {
// fputs ($fp, $header . $req);
// while (!feof($fp)) {
// $res = fgets ($fp, 1024);
// if (strcmp ($res, "VERIFIED") == 0) {
// /*
// check the payment_status is Completed
// check that txn_id has not been previously processed
// check that receiver_email is your Primary PayPal email
// check that payment_amount/payment_currency are correct
// process payment
// */
// return true;
// } else {
// if (strcmp ($res, "INVALID") == 0) {
// /*
// log for manual investigation
// */
// if($this->logFile != NULL){
//
// $this->doLog($data);
// }
// }
//
// return false;
// }
// }
// fclose ($fp);
// }
// return false;
}
/* Set Test */
function useSandBox($value)
{
$this->isTest=$value;
}
/* Private function to get paypal url */
private function getPaypal()
{
if($this->isTest == true){
return 'www.sandbox.paypal.com';
} else {
return 'www.paypal.com';
}
}
} | true |
6a8ddaf5d506216ba424e15246937249702b2719 | PHP | FiruzShirinov/shoppers-catalog | /app/Models/Product.php | UTF-8 | 1,056 | 2.9375 | 3 | [] | no_license | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var string[]
*/
protected $fillable = [
'name',
'SKU',
'price',
'image',
'admin_created_id',
'admin_updated_id',
];
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'created_at' => 'datetime:d/m/Y',
'updated_at' => 'datetime:d/m/Y',
];
/**
* Get the product's price to decimal.
*
* @param string $value
* @return string
*/
public function getPriceAttribute($value)
{
return $value/100;
}
/**
* Set the product's price to decimal.
*
* @param string $value
* @return void
*/
public function setPriceAttribute($value)
{
$this->attributes['price'] = $value*100;
}
}
| true |
2c8b7c487efb92f901b10986fa18b133363cd73c | PHP | TwistoPayments/Twisto.php | /src/Twisto/Address.php | UTF-8 | 1,382 | 3.34375 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
namespace Twisto;
class Address implements BaseAddress
{
/** @var string */
public $name;
/** @var string */
public $street;
/** @var string */
public $city;
/** @var string */
public $zipcode;
/** @var string */
public $phone_number;
/** @var string */
public $country;
/**
* @param string $name
* @param string $street
* @param string $city
* @param string $zipcode
* @param string $country
* @param string $phone_number
*/
public function __construct($name, $street, $city, $zipcode, $country, $phone_number)
{
$this->name = $name;
$this->street = $street;
$this->city = $city;
$this->zipcode = $zipcode;
$this->country = $country;
$this->phone_number = $phone_number;
}
/**
* @return array
*/
public function serialize()
{
return array(
'name' => $this->name,
'street' => $this->street,
'city' => $this->city,
'zipcode' => $this->zipcode,
'country' => $this->country,
'phone_number' => $this->phone_number
);
}
public static function deserialize($data)
{
return new self($data['name'], $data['street'], $data['city'], $data['zipcode'], $data['country'], $data['phone_number']);
}
} | true |
a04be229233a51555be3dc33a6c1af18801728f1 | PHP | jonaguera/JonagueraFacturasScraperBundle | /Jonaguera/FacturasScraperBundle/Services/Downloader.php | UTF-8 | 5,796 | 2.734375 | 3 | [] | no_license | <?php
/**
* Clase con funciones para la descarga y guardado de archivos
*
* (c) Jon Agüera Fuente <jon_aguera@viajeseroski.es>
*
* @package PackageName
* @author AuthorName
* @abstract Abstract
*/
namespace Jonaguera\FacturasScraperBundle\Services;
use Symfony\Component\Finder\Finder;
class Downloader {
private $url;
private $ckfile;
private $ruta;
private $sender;
private $recipient;
private $container;
private $datefolders;
function __construct($url, $ckfile, $ruta, $sender, $recipient, $container,$datefolders=true,$parsepdf = false) {
// $datefolders hace que se creen directorios en funcion de año y mes
$this->url = $url;
$this->ckfile = $ckfile;
$this->ruta = $ruta;
$this->sender = $sender;
$this->recipient = $recipient;
$this->container = $container;
$this->datefolders = $datefolders;
$this->parsepdf = $parsepdf;
}
function save($filename = null) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->url);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1");
// Enviar cookie
curl_setopt($ch, CURLOPT_COOKIEFILE, $this->ckfile);
// Para descargar
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
// Solo para debug
curl_setopt($ch, CURLOPT_VERBOSE, '0');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
// Evitar error SSL
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, '0');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, '0');
// Función callback para lectura de cabeceras
curl_setopt($ch, CURLOPT_HEADERFUNCTION, array($this, 'readHeader'));
$output = curl_exec($ch);
curl_close($ch);
// Mirar si el filename ya existe en el filesystem
//Obtener el filename
if (!$filename){
$filename = $this->getFilenameFromHeaders();
}
if ($filename) {
$i=0;
$finder = new Finder();
$finder->name($filename);
echo "Se va a comprobar la existencia de ".$filename." en ".$this->ruta."\n";
foreach ($finder->in($this->ruta) as $file) {
$i++;
echo "Encontrado el archivo ".$file->getFilename() . "\n";
}
if ($i>0) {
// Chequear si el documento existe
// Si existe
echo "El fichero " . $filename . " existe. No se hace nada.\n";
} else {
// Si no existe
echo "El fichero " . $filename . " no existe. Se baja.\n";
// Crear directorio destino
if($this->datefolders){
$this->ruta=$this->ruta."/".date('Y')."/".date('m');
}
if (!file_exists($this->ruta)){
mkdir($this->ruta, 0777, true);
}
$fp = fopen($this->ruta. "/" . $filename.".tmp", 'w');
fwrite($fp, $output);
fclose($fp);
chmod($this->ruta . "/" . $filename.".tmp", 0777);
rename ( $this->ruta . "/" . $filename.".tmp",$this->ruta . "/" . $filename );
// Obtener el total
if ($this->parsepdf){
$parser = new PdfParser($this->ruta . "/" . $filename);
$total_factura = "\nEl importe de la factura es: ".$parser->readInvoiceTotal();
} else {
$total_factura = "";
}
if ($this->recipient){
echo "Se envia mail a " . print_r($this->recipient,1) . ".\n";
$message = \Swift_Message::newInstance()
->setSubject('Factura '.$filename.' disponible')
->setFrom($this->sender)
->setTo($this->recipient)
->attach(\Swift_Attachment::fromPath($this->ruta . "/" . $filename))
->setBody(
"Se ha descargado la factura ". $filename." en la ruta ".$this->ruta .$total_factura
)
;
$this->container->get('mailer')->send($message);
}
}
} else {
// No se devuelve un archivo
echo "La operación no ha devuelto ningún archivo. Revise la configuración.\n";
}
}
private function readHeader($ch, $header) {
$this->headers[] = $header;
return strlen($header);
}
/* TODO
* Hacerlo compatible con el otro scraper
* tip: utilizar la posicion de "filename="
*/
private function getFilenameFromHeaders() {
foreach ($this->headers as $header) {
if (stripos($header, "filename=")) {
$filename = substr($header, stripos($header, "filename=") + 9);
// Quito dos caracteres salto línea al final
$filename = substr($filename, 0, strlen($filename) - 2);
// Solo caracteres alfanumericos y guiones, puntos
$filename = preg_replace('/[^\da-z\-\.]/i', '', $filename);
// Pongo extension si no viene
if (!strpos($filename, '.')){
foreach ($this->headers as $header) {
if (strpos($header, 'application/pdf')){
$filename = $filename.".pdf";
}
}
}
return $filename;
}
}
return false;
}
} | true |
cab4c280b395b569eddcc441792e54dfcf44cc38 | PHP | Iamoscarbc/ORQUIDEA_COLEGIO | /matricula/busquedaalumno.php | UTF-8 | 1,058 | 2.5625 | 3 | [] | no_license | <?php
//include("../seguridad.php");
include_once("../conexion/clsConexion.php");
$obj=new clsConexion;
if (isset($_GET['term'])){
//rrecorrer la tabla de
$return_arr = array();
/* Si la conexi�n a la base de datos , ejecuta instrucci�n SQL. */
$data=$obj->consultar("SELECT alumno.idalu
, alumno.codigo
, CONCAT(alumno.nombres, ' ', alumno.apepat_alu, ' ', alumno.apemat_alu) As nombres
, CONCAT(apoderado.nombre_apo, ' ', apoderado.apepat_apo, ' ', apoderado.apemat_apo) As nombre_apo
FROM
alumno
INNER JOIN apoderado
ON alumno.idapo = apoderado.idapo WHERE nombres like '%" .($_GET['term']) . "%' LIMIT 0 ,50");
/* Recuperar y almacenar en conjunto los resultados de la consulta.*/
foreach($data as $row) {
$row_array['value'] =$row['nombres']."|".$row['codigo'];
$row_array['idalumno']=$row['idalu'];
$row_array['nombre_apo']=$row['nombre_apo'];
$row_array['nombres']=$row['nombres'];
array_push($return_arr,$row_array);
}
/* Codifica el resultado del array en JSON. */
echo json_encode($return_arr);
}
?> | true |
8825e0dd0c79ea9ab443d4e4e500afbf5de6d027 | PHP | sunlollyking/Mobile-Patient-Record | /src/com/chrisdixon/PHP Scripts/addPatientDrug.php | UTF-8 | 2,094 | 2.90625 | 3 | [] | no_license | <?php
require("config.inc.php");
if (!empty($_POST)) {
$priority = $_POST['priority'];
$nhs_id = $_POST['nhs_id'];
$date_started = $_POST['date_started'];
$date_finished = $_POST['date_finished'];
$dosage = $_POST['dosage'];
$name = $_POST['name'];
$query = "INSERT INTO patient_drug (nhs_id, priority, name, date_started, date_finished, dosage)
VALUES ('$nhs_id', '$priority', '$name', '$date_started', '$date_finished', '$dosage')";
$query_params = array(
':priority' => $_POST['priority'],
':nhs_id' => $_POST['nhs_id'],
':name' => $_POST['name'],
':date_started' => $_POST['date_started'],
':date_finished' => $_POST['date_finished'],
':dosage' => $_POST['dosage']
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error. Reload And Contact System Admin";
die(json_encode($response));
}
}
else{
echo "Please Enter Fields";
}
?>
<form action="addPatientDrug.php" method="post">
Please enter the fields below and submit to add a details of any medication a patient is currently taking:<br />
<input type="text" name="nhs_id" placeholder="NHS ID Number" /> <br />
<br />
<input type="text" name="name" placeholder="Medication Name" /> <br />
<br />
<br />
<input type="text" name="priority" placeholder="What Is Drug Priority" /> <br />
<br />
<br />
<input type="text" name="dosage" placeholder="Enter Dosage Here" /> <br />
<br />
<br />
Please Enter The Date The Prescription Was Started:
This Should Be In The Form Of 'YYYY-MM-DD' <br /> <br />
<input type="text" name="date_started" placeholder="Date Started" /> <br />
<br />
Please Enter The Date The Prescription Will Finish:
This Should Be In The Form Of 'YYYY-MM-DD' <br /> <br />
<input type="text" name="date_finished" placeholder="Date Finished" /> <br />
<br />
<input type="submit" value="Add Concern" />
<br />
<br />
<a href="createNewPatient.php">Please Click To Go Back To Create Patient Screen</a>
</form> | true |
f79fdd3a7e52277a522df4069414413bc647aa1a | PHP | threebenji/goldpalm | /src/goldpalm.php | UTF-8 | 12,737 | 2.765625 | 3 | [
"MIT"
] | permissive | <?php
namespace ThreeBenji\GoldPalm;
/**
* Created by PhpStorm.
* User: yan
* Date: 2017/3/1
* Time: 下午5:27
*/
class GoldPalm
{
private $api_url = [
'test' => "https://test-api.lyht.cn/ntsms-contract-api/service/ContractWebService?wsdl",
'production' => "https://api.lyht.cn/ntsms-contract-api/service/ContractWebService?wsdl"
];
private $api;
private $token;
/**
* 实例化基础配置
* GoldPalm constructor.
* @param $config
* @throws \Exception
*/
public function __construct($config)
{
try {
//判断什么环境下的接口
$this->api = $this->api_url[$config['env'] ? $config['env'] : 'test'];
$client = new \SoapClient($this->api);
//默认先取authcode为登录token
if (isset($config['authcode']) && empty($config['authcode'])) {
$param = ['code' => $config['username'], 'authcode' => $config['authcode']];
$res = $client->__call('authenticationOTA', ['param' => $param]);
} else {
$param = ['code' => $config['username'], 'password' => md5($config['password'])];
$res = $client->__call('authentication', ['param' => $param]);
}
$result = json_decode($res->return);
if ($result->result == 'success') {
$this->token = $result->token;
} else {
throw new \Exception(json_encode($result->errors));
}
} catch (\SoapFault $soapFault) {
throw new \Exception($soapFault);
}
}
/**
* 上传电子合同,上传后进入已提交状态 or 上传后不提交
* @param $contract
* @param $is_upload bool true 上传后不提交 false 上传后提交
* @return mixed
* @throws \Exception
*/
public function submit($contract, $is_upload = false)
{
try {
$submitRequest = array();
$submitRequest['version'] = $contract['version'];//合同版本名称
$submitRequest['travelname'] = $contract['travel_name'];//旅游者代表
$submitRequest['travelmobile'] = $contract['travel_tel'];//旅游者代表手机号
$submitRequest['transactor'] = $contract['transactor'];//经办人
$submitRequest['price'] = $contract['price'];//费用合计
$submitRequest['no'] = $contract['no'];//合同号
//合同详情
$contractJSON = [];
//旅游者代表相关信息
$contractJSON['traveler'] = $contract['travelerJson'];
//地接社信息
$contractJSON['supplier'] = $contract['supplierJson'];
//旅行社信息(组团社信息)
$contractJSON['groupcorp'] = $contract['groupcorpJson'];
//旅游线路相关信息
$contractJSON['line'] = $contract['lineJson'];
//旅游费用支付方式及时间
$contractJSON['pay'] = $contract['payJson'];
//保险事项
$contractJSON['insurance'] = $contract['insuranceJson'];
//成团约定
$contractJSON['group'] = $contract['groupJson'];
//黄金周特别约定
$contractJSON['goldenweek'] = $contract['goldenweekJson'];
//争议处理
$contractJSON['controversy'] = $contract['controversyJson'];
//其他事项
$contractJSON['other'] = $contract['otherJson'];
$submitRequest['contractJSON'] = $contractJSON;
//电子合同团队信息
$contractTeam = [];
$contractTeam['linename'] = $contract['line_name'];//线路名称
$contractTeam['teamcode'] = $contract['team_code'];//团号
$contractTeam['days'] = $contract['days'];//行程天数
$contractTeam['nights'] = $contract['night_days'];//行程夜晚天数
$contractTeam['bgndate'] = $contract['start_on'];//出团日期
$contractTeam['enddate'] = $contract['end_on'];//返回日期
$contractTeam['qty'] = $contract['traveler_num'];//旅游人数
//行程安排
foreach ($contract['routes'] as $key => $route) {
$contractTeam['routes'][$key]['day'] = $route['day'];//第几天行程
$contractTeam['routes'][$key]['stop'] = $route['stop'];//当天行程第几站
$contractTeam['routes'][$key]['departcity'] = $route['starting_address'];//出发地
$contractTeam['routes'][$key]['arrivecity'] = $route['destination_city'];//目的地城市
$contractTeam['routes'][$key]['arrivestate'] = $route['destination_state'];//前往省
$contractTeam['routes'][$key]['arrivenation'] = $route['destination_country'];//前往国家
$contractTeam['routes'][$key]['trip'] = $route['trip'];//游览行程
}
//游客名单
foreach ($contract['guests'] as $key => $guest) {
$contractTeam['guests'][$key]['idtype'] = '1';//证件类型身份证号
$contractTeam['guests'][$key]['idcode'] = $guest['id_card'];//证件号
$contractTeam['guests'][$key]['name'] = $guest['name'];//姓名
$contractTeam['guests'][$key]['sex'] = Utils::gender($guest['id_card']);//性别
$contractTeam['guests'][$key]['birthday'] = Utils::birthday($guest['id_card']);//生日
$contractTeam['guests'][$key]['mobile'] = $guest['tel'];//合同人手机号
$contractTeam['guests'][$key]['no'] = $key + 1;//名单序号
}
$submitRequest['contractTeam'] = $contractTeam;//合同团队
$client = new \SoapClient($this->api);
$param = array('token' => $this->token, 'submitContractRequest' => $submitRequest);
if ($is_upload) {
$res = $client->__call('uploadContract', ['param' => $param]);
} else {
$res = $client->__call('submitContract', ['param' => $param]);
}
$result = json_decode($res->return);
if ($result->result == 'success') {
return $result->contract;
} else {
throw new \Exception(json_encode($result->errors));
}
} catch (\SoapFault $soapFault) {
throw new \Exception($soapFault);
}
}
/**
* 提交已经上传的合同
* @param $id
* @param $no
* @return bool
* @throws \Exception
*/
public function submitStatus($id, $no)
{
try {
$client = new \SoapClient($this->api);
$param = array('token' => $this->token, 'submitStatusRequest' => ['id' => $id, 'no' => $no]);
$res = $client->__call('submitStatus', array('param' => $param));
$result = json_decode($res->return);
if ($result->result == 'success') {
return true;
} else {
throw new \Exception(json_encode($result->errors));
}
} catch (\SoapFault $soapFault) {
throw new \Exception($soapFault);
}
}
/**
* 取消合同
* @param $id
* @param $no
* @return bool
* @throws \Exception
*/
public function cancelContract($id, $no)
{
try {
$client = new \SoapClient($this->api);
$param = array('token' => $this->token, 'cancelContractRequest' => ['id' => $id, 'no' => $no]);
$res = $client->__call('cancelContract', array('param' => $param));
$result = json_decode($res->return);
if ($result->result == 'success') {
return true;
} else {
throw new \Exception(json_encode($result->errors));
}
} catch (\SoapFault $soapFault) {
throw new \Exception($soapFault);
}
}
/**
* 补充完善合同保险信息接口
* @param $no
* @param $insurance string json
* @return bool
* @throws \Exception
*/
public function complementInsurance($no, $insurance)
{
try {
$client = new \SoapClient($this->api);
$param = array('token' => $this->token, 'complementInsuranceRequest' => ['no' => $no, 'insurance' => $insurance]);
$res = $client->__call('complementInsurance', array('param' => $param));
$result = json_decode($res->return);
if ($result->result == 'success') {
return true;
} else {
throw new \Exception(json_encode($result->errors));
}
} catch (\SoapFault $soapFault) {
throw new \Exception($soapFault);
}
}
/**
* 补充游客列表只有为提交的合同可以使用
* @param $guests
* @return bool
* @throws \Exception
*/
public function complementGuest($guests)
{
try {
$client = new \SoapClient($this->api);
$param = array('token' => $this->token, 'complementGuestRequest' =>$guests);
$res = $client->__call('complementGuest', array('param' => $param));
$result = json_decode($res->return);
if ($result->result == 'success') {
return true;
} else {
throw new \Exception(json_encode($result->errors));
}
} catch (\SoapFault $soapFault) {
throw new \Exception($soapFault);
}
}
/**
* 补充签名功能
* @param $id
* @param $base64image
* @return bool
* @throws \Exception
*/
public function submitSign($id,$base64image)
{
try {
$client = new \SoapClient($this->api);
$param = array('token' => $this->token, 'complementSignRequest' =>['id'=>$id,'base64image'=>$base64image]);
$res = $client->__call('submitSign', array('param' => $param));
$result = json_decode($res->return);
if ($result->result == 'success') {
return true;
} else {
throw new \Exception(json_encode($result->errors));
}
} catch (\SoapFault $soapFault) {
throw new \Exception($soapFault);
}
}
/**
* 根据合同ID获取是否签名
* @param $id
* @return bool|\Exception|\SoapFault
* @throws \Exception
*/
public function getSignCreate($id)
{
try {
$client = new \SoapClient($this->api);
$param = array('token' => $this->token, 'contractid' => $id);
$res = $client->__call('getSignCreate', array('param' => $param));
$result = json_decode($res->return);
if ($result->result == 'success') {
return true;
} else {
throw new \Exception(json_encode($result->errors));
}
} catch (\SoapFault $soapFault) {
throw new \Exception($soapFault);
}
}
/**
* 根据合同号获取合同基本信息
* @param $no
* @return bool
* @throws \Exception
*/
public function getContractBaseInfo($no)
{
try {
$client = new \SoapClient($this->api);
$param = array('token' => $this->token, 'contractno' => $no);
$res = $client->__call('getContractBaseInfo', array('param' => $param));
$result = json_decode($res->return);
if ($result->result == 'success') {
return true;
} else {
throw new \Exception(json_encode($result->errors));
}
} catch (\SoapFault $soapFault) {
throw new \Exception($soapFault);
}
}
/**
* 重发短信
* @param $id
* @param $guestname
* @param $guestmobile
* @return bool
* @throws \Exception
*/
public function resendMsg($id,$guestname,$guestmobile)
{
try {
$client = new \SoapClient($this->api);
$param = array('token' => $this->token, 'contractid' => $id,'guestname'=>$guestname,'guestmobile'=>$guestmobile);
$res = $client->__call('resendMsg', array('param' => $param));
$result = json_decode($res->return);
if ($result->result == 'success') {
return true;
} else {
throw new \Exception(json_encode($result->errors));
}
} catch (\SoapFault $soapFault) {
throw new \Exception($soapFault);
}
}
} | true |
de98d52af22027c562cc74b605ecfc796a4365b3 | PHP | MagnaFacta/zalt-loader | /test/Test1/Target1.php | UTF-8 | 882 | 2.515625 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
/**
*
* @package Test1
* @subpackage Target1
* @author Matijs de Jong <mjong@magnafacta.nl>
* @copyright Expression copyright is undefined on line 44, column 18 in Templates/Scripting/PHPClass.php.
* @license No free license, do not copy
*/
namespace Test1;
use Zalt\Loader\ProjectOverloader;
use Zalt\Loader\Target\TargetAbstract;
/**
*
* @package Test1
* @subpackage Target1
* @copyright Expression copyright is undefined on line 56, column 18 in Templates/Scripting/PHPClass.php.
* @license No free license, do not copy
* @since Class available since version 1.8.3 Aug 30, 2018 12:41:07 PM
*/
class Target1 extends TargetAbstract
{
/**
*
* @var ProjectOverloader
*/
public $loader;
/**
*
* @var \Test3\In3and1
*/
public $var31;
/**
*
* @var \Test3\In3and2and1
*/
public $var321;
}
| true |
d7eb21be8be7185534f2d8c0c929efef6817ee0c | PHP | mithunmo/phpsample | /libraries/cli/command/logToConsole.class.php | UTF-8 | 2,174 | 2.96875 | 3 | [] | no_license | <?php
/**
* cliCommandLogToConsole Class
*
* Stored in logToConsole.class.php
*
* @author Dave Redfern
* @copyright Dave Redfern (c) 2007-2010
* @package scorpio
* @subpackage cli
* @category cliCommandLogToConsole
* @version $Rev: 707 $
*/
/**
* cliCommandLogToConsole class
*
* Adds a systemLogWriterCli object to the systemLog instance allowing
* all log messages from ALWAYS to current log level to be output on
* the command line as the application is executing. This is mainly for
* debugging.
*
* Note: if using with cliCommandLog, this option should come LAST on the
* cli switch stack e.g. -oV will use the system default log level and
* NOT systemLogLevel::DEBUG as set by V. The correct order is -Vo.
*
* <code>
* // add output logging to app
* $oApp = new cliApplication('example', 'A simple example.');
* $oRequest = cliRequest::getInstance()->setApplication($oApp);
* $oApp->getCommandChain()
* ->addCommand(
* new cliCommandLogToConsole($oRequest)
* )
* $oApp->execute($oRequest);
*
* // add verbose logging and output to console
* $oApp = new cliApplication('example', 'A simple example.');
* $oRequest = cliRequest::getInstance()->setApplication($oApp);
* $oApp->getCommandChain()
* ->addCommand(new cliCommandLog($oRequest))
* ->addCommand(new cliCommandLogToConsole($oRequest))
* $oApp->execute($oRequest);
* </code>
*
* @package scorpio
* @subpackage cli
* @category cliCommandLogToConsole
*/
class cliCommandLogToConsole extends cliCommand {
/**
* Creates a new console logger switch
*
* @param cliRequest $inRequest
*/
function __construct(cliRequest $inRequest) {
parent::__construct($inRequest, null, null, 'o');
$this->setCommandHelp('Outputs systemLog messages to the console');
$this->setCommandIsOptional(true);
}
/**
* Executes the command adding the output logger
*
* @return void
*/
function execute() {
if ( $this->getRequest()->getSwitch('o') ) {
systemLog::getInstance()->setWriter(
new systemLogWriterCli(
new systemLogFilter(
systemLogLevel::ALWAYS, systemLog::getInstance()->getLogLevel()
)
)
);
}
}
} | true |
6830373c8c12a7d2ccd6c37fb127c45e55b3a426 | PHP | projetos-avanco/avanco | /dashboard/database/functions/profile/data/indices.php | UTF-8 | 5,846 | 2.578125 | 3 | [] | no_license | <?php
/**
* calcula o percentual avancino do colaborador em um período específico ou em uma data específica
* @param - objeto com uma conexão aberta
* @param - array com o modelo do colaborador
* @param - array com a data inicial e data final de um período ou específica
*/
function calculaPercentualAvancino($objeto, $modelo, $datas)
{
$query =
"SELECT
ROUND(100 * (
(SELECT
COUNT(d.id_chat)
FROM
(SELECT
e.id_chat,
c.chat_duration,
TIMEDIFF(FROM_UNIXTIME(c.user_closed_ts, '%H:%i:%s'), FROM_UNIXTIME(c.time, '%H:%i:%s')) AS time_diff
FROM lh_chat AS c
INNER JOIN av_questionario_externo AS e
ON e.id_chat = c.id
WHERE (c.user_id = {$modelo['pessoal']['id']})
AND (e.avaliacao_colaborador = 'Otimo' OR e.avaliacao_colaborador = 'Bom')
AND (DATE_FORMAT(e.data_pesquisa, '%Y-%m-%d') BETWEEN '{$datas['data_1']}' AND '{$datas['data_2']}')) AS d
WHERE NOT (d.time_diff < '00:03:00' AND d.chat_duration = 0))
/
(SELECT
COUNT(d.id_chat)
FROM
(SELECT
e.id_chat,
c.chat_duration,
TIMEDIFF(FROM_UNIXTIME(c.user_closed_ts, '%H:%i:%s'), FROM_UNIXTIME(c.time, '%H:%i:%s')) AS time_diff
FROM lh_chat AS c
INNER JOIN av_questionario_externo AS e
ON e.id_chat = c.id
WHERE (c.user_id = {$modelo['pessoal']['id']})
AND (DATE_FORMAT(e.data_pesquisa, '%Y-%m-%d') BETWEEN '{$datas['data_1']}' AND '{$datas['data_2']}')) AS d
WHERE NOT (d.time_diff < '00:03:00' AND d.chat_duration = 0))), 0) AS percentual_indice_avancino;";
$resultado = mysqli_query($objeto, $query);
$valor = mysqli_fetch_row($resultado);
$modelo['indices']['percentual_avancino'] = $valor[0];
return $modelo;
}
/**
* calcula o percentual de eficiência do colaborador em um período específico ou em uma data específica
* @param - objeto com uma conexão aberta
* @param - array com o modelo do colaborador
* @param - array com a data inicial e data final de um período ou específica
*/
function calculaPercentualEficiencia($objeto, $modelo, $datas)
{
$query =
"SELECT
ROUND(100 * (
(SELECT
COUNT(d.id_chat)
FROM
(SELECT
e.id_chat,
c.chat_duration,
TIMEDIFF(FROM_UNIXTIME(c.user_closed_ts, '%H:%i:%s'), FROM_UNIXTIME(c.time, '%H:%i:%s')) AS time_diff
FROM lh_chat AS c
INNER JOIN av_questionario_externo AS e
ON e.id_chat = c.id
WHERE (c.user_id = {$modelo['pessoal']['id']})
AND (e.avaliacao_atendimento = 'Otimo' OR e.avaliacao_atendimento = 'Bom')
AND (DATE_FORMAT(e.data_pesquisa, '%Y-%m-%d') BETWEEN '{$datas['data_1']}' AND '{$datas['data_2']}')) AS d
WHERE NOT (d.time_diff < '00:03:00' AND d.chat_duration = 0))
/
(SELECT
COUNT(d.id_chat)
FROM
(SELECT
e.id_chat,
c.chat_duration,
TIMEDIFF(FROM_UNIXTIME(c.user_closed_ts, '%H:%i:%s'), FROM_UNIXTIME(c.time, '%H:%i:%s')) AS time_diff
FROM lh_chat AS c
INNER JOIN av_questionario_externo AS e
ON e.id_chat = c.id
WHERE (c.user_id = {$modelo['pessoal']['id']})
AND (DATE_FORMAT(e.data_pesquisa, '%Y-%m-%d') BETWEEN '{$datas['data_1']}' AND '{$datas['data_2']}')) AS d
WHERE NOT (d.time_diff < '00:03:00' AND d.chat_duration = 0))), 0) AS percentual_indice_eficiencia;";
$resultado = mysqli_query($objeto, $query);
$valor = mysqli_fetch_row($resultado);
$modelo['indices']['percentual_eficiencia'] = $valor[0];
return $modelo;
}
/**
* calcula o percentual de questionários respondidos pelo colaborador em um período específico ou em uma data específica
* @param - objeto com uma conexão aberta
* @param - array com o modelo do colaborador
* @param - array com a data inicial e data final de um período ou específica
*/
function calculaPercentualQuestionariosRespondidos($objeto, $modelo, $datas)
{
$query =
"SELECT
ROUND(100 * (
(SELECT
COUNT(d.id_chat)
FROM
(SELECT
i.id_chat,
c.chat_duration,
TIMEDIFF(FROM_UNIXTIME(c.user_closed_ts, '%H:%i:%s'), FROM_UNIXTIME(c.time, '%H:%i:%s')) AS time_diff
FROM av_questionario_interno AS i
INNER JOIN lh_chat AS c
ON c.id = i.id_chat
WHERE (c.user_id = {$modelo['pessoal']['id']})
AND (c.status = 2)
AND (FROM_UNIXTIME(c.time, '%Y-%m-%d') BETWEEN '{$datas['data_1']}' AND '{$datas['data_2']}')) AS d
WHERE NOT (d.time_diff < '00:03:00' AND d.chat_duration = 0))
/
(SELECT
COUNT(d.id)
FROM
(SELECT
c.id,
c.chat_duration,
TIMEDIFF(FROM_UNIXTIME(c.user_closed_ts, '%H:%i:%s'), FROM_UNIXTIME(c.time, '%H:%i:%s')) AS time_diff
FROM lh_chat AS c
WHERE (c.user_id = {$modelo['pessoal']['id']})
AND (c.status = 2)
AND (FROM_UNIXTIME(c.time, '%Y-%m-%d') BETWEEN '{$datas['data_1']}' AND '{$datas['data_2']}')) AS d
WHERE NOT (d.time_diff < '00:03:00' AND d.chat_duration = 0))), 0) AS percentual_questionario_respondido;";
$resultado = mysqli_query($objeto, $query);
$valor = mysqli_fetch_row($resultado);
$modelo['indices']['percentual_questionario_respondido'] = $valor[0];
return $modelo;
}
/**
* consulta e retorna os dados dos índices (avancino, eficiência e questionários respondidos) do colaborador
* @param - objeto com uma conexão aberta
* @param - array com o modelo do colaborador
* @param - array com a data inicial e data final de um período ou específica
*/
function consultaDadosDosIndicesDoColaborador($objeto, $modelo, $datas)
{
# chamando funções que calculam e retornam os índices
$modelo = calculaPercentualAvancino($objeto, $modelo, $datas);
$modelo = calculaPercentualEficiencia($objeto, $modelo, $datas);
$modelo = calculaPercentualQuestionariosRespondidos($objeto, $modelo, $datas);
return $modelo;
}
| true |
dee804e90d578c54f4d7b94b1bfc59fe94f5b3a6 | PHP | dalloglio/api-republica-online | /app/Http/Controllers/FormContactController.php | UTF-8 | 2,569 | 2.578125 | 3 | [] | no_license | <?php
namespace App\Http\Controllers;
use App\Domains\Form\FormRepository;
use App\Mail\FormContactCreated;
use Illuminate\Http\Request;
use Mail;
class FormContactController extends Controller
{
/**
* @var FormRepository
*/
protected $repository;
/**
* FormContactController constructor.
* @param FormRepository $repository
*/
public function __construct(FormRepository $repository)
{
$this->repository = $repository;
}
/**
* @param $form_id
* @return mixed
*/
public function index($form_id)
{
return $this->repository->findById((int) $form_id)->contacts;
}
/**
* @param Request $request
* @param $form_id
* @return mixed
*/
public function store(Request $request, $form_id)
{
$form = $this->repository->findById((int) $form_id);
$contact = $form->contacts()->create($request->all());
if ($contact) {
Mail::to($form->email)->send(new FormContactCreated($form, $contact));
return $contact;
}
return response()->json(null, 400);
}
/**
* @param $form_id
* @param $contact_id
* @return mixed
*/
public function show($form_id, $contact_id)
{
$this->repository->setRelationships();
$contact = $this->repository->findById((int) $form_id)->contacts()->find((int) $contact_id);
$contact->contactable;
return $contact;
}
/**
* @param Request $request
* @param $form_id
* @param $contact_id
* @return \Illuminate\Http\JsonResponse
*/
public function update(Request $request, $form_id, $contact_id)
{
$form = $this->repository->findById((int) $form_id);
if ($form) {
$contact = $form->contacts()->find($contact_id);
if ($contact) {
if ($contact->update($request->all())) {
return $contact;
}
}
}
return response()->json(null, 404);
}
/**
* @param $form_id
* @param $contact_id
* @return \Illuminate\Http\JsonResponse
*/
public function destroy($form_id, $contact_id)
{
$form = $this->repository->findById((int) $form_id);
if ($form) {
$contact = $form->contacts()->find($contact_id);
if ($contact) {
if ($contact->delete()) {
return $contact;
}
}
}
return response()->json(null, 404);
}
}
| true |
c153d4acc73e4babc8c42afeda5d4bc9ad351f0d | PHP | vimac/currency-exchange-example | /src/BusinessImpl/CurrencyBusinessImpl.php | UTF-8 | 1,438 | 2.859375 | 3 | [] | no_license | <?php
namespace CurrencyExchangeExample\BusinessImpl;
use CurrencyExchangeExample\Lib\Injectable;
use PDO;
class CurrencyBusinessImpl extends Injectable
{
public function getCurrencies($page)
{
$pageSize = 3;
/** @var PDO $pdo */
$pdo = $this->getContainer()->get('db');
$st = $pdo->prepare('select `name`,`base` from `currencies` limit ?,?');
$st->bindValue(1, ($page - 1) * $pageSize, PDO::PARAM_INT);
$st->bindValue(2, $pageSize, PDO::PARAM_INT);
$st->execute();
$result = $st->fetchAll();
return $result;
}
public function exchange($fromCurrency, $fromValue, $toCurrency)
{
$fromBase = 0;
$toBase = 0;
/** @var PDO $pdo */
$pdo = $this->getContainer()->get('db');
$st = $pdo->prepare('select `name`, `base` from `currencies` where `name` in (?,?)');
$st->bindValue(1, $fromCurrency);
$st->bindValue(2, $toCurrency);
$st->execute();
$result = $st->fetchAll();
foreach ($result as $item) {
if ($item['name'] == $fromCurrency) {
$fromBase = $item['base'];
}
if ($item['name'] == $toCurrency) {
$toBase = $item['base'];
}
}
$toValue = $fromValue * ($toBase / $fromBase);
return $toValue;
}
public function append($name, $base)
{
}
} | true |
8ab4290d9b53dae008c9509f74368cc16894b640 | PHP | osamarafa1994/School_project_in_codeigniter_frameWork | /application/views/users_admin/years_study.php | UTF-8 | 243 | 2.765625 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | <?php
$years_study = '';
$years_study .= '<option value="">اختار الصف </option>';
foreach($years as $year){
$years_study .= '<option value="'. $year->id . '">'. $year->year_name . '</option>';
}
echo $years_study;
?>
| true |
a72727fbacac5bb44d9615198b36ff4eead7204d | PHP | hxpzlm/oo | /frontend/models/Purchase.php | UTF-8 | 3,092 | 2.53125 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
namespace frontend\models;
use Yii;
/**
* This is the model class for table "{{%purchase}}".
*
* @property integer $purchase_id
* @property integer $store_id
* @property string $store_name
* @property integer $warehouse_id
* @property string $warehouse_name
* @property integer $create_time
* @property integer $buy_time
* @property integer $confirm_time
* @property integer $confirm_user_id
* @property string $confirm_user_name
* @property integer $purchases_time
* @property integer $purchases_status
* @property integer $add_user_id
* @property string $add_user_name
* @property integer $principal_id
* @property string $principal_name
* @property string $invoice_and_pay_sate
* @property string $remark
* @property string $batch_num
* @property integer $invalid_time
* @property string $totle_price
*/
class Purchase extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%purchase}}';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['store_id', 'warehouse_id', 'create_time', 'add_user_id'], 'integer', 'message'=>'必须为数字'],
[['warehouse_id'], 'required','message'=>'请选择入库仓库'],
[['totle_price'], 'required','message'=>'总价不能为空'],
[['totle_price'], 'number','message'=>'总价必须为数字'],
[['invalid_time'], 'required','message'=>'请选择失效日期'],
[['batch_num'], 'required','message'=>'批号不能为空'],
[['buy_time'], 'required','message'=>'请选择采购日期'],
[['principal_id'], 'required','message'=>'请选择负责人'],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'purchase_id' => '采购ID',
'store_id' => '入驻商家ID',
'store_name' => '入驻商家名称',
'warehouse_id' => '仓库ID',
'warehouse_name' => '仓库名称',
'create_time' => '创建时间 ',
'buy_time' => '采购日期',
'confirm_time' => '审核时间',
'confirm_user_id' => '审核人ID',
'confirm_user_name' => '审核人姓名',
'purchases_time' => '入库时间',
'purchases_status' => '入库状态 0 未入库 1入库',
'add_user_id' => '创建人ID',
'add_user_name' => '创建人名称',
'principal_id' => '负责人',
'principal_name' => '负责人名称',
'invoice_and_pay_sate' => '发票和付款情况',
'remark' => '备注',
'batch_num' => '批次号',
'invalid_time' => '失效期',
'totle_price' => '总价',
];
}
public static function getGoodsCat($goods_id){
return Goods::findOne($goods_id);
}
public function getPgoods(){
return $this->hasMany(PurchaseGoods::className(), ['purchase_id' => 'purchase_id']);
}
}
| true |
c187c7365afb4134980817c9f9fb55b9cd3c2df4 | PHP | nguyenthithuuyen/ALL_question | /Priority/PriorityQueue.php | UTF-8 | 819 | 3.34375 | 3 | [] | no_license | <?php
include_once "Patient.php";
class PriorityQueue
{
const MAX_SIZE = 10;
protected $limit;
protected $array;
public function __construct()
{
$this->array = [];
$this->limit = self::MAX_SIZE;
}
protected function enqueue($patent)
{
if ($this->isFull()) {
echo "day";
exit();
}
array_push($this->array, $patent);
}
public function dequeue()
{
usort($this->array, function ($a, $b) {
if ($a->code < $b->code) {
return true;
}
return false;
});
return $this->array[0];
}
public function size()
{
return count($this->array);
}
public function isFull()
{
return $this->size();
}
} | true |
203f6d10c329b4357e4fd32d65ce724cc0653334 | PHP | Yas-Elak/task_manager | /app/Email.php | UTF-8 | 3,714 | 2.546875 | 3 | [
"MIT"
] | permissive | <?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Mail;
class Email extends Model
{
/**
* Send the email when a task is created/updated/deleted
*
* @param $data
* @param $route
* @param $subject
*/
public static function taskMail($data, $route, $subject)
{
//still must change the message to because if i do user>email it returns an error 400 form mailgun
//with mail gun i can send email to authorize adress only with the free account
//here I only have mine so i just leave it like that for now
foreach ($data['data']->users()->get() as $user) {
if ($user->option->task_email == 15) {
Mail::send($route, $data, function ($message) use ($data, $user, $subject) {
$message->to('elalaoui87@gmail.com')->subject($subject . $data['data']->subject);
});
}
}
}
/**
* Send the email when a ticket is created/updated/deleted
* @param $data
* @param $route
* @param $subject
*/
public static function ticketMail($data, $route, $subject)
{
// $message->to($data['data']->agent->email)->subject($subject . $data['data']->subject);
if ($data['data']->agent->option->ticket_email == 5) {
Mail::send($route, $data, function ($message) use ($data, $subject) {
$message->to('elalaoui87@gmail.com')->subject($subject . $data['data']->subject);
});
}
}
/**
* Send the email when a project is created/updated/deleted
*
* @param $data
* @param $route
* @param $subject
*/
public static function projectMail($data, $route, $subject)
{
//still must change the message to because if i do user>email it returns an error 400 form mailgun
foreach ($data['data']->users()->get() as $user) {
if ($user->option->project_email == 199) {
Mail::send($route, $data, function ($message) use ($data, $user, $subject) {
$message->to('elalaoui87@gmail.com')->subject($subject . $data['data']->subject);
});
}
}
}
/**
* Send the email when a comment is created
*
* @param $data
* @param $route
* @param $subject
*/
public static function commentMail($data, $route, $subject)
{
//the project, the ticket and the task are nullable so I must check which one the comment is for before
//sending the email
if (!empty($data['project'])) {
foreach ($data['project']->users()->get() as $user) {
if ($user->option->comment_email == 120) {
Mail::send($route, $data, function ($message) use ($data, $subject) {
$message->to('elalaoui87@gmail.com')->subject($subject . $data['project']->subject);
});
}
}
} else if (!empty($data['task'])) {
foreach ($data['task']->users()->get() as $user) {
if ($user->option->comment_email == 5) {
Mail::send($route, $data, function ($message) use ($data, $subject) {
$message->to('elalaoui87@gmail.com')->subject($subject . $data['task']->project->subject);
});
}
}
} else if (!empty($data['ticket'])) {
if ($data['data']->agent->option->ticket_email == 5) {
Mail::send($route, $data, function ($message) use ($data, $subject) {
$message->to('elalaoui87@gmail.com')->subject($subject . $data['ticket']->project->subject);
});
}
}
}
}
| true |
881ecd1cd46c77354d24ab4d397f505f7e29b416 | PHP | Xeviousbr/teletudo | /models/ExampleRepository.php | UTF-8 | 3,045 | 3.125 | 3 | [] | no_license | <?php
use Mgallegos\LaravelJqgrid\Repositories\RepositoryInterface;
class ExampleRepository implements RepositoryInterface {
/**
* Calculate the number of rows. It's used for paging the result.
*
* @param array $filters
* An array of filters, example: array(array('field'=>'column index/name 1','op'=>'operator','data'=>'searched string column 1'), array('field'=>'column index/name 2','op'=>'operator','data'=>'searched string column 2'))
* The 'field' key will contain the 'index' column property if is set, otherwise the 'name' column property.
* The 'op' key will contain one of the following operators: '=', '<', '>', '<=', '>=', '<>', '!=','like', 'not like', 'is in', 'is not in'.
* when the 'operator' is 'like' the 'data' already contains the '%' character in the appropiate position.
* The 'data' key will contain the string searched by the user.
* @return integer
* Total number of rows
*/
public function getTotalNumberOfRows(array $filters = array())
{
return 5;
}
/**
* Get the rows data to be shown in the grid.
*
* @param integer $limit
* Number of rows to be shown into the grid
* @param integer $offset
* Start position
* @param string $orderBy
* Column name to order by.
* @param array $sord
* Sorting order
* @param array $filters
* An array of filters, example: array(array('field'=>'column index/name 1','op'=>'operator','data'=>'searched string column 1'), array('field'=>'column index/name 2','op'=>'operator','data'=>'searched string column 2'))
* The 'field' key will contain the 'index' column property if is set, otherwise the 'name' column property.
* The 'op' key will contain one of the following operators: '=', '<', '>', '<=', '>=', '<>', '!=','like', 'not like', 'is in', 'is not in'.
* when the 'operator' is 'like' the 'data' already contains the '%' character in the appropiate position.
* The 'data' key will contain the string searched by the user.
* @return array
* An array of array, each array will have the data of a row.
* Example: array(array("column1" => "1-1", "column2" => "1-2"), array("column1" => "2-1", "column2" => "2-2"))
*/
public function getRows($limit, $offset, $orderBy = null, $sord = null, array $filters = array())
{
return array(
array("column1" => "1-1", "column2" => "1-2", "column3" => "1-3", "column4" => "1-4", "column5" => "1-5"),
array("column1" => "2-1", "column2" => "2-2", "column3" => "2-3", "column4" => "2-4", "column5" => "2-5"),
array("column1" => "3-1", "column2" => "3-2", "column3" => "3-3", "column4" => "3-4", "column5" => "3-5"),
array("column1" => "4-1", "column2" => "4-2", "column3" => "4-3", "column4" => "4-4", "column5" => "4-5"),
array("column1" => "5-1", "column2" => "5-2", "column3" => "5-3", "column4" => "5-4", "column5" => "5-5"),
);
}
} | true |
0c1d98b3b26cb706c958225cc753e5b0482744a2 | PHP | jcwing77/bigproject | /iweb-m/php/order.php | UTF-8 | 1,148 | 2.71875 | 3 | [] | no_license | <?php
/* 生成订单
请求方法: POST
请求消息头部:
Content-Type: application/json
响应消息主体数据形如:
{
"uid": 999,
"price":1999,
"data":[
{"cid":10, "count":3,"price":100},
{"cid":15, "count":1,"price":200}
]
}
响应消息头部:
Content-Type: application.json
响应消息主体数据形如:
{"code":1}
*/
$postData = $GLOBALS['HTTP_RAW_POST_DATA']; //读取原始POST请求主体数据
$postData = json_decode($postData, true); //将原始JSON数据解析为PHP数组
$uid = $postData['uid'];
$price = $postData['price'];
require('init.php');
//生成订单记录,并获取订单编号
$t = time() * 1000;
$sql = "INSERT INTO orders VALUES(NULL, $uid,$t,'北三环西路',$price,0)";
mysqli_query($conn,$sql);
$oid = mysqli_insert_id($conn);
foreach($postData['data'] as $d){
$sql="INSERT INTO orders_detail VALUES (NULL,$oid,$d[cid],$d[count],$d[price])";
mysqli_query($conn,$sql);
$sql="DELETE FROM cart WHERE userid=$uid and courseid=$d[cid]";
mysqli_query($conn,$sql);
$output["code"]=1;
}
echo json_encode($output);
| true |
1c1c2a1c71628bf172f973f7539248f33caf836c | PHP | elo-mkt/elo-api | /src/Elo/Api/Cmd/AddAgreementTermsToProvisionedUser.php | UTF-8 | 653 | 2.609375 | 3 | [] | no_license | <?php
namespace Elo\Api\Cmd;
use Elo\Api\Cmd\VO\UserData;
class AddAgreementTermsToProvisionedUser extends EloApiCMD
{
/** @var UserData */
private $userId;
private $termId;
public function __construct(string $userId, string $termId)
{
parent::__construct();
$this->userId = $userId;
$this->termId = $termId;
$this->isPrivateCall = true;
$this->graphQLFile = "addAgreementTermsToProvisonedUser";
}
public function execute()
{
$data = [
'userId' => $this->userId,
'termId' => $this->termId
];
$this->call($data);
}
} | true |
8673e47188dc66b62b37dd11cbe6b7e8ffda43cf | PHP | nanasess/eccube3-freee-plugin | /Entity/FreeeWallet.php | UTF-8 | 1,692 | 2.546875 | 3 | [] | no_license | <?php
namespace Plugin\FreeeLight\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* FreeeWallet
*/
class FreeeWallet extends \Eccube\Entity\AbstractEntity
{
/**
* @var integer
*/
private $id;
/**
* @var string
*/
private $name;
/**
* @var integer
*/
private $bank_id;
/**
* @var string
*/
private $type;
/**
* Set id
*
* @param integer $id
* @return FreeeWallet
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* @param string $name
* @return FreeeWallet
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Set bank_id
*
* @param integer $bankId
* @return FreeeWallet
*/
public function setBankId($bankId)
{
$this->bank_id = $bankId;
return $this;
}
/**
* Get bank_id
*
* @return integer
*/
public function getBankId()
{
return $this->bank_id;
}
/**
* Set type
*
* @param string $type
* @return FreeeWallet
*/
public function setType($type)
{
$this->type = $type;
return $this;
}
/**
* Get type
*
* @return string
*/
public function getType()
{
return $this->type;
}
}
| true |
7862ae6bc06199afc4d77571742820819b3d2cda | PHP | RyotaMuramatsu/php-laravel-kadai | /php-laravel03.php | UTF-8 | 1,381 | 3.859375 | 4 | [] | no_license | <?php
//課題1$name にあなたの名前を代入し、 if文で $name があなたの名前だったら 「私は あなたの名前 です」
// もし違ったら「あなたの名前ではありません」と表示するように実装してください。
$name = "Ryota";
//6行目にイコールが一つ足りなかった
if ($name == "Ryota"){
echo "私は $name です"."\n";
}else {
echo "あなたの名前ではありません"."\n";
}
//課題2for文を使って、1から10000までの合計の値を表示してください。
//total=0 としていなかった
$total = 0;
for($i = 0; $i <= 10000; $i++){
$total += $i;
}
echo $total."\n";
//課題3$fruits に配列で好きなフルーツを5個代入し、foreach文で順番に出力してください。
$fruits = ["apple","banana","orange","kwi","melon"];
// 一時変数名を$kajitsuとしてやり直しました
foreach($fruits as $kajitsu){
echo "要素は" .$kajitsu;
echo "\n";
}
//課題4【応用】 次のプログラムのバグを修正し、1から100までの間で5の倍数のみ表示するようにしてみてください。
$start = 1;
$end = 100;
// 32行目 $i <= $end のところに < が足りなかった。
for($i = $start; $i <= $end; $i++){
if($i % 5 == 0){
echo $i."\n";
}
}
// if($i % 5 == 0)
// echo $i | true |
d014b273b03ace82e446e169e9471756f0f3f6a9 | PHP | fiher/PHP-Fundamentals | /Arrays/IndexOfLetters.php | UTF-8 | 450 | 3.09375 | 3 | [] | no_license | <?php
$alphabet = "a b c d e f g h i j k l m n o p q r s t u v w x y z";
$alphabetArray = explode(' ',$alphabet);
unset($alphabet);
$input = fgets(STDIN);
$input = trim(strtolower($input));
$last = "";
for ($i=0;$i<strlen($input)-1;$i++){
$index = array_search($input[$i],$alphabetArray);
if($i==strlen($input)-2){
$last=array_search($input[$i+1],$alphabetArray);
}
echo "$input[$i] -> $index\n";
}
echo "$input[$i] -> $last"; | true |
2c46ca8b8ca87c5f7e6ee4e5b9fdec2715471477 | PHP | riking/alttp_vt_randomizer | /app/Region/LightWorld.php | UTF-8 | 18,358 | 2.5625 | 3 | [
"MIT"
] | permissive | <?php namespace ALttP\Region;
use ALttP\Item;
use ALttP\Location;
use ALttP\Region;
use ALttP\Support\LocationCollection;
use ALttP\World;
/**
* Light World Region and it's Locations contained within
*/
class LightWorld extends Region {
protected $name = 'Light World';
/**
* Create a new Light World Region and initalize it's locations
*
* @param World $world World this Region is part of
*
* @return void
*/
public function __construct(World $world) {
parent::__construct($world);
$this->locations = new LocationCollection([
new Location\Altar("Altar", 0x289B0, null, $this),
new Location\Npc("Uncle", 0x2DF45, null, $this),
new Location\Chest("[cave-034] Hyrule Castle secret entrance", 0xE971, null, $this),
new Location\Chest("[cave-018] Graveyard - top right grave", 0xE97A, null, $this),
new Location\Chest("[cave-047] Dam", 0xE98C, null, $this),
new Location\Chest("[cave-040] Link's House", 0xE9BC, null, $this),
new Location\Chest("[cave-031] Tavern", 0xE9CE, null, $this),
new Location\Chest("[cave-026] chicken house", 0xE9E9, null, $this),
new Location\Chest("[cave-044] Aginah's cave", 0xE9F2, null, $this),
new Location\Chest("[cave-035] Sahasrahla's Hut [left chest]", 0xEA82, null, $this),
new Location\Chest("[cave-035] Sahasrahla's Hut [center chest]", 0xEA85, null, $this),
new Location\Chest("[cave-035] Sahasrahla's Hut [right chest]", 0xEA88, null, $this),
new Location\Chest("[cave-021] Kakariko well [top chest]", 0xEA8E, null, $this),
new Location\Chest("[cave-021] Kakariko well [left chest row of 3]", 0xEA91, null, $this),
new Location\Chest("[cave-021] Kakariko well [center chest row of 3]", 0xEA94, null, $this),
new Location\Chest("[cave-021] Kakariko well [right chest row of 3]", 0xEA97, null, $this),
new Location\Chest("[cave-021] Kakariko well [bottom chest]", 0xEA9A, null, $this),
new Location\Chest("[cave-022-B1] Thief's hut [top chest]", 0xEB0F, null, $this),
new Location\Chest("[cave-022-B1] Thief's hut [top left chest]", 0xEB12, null, $this),
new Location\Chest("[cave-022-B1] Thief's hut [top right chest]", 0xEB15, null, $this),
new Location\Chest("[cave-022-B1] Thief's hut [bottom left chest]", 0xEB18, null, $this),
new Location\Chest("[cave-022-B1] Thief's hut [bottom right chest]", 0xEB1B, null, $this),
new Location\Chest("[cave-016] cave under rocks west of Santuary", 0xEB3F, null, $this),
new Location\Chest("[cave-050] cave southwest of Lake Hylia [bottom left chest]", 0xEB42, null, $this),
new Location\Chest("[cave-050] cave southwest of Lake Hylia [top left chest]", 0xEB45, null, $this),
new Location\Chest("[cave-050] cave southwest of Lake Hylia [top right chest]", 0xEB48, null, $this),
new Location\Chest("[cave-050] cave southwest of Lake Hylia [bottom right chest]", 0xEB4B, null, $this),
new Location\Chest("[cave-051] Ice Cave", 0xEB4E, null, $this),
new Location\Npc("Bottle Vendor", 0x2EB18, null, $this),
new Location\Npc("Sahasrahla", 0x2F1FC, null, $this),
new Location\Npc("Magic Bat", 0x180015, null, $this),
new Location\Npc\BugCatchingKid("Sick Kid", 0x339CF, null, $this),
new Location\Npc("Hobo", 0x33E7D, null, $this),
new Location\Drop\Bombos("Bombos Tablet", 0x180017, null, $this),
new Location\Npc\Zora("King Zora", 0xEE1C3, null, $this),
new Location\Standing("Piece of Heart (Thieves' Forest Hideout)", 0x180000, null, $this),
new Location\Standing("Piece of Heart (Lumberjack Tree)", 0x180001, null, $this),
new Location\Standing("Piece of Heart (south of Haunted Grove)", 0x180003, null, $this),
new Location\Standing("Piece of Heart (Graveyard)", 0x180004, null, $this),
new Location\Standing("Piece of Heart (Desert - northeast corner)", 0x180005, null, $this),
new Location\Npc("[cave-050] cave southwest of Lake Hylia - generous guy", 0x180010, null, $this),
new Location\Dash("Library", 0x180012, null, $this),
new Location\Standing("Mushroom", 0x180013, null, $this),
new Location\Npc\Witch("Witch", 0x180014, null, $this),
new Location\Standing("Piece of Heart (Maze Race)", 0x180142, null, $this),
new Location\Standing("Piece of Heart (Desert - west side)", 0x180143, null, $this),
new Location\Standing("Piece of Heart (Lake Hylia)", 0x180144, null, $this),
new Location\Standing("Piece of Heart (Dam)", 0x180145, null, $this),
new Location\Standing("Piece of Heart (Zora's River)", 0x180149, null, $this),
new Location\Dig\HauntedGrove("Haunted Grove item", 0x18014A, null, $this),
new Location\Chest("Waterfall Fairy - Left", 0xE9B0, null, $this),
new Location\Chest("Waterfall Fairy - Right", 0xE9D1, null, $this),
]);
}
/**
* Set Locations to have Items like the vanilla game.
*
* @return $this
*/
public function setVanilla() {
$this->locations["Altar"]->setItem(Item::get('MasterSword'));
$this->locations["Uncle"]->setItem(Item::get('L1SwordAndShield'));
$this->locations["[cave-034] Hyrule Castle secret entrance"]->setItem(Item::get('Lamp'));
$this->locations["[cave-018] Graveyard - top right grave"]->setItem(Item::get('Cape'));
$this->locations["[cave-047] Dam"]->setItem(Item::get('ThreeBombs'));
$this->locations["[cave-040] Link's House"]->setItem(Item::get('Lamp'));
$this->locations["[cave-031] Tavern"]->setItem(Item::get('Bottle'));
$this->locations["[cave-026] chicken house"]->setItem(Item::get('TenArrows'));
$this->locations["[cave-044] Aginah's cave"]->setItem(Item::get('PieceOfHeart'));
$this->locations["[cave-035] Sahasrahla's Hut [left chest]"]->setItem(Item::get('FiftyRupees'));
$this->locations["[cave-035] Sahasrahla's Hut [center chest]"]->setItem(Item::get('ThreeBombs'));
$this->locations["[cave-035] Sahasrahla's Hut [right chest]"]->setItem(Item::get('FiftyRupees'));
$this->locations["[cave-021] Kakariko well [top chest]"]->setItem(Item::get('PieceOfHeart'));
$this->locations["[cave-021] Kakariko well [left chest row of 3]"]->setItem(Item::get('TwentyRupees'));
$this->locations["[cave-021] Kakariko well [center chest row of 3]"]->setItem(Item::get('TwentyRupees'));
$this->locations["[cave-021] Kakariko well [right chest row of 3]"]->setItem(Item::get('TwentyRupees'));
$this->locations["[cave-021] Kakariko well [bottom chest]"]->setItem(Item::get('ThreeBombs'));
$this->locations["[cave-022-B1] Thief's hut [top chest]"]->setItem(Item::get('PieceOfHeart'));
$this->locations["[cave-022-B1] Thief's hut [top left chest]"]->setItem(Item::get('TwentyRupees'));
$this->locations["[cave-022-B1] Thief's hut [top right chest]"]->setItem(Item::get('TwentyRupees'));
$this->locations["[cave-022-B1] Thief's hut [bottom left chest]"]->setItem(Item::get('TwentyRupees'));
$this->locations["[cave-022-B1] Thief's hut [bottom right chest]"]->setItem(Item::get('TwentyRupees'));
$this->locations["[cave-016] cave under rocks west of Santuary"]->setItem(Item::get('PieceOfHeart'));
$this->locations["[cave-050] cave southwest of Lake Hylia [bottom left chest]"]->setItem(Item::get('ThreeBombs'));
$this->locations["[cave-050] cave southwest of Lake Hylia [top left chest]"]->setItem(Item::get('TwentyRupees'));
$this->locations["[cave-050] cave southwest of Lake Hylia [top right chest]"]->setItem(Item::get('TwentyRupees'));
$this->locations["[cave-050] cave southwest of Lake Hylia [bottom right chest]"]->setItem(Item::get('TenArrows'));
$this->locations["[cave-051] Ice Cave"]->setItem(Item::get('IceRod'));
$this->locations["Bottle Vendor"]->setItem(Item::get('Bottle'));
$this->locations["Sahasrahla"]->setItem(Item::get('PegasusBoots'));
$this->locations["Magic Bat"]->setItem(Item::get('HalfMagic')); // @TODO: perhaps use 0xFF here
$this->locations["Sick Kid"]->setItem(Item::get('BugCatchingNet'));
$this->locations["Hobo"]->setItem(Item::get('Bottle'));
$this->locations["Bombos Tablet"]->setItem(Item::get('Bombos'));
$this->locations["King Zora"]->setItem(Item::get('Flippers'));
$this->locations["Piece of Heart (Thieves' Forest Hideout)"]->setItem(Item::get('PieceOfHeart'));
$this->locations["Piece of Heart (Lumberjack Tree)"]->setItem(Item::get('PieceOfHeart'));
$this->locations["Piece of Heart (south of Haunted Grove)"]->setItem(Item::get('PieceOfHeart'));
$this->locations["Piece of Heart (Graveyard)"]->setItem(Item::get('PieceOfHeart'));
$this->locations["Piece of Heart (Desert - northeast corner)"]->setItem(Item::get('PieceOfHeart'));
$this->locations["[cave-050] cave southwest of Lake Hylia - generous guy"]->setItem(Item::get('ThreeHundredRupees'));
$this->locations["Library"]->setItem(Item::get('BookOfMudora'));
$this->locations["Mushroom"]->setItem(Item::get('Mushroom'));
$this->locations["Witch"]->setItem(Item::get('Powder'));
$this->locations["Piece of Heart (Maze Race)"]->setItem(Item::get('PieceOfHeart'));
$this->locations["Piece of Heart (Desert - west side)"]->setItem(Item::get('PieceOfHeart'));
$this->locations["Piece of Heart (Lake Hylia)"]->setItem(Item::get('PieceOfHeart'));
$this->locations["Piece of Heart (Dam)"]->setItem(Item::get('PieceOfHeart'));
$this->locations["Piece of Heart (Zora's River)"]->setItem(Item::get('PieceOfHeart'));
$this->locations["Haunted Grove item"]->setItem(Item::get('OcarinaInactive'));
$this->locations["Waterfall Fairy - Left"]->setItem(Item::get('RedShield'));
$this->locations["Waterfall Fairy - Right"]->setItem(Item::get('RedBoomerang'));
return $this;
}
/**
* Initalize the requirements for Entry and Completetion of the Region as well as access to all Locations contained
* within for No Major Glitches
*
* @return $this
*/
public function initNoMajorGlitches() {
$this->locations["Altar"]->setRequirements(function($locations, $items) {
return $items->has('PendantOfPower')
&& $items->has('PendantOfWisdom')
&& $items->has('PendantOfCourage');
});
$this->locations["[cave-018] Graveyard - top right grave"]->setRequirements(function($locations, $items) {
return $items->has('PegasusBoots') && ($items->canLiftDarkRocks()
|| ($items->has('MagicMirror') && $items->has('MoonPearl')
&& $this->world->getRegion('North West Dark World')->canEnter($locations, $items)));
});
$this->locations["[cave-016] cave under rocks west of Santuary"]->setRequirements(function($locations, $items) {
return $items->has('PegasusBoots');
});
$this->locations["Sahasrahla"]->setRequirements(function($locations, $items) {
return $items->has('PendantOfCourage');
});
$this->locations["Magic Bat"]->setRequirements(function($locations, $items) {
return $items->has('Powder')
&& ($items->has('Hammer')
|| ($items->has('MoonPearl') && $items->has('MagicMirror') && $items->canLiftDarkRocks()));
});
$this->locations["Sick Kid"]->setRequirements(function($locations, $items) {
return $items->hasABottle();
});
$this->locations["Hobo"]->setRequirements(function($locations, $items) {
return $items->has('Flippers');
});
$this->locations["Bombos Tablet"]->setRequirements(function($locations, $items) {
return $items->has('BookOfMudora') && ($items->hasUpgradedSword()
|| (config('game-mode') == 'swordless' && $items->has('Hammer')))
&& $items->has('MagicMirror') && $this->world->getRegion('South Dark World')->canEnter($locations, $items);
});
$this->locations["King Zora"]->setRequirements(function($locations, $items) {
return $items->canLiftRocks() || $items->has('Flippers');
});
$this->locations["Piece of Heart (Lumberjack Tree)"]->setRequirements(function($locations, $items) {
return $items->has('DefeatAgahnim') && $items->has('PegasusBoots');
});
$this->locations["Piece of Heart (south of Haunted Grove)"]->setRequirements(function($locations, $items) {
return $items->has('MagicMirror') && $this->world->getRegion('South Dark World')->canEnter($locations, $items);
});
$this->locations["Piece of Heart (Graveyard)"]->setRequirements(function($locations, $items) {
return $items->has('MagicMirror') && $items->has('MoonPearl')
&& $this->world->getRegion('North West Dark World')->canEnter($locations, $items);
});
$this->locations["Piece of Heart (Desert - northeast corner)"]->setRequirements(function($locations, $items) {
return $items->canFly() && $items->canLiftDarkRocks() && $items->has('MagicMirror');
});
$this->locations["Library"]->setRequirements(function($locations, $items) {
return $items->has('PegasusBoots');
});
$this->locations["Witch"]->setRequirements(function($locations, $items) {
return $items->has('Mushroom');
});
$this->locations["Piece of Heart (Desert - west side)"]->setRequirements(function($locations, $items) {
return $this->world->getRegion('Desert Palace')->canEnter($locations, $items);
});
$this->locations["Piece of Heart (Lake Hylia)"]->setRequirements(function($locations, $items) {
return $items->has('Flippers') && $items->has('MoonPearl') && $items->has('MagicMirror')
&& ($this->world->getRegion('South Dark World')->canEnter($locations, $items)
|| $this->world->getRegion('North East Dark World')->canEnter($locations, $items));
});
$this->locations["Piece of Heart (Zora's River)"]->setRequirements(function($locations, $items) {
return $items->has('Flippers');
});
$this->locations["Haunted Grove item"]->setRequirements(function($locations, $items) {
return $items->has('Shovel');
});
$this->locations["Waterfall Fairy - Left"]->setRequirements(function($locations, $items) {
return $items->has('Flippers');
});
$this->locations["Waterfall Fairy - Right"]->setRequirements(function($locations, $items) {
return $items->has('Flippers');
});
return $this;
}
/**
* Initalize the requirements for Entry and Completetion of the Region as well as access to all Locations contained
* within for MajorGlitches Mode
*
* @return $this
*/
public function initMajorGlitches() {
$this->initOverworldGlitches();
$this->locations["[cave-018] Graveyard - top right grave"]->setRequirements(function($locations, $items) {
return $items->has('PegasusBoots') && ($items->canLiftDarkRocks()
|| ($items->has('MagicMirror') && $items->glitchedLinkInDarkWorld()));
});
$this->locations["Magic Bat"]->setRequirements(function($locations, $items) {
return $items->has('Powder')
&& ($items->has('Hammer')
|| $items->has('PegasusBoots')
|| $items->has('MagicMirror'));
});
$this->locations["Piece of Heart (Graveyard)"]->setRequirements(function($locations, $items) {
return $items->has('PegasusBoots')
|| ($items->has('MagicMirror') && $items->glitchedLinkInDarkWorld());
});
$this->locations["Piece of Heart (Lake Hylia)"]->setRequirements(function($locations, $items) {
return $items->has('PegasusBoots')
|| ($items->has('Flippers') && $items->has('MagicMirror')
&& ($items->glitchedLinkInDarkWorld()
|| $this->world->getRegion('North East Dark World')->canEnter($locations, $items)));
});
return $this;
}
/**
* Initalize the requirements for Entry and Completetion of the Region as well as access to all Locations contained
* within for Overworld Glitches Mode
*
* @return $this
*/
public function initOverworldGlitches() {
$this->initNoMajorGlitches();
$this->locations["[cave-018] Graveyard - top right grave"]->setRequirements(function($locations, $items) {
return $items->has('PegasusBoots') && ($items->canLiftDarkRocks()
|| ($items->has('MagicMirror') && $items->has('MoonPearl')));
});
$this->locations["Magic Bat"]->setRequirements(function($locations, $items) {
return $items->has('Powder')
&& ($items->has('Hammer')
|| $items->has('PegasusBoots')
|| ($items->has('MoonPearl') && $items->has('MagicMirror') && $items->canLiftDarkRocks()
&& $this->world->getRegion('North West Dark World')->canEnter($locations, $items)));
});
$this->locations["Hobo"]->setRequirements(function($locations, $items) {
return true;
});
$this->locations["Bombos Tablet"]->setRequirements(function($locations, $items) {
return $items->has('BookOfMudora') && ($items->hasUpgradedSword()
|| (config('game-mode') == 'swordless' && $items->has('Hammer')))
&& ($items->has('PegasusBoots')
|| ($items->has('MagicMirror') && $this->world->getRegion('South Dark World')->canEnter($locations, $items)));
});
$this->locations["King Zora"]->setRequirements(function($locations, $items) {
return true;
});
$this->locations["Piece of Heart (south of Haunted Grove)"]->setRequirements(function($locations, $items) {
return $items->has('PegasusBoots')
|| ($items->has('MagicMirror') && $this->world->getRegion('South Dark World')->canEnter($locations, $items));
});
$this->locations["Piece of Heart (Graveyard)"]->setRequirements(function($locations, $items) {
return $items->has('PegasusBoots')
|| ($items->has('MagicMirror') && $items->has('MoonPearl')
&& $this->world->getRegion('North West Dark World')->canEnter($locations, $items));
});
$this->locations["Piece of Heart (Desert - northeast corner)"]->setRequirements(function($locations, $items) {
return $items->canLiftRocks()
&& ($items->has('PegasusBoots')
|| ($items->has('MagicMirror') && $this->world->getRegion('Mire')->canEnter($locations, $items)));
});
$this->locations["Piece of Heart (Lake Hylia)"]->setRequirements(function($locations, $items) {
return $items->has('PegasusBoots')
|| ($items->has('Flippers') && $items->has('MagicMirror')
&& (($items->has('MoonPearl') && $this->world->getRegion('South Dark World')->canEnter($locations, $items))
|| $this->world->getRegion('North East Dark World')->canEnter($locations, $items)));
});
$this->locations["Piece of Heart (Zora's River)"]->setRequirements(function($locations, $items) {
return $items->has('Flippers')
|| ($items->has('PegasusBoots') && $items->has('MoonPearl'));
});
$this->locations["Waterfall Fairy - Left"]->setRequirements(function($locations, $items) {
return $items->has('Flippers') || $items->has('MoonPearl');
});
$this->locations["Waterfall Fairy - Right"]->setRequirements(function($locations, $items) {
return $items->has('Flippers') || $items->has('MoonPearl');
});
return $this;
}
}
| true |
481653cb4906c9e6d85c9afc587ce3a71661f7b2 | PHP | SuPair/Epreseller | /app/Http/Middleware/CheckUserStatus.php | UTF-8 | 954 | 2.640625 | 3 | [] | no_license | <?php
namespace App\Http\Middleware;
use Carbon\Carbon;
use Closure;
class CheckUserStatus
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if($this->checkStatus($request->user())){
if($this->checkExpire($request->user())){
return $next($request);
}else{
return $this->fail('1008');
}
}else{
return $this->fail('1006');
}
}
public function checkStatus($user){
return $user->status == 0;
}
public function checkExpire($user){
return $user->expires_at > Carbon::now();
}
public function fail($code){
return response()->json([
'code' => $code,
'msg' => config('errorcode.msg.'.$code)
]);
}
}
| true |
f50ebdd6f35fde4ea8000bc0c87b3c4dfd8d6f6e | PHP | HopStudios/Hop-Alerts-Fetch-Craft | /hopalertsfetch/helpers/Main_Helper.php | UTF-8 | 1,918 | 2.734375 | 3 | [] | no_license | <?php
namespace Craft;
class Main_Helper
{
public static function createAlertEntry($sectionHandle, $author_id, $title, $type, $type_handle, $custom_id, $custom_id_handle, $content, $content_handle, $datetime = NULL)
{
$entry = new EntryModel();
$entry->sectionId = craft()->sections->getSectionByHandle($sectionHandle)->id;
$postDate = new DateTime();
if ($datetime)
{
$postDate = $datetime;
}
$entry->enabled = TRUE;
$entry->authorId = $author_id;
$entry->postDate = $postDate;
$entry->getContent()->title = $title;
$entry->getContent()->{$type_handle} = $type;
$entry->getContent()->{$custom_id_handle} = $custom_id;
$entry->getContent()->{$content_handle} = $content;
if (craft()->entries->saveEntry($entry))
{
}
else
{
HopAlertsFetchPlugin::log('Tried to create an Alert entry but saving into DB failed: '.$entry->getErrors() , LogLevel::Error);
}
}
public static function createEntry($sectionHandle, $author_id, $title, $fields, $timestamp = NULL)
{
if (!is_array($fields))
{
throw new Exception('Main_Helper::createEntry() - 4th parameter must be an array.');
}
$entry = new EntryModel();
$entry->sectionId = craft()->sections->getSectionByHandle($sectionHandle)->id;
$postDate = new DateTime();
if ($timestamp)
{
$postDate->setTimestamp($timestamp);
}
$postDate = DateTime::createFromString($postDate, craft()->timezone);
$entry->enabled = TRUE;
$entry->authorId = $author_id;
$entry->postDate = $postDate;
$entry->getContent()->title = $title;
foreach($fields as $field_name => $field_value)
{
$entry->getContent()->{$field_name} = $field_value;
}
if (craft()->entries->saveEntry($entry))
{
}
else
{
HopAlertsFetchPlugin::log('Tried to create an Alert entry but saving into DB failed: '.$entry->getErrors() , LogLevel::Error);
}
}
} | true |
10ae57699e932c0e542ec55576093b02950e8399 | PHP | nmiannay/leaf | /src/Leaf/Nodes/Tag/Doctype.class.php | UTF-8 | 338 | 2.734375 | 3 | [] | no_license | <?php
namespace Leaf\Nodes\Tag;
class Doctype extends Common
{
protected $doctype;
public function __construct($tagName, $textContent = null)
{
$this->doctype = 'html';
parent::__construct('doctype');
}
public static function render(\Leaf\Node $Node)
{
return (sprintf("<!DOCTYPE %s>", $Node->nodeValue));
}
} | true |
ca99ab501f11890a2f2aa6cfcd42913938f6f82e | PHP | manuth/TemPHPlate | /System/Web/Forms/MenuItemGroup.php | UTF-8 | 1,007 | 2.796875 | 3 | [
"Apache-2.0"
] | permissive | <?php
/**
* @author Manuel Thalmann <m@nuth.ch>
* @license Apache-2.0
*/
namespace System\Web\Forms;
use System\Collections\{
ArrayList
};
{
/**
* Represents a menu-item that contains a set of menu-items.
*
* @property-read ArrayList $Items
* Gets the items of the menu-item-group.
*/
class MenuItemGroup extends MenuItem
{
/**
* The items of the menu-item-group.
*
* @var ArrayList
*/
private $items;
/**
* Initializes a new instance of the `MenuItemGroup` class.
*/
public function MenuItemGroup()
{
$this->items = new ArrayList();
}
/**
* @ignore
*/
public function getItems() : ArrayList
{
return $this->items;
}
}
}
?> | true |
ec42157664325df378a188d508a876e774588e54 | PHP | Deadheded/Extended-Ravencoin-Metadata-Specification | /Proof of Concept/ReadValidateTest.php | UTF-8 | 4,791 | 2.859375 | 3 | [
"MIT"
] | permissive | <?php
/*
The following is an example of validating a set of Meta Data, using schema files (where applicable).
Scenarios
Normal operation:
This test will validate all fields in metadata.json, without
any errors, or indicate that some unknown fields were detected.
Invalid Meta Data:
When metadata.json is edited to utilze v0.2 of the
asset_data_schema_o.2.json file, the asset_metadata will be invalidated and not
display.
===============================================================================
MIT License
Copyright (c) 2019 RealBokito
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
// Read the Meta Data
$json_data = file_get_contents('metadata.json');
// Decode the Meta Data to associative arrays
$data = json_decode($json_data,true);
// Loop through each Meta Data object
foreach($data['metadata'] as $obj){
//echo "Using schema: ".$obj['schema']." ";
//echo "version: ".$obj['version']."\r\n";
echo "Checking ".$obj['schema']." meta data.....\r\n";
// Validate the Meta Data
$ret = validateMetaData($obj);
if($ret){
echo $obj['schema']." meta data is valid\r\n\r\n";
//var_dump($obj);
}else{
echo $obj['schema']." meta data invalid\r\n\r\n";
}
}
function validateMetaData($data){
// Put together the link the to schema file used for the Meta Data
$schema = $data['schema'].'_'.$data['version'].'.json';
// Validate if the Meta Data exists.
// It's up to the software engineer to decide if the non existence of a Meta Data Schema file results into a true or false validation
if(file_exists('schemas/'.$schema)){
// Read the Schema file and decode into associative arrays
$schema = file_get_contents('schemas/'.$schema);
$schema = json_decode($schema,true);
// Get the fieldnames from the Schema by abstracting the array keys
$ret = validate($data,$schema);
if(!$ret)
return false;
}else{
// The software engineer will have to decide how it's program will behave when there is nog Schema file found
echo "Schema file not found.\r\n";
echo "Assume ";
}
// All is good. Meta Data is valid
return true;
}
function validate($data,$schema,$level=1){
echo "Level: ".$level."...\r\n";
// Get the fieldnames from the Schema by abstracting the array keys
$schemaFields = array_keys($schema);
// Loop through all the fields
foreach($schemaFields as $schemaField){
if($schemaField == "schema" || $schemaField == "version")// Exlude the schema and version fields
continue;
// Check if a field is SET
if(isset($data[$schemaField]) && !is_array($data[$schemaField])){
echo $schemaField." is SET\r\n";
}elseif(isset($data[$schemaField]) && is_array($data[$schemaField])){
$level++;
$ret = validate($data[$schemaField],$schema[$schemaField]['fields'],$level);
if(!$ret)
return false;
$level--;
echo "Back at level: ".$level."\r\n";
}else{
// Check if the NOT SET field is required
if($schema[$schemaField]['required']){
// Invalidate the Meta Data because at least 1 field is missing
echo "Schema validation error: ".$schemaField."-field is required...\r\n";
return false;
}
// The current field is missing, but not required
echo $schemaField." is NOT set\r\n";
}
}
// Do one final check for fields described in the metadata but NOT in the schema and mark them as Unknown Field(s)
$dataFields = array_keys($data); // Get keys from the metadata
$unknownFields = array_diff($dataFields, $schemaFields); // Calculate the differences between the metadata keys and schema keys
// If any metadata keys are not found in the schema keys array, mark as unknown...
if($unknownFields){
foreach($unknownFields as $unknownField){
echo $unknownField." is an unknown field.\r\n";
}
}
// If we get here, assume everything is OK
return true;
}
?>
| true |
ee0ec19c6be59db4894c978d5305ec2f5c93ef7b | PHP | podlove/podlove-subscribe-button-wp-plugin | /model/button.php | UTF-8 | 5,848 | 2.828125 | 3 | [
"MIT"
] | permissive | <?php
namespace PodloveSubscribeButton\Model;
class Button extends Base {
public static $properties = array(
// $property => $default value
'size' => 'big',
'color' => '#599677',
'autowidth' => 'on',
'style' => 'filled',
'format' => 'rectangle',
'hide' => 'false'
// Note: the fields 'language' and 'json-data' cannot be set here (No function call allowed within class variables)
);
public static $style = array(
'filled' => 'Filled',
'outline' => 'Outline',
'frameless' => 'Frameless'
);
public static $format = array(
'rectangle' => 'Rectangle',
'square' => 'Square',
'cover' => 'Cover'
);
public static $width = array(
'on' => 'Yes',
'off' => 'No'
);
public static $size = array(
'small' => 'Small',
'medium' => 'Medium',
'big' => 'Big'
);
/**
* Fetches a Button or Network Button with a specific name
* @param string $name
* @return object||FALSE
*/
public static function get_button_by_name($name) {
if ( $button = \PodloveSubscribeButton\Model\Button::find_one_by_property('name', $name) ) {
return $button;
}
if ( $network_button = \PodloveSubscribeButton\Model\NetworkButton::find_one_by_property('name', $name) ) {
$network_button->id = $network_button->id . 'N';
return $network_button;
}
return false;
}
/**
* Returns either global buttons settings or the default settings
* @param array
* @return array
*/
public static function get_global_setting_with_fallback( $settings=array() ) {
foreach (self::$properties as $property => $default) {
$settings[$property] = ( get_option('podlove_subscribe_button_default_' . $property) ? get_option('podlove_subscribe_button_default_' . $property) : $default );
}
return $settings;
}
/**
* Gathers all information and renders the Subscribe button.
* @param string $size
* @param string $autowidth
* @param string $style
* @param string $format
* @param string $color
* @param boolean $hide
* @return string
*/
public function render( $size='big', $autowidth='on', $style='filled', $format='rectangle', $color='#599677', $hide = false, $buttonid = false, $language='en' ) {
$button_styling = array_merge(
$this->get_button_styling($size, $autowidth, $style, $format, $color),
array(
'hide' => $hide,
'language' => $language
)
);
return $this->provide_button_html(
array(
'title' => sanitize_text_field($this->title),
'subtitle' => sanitize_text_field($this->subtitle),
'description' => sanitize_textarea_field($this->description),
'cover' => sanitize_text_field($this->cover),
'feeds' => $this->get_feeds_as_array($this->feeds)
), $button_styling );
}
/**
* Provides the feed as an array in the required format
* @return array
*/
private function get_feeds_as_array( $feeds=array() ) {
$returnedFeeds = array();
if (! $feeds)
return $returnedFeeds;
foreach ($feeds as $feed) {
if ( isset(\PodloveSubscribeButton\MediaTypes::$audio[$feed['format']]['extension']) ) {
$new_feed = array(
'type' => 'audio',
'format' => \PodloveSubscribeButton\MediaTypes::$audio[$feed['format']]['extension'],
'url' => $feed['url'],
'variant' => 'high'
);
if ( isset($feed['itunesfeedid']) && $feed['itunesfeedid'] > 0 )
$new_feed['directory-url-itunes'] = "https://itunes.apple.com/podcast/id" . $feed['itunesfeedid'];
$returnedFeeds[] = $new_feed;
}
}
return $returnedFeeds;
}
/**
* Provides the HTML source of the Subscribe Button
* @param array $podcast_data
* @param array $button_styling
* @param string $data_attributes
* @return string
*/
private function provide_button_html($podcast_data, $button_styling, $data_attributes="") {
// Create data attributes for Button
foreach ($button_styling as $attribute => $value) {
$data_attributes .= 'data-' . $attribute . '="' . $value . '" ';
}
return"
<script>
podcastData".$this->id . " = ".json_encode($podcast_data)."
</script>
<script
class=\"podlove-subscribe-button\"
src=\"https://cdn.podlove.org/subscribe-button/javascripts/app.js\" " . $data_attributes . ">
</script>
";
}
/**
* Returns an array with either the set or default values
* @param string $size
* @param string $autowidth
* @param string $style
* @param string $format
* @param string $color
* @return array
*/
public function get_button_styling($size, $autowidth, $style, $format, $color) {
return array(
// $attribute => $value
'size' => ( $size == 'default' ? get_option('podlove_subscribe_button_default_size', $size) : $size )
. self::interpret_autowidth_attribute($autowidth),
'style' => ( $style == 'default' ? get_option('podlove_subscribe_button_default_style', $style) : $style ),
'format' => ( $format == 'default' ? get_option('podlove_subscribe_button_default_format', $format) : $format ),
'color' => ( isset($color) ? $color : get_option('podlove_subscribe_button_default_color', $color) ),
'json-data' => 'podcastData' . $this->id
);
}
/**
* Helper function to interpret the given $autowidth value correctly
* @param string $autowidth
* @return string
*/
private static function interpret_autowidth_attribute($autowidth) {
if ( $autowidth == 'default' && get_option('podlove_subscribe_button_default_autowidth') !== 'on' )
return '';
if ( $autowidth !== 'default' && $autowidth !== 'on' )
return '';
return ' auto';
}
}
Button::property( 'id', 'INT NOT NULL AUTO_INCREMENT PRIMARY KEY' );
Button::property( 'name', 'VARCHAR(255)' );
Button::property( 'title', 'VARCHAR(255)' );
Button::property( 'subtitle', 'VARCHAR(255)' );
Button::property( 'description', 'TEXT' );
Button::property( 'cover', 'VARCHAR(255)' );
Button::property( 'feeds', 'TEXT' );
| true |
35af08616f86ae984ef30dd16063638958c1bf78 | PHP | Sistemas-2014-I/Miski | /MiskiCode/tests/traits/MakePisoTrait.php | UTF-8 | 1,100 | 2.671875 | 3 | [
"MIT"
] | permissive | <?php
use Faker\Factory as Faker;
use App\Models\Piso;
use App\Repositories\PisoRepository;
trait MakePisoTrait
{
/**
* Create fake instance of Piso and save it in database
*
* @param array $pisoFields
* @return Piso
*/
public function makePiso($pisoFields = [])
{
/** @var PisoRepository $pisoRepo */
$pisoRepo = App::make(PisoRepository::class);
$theme = $this->fakePisoData($pisoFields);
return $pisoRepo->create($theme);
}
/**
* Get fake instance of Piso
*
* @param array $pisoFields
* @return Piso
*/
public function fakePiso($pisoFields = [])
{
return new Piso($this->fakePisoData($pisoFields));
}
/**
* Get fake data of Piso
*
* @param array $postFields
* @return array
*/
public function fakePisoData($pisoFields = [])
{
$fake = Faker::create();
return array_merge([
'cod' => $fake->word,
'descripcion' => $fake->word,
'activo' => $fake->word
], $pisoFields);
}
}
| true |
4df60c28792849d6e5f238bdb48edbacf9d51650 | PHP | narasingh/news-bot | /bot.php | UTF-8 | 2,176 | 2.609375 | 3 | [] | no_license | <?php
header('content-type: application/json; charset=utf-8');
header("Access-Control-Allow-Origin: *");
$postdata = json_decode(file_get_contents("php://input"), true);
$action = '';
$data = $postdata['item'];
$message = $data['message']['message'];
$userName = $data['message']['from']['name'];
$userId = $data['message']['id'];
function getHelp() {
$usages = 'Usage: \n';
$usages .= '/timely print this help message \n';
$usages .= '/timely :week show the clarity entered by the user for the current week \n';
$usages .= '/timely :day show the clarity entered by the user for the current week \n';
$usages .= '/timely :project-id :hours-minutes :message submit clarity for the day \n';
$usages .= '/timely :date :project-id :hours-minutes :message submit clarity for particular date \n';
return array(
'color' => 'gray',
'message' => $usages
);
}
function afterInsert() {
global $userName;
global $userId;
$description = $userName. ' '. ' has submitted his timesheet';
$response = array(
"color" => "green",
"card" => array(
"style" => "link",
"url" => 'http://i0.kym-cdn.com/photos/images/newsfeed/000/131/786/tumblr_ljkeuyjp1a1qafrh6.gif',
"id" => $userId,
"title" => 'Timely card layout',
"description" => $description,
"date" => time(),
"thumbnail" => array(
"url" => 'https://c.martech.zone/wp-content/uploads/2010/06/example-logo.png',
"url@2x" => 'https://c.martech.zone/wp-content/uploads/2010/06/example-logo.png',
"width" => 1193,
"height" => 564
)
),
"message" => "test",
"message_format" => "html"
);
return $response;
}
//this method is only for hipchat bot
function effortByChatBot($type) {
$response = array();
switch($type) {
default:
$response = afterInsert();
break;
}
return json_encode($response, JSON_FORCE_OBJECT);
}
try{
echo effortByChatBot('help');
}catch(Exception $e) {
echo 'Caught Exception, ',$e->getMessage(),'\n';
}
?>
| true |
9fbee14beb2025563ad4cbca8014343981e772fc | PHP | KubqoA/sacharidovejednotky | /app/Http/Controllers/UserController.php | UTF-8 | 2,043 | 2.84375 | 3 | [] | no_license | <?php
namespace App\Http\Controllers;
use App\Entry;
use App\Http\Requests\UpdateUser;
use Auth;
use Carbon\Carbon;
use Carbon\CarbonInterval;
use DatePeriod;
class UserController extends Controller
{
/**
* Show the form for editing the specified resource.
*
* @return \Illuminate\Http\Response
*/
public function edit()
{
return view('user.settings', ['user' => Auth::user()]);
}
/**
* Update the specified resource in storage.
*
* @param UpdateUser $request
* @return \Illuminate\Http\Response
*/
public function update(UpdateUser $request)
{
Auth::user()->update(array_filter($request->validated()));
return redirect(route('user.edit'));
}
public function summary()
{
$entries = Entry::whereDate('created_at', '>', now()->startOfDay()->subWeek())->get();
$dates = $this->date_range(now()->subWeek(),now());
return view('user.summary', compact('entries', 'dates'));
}
/**
* Compute a range between two dates, and generate
* a plain array of Carbon objects of each day in it.
*
* @param Carbon $from
* @param Carbon $to
* @param bool $inclusive
* @return array|null
*
* @author Tristan Jahier
*/
private function date_range(Carbon $from, Carbon $to, $inclusive = true)
{
if ($from->gt($to)) {
return null;
}
// Clone the date objects to avoid issues, then reset their time
$from = $from->copy()->startOfDay();
$to = $to->copy()->startOfDay();
// Include the end date in the range
if ($inclusive) {
$to->addDay();
}
$step = CarbonInterval::day();
$period = new DatePeriod($from, $step, $to);
// Convert the DatePeriod into a plain array of Carbon objects
$range = [];
foreach ($period as $day) {
$range[] = new Carbon($day);
}
return ! empty($range) ? $range : null;
}
}
| true |
ce8a5803690ec71c3274000a37e40599e08343a0 | PHP | ikhwan12/nihao-news-theme | /plugins/theia-post-slider/TpsNavigationBar.php | UTF-8 | 5,166 | 2.84375 | 3 | [
"Apache-2.0"
] | permissive | <?php
/*
* Copyright 2012-2018, Theia Post Slider, WeCodePixels, http://wecodepixels.com
*/
class TpsNavigationBar {
// Get HTML for a navigation bar.
public static function get_navigation_bar( $options ) {
global $post;
$defaults = array(
'currentSlide' => null,
'totalSlides' => null,
'prevPostId' => null,
'nextPostId' => null,
'prevPostUrl' => null,
'nextPostUrl' => null,
'id' => null,
'class' => array(),
'style' => null,
'title' => null
);
$options = array_merge( $defaults, $options );
if ( ! is_array( $options['class'] ) ) {
$options['class'] = array( $options['class'] );
}
if ( $options['totalSlides'] == 1 && in_array( TpsOptions::get( 'button_behaviour', 'tps_nav' ), array( 'standard', 'loop' ) ) ) {
return '';
}
// Get text
if ( $options['totalSlides'] == 1 ) {
$text = '';
} else {
$text = TpsOptions::get( 'navigation_text' );
$text = str_replace( '%{currentSlide}', $options['currentSlide'], $text );
$text = str_replace( '%{totalSlides}', $options['totalSlides'], $text );
}
// Get button URLs
$prev = TpsNavigationBar::get_navigation_barButton( $options, false );
$next = TpsNavigationBar::get_navigation_barButton( $options, true );
// Title
if ( ! $options['title'] ) {
$options['title'] = '<span class="_helper">' . TpsOptions::get( 'helper_text' ) . '</span>';
}
// Classes
$options['class'][] = '_slide_number_' . ( $options['currentSlide'] - 1 );
if ( $post && TpsPostOptions::get( $post->ID, 'nav_hide_on_first_slide' ) ) {
$options['class'][] = '_hide_on_first_slide';
}
// Final HTML
$class = array( 'theiaPostSlider_nav' );
$class[] = '_' . TpsOptions::get( 'nav_horizontal_position' );
if ( TpsOptions::get( 'theme_type' ) == 'font' ) {
$class[] = 'fontTheme';
}
foreach ( $options['class'] as $c ) {
$class[] = $c;
}
$html =
'<div' . ( $options['id'] !== null ? ' id="' . $options['id'] . '"' : '' ) . ( $options['style'] !== null ? ' style="' . $options['style'] . '"' : '' ) . ' class="' . implode( $class, ' ' ) . '">' .
'<div class="_buttons">' . $prev . '<span class="_text">' . $text . '</span>' . $next . '</div>' .
'<div class="_title">' . $options['title'] . '</div>' .
'</div>';
return $html;
}
/*
* Get a button for a navigation bar.
* @param direction boolean False = prev; True = next;
*/
public static function get_navigation_barButton( $options, $direction ) {
global $page, $pages;
$direction_name = $direction ? 'next' : 'prev';
$url = TpsMisc::get_post_page_url( $options['currentSlide'] + ( $direction ? 1 : - 1 ) );
$left_text = null;
$right_text = null;
// Functionality: Last Slide's Next Goes to the First Slide and vice-versa.
// Used the URLs directly compared to the previous version.
if ( ! $url && TpsOptions::get( 'button_behaviour', 'tps_nav' ) == 'loop' ) {
if ( $direction_name == 'next' ) {
$url = TpsMisc::get_post_page_url( 1 );
} else {
$url = TpsMisc::get_post_page_url( count( $pages ) );
}
}
// Check if there isn't another page but there is another post.
$url_is_another_post = ! $url && $options[ $direction_name . 'PostUrl' ];
if ( $url_is_another_post && TpsOptions::get( 'button_behaviour', 'tps_nav' ) == 'post' ) {
$url = $options[ $direction_name . 'PostUrl' ];
}
// Check what text we should display on the buttons.
if ( TpsOptions::get( 'button_behaviour' ) === 'post' && ( ( $direction == false && $page == 1 ) || ( $direction == true && $page == count( $pages ) ) ) ) {
$button_text = TpsOptions::get( $direction_name . '_text_post' );
} else {
$button_text = TpsOptions::get( $direction_name . '_text' );
}
switch ( TpsOptions::get( 'theme_type' ) ) {
case 'font':
$direction_name_for_icons = ($direction xor is_rtl()) ? 'next' : 'prev';
$text = $direction_name_for_icons == 'next' ? TpsOptions::get_font_icon( 'right' ) : TpsOptions::get_font_icon( 'left' );
$width = 0;
if ( $direction_name == 'next' ) {
$left_text = $button_text;
} else {
$right_text = $button_text;
}
break;
case 'classic':
$text = $button_text;
$left_text = '';
$right_text = '';
if ( $url_is_another_post ) {
$width = TpsOptions::get( 'button_width_post' );
} else {
$width = TpsOptions::get( 'button_width' );
}
break;
default:
return '';
}
$style = $width == 0 ? '' : 'style="width: ' . $width . 'px"';
// if(! is_rtl())
$html_part_1 = '<span class="_1">' . $left_text . '</span><span class="_2" ' . $style . '>';
$html_part_2 = '</span><span class="_3">' . $right_text . '</span>';
// HTML
$html = $html_part_1 . $text . $html_part_2;
$class = $url_is_another_post ? ' _another_post' : '';
if ( $url ) {
$button = '<a rel="' . $direction_name . '" href="' . esc_url( $url ) . '" class="_button _' . $direction_name . $class . '">' . $html . '</a>';
} else {
$button = '<span class="_button _' . $direction_name . $class . ' _disabled">' . $html . '</span>';
}
return $button;
}
} | true |
0766f12071aeea4cab1e0761a369ba37c71c6d5a | PHP | altairm/libs | /PHP/Conveyor/Condition/Permission1.php | UTF-8 | 773 | 2.609375 | 3 | [] | no_license | <?php
require_once dirname(__FILE__) . '/Abstract.php';
class Conveyor_Condition_Permission1 extends Conveyor_Condition_Abstract{
const CONVEYOR_CONDITION_PERMESSION1_CODE = 1;
const CONVEYOR_CONDITION_PERMESSION1_MODIFIRE = "PERMISSION 1";
/**
* @param Conveyor_Object_Abstract $object
*/
public function process($object) {
$this->_checkObject($object);
$data = $object->getData();
if($data & Conveyor_Condition_Permission1::CONVEYOR_CONDITION_PERMESSION1_CODE) {
$object->conditionSuccess(Conveyor_Condition_Permission1::CONVEYOR_CONDITION_PERMESSION1_MODIFIRE);
return;
}
$object->conditionFail(Conveyor_Condition_Permission1::CONVEYOR_CONDITION_PERMESSION1_MODIFIRE);
}
}
?> | true |
e11a1035bdda4220c06c2b576656a4eef1ca3eb9 | PHP | jacekll/x-challenge | /src/AppBundle/Command/AppBenchmarkCommand.php | UTF-8 | 2,215 | 2.5625 | 3 | [] | no_license | <?php
namespace AppBundle\Command;
use AppBundle\Benchmark\IncorrectUrlsException;
use AppBundle\ConstraintViolationInvalidValueCollector;
use AppBundle\Service\Benchmark;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class AppBenchmarkCommand extends Command
{
/** @var LoggerInterface */
private $logger;
/** @var Benchmark */
private $benchmark;
public function __construct(LoggerInterface $logger, Benchmark $benchmark)
{
$this->logger = $logger;
$this->benchmark = $benchmark;
parent::__construct();
}
/**
* @return LoggerInterface
*/
public function getLogger(): LoggerInterface
{
return $this->logger;
}
/**
* @param LoggerInterface $logger
*/
public function setLogger(LoggerInterface $logger)
{
$this->logger = $logger;
}
protected function configure()
{
$this
->setName('app:benchmark')
->setDescription('Benchmarks a website against other websites; currently checks website response time')
->addArgument('url', InputArgument::REQUIRED, 'Website address to benchmark')
->addArgument('otherUrl', InputArgument::REQUIRED | InputArgument::IS_ARRAY,
'Other websites to benchmark against (separated by a space)
All should start with "http(s)://"
');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$url = $input->getArgument('url');
$urls = $input->getArgument('otherUrl');
$logger = $this->getLogger();
try {
$this->benchmark->benchmark($url, $urls);
} catch (IncorrectUrlsException $e) {
$invalidValues = (new ConstraintViolationInvalidValueCollector())
->getInvalidValues($e->getViolations());
$logger->error(
sprintf('Incorrect Urls: %s',
implode(', ', $invalidValues)
));
}
}
}
| true |
830bbf7a04940a4fbbd8c4fcc32013158ebfca19 | PHP | GregoryStrbt/M-I | /API/api.php | UTF-8 | 5,661 | 2.828125 | 3 | [] | no_license | <?php
header('Access-Control-Allow-Origin: *');
//
// API Demo
//
// This script provides a RESTful API interface for a web application
//
// Input:
//
// $_GET['format'] = [ json | html | xml ]
// $_GET['m'] = []
//
// Output: A formatted HTTP response
//
// Author: Mark Roland
//
// History:
// 11/13/2012 - Created
//
// Adapted by:
// Steven Ophalvens
// --- Step 0 : connect to db
//require_once "dbcon.php";
// een verbinding leggen met de databank
$servername = "localhost";
$username = "jengar1q_mobiel";// dangerous
$password = "thib4life";// dangerous
$dbname = "jengar1q_mobiel";// standaard test databank
// Define API response codes and their related HTTP response
$api_response_code = array(0 => array('HTTP Response' => 400, 'Message' => 'Unknown Error'), 1 => array('HTTP Response' => 200, 'Message' => 'Success'), 2 => array('HTTP Response' => 403, 'Message' => 'HTTPS Required'), 3 => array('HTTP Response' => 401, 'Message' => 'Authentication Required'), 4 => array('HTTP Response' => 401, 'Message' => 'Authentication Failed'), 5 => array('HTTP Response' => 404, 'Message' => 'Invalid Request'), 6 => array('HTTP Response' => 400, 'Message' => 'Invalid Response Format'), 7 => array('HTTP Response' => 400, 'Message' => 'DB problems'));
// Set default HTTP response of 'ok' or NOK in this case
$response['code'] = 0;
$response['status'] = 404;
$response['data'] = NULL;
$conn = new mysqli($servername, $username, $password, $dbname) or die(mysqli_connect_error());
// de or die() kan vervangen worden door de juiste aanroep van deliver_response();
// dit wordt later gedaan toch nog gedaan op de juiste plaatsen, dus we raken niet verder dan hier.
// Dit treedt normaal enkel op wanneer dit niet nog niet juist is ingesteld.
//require_once "functies.php";
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
$response['code'] = 7;
$response['status'] = 404;
}
// --- Step 1: Initialize variables and functions
///**
// * Deliver HTTP Response
// * @param string $format The desired HTTP response content type: [json, html, xml]
// * @param string $api_response The desired HTTP response data
// * @return void
// **/
function deliver_response($format, $api_response)
{
// Define HTTP responses
$http_response_code = array(200 => 'OK', 400 => 'Bad Request', 401 => 'Unauthorized', 403 => 'Forbidden', 404 => 'Not Found');
// Set HTTP Response
header('HTTP/1.1 ' . $api_response['status'] . ' ' . $http_response_code[$api_response['status']]);
header('Content-Type: application/json; charset=utf-8');
$json_response = json_encode($api_response);
echo $json_response;
exit;
}
switch ($_GET['m'])
{
case 'login':
login($conn,$api_response_code);
break;
case 'getGegevens':
getGegevens($conn,$api_response_code);
break;
case 'setMeterstand':
setMeterstand($conn,$api_response_code);
break;
case 'NieuweGebruiker':
maakUser($conn,$api_response_code);
break;
default:
# code...
break;
}
function maakUser($conn,$api_response_code)
{
$response['code'] = 1;
$response['status'] = $api_response_code[$response['code']]['HTTP Response'];
$hashwachtwoord = password_hash($_POST['wachtwoord'], PASSWORD_DEFAULT);
$lQuery = "insert into Users(Naam, Achternaam, Email, Wachtwoord) values ('" . $_POST['voornaam'] . "','" . $_POST['achternaam'] . "','" . $_POST['email'] . "','" . $hashwachtwoord . "')";
$conn->query($lQuery);
deliver_response($_POST['format'], $response);
}
function setMeterstand($conn,$api_response_code)
{
$response['code'] = 0;
$response['status'] = $api_response_code[$response['code']]['HTTP Response'];
$lQuery = "insert into Gegevens(Meterstand, datum) values ('" . $_POST['gegeven'] . "','" . $_POST['datum'] . "')";
$conn->query($lQuery);
deliver_response($_POST['format'], $response);
}
function getGegevens($conn,$api_response_code)
{
$response['code'] = 0;
$response['status'] = $api_response_code[$response['code']]['HTTP Response'];
$lQuery = "select * FROM Gegevens";
$result = $conn->query($lQuery);
$rows = array();
if (!$result) {
$response['data'] = "db error";
} else {
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
$response['code'] = 1;
$response['status'] = $api_response_code[$response['code']]['HTTP Response'];
$response['data'] = $rows;
}
deliver_response($_POST['format'], $response);
}
function login($conn,$api_response_code)
{
$lQuery = "select Wachtwoord FROM Users where Email = '" . $_POST['naam'] . "'";
$ww = $_POST['password'];
$result = $conn->query($lQuery);
$rows = array();
if (!$result) {
$response['code'] = 4;
$response['data'] = "db error";
} else {
if (password_verify($ww, $result)) {
if (count($rows) > 0) {
$response['code'] = 1;
$response['status'] = $api_response_code[$response['code']]['HTTP Response'];
$response['data'] = $result;
} else {
$response['code'] = "4";
$response['status'] = $api_response_code[$response['code']]['HTTP Response'];
$response['data'] = $api_response_code[$response['code']]['Message'];
}
}
}
deliver_response($_POST['format'], $response);
}
mysqli_close($conn);
?>
| true |
bcd9a618cea0971ce960f2d1c0ff9563ee7285d2 | PHP | tayduivn/distribution-management-system | /database/migrations/2016_02_11_043504_stockmain.php | UTF-8 | 722 | 2.578125 | 3 | [
"MIT"
] | permissive | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class Stockmain extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
//
Schema::create('stock_main', function(Blueprint $table){
$table->increments('id');
$table->string('stock_code');
$table->date('recieved_date')->nullable();
$table->string('remarks')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
Schema::drop('stock_main');
}
}
| true |
5b33b1d44f9669d5b8083b0668600abcff733b1a | PHP | devDandy/devdandy | /portfolio/phpFinal/admin/deleteSponsor.php | UTF-8 | 3,369 | 2.78125 | 3 | [] | no_license | <?php
session_cache_limiter('none'); //This prevents a Chrome error when using the back button to return to this page.
session_start();
error_reporting(E_ERROR | E_PARSE); // Removes Notices and Warnings that would be visible to user.
$message = "";
$sponsorId = $_GET['SponId'];
$deleteSponsor = "";
$title = "Delete Sponsor $sponsorID - Ankeny SummerFest";
if ($_SESSION['validUser'] == "yes") { //is there already a valid user?
try {
include '../php/databaseConnect.php';
$unpreparedSQL = "SELECT sponsor_business_name FROM ank_summfest_sponsors_2018 WHERE sponsor_id=:sponsorId ";
//prepare
$stmt = $conn->prepare($unpreparedSQL);
//bind
$stmt->bindParam(":sponsorId", $sponsorId);
//execute
if ($stmt->execute()) {
//Find which sponsor id to delete...
if ($stmt->rowCount() > 0) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$deleteSponsor = $row['sponsor_business_name'];
}
//SQL DELETE STATEMENT
$SQL = "DELETE FROM ank_summfest_sponsors_2018 WHERE sponsor_id=:sponsorId";
$delStmt = $conn->prepare($SQL);
$delStmt->bindParam(":sponsorId", $sponsorId);
if ($delStmt->execute()) {
$message = "<h1>Success!</h1>";
$message .= "<p>You have successfully deleted $deleteSponsor </p>";
}
}
}
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
} else {
header('Location: admin.php');
}
?>
<!doctype html>
<html lang="en">
<head>
<title><?php echo $title ?></title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" type="text/css" href="../css/main.css">
<style>
html {
height: 100%;
}
</style>
</head>
<body class="listView">
<nav>
<div class="navMenuNew">
<ul class="navList">
<li><a href="../index.php">Home</a></li>
<li><a href="#">Theme</a></li>
<li><a href="#">Sponsors</a></li>
<li><a href="../get-involved.php">Get Involved</a></li>
<li><a href="../contact.php">Contact Us</a></li>
<li class="active"><a href="admin.php">Admin</a></li>
</ul>
<div class="logo"><a href="../index.php"><span class="ankeny">Ankeny</span><br> <span class="summerfest">Summerfest</span></a></div>
</div>
</nav>
<div class="container">
<div class="deleteContainer">
<div class="listContainer">
<?php echo $message; ?>
<a href="admin.php"><button class="btn">Return to Admin Hub</button></a>
<a href="listOfSponsors.php"><button class="btn">Return to List</button></a>
</div>
</div>
</div>
</body>
</html> | true |
37da4039b642dec5fceb371aed86595579323ee4 | PHP | qidouhai/reindex | /src/ReIndex/Doc/Subscription.php | UTF-8 | 771 | 2.65625 | 3 | [
"Apache-2.0"
] | permissive | <?php
/**
* @file Subscription.php
* @brief This file contains the Subscription class.
* @details
* @author Filippo F. Fadda
*/
namespace ReIndex\Doc;
use ToolBag\Helper;
use EoC\Doc\Doc;
/**
* @brief This class is used to keep trace of a member's subscriptions.
* @nosubgrouping
*/
class Subscription extends Doc {
/**
* @brief Creates an instance of Subscription class.
*/
public static function create($itemId, $memberId, $timestamp = NULL) {
$instance = new self();
$instance->meta["itemId"] = Helper\TextHelper::unversion($itemId);
$instance->meta["memberId"] = $memberId;
if (is_null($timestamp))
$instance->meta["timestamp"] = time();
else
$instance->meta["timestamp"] = $timestamp;
return $instance;
}
} | true |
d07d6d54fb9bc6aa2c34b0dc334b33cf15c4185c | PHP | cybercog/geo-geometry | /src/LinearRing.php | UTF-8 | 1,118 | 2.953125 | 3 | [
"MIT"
] | permissive | <?php
namespace GeoIO\Geometry;
use GeoIO\Geometry\Exception\InsufficientNumberOfGeometriesException;
use GeoIO\Geometry\Exception\LinearRingNotClosedException;
class LinearRing extends LineString
{
public function __construct($dimension, array $points = array(), $srid = null)
{
parent::__construct($dimension, $points, $srid);
$this->assert();
}
private function assert()
{
$points = $this->getPoints();
$count = count($points);
if ($count > 0 && $count < 4) {
throw InsufficientNumberOfGeometriesException::create(
4,
$count,
'Point'
);
}
$lastPoint = end($points);
$firstPoint = reset($points);
if ($lastPoint && $firstPoint &&
($lastPoint->getX() !== $firstPoint->getX() ||
$lastPoint->getY() !== $firstPoint->getY() ||
$lastPoint->getZ() !== $firstPoint->getZ() ||
$lastPoint->getM() !== $firstPoint->getM())) {
throw LinearRingNotClosedException::create();
}
}
}
| true |
1fe4712283b5806f6727f2680d77b2e7c219fa9a | PHP | kantorku015/kpknl | /backend/models/TiketSeksi.php | UTF-8 | 1,014 | 2.5625 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
namespace backend\models;
use Yii;
/**
* This is the model class for table "tiket_seksi".
*
* @property string $ticket_code
* @property string $tgl_terima
* @property int $status
* @property int $id_seksi
*/
class TiketSeksi extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'tiket_seksi';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['ticket_code', 'tgl_terima', 'id_seksi'], 'required'],
[['tgl_terima'], 'safe'],
[['id_seksi'], 'integer'],
[['ticket_code'], 'string', 'max' => 10],
[['status'], 'string', 'max' => 1],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'ticket_code' => 'Ticket Code',
'tgl_terima' => 'Tgl Terima',
'status' => 'Status',
'id_seksi' => 'Id Seksi',
];
}
}
| true |
ae6dc73fc5438eeca0fd520948ca1d8f85641190 | PHP | secytunlp/centros_mvc | /classes/com/centros/action/unidadesTiposEstados/CambiarEstadoUnidadInitAction.Class.php | UTF-8 | 1,165 | 2.625 | 3 | [] | no_license | <?php
/**
* Acción para inicializar el contexto
* para cambiar el estado de una unidad
*
* @author Marcos
* @since 11-10-2013
*
*/
class CambiarEstadoUnidadInitAction extends EditEntityInitAction {
/**
* (non-PHPdoc)
* @see classes/com/gestion/action/entities/EditEntityInitAction::getNewFormInstance()
*/
public function getNewFormInstance($action){
return new CMPCambiarEstadoUnidadForm($action);
}
/**
* (non-PHPdoc)
* @see classes/com/gestion/action/entities/EditEntityInitAction::getNewEntityInstance()
*/
public function getNewEntityInstance(){
$cambiarEstadoUnidad = new CambiarEstadoUnidad();
$filter = new CMPUnidadTipoEstadoFilter();
$filter->fillSavedProperties();
$cambiarEstadoUnidad->setUnidad($filter->getUnidad());
return $cambiarEstadoUnidad;
}
/**
* (non-PHPdoc)
* @see CdtEditAction::getOutputTitle();
*/
protected function getOutputTitle(){
return CYT_MSG_UNIDAD_TIPO_ESTADO_CAMBIAR;
}
/**
* (non-PHPdoc)
* @see classes/com/gestion/action/entities/EditEntityInitAction::getSubmitAction()
*/
protected function getSubmitAction(){
return "cambiarEstadoUnidad";
}
}
| true |
00f99b02721d7c59b7c2017403f6669717f61780 | PHP | uberger500/WebProgramming | /cookies_sessions_storage/session_test.php | UTF-8 | 151 | 2.515625 | 3 | [] | no_license | <?php
session_start();
$_SESSION['name'] = 'Blinky';
echo "<h1>Hello " . $_SESSION['name'] . ". Your session ID is " . session_id() . "</h1>\n";
?>
| true |
e113bf1180e95114505d77460370629eae812cce | PHP | erinmccauley/BiaBook | /src/api/userbyusername.php | UTF-8 | 588 | 2.65625 | 3 | [] | no_license | <?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, OPTIONS");
header("Content-Type:application/json");
/**
* Returns the recipe details
*/
require 'conn.php';
$user = [];
$username = $_GET['username'];
$cr = 0;
$sql= "SELECT id FROM Users WHERE username = '$username' LIMIT 1";
$conn -> set_charset("utf8");
if($result = mysqli_query($conn,$sql))
{
while($row = mysqli_fetch_assoc($result))
{
$user[$cr]['id'] = $row['id'];
$cr++;
}
echo json_encode($user, JSON_UNESCAPED_SLASHES);
}
else
{
http_response_code(404);
}
| true |
5dfd467cf1c31bd4c328747a3a8eed03c9555107 | PHP | etelyatn/HorseRacingSimulator | /www/src/Service/ParticipantCalculationService.php | UTF-8 | 2,568 | 3.03125 | 3 | [] | no_license | <?php
namespace App\Service;
use App\Entity\Participant;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Class ParticipantCalculationService
* @package App\Service
*/
class ParticipantCalculationService
{
/** @var int $distance */
private $distance;
/**
* ParticipantCalculationService constructor.
*
* @param int $distance
*/
public function __construct(int $distance = 1500)
{
$this->distance = $distance;
}
/**
* Calculate Participant
*
* @param Participant $participant
* @return Participant
*/
public function proceed(Participant $participant): Participant
{
$horseCalculator = new HorseCalculationService();
$newParticipantDistance = $horseCalculator->calculateDistance(
$participant->getHorse(),
$participant->getDistance()
);
$participant->setDistance($newParticipantDistance);
$participant->setTime($participant->getTime() + 1);
$participant->setActive($this->isFinish($participant));
return $participant;
}
/**
* Check participant for distance finish
*
* @param Participant $participant
* @return bool
*/
public function isFinish(Participant $participant): bool
{
return $participant->getDistance() < $this->distance;
}
/**
* Calculate Participant Positions
*
* @param ArrayCollection $participants
*
* @return ArrayCollection
*/
public function calculatePositions(ArrayCollection $participants): ArrayCollection
{
$iterator = $participants->getIterator();
$iterator->uasort(function ($a, $b) {
return ($a->getDistance() > $b->getDistance()) ? -1 : 1;
});
$sortedParticipants = new ArrayCollection();
$position = 1;
/** @var Participant $participant */
foreach (iterator_to_array($iterator) as $participant) {
$participant->setPosition($position);
$sortedParticipants->add($participant);
$position++;
}
return $sortedParticipants;
}
/**
* Get leader of participants
*
* @param ArrayCollection $participants
* @return Participant|null
*/
public function getLeader(ArrayCollection $participants): ?Participant
{
$participants = $participants->filter(function (Participant $participant) {
return $participant->getPosition() == 1;
});
return $participants[0] ?? null;
}
} | true |
aca44e6b84ed1fafe47d02c6f60d2b4bc133c576 | PHP | eggmatters/pmf_composer | /src/utilities/cache/DBCache.php | UTF-8 | 4,513 | 2.8125 | 3 | [] | no_license | <?php
namespace utilities\cache;
use core\connectors\PDOConnector;
/**
* DBCache -- primary responsibility is to identify and map foreign key
* relationships, caching the search patterns. The relationships shall be
* modeled as a n-ary ADT tree.
*
* Each node of the tree shall contain a model namespace (if exists) and
* the table name. Each node shall point to one or many children.
*
* DBCache shall additionally cache each column list for tables in the DB,
* alleviating the need to query it each time.
*
* @author meggers
*/
class DBCache extends CacheBase {
const DB_NODES = 'db_nodes';
/**
*
* @var array - array of anonymous classes.
*/
private $dbNodes;
private $tables;
private $relations;
/**
*
* @var \core\connectors\PDOConnector
*/
private $pdoConn;
/**
*
* @var ModelCache
*/
private $modelCache;
private $modelNamespaces;
use \configurations\schemaConnectorTrait;
public function __construct($appPath = null) {
parent::__construct($appPath);
$this->dbNodes = [];
$this->setPDOConn();
$this->modelCache = new ModelCache($appPath);
$this->modelNamespaces = $this->modelCache->getTableNamespaces();
}
public function setDbNodes() {
$this->dbNodes = $this->getCachedArray(self::DB_NODES);
if (!empty($this->dbNodes)) {
return;
}
$this->tables = $this->getAllTables();
$this->relations = $this->getTableRelations();
foreach($this->tables as $table) {
$tableColumns = $this->getTableColumns($table);
$this->setRelatedNodes($table);
$this->dbNodes[$table]->setColumns($tableColumns);
}
}
public function getDbNodes() {
$this->dbNodes = $this->getCachedArray(self::DB_NODES);
if (empty($this->dbNodes)) {
$this->setDbNodes();
$this->setCachedArray($this->dbNodes, self::DB_NODES);
}
return $this->dbNodes;
}
/**
*
* @param string $tableName
* @return DBNode
*/
public function getDBNode($tableName) {
if (!isset($this->dbNodes[$tableName])) {
$modelNamespace = isset($this->modelNamespaces[$tableName]) ?
$this->modelNamespaces[$tableName] : null;
$this->dbNodes[$tableName] = new DBNode($tableName, $modelNamespace);
}
return $this->dbNodes[$tableName];
}
public function getMatchingKey($parentTable, $childTable) {
foreach($this->relations as $relation) {
if ($relation['TABLE_NAME'] == $childTable &&
$relation['REFERENCED_TABLE_NAME'] == $parentTable) {
return $relation['COLUMN_NAME'];
}
}
return null;
}
private function getTableRelations() {
$sql = "SELECT i.TABLE_NAME, k.COLUMN_NAME, k.REFERENCED_TABLE_NAME"
. " FROM information_schema.TABLE_CONSTRAINTS i"
. " LEFT JOIN information_schema.KEY_COLUMN_USAGE k ON i.CONSTRAINT_NAME = k.CONSTRAINT_NAME"
. " WHERE i.CONSTRAINT_TYPE = 'FOREIGN KEY'"
. " AND i.TABLE_SCHEMA = DATABASE();";
return $this->pdoConn->rawQuery($sql);
}
private function getAllTables() {
$sql = "SELECT TABLE_NAME FROM information_schema.TABLES"
. " WHERE TABLE_SCHEMA = DATABASE();";
return array_column($this->pdoConn->rawQuery($sql), 'TABLE_NAME');
}
private function getTableColumns($table) {
$sql = "SELECT COLUMN_NAME FROM information_schema.COLUMNS "
." WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = :table";
$resultsSet = $this->pdoConn->rawQuery($sql, ['table' => $table]);
if ($resultsSet) {
return array_column($resultsSet, 'COLUMN_NAME');
} else {
return null;
}
}
private function setRelatedNodes($tableName) {
$iterator = new \core\SimpleIterator($this->relations);
$row = $iterator->current();
$node = $this->getDBNode($tableName);
while ($iterator->hasNext()) {
$parentNode = $this->getDBNode($row['REFERENCED_TABLE_NAME']);
$childNode = $this->getDBNode($row['TABLE_NAME']);
if ($row['TABLE_NAME'] == $tableName) {
$node->setParent($row['REFERENCED_TABLE_NAME'], $parentNode);
} else if ($row['REFERENCED_TABLE_NAME'] == $tableName) {
$node->setChild($row['TABLE_NAME'], $childNode);
}
$row = $iterator->next();
}
}
private function setPDOConn() {
$credentials = self::getConnectorConfiguration()['ConnectorConfig'];
$this->pdoConn = new PDOConnector($credentials['host'], $credentials['dbName'], $credentials['user'], $credentials['pass']);
}
}
| true |
cce80a5d808a74f0c9adf755eefa7bbce1b1199c | PHP | molbal/svcfitstat | /app/Exceptions/QuotaLimitException.php | UTF-8 | 89 | 2.5625 | 3 | [] | no_license | <?php
namespace App\Exceptions;
class QuotaLimitException extends \Exception {
}
| true |
06173dc9605be79acea0f1f2bcf7fbfdbdd35c80 | PHP | italyfm/RubyGarage-1 | /API/get_lists.php | UTF-8 | 1,883 | 2.65625 | 3 | [] | no_license | <?php
include 'connect.php';
if (!$mybd) {
$sql = 'CREATE DATABASE task_manager';
if (mysql_query($sql, $connect)) {
echo "Database task_manager created successfully\n";
$mybd = mysql_select_db('task_manager');
} else {
echo 'Error creating database: ' . mysql_error() . "\n";
}
}
$sqllist = "CREATE TABLE IF NOT EXISTS `lists`
(`id` int NOT NULL auto_increment,
`name` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM;";
mysql_query($sqllist) or die ('Cannot create list' . mysql_error());
$sqllist = "CREATE TABLE IF NOT EXISTS `tasks`
(`task_id` int NOT NULL auto_increment,
`id` int NOT NULL,
`name` text NOT NULL,
`status` text NOT NULL,
`position` int NOT NULL,
`deadline` DATE NOT NULL ,
PRIMARY KEY (`task_id`),
FOREIGN KEY (`id`) REFERENCES lists(id)
) ENGINE=MyISAM;";
mysql_query($sqllist) or die ('Cannot create list' . mysql_error());
$lists = mysql_query("SELECT * FROM lists ORDER BY id", $connect);
$tasks = mysql_query("SELECT * FROM tasks ORDER BY position", $connect);
$json = array();
$jsont = array();
while($rows = mysql_fetch_array($lists, MYSQL_ASSOC))
{
array_push($json,array('id'=>$rows['id'], 'title'=>$rows['name'], 'tasks' => $jsont));
};
while($rowst = mysql_fetch_array($tasks, MYSQL_ASSOC))
{
foreach ($json as &$task){
if($rowst['id'] == $task['id']){
if($rowst['deadline'] === '0000-00-00'){
$rowst['deadline'] = 'choose deadline';
} else {
$rowst['deadline'] = date('d-m-Y', strtotime($rowst['deadline']));
}
array_push($task['tasks'], array('title' => $rowst['name'], 'id' => $rowst['task_id'], 'status' => $rowst['status'], 'deadline' => $rowst['deadline'], 'position' => $rowst['position']));
};
};
};
echo json_encode($json, JSON_NUMERIC_CHECK );
mysql_close($connect);
?> | true |
005e67e0b8a98b3f92085cf5f99c6891bfe791ad | PHP | eunbeanie/bus465 | /payment.php | UTF-8 | 1,615 | 2.578125 | 3 | [] | no_license | <!--
Page Name: Admin Payment Confirm Page
Page Description: Displays the payments to be confirmed
Created By: Oliver
-->
<?php
session_start();
//handles database connection
include "db_connect.php";
?>
<!DOCTYPE html>
<html lang=en>
<head>
<link rel="stylesheet" href="css/bootstrap.css">
<title>Payment Confirmations</title>
</head>
<body>
<div class="container">
<!-- List of payments -->
<h3> Payments </h3>
<table class="table table-striped">
<thead class="thead-dark">
<tr>
<th scope="col">Name</th>
<th scope="col">Order ID</th>
<th scope="col">Delivery Date</th>
<th scope="col">Amount</th>
<th scope="col">Status</th>
</tr>
</thead>
<tbody>
<!-- Loop through sql query to generate table content (payments) -->
<?php
$sql = "
SELECT CONCAT(c.first_name,' ',c.last_name) AS 'name', o.id, o.date, SUM(oi.quantity*oi.price) as 'amount', o.status
FROM orders o
INNER JOIN order_items oi
ON o.id = oi.order_id
INNER JOIN customers c
ON o.customer_id = c.id
GROUP BY o.id
ORDER BY o.date;
";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo "
<tr>
<td>".$row['name']."</td>
<td>".$row['id']."</td>
<td>".$row['date']."</td>
<td>".$row['amount']."</td>
<td>".$row['status']."</td>
</tr>";
};
?>
</tbody>
</table>
</body>
</html>
| true |
66c6b84ce7858062a0ffdaa5cc11699487b75fe1 | PHP | Alancx/Flashcard | /Application/Home/Controller/HongController.class.php | UTF-8 | 4,782 | 2.578125 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: xu
* Date: 2017/11/30
* Time: 17:31
*/
namespace Home\Controller;
use Think\Controller;
class HongController extends BaseController
{
public function _initialize()
{
parent::_initialize(); // TODO: Change the autogenerated stub
}
public function gethongbao() {
$couponId = $_GET['id'];
//$coupon = M()->query("SELECT * FROM RS_Coupon WHERE stoken='{$this->stoken}' AND IsEnable=1 AND CouponId='{$couponId}'");
$whereStr = "stoken='{$this->stoken}' AND IsEnable=1 AND CouponId='{$couponId}'";
$coupon = M()->table("RS_Coupon")->where($whereStr)->field("CONVERT(varchar(20),ExpiredDate,120) as ExpiredDate,Rules")->find();//结果为一维数组
$this->assign('coupon',$coupon);
$this->display();
}
//XXXXX。。是需要开发者自己填写的内容,注意不要泄密
// 从session中获取到openid;
// 关键的函数
public function weixin_red_packet(){
$openid=$_SESSION["openid"];
if(empty($openid))
{
header('location:https://open.weixin.qq.com/connect/oauth2/authorize?appid=XXXXXXXX&redirect_uri=http://www.XXXXXXX.com/oauth2.php&respose_type=code&scope=snsapi_base&state=XXXX&connect_redirect=1#wechat_redirect');
}
// 请求参数
// 随机字符串
$data['nonce_str']=$this->get_unique_value();
//商户号,输入你的商户号
$data['mch_id']="XXXXXXX";
//商户订单号,可以按要求自己组合28位的商户订单号
$data['mch_billno']=$data['mch_id'].date("ymd")."XXXXXX".rand(1000,9999);
//公众帐号appid,输入自己的公众号appid
$data['wxappid']=$this->app_id;
//商户名称
$data['send_name']="XXXXX";
//用户openid,输入待发红包的用户openid
session_start();
$data['re_openid']=$_SESSION["openid"];
//付款金额
$data['total_amount']="XXXX";
//红包发放总人数
$data['total_num']="XXXX";
//红包祝福语
$data['wishing']="XXXX";
//IP地址
$data['client_ip']=$_SERVER['LOCAL_ADDR'];
//活动名称
$data['act_name']="XXXXX";
//备注
$data['remark']="XXXXX";
// 生成签名
//对数据数组进行处理
//API密钥,输入自己的K 微信商户号里面的K
$appsecret="XXXXXXXXXXXXXX"; //
$data=array_filter($data);
ksort($data);
$str="";
foreach($data as $k=>$v){
$str.=$k."=".$v."&";
}
$str.="key=".$appsecret;
$data['sign']=strtoupper(MD5($str));
/*
发红包操作过程:
1.将请求数据转换成xml
2.发送请求
3.将请求结果转换为数组
4.将请求信息和请求结果录入到数据库中
4.判断是否通信成功
5.判断是否转账成功
*/
//发红包接口地址
$url="https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
//将请求数据由数组转换成xml
$xml=$this->arraytoxml($data);
//进行请求操作
$res=$this->curl($xml,$url);
//将请求结果由xml转换成数组
$arr=$this->xmltoarray($res);
}
// 生成32位唯一随机字符串
private function get_unique_value(){
$str=uniqid(mt_rand(),1);
$str=sha1($str);
return md5($str);
}
// 将数组转换成xml
private function arraytoxml($arr){
$xml="<xml>";
foreach($arr as $k=>$v){
$xml.="<".$k.">".$v."</".$k.">";
}
$xml.="</xml>";
return $xml;
}
// 将xml转换成数组
private function xmltoarray($xml){
//禁止引用外部xml实体
libxml_disable_entity_loader(true);
$xmlstring=simplexml_load_string($xml,"SimpleXMLElement",LIBXML_NOCDATA);
$arr=json_decode(json_encode($xmlstring),true);
return $arr;
}
//进行curl操作
private function curl($param="",$url) {
$postUrl = $url;
$curlPost = $param;
//初始化curl
$ch = curl_init();
//抓取指定网页
curl_setopt($ch, CURLOPT_URL,$postUrl);
//设置header
curl_setopt($ch, CURLOPT_HEADER, 0);
//要求结果为字符串且输出到屏幕上
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//post提交方式
curl_setopt($ch, CURLOPT_POST, 1);
// 增加 HTTP Header(头)里的字段
curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
// 终止从服务端进行验证
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
//证书放到网站根目录的cert文件夹底下
curl_setopt($ch,CURLOPT_SSLCERT,dirname(__FILE__).DIRECTORY_SEPARATOR.
'cert'.DIRECTORY_SEPARATOR.'apiclient_cert.pem');
curl_setopt($ch,CURLOPT_SSLKEY,dirname(__FILE__).DIRECTORY_SEPARATOR.
'cert'.DIRECTORY_SEPARATOR.'apiient_key.pem');
curl_setopt($ch,CURLOPT_CAINFO,dirname(__FILE__).DIRECTORY_SEPARATOR.
'cert'.DIRECTORY_SEPARATOR.'rootca.pem');
//运行curl
$data = curl_exec($ch);
//关闭curl
curl_close($ch);
return $data;
}
} | true |
a04b6db5d2feb6e698a445d98633121ee5092613 | PHP | CNAWebDevCP2420/labs-datkanz093 | /Lab1/RoundedValues.php | UTF-8 | 637 | 3.453125 | 3 | [] | no_license | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Rounded Values</title>
<meta http-equiv="content-type"
content="text/html; charset=iso-8859-1" />
</head>
<body>
<?php
$Value = 56.6;
echo "Initial value = $Value<br /><br />";
$Value = 56.6;
$Value = round($Value);
echo "Rounded value is $Value<br /><br />";
$Value = 56.6;
$Value = ceil($Value);
echo "Rounded with ceil is $Value<br /><br />";
$Value = 56.6;
$Value = floor($Value);
echo "Rounded with floor is $Value<br /><br />";
?>
</body>
</html> | true |
a7fe6bcfdf879f2a61a68877ebcd640b7a6ef555 | PHP | tallcoder/Datatable | /src/OpenSkill/Datatable/DatatableService.php | UTF-8 | 2,588 | 2.71875 | 3 | [] | no_license | <?php
namespace OpenSkill\Datatable;
use OpenSkill\Datatable\Columns\ColumnConfiguration;
use OpenSkill\Datatable\Providers\Provider;
use OpenSkill\Datatable\Versions\Version;
use OpenSkill\Datatable\Versions\VersionEngine;
use OpenSkill\Datatable\Views\DatatableView;
use Symfony\Component\HttpFoundation\RequestStack;
/**
* Class DatatableService
* @package OpenSkill\Datatable
*
* The finalized and built DatatableService that can be used to handle a request or can be passed to the view.
*/
class DatatableService
{
/** @var Provider */
private $provider;
/** @var ColumnConfiguration[] */
private $columnConfigurations;
/** @var VersionEngine */
private $versionEngine;
/**
* DatatableService constructor.
* @param Provider $provider The provider that will prepare the data
* @param ColumnConfiguration[] $columnConfigurations
* @param VersionEngine $versionEngine
*/
public function __construct(Provider $provider, $columnConfigurations, VersionEngine $versionEngine)
{
$this->provider = $provider;
$this->columnConfigurations = $columnConfigurations;
$this->versionEngine = $versionEngine;
}
/**
* @param Version $version The version that should be used to generate the view and the responses
*/
public function setVersion(Version $version)
{
$this->versionEngine->setVersion($version);
}
/**
* @return bool True if any version should handle the current request
*/
public function shouldHandle()
{
return $this->versionEngine->hasVersion();
}
/**
* Will handle the current request and returns the correct response
*/
public function handleRequest()
{
$version = $this->versionEngine->getVersion();
$queryConfiguration = $version->parseRequest($this->columnConfigurations);
$this->provider->prepareForProcessing($queryConfiguration, $this->columnConfigurations);
$data = $this->provider->process();
return $version->createResponse($data, $queryConfiguration, $this->columnConfigurations);
}
/**
* @param string $tableView the view to use or null if the standard view should be used for the table and the script
* @param string $scriptView the view to use or null if the standard view should be used for the table and the script
*/
public function view($tableView = null, $scriptView = null)
{
new DatatableView($tableView, $scriptView, $this->versionEngine->getVersion(), $this->columnConfigurations);
}
} | true |
513ba9a44859c7a7ae20f2964774ea7d61525ebc | PHP | Blackbam/cistoolkit | /src/Color.php | UTF-8 | 16,744 | 3.25 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types=1);
namespace CisTools;
use JetBrains\PhpStorm\ArrayShape;
use JetBrains\PhpStorm\Pure;
/**
* Class Color
* @package CisTools
* @author David Stöckl <admin@blackbam.at>
* @todo Test some functions (especially hsl/hsla/hsb/hsv and add the correct required input types). This class is in beta.
*
* Representations supported:
* - Int is the integer representation
* - Hex is the hexadecimal string
* - RGB is an array of [red,green,blue]
* - RGBA is an array of [red,green,blue,alpha]
* - HSL is an array of [hue,saturation,lightness]
* - HSLA is an array of [hue,saturation,lightness,alpha]
* - HSB/HSV is an array of [hue,saturation,brightness]
* - CMYK is an array of [cyan,magenta,yellow,key]
*/
class Color
{
public const COLOR_MAX = 16777215; // 256^3 possible colors
protected int $color = 0x0;
protected float $alpha = 1.0;
/**
* Color constructor.
*/
public function __construct()
{
}
/*
╔═╗┌─┐┌┬┐┌┬┐┌─┐┬─┐┌─┐
╚═╗├┤ │ │ ├┤ ├┬┘└─┐
╚═╝└─┘ ┴ ┴ └─┘┴└─└─┘
*/
/**
* @param int $color
*/
public function setInt(int $color): void
{
$this->color = Math::rangeInt($color, 0, self::COLOR_MAX);
}
/**
* @param string $color
*/
public function setHexString(string $color): void
{
$colorAlphaTuple = self::colorHexRgbaToIntWithAlpha($color);
$this->color = $colorAlphaTuple['color'];
$this->alpha = $colorAlphaTuple['alpha'];
}
/**
* Hex RGBA color
* @param string $hexCode : Hexadecimal color code with alpha
* @return array: A tuple with color int and alpha float
*/
#[ArrayShape(['color' => "int", 'alpha' => "float"])]
public static function colorHexRgbaToIntWithAlpha(
string $hexCode
): array {
$hexCode = ltrim(trim($hexCode), "#");
$length = strlen($hexCode);
if ($length === 4) {
return [
'color' => self::colorHexToInt(substr($hexCode, 0, 3)),
'alpha' => self::hexToAlpha(substr($hexCode, -1))
];
}
if ($length > 6) {
return [
'color' => self::colorHexToInt(substr($hexCode, 0, 6)),
'alpha' => self::hexToAlpha(($length > 7) ? $hexCode[7] . $hexCode[8] : $hexCode[7])
];
}
return [
'color' => self::colorHexToInt($hexCode),
'alpha' => 1.0
];
}
/**
* Hex color to RGB color
*
* @param $hexCode : Hexadecimal color code
* @return int: The RGB color value
*/
public static function colorHexToInt(string $hexCode): int
{
$hexCode = substr(self::colorSanitizeHexString($hexCode), 1);
if (strlen($hexCode) === 3) {
$hexCode = $hexCode[0] . $hexCode[0] . $hexCode[1] . $hexCode[1] . $hexCode[2] . $hexCode[2];
}
$r = hexdec($hexCode[0] . $hexCode[1]);
$g = hexdec($hexCode[2] . $hexCode[3]);
$b = hexdec($hexCode[4] . $hexCode[5]);
return (int)$b + ($g << 0x8) + ($r << 0x10);
}
/**
* Takes a color string which is expected to be a hex color (with or without hashtag) and returns
* a valid hex color with 6 digits and prefixed with hashtag.
*
* @param string $color : The color to sanitize in hex notation
* @param string $default : Default color to return if color is not useable
* @return string: A hex color prefixed with hashtag (e.g. #ffffff)
*/
public static function colorSanitizeHexString(string $color, string $default = "#ffffff"): string
{
$color = trim($color);
$regex = '|^#([A-Fa-f0-9]{3}){1,2}$|';
if ($color && $color[0] !== "#") {
$color = "#" . $color;
}
// 3 or 6 hex digits, or the empty string.
if (preg_match($regex, $color)) {
return $color;
}
if (preg_match($regex, $default)) {
return $default;
}
return '#ffffff';
}
/**
* @param string $hexCode
* @return float
*/
#[Pure]
public static function hexToAlpha(
string $hexCode
): float {
$hexCode = ltrim(trim($hexCode), "#");
if (strlen($hexCode) === 1) {
$hexCode .= $hexCode;
}
return Math::rangeInt(hexdec($hexCode), 0, 100) / 100.00;
}
/**
* @param int $red
* @param int $green
* @param int $blue
* @param float $alpha
*/
public function setRgba(int $red, int $green, int $blue, float $alpha = 1.0): void
{
$this->color = self::rgbToInt($red, $green, $blue);
$this->setAlpha($alpha);
}
/**
* @param int $red
* @param int $green
* @param int $blue
* @return int
*/
#[Pure] public static function rgbToInt(int $red, int $green, int $blue): int
{
return 0xFFFF * Math::rangeInt($red, 0, 255) + 0xFF * Math::rangeInt($green, 0, 255) + Math::rangeInt(
$blue,
0,
255
);
}
/**
* @param float $alpha
*/
public function setAlpha(float $alpha = 1.0): void
{
$this->alpha = Math::rangeFloat($alpha, 0.0, 1.0);
}
/**
* @param $hue
* @param $saturation
* @param $lightness
* @param float $alpha
*/
public function setHsla($hue, $saturation, $lightness, float $alpha = 1.0): void
{
$rgb = self::hslToRgb($hue, $saturation, $lightness);
$this->color = self::rgbToInt($rgb[0], $rgb[1], $rgb[2]);
$this->setAlpha($alpha);
}
/*
╔═╗┌─┐┌┬┐┌┬┐┌─┐┬─┐┌─┐
║ ╦├┤ │ │ ├┤ ├┬┘└─┐
╚═╝└─┘ ┴ ┴ └─┘┴└─└─┘
*/
/**
* @param int $h
* @param int $s
* @param int $l
* @return array
*/
public static function hslToRgb(int $h, int $s, int $l): array
{
$c = (1 - abs(2 * ($l / 100) - 1)) * $s / 100;
$x = $c * (1 - abs(fmod(($h / 60), 2) - 1));
$m = ($l / 100) - ($c / 2);
if ($h < 60) {
$r = $c;
$g = $x;
$b = 0;
} elseif ($h < 120) {
$r = $x;
$g = $c;
$b = 0;
} elseif ($h < 180) {
$r = 0;
$g = $c;
$b = $x;
} elseif ($h < 240) {
$r = 0;
$g = $x;
$b = $c;
} elseif ($h < 300) {
$r = $x;
$g = 0;
$b = $c;
} else {
$r = $c;
$g = 0;
$b = $x;
}
return [floor(($r + $m) * 255), floor(($g + $m) * 255), floor(($b + $m) * 255)];
}
/**
* @param $hue
* @param $saturation
* @param $brightness
*/
public function setHsv($hue, $saturation, $brightness): void
{
$rgb = self::hsvToRgb($hue, $saturation, $brightness);
$this->color = self::rgbToInt($rgb[0], $rgb[1], $rgb[2]);
$this->alpha = 1.0;
}
/**
* Converts an HSV color value to RGB. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSV_color_space.
* Assumes h, s, and v are contained in the set [0, 1] and
* returns r, g, and b in the set [0, 255].
*
* @param int $h : The hue
* @param int $s : The saturation
* @param int $v : The value
* @return array: The RGB representation
*/
public static function hsvToRgb(int $h, int $s, int $v): array
{
$r = null;
$g = null;
$b = null;
$i = floor($h * 6);
$f = $h * 6 - $i;
$p = $v * (1 - $s);
$q = $v * (1 - $f * $s);
$t = $v * (1 - (1 - $f) * $s);
switch ($i % 6) {
case 0:
$r = $v;
$g = $t;
$b = $p;
break;
case 1:
$r = $q;
$g = $v;
$b = $p;
break;
case 2:
$r = $p;
$g = $v;
$b = $t;
break;
case 3:
$r = $p;
$g = $q;
$b = $v;
break;
case 4:
$r = $t;
$g = $p;
$b = $v;
break;
case 5:
$r = $v;
$g = $p;
$b = $q;
break;
}
return [$r * 255, $g * 255, $b * 255];
}
/**
* @param $cyan
* @param $magenta
* @param $yellow
* @param $key
*/
public function setCmyk($cyan, $magenta, $yellow, $key): void
{
$rgb = self::cmykToRgb($cyan, $magenta, $yellow, $key);
$this->color = self::rgbToInt($rgb[0], $rgb[1], $rgb[2]);
$this->alpha = 1.0;
}
/**
* @param $c
* @param $m
* @param $y
* @param $k
* @return array
*/
#[Pure]
public static function cmykToRgb(
$c,
$m,
$y,
$k
): array {
$c /= 100;
$m /= 100;
$y /= 100;
$k /= 100;
$r = 1 - ($c * (1 - $k)) - $k;
$g = 1 - ($m * (1 - $k)) - $k;
$b = 1 - ($y * (1 - $k)) - $k;
$r = round($r * 255);
$g = round($g * 255);
$b = round($b * 255);
return [$r, $g, $b];
}
/**
* @param int $red
*/
public function setR(int $red): void
{
$rgb = $this->getRgb();
$this->color = self::rgbToInt(Math::rangeInt($red, 0, 255), $rgb[1], $rgb[2]);
}
/**
* @return array
*/
public function getRgb(): array
{
return self::intToRgb($this->color);
}
/**
* @param int $color
* @return array
*/
public static function intToRgb(int $color): array
{
[$r, $g, $b] = sscanf(str_pad(dechex($color), 6, "0", STR_PAD_LEFT), "%02x%02x%02x");
return [$r, $g, $b];
}
/**
* @param int $green
*/
public function setG(int $green): void
{
$rgb = $this->getRgb();
$this->color = self::rgbToInt($rgb[0], Math::rangeInt($green, 0, 255), $rgb[2]);
}
/**
* @param int $blue
*/
public function setB(int $blue): void
{
$rgb = $this->getRgb();
$this->color = self::rgbToInt($rgb[0], $rgb[1], Math::rangeInt($blue, 0, 255));
}
/**
* @return int
*/
public function getInt(): int
{
return $this->color;
}
/**
* @return int
*/
public function getR(): int
{
return $this->getRgb()[0];
}
/**
* @return int
*/
public function getG(): int
{
return $this->getRgb()[1];
}
/**
* @return int
*/
public function getB(): int
{
return $this->getRgb()[2];
}
/*
╔═╗┌─┐┌┐┌┬ ┬┌─┐┬─┐┌┬┐┌─┐┬─┐┌─┐
║ │ ││││└┐┌┘├┤ ├┬┘ │ ├┤ ├┬┘└─┐
╚═╝└─┘┘└┘ └┘ └─┘┴└─ ┴ └─┘┴└─└─┘
*/
/**
* @return array
*/
public function getCmyk(): array
{
$rgb = self::intToRgb($this->color);
return self::rgbToCmyk($rgb[0], $rgb[1], $rgb[2]);
}
/**
* @param float|int $r
* @param float|int $g
* @param float|int $b
* @return array
*/
#[ArrayShape(['c' => "float|int", 'm' => "float|int", 'y' => "float|int", 'k' => "float|int"])]
public static function rgbToCmyk(
int|float $r,
int|float $g,
int|float $b
): array {
$c = (255 - $r) / 255.0 * 100;
$m = (255 - $g) / 255.0 * 100;
$y = (255 - $b) / 255.0 * 100;
$b = min([$c, $m, $y]);
$c -= $b;
$m -= $b;
$y -= $b;
return ['c' => $c, 'm' => $m, 'y' => $y, 'k' => $b];
}
/**
* @return array
*/
public function getRgba(): array
{
$rgb = self::intToRgb($this->color);
$rgb[] = $this->alpha;
return $rgb;
}
/**
* @return array
*/
public function getHsl(): array
{
$rgb = self::intToRgb($this->color);
return self::rgbToHsl($rgb[0], $rgb[1], $rgb[2]);
}
/**
* @param int $r
* @param int $g
* @param int $b
* @return array
*/
public static function rgbToHsl(int $r, int $g, int $b): array
{
$r /= 255;
$g /= 255;
$b /= 255;
$max = max($r, $g, $b);
$min = min($r, $g, $b);
$l = ($max + $min) / 2;
$d = $max - $min;
$h = $s = 0;
if ($d !== 0) {
$s = $d / (1 - abs(2 * $l - 1));
switch ($max) {
case $r:
$h = 60 * fmod((($g - $b) / $d), 6);
if ($b > $g) {
$h += 360;
}
break;
case $g:
$h = 60 * (($b - $r) / $d + 2);
break;
case $b:
$h = 60 * (($r - $g) / $d + 4);
break;
}
}
return [round($h), round($s * 100), round($l * 100)];
}
/**
* @return array
*/
public function getHsla(): array
{
$rgb = self::intToRgb($this->color);
$hsl = self::rgbToHsl($rgb[0], $rgb[1], $rgb[2]);
$hsl[] = $this->alpha;
return $hsl;
}
/**
* @return array
*/
public function getHsv(): array
{
$rgb = self::intToRgb($this->color);
return self::rgbToHsv($rgb[0], $rgb[1], $rgb[2]);
}
/**
* Converts an RGB color value to HSV. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSV_color_space.
* Assumes r, g, and b are contained in the set [0, 255] and
* returns h, s, and v in the set [0, 1].
*
* @param int $r : The red color value
* @param int $g : The green color value
* @param int $b : The blue color value
* @return array: The HSV representation
*/
#[Pure]
public static function rgbToHsv(
int $r,
int $g,
int $b
): array {
$r /= 255;
$g /= 255;
$b /= 255;
$max = max($r, $g, $b);
$min = min($r, $g, $b);
$v = $max;
$d = $max - $min;
$s = ($max === 0) ? 0 : $d / $max;
if ($max === $min) {
$h = 0; // achromatic
} else {
$h = match ($max) {
$r => ($g - $b) / $d + ($g < $b ? 6 : 0),
$g => ($b - $r) / $d + 2,
$b => ($r - $g) / $d + 4,
};
$h /= 6;
}
return [$h, $s, $v];
}
/**
* @return string
*/
public function getCssRgba(): string
{
$rgb = self::intToRgb($this->color);
return "rgba(" . $rgb[0] . "," . $rgb[1] . "," . $rgb[2] . "," . $this->alpha . ")";
}
/**
* @param bool $withAlpha
* @return string
*/
#[Pure] public function getHexRgba(bool $withAlpha = false): string
{
$out = "#" . str_pad($this->getHexString(), 6, "0", STR_PAD_LEFT);
if ($withAlpha) {
$out .= str_pad($this->getHexAlpha(), 2, "0", STR_PAD_LEFT);
}
return $out;
}
/**
* @return string
*/
#[Pure] public function getHexString(): string
{
return dechex($this->color);
}
/*
╔═╗┌┬┐┌─┐┌┬┐┌─┐ ┬┌┐┌┌─┐┌─┐
╚═╗ │ ├─┤ │ ├┤ ││││├┤ │ │
╚═╝ ┴ ┴ ┴ ┴ └─┘ ┴┘└┘└ └─┘
*/
/**
* @return string
*/
#[Pure] public function getHexAlpha(): string
{
return dechex((int)($this->alpha * 100));
}
/*
╦ ╦┌─┐┬ ┌─┐┌─┐┬─┐┌─┐
╠═╣├┤ │ ├─┘├┤ ├┬┘└─┐
╩ ╩└─┘┴─┘┴ └─┘┴└─└─┘
*/
/**
* @param float $threshold
* @return bool
*/
public function isDark(float $threshold = 127.0): bool
{
$threshold = Math::rangeFloat($threshold, 0.0, 256.0);
$trel = $threshold * 100.0 / 256.0;
$rgb = self::intToRgb($this->color);
$hsl = self::rgbToHsl($rgb[0], $rgb[1], $rgb[2]);
return $hsl[2] <= $trel;
}
} | true |
9d198ae7072c21c67a951ebf406752cfc5aecba9 | PHP | hperala/salakanto | /test/include/model/MarkupTest.php | UTF-8 | 5,518 | 3.015625 | 3 | [] | no_license | <?php
require_once 'include/model/Markup.php';
class MarkupTest extends PHPUnit_Framework_TestCase
{
function testEmpty() {
$expected = '';
$m = new Markup('');
$this->assertEquals(Markup::OK, $m->error());
$this->assertEquals($expected, $m->html());
}
function testPlainText() {
$expected = 'aaa';
$m = new Markup('aaa');
$this->assertEquals(Markup::OK, $m->error());
$this->assertEquals($expected, $m->html());
}
function testHtml() {
$expected = 'aaa <i class="el">bbb</i>';
$m = new Markup('aaa [w]bbb[/w]');
$this->assertEquals(Markup::OK, $m->error());
$this->assertEquals($expected, $m->html());
}
function testTrailingText() {
$expected = '<i class="el">bbb</i> aaa';
$m = new Markup('[w]bbb[/w] aaa');
$this->assertEquals(Markup::OK, $m->error());
$this->assertEquals($expected, $m->html());
}
function testNoLeadingOrTrailingWhitespace() {
$expected = '<p>a</p>';
$m = new Markup('[p]a[/p]');
$this->assertEquals(Markup::OK, $m->error());
$this->assertEquals($expected, $m->html());
}
function testErrorMissingClosingTag() {
$m = new Markup('aaa [w]bbb');
$this->assertEquals(Markup::MISSING_CLOSING_TAG, $m->error());
}
function testErrorMissingClosingTagNested() {
$m = new Markup('aaa [p][w]bbb');
$this->assertEquals(Markup::MISSING_CLOSING_TAG, $m->error());
}
function testErrorMissingOpeningTag() {
$m = new Markup('aaa bbb[/w]');
$this->assertEquals(Markup::MISSING_OPENING_TAG, $m->error());
}
function testSquareBrackets() {
$expected = ']][][][[';
$m = new Markup(']][][][[');
$this->assertEquals(Markup::OK, $m->error());
$this->assertEquals($expected, $m->html());
}
function testHtmlReservedCharacters() {
$expected = '<p>a <p> b</p>';
$m = new Markup('[p]a <p> b[/p]');
$this->assertEquals(Markup::OK, $m->error());
$this->assertEquals($expected, $m->html());
}
function testComplexDocument() {
$input = '
[p]
Aaaa [w]bbb[b]bb[/w] ccc.
[/p]
[p]D [w]e[/w][w]f[/w][/p] [i]g[/i] xyz [r]xyz[/r]';
$expected = '
<p>
Aaaa <i class="el">bbb[b]bb</i> ccc.
</p>
<p>D <i class="el">e</i><i class="el">f</i></p> <i>g</i> xyz <span class="root">xyz</span>';
$m = new Markup($input);
$this->assertEquals(Markup::OK, $m->error());
$this->assertEquals($expected, $m->html());
}
function testLink() {
$expected = '<a href="dot.com/?a=1&b=2">link</a>';
$m = new Markup('[l=dot.com/?a=1&b=2]link[/l]');
$this->assertEquals(Markup::OK, $m->error());
$this->assertEquals($expected, $m->html());
}
function testLinkEmptyUrl() {
$expected = '<a href="">link</a>';
$m = new Markup('[l=]link[/l]');
$this->assertEquals(Markup::OK, $m->error());
$this->assertEquals($expected, $m->html());
}
function testBrokenLinkTag() {
$expected = '[l=pseudolink';
$m = new Markup('[l=pseudolink');
$this->assertEquals(Markup::OK, $m->error());
$this->assertEquals($expected, $m->html());
}
function testContainsBlockElements() {
$m = new Markup('aaaa [w]bbb[/w]');
$this->assertEquals(Markup::OK, $m->error());
$this->assertFalse($m->containsBlockElements());
$m2 = new Markup('aaaa [p][w]bbb[/w] ccc[/p]');
$this->assertEquals(Markup::OK, $m2->error());
$this->assertTrue($m2->containsBlockElements());
}
function testFinalCharacter() {
$expected = 'aaa <i class="el">bbb</i>c';
$m = new Markup('aaa [w]bbb[/w]c');
$this->assertEquals(Markup::OK, $m->error());
$this->assertEquals($expected, $m->html());
}
function testNomarkup() {
$expected = 'aaa [w]ww c';
$m = new Markup('aaa [nomarkup][w][/nomarkup]ww c');
$this->assertEquals(Markup::OK, $m->error());
$this->assertEquals($expected, $m->html());
}
function testNomarkupClosingOptional() {
$expected = 'aaa [w]ww c';
$m = new Markup('aaa [nomarkup][w]ww c');
$this->assertEquals(Markup::OK, $m->error());
$this->assertEquals($expected, $m->html());
}
function testNomarkupNestingNotAllowed() {
$m = new Markup('aa[nomarkup]a [nomarkup][w][/nomarkup]ww[/nomarkup] c');
$this->assertEquals(Markup::MISSING_OPENING_TAG, $m->error());
}
function testNomarkupEmpty() {
$expected = 'aaa www c';
$m = new Markup('aaa [nomarkup][/nomarkup]www c');
$this->assertEquals(Markup::OK, $m->error());
$this->assertEquals($expected, $m->html());
}
function testNomarkupEscapeOneChar() {
$expected = 'aaa [w]ww c';
$m = new Markup('aaa [nomarkup][[/nomarkup]w]ww c');
$this->assertEquals(Markup::OK, $m->error());
$this->assertEquals($expected, $m->html());
}
function testNomarkupMulti() {
$expected = 'w[w]w[/w] <i class="el">bbb</i> www';
$m = new Markup('[nomarkup]w[w]w[/w][/nomarkup] [w]bbb[/w] [nomarkup]www[/nomarkup]');
$this->assertEquals(Markup::OK, $m->error());
$this->assertEquals($expected, $m->html());
}
}
| true |
d920e92078c1347b2533d739d7f73b64da0e7e83 | PHP | shivanshuit914/recipe-api | /src/Domain/Recipe/RecipeLister.php | UTF-8 | 1,100 | 3.1875 | 3 | [] | no_license | <?php
namespace Domain\Recipe;
use Exception;
class RecipeLister
{
/**
* @var RecipeRepositoryInterface
*/
private $recipeRepository;
/**
* RecipeLister constructor.
* @param RecipeRepositoryInterface $recipeRepository
*/
public function __construct(RecipeRepositoryInterface $recipeRepository)
{
$this->recipeRepository = $recipeRepository;
}
/**
* @param int $id
* @return mixed
* @throws Exception
*/
public function listById(int $id)
{
$result = $this->recipeRepository->fetchById($id);
if (empty($result)) {
throw new Exception('No recipe found for id : '. $id);
}
return $result;
}
/**
* @param string $cuisine
* @return mixed
* @throws Exception
*/
public function listByCuisine(string $cuisine)
{
$result = $this->recipeRepository->fetchByCuisine($cuisine);
if (empty($result)) {
throw new Exception('No recipe found for cuisine : '. $cuisine);
}
return $result;
}
}
| true |
c9281cb01b96e74c2d6ab6ad5a9531b83874a976 | PHP | loveblair520/backend | /app/Http/Controllers/ProductsController.php | UTF-8 | 5,330 | 2.65625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers;
use App\ProductImg;
use App\Products;
use App\ProductTypes;
use Illuminate\Support\Facades\File;
use Illuminate\Http\Request;
class ProductsController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
// $news_list = Products::with('product_types')->find(1);
// with(函式名字)抓取跟此筆資料有關係的其他資料表的資料
//Q:為什麼要做關聯? A:每次搜尋都需要進不斷進出資料庫收集資料,對伺服器的負擔較大,讀取時間也會更久
// dd($news_list);
$news_list = Products::all();
return view('admin.products.index',compact('news_list'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$product_types = ProductTypes::all();
return view('admin.products.create',compact('product_types'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$files = $request->file('multi_images');
// dd($files);
$requestData = $request->all();
if($request->hasFile('product_image')) {
$file = $request->file('product_image');
$path = $this->fileUpload($file,'products');
$requestData['product_image'] = $path;
}
$product = Products::create($requestData);
//取得剛剛建立資料的id
$product_id = $product->id;
//多圖上傳
if($request->hasFile('multi_images')){
$files = $request->file('multi_images');
foreach($files as $file){
$path = $this->fileUpload($file,'products');
ProductImg::create([
'img_url' => $path,
'product_id' => $product_id,
]);
}
}
return redirect('/admin/products');
}
/**
* 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)
{
$products = Products::find($id);
// dd($products->productImgs);
$product_types = ProductTypes::all();
return view('admin.products.edit',compact('products','product_types'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$products = Products::find($id);
$requestData = $request->all();
//判斷是否有上傳圖片 若有
if($request->hasFile('product_image')){
//刪除舊有圖片
$old_image = $products->product_image;
File::delete(public_path().$old_image);
//上傳新的圖片
$file =$request->file('product_image');
$path =$this->fileUpload($file,'news');
//將新圖片的路徑,放入$RequestData中
$requestData['product_image'] = $path;
}
$products->update($requestData);
return redirect('/admin/products');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//刪除舊有的圖片
$products = Products::find($id);
$old_image = $products->product_image;
File::delete(public_path().$old_image);
//刪除資料庫資料
Products::destroy($id);
//多張圖片的刪除
$product_imgs = ProductImg::where('product_id',$id)->get();
foreach($product_imgs as $product_img){
$old_product_img = $product_img->img;
if(file_exists(public_path().$old_product_img)){
File::delete(public_path().$old_product_img);
}
$product_img->delete();
}
return redirect('/admin/products');
}
private function fileUpload($file,$dir){
//防呆:資料夾不存在時將會自動建立資料夾,避免錯誤
if( ! is_dir('upload/')){
mkdir('upload/');
}
//防呆:資料夾不存在時將會自動建立資料夾,避免錯誤
if ( ! is_dir('upload/'.$dir)) {
mkdir('upload/'.$dir);
}
//取得檔案的副檔名
$extension = $file->getClientOriginalExtension();
//檔案名稱會被重新命名
$filename = strval(time().md5(rand(100, 200))).'.'.$extension;
//移動到指定路徑
move_uploaded_file($file, public_path().'/upload/'.$dir.'/'.$filename);
//回傳 資料庫儲存用的路徑格式
return '/upload/'.$dir.'/'.$filename;
}
}
| true |
0b9abb9b3722a333cdcf9576eadcbc2c0d9f80a7 | PHP | manix/brat | /src/Components/Errors/Handler.php | UTF-8 | 619 | 2.65625 | 3 | [] | no_license | <?php
namespace Manix\Brat\Components\Errors;
use Manix\Brat\Components\Controller;
use Throwable;
/**
* The default error handler
*/
class Handler extends Controller {
public $page = View::class;
protected $throwable;
public function __construct(Throwable $throwable) {
$this->throwable = $throwable;
}
public function before($method) {
parent::before($method);
return 'handle';
}
public function handle() {
return [
'throwable' => $this->throwable,
'code' => $this->throwable->getCode(),
'message' => $this->throwable->getMessage()
];
}
}
| true |
92538c9fd64f05b60b9ddd4f83bdf5f1b1b02fca | PHP | duaraellen/mvc_nativoPHP | /conexion.php | UTF-8 | 562 | 2.796875 | 3 | [] | no_license | <?php
class Conexion {
public function conectarBD() {
// Conectando, seleccionando la base de datos
$db_host="127.0.0.1";
$db_port="3306";
$db_name="exempel";
$db_user="root";
$db_pass="";
$conn = mysqli_connect($db_host.':'.$db_port, $db_user, $db_pass) or die ("Error conectando a la base de datos.");
mysqli_select_db($conn,$db_name) or die("Error seleccionando la base de datos.");
mysqli_set_charset($conn,"utf8");
return $conn;
}
}
?> | true |
3625fb75b32ed438176cf220de1af8e1a613b59c | PHP | valmat/rocksdbphp | /tests/t/005.phpt | UTF-8 | 501 | 2.515625 | 3 | [
"BSD-3-Clause"
] | permissive | --TEST--
Test del
--DESCRIPTION--
Testing $db->del()
--FILEEOF--
<?php
require dirname(__FILE__) . '/../include/inc.php';
# Test del
var_export($db->set('test1', 'val1'));
echo PHP_EOL;
var_export($db->get('test1'));
echo PHP_EOL;
var_export($db->del('test1'));
echo PHP_EOL;
var_export($db->get('test1'));
echo PHP_EOL;
var_export($db->get('noexist'));
echo PHP_EOL;
var_export($db->del('noexist'));
echo PHP_EOL;
var_export($db->get('noexist'));
--EXPECT--
true
'val1'
true
NULL
NULL
true
NULL | true |
e6413d9448d86c3fa4b286aa6a7275539c6e7ae7 | PHP | freelaxdeveloper/docker-dcms | /www/sys/plugins/classes/user.mess.php | UTF-8 | 753 | 2.609375 | 3 | [] | no_license | <?php
/**
* Отправляем пользователю личное сообщение
* Использовать как $user->mess(сообщение, [id отправителя. по умолчанию система])
* @param \user $user
* @param array $args
* @return boolean
*/
function user_mess($user, $args) {
if (!$user->id) {
return false;
}
$msg = $args[0];
$id_user = empty($args[1]) ? 0 : $args[1];
mysql_query("UPDATE `users` SET `mail_new_count` = `mail_new_count` + '1' WHERE `id` = '" . $user->id . "' LIMIT 1");
mysql_query("INSERT INTO `mail` (`id_user`,`id_sender`,`time`,`mess`)
VALUES ('" . $user->id . "', '$id_user', '" . TIME . "', '" . my_esc($msg) . "' )");
return true;
}
?>
| true |
de6cdf862c08edcb53a7523ed3c5fc7456cdd5f2 | PHP | soaresrodrigo/Tomada-Zero | /app/Http/Controllers/Api/ActorController.php | UTF-8 | 2,092 | 2.609375 | 3 | [] | no_license | <?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\MasterApiController;
use Illuminate\Http\Request;
use App\Models\Actor;
use App\Models\Employee;
class ActorController extends MasterApiController
{
protected $model;
function __construct(Actor $ator, Request $request)
{
$this->model = $ator;
$this->request = $request;
}
public function store(Request $request)
{
$this->validate($request, $this->model->rules());
$dataForm = $request->all();
// Verifica se o funcionário pode atuar
$funcionario = new Employee();
$funcionario = $funcionario->find($dataForm['employee_id']);
if ($funcionario['office'] === 'director') {
return response()->json(['error' => $funcionario['name'] . " não está registrado(a) para atuação."], 500);
}
$data = $this->model->create($dataForm);
return response()->json($data, 201);
}
public function update(Request $request, $id)
{
if (!$data = $this->model->find($id)) return response()->json(['error' => 'Nada foi encontrado'], 404);
$this->validate($request, $this->model->rules());
$dataForm = $request->all();
// Verifica se o funcionário pode atuar
$funcionario = new Employee();
$funcionario = $funcionario->find($dataForm['employee_id']);
if ($funcionario['office'] === 'director') {
return response()->json(['error' => $funcionario['name'] . " não está registrado(a) para atuação."], 500);
}
$data->update($dataForm);
return response()->json($data);
}
public function employee ($id) {
if (!$data = $this->model->with('employee')->find($id)) return response()->json(['error' => 'Nada foi encontrado'], 404);
return response()->json($data);
}
public function movie ($id) {
if (!$data = $this->model->with('movie')->find($id)) return response()->json(['error' => 'Nada foi encontrado'], 404);
return response()->json($data);
}
}
| true |
b7710062f561336f6f6431f992748b2ee87d42b5 | PHP | sikimar/AutoMicrosite-Repository | /AutoMicrosite/UT/Hans/AutoMicrosite/RuleGenerator/RuleMlElement/AbstractContainer.php | UTF-8 | 1,259 | 2.90625 | 3 | [] | no_license | <?php
namespace UT\Hans\AutoMicrosite\RuleGenerator\RuleMlElement;
use DOMDocument;
/**
* Abstract container element that can contain several child RuleML elements
*/
abstract class AbstractContainer extends AbstractRuleMl {
/**
* Child RuleML elements
*
* @var array
*/
protected $children = array();
/**
* Get child elements
*
* @return array
*/
public function getChildren() {
return $this->children;
}
public function __construct(array $children = array()) {
$this->children = $children;
}
/**
* Append child element
*
* @param \UT\Hans\AutoMicrosite\RuleMl\Element\RuleMl $element
*/
public function appendChild(IRuleMl $element) {
$this->children[] = $element;
}
/**
* Append an array of child elements
*
* @param array $elements
*/
public function appendChildren(array $elements) {
foreach ($elements as $element) {
$this->appendChild($element);
}
}
/**
*
* @param \DOMDocument $document
* @return \DOMElement
*/
public function getDom(DOMDocument $document) {
$element = $document->createElementNS(RuleMl::RULML_NS, $this->getElementName());
foreach ($this->getChildren() as $child) {
$element->appendChild($child->getDom($document));
}
return $element;
}
}
| true |
332bdf04e878589365777a125d3286fc98579412 | PHP | macielbombonato/docker-chamilo | /1.11.2/chamilo-lms-1.11.2/src/Chamilo/CourseBundle/Component/CourseCopy/Resources/ForumPost.php | UTF-8 | 626 | 2.625 | 3 | [
"GPL-3.0-or-later",
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | <?php
/* For licensing terms, see /license.txt */
namespace Chamilo\CourseBundle\Component\CourseCopy\Resources;
/**
* A forum-post
* @author Bart Mollet <bart.mollet@hogent.be>
* @package chamilo.backup
*/
class ForumPost extends Resource
{
/**
* Create a new ForumPost
*/
public function __construct($obj)
{
parent::__construct($obj->post_id, RESOURCE_FORUMPOST);
$this->obj = $obj;
}
/**
* Show this resource
*/
public function show()
{
parent::show();
echo $this->obj->title . ' (' . $this->obj->poster_name . ', ' . $this->obj->post_date . ')';
}
}
| true |
cebd658bc7afb88fa2d2d6c4eee9a9f180191154 | PHP | fixmind/enum | /demo/index.php | UTF-8 | 1,599 | 3.4375 | 3 | [
"MIT"
] | permissive | <?php
namespace FixMind\Enum;
include '..\src\EnumCore.php';
include '..\src\Enum.php';
// COLLECTOIN DEFINITION
class Vertical extends Enum
{
const TOP = 'TOP';
const MIDDLE = 'MIDDLE';
const BOTTOM = 'BOTTOM';
}
class Horizontal extends Enum
{
const VALUE = ['LEFT', 'CENTER', 'RIGHT'];
}
// STRICT USAGE
class MyClass
{
public $vertical;
public $horizontal;
public function setVertical(Vertical $vertical)
{
$this->vertical = $vertical;
echo "set vertical option: {$vertical}<br>";
}
public function setHorizontal(Horizontal $horizontal)
{
$this->horizontal = $horizontal;
echo "set horizontal option: {$horizontal}<br>";
}
}
// USAGE
try{
$myClass = new MyClass();
// set vertical option: TOP
$myClass->setVertical(Vertical::TOP());
// set horizontal option: RIGHT
$myClass->setHorizontal(Horizontal::RIGHT());
// vertical option is TOP
if ($myClass->vertical == Vertical::TOP())
{
echo "vertical option is TOP<br>";
}
// vertical option is still TOP
if ($myClass->vertical->is(Vertical::TOP()) === true)
{
echo "vertical option is still TOP<br>";
}
// vertical option is not BOTTOM
if ($myClass->vertical->is(Vertical::BOTTOM()) === false)
{
echo "vertical option is not BOTTOM<br>";
}
// vertical hasn't option CENTER, all 3 possibilities: TOP, MIDDLE, BOTTOM
if (Vertical::isValid('CENTER') === false)
{
echo "vertical hasn't option CENTER, all " . Vertical::getOptionCount() . " possibilities: " . implode(', ', Vertical::getOptionList()) . "<br>";
}
}
catch (\Exception $error)
{
echo $error->getMessage();
}
| true |
4bf642891b26f4cf57229ebb530947d63452fc37 | PHP | shoaibi/image-parser | /ThumbnailHtmlPageGenerator.php | UTF-8 | 1,354 | 3.21875 | 3 | [] | no_license | <?php
/**
* Class ThumbnailHtmlPageGenerator
* Utility class to generate an html page with given array of converted images
*/
abstract class ThumbnailHtmlPageGenerator
{
/**
* Render a html page for converted images
*/
public static function renderHtml($thumbnails)
{
$content = '';
foreach ($thumbnails as $imagePath)
{
// could have hardcoded the <img> element, using a wrapper to add common
// features like alt, etc in future and have them apply equally to all generated
// tags
$content .= static::generateThumbnailImageTag($imagePath);
$content .= "<br />";
}
// heredoc to be used as a html template
// in real life this could be a view template with strtr based transformations
$template = <<<HTM
<!doctype html>
<html>
<head>
<title>Thumbails</title>
</head>
<body style="background-color:#CCCCCC;">
$content
</body>
</html>
HTM;
// time to display the results of the hard word
echo $template;
}
/**
* Generate an image (html) tag for provided file path.
* @param $imageFilePath
* @return string
*/
protected static function generateThumbnailImageTag($imageFilePath)
{
// nothing fancy
return "<img src='$imageFilePath' />";
}
}
| true |
ddc21fdb8b17cc884c7e1965c6ee1b846f5ccc3a | PHP | gitstashgithub/php-imap | /src/Attachment.php | UTF-8 | 9,102 | 2.6875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | <?php
/*
* File: Attachment.php
* Category: -
* Author: M. Goldenbaum
* Created: 16.03.18 19:37
* Updated: -
*
* Description:
* -
*/
namespace Webklex\PHPIMAP;
use Illuminate\Support\Str;
use Webklex\PHPIMAP\Exceptions\MaskNotFoundException;
use Webklex\PHPIMAP\Exceptions\MethodNotFoundException;
use Webklex\PHPIMAP\Support\Masks\AttachmentMask;
/**
* Class Attachment
*
* @package Webklex\PHPIMAP
*
* @property integer part_number
* @property integer size
* @property string content
* @property string type
* @property string content_type
* @property string id
* @property string name
* @property string disposition
* @property string img_src
*
* @method integer getPartNumber()
* @method integer setPartNumber(integer $part_number)
* @method string getContent()
* @method string setContent(string $content)
* @method string getType()
* @method string setType(string $type)
* @method string getContentType()
* @method string setContentType(string $content_type)
* @method string getId()
* @method string setId(string $id)
* @method string getSize()
* @method string setSize(integer $size)
* @method string getName()
* @method string getDisposition()
* @method string setDisposition(string $disposition)
* @method string setImgSrc(string $img_src)
*/
class Attachment {
/**
* @var Message $oMessage
*/
protected $oMessage;
/**
* Used config
*
* @var array $config
*/
protected $config = [];
/** @var Part $part */
protected $part;
/**
* Attribute holder
*
* @var array $attributes
*/
protected $attributes = [
'content' => null,
'type' => null,
'part_number' => 0,
'content_type' => null,
'id' => null,
'name' => null,
'disposition' => null,
'img_src' => null,
'size' => null,
];
/**
* Default mask
*
* @var string $mask
*/
protected $mask = AttachmentMask::class;
/**
* Attachment constructor.
* @param Message $oMessage
* @param Part $part
*/
public function __construct(Message $oMessage, Part $part) {
$this->config = ClientManager::get('options');
$this->oMessage = $oMessage;
$this->part = $part;
$this->part_number = $part->part_number;
$default_mask = $this->oMessage->getClient()->getDefaultAttachmentMask();
if($default_mask != null) {
$this->mask = $default_mask;
}
$this->findType();
$this->fetch();
}
/**
* Call dynamic attribute setter and getter methods
* @param string $method
* @param array $arguments
*
* @return mixed
* @throws MethodNotFoundException
*/
public function __call(string $method, array $arguments) {
if(strtolower(substr($method, 0, 3)) === 'get') {
$name = Str::snake(substr($method, 3));
if(isset($this->attributes[$name])) {
return $this->attributes[$name];
}
return null;
}elseif (strtolower(substr($method, 0, 3)) === 'set') {
$name = Str::snake(substr($method, 3));
$this->attributes[$name] = array_pop($arguments);
return $this->attributes[$name];
}
throw new MethodNotFoundException("Method ".self::class.'::'.$method.'() is not supported');
}
/**
* Magic setter
* @param $name
* @param $value
*
* @return mixed
*/
public function __set($name, $value) {
$this->attributes[$name] = $value;
return $this->attributes[$name];
}
/**
* magic getter
* @param $name
*
* @return mixed|null
*/
public function __get($name) {
if(isset($this->attributes[$name])) {
return $this->attributes[$name];
}
return null;
}
/**
* Determine the structure type
*/
protected function findType() {
switch ($this->part->type) {
case IMAP::ATTACHMENT_TYPE_MESSAGE:
$this->type = 'message';
break;
case IMAP::ATTACHMENT_TYPE_APPLICATION:
$this->type = 'application';
break;
case IMAP::ATTACHMENT_TYPE_AUDIO:
$this->type = 'audio';
break;
case IMAP::ATTACHMENT_TYPE_IMAGE:
$this->type = 'image';
break;
case IMAP::ATTACHMENT_TYPE_VIDEO:
$this->type = 'video';
break;
case IMAP::ATTACHMENT_TYPE_MODEL:
$this->type = 'model';
break;
case IMAP::ATTACHMENT_TYPE_TEXT:
$this->type = 'text';
break;
case IMAP::ATTACHMENT_TYPE_MULTIPART:
$this->type = 'multipart';
break;
default:
$this->type = 'other';
break;
}
}
/**
* Fetch the given attachment
*/
protected function fetch() {
$content = $this->part->content;
$this->content_type = $this->part->content_type;
$this->content = $this->oMessage->decodeString($content, $this->part->encoding);
if (($id = $this->part->id) !== null) {
$this->id = str_replace(['<', '>'], '', $id);
}else{
$this->id = hash("sha256", (string)microtime(true));
}
$this->size = $this->part->bytes;
$this->disposition = $this->part->disposition;
if (($filename = $this->part->filename) !== null) {
$this->setName($filename);
} elseif (($name = $this->part->name) !== null) {
$this->setName($name);
}else {
$this->setName("undefined");
}
if (IMAP::ATTACHMENT_TYPE_MESSAGE == $this->part->type) {
if ($this->part->ifdescription) {
$this->setName($this->part->description);
} else {
$this->setName($this->part->subtype);
}
}
}
/**
* Save the attachment content to your filesystem
* @param string $path
* @param string|null $filename
*
* @return boolean
*/
public function save(string $path, $filename = null): bool {
$filename = $filename ?: $this->getName();
return file_put_contents($path.$filename, $this->getContent()) !== false;
}
/**
* Set the attachment name and try to decode it
* @param $name
*/
public function setName($name) {
$decoder = $this->config['decoder']['attachment'];
if ($name !== null) {
if($decoder === 'utf-8' && extension_loaded('imap')) {
$this->name = \imap_utf8($name);
}else{
$this->name = mb_decode_mimeheader($name);
}
}
}
/**
* Get the attachment mime type
*
* @return string|null
*/
public function getMimeType(){
return (new \finfo())->buffer($this->getContent(), FILEINFO_MIME_TYPE);
}
/**
* Try to guess the attachment file extension
*
* @return string|null
*/
public function getExtension(){
$guesser = "\Symfony\Component\Mime\MimeTypes";
if (class_exists($guesser) !== false) {
/** @var Symfony\Component\Mime\MimeTypes $guesser */
$extensions = $guesser::getDefault()->getExtensions($this->getMimeType());
return $extensions[0] ?? null;
}
$deprecated_guesser = "\Symfony\Component\HttpFoundation\File\MimeType\ExtensionGuesser";
if (class_exists($deprecated_guesser) !== false){
/** @var \Symfony\Component\HttpFoundation\File\MimeType\ExtensionGuesser $deprecated_guesser */
return $deprecated_guesser::getInstance()->guess($this->getMimeType());
}
return null;
}
/**
* Get all attributes
*
* @return array
*/
public function getAttributes(): array {
return $this->attributes;
}
/**
* @return Message
*/
public function getMessage(): Message {
return $this->oMessage;
}
/**
* Set the default mask
* @param $mask
*
* @return $this
*/
public function setMask($mask): Attachment {
if(class_exists($mask)){
$this->mask = $mask;
}
return $this;
}
/**
* Get the used default mask
*
* @return string
*/
public function getMask(): string {
return $this->mask;
}
/**
* Get a masked instance by providing a mask name
* @param string|null $mask
*
* @return mixed
* @throws MaskNotFoundException
*/
public function mask($mask = null){
$mask = $mask !== null ? $mask : $this->mask;
if(class_exists($mask)){
return new $mask($this);
}
throw new MaskNotFoundException("Unknown mask provided: ".$mask);
}
} | true |
256c6742f5f6fa1476c48f61019dae6253ef6dec | PHP | kardi31/ap | /application/modules/order/services/DeliveryType.php | UTF-8 | 3,625 | 2.5625 | 3 | [] | no_license | <?php
/**
* Order_Service_DeliveryType
*
@author Andrzej Wilczyński <and.wilczynski@gmail.com>
*/
class Order_Service_DeliveryType extends MF_Service_ServiceAbstract {
protected $deliveryTypeTable;
public function init() {
$this->deliveryTypeTable = Doctrine_Core::getTable('Order_Model_Doctrine_DeliveryType');
parent::init();
}
public function getDeliveryType($id, $field = 'id', $hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
return $this->deliveryTypeTable->findOneBy($field, $id, $hydrationMode);
}
public function getDeliveryTypeForm(Order_Model_Doctrine_DeliveryType $deliveryType = null) {
$form = new Order_Form_DeliveryType();
if(null != $deliveryType) {
$form->populate($deliveryType->toArray());
}
return $form;
}
public function saveDeliveryTypeFromArray($values) {
foreach($values as $key => $value) {
if(!is_array($value) && strlen($value) == 0) {
$values[$key] = NULL;
}
}
if(!$deliveryType = $this->getDeliveryType((int) $values['id'])) {
$deliveryType = $this->deliveryTypeTable->getRecord();
}
$deliveryType->fromArray($values);
$deliveryType->save();
return $deliveryType;
}
public function removeDeliveryType(Order_Model_Doctrine_DeliveryType $deliveryType) {
$deliveryType->delete();
}
public function getAllDeliveryType($hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
$q = $this->deliveryTypeTable->getDeliveryTypeQuery();
return $q->execute(array(), $hydrationMode);
}
public function getAllDeliveryTypeSorted($hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
$q = $this->deliveryTypeTable->getDeliveryTypeQuery();
$q->addOrderBy('dt.created_at ASC');
return $q->execute(array(), $hydrationMode);
}
public function getTargetDeliveryTypeSelectOptionsSorted($prependEmptyValue = false) {
$items = $this->getAllDeliveryTypeSorted();
$result = array();
if($prependEmptyValue) {
$result[''] = '';
}
foreach($items as $item) {
if($item->getId() != 9){
$result[$item->getId()] = $item->name." - ".$item->price." zł ";
}
else{
$result[$item->getId()] = $item->name;
}
}
return $result;
}
public function getTargetDeliveryTypeSelectOptions($prependEmptyValue = false) {
$items = $this->getAllDeliveryType();
$result = array();
if($prependEmptyValue) {
$result[''] = ' ';
}
foreach($items as $item) {
$result[$item->getId()] = $item->name." - ".$item->price." zł";
}
return $result;
}
public function getTargetTypeSelectOptions($prependEmptyValue = false) {
$result = array();
if($prependEmptyValue) {
$result[''] = ' ';
}
$result['pobranie'] = "pobranie";
$result['przelew'] = "przelew";
$result['brak'] = "brak";
return $result;
}
public function getMinimalPriceForDelivery() {
$items = $this->getAllDeliveryType();
$min = $items[0]->getPrice();
foreach($items as $item):
if ($item->getPrice() > 0):
if ($min > $item->getPrice()):
$min = $item->getPrice();
endif;
endif;
endforeach;
return $min;
}
}
?>
| true |
b058dfb1b1e12b78bedaa5fd116b664e0dd89a44 | PHP | paullewallencom/symfony-978-1-8471-9456-5 | /_src/lib/model/MilkshakePeer.php | UTF-8 | 936 | 2.734375 | 3 | [
"Apache-2.0"
] | permissive | <?php
class MilkshakePeer extends BaseMilkshakePeer
{
/**
* Get all milshakes
*
* @param Int $limit
* @return Array Get all
*/
public static function getAllShakes($currentPage, $totalItems)
{
$pagerObj = DbFinder::from('Milkshake')->useCache(new sfMemcacheCache())->select(array('name'))->paginate($currentPage, $totalItems);
return $pagerObj;
}
public static function getBestMilkshakes()
{
$milkshakeResults = DbFinder::from('Milkshake')->find();
return $milkshakeResults;
}
public static function searchMilkshakesAjax($q, $limit)
{
$c = new Criteria();
$c->add(self::NAME, '%'.$q.'%', Criteria::LIKE);
$c->addAscendingOrderByColumn(self::NAME);
$c->setLimit($limit);
$milkshakes = array();
foreach (self::doSelect($c) as $milkshake)
{
$milkshakes[$milkshake->getUrlSlug()] = $milkshake->getName();
}
return $milkshakes;
}
}
| true |
20919c4dc155b6217d64c49c86be2ae7540fc659 | PHP | Nabcellent/highschool-elections | /insert/vote_ins.php | UTF-8 | 1,106 | 2.609375 | 3 | [] | no_license | <?php
include_once "../functions.php";
$link = connect_to_db();
$voter_id = $_POST['voter_id'];
$head_boy_id = $_POST['head_boy'];
$head_girl_id = $_POST['head_girl'];
$dh_capt_id = $_POST['dh_capt'];
$games_capt_id = $_POST['games_capt'];
$lib_capt_id = $_POST['lib_capt'];
$form_capt_id = $_POST['form_capt'];
$class_prefect_id = $_POST['class_prefect'];
// Check if already voted
$sql_voted = "SELECT * FROM vote_tbl WHERE voter_id = '$voter_id'";
$res_voted = mysqli_query($link, $sql_voted);
if(mysqli_num_rows($res_voted) > 0) {
echo "You CANNOT vote twice!";
} else {
$sql = "INSERT INTO vote_tbl (voter_id, head_boy_id, head_girl_id, dh_capt_id, games_capt_id, lib_capt_id, form_capt_id, class_prefect_id)
VALUES ('$voter_id', '$head_boy_id', '$head_girl_id', '$dh_capt_id', '$games_capt_id', '$lib_capt_id', '$form_capt_id', '$class_prefect_id')";
if(mysqli_query($link, $sql)) {
echo "You have Voted Successfully!";
} else {
echo "ERROR IN VOTING! \nPlease contact your Administrator @Lè_•Çapuchôn✓🩸";
}
} | true |
86f703dcb8a5204653b68af16d99f15edda9239d | PHP | NicholasZyl/chess | /features/bootstrap/Helper/InMemoryGames.php | UTF-8 | 769 | 2.859375 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types=1);
namespace Helper;
use NicholasZyl\Chess\Domain\Exception\GameNotFound;
use NicholasZyl\Chess\Domain\Game;
use NicholasZyl\Chess\Domain\GameId;
use NicholasZyl\Chess\Domain\GamesRepository;
class InMemoryGames implements GamesRepository
{
/**
* @var Game[]
*/
private $games = [];
/**
* {@inheritdoc}
*/
public function add(GameId $identifier, Game $game): void
{
$this->games[$identifier->id()] = $game;
}
/**
* {@inheritdoc}
*/
public function find(GameId $identifier): Game
{
if (!array_key_exists($identifier->id(), $this->games)) {
throw new GameNotFound($identifier);
}
return $this->games[$identifier->id()];
}
} | true |
b6e8a3b931add1aa7a0210d82f813f5369063d59 | PHP | rtsantos/mais | /library/ZendT/Tool/Crud/Table.php | UTF-8 | 10,240 | 2.59375 | 3 | [] | no_license | <?php
/**
* Classe para geração do arquivo Table do módulo
*
* @package ZendT
* @subpackage Tool
* @category Crud
* @author rsantos
*/
class ZendT_Tool_Crud_Table {
/**
* Cria o modelo do crud na qual o desenvolvedor não coloca a mão
* Esses dados são sempre substituído
*
* @param string $pathBase
* @param array $config
*/
public static function crudTable($pathBase, $config) {
if (!isset($config['table']['modelName'])){
$config['table']['modelName'] = $config['table']['name'];
}
$modelName = ZendT_Lib::convertTableNameToClassName($config['table']['modelName']);
$strPrimary = '';
if (is_string($config['table']['primary'])) {
$upPrimary = strtolower($config['table']['primary']);
$strPrimary = "'{$upPrimary}'";
} else {
foreach ($config['table']['primary'] as $primary) {
$upPrimary = strtolower($primary);
$strPrimary .= ",'{$upPrimary}'";
}
$strPrimary = substr($strPrimary, 1);
}
$strUnique = '';
if (isset($config['table']['unique'])){
foreach ($config['table']['unique'] as $unique) {
$upUnique = strtolower($unique);
$strUnique .= ",'{$upUnique}'";
}
$strUnique = substr($strUnique, 1);
}
if ($config['table']['moduleName'] == '' || $config['table']['moduleName'] == 'Application') {
$config['table']['moduleName'] = 'Application';
$path = 'application/models/Crud';
} else {
$path = 'application/modules/' . $config['table']['moduleName'] . '/models/' . $modelName . '/Crud';
}
$ucModuleName = ucfirst($config['table']['moduleName']);
ZendT_Lib::createDirectory($pathBase, $path);
$filename = $pathBase . '/' . $path . '/Table.php';
$strDependentTables = '';
foreach ($config['table']['dependentTables'] as $value) {
$strDependentTables.= ",
'" . $value . "_Table'";
}
$strDependentTables = substr($strDependentTables, 1);
$strReferenceMap = '';
foreach ($config['table']['referenceMaps'] as $prop) {
$referenceName = ZendT_Lib::convertTableNameToClassName($prop['columnName']);
$strReferenceMap.= ",
'" . $referenceName . "' => array(
'columns' => '" . $prop['columnName'] . "',
'refTableClass' => '" . $prop['objectNameReference'] . "_Table',
'refColumns' => '" . $prop['columnReference'] . "'
)";
}
$strReferenceMap = substr($strReferenceMap, 1);
/**
* Gera a lista de opções de colunas de status
*/
$firstOptions = true;
$strListOptions = '';
$strCols = '';
$strRequired = '';
$strColumnMappers = "array('default'=>array('mapper'=>'{$ucModuleName}_Model_{$modelName}_Mapper'),";
foreach ($config['table']['columns'] as $column => $prop) {
$upColumn = strtolower($column);
$strCols.= ",'$upColumn'";
$listOptions = $prop['object']['listOptions'];
if ($prop['object']['required']) {
$strRequired .= ",'" . strtolower($column) . "'";
}
if (count($listOptions) > 0) {
$firstItem = true;
$strListItem = '';
if ($firstOptions) {
$strListOptions.= "'$column'=>array(";
$firstOptions = false;
}else
$strListOptions.= "\n ,'$column'=>array(";
foreach ($listOptions as $key => $value) {
if ($firstItem) {
$strListItem.= "'{$key}'=>'{$value}'";
$firstItem = false;
}else
$strListItem.= "\n ,'{$key}'=>'{$value}'";
}
$strListOptions.= $strListItem;
$strListOptions.= ")";
}
/**
* faz o mapeamento das colunas padrão e seus
* respectivos mappers
*/
if ($prop['object']['type'] == 'Seeker') {
foreach ($config['table']['referenceMaps'] as $reference) {
if (strtolower($reference['columnName']) == strtolower($column)) {
$mapperName = $reference['objectNameReference'] . '_Mapper';
}
}
if (substr(strtolower($column),0,3) == 'id_'){
$tableColumn = substr(strtolower($column),3);
}else if (substr(strtolower($column),0,2) == 'id'){
$tableColumn = substr(strtolower($column),2);
}else{
$tableColumn = $prop['object']['seeker']['tableName'];
}
$strColumnMappers.= "
'{$prop['object']['seeker']['field']['search']}_{$tableColumn}'=>array('mapper'=>'{$mapperName}','column'=>'{$prop['object']['seeker']['field']['search']}'),
";
if ($prop['object']['seeker']['field']['display'] != '') {
$strColumnMappers.= "
'{$prop['object']['seeker']['field']['display']}_{$tableColumn}'=>array('mapper'=>'{$mapperName}','column'=>'{$prop['object']['seeker']['field']['display']}'),
";
}
}
}
$strCols = substr($strCols, 1);
$strRequired = ltrim($strRequired, ',');
$upTableName = strtolower($config['table']['name']);
$upTableAlias = strtolower($config['table']['alias']);
if (!$upTableAlias){
$upTableAlias = strtolower($config['table']['name']);
}
$upSchemaName = strtolower($config['table']['schema']);
$upSequenceName = strtolower($config['table']['sequenceName']);
if ($upSequenceName == ''){
$upSequenceName = '';
}else{
$upSequenceName = "protected \$_sequence = '{$upSequenceName}';";
}
$contentText = <<<EOS
<?php
/**
* Classe de mapeamento da tabela {$config['table']['name']}
*/
class {$ucModuleName}_Model_{$modelName}_Crud_Table extends ZendT_Db_Table_Abstract
{
protected \$_name = '{$upTableName}';
protected \$_alias = '{$upTableAlias}';
{$upSequenceName}
protected \$_required = array({$strRequired});
protected \$_primary = array({$strPrimary});
protected \$_unique = array({$strUnique});
protected \$_cols = array({$strCols});
protected \$_search = '{$config['table']['seeker']['field']['search']}';
protected \$_schema = '{$upSchemaName}';
protected \$_adapter = 'db.{$config['table']['schema']}';
protected \$_dependentTables = array({$strDependentTables});
protected \$_referenceMap = array({$strReferenceMap});
protected \$_listOptions = array({$strListOptions});
protected \$_mapper = '{$ucModuleName}_Model_{$modelName}_Mapper';
protected \$_element = '{$ucModuleName}_Form_{$modelName}_Elements';
/**
* Retorna as configurações do elemento HTML
*
* @param string \$columnName
* @return {$ucModuleName}_Model_{$modelName}_Element
*/
public function getElement(\$columnName){
\$_element = new {$ucModuleName}_Form_{$modelName}_Elements();
\$method = 'get' . ZendT_Lib::convertTableNameToClassName(\$columnName);
return \$_element->\$method();
}
/**
* Retorna o objeto Mapper do Modelo
*
* @return {$ucModuleName}_Model_{$modelName}_Mapper
*/
public function getMapper(){
\$mapper = new {$ucModuleName}_Model_{$modelName}_Mapper();
return \$mapper;
}
/**
* Retorna um array contendo todas as colunas obrigatórias
*
* @return array
*/
public function getRequired() {
return \$this->_required;
}
/**
* Informa se a coluna é obrigatória
*
* @param string \$field
* @return boolean
*/
public function isRequired(\$field) {
return in_array(\$field, \$this->_required);
}
}
?>
EOS;
file_put_contents($filename, $contentText);
}
/**
* Cria o modelo do desenvolvedor que pode manipular os dados
*
* @param string $pathBase
* @param array $config
*/
public static function developerTable($pathBase, $config) {
if (!isset($config['table']['modelName'])){
$config['table']['modelName'] = $config['table']['name'];
}
$modelName = ZendT_Lib::convertTableNameToClassName($config['table']['modelName']);
if ($config['table']['moduleName'] == '' || $config['table']['moduleName'] == 'Application') {
$config['table']['moduleName'] = 'Application';
$path = 'application/models';
} else {
$path = 'application/modules/' . $config['table']['moduleName'] . '/models/' . $modelName;
}
ZendT_Lib::createDirectory($pathBase, $path);
$filename = $pathBase . '/' . $path . '/Table.php';
$ucModuleName = ucfirst($config['table']['moduleName']);
$contentText = <<<EOS
<?php
/**
* Classe de mapeamento da tabela {$config['table']['name']}
*/
class {$ucModuleName}_Model_{$modelName}_Table extends {$ucModuleName}_Model_{$modelName}_Crud_Table{
}
?>
EOS;
if (!file_exists($filename)) {
file_put_contents($filename, $contentText);
}
}
/**
* Cria as classes de modelo
*
* @param string $pathBase
* @param array $config
*/
public static function create($pathBase, $config){
ZendT_Tool_Crud_Table::crudTable($pathBase, $config);
ZendT_Tool_Crud_Table::developerTable($pathBase, $config);
}
}
?>
| true |
87fde8b2ef6cf90a87bb1da58c66623cd67cb118 | PHP | rahulyhg/happy-giraffe | /site/common/behaviors/UrlBehavior.php | UTF-8 | 2,173 | 2.5625 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: mikita
* Date: 10/09/14
* Time: 14:58
*/
namespace site\common\behaviors;
class UrlBehavior extends \CActiveRecordBehavior
{
public $preparedUrl;
public $route;
public $params = array('id');
public $urlAttribute = 'url';
private $urlSaved = false;
public function afterSave($event)
{
if ($this->owner->hasAttribute($this->urlAttribute) && $this->urlSaved === false) {
$this->owner->url = $this->getUrl(true);
$this->owner->isNewRecord = false;
$this->urlSaved = true;
$this->owner->update(array('url'));
$this->owner->isNewRecord = true;
}
}
public function getUrl($absolute = false)
{
if ($this->preparedUrl !== null) {
return $this->normalizePreparedUrl($this->preparedUrl);
}
if ($this->route === null) {
throw new \CException('Route is not provided');
}
$finalRoute = $this->normalizeRoute($this->route);
$finalParams = $this->normalizeParams($this->params);
return $absolute ? \Yii::app()->createAbsoluteUrl($finalRoute, $finalParams) : \Yii::app()->createUrl($finalRoute, $finalParams);
}
protected function normalizePreparedUrl($preparedUrl)
{
if (is_callable($preparedUrl)) {
return call_user_func($preparedUrl, $this->owner);
} elseif ($this->owner->getAttribute($preparedUrl) !== null) {
return $this->owner->$preparedUrl;
}
return $preparedUrl;
}
protected function normalizeRoute($route)
{
return (is_callable($route)) ? call_user_func($route, $this->owner) : $route;
}
protected function normalizeParams($inputParams)
{
if (is_callable($inputParams)) {
return call_user_func($inputParams, $this->owner);
} else {
$outputParams = array();
foreach ($inputParams as $k => $v) {
$key = is_int($k) ? $v : $k;
$outputParams[$key] = $this->owner->getAttribute($v);
}
return $outputParams;
}
}
} | true |
3168a3ea83a126aea8d2eddbb190aadcbd2b30c0 | PHP | thecodingmachine/metahydrator | /tests/Validator/EnumValidatorTest.php | UTF-8 | 828 | 2.609375 | 3 | [
"MIT"
] | permissive | <?php
namespace MetaHydratorTest\Validator;
use MetaHydrator\Validator\EnumValidator;
class EnumValidatorTest extends \PHPUnit_Framework_TestCase
{
private $validator;
public function __construct($name = null, array $data = [], $dataName = '')
{
parent::__construct($name, $data, $dataName);
$enum = ['blue', 'red', 'magenta'];
$this->validator = new EnumValidator($enum);
}
public function testValidate()
{
$this->validator->validate('red');
}
public function testValidateNull()
{
$this->validator->validate(null);
$this->validator->validate('');
}
/**
* @expectedException \MetaHydrator\Exception\ValidationException
*/
public function testValidateThrow()
{
$this->validator->validate('cyan');
}
}
| true |
b419146ac77c90008612c732dd44ff604834cf70 | PHP | dmanners/DavidAndVinai_PreferencesInfoCommand | /Model/Shell/Command/PreferencesInfo.php | UTF-8 | 2,768 | 2.65625 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
namespace DavidAndVinai\PreferencesInfoCommand\Model\Shell\Command;
use Magento\Framework\ObjectManager\ConfigInterface as ObjectManagerConfig;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class PreferencesInfo extends Command
{
const INPUT_KEY_INTERFACE = 'interface';
/**
* @var string[]
*/
private $outputList = [];
/**
* @var ObjectManagerConfig
*/
private $objectManagerConfig;
public function __construct(ObjectManagerConfig $objectManagerConfig)
{
parent::__construct();
$this->objectManagerConfig = $objectManagerConfig;
}
protected function configure()
{
$this->addArgument(
self::INPUT_KEY_INTERFACE,
InputArgument::IS_ARRAY,
'List of interfaces or class names for which to show the preferences configuration.'
);
$this->setName('preferences:info')
->setDescription('Displays configured preference config for given interface(s)');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->outputList = [];
$this->collectPreferencesForGivenInterfaces($input);
$this->displayMatchedPreferences($output);
}
private function collectPreferencesForGivenInterfaces(InputInterface $input)
{
foreach ($this->getRequestedInterfaces($input) as $interfaceName) {
$this->collectPreferencesForInterface(ltrim($interfaceName, '\\'));
}
}
private function collectPreferencesForInterface($interfaceName)
{
$preferences = $this->objectManagerConfig->getPreferences();
foreach ($preferences as $type => $targetClass) {
if ($this->isMatchingPreference($interfaceName, $type)) {
$this->outputList[$type] = $targetClass;
}
}
}
private function displayMatchedPreferences(OutputInterface $output)
{
foreach ($this->outputList as $type => $targetClass) {
$output->writeln(sprintf('<info>%s => %s</info>', $type, $targetClass));
}
}
private function getRequestedInterfaces(InputInterface $input)
{
$argument = $input->getArgument(self::INPUT_KEY_INTERFACE);
$requestedInterfaces = array_map('trim', $argument);
return array_filter($requestedInterfaces, 'strlen');
}
private function isMatchingPreference($interfaceName, $type)
{
$len = strlen($interfaceName);
return substr($type, $len * -1) === $interfaceName;
}
}
| true |
3fc3b2ef9f74f9a8a223d91038a785484dd9468e | PHP | matzpersson/laravel-ladbrokes | /app/Http/Controllers/RaceController.php | UTF-8 | 2,688 | 2.625 | 3 | [] | no_license | <?php
namespace App\Http\Controllers;
use App\Race;
use Illuminate\Http\Request;
class RaceController extends Controller
{
/**
* Reset race close.
*
* @return \Illuminate\Http\Response
*/
public function restart()
{
// -- For demonstration purposes only.
// -- Re-seed the closing time to demonstrate row closure after closing time incrementing each race with 1 then 2 minutes.
date_default_timezone_set('Australia/Brisbane');
$races = Race::all();
$increment = 1;
foreach ($races as $race) {
$starttime = date('Y-m-d H:i:s',strtotime('+' . $increment . ' minutes'));
$race->closing_time = $starttime;
$race->save();
$increment += 2;
}
return Race::all();
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return Race::with("meeting")->get();
}
/**
* Display a paginated listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function paginate(Request $request)
{
// -- Hardcoded timezone is not good but works for the sake of the demo Should probably be UTC closing time applying closing time to local time
// -- as a flight would do.
date_default_timezone_set('Australia/Brisbane');
$now = date('y-m-d H:i:s');
// -- Handle sort
if (request()->has('sort')) {
list($sortCol, $sortDir) = explode('|', request()->sort);
$query = Race::with("meeting")->where('closing_time','>',$now)->orderBy($sortCol, $sortDir);
} else {
$query = Race::with("meeting")->where('closing_time','>',$now)->orderBy('closing_time', 'asc');
}
$perPage = request()->has('per_page') ? (int) request()->per_page : null;
return response()->json( $query->paginate($perPage) );
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Job $job
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$race = Race::findOrFail($id);
$race->update($request->all());
return response()->json($job, 200);
}
/**
* Remove the specified resource from storage.
*
* @param \App\Job $job
* @return \Illuminate\Http\Response
*/
public function delete(Request $request, $id)
{
$race = Race::findOrFail($id);
$race->delete();
return response()->json(null, 204);
}
}
| true |
9f0afdc7d6940908330176e72d31cc41fcdd86d9 | PHP | base10-at/util | /src/Email/SmtpConnectionConfig.php | UTF-8 | 2,050 | 2.90625 | 3 | [] | no_license | <?php namespace Base10\Email;
use Base10\Contract\EmailAddressInterface;
use Base10\Mixin\CanInitialise;
class SmtpConnectionConfig
{
use CanInitialise;
/**
* @var string
*/
private $_username;
/**
* @var string
*/
private $_password;
/**
* @var string
*/
private $_server;
/**
* @var integer
*/
private $_port;
/**
* @var EmailAddressInterface
*/
private $_email;
/**
* @return string
*/
public function getUsername(): string
{
return $this->_username;
}
/**
* @param string $username
* @return self
*/
public function username(string $username): self
{
$this->_username = $username;
return $this;
}
/**
* @return string
*/
public function getPassword(): string
{
return $this->_password;
}
/**
* @param string $password
* @return self
*/
public function password(string $password): self
{
$this->_password = $password;
return $this;
}
/**
* @return string
*/
public function getServer(): string
{
return $this->_server;
}
/**
* @param string $server
* @return self
*/
public function server(string $server): self
{
$this->_server = $server;
return $this;
}
/**
* @return EmailAddressInterface
*/
public function getEmail(): EmailAddressInterface
{
return $this->_email;
}
/**
* @param EmailAddressInterface $email
* @return self
*/
public function email(EmailAddressInterface $email): self
{
$this->_email = $email;
return $this;
}
/**
* @return int
*/
public function getPort(): int
{
return $this->_port;
}
/**
* @param int $port
* @return self
*/
public function port(int $port): self
{
$this->_port = $port;
return $this;
}
} | true |
f22202a162ee91b42f5b54f7fb635a502d9f34c2 | PHP | kiyonlin/knox | /app/Modules/User/User.php | UTF-8 | 2,016 | 2.515625 | 3 | [] | no_license | <?php
namespace App\Modules\User;
use App\Modules\Module\Module;
use App\Modules\Role\Role;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Collection;
use Parsidev\Entrust\Traits\EntrustUserTrait;
class User extends Authenticatable
{
use Notifiable, EntrustUserTrait;
const SYSTEM_ADMIN = 'system_admin';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'username', 'email', 'display_name', 'phone_number', 'password', 'remember_token'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
protected $with = [];
/**
* 获取用户的所有模块
*
* @return Collection
*/
public function modules()
{
return Module::all()->filter(function ($module) {
return $this->can("module.view.{$module->key}");
})->sortBy('sort');
}
/**
* 获取用户的所有权限名称
*
* @return mixed
*/
public function permissions()
{
return $this->roles->reduce(function ($permissions, $role) {
return $permissions->merge($role->perms);
}, new Collection([]))->pluck('name');
}
/**
* 获取用户可以分配的角色
* @param string $query
* @return Collection
*/
public function optionalRoles(string $query = '')
{
$roleIds = $this->roles->pluck('id')->toArray();
return Role::where('display_name', 'like', "%{$query}%")
->get(['id', 'name', 'display_name', 'description'])
->reject(function ($role) use ($roleIds) {
return in_array($role->id, $roleIds);
})
->values();
}
public static function systemAdmin()
{
return self::where('username', self::SYSTEM_ADMIN)->first();
}
}
| true |
5da570204d49155075699ccec869bce1b3141630 | PHP | KashyapBhat/Paper-Evaluation-using-AI-ML | /WebApp/uploadanswer.php | UTF-8 | 7,503 | 2.578125 | 3 | [
"Apache-2.0",
"CC-BY-4.0",
"CC-BY-3.0"
] | permissive | <?php
include('conect.php');
error_reporting(1);
extract($_POST);
$error=array();
//clear previos adds of images
foreach($_POST as $nameaa => $content) {
}
$usn = $_POST['usnp'];
if (!file_exists($usn) && !is_dir($usn)) {
mkdir($usn, 0777, true);
}
$target_dir = $usn."/";
$extension=array("jpeg","jpg","png","gif");
$i1=0;
$i2=0;
$i3=0;
$i4=0;
$i5=0;
$i6=0;
foreach($_FILES["ans1p"]["tmp_name"] as $key=>$tmp_name)
{
$i1++;
$file_name=$_FILES["ans1p"]["name"][$key]; //name: gets the name of the image
$file_tmp=$_FILES["ans1p"]["tmp_name"][$key]; //tmp_name gets the path of the image
$ext=pathinfo($file_name,PATHINFO_EXTENSION);
if(in_array($ext,$extension))
{
if(!file_exists($target_dir.$file_name))
{
$newFileName="a".$i1.".".$ext;
move_uploaded_file($file_tmp=$_FILES["ans1p"]["tmp_name"][$key],$target_dir."$newFileName");
$tempp1=$target_dir.$newFileName;
$temp1=$temp1.$tempp1.",";
echo "$temp";
}
else
{
echo "File Exists";
}
}
else
{
array_push($error,"$file_name, ");
}
$tempppp=$tempppp.",".$file_tmp;
}
foreach($_FILES["ans2p"]["tmp_name"] as $key=>$tmp_name)
{
$i2++;
$file_name=$_FILES["ans2p"]["name"][$key]; //name: gets the name of the image
$file_tmp=$_FILES["ans2p"]["tmp_name"][$key]; //tmp_name gets the path of the image
$ext=pathinfo($file_name,PATHINFO_EXTENSION);
if(in_array($ext,$extension))
{
if(!file_exists($target_dir.$file_name))
{
$newFileName="b".$i2.".".$ext;
move_uploaded_file($file_tmp=$_FILES["ans2p"]["tmp_name"][$key],$target_dir."$newFileName");
$tempp2=$target_dir.$newFileName;
$temp2=$temp2.$tempp2.",";
echo "$temp";
}
else
{
echo "File Exists";
}
}
else
{
array_push($error,"$file_name, ");
}
}
foreach($_FILES["ans3p"]["tmp_name"] as $key=>$tmp_name)
{
$i3++;
$file_name=$_FILES["ans3p"]["name"][$key]; //name: gets the name of the image
$file_tmp=$_FILES["ans3p"]["tmp_name"][$key]; //tmp_name gets the path of the image
$ext=pathinfo($file_name,PATHINFO_EXTENSION);
if(in_array($ext,$extension))
{
if(!file_exists($target_dir.$file_name))
{
$newFileName="c".$i3.".".$ext;
move_uploaded_file($file_tmp=$_FILES["ans3p"]["tmp_name"][$key],$target_dir."$newFileName");
$tempp3=$target_dir.$newFileName;
$temp3=$temp3.$tempp3.",";
echo "$temp";
}
else
{
echo "File Exists";
}
}
else
{
array_push($error,"$file_name, ");
}
}
foreach($_FILES["ans4p"]["tmp_name"] as $key=>$tmp_name)
{
$i4++;
$file_name=$_FILES["ans4p"]["name"][$key]; //name: gets the name of the image
$file_tmp=$_FILES["ans4p"]["tmp_name"][$key]; //tmp_name gets the path of the image
$ext=pathinfo($file_name,PATHINFO_EXTENSION);
if(in_array($ext,$extension))
{
if(!file_exists($target_dir.$file_name))
{
$newFileName="d".$i4.".".$ext;
move_uploaded_file($file_tmp=$_FILES["ans4p"]["tmp_name"][$key],$target_dir."$newFileName");
$tempp4=$target_dir.$newFileName;
$temp4=$temp4.$tempp4.",";
echo "$temp";
}
else
{
echo "File Exists";
}
}
else
{
array_push($error,"$file_name, ");
}
}
foreach($_FILES["ans5p"]["tmp_name"] as $key=>$tmp_name)
{
$i5++;
$file_name=$_FILES["ans5p"]["name"][$key]; //name: gets the name of the image
$file_tmp=$_FILES["ans5p"]["tmp_name"][$key]; //tmp_name gets the path of the image
$ext=pathinfo($file_name,PATHINFO_EXTENSION);
if(in_array($ext,$extension))
{
if(!file_exists($target_dir.$file_name))
{
$newFileName="e".$i5.".".$ext;
move_uploaded_file($file_tmp=$_FILES["ans5p"]["tmp_name"][$key],$target_dir."$newFileName");
$tempp5=$target_dir.$newFileName;
$temp5=$temp5.$tempp5.",";
echo "$temp";
}
else
{
echo "File Exists";
}
}
else
{
array_push($error,"$file_name, ");
}
}
foreach($_FILES["ans6p"]["tmp_name"] as $key=>$tmp_name)
{
$i6++;
$file_name=$_FILES["ans6p"]["name"][$key]; //name: gets the name of the image
$file_tmp=$_FILES["ans6p"]["tmp_name"][$key]; //tmp_name gets the path of the image
$ext=pathinfo($file_name,PATHINFO_EXTENSION);
if(in_array($ext,$extension))
{
if(!file_exists($target_dir.$file_name))
{
$newFileName="f".$i6.".".$ext;
move_uploaded_file($file_tmp=$_FILES["ans6p"]["tmp_name"][$key],$target_dir."$newFileName");
$tempp6=$target_dir.$newFileName;
$temp6=$temp6.$tempp6.",";
echo "$temp";
}
else
{
echo "File Exists";
}
}
else
{
array_push($error,"$file_name, ");
}
}
$query1 = "INSERT INTO `answer`(`usn`, `q1`, `q2`, `q3`, `q4`, `q5`, `q6`) VALUES ('$usn','$temp1','$temp2','$temp3','$temp4','$temp5','$temp6')";
mysqli_query($con,$query1);
header('Location: ' . $_SERVER['HTTP_REFERER']);
?> | true |
170e4a955be7d422e5a48ec0d28f096430b998be | PHP | EmmanuelAmet/online-student-portal--core-php | /admin/result.php | UTF-8 | 19,311 | 2.578125 | 3 | [] | no_license | <?php
require '../dbConnection/connect.inc.php';
$myuser = $_GET['username'];
$query = "SELECT * FROM students WHERE username = '{$myuser}' ";
$result = mysqli_query($connection, $query);
while ($row = mysqli_fetch_array($result)) {
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$othername = $row['othername'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Portal - SBA</title>
<!-- Bootstrap styles for this template-->
<link href="../bootstrap/css/bootstrap.min.css" rel="stylesheet">
<script>
function printContent(el) {
var restorepage = document.body.innerHTML;
var printcontent = document.getElementById(el).innerHTML;
document.body.innerHTML = printcontent;
window.print();
document.body.innerHTML = restorepage;
}
</script>
</head>
<body class="bg-gradient-primary">
<div class="container">
<div class="card o-hidden border-0 shadow-lg my-5" style="border-bottom-right-radius: 200px; border-top-left-radius: 200px;">
<div class="card-body p-0">
<?php
$query = "SELECT * FROM students WHERE username = '{$myuser}' ";
$result = mysqli_query($connection, $query);
if(!$result)
{
die('QUERY FAILED'.mysqli_error($connection));
}
while ($row = mysqli_fetch_array($result)) {
$db_username = $row['username'];
}
if($db_username == $myuser)
{
$query = "SELECT * FROM mathematics WHERE username = '{$myuser}' ";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_array($result);
if($row == false)
{
$mathsClass = 'IC';
$mathsExam = 'IC';
$mathsTotal = 'IC';
$mathsGrade = 'IC';
$mathsRemark = 'IC';
}elseif($row['ClassScore'] == "" || $row['ExamScore'] == ""){
$mathsClass = 'IC';
$mathsExam = 'IC';
$mathsTotal = 'IC';
$mathsGrade = 'IC';
$mathsRemark = 'IC';
}
else{
$mathsClass = $row['ClassScore'];
$mathsExam = $row['ExamScore'];
$mathsTotal = $row['TotalScore'];
$mathsGrade = $row['Grade'];
$mathsRemark = $row['Remark'];
}
$query = "SELECT * FROM english WHERE username = '{$myuser}' ";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_array($result);
if($row == false)
{
$EnglishClass = 'IC';
$EnglishExam = 'IC';
$EnglishTotal = 'IC';
$EnglishGrade = 'IC';
$EnglishRemark = 'IC';
}elseif($row['ClassScore'] == "" || $row['ExamScore'] == ""){
$EnglishClass = 'IC';
$EnglishExam = 'IC';
$EnglishTotal = 'IC';
$EnglishGrade = 'IC';
$EnglishRemark = 'IC';
}else{
$EnglishClass = $row['ClassScore'];
$EnglishExam = $row['ExamScore'];
$EnglishTotal = $row['TotalScore'];
$EnglishGrade = $row['Grade'];
$EnglishRemark = $row['Remark'];
}
$query = "SELECT * FROM social WHERE username = '{$myuser}' ";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_array($result);
if($row == false)
{
$SocialClass = 'IC';
$SocialExam = 'IC';
$SocialTotal = 'IC';
$SocialGrade = 'IC';
$SocialRemark = 'IC';
}elseif($row['ClassScore'] == "" || $row['ExamScore'] == ""){
$SocialClass = 'IC';
$SocialExam = 'IC';
$SocialTotal = 'IC';
$SocialGrade = 'IC';
$SocialRemark = 'IC';
}else{
$SocialClass = $row['ClassScore'];
$SocialExam = $row['ExamScore'];
$SocialTotal = $row['TotalScore'];
$SocialGrade = $row['Grade'];
$SocialRemark = $row['Remark'];
}
$query = "SELECT * FROM science WHERE username = '{$myuser}' ";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_array($result);
if($row == false)
{
$ScienceClass = 'IC';
$ScienceExam = 'IC';
$ScienceTotal = 'IC';
$ScienceGrade = 'IC';
$ScienceRemark = 'IC';
}elseif($row['ClassScore'] == "" || $row['ExamScore'] == ""){
$ScienceClass = 'IC';
$ScienceExam = 'IC';
$ScienceTotal = 'IC';
$ScienceGrade = 'IC';
$ScienceRemark = 'IC';
}else{
$ScienceClass = $row['ClassScore'];
$ScienceExam = $row['ExamScore'];
$ScienceTotal = $row['TotalScore'];
$ScienceGrade = $row['Grade'];
$ScienceRemark = $row['Remark'];
}
$query = "SELECT * FROM rme WHERE username = '{$myuser}' ";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_array($result);
if($row == false)
{
$RMEClass = 'IC';
$RMEExam = 'IC';
$RMETotal = 'IC';
$RMEGrade = 'IC';
$RMERemark = 'IC';
}elseif($row['ClassScore'] == "" || $row['ExamScore'] == ""){
$RMEClass = 'IC';
$RMEExam = 'IC';
$RMETotal = 'IC';
$RMEGrade = 'IC';
$RMERemark = 'IC';
}else{
$RMEClass = $row['ClassScore'];
$RMEExam = $row['ExamScore'];
$RMETotal = $row['TotalScore'];
$RMEGrade = $row['Grade'];
$RMERemark = $row['Remark'];
}
$query = "SELECT * FROM ict WHERE username = '{$myuser}' ";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_array($result);
if($row == false)
{
$ICTClass = 'IC';
$ICTExam = 'IC';
$ICTTotal = 'IC';
$ICTGrade = 'IC';
$ICTRemark = 'IC';
}elseif($row['ClassScore'] == "" || $row['ExamScore'] == ""){
$ICTClass = 'IC';
$ICTExam = 'IC';
$ICTTotal = 'IC';
$ICTGrade = 'IC';
$ICTRemark = 'IC';
}else{
$ICTClass = $row['ClassScore'];
$ICTExam = $row['ExamScore'];
$ICTTotal = $row['TotalScore'];
$ICTGrade = $row['Grade'];
$ICTRemark = $row['Remark'];
}
$query = "SELECT * FROM bdt WHERE username = '{$myuser}' ";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_array($result);
if($row == false)
{
$BDTClass = 'IC';
$BDTExam = 'IC';
$BDTTotal = 'IC';
$BDTGrade = 'IC';
$BDTRemark = 'IC';
}elseif($row['ClassScore'] == "" || $row['ExamScore'] == ""){
$BDTClass = 'IC';
$BDTExam = 'IC';
$BDTTotal = 'IC';
$BDTGrade = 'IC';
$BDTRemark = 'IC';
}else{
$BDTClass = $row['ClassScore'];
$BDTExam = $row['ExamScore'];
$BDTTotal = $row['TotalScore'];
$BDTGrade = $row['Grade'];
$BDTRemark = $row['Remark'];
}
$query = "SELECT * FROM GhanaianLanguage WHERE username = '{$myuser}' ";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_array($result);
if($row == false)
{
$GHLanguageClass = 'IC';
$GHLanguageExam = 'IC';
$GHLanguageTotal = 'IC';
$GHLanguageGrade = 'IC';
$GHLanguageRemark = 'IC';
}elseif($row['ClassScore'] == "" || $row['ExamScore'] == ""){
$GHLanguageClass = 'IC';
$GHLanguageExam = 'IC';
$GHLanguageTotal = 'IC';
$GHLanguageGrade = 'IC';
$GHLanguageRemark = 'IC';
}else{
$GHLanguageClass = $row['ClassScore'];
$GHLanguageExam = $row['ExamScore'];
$GHLanguageTotal = $row['TotalScore'];
$GHLanguageGrade = $row['Grade'];
$GHLanguageRemark = $row['Remark'];
}
$query = "SELECT * FROM french WHERE username = '{$myuser}' ";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_array($result);
if($row == false)
{
$FrenchClass = 'IC';
$FrenchExam = 'IC';
$FrenchTotal = 'IC';
$FrenchGrade = 'IC';
$FrenchRemark = 'IC';
}elseif($row['ClassScore'] == "" || $row['ExamScore'] == ""){
$FrenchClass = 'IC';
$FrenchExam = 'IC';
$FrenchTotal = 'IC';
$FrenchGrade = 'IC';
$FrenchRemark = 'IC';
}else{
$FrenchClass = $row['ClassScore'];
$FrenchExam = $row['ExamScore'];
$FrenchTotal = $row['TotalScore'];
$FrenchGrade = $row['Grade'];
$FrenchRemark = $row['Remark'];
}
if(!empty($mathsGrade) && !empty($SocialGrade) && !empty($ScienceGrade) && !empty($ScienceClass) && !empty($RMEGrade) && !empty($ICTGrade) && !empty($BDTGrade) && !empty($GHLanguageGrade) && !empty($FrenchGrade))
{
$coreSubjects = "";
}else{
$coreSubjects = $mathsGrade + $EnglishGrade + $SocialGrade + $ScienceGrade;
}
if(!empty($mathsGrade) && !empty($SocialGrade) && !empty($ScienceGrade) && !empty($ScienceClass) && !empty($RMEGrade) && !empty($ICTGrade) && !empty($BDTGrade) && !empty($GHLanguageGrade) && !empty($FrenchGrade))
{
$coreSubjects = "";
}else{
$coreSubjects = $mathsGrade + $EnglishGrade + $SocialGrade + $ScienceGrade;
}
$coreTotal = $mathsTotal + $ScienceTotal + $EnglishTotal + $SocialTotal;
$totalScore = $coreTotal + $FrenchTotal + $BDTTotal + $RMETotal + $ICTTotal + $GHLanguageTotal;
// $rawScore = $mathsTotal + $SocialTotal + $EnglishTotal + $ScienceTotal + $RMETotal + $ICTTotal + $BDTTotal + $GHLanguageTotal + $FrenchTotal;
//$electives = array('$FrenchGrade', ' $GHLanguageGrade', '$BDTGrade', '$ICTGrade', '$RMEGrade');
// $first = max($electives);
// $second = min($electives);
?>
<br>
<br>
<div id="result">
<center>
<div class="table-responsive">
<table border="1" width="90%">
<tr>
<td>
<table width=100%>
<tr>
<td>
<img src='../images/ucclogo.jpg' width=80 height=70>
</td>
<td>
<b><font size='5'>Mystic Falls International School</font> </b><br>
<font size='4' color='grey'><b>Student Terminal Report (Email: info@MysticFalls.com)</b></font>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<table>
<tr><td><font size='4'>NAME OF STUDENT: <?php echo $firstname; echo " "; echo $othername; echo " "; echo $lastname; ?> </font></td></tr>
<tr><td><font size='4'>CLASS: FORM 2 TERM: 3 INDEX NUMBER: <?php echo "$myuser"; ?></font></td></tr>
<tr><td><font size='4'>VACATION DATE: 23/10/2019 NEXT TERM BEGINS: 10/09/2019 </font></td></tr>
</table>
</td>
</tr>
<tr>
<td>
<table border="" width="100%" class="table table-bordered table-hover table-condense">
<tr><th><i>Subjects</i></th><th><i>Class score 50%</i></th><th><i>Exam Score 50%</i></th><th><i>Total Score 100%</i></th><th><i>Grade</i></th><th><i>Remark</i></th></tr>
<td style="background-color: #DCDCDC;" colspan=6><div class='text-danger'><B> CORE</B></div></td>
<tr><td> English Language</td><td align="center"><?php echo "$EnglishClass"; ?></td><td align="center"><?php echo "$EnglishExam"; ?></td><td align="center"><?php echo "$EnglishTotal"; ?></td><td align="center"><?php echo "$EnglishGrade"; ?></td><td><?php echo "$EnglishRemark"; ?></td></tr>
<tr><td> Integrated Science</td><td align="center"><?php echo "$ScienceClass"; ?></td><td align="center"><?php echo "$ScienceExam"; ?></td><td align="center"><?php echo "$ScienceTotal"; ?></td><td align="center"><?php echo "$ScienceGrade"; ?></td><td><?php echo "$ScienceRemark"; ?></td></tr>
<tr><td> Mathematics</td><td align="center"><?php echo "$mathsClass"; ?></td><td align="center"><?php echo "$mathsExam"; ?></td><td align="center"><?php echo "$mathsTotal"; ?></td><td align="center"><?php echo "$mathsGrade"; ?></td><td><?php echo "$mathsRemark"; ?></td></tr>
<tr><td> Social Studies</td><td align="center"><?php echo "$SocialClass"; ?></td><td align="center"><?php echo "$SocialExam"; ?></td><td align="center"><?php echo "$SocialTotal"; ?></td><td align="center"><?php echo "$SocialGrade"; ?></td><td><?php echo "$SocialRemark"; ?></td></tr>
<td style="background-color: #DCDCDC;" colspan=6><div class='text-danger'><B> ELECTIVES</B></div></td>
<tr><td> I.C.T</td><td align="center"><?php echo "$ICTClass"; ?></td><td align="center"><?php echo "$ICTExam"; ?></td><td align="center"><?php echo "$ICTTotal"; ?></td><td align="center"><?php echo "$ICTGrade"; ?></td><td><?php echo "$ICTRemark"; ?></td></tr>
<tr><td> B.D.T</td><td align="center"><?php echo "$BDTClass"; ?></td><td align="center"><?php echo "$BDTExam"; ?></td><td align="center"><?php echo "$BDTTotal"; ?></td><td align="center"><?php echo "$BDTGrade"; ?></td><td><?php echo "$BDTRemark"; ?></td></tr>
<tr><td> R.M.E</td><td align="center"><?php echo "$RMEClass"; ?></td><td align="center"><?php echo "$RMEExam"; ?></td><td align="center"><?php echo "$RMETotal"; ?></td><td align="center"><?php echo "$RMEGrade"; ?></td><td><?php echo "$RMERemark"; ?></td></tr>
<tr><td> Ghanaian Language</td><td align="center"><?php echo "$GHLanguageClass"; ?></td><td align="center"><?php echo "$GHLanguageExam"; ?></td><td align="center"><?php echo "$GHLanguageTotal"; ?></td><td align="center"><?php echo "$GHLanguageGrade"; ?></td><td><?php echo "$GHLanguageRemark"; ?></td></tr>
<tr><td> French</td><td align="center"><?php echo "$FrenchClass"; ?></td><td align="center"><?php echo "$FrenchExam"; ?></td><td align="center"><?php echo "$FrenchTotal"; ?></td><td align="center"><?php echo "$FrenchGrade"; ?></td><td><?php echo "$FrenchRemark"; ?></td></tr>
</table>
</td>
</tr>
<?php
if($RMETotal > 50)
{
$attitude = 'SOCIABLE';
}else
{
$attitude = 'FRIENDLY';
}
if($SocialTotal > 50)
{
$conduct = 'HONEST';
}else
{
$conduct = 'KIND';
}
if($EnglishTotal > 50)
{
$interest = 'HONEST';
}else
{
$interest = 'SPORTS AND GAMES';
}
?>
<tr>
<td>
<table class=" table-hover">
<tr class="warning"><td> ATTENDANCE</td><td> 56 OUT OF 60</td><td> TOTAL SCORE: <?php echo $totalScore; echo "/900"; ?></td></tr>
<tr><td> STATUS</td><td colspan=3> PROMOTED</td></tr>
<tr><td> CONDUCT</td><td colspan=3> <?php echo $attitude ?></td></tr>
<tr><td> ATTITUDE</td><td colspan=3> <?php echo $conduct ?></td></tr>
<tr><td> INTEREST</td><td colspan=3> <?php echo $interest ?></td></tr>
<tr><td> REMARK</td><td colspan=3> STUDY YOUR GRADES AND IMPROVE UPON THE WEAK ONES.</td></tr>
</table><br>
<table border="1" width="50%" class="table-borderd table-hover">
<tr><td align="center"><b>GRADING CODE</b></td><td align="center"><b>GRADE</b></td><td><b> REMARK</b></td></tr>
<tr><td align="center">80 - 100</td><td align="center">1</td><td> Highest</td></tr>
<tr><td align="center">70 - 79</td><td align="center">2</td><td> Higher</td></tr>
<tr><td align="center">65 - 69</td><td align="center">3</td><td> High</td></tr>
<tr><td align="center">60 - 64</td><td align="center">4</td><td> High Average</td></tr>
<tr><td align="center">55 - 59</td><td align="center">5</td><td> Average</td></tr>
<tr><td align="center">50 - 54</td><td align="center">6</td><td> Low Average</td></tr>
<tr><td align="center">45 - 49</td><td align="center">7</td><td> Low</td></tr>
<tr><td align="center">35 - 44</td><td align="center">8</td><td> Lower</td></tr>
<tr><td align="center">00 - 34</td><td align="center">9</td><td> Lowest</td></tr>
</table><br>
<font size='3'><I><b>ANY ALTRATION TO THIS DOCUMENT RENDERS IT INVALID.</b></I></font><br>
<font size='3' color='green'><I><b>DATE & TIME PRINTED: 34/09/2019 TIME: 10:30</b></I></font><br>
<font size='3' color='orange'><I><b>POWERED BY CYPHER SOFTWARE. For more info. call: +233 546501162/+233 247101346</b></I></font>
</td>
</tr>
</table>
</div>
</center>
</div><br>
<center> <button class="btn btn-primary btn-block" onclick="printContent('result')">Print</button>
<a href="home.php" class="btn btn-danger btn-user btn-block">Back to Home</a>
</center>
<?php
}else{
?>
<center>
<div class="col-xl-3 col-md-6 mb-4">
<div class="card border-left-primary shadow h-30 py-2">
<div class="card-body">
<div class="row no-gutters align-items-center">
<div class="col mr-2">
<div class="text-mb font-weight-bold text-primary text-uppercase mb-1">
<a href="">ERROR</a>
</div>
<div class="row no-gutters align-items-center text-uppercase">
<div class="col">
<li class="nav-item active">
<a class="nav-link btn-primary font-weight-bold" style="border-radius: 20px;" href="#">
<i class="fas fa fa-arr+ow-circle-right"></i>
<span>Unknow Index Number</span></a>
</li>
<hr>
<a href="home.php" class="btn btn-danger btn-user btn-block">Back to Home</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</center>
<?php
}
?>
</div>
</div>
</body>
</html> | true |
66bfbf45216cc7b39b47a8d6d1653b6984d65025 | PHP | redbastie/swift | /src/Components/ListGroupComponent.php | UTF-8 | 433 | 2.53125 | 3 | [] | no_license | <?php
namespace Redbastie\Swift\Components;
class ListGroupComponent extends BaseComponent
{
protected $content;
public function __construct($content)
{
parent::__construct();
$this->content = $content;
}
public function flush()
{
return $this->class('list-group-flush');
}
public function horizontal()
{
return $this->class('list-group-horizontal');
}
}
| true |
e0e4fea419d4ef0acb4d48cd457388e2514e2608 | PHP | maclof/kubernetes-client | /tests/collections/DeploymentCollectionTest.php | UTF-8 | 573 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
use Maclof\Kubernetes\Collections\DeploymentCollection;
class DeploymentCollectionTest extends TestCase
{
protected array $items = [
[],
[],
[],
];
protected function getDeploymentCollection(): DeploymentCollection
{
$deploymentCollection = new DeploymentCollection($this->items);
return $deploymentCollection;
}
public function test_get_items(): void
{
$deploymentCollection = $this->getDeploymentCollection();
$items = $deploymentCollection->toArray();
$this->assertTrue(is_array($items));
$this->assertEquals(3, count($items));
}
}
| true |
812330bd5dceedb32f96cf7b5edf24fb793fa948 | PHP | kamilbiela/shop-backend | /src/model/ProductLang.php | UTF-8 | 1,845 | 2.625 | 3 | [
"MIT"
] | permissive | <?php
namespace Shop\Model;
use Shop\Lib\Serializer\ArraySerializableInterface;
/**
* @Entity(repositoryClass="Shop\Repository\ProductLangRepository")
* @HasLifecycleCallbacks
*/
class ProductLang implements ArraySerializableInterface
{
/**
* @Column(type="integer")
* @Id
* @GeneratedValue
* @var integer
*/
protected $id;
/**
* @Column(type="string")
* @var string
*/
protected $productUid;
/**
* @Column(type="string")
* @var string
*/
protected $name;
/**
* @Column(type="string")
* @var string
*/
protected $description;
/**
* @param string $description
*/
public function setDescription($description)
{
$this->description = $description;
}
/**
* @return string
*/
public function getDescription()
{
return $this->description;
}
/**
* @param string $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @param string $productUid
*/
public function setProductUid($productUid)
{
$this->productUid = $productUid;
}
/**
* @return string
*/
public function getProductUid()
{
return $this->productUid;
}
/**
* @param mixed $product
*/
public function setProduct($product)
{
$this->product = $product;
}
/**
* @return mixed
*/
public function getProduct()
{
return $this->product;
}
public function serializeToArray($group) {
return array(
'name' => $this->getName(),
'description' => $this->getDescription()
);
}
} | true |
24e334a2ee5065fe8a19f0f3e733e180d014c2d5 | PHP | cnzhaor/bike | /application/admin/controller/Category.php | UTF-8 | 3,160 | 2.546875 | 3 | [
"Apache-2.0"
] | permissive | <?php
namespace app\admin\controller;
use think\Controller;
use think\Request;
use app\admin\model\Category as CatModel;
class Category extends Common
{
/**
* 显示栏目列表
*
* @return \think\Response
*/
public function index()
{
$catModel = new CatModel();
$cats = $catModel->getAll();
$this->assign('cats', $cats);
return view();
}
/**
* 显示创建栏目表单页.
*
* @return \think\Response
*/
public function create()
{
$catModel = new CatModel();
$cats = $catModel->getAll();
$this->assign('cats', $cats);
return view();
}
/**
* 保存新建的栏目
*
* @param \think\Request $request
* @return \think\Response
*/
public function save(Request $request)
{
if($request)
{
$catModel = new CatModel();
if($catModel->save($request->param()))
$this->success('新增成功!',url('index'));
else
$this->error('新增失败!');
}
}
/**
* 显示指定的栏目
*
* @param int $id
* @return \think\Response
*/
public function read($id)
{
//
}
/**
* 显示编辑栏目表单页.
*
* @param int $id
* @return \think\Response
*/
public function edit($id)
{
//获取要修改的对象
if($data = catModel::get($id)){
if(request()->isPost()){
if ($data -> save(input('post.')))
$this->success('修改成功!',url('index'));
else
$this->error('修改失败!');
}
else{
$catModel = new CatModel();
$cats = $catModel->getAll();
$cat = catModel::getById($id);
$this->assign([
'cats'=> $cats,
'cat'=> $cat,
]);
return view();
}
}
else
$this->error('非法操作!');
}
/**
* 保存更新的栏目
*
* @param \think\Request $request
* @param int $id
* @return \think\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* 删除指定栏目
*
* @param int $id
* @return \think\Response
*/
public function delete($id)
{
$pCat = catModel::getByPid($id);
if($pCat)
$this->error('请先删除它的子分类');
else{
if(catModel::destroy($id))
$this->success('删除成功!',url('index'));
else
$this->error('删除失败!');
}
}
public function sort()
{
if(request()->isPost()){
foreach (input('post.') as $key => $value){
catModel::update(['id' => $key, 'sort' => $value]);
}
$this->redirect('index');
}
else
$this->error('非法操作!',url('index'));
}
}
| true |
2587d3bfbb7e68b1c59e081cb487faba46b5fd45 | PHP | xemuj/Slice-Library | /application/controllers/Test.php | UTF-8 | 1,381 | 2.9375 | 3 | [
"MIT"
] | permissive | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* This is a test class to show you how to work with Slice-Library!
*/
class Test extends CI_Controller
{
public function __construct()
{
parent::__construct();
// Load the Slice-Library as any CodeIgniter library
$this->load->library('slice');
$this->load->helper('url');
}
public function index()
{
/**
* The with() method adds a pair of key/value data.
* The directive() method inserts a custom directive
* The view() method shows the page located at 'application/views/page.slice.php'
*/
$this->slice->with('full_name', 'John Doe')
->with('users', [['id' => 1, 'name' => 'John'], ['id' => 2, 'name' => 'Jane'], ['id' => 3, 'name' => 'Dave'], ['id' => 4, 'name' => 'Arthur'], ['id' => 5, 'name' => 'Michael'], ['id' => 6, 'name' => 'Ben']])
->with('members', [])
->with('rows', '0')
->directive('Test::custom_slice_directive');
// Slice-Library 1.3 comes with helpers to make things easier!
view('page');
}
/**
* This is a custom function that adds a custom directive to Slice-Library!
* This function finds for @slice('string') directive and shows the string
*/
static function custom_slice_directive($content)
{
$pattern = '/(\s*)@slice\s*\((\'.*\')\)/';
return preg_replace($pattern, '$1<?php echo "$2"; ?>', $content);
}
}
| true |