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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
dca0f7a72fcdccaef237648e864faafed610a064 | PHP | dennau/Jam | /Jam/Db/Select.php | UTF-8 | 10,819 | 2.734375 | 3 | [] | no_license | <?php
namespace Jam\Db;
use Jam\Db\QueryParts\Where;
use Jam\Db\QueryParts\Join;
use Jam\Db\QueryParts\Group;
use Jam\Db\QueryParts\Having;
use Jam\Db\QueryParts\Order;
use Jam\Db\QueryParts\Limit;
/**
* Class Select
* @package Jam\Db
* @method $this is($field, $value = null)
* @method $this notIs($field, $value = null)
* @method $this like($field, $value)
* @method $this notLike($field, $value)
* @method $this between($field, $value)
* @method $this notBetween($field, $value)
* @method $this regexp($field, $value)
* @method $this notRegexp($field, $value)
* @method $this gt($field, $value)
* @method $this gtEq($field, $value)
* @method $this lt($field, $value)
* @method $this ltEq($field, $value)
*
* @method $this glueAnd()
* @method $this glueOr()
* @method $this openBracket()
* @method $this closeBracket()
*
* @method $this getCount($field, $alias = null)
* @method $this getDistinct($field, $alias = null)
* @method $this getAverage($field, $alias = null)
* @method $this getMin($field, $alias = null)
* @method $this getMax($field, $alias = null)
* @method $this getSum($field, $alias = null)
* @method $this getSingleColumn($field)
*/
class Select {
/** @var Adapter */
protected $adapter;
/** @var Table */
protected $table;
protected $modelClassName;
protected $tableName = '';
protected $columns = [];
/** @var Where */
protected $where;
/** @var Join */
protected $join;
/** @var Group */
protected $group;
/** @var Having */
protected $having;
/** @var Order */
protected $order;
/** @var Limit */
protected $limit;
protected $binds = [];
protected $asArray = false;
protected $currentFunction = null;
public function __construct(Table $table) {
$this->table = $table;
$this->tableName = $table->getName();
$this->adapter = $table->getAdapter();
$this->modelClassName = str_replace('Table', 'Model', get_class($table));
$this->columns = [$table->getName() . '.*'];
}
protected function getWhere() {
if (!$this->where) {
$this->where = new Where();
}
return $this->where;
}
public function __call($method, $args) {
if (in_array($method, ['glueAnd', 'glueOr', 'openBracket', 'closeBracket'])) {
$this->getWhere()->simpleOperator($method);
return $this;
} elseif (in_array($method, ['gt', 'gtEq', 'lt', 'ltEq'])) {
$column = $this->grave($args[0]);
$value = $args[1];
$this->getWhere()->makeGL($column, $value, $method);
return $this;
} elseif (preg_match('!^(not|)(is)$!i', $method, $match)) {
$not = 'not' == $match[1] ? true : false;
$column = $this->grave($args[0]);
$value = isset($args[1]) ? $args[1] : null;
if (is_array($value)) {
$placeholders = [];
foreach ($value as $val) {
$placeholders[] = $this->bind($val);
}
$ine = 'in';
$value = '(' . implode(', ', $placeholders) . ')';
} elseif (null !== $value) {
$ine = 'equals';
$value = $this->bind($value);
} else {
$ine = 'null';
$value = '';
}
$this->getWhere()->makeIne($column, $value, $not, $ine);
return $this;
} elseif (preg_match('!^(not|)(like|between|regexp)$!i', $method, $match)) {
$not = 'not' == $match[1] ? true : false;
$lbr = lcfirst($match[2]);
$column = $this->grave($args[0]);
$value = $args[1];
if ('between' == $lbr) {
$value = (array) $value;
$value = $this->bind(min($value)) . ' AND ' . $this->bind(max($value));
} else {
$value = $this->bind($value);
}
$this->getWhere()->makeLBR($column, $value, $not, $lbr);
return $this;
} elseif (in_array($method, ['getCount', 'getDistinct', 'getAverage', 'getMin', 'getMax', 'getSum', 'getSingleColumn'])) {
$alias = !empty($args[1]) ? $args[1] : null;
$this->makeFunctions($method, $args[0], $alias);
return $this;
} elseif (preg_match('!^(with)(Via)?[A-Z]!', $method, $methodMatch)) {
$methodMatch = $methodMatch[1] . (!empty($methodMatch[2]) ? $methodMatch[2] : '');
$relationName = StringsHelper::getUnderscore(str_replace($methodMatch, '', $method));
$relation = $this->table->getRelation($relationName);
if (!$relation) {
throw new \LogicException(
sprintf('Unknown relation %s for %s table', $relationName, get_class($this))
);
}
$joins = $relation->getJoin();
if ('withVia' == $methodMatch) {
if ('many-to-many' != $relation->getType()) {
throw new \LogicException(
sprintf('Unknown Via table for relation %s', $relationName)
);
}
$join = $joins['via'];
$this->join($join['table'], $join['column1'], $join['column2'], 'LEFT OUTER JOIN');
/** @var Relations\ManyToMany $relation */
$relatedTableFieldInVia = $relation->getRelatedTableFieldInVia();
$value = !isset($args[1]) ? null : $args[1];
$operator = !isset($args[0]) ? null : $args[0];
if ($operator) {
$this->$operator($relatedTableFieldInVia, $value);
}
} else {
foreach ($joins as $join) {
$this->join($join['table'], $join['column1'], $join['column2']);
}
}
return $this;
}
throw new \BadMethodCallException(
sprintf('%s: unknown method %s::%s()', get_class($this), get_class($this), $method)
);
}
protected function makeFunctions($function, $column, $alias = null) {
$function = mb_convert_case(str_replace('get', '', $function), MB_CASE_UPPER);
if ('SINGLECOLUMN' == $function) {
$expression = $column;
} else {
$expression = $function . ('DISTINCT' == $function ? ' ' . $column : '(' . $column . ')' ) . (null === $alias ? '' : ' AS ' . $alias);
}
$this->columns = [$this->grave($expression)];
$this->currentFunction = $function;
}
protected function queryTable() {
return $this->grave($this->tableName);
}
protected function queryColumns() {
$columns = [];
foreach ($this->columns as $column) {
$columns[] = $this->grave(trim($column));
}
return implode(', ', $columns);
}
/**
* @param $table
* @param $column1
* @param $column2
* @param string $type
* @return $this
*/
public function join($table, $column1, $column2, $type = 'INNER JOIN') {
if (!$this->join) {
$this->join = new Join();
}
$this->join->add(
$this->grave($table),
$this->grave($column1),
$this->grave($column2),
mb_strtoupper($type)
);
return $this;
}
/**
* @param $column
* @return $this
*/
public function group($column) {
if (!$this->group) {
$this->group = new Group();
}
$this->group->add($this->grave($column));
return $this;
}
/**
* @param $column
* @param $operator
* @param $value
* @return $this
*/
public function having($column, $operator, $value) {
if (!$this->having) {
$this->having = new Having();
}
$this->having->add(
$this->grave($column),
$operator,
$this->bind($value)
);
return $this;
}
/**
* @param $column
* @param string $direction
* @return $this
*/
public function order($column, $direction = 'ASC') {
if (!$this->order) {
$this->order = new Order();
}
$this->order->add($this->grave($column), $direction);
return $this;
}
/**
* @param $limit
* @param null $offset
* @return $this
*/
public function limit($limit, $offset = null) {
if (!$this->limit) {
$this->limit = new Limit();
}
$this->limit->add($limit, $offset);
return $this;
}
/** @param $field
* @return mixed|string
*/
protected function grave($field) {
$fieldParts = explode(' ', $field);
$graveField = '';
foreach ($fieldParts as $part) {
if (!preg_match('!^[\d\.]+$!u', $part)) {
$part = str_replace('.', '`.`', $part);
}
if (preg_match('!COUNT\(|DISTINCT|AVG\(|MIN\(|MAX\(|SUM\(!iu', $field)) {
$part = str_replace(['(', ')'], ['(`', '`)'], $part);
}
$notInArray = (!in_array($part, array('AS', 'as', '=', '*', '+', '-')));
$notFunction = (!preg_match('!COUNT\(|DISTINCT|AVG\(|MIN\(|MAX\(|SUM\(!iu', $part));
$notFloat = (!preg_match('!^[\d\.]+$!u', $part));
if ($notInArray && $notFunction && $notFloat) {
$part = '`' . $part . '`';
}
$graveField .= ' ' . $part;
}
$graveField = str_replace('`*`','*', $graveField);
return preg_replace('!`{2,}!', '`', $graveField);
}
public function query() {
$query = 'SELECT SQL_CALC_FOUND_ROWS ' . $this->queryColumns() . ' FROM ' . $this->queryTable();
$query .= $this->join ? $this->join->query() : '';
$query .= $this->where ? $this->where->query() : '';
if ($this->group) {
$query .= $this->group->query();
$query .= $this->having ? $this->having->query() : '';
}
$query .= $this->order ? $this->order->query() : '';
$query .= $this->limit ? $this->limit->query() : '';
return preg_replace('!\s{2,}!', ' ', $query);
}
public function bind($value) {
$field = ':' . uniqid();
$this->binds[$field] = $value;
return $field;
}
public function binds() {
return $this->binds;
}
public function getAdapter() {
return $this->adapter;
}
public function asArray() {
$this->asArray = true;
return $this;
}
public function find() {
$query = $this->query();
$binds = $this->binds();
if ($this->currentFunction) {
if (in_array($this->currentFunction, ['DISTINCT', 'SINGLECOLUMN']) || $this->group) {
$rows = $this->getAdapter()->fetchColumn($query, $binds);
} else {
$rows = $this->getAdapter()->fetchOne($query, $binds);
}
$this->asArray();
$this->currentFunction = null;
} else {
$rows = $this->getAdapter()->fetchAll($query, $binds);
}
if ($this->asArray) {
$this->asArray = false;
return $rows;
}
$rows = null === $rows ? [] : $rows;
return new Table\RowSet($rows, $this->modelClassName);
}
public function findOne() {
$this->limit(1);
$query = $this->query();
$binds = $this->binds();
$rows = $this->getAdapter()->fetchRow($query, $binds);
if ($this->asArray) {
$this->asArray = false;
return $rows;
}
return null === $rows
? null
: new $this->modelClassName($rows)
;
}
public function found() {
return $this->getAdapter()->getFoundRows();
}
public function __toString() {
return str_replace(
array_keys($this->binds),
array_values($this->binds),
$this->query()
);
}
} | true |
ff66d05e5c599c2b762b3399022c24e44ece6bc1 | PHP | brucewu16899/SingleSignOn | /app/ViewHelpers/StatusLabel.php | UTF-8 | 1,146 | 2.8125 | 3 | [] | no_license | <?php
namespace App\ViewHelpers;
use App\ServiceStatus;
class StatusLabel
{
public static function forStatus(ServiceStatus $status)
{
$label = self::getLabel($status->group);
return self::labelFor($label, $status->status);
}
protected static function getLabel($group) {
switch ($group) {
case ServiceStatus::GROUP_GOOD:
$label = 'success';
break;
case ServiceStatus::GROUP_BAD:
$label = 'danger';
break;
case ServiceStatus::GROUP_WARNING:
$label = 'warning';
break;
default:
$label = 'default';
}
return $label;
}
public static function alertFor($status)
{
$label = self::getLabel($status['group']);
return '<div class="alert alert-' . $label . '" role="alert"><strong>' . $status['name'] . "</strong> " . $status['status'] . '</div>';
}
protected static function labelFor($label, $status)
{
return '<span class="label label-' . $label . '">' . $status . '</span>';
}
} | true |
3c174eb1fd3afc5948c344c74d0c553a432d0416 | PHP | holubv/fsedit_backend | /src/FSEdit/StatusExceptionMiddleware.php | UTF-8 | 1,188 | 2.71875 | 3 | [] | no_license | <?php
namespace FSEdit;
use FSEdit\Exception\BadRequestException;
use FSEdit\Exception\StatusException;
use Slim\App;
use Slim\Http\Request;
use Slim\Http\Response;
class StatusExceptionMiddleware
{
/**
* @var bool $debug
*/
private $debug;
/**
* StatusExceptionMiddleware constructor.
* @param App $app
*/
public function __construct(App $app)
{
$this->debug = $app->getContainer()->get('config')->debug;
}
/**
* @param Request $req
* @param Response $res
* @param $next
* @return Response
*/
public function __invoke($req, $res, $next)
{
$ex = null;
try {
return $next($req, $res);
} catch (StatusException $e) {
$ex = $e;
} catch (\InvalidArgumentException $e) {
$ex = new BadRequestException($e->getMessage(), $e);
}
$data = [
'message' => $ex->getMessage(),
'status' => $ex->getStatus()
];
if ($this->debug) {
$data['trace'] = $ex->getTraceAsString();
}
return $res->withJson($data, $ex->getStatus(), JSON_PRETTY_PRINT);
}
} | true |
5b2797ec0ceba84a0a59b850b3e30975d865d760 | PHP | nikhvj7/Velocity | /display/problems/problems_single.php | UTF-8 | 9,083 | 2.515625 | 3 | [] | no_license | <?php
require '../../query/conn.php';
if ((isset($_GET['car_id'])) && (isset($_GET['gqg_no'])) && (isset($_GET['company']))) {
$car_id = $_GET['car_id'];
$gqg_no = $_GET['gqg_no'];
$comp_id = $_GET['company'];
// echo $comp_id;
//Add this code for Dynamic
// $sql_cars = "SELECT DISTINCT(a.car_id),b.gqg_no
// FROM `problems` a
// JOIN `cars` b
// ON a.car_id = b.car_id
// WHERE a.car_id = '".$car_id."'";
$sql_cars = "SELECT DISTINCT(a.car_id),b.gqg_no
FROM `problems` a
JOIN `cars` b
ON a.car_id = b.car_id
WHERE a.car_id = '".$car_id."'";
$exe_cars = mysqli_query($conn,$sql_cars);
if(mysqli_num_rows($exe_cars) > 0){
// container div for styling
echo '<div id="problem_table_holder">';
echo '<table id="prob_table">';
echo '</tr>';
echo '<td>GQG NO</td>';
echo '<td>Date</td>';
echo '<td>Category</td>';
echo '<td>Description</td>';
echo '<td>Count</td>';
echo '</tr>';
// get distinct cars and gqg_nos
while($row_cars = mysqli_fetch_assoc($exe_cars)){
$car_id = $row_cars['car_id'];
$gqg_no = $row_cars['gqg_no'];
// $comp_id= $_GET['comp_id'];
// get distinct count of problems to render table
// we need to find rowspan for gqg
$sql_row_span = "SELECT count(distinct(prob_menu_id))
FROM problems
WHERE `car_id` = ".$car_id." ";
$exe_row_span = mysqli_query($conn,$sql_row_span);
$r_rspan = mysqli_fetch_assoc($exe_row_span);
$rowspan = $r_rspan['count(distinct(prob_menu_id))'];
// sorting problems car-wise
$sql_probs = "SELECT a.prob_menu_id, a.open_date,a.comp_id ,b.category, b.description
FROM problems a
JOIN `problem_menu` b
ON a.prob_menu_id = b.prob_menu_id
WHERE `car_id` = ".$car_id."
ORDER by b.category,a.prob_menu_id,a.open_date";
$exe_probs = mysqli_query($conn,$sql_probs);
// get distinct cars and gqg_nos
$prob_menu_id = null;
$open_date = null;
$counter = 0;
$tr_check = null;
// foreach problems per car
while($row_probs = mysqli_fetch_assoc($exe_probs)){
// this ends the table row
if( ($prob_menu_id != null) && ($prob_menu_id != $row_probs['prob_menu_id']) ){
echo '<td class="ptab_right">'.$counter.'</td>';
echo '</tr>';
}
// this starts the table row
if( ($prob_menu_id == null) || ($prob_menu_id != $row_probs['prob_menu_id']) ){
$counter = 1;
$prob_menu_id = $row_probs['prob_menu_id'];
$open_date = $row_probs['open_date'];
$category = $row_probs['category'];
$description = $row_probs['description'];
if($tr_check == null){
echo '<tr class="find_tr">';
echo '<td rowspan="'.$rowspan.'">'.$gqg_no.'</td>';
$tr_check = 1;
}else{
echo '<tr>';
}
// echo '<td>'.$prob_menu_id.'</td>';
echo '<td>'.$open_date.'</td>';
echo '<td>'.$category.'</td>';
echo '<td>'.$description.'</td>';
}else{
++$counter;
}
}// foreach problems per car
//last row doesnt get fired in loop
echo '<td class="ptab_right">'.$counter.'</td>';
echo '</tr>';
}// foreach car
echo '</table>';
echo '</div>';
}else{
echo'No Data Found';
}
}//if of isset function
?>
<!DOCTYPE html>
<html>
<head>
<title>CARS PROTO</title>
<link href="css/main.css" rel="stylesheet">
<link rel="apple-touch-icon" sizes="57x57" href="css/favi5/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="css/favi5/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="css/favi5/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="css/favi5/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="css/favi5/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="css/favi5/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="css/favi5/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="css/favi5/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="css/favi5/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="css/favi5/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="css/favi5/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="css/favi5/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="css/favi5/favicon-16x16.png">
<link rel="manifest" href="css/favi5/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="css/favi5/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<link href="https://fonts.googleapis.com/css?family=Roboto:400,500,700" rel="stylesheet">
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/main.js"></script>
<style type="text/css">
/*@override*/
#wrapper{overflow: hidden;}
#result{width: 964px;background-color: white;margin: 30px auto;}
.text_selected{color: #5264AE;font-weight: 500;}
#snackbar{
/*display: none;*/
position: fixed;bottom: -50px;
width: 400px;
height: 50px;
background-color: rgb(20,20,20);
color: white;
right: 0;
margin-right: 40px;
line-height: 50px;
padding-left: 24px;
}
.show_row{
height: 48px;line-height: 48px;padding-left: 24px;border-bottom: 1px solid rgb(240,240,240);
}
.inline{display: inline-block;vertical-align: top;}
.gqg_no{width: 180px;}
.num_val_small{width: 65px;text-align: right;padding-right: 10px;}
.num_val{width: 115px;text-align: right;padding-right: 10px;}
/*this has to be below- overides color above*/
.header{color: rgba(0,0,0,0.3);font-weight: 500;}
/*fab*/
#fab{
background: url('css/icons/ic_add.png') no-repeat center center;
height: 50px;width: 50px;
border-radius: 50%;
position: fixed;
background-color: #1aba7a;
z-index: 2;bottom: 0;right: 0;margin-bottom: 25px;margin-right: 25px;
-webkit-box-shadow: 0px 1px 4px 0px rgba(0,0,0,0.6);
-moz-box-shadow: 0px 1px 4px 0px rgba(0,0,0,0.6);
box-shadow: 0px 1px 4px 0px rgba(0,0,0,0.6);
}
#fab:active{background-color: #138e5d;}
/*forms*/
#form_main{background-color: white;}
.form_row{height: 52px;line-height: 52px;padding-left: 64px;color: #6b6b6b;}
.form_spacer{height: 20px;}
.form_inline{display: inline-block;/*background-color: green;*/}
.text_placeholder{width: 250px;}
.input_placeholder input{
font-size:17px;
padding:5px 10px 5px 5px;
display:block;
width:250px;
border:none;
border-bottom:1px solid #757575;
}
.input_placeholder input:focus{ outline:none; }
.form_divider{height: 20px;border-top: 1px solid rgb(230,230,230);margin-top: 5px;}
/* BOTTOM BARS*/
.bar { position:relative; display:block; width:265px; }
.bar:before, .bar:after {
content:'';
height:1.5px;
width:0;
bottom:1px;
position:absolute;
background:#5264AE;
transition:0.2s ease all;
-moz-transition:0.2s ease all;
-webkit-transition:0.2s ease all;
}
.bar:before {
left:50%;
}
.bar:after {
right:50%;
}
.input_placeholder input:focus ~ .bar:before, .input_placeholder input:focus ~ .bar:after {
width:50%;
}
.form_button_holder{padding-left: 64px;padding-top: 0px;padding-bottom: 40px;}
.mat_btn{
display: inline-block;
position: relative;
/*background-color: #4285f4;*/
background-color: rgb(100,100,100);
color: #fff;
width: 120px;
height: 32px;
line-height: 32px;
border-radius: 2px;
font-size: 0.9em;
text-align: center;
transition: box-shadow 0.2s cubic-bezier(0.4, 0, 0.2, 1);
transition-delay: 0.2s;
box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.26);
}
.mat_btn:hover{cursor: pointer;}
.mat_btn:active {
background-color: rgb(90,90,90);
box-shadow: 0 8px 17px 0 rgba(0, 0, 0, 0.2);
transition-delay: 0s;
}
#problem_table_holder{width: 65%;background: white;margin-left: 30px; border-radius: 5px;padding: 20px;}
table{border-collapse: collapse; margin-left: 30px;}
td{border: 1px solid rgb(200,200,200);font-size: 14px;color: rgb(20,20,20);padding: 5px;}
.ptab_right{text-align: right;}
.toggle{display: none;}
</style>
</head>
<body>
</body>
</html> | true |
226e19cf7f690544960a480dc57bc50e3840a344 | PHP | renmuell/SiteAudit | /admin/tableAndRun/class-site-audit-table.php | UTF-8 | 4,370 | 2.640625 | 3 | [] | no_license | <?php
if( ! class_exists( 'WP_List_Table' ) ) {
require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
}
class Site_Audit_Table extends WP_List_Table {
function __construct() {
global $status, $page;
parent::__construct(array(
'singular' => 'Site Audit',
'plural' => 'Site Audits'
));
}
function column_default($item, $column_name)
{
return $item[$column_name];
}
function column_cb($item)
{
return sprintf(
'<input type="checkbox" name="id[]" value="%s" />',
$item['id']
);
}
function column_author($item)
{
$user_info = get_userdata($item['author']);
return $user_info->user_login;
}
function column_created($item)
{
return date(get_option( 'date_format' ), strtotime($item['created']));;
}
function column_title($item)
{
$actions = array(
'edit' => sprintf('<a href="?page=site_audit_form&id=%s">%s</a>', $item['id'], __('Edit')),
'delete' => sprintf('<a href="?page=%s&action=delete&id=%s">%s</a>', $_REQUEST['page'], $item['id'], __('Delete')),
'run' => sprintf('<a href="?page=site_audit&id=%s">%s</a>', $item['id'], __('Run'))
);
return sprintf('%s %s',
$item['title'],
$this->row_actions($actions)
);
}
function extra_tablenav( $which ) {
if ( $which == "top" ){
}
if ( $which == "bottom" ){
}
}
function get_columns() {
return $columns= array(
'cb' => '<input type="checkbox" />', //Render a checkbox instead of text
'title' =>__('Title'),
'author' => __('Author'),
'created' => __('Created'),
);
}
public function get_sortable_columns() {
return $sortable = array(
'title' =>'title',
'author' =>'author',
'created' =>'created'
);
}
function get_bulk_actions()
{
$actions = array(
'delete' => 'Delete'
);
return $actions;
}
function process_bulk_action()
{
global $wpdb;
$table_name = $wpdb->prefix . SITE_AUDIT_TABLE;
if ('delete' === $this->current_action()) {
$ids = isset($_REQUEST['id']) ? $_REQUEST['id'] : array();
if (is_array($ids)) $ids = implode(',', $ids);
if (!empty($ids)) {
$wpdb->query("DELETE FROM $table_name WHERE id IN($ids)");
}
}
}
function prepare_items() {
global $wpdb;
$table_name = $wpdb->prefix . SITE_AUDIT_TABLE;
$per_page = 5; // constant, how much records will be shown per page
$columns = $this->get_columns();
$hidden = array();
$sortable = $this->get_sortable_columns();
// here we configure table headers, defined in our methods
$this->_column_headers = array($columns, $hidden, $sortable);
// [OPTIONAL] process bulk action if any
$this->process_bulk_action();
// will be used in pagination settings
$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $table_name");
// prepare query params, as usual current page, order by and order direction
$paged = isset($_REQUEST['paged']) ? max(0, intval($_REQUEST['paged'] - 1) * $per_page) : 0;
$orderby = (isset($_REQUEST['orderby']) && in_array($_REQUEST['orderby'], array_keys($this->get_sortable_columns()))) ? $_REQUEST['orderby'] : 'id';
$order = (isset($_REQUEST['order']) && in_array($_REQUEST['order'], array('asc', 'desc'))) ? $_REQUEST['order'] : 'asc';
// [REQUIRED] define $items array
// notice that last argument is ARRAY_A, so we will retrieve array
$this->items = $wpdb->get_results($wpdb->prepare("SELECT * FROM $table_name ORDER BY $orderby $order LIMIT %d OFFSET %d", $per_page, $paged), ARRAY_A);
// [REQUIRED] configure pagination
$this->set_pagination_args(array(
'total_items' => $total_items, // total items defined above
'per_page' => $per_page, // per page constant defined at top of method
'total_pages' => ceil($total_items / $per_page) // calculate pages count
));
}
} | true |
edecd65f674175a81e1a6d202b721d4a8760777d | PHP | kitlabs-cn/KitCryptBundle | /Service/OpensslService.php | UTF-8 | 5,000 | 2.78125 | 3 | [
"MIT"
] | permissive | <?php
namespace Kit\CryptBundle\Service;
class OpensslService
{
private $clients;
/**
*
* @param array $clients
*/
public function __construct($clients)
{
$this->clients = $clients;
}
/**
*
* @param string $string
* @param string $iv
* @return boolean|string
*/
public function encrypt($string, $name = 'default', $iv = null)
{
// hash
$key = (strcasecmp('AES-256-CBC', $this->getMethod($name)) == 0) ? hash('sha256', $this->getSecretKey($name)) : $this->getSecretKey($name);
$iv = ($iv === null) ? $this->getSecretIv($name) : $iv;
if ('aes-256-cbc' == $this->getMethod($name) && ! $this->checkIv($iv)) {
return false;
}
if (! $this->checkMethod($name)) {
return false;
}
return base64_encode(openssl_encrypt($string, $this->getMethod($name), $key, $this->getOption($name), $iv));
}
/**
*
* @param string $string
* @param string $iv
* @return boolean|string
*/
public function decrypt($string, $name = 'default', $iv = null)
{
// hash
$key = (strcasecmp('AES-256-CBC', $this->getMethod($name)) == 0) ? hash('sha256', $this->getSecretKey($name)) : $this->getSecretKey($name);
$iv = ($iv === null) ? $this->getSecretIv($name) : $iv;
if ('aes-256-cbc' == $this->getMethod($name) && ! $this->checkIv($iv)) {
return false;
}
if (! $this->checkMethod($name)) {
return false;
}
return openssl_decrypt(base64_decode($string), $this->getMethod($name), $key, $this->getOption($name), $iv);
}
/**
*
* @return boolean
*/
private function checkMethod($name = 'default')
{
return in_array($this->getMethod($name), array_map('strtolower', openssl_get_cipher_methods(true)));
}
/**
*
* @param string $iv
* @return boolean
*/
private function checkIv($iv)
{
// iv - encrypt method aes-256-cbc expects 16 bytes - else you will get a warning
return strlen($iv) === 16;
}
/**
*
* @param string $name
* @return string
*/
private function getSecretKey($name)
{
return $this->getClient($name)['secret_key'];
}
/**
*
* @param string $name
* @return string
*/
private function getSecretIv($name)
{
return $this->getClient($name)['secret_iv'];
}
/**
*
* @param string $name
* @return mixed
*/
private function getMethod($name)
{
return strtolower($this->getClient($name)['method']);
}
/**
*
* @param string $name
* @return mixed
*/
private function getOption($name)
{
return $this->getClient($name)['option'];
}
/**
*
* @param string $name
* @return array
*/
private function getClient($name)
{
return isset($this->clients[$name]) ? $this->clients[$name] : $this->clients['default'];
}
/**
* Decrypt data from a CryptoJS json encoding string
*
* @param mixed $passphrase
* @param mixed $jsonString
* @return mixed
*/
function cryptoJsAesDecrypt($passphrase, $ct, $iv, $s)
{
try {
$salt = hex2bin($s);
$iv = hex2bin($iv);
} catch (\Exception $e) {
return false;
}
$ct = base64_decode($ct);
$concatedPassphrase = $passphrase . $salt;
$md5 = array();
$md5[0] = md5($concatedPassphrase, true);
$result = $md5[0];
for ($i = 1; $i < 3; $i ++) {
$md5[$i] = md5($md5[$i - 1] . $concatedPassphrase, true);
$result .= $md5[$i];
}
$key = substr($result, 0, 32);
$data = openssl_decrypt($ct, 'aes-256-cbc', $key, true, $iv);
return trim($data, '"');
}
/**
* Encrypt value to a cryptojs compatiable json encoding string
*
* @param mixed $passphrase
* @param mixed $value
* @return string
*/
function cryptoJsAesEncrypt($passphrase, $value)
{
$salt = openssl_random_pseudo_bytes(8);
$salted = '';
$dx = '';
while (strlen($salted) < 48) {
$dx = md5($dx . $passphrase . $salt, true);
$salted .= $dx;
}
$key = substr($salted, 0, 32);
$iv = substr($salted, 32, 16);
$encrypted_data = openssl_encrypt(json_encode($value), 'aes-256-cbc', $key, true, $iv);
$data = array(
"ct" => base64_encode($encrypted_data),
"iv" => bin2hex($iv),
"s" => bin2hex($salt)
);
return json_encode($data);
}
} | true |
5335516c17ee4bb8ee832eae0682b5e0eadb8844 | PHP | uzairlive/hcp-engagement-portal | /app/Helpers/FileManager.php | UTF-8 | 1,530 | 2.734375 | 3 | [
"MIT"
] | permissive | <?php
use Carbon\Carbon;
use Illuminate\Support\Facades\File;
function uploadFile(object $file, string $uploadPath, string $oldFile = null)
{
// $files it can be array incase of multi files, and it can be object in case of single file
$fileNameToStore = "";
$file_path = public_path($oldFile);
if($file_path){
if(file_exists($oldFile)){
unlink($file_path);
}
}
if(gettype($file) == 'object'){
$fileNameToStore = $file->hashName();
// if (config('app.env') == 'production'){
// $path = $file->move($uploadPath, $fileNameToStore);
// } else{
$path = $file->move(public_path($uploadPath), $fileNameToStore);
// }
}
return $fileNameToStore;
}
function deleteFile(string $fileName, string $uploadPath)
{
$file_path = public_path($fileName);
if($file_path){
if(file_exists($file_path)){
unlink($file_path);
}
}
}
function avatarsPath()
{
return 'storage/avatars/';
}
function postPath()
{
return 'storage/post/';
}
function gamificationPath()
{
return 'storage/gamification/';
}
function gamificationDocPath()
{
return 'storage/gamificationDoc/';
}
function clinicalPath()
{
return 'storage/clinical/';
}
function clinicalDocPath()
{
return 'storage/clinicalDoc/';
}
function webinarPath()
{
return 'storage/webinar/';
}
function virtualPath()
{
return 'storage/virtual/';
}
function trainingPath()
{
return 'storage/training/';
}
| true |
f7ec01be67833e7b26504addbfd6b1f28fc235d8 | PHP | lord2800/dynamo | /tests/ProxyTest.php | UTF-8 | 868 | 2.90625 | 3 | [
"MIT"
] | permissive | <?php
namespace Dynamo\Tests;
use Dynamo\Proxy;
class A {
public $value = 5;
public $passed;
public function __construct($v) { $this->passed = $v; }
public function getStr() { return 'test'; }
public static function notVisible() { }
}
class ProxyA extends Proxy {
public function __construct($v) { parent::__construct('Dynamo\\Tests\\A', $v); }
}
class ProxyTest extends \PHPUnit_Framework_TestCase {
private $proxy;
public function setUp() {
$this->proxy = new ProxyA('info');
}
public function testProxyHasAllMethodsOfOriginal() {
$this->assertEquals(5, $this->proxy->value);
$this->proxy->value = 10;
$this->assertEquals(10, $this->proxy->value);
$this->assertEquals('info', $this->proxy->passed);
$this->assertEquals('test', $this->proxy->getStr());
$this->assertTrue(isset($this->proxy->passed));
unset($this->proxy->passed);
}
}
| true |
a906da256f74e32a62bb4dfbf99843683a4cfb13 | PHP | TamNguyenCG/PHP-Exercise | /Array-DeleteValue/index.php | UTF-8 | 1,564 | 3.21875 | 3 | [] | no_license | <!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Delete Value in Array</title>
<style>
h1{
color: green;
}
span {
color: red;
}
</style>
</head>
<body>
<form action="" method="get">
<h1>Check and Delete value in Array</h1>
<table>
<tr>
<td>Input value of array(separate with ",")<span>*</span>:</td>
<td><input type="text" name="input_array"><br></td>
</tr>
<tr>
<td>Input the value that you want to delete<span>*</span>:</td>
<td><input type="text" name="delete_value"><br></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="delete_ele" value="Delete"></td>
</tr>
</table>
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "GET") {
$value = $_GET["input_array"];
$delete = $_GET["delete_value"];
//Tách chuỗi thành 1 mảng
$arr = explode(",", $value);
$flag = false;
for ($i = 0; $i < count($arr); $i++) {
if ($delete == $arr[$i]) {
array_splice($arr, $i, 1);
$flag = true;
}
}
if ($flag) {
echo '<pre>';
print_r($arr);
echo '</pre>';
} else {
echo "<span>Cannot found $delete in array</span>";
}
}
?>
</body>
</html> | true |
388bb0bf0d07145bf0eec5aabe1e707f1915aa72 | PHP | oikenfight/web-md-editor | /laravel/app/Entities/Contracts/FolderInterface.php | UTF-8 | 2,062 | 2.609375 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types=1);
namespace App\Entities\Contracts;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
/**
* FolderInterface interface
*
* @package App\Entities\Contracts
* @property int $id
* @property int $user_id
* @property int $rack_id
* @property string $name
* @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at
* @property \Illuminate\Support\Carbon|null $deleted_at
* @property-read \Illuminate\Database\Eloquent\Collection|\App\Entities\Note[] $notes
* @property-read array $note_ids
* @property-read \App\Entities\Rack $rack
* @property-read \App\Entities\User $user
* @method static \Illuminate\Database\Eloquent\Builder|\App\Entities\Folder newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder|\App\Entities\Folder newQuery()
* @method static \Illuminate\Database\Eloquent\Builder|\App\Entities\Folder query()
* @method static \Illuminate\Database\Eloquent\Builder|\App\Entities\Folder whereCreatedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder|\App\Entities\Folder whereDeletedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder|\App\Entities\Folder whereId($value)
* @method static \Illuminate\Database\Eloquent\Builder|\App\Entities\Folder whereName($value)
* @method static \Illuminate\Database\Eloquent\Builder|\App\Entities\Folder whereRackId($value)
* @method static \Illuminate\Database\Eloquent\Builder|\App\Entities\Folder whereUpdatedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder|\App\Entities\Folder whereUserId($value)
*/
interface FolderInterface extends EntityInterface
{
/**
* @return array
*/
public function getNoteIdsAttribute(): array;
/**
* @return BelongsTo|UserInterface
*/
public function user();
/**
* @return BelongsTo|RackInterface
*/
public function rack();
/**
* @return hasMany|NoteInterface[]
*/
public function notes();
}
| true |
0a30bf5fb37d13d05e426122811f5fd6d23cfefa | PHP | karbassi/PHP-Metacritic | /demo.php | UTF-8 | 667 | 2.515625 | 3 | [] | no_license | <?php
require_once 'metacritic.php';
// Retrieve the score for Rock Band for XBOX 360
$metacritic = new Metacritic(array('title' => 'Rock Band'));
?>
<h1>Demo File</h1>
<h2>Grabbing score #1</h2>
<h3>Title:</h3>
<p><?php echo $metacritic->title; ?></p>
<h3>Score:</h3>
<p><?php echo $metacritic->score; ?></p>
<h3>Error:</h3>
<p><?php echo $metacritic->error; ?></p>
<?php
$metacritic->getFresh();
?>
<h2>Grabbing score #2</h2>
<h3>Title:</h3>
<p><?php echo $metacritic->title; ?></p>
<h3>Score:</h3>
<p><?php echo $metacritic->score; ?></p>
<h3>Error:</h3>
<p><?php echo $metacritic->error; ?></p>
| true |
847aa972f151c193ea10546038f4ac2ac3c8b716 | PHP | wangkaikai12345/edu | /app/Http/Controllers/Web/CalculateController.php | UTF-8 | 3,023 | 2.546875 | 3 | [] | no_license | <?php
namespace App\Http\Controllers\Web;
use App\Enums\CouponStatus;
use App\Enums\ProductType;
use App\Http\Controllers\Controller;
use App\Models\Classroom;
use App\Models\Coupon;
use App\Models\Plan;
use App\Models\Recharging;
use App\Rules\CustomEnumRule;
use Illuminate\Http\Request;
class CalculateController extends Controller
{
/**
* @SWG\Post(
* path="/calculate-price",
* tags={"web/coupon"},
* summary="计算价格",
* description="在填写完优惠券时,调用本接口,自动根据优惠码计算优惠额度",
* @SWG\Parameter(name="coupon_code",type="string",in="formData",required=true,description="优惠码"),
* @SWG\Parameter(name="product_type",type="string",in="formData",enum={"plan","recharging","classroom"},required=true,description="商品类型行:课程版本/充值订单"),
* @SWG\Parameter(name="product_id",type="integer",in="formData",required=true,description="商品ID"),
* @SWG\Response(response=200,description="单位:分;数据结构:{'pay_amount':1}"),
* security={
* {"Bearer": {}}
* },
* )
*/
public function store(Request $request)
{
$this->validate($request, [
'coupon_code' => 'required|exists:coupons,code',
'product_type' => ['required', new CustomEnumRule(ProductType::class)],
'product_id' => 'required|integer'
]);
$coupon = Coupon::find($request->coupon_code);
switch ($request->product_type) {
case ProductType::PLAN:
$product = Plan::findOrFail($request->product_id);
break;
case ProductType::CLASSROOM:
$product = Classroom::findOrFail($request->product_id);
break;
case ProductType::RECHARGING:
$product = Recharging::findOrFail($request->product_id);
break;
default:
$this->response->errorBadRequest(__('Product not found.'));
}
// 状态
if ($coupon->status === CouponStatus::USED) {
$this->response->errorBadRequest(__('Coupon code has been used.'));
}
// 有效期
if ($coupon->expired_at->lt(now())) {
$this->response->errorBadRequest(__('Coupon code is out of date.'));
}
// 指定使用人
if ($coupon->consumer_id && $coupon->consumer_id !== auth()->id()) {
$this->response->errorBadRequest(__('Coupon code has been activated.'));
}
// 适用商品
if ($coupon->product_type && ($coupon->product_type !== $request->product_type || $coupon->product_id !== (int)$request->product_id)) {
$this->response->errorBadRequest(__('Coupon code does not apply.'));
}
$payAmount = $coupon->calculatePrice($product->price);
return $this->response->array([
'price' => $product->price,
'pay_amount' => $payAmount,
]);
}
}
| true |
ef738b621f2a4c4d07ba834418611aa50bf8ec0b | PHP | anilkobakoglu/php-oop | /sihirli metodlar/function__clone.php | UTF-8 | 147 | 2.90625 | 3 | [] | no_license | <?php
class deneme{
public function __clone(){
echo"bu clone methotudur.";
}
}//class end
$class=new deneme();
$b=clone $class;
?> | true |
909f8b741cb0d5210776ce7e5b4958197c7c242f | PHP | au-research/ANDS-ResearchData-Registry | /applications/registry/services/method_handlers/registry_object_handlers/subjects.php | UTF-8 | 1,548 | 2.625 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once(SERVICES_MODULE_PATH . 'method_handlers/registry_object_handlers/_ro_handler.php');
/**
* Subjects handler
* @author Minh Duc Nguyen <minh.nguyen@ands.org.au>
* @return array list of subjects from SOLR index
*/
class Subjects extends ROHandler {
function handle() {
$result = array();
if($this->ro->status == 'PUBLISHED')
{
if($this->index && isset($this->index['subject_value_resolved'])) {
//subject_value_unresolved, subject_value_resolved, subject_type, subject_vocab_uri
foreach($this->index['subject_value_unresolved'] as $key=>$sub) {
$result[] = array(
'subject' => $sub,
'resolved' => $this->index['subject_value_resolved'][$key],
'type' => $this->index['subject_type'][$key],
'vocab_uri' => isset($this->index['subject_vocab_uri'][$key]) ? $this->index['subject_vocab_uri'][$key] : ''
);
}
}
}
else{
$subjects = $this->ro->processSubjects();
foreach($subjects as $subject) {
$result[] = array(
'subject' => $subject['value'],
'resolved' => $subject['resolved'],
'type' => $subject['type'],
'vocab_uri' => $subject['uri'],
);
}
}
return $result;
}
} | true |
cb6885580c2e1623ae3af08a217a656d3069eccc | PHP | umitcanb/CardsGame | /tests/AutomaticPlayerTest.php | UTF-8 | 2,117 | 3.125 | 3 | [] | no_license | <?php
use PHPUnit\Framework\TestCase;
use App\AutomaticPlayer;
use App\Card;
final class AutomaticPlayerTest extends TestCase
{
public function test_player_plays_random(){
$cardsArray = [new Card(["red","♥"], "A"), new Card(["red","♦"], "1"), new Card(["black","♠"], "10")];
$player = new AutomaticPlayer($cardsArray);
$cardPlayed = $player->play();
$this->assertContains($cardPlayed, $cardsArray);
$this->assertNotContains($cardPlayed, $player->getCards());
$this->assertContains($cardPlayed, $player->getHistory());
}
/*
public function test_select_and_play_card(){
$cardsArray = [new Card(["red","♥"], "A"), new Card(["red","♦"], "1"), new Card(["black","♠"], "10")];
$player = new Player($cardsArray);
$selectedCard = $player->play(0);
$this->assertEquals("A", $selectedCard->getValue());
$this->assertEquals("♥", $selectedCard->getSymbol()->getShape());
$this->assertContains($selectedCard, $cardsArray);
$this->assertNotContains($selectedCard, $player->getCards());
$this->assertContains($selectedCard, $player->getHistory());
}
public function test_cannot_play_if_selected_card_index_is_out_of_range(){
$cardsArray = [new Card(["red","♥"], "A"), new Card(["red","♦"], "1"), new Card(["black","♠"], "10")];
$player = new Player($cardsArray);
$selectedCard = $player->play(4);
$this->expectOutputString("the number indicated does not correspond to any card in your hand");
}
/* The test below was meatn to test a private method that is already interacted by the public play method that is tested above.
public function test_check_if_index_number_is_in_the_range(){
$cardsArray = [new Card(["red","♥"], "A"), new Card(["red","♦"], "1"), new Card(["black","♠"], "10")];
$player = new Player($cardsArray);
$inRange = $player->checkIndexRange(0);
$this->assertTrue($inRange);
$inRange = $player->checkIndexRange(4);
$this->assertFalse($inRange);
}
*/
}
| true |
2335955122d3f0decbd14347ac4581d01e87d729 | PHP | AlexandrTs/test-symfony-api | /src/Request/MathDivideRequest.php | UTF-8 | 1,666 | 2.734375 | 3 | [] | no_license | <?php
declare(strict_types=1);
namespace App\Request;
use App\Resolver\RequestObjectResolver;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
/**
* Класс для валидации запроса апи на деление одного числа на другое
*
* @package App\Request
*/
class MathDivideRequest extends RequestObjectResolver
{
/**
* Возвращает список constraint для валидации параметров запроса
*
* @return Assert\Collection
*/
public function rules(): Assert\Collection
{
$constraints = [
new Assert\Type([
'type' => 'numeric',
'message' => 'Value must be valid integer of float',
]),
new Assert\Callback(function($value, ExecutionContextInterface $context){
$check = $value + 0;
if ((is_float($check) || is_int($check)) && is_infinite($check)) {
$context->buildViolation('Value is too big but must be valid integer of float')
->addViolation();
}
}),
];
return new Assert\Collection([
'divisible' => new Assert\Sequentially($constraints),
'divisor' => new Assert\Sequentially(array_merge(
$constraints,
[
new Assert\NotEqualTo([
'value' => 0,
'message' => 'Divisor cannot be zero',
])
]
))
]);
}
} | true |
23f509c7f72f87620026dc16d740dc165718a32d | PHP | mkoplitz/Crew-Chief | /2/php/insert/insert-new-client.php | UTF-8 | 853 | 2.984375 | 3 | [] | no_license | <?php
session_start();
$servername = "localhost";
$username = "apache";
$password = "apache";
$dbname = '05-Company_' . $_SESSION['Company_ID'];
$name = $_GET['name'];
$address1 = $_GET['addr1'];
$address2 = $_GET['addr2'];
$city = $_GET['city'];
$state = $_GET['state'];
$zip = $_GET['zip'];
$phoneNum = $_GET['phone'];
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO Clients (Name, Address1, Address2, City, State, Zip, Phone_Number)
VALUES ('$name', '$address1', '$address2', '$city', '$state', '$zip', '$phoneNum')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?> | true |
41d5dee7863341a09594231eea587db426b813c1 | PHP | warkol66/egytca_phpmvc53 | /WEB-INF/lib/pear/propel_1.3/propel/engine/builder/sql/DDLBuilder.php | UTF-8 | 5,570 | 2.578125 | 3 | [] | no_license | <?php
/*
* $Id: DDLBuilder.php 1025 2008-04-09 10:08:49Z hans $
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information please see
* <http://propel.phpdb.org>.
*/
require_once 'propel/engine/builder/DataModelBuilder.php';
/**
* Baseclass for SQL DDL-building classes.
*
* DDL-building classes are those that build all the SQL DDL for a single table.
*
* @author Hans Lellelid <hans@xmpl.org>
* @package propel.engine.builder.sql
*/
abstract class DDLBuilder extends DataModelBuilder {
/**
* Builds the SQL for current table and returns it as a string.
*
* This is the main entry point and defines a basic structure that classes should follow.
* In most cases this method will not need to be overridden by subclasses.
*
* @return string The resulting SQL DDL.
*/
public function build()
{
$script = "";
$this->addTable($script);
$this->addIndices($script);
$this->addForeignKeys($script);
return $script;
}
/**
* Gets the name to use for creating a sequence for the current table.
*
* This will create a new name or use one specified in an id-method-parameter
* tag, if specified.
*
* @return string Sequence name for this table.
*/
public function getSequenceName()
{
$table = $this->getTable();
static $longNamesMap = array();
$result = null;
if ($table->getIdMethod() == IDMethod::NATIVE) {
$idMethodParams = $table->getIdMethodParameters();
$maxIdentifierLength = $table->getDatabase()->getPlatform()->getMaxColumnNameLength();
if (empty($idMethodParams)) {
if (strlen($table->getName() . "_SEQ") > $maxIdentifierLength) {
if (!isset($longNamesMap[$table->getName()])) {
$longNamesMap[$table->getName()] = strval(count($longNamesMap) + 1);
}
$result = substr($table->getName(), 0, $maxIdentifierLength - strlen("_SEQ_" . $longNamesMap[$table->getName()])) . "_SEQ_" . $longNamesMap[$table->getName()];
}
else {
$result = substr($table->getName(), 0, $maxIdentifierLength -4) . "_SEQ";
}
} else {
$result = substr($idMethodParams[0]->getValue(), 0, $maxIdentifierLength);
}
}
return $result;
}
/**
* Builds the DDL SQL for a Column object.
* @return string
*/
public function getColumnDDL(Column $col)
{
$platform = $this->getPlatform();
$domain = $col->getDomain();
$sb = "";
$sb .= $this->quoteIdentifier($col->getName()) . " ";
$sb .= $domain->getSqlType();
if ($platform->hasSize($domain->getSqlType())) {
$sb .= $domain->printSize();
}
$sb .= " ";
$sb .= $col->getDefaultSetting() . " ";
$sb .= $col->getNotNullString() . " ";
$sb .= $col->getAutoIncrementString();
return trim($sb);
}
/**
* Creates a delimiter-delimited string list of column names, quoted using quoteIdentifier().
* @param array Column[] or string[]
* @param string $delim The delimiter to use in separating the column names.
* @return string
*/
public function getColumnList($columns, $delim=',')
{
$list = array();
foreach ($columns as $col) {
if ($col instanceof Column) {
$col = $col->getName();
}
$list[] = $this->quoteIdentifier($col);
}
return implode($delim, $list);
}
/**
* This function adds any _database_ start/initialization SQL.
* This is designed to be called for a database, not a specific table, hence it is static.
* @return string The DDL is returned as astring.
*/
public static function getDatabaseStartDDL()
{
return '';
}
/**
* This function adds any _database_ end/cleanup SQL.
* This is designed to be called for a database, not a specific table, hence it is static.
* @return string The DDL is returned as astring.
*/
public static function getDatabaseEndDDL()
{
return '';
}
/**
* Resets any static variables between building a SQL file for a database.
*
* Theoretically, Propel could build multiple .sql files for multiple databases; in
* many cases we don't want static values to persist between these. This method provides
* a way to clear out static values between iterations, if the subclasses choose to implement
* it.
*/
public static function reset()
{
// nothing by default
}
/**
* Adds table definition.
* @param string &$script The script will be modified in this method.
*/
abstract protected function addTable(&$script);
/**
* Adds index definitions.
* @param string &$script The script will be modified in this method.
*/
abstract protected function addIndices(&$script);
/**
* Adds foreign key constraint definitions.
* @param string &$script The script will be modified in this method.
*/
abstract protected function addForeignKeys(&$script);
}
| true |
eef8f1cfb7134f722d4855da6bb9676863ac2308 | PHP | doctrine/dbal | /tests/Functional/Platform/DefaultExpressionTest.php | UTF-8 | 2,465 | 2.578125 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types=1);
namespace Doctrine\DBAL\Tests\Functional\Platform;
use Doctrine\DBAL\Platforms\AbstractMySQLPlatform;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Platforms\OraclePlatform;
use Doctrine\DBAL\Schema\Table;
use Doctrine\DBAL\Tests\FunctionalTestCase;
use Doctrine\DBAL\Types\Types;
use function sprintf;
class DefaultExpressionTest extends FunctionalTestCase
{
public function testCurrentDate(): void
{
$platform = $this->connection->getDatabasePlatform();
if ($platform instanceof AbstractMySQLPlatform) {
self::markTestSkipped('Not supported on MySQL');
}
$this->assertDefaultExpression(Types::DATE_MUTABLE, static function (AbstractPlatform $platform): string {
return $platform->getCurrentDateSQL();
});
}
public function testCurrentTime(): void
{
$platform = $this->connection->getDatabasePlatform();
if ($platform instanceof AbstractMySQLPlatform) {
self::markTestSkipped('Not supported on MySQL');
}
if ($platform instanceof OraclePlatform) {
self::markTestSkipped('Not supported on Oracle');
}
$this->assertDefaultExpression(Types::TIME_MUTABLE, static function (AbstractPlatform $platform): string {
return $platform->getCurrentTimeSQL();
});
}
public function testCurrentTimestamp(): void
{
$this->assertDefaultExpression(Types::DATETIME_MUTABLE, static function (AbstractPlatform $platform): string {
return $platform->getCurrentTimestampSQL();
});
}
private function assertDefaultExpression(string $type, callable $expression): void
{
$platform = $this->connection->getDatabasePlatform();
$defaultSql = $expression($platform, $this);
$table = new Table('default_expr_test');
$table->addColumn('actual_value', $type);
$table->addColumn('default_value', $type, ['default' => $defaultSql]);
$this->dropAndCreateTable($table);
$this->connection->executeStatement(
sprintf(
'INSERT INTO default_expr_test (actual_value) VALUES (%s)',
$defaultSql,
),
);
$row = $this->connection->fetchNumeric('SELECT default_value, actual_value FROM default_expr_test');
self::assertNotFalse($row);
self::assertEquals(...$row);
}
}
| true |
bfa6e9b55fa948696d6814ab6016b783c02e1141 | PHP | gachakra/php-enum | /examples/BasicMethods/Continent.php | UTF-8 | 2,933 | 3.125 | 3 | [
"MIT"
] | permissive | <?php
/**
* Created by IntelliJ IDEA.
* User: gachakra
* Date: 2019-06-22
* Time: 23:54
*/
declare(strict_types=1);
namespace Gachakra\PhpEnum\Examples\BasicMethods;
require_once __DIR__ . "/../../vendor/autoload.php";
use Gachakra\PhpEnum\Enum;
/**
* Class Continent
*
* @method static static AFRICA()
* @method static static ASIA()
* @method static static EUROPE()
* @method static static NORTH_AMERICA()
* @method static static SOUTH_AMERICA()
* @method static static ANTARCTICA()
* @method static static AUSTRALIA()
*/
final class Continent extends Enum {
private const AFRICA = 1;
private const ASIA = 2;
private const EUROPE = 3;
private const NORTH_AMERICA = 4;
private const SOUTH_AMERICA = 5;
private const ANTARCTICA = 6;
private const AUSTRALIA = 7;
}
/**
* instance methods
*/
{
assert(Continent::AFRICA()->name() === 'AFRICA');
assert(Continent::AFRICA()->value() === 1);
assert(Continent::AFRICA()->__toString() === '1');
}
/**
* class methods
*/
{
assert(Continent::of('AFRICA')->equals(Continent::AFRICA()));
assert(Continent::fromValue(1)->equals(Continent::AFRICA()));
assert(Continent::elements()['AFRICA']->equals(Continent::AFRICA()));
assert(Continent::valueToElement()[1]->equals(Continent::AFRICA()));
}
/**
* class methods for array
*/
{
assert(Continent::elements() === [
'AFRICA' => Continent::AFRICA(),
'ASIA' => Continent::ASIA(),
'EUROPE' => Continent::EUROPE(),
'NORTH_AMERICA' => Continent::NORTH_AMERICA(),
'SOUTH_AMERICA' => Continent::SOUTH_AMERICA(),
'ANTARCTICA' => Continent::ANTARCTICA(),
'AUSTRALIA' => Continent::AUSTRALIA(),
]);
assert(Continent::constants() === [
'AFRICA' => 1,
'ASIA' => 2,
'EUROPE' => 3,
'NORTH_AMERICA' => 4,
'SOUTH_AMERICA' => 5,
'ANTARCTICA' => 6,
'AUSTRALIA' => 7,
]);
assert(Continent::names() === [
'AFRICA',
'ASIA',
'EUROPE',
'NORTH_AMERICA',
'SOUTH_AMERICA',
'ANTARCTICA',
'AUSTRALIA'
]);
assert(Continent::values() === [1, 2, 3, 4, 5, 6, 7]);
assert(Continent::toStrings() === [
'AFRICA' => '1',
'ASIA' => '2',
'EUROPE' => '3',
'NORTH_AMERICA' => '4',
'SOUTH_AMERICA' => '5',
'ANTARCTICA' => '6',
'AUSTRALIA' => '7',
]);
} | true |
9d2770d653329a33772c9f35a3f28909a1077faf | PHP | sanket-neosoft/Crud-oops-Assignment | /classes/add.class.php | UTF-8 | 1,252 | 2.859375 | 3 | [] | no_license | <?php
include("common.class.php");
class Add extends Connection
{
public function __construct($username, $email, $name, $age, $city, $image, $image_tmp)
{
// input fields
$this->username = $username;
$this->email = $email;
$this->name = $name;
$this->age = $age;
$this->city = $city;
$this->image = $image;
$this->image_tmp = $image_tmp;
// errors check
$errors = $this->errorHandler($this->username, $this->email, $this->name, $this->age, $this->city, $this->image);
if ($errors === true) {
// uploding file
$uploadImage = $this->imageUpload($image, $image_tmp);
if ($uploadImage === true) {
// inserting data to db
$add = $this->connect()->prepare("INSERT INTO employees(`username`, `email`, `name`, `age`, `city`, `image`) VALUES(?, ?, ?, ?, ?, ?);");
$add->execute(array($this->username, $this->email, $this->name, $this->age, $this->city, $this->filename));
} else {
// returning error
return $uploadImage;
}
} else {
// returning error
return $errors;
}
}
}
| true |
b624623d75c8f8c9acc74cf87172e37df3217bd6 | PHP | opstalent/elastica-bundle | /Model/ScorableInterface.php | UTF-8 | 295 | 2.625 | 3 | [] | no_license | <?php
namespace Opstalent\ElasticaBundle\Model;
/**
* @author Patryk Grudniewski <patgrudniewski@gmail.com>
* @package Opstalent\ElasticaBundle
*/
interface ScorableInterface
{
/**
* @param float $score
* @return ScorableInterface
*/
public function setScore(float $score) : ScorableInterface;
}
| true |
f650acaa75eae08c93f5a812ae24282c77a1903c | PHP | yinming93/xyt | /wxdevelop/dev_snlh/index.php | UTF-8 | 20,898 | 2.703125 | 3 | [] | no_license | <?php
/*
* 1.一次工作可以使用页面调试工具完成:如第三方服务器配置,自定义菜单等
* 2.修改自定义菜单不用删除,直接创建即可
*
*
* author: WangKai
* date: 2015.07.20
* mail:wangkaisd@163.com
*/
//加载公共函数
//include "func.php";
//声明一个常量定义一个token的值
define("TOKEN", "dev_snlh1013");
//通过WhChat类,创建一个对象
$wechatObj = new WeChat();
//如果没有通过GET收到echostr字符串,说明不是在使用token验证
if(!isset($_GET['echostr'])){
//调用WeChat对象中的方法响应用户消息
$wechatObj->responseMsg();
}else{
//验证token
$wechatObj->valid();
}
class WeChat{
//验证签名 -- 开发者首次提交验证申请时
public function valid(){
$echoStr = $_GET["echostr"];
$signature = $_GET["signature"];
$timestamp = $_GET["timestamp"];
$nonce = $_GET["nonce"];
$token = TOKEN;
$tmpArr = array($token, $timestamp, $nonce);
sort($tmpArr);
$tmpStr = implode($tmpArr);
$tmpStr = sha1($tmpStr);
if($tmpStr == $signature){
echo $echoStr;
exit;
}
}
//===========================================================================================
//响应消息
public function responseMsg(){
//接收微信服务器传来的XML数据包
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
if(!empty($postStr)){
//将接收到的XML格式字符串写入日志,R表示接收数据
$this->logger("接收消息:\n".$postStr);
//XML 转化为 对象格式
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
//获取数据类型
$RX_TYPE = trim($postObj->MsgType);
//将接收到的XML格式字符串写入日志,R表示接收数据
$this->logger("接收消息,'.$RX_TYPE.':\n".$postStr);
//消息类型分离
switch($RX_TYPE){
case "event":
$result = $this->receiveEvent($postObj); //事件
break;
case "text":
$result = $this->receiveText($postObj); //文本
break;
case "image":
$result = $this->receiveImage($postObj); //图片
break;
case "voice":
$result = $this->receiveVoice($postObj); //语音
break;
case "video":
$result = $this->receiveVideo($postObj); //视频
break;
case "link":
$result = $this->receiveLink($postObj); //链接
break;
default:
$result = "unknown msg type: ".$RX_TYPE;
break;
}
//将响应的XML消息再次写入日志,T表示响应消息
$this->logger("回复消息,类型是'.$RX_TYPE.':\n".$result);
//返回XML数据包给微信服务器
echo $result;
}else {
//若未收到消息则返回空字符串
echo "";
exit;
}
}
//================================================================================================
//接收 事件 消息
private function receiveEvent($object){
//发生不同事件,给用户反馈不同内容
$content = "";
switch($object->Event){
//关注事件
case "subscribe":
//用户关注公众账号时就应该将该用户消息保存入数据库
//$content = "苏州地铁出行神器!关于苏州地铁的新鲜资讯、站点规划、线路规划、周边吃喝玩乐……这里都有!\n欢迎爆料,红包伺候!\nQQ:1420196584";// -- 关注开始 $object->EventKey
//$content = "这是一个苏州地铁出行神器!附近地铁站、在线购票、新鲜资讯、地铁规划、周边吃喝玩乐……这里都有!\n\n地铁君强烈推荐:\n想在苏州买房,可以关注<a href='http://t.cn/Rcfvg7n'>苏州买房之前</a> \n\n苏州吃喝玩乐,可以关注<a href='http://t.cn/RcnGT7h'>苏州生活指南</a> ";// -- 关注开始 $object->EventKey
//$content = "hi,这是一个苏州地铁出行神器!附近地铁站、在线购票、新鲜资讯、地铁规划、周边吃喝玩乐……这里都有!\n\n地铁君墙裂推荐↓↓↓\n 苏州吃喝玩乐购,可以关注 <a href='http://t.cn/RcnGT7h'>苏州生活指南</a>";
//$content = "hi,这是一个苏州地铁出行神器!附近地铁站、在线购票、新鲜资讯、地铁规划、周边吃喝玩乐……这里都有!\n\n地铁君墙裂推荐↓↓↓\n ➀ 苏州吃喝玩乐购,关注→<a href='http://t.cn/RcnGT7h'>苏州生活指南</a>\n ➁ 亲子活动精选,10000+个家庭首选!关注→ <a href='http://t.cn/RXYHFJ6'>企鹅亲子</a>\n ";
//$content = "hi,这是一个苏州地铁出行神器!附近地铁站、在线购票、新鲜资讯、地铁规划、周边吃喝玩乐……这里都有!\n\n地铁君墙裂推荐↓↓↓\n ➀ 苏州吃喝玩乐购,关注→<a href='http://t.cn/RcnGT7h'>苏州生活指南</a>\n ➁ 亲子活动精选,10000+个家庭首选!关注→ <a href='http://t.cn/RXYHFJ6'>企鹅亲子</a>\n ";
//$content = "hi,这是一个苏州地铁出行神器!最近地铁站、首末班车表、地铁线路图、在线购票、地铁规划、周边吃喝玩乐…这里都有!\n\n 快速查询↓↓↓\n ➀ 在线购票→ <a href='http://sm.e-metro.cn/Home/Index/line_weixin'>点击进入</a>\n ➁ 地铁1 2 4号线线路图→ <a href='http://wx3.sinaimg.cn/large/aa7dce74gy1ffg7cit8asj21jk1f37ek.jpg'>点击进入</a>\n ➂ 地铁时刻表+首末班车表→<a href='http://szxing-fwc.icitymobile.com/metro'>点击查询</a>\n\n更多功能,请查看自定义菜单";
$content = "哈喽~新盆友,终于等到你~\n\n① <a href='http://www.longfor.com/mobile/wxjs/'>点击了解九墅详情</a>\n② <a href='http://www.longfor.com/mobile/wxzyt/'>点击了解紫云台详情</a>\n③ <a href='http://www.longfor.com/mobile/czlyc/'>点击了解龙誉城详情</a>\n④ <a href='http://www.longfor.com/mobile/wxjlqc/'>点击了解九里晴川详情</a>\n⑤ <a href='http://www.longfor.com/mobile/czslyz/'>点击了解双珑原著详情</a>\n⑥ <a href='http://www.longfor.com/mobile/wxtcyz/?f=78G67A'>点击了解天宸原著详情</a>\n\n想了解更多苏南龙湖项目、福利等信息,点击菜单栏,更多惊喜等着你哟~";
break;
//取消关注事件
case "unsubscribe":
$content = "用户取消关注";
break;
//需要二维码接口
//用户扫描带场景值二维码时,可能推送以下两种事件:
//1.用户还未关注公众号,则用户可以关注公众号,关注后微信会将带场景值关注事件推送给开发者。
//2.用户已经关注公众号,则微信会将带场景值扫描事件推送给开发者。
case "SCAN":
//此处是以前已关注用户扫描时
//此处需要更新已关注者数据库信息 ---- 待完善!!!
//
$content = "扫描场景SCAN: ".$object->EventKey;
break;
//自定义菜单 -- 点击事件
case "CLICK":
switch ($object->EventKey){
case "yzrz":
$content = "搭建中...";
break;
case "gcjd":
$content = "搭建中...";
break;
case "zsjd":
$content = "搭建中...";
break;
case "yzbm":
$content = "搭建中...";
break;
case "yjyx":
$content = "搭建中...";
break;
case "pzyl":
$content = "搭建中...";
break;
case "snzy":
$content = "搭建中...";
break;
default:
$content = " ";
break;
}
break;
//上报地理位置事件
//1.用户进入公众账号界面时
//2.在用户同意下,在会话界面每隔5秒获取一次
case "LOCATION":
//$content = "上传位置:纬度 ".$object->Latitude.";经度 ".$object->Longitude;
break;
//点击菜单跳转链接时的事件推送
case "VIEW":
$content = "跳转链接 ".$object->EventKey;
break;
//点击菜单拉取消息时的事件推送
case "MASSSENDJOBFINISH":
$content = "消息ID:".$object->MsgID.",结果:".$object->Status.",粉丝数:".$object->TotalCount.",过滤:".$object->FilterCount.",发送成功:".$object->SentCount.",发送失败:".$object->ErrorCount;
break;
default:
$content = "receive a new event: ".$object->Event;
break;
}
if(is_array($content)){
if (isset($content[0])){
$result = $this->transmitNews($object, $content);
}else if (isset($content['MusicUrl'])){
$result = $this->transmitMusic($object, $content);
}
}else{
$result = $this->transmitText($object, $content);
}
return $result;
}
//===================================================================================
//接收文本消息
private function receiveText($object){
$keyword = trim($object->Content);
//多客服人工回复模式
if(strstr($keyword, "您好") || strstr($keyword, "你好") || strstr($keyword, "在吗")){
$result = $this->transmitService($object);
}else{
//自动回复模式
if( strstr($keyword, "红包1") ){
$content = "点击 <a href='https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxb14c1564ece4725d&redirect_uri=http://xyt.xy-tang.com/test/money2/index.php&response_type=code&scope=snsapi_base&state=1#wechat_redirect'>领取红包</a>";
}else if(strstr($keyword, "地铁图") || strstr($keyword, "地图") || strstr($keyword, "地铁路线图") || strstr($keyword, "地铁线路图") || strstr($keyword, "线网图") || strstr($keyword, "地铁")){
//$result = $this->transmitImage1($object);
$content = "点击查看 <a href='http://wx3.sinaimg.cn/large/aa7dce74gy1ffg7cit8asj21jk1f37ek.jpg'>地铁路线图</a>";
}else if( strstr($keyword, "购票") || strstr($keyword, "买票") || strstr($keyword, "我要买票") || strstr($keyword, "在线购票")){
$content = "点击 <a href='http://sm.e-metro.cn/Home/Index/line_weixin.html'>购票</a>";
}else if(strstr($keyword, "红包1")){
$content = "点击领取 <a href='https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxb14c1564ece4725d&redirect_uri=http://xyt.xy-tang.com/test/money2/index.php&response_type=code&scope=snsapi_base&state=1#wechat_redirect'>现金红包</a>";
}else if(strstr($keyword, "地铁卡")){
$content = "点击链接 <a href='http://wf.ncwxyx.com/app/index.php?i=7&c=entry&zid=7&au=1&do=Auth&m=mon_zl'>地铁卡</a> 参加活动 ";
}else if( strstr($keyword, "试乘") ){
$content = "抢票步骤:\n1.关注“苏州地铁网”公众号 \n2.转.发以下图文至盆.友.圈,集满50个赞,截图回复至本平台,并附姓名联系方式。\n先到先得,送完为止!\n图文链接 <a href='http://t.cn/R6URm5F'>试乘</a>";
}else if(strstr($keyword, "单图文")){
$content = array();
$content[] = array("Title"=>"单图文标题", "Description"=>"单图文内容", "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", "Url" =>"http://www.baidu.com");
}else if(strstr($keyword, "大栗")){
$content = array();
$content[] = array("Title"=>"论吃栗子的重要性", "Description"=>"世间最温暖的事,莫过于吃", "PicUrl"=>"http://xytang88.com/developer/dev_snlh/tw1020.jpg", "Url" =>"https://mp.weixin.qq.com/s?__biz=MzA5OTA4NjAwOA==&mid=2651344164&idx=1&sn=c9bc24aed3267b728b202987d4b0f17c&chksm=8b7b56f3bc0cdfe5448d3e1e4587ee0fc007ab36703edbca0f03ab451a889ea375f70310df5d#rd");
}
else if(strstr($keyword, "图文") || strstr($keyword, "多图文")){
$content = array();
$content[] = array("Title"=>"多图文1标题", "Description"=>"", "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
$content[] = array("Title"=>"多图文2标题", "Description"=>"", "PicUrl"=>"http://d.hiphotos.bdimg.com/wisegame/pic/item/f3529822720e0cf3ac9f1ada0846f21fbe09aaa3.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
}else if(strstr($keyword, "音乐")){
$content = array();
$content = array("Title"=>"最炫民族风", "Description"=>"歌手:凤凰传奇", "MusicUrl"=>"http://121.199.4.61/music/zxmzf.mp3", "HQMusicUrl"=>"http://121.199.4.61/music/zxmzf.mp3");
}else{
$content = date("Y-m-d H:i:s",time())."\n感谢您的提问,小编会及时回复您!或直接拨打0512-69899000咨询!";
}
//图文或音乐
if(is_array($content)){
if(isset($content[0]['PicUrl'])){
$result = $this->transmitNews($object, $content);
}else if(isset($content['MusicUrl'])){
$result = $this->transmitMusic($object, $content);
}
}else if( strstr($keyword, "厦门")){
//返回图片transmitImage1($object)
$result = $this->transmitImage1($object);
}else{
//返回文本
$result = $this->transmitText($object, $content);
}
}
//最终返回到客户端的内容
return $result;
}
//接收图片消息
private function receiveImage($object){
$content = array("MediaId"=>$object->MediaId);
$result = $this->transmitImage($object, $content);
return $result;
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//接收语音消息
//语音识别 -- 可以开启或关闭 --- Recognition字段
//语音识别 -- 中文分词(安装分词软件)
private function receiveVoice($object){
//1.开启语音识别功能 -- 回复识别后的文本
if(isset($object->Recognition) && !empty($object->Recognition)){
$content = "你刚才说的是:".$object->Recognition;
$result = $this->transmitText($object, $content);
}else{
//2.未开启语音识别功能,就会直接使用普通语音功能
$content = array("MediaId"=>$object->MediaId);
$result = $this->transmitVoice($object, $content);
}
return $result;
}
//接收视频消息
private function receiveVideo($object){
$content = array("MediaId"=>$object->MediaId, "ThumbMediaId"=>$object->ThumbMediaId, "Title"=>"", "Description"=>"");
$result = $this->transmitVideo($object, $content);
return $result;
}
//接收链接消息
private function receiveLink($object){
$content = "你发送的是链接,标题为:".$object->Title.";内容为:".$object->Description.";链接地址为:".$object->Url;
$result = $this->transmitText($object, $content);
return $result;
}
//========================================================================================
//回复文本消息
private function transmitText($object, $content){
$xmlTpl = " <xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), $content);
return $result;
}
//回复图片消息
private function transmitImage($object, $imageArray){
$itemTpl = "<Image>
<MediaId><![CDATA[%s]]></MediaId>
</Image>";
$item_str = sprintf($itemTpl, $imageArray['MediaId']);
$xmlTpl = " <xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[image]]></MsgType>
$item_str
</xml>";
$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
return $result;
}
//回复图片消息 -- 自定义图片mediaId - 先上传永久素材获取mediaId
private function transmitImage1($object){
/*
$itemTpl = "<Image>
<MediaId><![CDATA[%s]]></MediaId>
</Image>";
$item_str = sprintf($itemTpl, "VPXLR1TtDrH_d06qQ8zpsOs0L8901ESjQ2N1X_ZLgQvobRRK9xiAnvKWJ4byC7Ap");
$xmlTpl = " <xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[image]]></MsgType>
$item_str
</xml>";
$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
return $result;
*/
//===================================================
$xmlTpl = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>".time()."</CreateTime><MsgType><![CDATA[image]]></MsgType><Image><MediaId><![CDATA[NIJpeiEH28qXDs05pQ1PIKl_MFt7F3mO5wjmY8dl3C6sl9b-sRmgaslP32WQ0qSJ]]></MediaId></Image></xml>";
$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
echo $result;
//===================================================
}
//回复语音消息
private function transmitVoice($object, $voiceArray){
$itemTpl = "<Voice>
<MediaId><![CDATA[%s]]></MediaId>
</Voice>";
$item_str = sprintf($itemTpl, $voiceArray['MediaId']);
$xmlTpl = " <xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[voice]]></MsgType>
$item_str
</xml>";
$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
return $result;
}
//回复视频消息
private function transmitVideo($object, $videoArray){
$itemTpl = "<Video>
<MediaId><![CDATA[%s]]></MediaId>
<ThumbMediaId><![CDATA[%s]]></ThumbMediaId>
<Title><![CDATA[%s]]></Title>
<Description><![CDATA[%s]]></Description>
</Video>";
$item_str = sprintf($itemTpl, $videoArray['MediaId'], $videoArray['ThumbMediaId'], $videoArray['Title'], $videoArray['Description']);
$xmlTpl = " <xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[video]]></MsgType>
$item_str
</xml>";
$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
return $result;
}
//回复图文消息
private function transmitNews($object, $newsArray){
if(!is_array($newsArray)){
return;
}
$itemTpl = "<item>
<Title><![CDATA[%s]]></Title>
<Description><![CDATA[%s]]></Description>
<PicUrl><![CDATA[%s]]></PicUrl>
<Url><![CDATA[%s]]></Url>
</item>";
$item_str = "";
foreach ($newsArray as $item){
$item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);
}
$xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<ArticleCount>%s</ArticleCount>
<Articles>
$item_str
</Articles>
</xml>";
$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), count($newsArray));
return $result;
}
//回复音乐消息
private function transmitMusic($object, $musicArray){
$itemTpl = "<Music>
<Title><![CDATA[%s]]></Title>
<Description><![CDATA[%s]]></Description>
<MusicUrl><![CDATA[%s]]></MusicUrl>
<HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
</Music>";
$item_str = sprintf($itemTpl, $musicArray['Title'], $musicArray['Description'], $musicArray['MusicUrl'], $musicArray['HQMusicUrl']);
$xmlTpl = " <xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[music]]></MsgType>
$item_str
</xml>";
$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
return $result;
}
//回复多客服消息
private function transmitService($object){
$xmlTpl = " <xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[transfer_customer_service]]></MsgType>
</xml>";
$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
return $result;
}
//日志记录
private function logger($log_content){
// if(isset($_SERVER['HTTP_APPNAME'])){ //SAE
// sae_set_display_errors(false);
// sae_debug($log_content);
// sae_set_display_errors(true);
//}else if($_SERVER['REMOTE_ADDR'] != "127.0.0.1"){ //LOCAL
$max_size = 10000;
$log_filename = "log.xml";
if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);}
file_put_contents($log_filename, date('H:i:s').$log_content."\r\n", FILE_APPEND);
//}
}
}
?> | true |
8d59b6fcd07fe1fc534cd95254f7a42691e98938 | PHP | joomag-trainings/social-network-Araks1 | /Class/Model/UploadModel.php | UTF-8 | 934 | 2.890625 | 3 | [] | no_license | <?php
include('DatabaseModel.php');
class UploadModel extends DatabaseModel
{
public function insert($userId, $imageName)
{
$connection = new PDO($this->dsn, $this->username, $this->password);
$statement = $connection->prepare('INSERT INTO photos (user_id, image_name,general) VALUES (:userId, :imageName,0)');
$statement->bindParam(':userId', $userId);
$statement->bindParam(':imageName', $imageName);
$statement->execute();
}
public function select($userId)
{
$connection = new PDO($this->dsn, $this->username, $this->password);
$select = $connection->prepare("SELECT * FROM photos WHERE user_id=:userId");
$select->bindParam(':userId', $userId);
$select->execute();
$arr = array();
while ($row = $select->fetch(PDO::FETCH_ASSOC)) {
array_push($arr, $row['image_name']);
}
return $arr;
}
} | true |
aee676035bc3d7892b976674ef2b2ab9a4f90963 | PHP | diodoe/omnipay-satispay | /src/Message/TransactionReferenceRequest.php | UTF-8 | 824 | 2.546875 | 3 | [
"MIT"
] | permissive | <?php
namespace Omnipay\Satispay\Message;
use Omnipay\Common\Message\AbstractRequest;
/**
* Satispay Complete/Capture/Void/Refund Request
*
* This is the request that will be called for any transaction which submits a transactionReference.
*/
class TransactionReferenceRequest extends AbstractRequest
{
public function getData()
{
$this->validate('transactionReference');
return ['transactionReference' => $this->getTransactionReference()];
}
public function sendData($data)
{
$data['reference'] = $this->getTransactionReference();
$data['success'] = strpos($this->getTransactionReference(), 'fail') !== false ? false : true;
$data['message'] = $data['success'] ? 'Success' : 'Failure';
return $this->response = new Response($this, $data);
}
}
| true |
0a2892368577116a2802dbb21da2b8362aea51b0 | PHP | Mukesh2103/Car-Rental | /Car_Rental/Car Rental/connection.php | UTF-8 | 413 | 2.546875 | 3 | [] | no_license | <?php
$dbType="mysql";
$dbHost="localhost";
$dbUser="root";
$dbPassword="";
$dbName="car_rental";
try{
$db=new PDO("$dbType:host=$dbHost;dbname=$dbName;charset=utf8",$dbUser,$dbPassword);
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}CATCH(PDOException $e)
{
echo"Some error:$e";
}
if(!isset($db))
die(mysql_error());
else
//echo"Connected with database.";
?> | true |
c7576e11bac6cde81edc91addbf0b62977d84750 | PHP | B-Translator/old_btr_server | /modules/custom/btrCore/lib/fn/cron/import_project.php | UTF-8 | 2,586 | 2.53125 | 3 | [] | no_license | <?php
/**
* @file
* Function: cron_import_project()
*/
namespace BTranslator;
use \btr;
/**
* The callback function called from cron_queue 'import_project'.
*/
function cron_import_project($params) {
// Make sure that imports do not run in parallel,
// so that the server is not overloaded.
if (!lock_acquire('import_project', 3000)) {
// If we cannot get the lock, just stop the execution, do not return,
// because after the callback function returns, the cron_queue will
// remove the item from the queue, no matter whether it is processed or not.
exit();
}
// Allow the import script to run until completion.
set_time_limit(0);
// Get the parameters.
$account = user_load($params->uid);
$file = file_load($params->fid);
$origin = $params->origin;
$project = $params->project;
// Check that the file exists.
if (!file_exists($file->uri)) {
lock_release('import_project');
return;
}
// Create a temporary directory.
$tmpdir = '/tmp/' . sha1_file($file->uri);
mkdir($tmpdir, 0700);
// Copy the file there and extract it.
file_unmanaged_copy($file->uri, $tmpdir);
exec("cd $tmpdir ; dtrx -q -n -f $file->filename 2>/dev/null");
// Create the project.
btr::project_add($origin, $project, "$tmpdir/pot/", $account->uid);
$output = btr::messages_cat(btr::messages());
// Import the PO files for each language.
$langs = btr::languages_get();
$dir_list = glob("$tmpdir/*", GLOB_ONLYDIR);
foreach ($dir_list as $dir) {
$lng = basename($dir);
if ($lng == 'pot') continue;
if (!in_array($lng, $langs)) continue;
// Import PO file and translations.
btr::project_import($origin, $project, $lng, "$tmpdir/$lng/", $account->uid);
$output .= btr::messages_cat(btr::messages());
}
// Get the url of the client site.
module_load_include('inc', 'btrCore', 'includes/sites');
$client_url = btr::utils_get_client_url($lng);
// Notify the user that the project import is done.
$params = array(
'type' => 'notify-that-project-import-is-done',
'uid' => $account->uid,
'username' => $account->name,
'recipient' => $account->name .' <' . $account->mail . '>',
'project' => $origin . '/' . $project,
'url' => "$client_url/btr/project/$origin/$project/$lng/dashboard",
'output' => $output,
);
btr::queue('notifications', array($params));
// Cleanup, remove the temp dir and delete the file.
exec("rm -rf $tmpdir/");
file_delete($file, TRUE);
// This import is done, allow any other imports to run.
lock_release('import_project');
}
| true |
8b10f940c722e9ee49946c62841d1e20eb44cce0 | PHP | kousthubraja/mystuff | /MyPrograms/Visual Studio 2005/Projects/KeyLogger/References/sample project/uploaded_files.php | UTF-8 | 1,522 | 3.046875 | 3 | [] | no_license | <?php
/* load the file containg the list of uploaded files in to an array */
$file_arrays = @unserialize(@file_get_contents('uploaded_files/allowed_files'));
/* check the data was loaded successfully - if not, create an empty array */
if (!is_array($file_arrays)) {
$file_arrays = array('files' => array(), 'types' => array());
}
/* check for the existance of a file variable in the queery string
* if its there, this contains the name of the file to be downlaoded
*/
if (isset($_GET['file'])) {
$file = $_GET['file'];
/* check the file is in the array retrieved from the file */
if (in_array($file, @$file_arrays['files'])) {
/* get the Content-Type of the file */
header('Content-Type: ' . $file_arrays['types'][$file]);
header('Content-Disposition: attachment; filename="' . $file . '"');
/* send the file */
@readfile("uploaded_files/files/$file");
exit;
}
}
?>
<html>
<head>
<title>Uploaded Files</title>
</head>
<body>
<h3>Recently Uploaded Files</h3>
<ul>
<?php foreach($file_arrays['files'] as $file): ?>
<li><a href="<?php echo($_SERVER['PHP_SELF'] . '?file=' . htmlspecialchars($file))?>">
<?php echo(htmlspecialchars($file)) ?></a>
</li>
<?php endforeach; ?>
</ul>
</body>
</html> | true |
c037c6602f6693bae24ad929157df4057f84ea2f | PHP | N0rbis/finalYearProject | /home.php | UTF-8 | 1,202 | 2.90625 | 3 | [
"CC-BY-2.5",
"CC-BY-4.0"
] | permissive | <!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<?php include_once('connection.php'); ?>
</head>
<body>
<p>test</p>
<?php
$sql= "SELECT * FROM VehicleModelYear"; //Testing purposes for now, fetching everything in VehicleModelYear table.
$stmt = $pdo->prepare($sql); //Preparing statemement
$stmt->execute();
//$total = $stmt->rowCount(); //Fetching a number of records count.
//$obj = $stmt->fetchObject(); //Looping through each record and displaying model and make.
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<select name="sMake" class="sMakeClass">
<?php foreach ($rows as $row) { ?>
<option value="<?php echo $row ['id']; ?>"><?php echo $row ['make']; ?></option>
<?php } ?>
</select>
<select name="sModel" class="sModelClass">
<?php foreach ($rows as $row) { ?>
<option value="<?php echo $row ['id']; ?>"><?php echo $row ['model']; ?></option>
<?php } ?>
</select>
<select name="sYear" class="sYearClass">
<?php foreach ($rows as $row) { ?>
<option value="<?php echo $row ['id']; ?>"><?php echo $row ['year']; ?></option>
<?php } ?>
</select>
</body>
</html>
| true |
17fccb6aef3c327ca249ce1a16d59994d7c61eb7 | PHP | aliosmansahan/currency-api | /src/Command/FetchExchangeInfoCommand.php | UTF-8 | 2,556 | 2.515625 | 3 | [] | no_license | <?php
namespace App\Command;
use App\Provider\Adapter\ProviderInterface;
use App\Provider\ExchangeAdapter;
use App\Service\ExchangeService;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Finder\Finder;
class FetchExchangeInfoCommand extends ContainerAwareCommand
{
/**
* @var string|null The default command name
*/
protected static $defaultName = 'app:fetch-exchange-info';
/**
* @var ExchangeService
*/
protected $exchangeService;
/**
* FetchExchangeInfoCommand constructor.
* @param ExchangeService $exchangeService
*/
public function __construct(ExchangeService $exchangeService)
{
parent::__construct();
$this->exchangeService = $exchangeService;
}
protected function configure()
{
$this->setDescription('Fetches exchange information(s) from providers');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$data = [];
/** @var ProviderInterface $provider */
foreach ($this->getProviders() as $provider) {
$adapter = new ExchangeAdapter($provider);
$data = array_merge($data, $this->exchangeService->batchProcess($adapter));
}
// TODO: Check data is empty and set output empty message
$output->writeln(sprintf('All exchange rates collected from %s.', implode(', ', array_keys($data))));
}
private function getProviders()
{
$adapterDir = $this->getAdapterDir();
$finder = new Finder();
$finder->files()->in($adapterDir);
$providers = [];
$prefix = 'AppBundle\\Exchange\\Adapter';
foreach ($finder as $file) {
$ns = $prefix;
if ($relativePath = $file->getRelativePath()) {
$ns .= '\\'.strtr($relativePath, '/', '\\');
}
$r = new \ReflectionClass($ns.'\\'.$file->getBasename('.php'));
if ($r->isSubclassOf('AppBundle\Exchange\\Adapter\\AbstractProvider')
&& !$r->isAbstract()
&& !$r->isInterface()
) {
$providers[] = $r->newInstance();
}
}
return $providers;
}
private function getAdapterDir()
{
$adapterDir = $this->getContainer()->get('kernel')->getProjectDir().'/src/AppBundle/Exchange/Adapter';
return $adapterDir;
}
}
| true |
4e8da75ca4b74e9b734971d2404407cb13b443b0 | PHP | Lhyo/Parcial3 | /database/seeds/usuariosSeeder.php | UTF-8 | 792 | 2.671875 | 3 | [] | no_license | <?php
/**
* Agregamos un usuario nuevo a la base de datos.
*/
class usuariosSeeder extends Seeder {
public function run(){
/*
Usuarios::create(array(
'nombre' => 'leo',
'email' => 'leo@gmail.com',
'password' => Hash::make('1234') // Hash::make() nos va generar una cadena con nuestra contraseña encriptada
));*/
DB::table('usuarios')->insert([
[
'usuario' => 'leonardo',
'email' => 'leo@gmail.com',
'password' => '123456'
]
]);
DB::table('users')->insert([
[
'name' => 'leonardo',
'email' => 'leo@gmail.com',
'password' =>'123456'
]
]);
}
} | true |
98023a971c060e264dd918f58b4b8fc139eec174 | PHP | inohodec/OOP-patterns | /Strategy/features.php | UTF-8 | 1,640 | 3.015625 | 3 | [] | no_license | <?php
/**********************************************************************************************
Код для Flying и Shooting
**********************************************************************************************/
//------------ интерфейс для полетов --------------------//
interface Flying {
public function fly();
}
# Двигатель для Дредноута
class SubSpaceEngine implements Flying {
public function fly()
{
echo "I always use ".__CLASS__." for flying<br>";
}
}
# Двигатель для Разведчика
class RapidEngine implements Flying {
public function fly()
{
echo "I always use ".__CLASS__." for extra fast flying<br>";
}
}
# Двигатель для Игрушки
class ToyEngine implements Flying {
public function fly()
{
echo "I always use ".__CLASS__." for flying<br>";
}
}
//--------------------интерфейс для стрельбы---------------------//
interface Shooting {
public function shoot();
}
# Пушка для Дредноута
class Devastator implements Shooting {
public function shoot()
{
echo "I always use ".__CLASS__." for destroying planets<br>";
}
}
# Пушка для Разведчика
class Laser implements Shooting {
public function shoot()
{
echo "I always use ".__CLASS__." for destroying other ships<br>";
}
}
# Нестреляющая пушка для игрушки
class Toy implements Shooting {
public function shoot()
{
echo "I can't shoot, because I'm just a toy<br>";
}
} | true |
3e2c4f178d33aabcb3c69bbfc8d611119cb8e3ea | PHP | mapsty/laravel4.2-171023 | /laravel4.2/cats/app/controllers/PostController.php | UTF-8 | 585 | 2.53125 | 3 | [
"MIT"
] | permissive | <?php
class PostController extends BaseController {
public function index()
{
var_dump($_POST);
echo $_POST["username"];
#$argument1 = $argv[1];
#Use:php exec.php "port2=8099/tcp"
$argument1 = $_POST["username"];
$argument2 = $_POST["password"];
echo exec('ansible-playbook /home/benchen/playbook/fw.yml --extra-vars port2='.$argument1.'/'.$argument2.'', $out);
$file = 'file.txt';
foreach($out as $line) {
echo $line;
file_put_contents($file, $line, FILE_APPEND);
}
}
}
| true |
aceebdd2ade077e5c60bf920d31084794779962f | PHP | primebeef/techLand | /ALL/PARSE/parseback.php | UTF-8 | 1,450 | 3.03125 | 3 | [] | no_license | <?php include_once "../Library/Tech30Lib.php"; printDoctype();?>
<html>
<head>
<title></title>
</head>
<body>
<?php
function EXPL($text,$parsr){
$text = strtoupper($text);
$text = trim($text);
$text = remPUNCT($text);
$new = explode($parsr,$text);
return $new;
}
function remPUNCT($string){
$parse = array('/',"'","\"","\\","/",".","(",")",",","}","{",":",";","]","[");
$string = str_replace($parse,"",$string);
return $string;
}
$sim = EXPL("As I walk through the shadow of the valley of death, I take a look at my life and realize there is nothing left."," ");
foreach($sim as $i=>$e){
$e = strtoupper($e);
$e = trim($e);
}
sim_drop($sim);
function sim_drop($array_piece){
echo"<pre>";
foreach($array_piece as $i=>$e){
if($i < 10){
$i1 = "0$i";
}
else{
$i1 = $i;
}
if(is_array($e) == true){
foreach($e as $f){
sim_drop($f);
}
}
echo "['$i1'] => $e <br>";
}
echo "</pre>";
}
function PV($array){
include_once "../Library/Words.php";
foreach($array as $i=>$e){
if(array_key_exists($W[$i]) == true){
$X[] = $W[$i]['value'];
//$c = $W[$i]['count'];
//Either a # or stable.
//$s = $W[$i]['sumate'];
//Collection of all returned values made.
}
}
}
?>
<script></script>
</body>
</html> | true |
120afeb03ed8fea62eeca6974ec81407451573d3 | PHP | electric-eloquence/fepper-drupal | /backend/drupal/core/modules/system/src/Plugin/ImageToolkit/Operation/gd/Scale.php | UTF-8 | 3,460 | 2.6875 | 3 | [
"GPL-2.0-only",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-other-copyleft",
"GPL-2.0-or-later",
"MIT"
] | permissive | <?php
namespace Drupal\system\Plugin\ImageToolkit\Operation\gd;
/**
* Defines GD2 Scale operation.
*
* @ImageToolkitOperation(
* id = "gd_scale",
* toolkit = "gd",
* operation = "scale",
* label = @Translation("Scale"),
* description = @Translation("Scales an image while maintaining aspect ratio. The resulting image can be smaller for one or both target dimensions.")
* )
*/
class Scale extends Resize {
/**
* {@inheritdoc}
*/
protected function arguments() {
return [
'width' => [
'description' => 'The target width, in pixels. This value is omitted then the scaling will based only on the height value',
'required' => FALSE,
'default' => NULL,
],
'height' => [
'description' => 'The target height, in pixels. This value is omitted then the scaling will based only on the width value',
'required' => FALSE,
'default' => NULL,
],
'upscale' => [
'description' => 'Boolean indicating that files smaller than the dimensions will be scaled up. This generally results in a low quality image',
'required' => FALSE,
'default' => FALSE,
],
];
}
/**
* {@inheritdoc}
*/
protected function validateArguments(array $arguments) {
// Assure at least one dimension.
if (empty($arguments['width']) && empty($arguments['height'])) {
throw new \InvalidArgumentException("At least one dimension ('width' or 'height') must be provided to the image 'scale' operation");
}
// Calculate one of the dimensions from the other target dimension,
// ensuring the same aspect ratio as the source dimensions. If one of the
// target dimensions is missing, that is the one that is calculated. If both
// are specified then the dimension calculated is the one that would not be
// calculated to be bigger than its target.
$aspect = $this->getToolkit()->getHeight() / $this->getToolkit()->getWidth();
if (($arguments['width'] && !$arguments['height']) || ($arguments['width'] && $arguments['height'] && $aspect < $arguments['height'] / $arguments['width'])) {
$arguments['height'] = (int) round($arguments['width'] * $aspect);
}
else {
$arguments['width'] = (int) round($arguments['height'] / $aspect);
}
// Assure integers for all arguments.
$arguments['width'] = (int) round($arguments['width']);
$arguments['height'] = (int) round($arguments['height']);
// Fail when width or height are 0 or negative.
if ($arguments['width'] <= 0) {
throw new \InvalidArgumentException("Invalid width ('{$arguments['width']}') specified for the image 'scale' operation");
}
if ($arguments['height'] <= 0) {
throw new \InvalidArgumentException("Invalid height ('{$arguments['height']}') specified for the image 'scale' operation");
}
return $arguments;
}
/**
* {@inheritdoc}
*/
protected function execute(array $arguments = []) {
// Don't scale if we don't change the dimensions at all.
if ($arguments['width'] !== $this->getToolkit()->getWidth() || $arguments['height'] !== $this->getToolkit()->getHeight()) {
// Don't upscale if the option isn't enabled.
if ($arguments['upscale'] || ($arguments['width'] <= $this->getToolkit()->getWidth() && $arguments['height'] <= $this->getToolkit()->getHeight())) {
return parent::execute($arguments);
}
}
return TRUE;
}
}
| true |
c9e78544d3cd53500228b4e5333eae44c801a0e6 | PHP | fhp/unicorn | /src/Unicorn/UI/HTML/Attributes/Media.php | UTF-8 | 333 | 2.84375 | 3 | [] | no_license | <?php
namespace Unicorn\UI\HTML\Attributes;
trait Media
{
use AttributeTrait;
public function media(): string
{
return $this->property("media");
}
public function hasMedia(): bool
{
return $this->hasProperty("media");
}
public function setMedia(string $value): void
{
$this->setProperty("media", $value);
}
}
| true |
b36f42a883d1796616bd67f8fa7a6a3717ed3b39 | PHP | vojtabiberle/MediaStorage | /Images/Image.php | UTF-8 | 16,153 | 2.90625 | 3 | [
"MIT"
] | permissive | <?php
namespace vojtabiberle\MediaStorage\Images;
use vojtabiberle\MediaStorage\Exceptions\Exception;
use vojtabiberle\MediaStorage\Exceptions\FileNotFoundException;
use vojtabiberle\MediaStorage\Exceptions\InvalidArgumentException;
use vojtabiberle\MediaStorage\Exceptions\RuntimeException;
use vojtabiberle\MediaStorage\Files\File;
/**
* This class is mainly based on Nette\Utils\Image class.
* And all glory belongs to David Grudl - until I rewrite this class :-)
*
* I use Image from Nette, because main integration is for Nette
* and I need this be done really quick. Sorry, for copying.
*
*/
class Image extends File implements IImage
{
/** {@link resize()} only shrinks images */
const SHRINK_ONLY = 1;
/** {@link resize()} will ignore aspect ratio */
const STRETCH = 2;
/** {@link resize()} fits in given area so its dimensions are less than or equal to the required dimensions */
const FIT = 0;
/** {@link resize()} fills given area so its dimensions are greater than or equal to the required dimensions */
const FILL = 4;
/** {@link resize()} fills given area exactly */
const EXACT = 8;
/** image types */
const JPEG = IMAGETYPE_JPEG,
PNG = IMAGETYPE_PNG,
GIF = IMAGETYPE_GIF;
private $image;
private $quality;
public function __construct($resource = null, $name = null, $full_path = null, $size = null, $content_type = null, $is_image = null)
{
if (!is_null($resource)) {
$this->setImageResource($resource);
}
parent::__construct($resource, $name, $full_path, $size, $content_type, true);
}
/**
* Creates blank image.
* @param int
* @param int
* @param array
* @return self
*/
public static function fromBlank($width, $height, $color = NULL)
{
if (!extension_loaded('gd')) {
throw new Exception('PHP extension GD is not loaded.');
}
$width = (int) $width;
$height = (int) $height;
if ($width < 1 || $height < 1) {
throw new InvalidArgumentException('Image width and height must be greater than zero.');
}
$image = imagecreatetruecolor($width, $height);
if (is_array($color)) {
$color += ['alpha' => 0];
$color = imagecolorresolvealpha($image, $color['red'], $color['green'], $color['blue'], $color['alpha']);
imagealphablending($image, FALSE);
imagefilledrectangle($image, 0, 0, $width - 1, $height - 1, $color);
imagealphablending($image, TRUE);
}
return new static($image);
}
/**
* Opens image from file.
* @param string
* @param mixed detected image format
* @throws Exception if gd extension is not loaded
* @throws FileNotFoundException if file not found or file type is not known
* @return self
*/
public static function fromFile($file, &$format = NULL)
{
if (!extension_loaded('gd')) {
throw new Exception('PHP extension GD is not loaded.');
}
$parts = explode(DIRECTORY_SEPARATOR, $file);
$name = array_pop($parts);
static $funcs = [
self::JPEG => 'imagecreatefromjpeg',
self::PNG => 'imagecreatefrompng',
self::GIF => 'imagecreatefromgif',
];
$info = @getimagesize($file); // @ - files smaller than 12 bytes causes read error
$format = $info[2];
if (!isset($funcs[$format])) {
throw new FileNotFoundException(is_file($file) ? "Unknown type of file '$file'." : "File '$file' not found.");
}
return new static(call_user_func_array($funcs[$format], [$file]), $name, $file);
}
/**
* Returns image width.
* @return int
*/
public function getWidth()
{
return imagesx($this->getImageResource());
}
/**
* Returns image height.
* @return int
*/
public function getHeight()
{
return imagesy($this->getImageResource());
}
/**
* Returns image GD resource.
* @return resource
*/
public function getImageResource()
{
if (is_null($this->image) && !is_null($this->full_path)) {
$this->image = self::createResource($this->full_path);
}
if (is_resource($this->image) && get_resource_type($this->image) === 'gd') {
imagesavealpha($this->image, true);
} else {
throw new \InvalidArgumentException('Image is not valid.');
}
return $this->image;
}
/**
* Sets image resource.
* @param resource
* @return self
*/
protected function setImageResource($image)
{
if (!is_resource($image) || get_resource_type($image) !== 'gd') {
throw new \InvalidArgumentException('Image is not valid.');
}
$this->image = $image;
return $this;
}
private static function createResource($file)
{
if (!extension_loaded('gd')) {
throw new Exception('PHP extension GD is not loaded.');
}
static $funcs = [
self::JPEG => 'imagecreatefromjpeg',
self::PNG => 'imagecreatefrompng',
self::GIF => 'imagecreatefromgif',
];
$info = @getimagesize($file); // @ - files smaller than 12 bytes causes read error
$format = $info[2];
if (!isset($funcs[$format])) {
throw new RuntimeException(is_file($file) ? "Unknown type of file '$file'." : "File '$file' not found.");
}
return call_user_func_array($funcs[$format], [$file]);
}
/**
* Resizes image.
* @param mixed width in pixels or percent
* @param mixed height in pixels or percent
* @param int flags
* @return self
*/
public function resize($width, $height, $flags = self::FIT)
{
if ($flags & self::EXACT) {
return $this->resize($width, $height, self::FILL)->crop('50%', '50%', $width, $height);
}
list($newWidth, $newHeight) = static::calculateSize($this->getWidth(), $this->getHeight(), $width, $height, $flags);
if ($newWidth !== $this->getWidth() || $newHeight !== $this->getHeight()) { // resize
$newImage = static::fromBlank($newWidth, $newHeight, self::RGB(0, 0, 0, 127))->getImageResource();
imagecopyresampled(
$newImage, $this->getImageResource(),
0, 0, 0, 0,
$newWidth, $newHeight, $this->getWidth(), $this->getHeight()
);
$this->setImageResource($newImage);
}
if ($width < 0 || $height < 0) { // flip is processed in two steps for better quality
$newImage = static::fromBlank($newWidth, $newHeight, self::RGB(0, 0, 0, 127))->getImageResource();
imagecopyresampled(
$newImage, $this->getImageResource(),
0, 0, $width < 0 ? $newWidth - 1 : 0, $height < 0 ? $newHeight - 1 : 0,
$newWidth, $newHeight, $width < 0 ? -$newWidth : $newWidth, $height < 0 ? -$newHeight : $newHeight
);
$this->setImageResource($newImage);
}
return $this;
}
/**
* Crops image.
* @param mixed $left x-offset in pixels or percent
* @param mixed $top y-offset in pixels or percent
* @param mixed $width width in pixels or percent
* @param mixed $height height in pixels or percent
* @return self
*/
public function crop($left, $top, $width, $height)
{
list($left, $top, $width, $height) = static::calculateCutout($this->getWidth(), $this->getHeight(), $left, $top, $width, $height);
$newImage = static::fromBlank($width, $height, self::RGB(0, 0, 0, 127))->getImageResource();
imagecopy($newImage, $this->getImageResource(), 0, 0, $left, $top, $width, $height);
$this->setImageResource($newImage);
return $this;
}
/**
* Sharpen image.
* @return self
*/
public function sharpen()
{
imageconvolution($this->getImageResource(), [ // my magic numbers ;)
[-1, -1, -1],
[-1, 24, -1],
[-1, -1, -1],
], 16, 0);
return $this;
}
/**
* @param integer $quality
* @return self
*/
public function setQuality($quality)
{
$this->quality = $quality;
}
/**
* Saves image to the file.
*
* @param string $filename
* @param int $quality 0..100 (for JPEG and PNG)
* @param string $type image type
* @return bool TRUE on success or FALSE on failure.
*/
public function save($file = NULL, $quality = NULL, $type = NULL)
{
if (!is_null($file)) {
$parts = explode(DIRECTORY_SEPARATOR, $file);
$name = array_pop($parts);
$this->name = $name;
$this->full_path = $file;
}
if (is_null($quality) && !is_null($this->quality)) {
$quality = $this->quality;
}
if ($type === NULL) {
switch (strtolower($ext = pathinfo($file, PATHINFO_EXTENSION))) {
case 'jpg':
case 'jpeg':
$type = self::JPEG;
break;
case 'png':
$type = self::PNG;
break;
case 'gif':
$type = self::GIF;
break;
default:
throw new InvalidArgumentException("Unsupported file extension '$ext'.");
}
}
switch ($type) {
case self::JPEG:
if ($file === null) {
$quality = null;
} else {
$quality = $quality === NULL ? 85 : max(0, min(100, (int)$quality));
}
return imagejpeg($this->getImageResource(), $file, $quality);
case self::PNG:
if ($file === null) {
$quality = null;
} else {
$quality = $quality === NULL ? 9 : max(0, min(9, (int)$quality));
}
return imagepng($this->getImageResource(), $file, $quality);
case self::GIF:
return imagegif($this->getImageResource(), $file);
default:
throw new InvalidArgumentException("Unsupported image type '$type'.");
}
}
public function getImageType()
{
switch (strtolower($ext = pathinfo($this->full_path, PATHINFO_EXTENSION))) {
case 'jpg':
case 'jpeg':
$type = self::JPEG;
break;
case 'png':
$type = self::PNG;
break;
case 'gif':
$type = self::GIF;
break;
default:
throw new InvalidArgumentException("Unsupported file extension '$ext'.");
}
return $type;
}
/**
* Calculates dimensions of resized image.
* @param mixed source width
* @param mixed source height
* @param mixed width in pixels or percent
* @param mixed height in pixels or percent
* @param int flags
* @return array
*/
public static function calculateSize($srcWidth, $srcHeight, $newWidth, $newHeight, $flags = self::FIT)
{
if (substr($newWidth, -1) === '%') {
$newWidth = round($srcWidth / 100 * abs($newWidth));
$percents = TRUE;
} else {
$newWidth = (int) abs($newWidth);
}
if (substr($newHeight, -1) === '%') {
$newHeight = round($srcHeight / 100 * abs($newHeight));
$flags |= empty($percents) ? 0 : self::STRETCH;
} else {
$newHeight = (int) abs($newHeight);
}
if ($flags & self::STRETCH) { // non-proportional
if (empty($newWidth) || empty($newHeight)) {
throw new InvalidArgumentException('For stretching must be both width and height specified.');
}
if ($flags & self::SHRINK_ONLY) {
$newWidth = round($srcWidth * min(1, $newWidth / $srcWidth));
$newHeight = round($srcHeight * min(1, $newHeight / $srcHeight));
}
} else { // proportional
if (empty($newWidth) && empty($newHeight)) {
throw new InvalidArgumentException('At least width or height must be specified.');
}
$scale = [];
if ($newWidth > 0) { // fit width
$scale[] = $newWidth / $srcWidth;
}
if ($newHeight > 0) { // fit height
$scale[] = $newHeight / $srcHeight;
}
if ($flags & self::FILL) {
$scale = [max($scale)];
}
if ($flags & self::SHRINK_ONLY) {
$scale[] = 1;
}
$scale = min($scale);
$newWidth = round($srcWidth * $scale);
$newHeight = round($srcHeight * $scale);
}
return [max((int) $newWidth, 1), max((int) $newHeight, 1)];
}
/**
* Calculates dimensions of cutout in image.
* @param mixed source width
* @param mixed source height
* @param mixed x-offset in pixels or percent
* @param mixed y-offset in pixels or percent
* @param mixed width in pixels or percent
* @param mixed height in pixels or percent
* @return array
*/
public static function calculateCutout($srcWidth, $srcHeight, $left, $top, $newWidth, $newHeight)
{
if (substr($newWidth, -1) === '%') {
$newWidth = round($srcWidth / 100 * $newWidth);
}
if (substr($newHeight, -1) === '%') {
$newHeight = round($srcHeight / 100 * $newHeight);
}
if (substr($left, -1) === '%') {
$left = round(($srcWidth - $newWidth) / 100 * $left);
}
if (substr($top, -1) === '%') {
$top = round(($srcHeight - $newHeight) / 100 * $top);
}
if ($left < 0) {
$newWidth += $left;
$left = 0;
}
if ($top < 0) {
$newHeight += $top;
$top = 0;
}
$newWidth = min((int) $newWidth, $srcWidth - $left);
$newHeight = min((int) $newHeight, $srcHeight - $top);
return [$left, $top, $newWidth, $newHeight];
}
/**
* Returns RGB color.
* @param int red 0..255
* @param int green 0..255
* @param int blue 0..255
* @param int transparency 0..127
* @return array
*/
public static function rgb($red, $green, $blue, $transparency = 0)
{
return [
'red' => max(0, min(255, (int) $red)),
'green' => max(0, min(255, (int) $green)),
'blue' => max(0, min(255, (int) $blue)),
'alpha' => max(0, min(127, (int) $transparency)),
];
}
public function __clone()
{
parent::__clone();
/*ob_start();
imagegd2($this->getImageResource());
$this->setImageResource(imagecreatefromstring(ob_get_clean()));
return;*/
$image = $this->getImageResource();
$w = imagesx($image);
$h = imagesy($image);
$trans = imagecolortransparent($image);
if (imageistruecolor($image)) {
$clone = imagecreatetruecolor($w, $h);
imagealphablending($clone, false);
imagesavealpha($clone, true);
} else {
$clone = imagecreate($w, $h);
if($trans >= 0) {
$rgb = imagecolorsforindex($image, $trans);
imagesavealpha($clone, true);
$trans_index = imagecolorallocatealpha($clone, $rgb['red'], $rgb['green'], $rgb['blue'], $rgb['alpha']);
imagefill($clone, 0, 0, $trans_index);
}
}
imagecopy($clone, $image, 0, 0, 0, 0, $w, $h);
$this->setImageResource($clone);
}
} | true |
4d6512a3661e192daa7eed80a59bb409244ee7ad | PHP | cryptobuks1/crypterion | /app/Models/NotificationSetting.php | UTF-8 | 432 | 2.59375 | 3 | [] | no_license | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class NotificationSetting extends Model
{
/**
* The attributes that aren't mass assignable.
*
* @var array
*/
protected $guarded = [];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'enable_sms' => "boolean",
'enable_database' => "boolean",
'enable_email' => "boolean",
];
}
| true |
f6f90f7657b9f2a4098b20e1ada9f53858c74335 | PHP | saarge92/service_diploma | /app/Traits/HomeTrait.php | UTF-8 | 1,581 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Traits;
use App\Slider;
use App\About;
use App\Service;
use App\Cart;
use App\Team;
use Illuminate\Support\Facades\Session;
use App\Http\Requests\ContactRequest;
use App\ContactRequestTable;
/**
* Трейт для работы с данными на главной странице (frontend)
*
* Содержит методы, возвращающие необходимые данные для работы главной страницы
*
* @author Inara Durdyeva <inara97_97@mail.ru>
* @copyright Copyright (c) Inara Durdyeva
*/
trait HomeTrait
{
/**
* Данные, необходимые для главной страницы
*
* Возвращает список слайдеров, данные о компании и прочее
*
* @return array $data - список необходимых данных для главной страницы
*/
public function getDataForIndexPage(): array
{
$sliders = Slider::where(['is_on_main' => true])->get();
$abouts = About::all()->first();
$abouts ? $aboutFeatures = explode('|', $abouts->description) : $aboutFeatures = ['Автоматизация бизнеса', 'Интеграция торговых платформ'];
$services = Service::all()->take(6);
$teams = Team::all()->take(4);
$data = array(
'sliders' => $sliders,
'about' => $abouts,
'aboutFeatures' => $aboutFeatures,
'services' => $services,
'teams' => $teams
);
return $data;
}
}
| true |
9a32521d6986060c9d61a7f987299b74f3c37819 | PHP | kahlan/kahlan | /spec/Suite/Reporter/Terminal.spec.php | UTF-8 | 2,453 | 2.734375 | 3 | [
"MIT"
] | permissive | <?php
namespace Kahlan\Spec\Suite\Reporter\Coverage;
use Kahlan\Reporter\Terminal;
describe("Terminal", function () {
beforeEach(function () {
$this->terminal = new Terminal([]);
});
describe("->kahlan()", function () {
it("returns the kahlan ascii logo", function () {
$kahlan = <<<EOD
_ _
/\ /\__ _| |__ | | __ _ _ __
/ //_/ _` | '_ \| |/ _` | '_ \
/ __ \ (_| | | | | | (_| | | | |
\/ \/\__,_|_| |_|_|\__,_|_| |_|
EOD;
$actual = $this->terminal->kahlan();
expect($actual)->toBe($kahlan);
});
});
describe("->kahlanBaseline()", function () {
it("returns the baseline", function () {
$actual = $this->terminal->kahlanBaseline();
expect($actual)->toBe("The PHP Test Framework for Freedom, Truth and Justice.");
});
});
describe("->indent()", function () {
it("returns no indentation by default", function () {
$actual = $this->terminal->indent();
expect($actual)->toBe(0);
});
it("returns indent", function () {
$indent = 2;
$actual = $this->terminal->indent($indent);
expect($actual)->toBe($indent);
});
});
describe("->prefix()", function () {
it("returns an empty prefix by default", function () {
$actual = $this->terminal->prefix();
expect($actual)->toBe('');
});
it("sets the prefix string", function () {
$prefix = 'prefix';
$actual = $this->terminal->prefix($prefix);
expect($actual)->toBe($prefix);
});
});
describe("->readableSize()", function () {
it("returns `'0'` when size is < `1`", function () {
$readableSize = '0';
$actual = $this->terminal->readableSize(0, 2, 1024);
expect($actual)->toBe($readableSize);
});
it("doesn't add any unit for small size number", function () {
$readableSize = '10';
$actual = $this->terminal->readableSize(10, 2, 1024);
expect($actual)->toBe($readableSize);
});
it("formats big size number using appropriate unit", function () {
$readableSize = '9.77K';
$actual = $this->terminal->readableSize(10000, 2, 1024);
expect($actual)->toBe($readableSize);
});
});
});
| true |
616eec16fc2bd6a622c2995b2caa4da8706750aa | PHP | GYung/redis | /src/pagec.php | UTF-8 | 2,629 | 2.609375 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: root
* Date: 17-12-16
* Time: 下午5:56
*/
define("ONE_WEEK",7*86400);
define("VOTE_SCORE",86400/200);
define("ARTICLE_PER_PAGE",10);
index();
function index(){
$redis=new redis();
$redis->connect('127.0.0.1');
$article_id= post_vote($redis,12,"今日头条","www.baidu.com");
add_remove_group($redis,$article_id,array('study'));
var_dump(get_group_articles($redis,'study',2));
print_r(($redis->getLastError()));die;
// vote($redis,1,"article:123");
}
//建立新的文章
function post_vote(Redis $conn,$user,$title,$link){
$article_id=$conn->incr('article');
$voted="voted:".$article_id;
$conn->sAdd($voted,$user);
$conn->expire($voted,ONE_WEEK);
$now=time();
$article='article:'.$article_id;
$conn->delete($article);
if(!$conn->exists($article)){
$conn->hMset($article,array(
'title'=>$title,
'link'=>$link,
'poster'=>$user,
'time' =>$now,
'votes'=>1
));
}
$conn->zAdd('score:',$now+VOTE_SCORE,$article);
$conn->zAdd('time:',$now,$article);
return $article_id;
}
//投票
function vote(Redis $conn,$user,$article){
$cutoff=time()-ONE_WEEK;
$article_id=explode(':',$article);
//判断是否过期
if($conn->zScore('time',$article) < $cutoff)
return;
//已投用户表添加
if($conn->sAdd('voted:'.$article_id[1],$user));
{ //文章分数表自增
$conn->zIncrBy('score:',VOTE_SCORE,$article);
//文章表增加投票数
$conn->hIncrBy($article,'votes', 1);
}
}
//获取排序文章投票
function get_articles(Redis $conn,$page,$order='score:'){
$start=($page-1)*ARTICLE_PER_PAGE;
$end=$start+ARTICLE_PER_PAGE-1;
$ids=$conn->zRevRange($order,$start,$end);
$articles=array();
foreach ($ids as $id){
$article_data=$conn->hGetAll($id);
$article_data['id']=$id;
$articles[]=$article_data;
}
return $articles;
}
//添加群组
function add_remove_group(Redis $conn,$article_id,$to_add=array(),$to_remove=array()){
$article='article:'.$article_id;
foreach ($to_add as $item){
$conn->sAdd('group:'.$item,$article);
}
foreach ($to_remove as $item){
$conn->srem('group:'.$item,$article);
}
}
//获取排序文章组投票
function get_group_articles(Redis $conn,$group,$page,$order='score:'){
$key=$order.$group;
$conn->delete($key);
if(!$conn->exists($key)){
var_dump($conn->zInter($key,array($order,'group:'.$group),null,"MAX"));
}
$conn->expire($key,60);
return get_articles($conn,$page,$key);
}
include('pagev.php'); | true |
3a82763848fe91ae7b680d9edd407b755caf42a7 | PHP | vukojevicc/Kalendar | /tabele/susret.php | UTF-8 | 736 | 2.75 | 3 | [] | no_license | <?php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/Database.php';
class Susret {
public $id;
public $opis_susreta;
public $datum_susreta;
public static function unesiSusret($opis_susreta, $datum_susreta) {
$db = Database::getInstance();
$db->insert('Susret', "INSERT INTO `susreti` (`opis_susreta`, `datum_susreta`) VALUES (:opis_susreta, :datum_susreta);", [
':opis_susreta' => $opis_susreta,
':datum_susreta' => $datum_susreta
]);
}
public static function izlistajSusrete(){
$db = Database::getInstance();
$susreti = $db->select('Susret', 'SELECT * FROM `susreti`');
return $susreti;
}
}
| true |
d6a0baf7bf017bb3c6c2a0dacfcbd428ae9e74c7 | PHP | Shofiul-Alam/magento-app | /src/vendor/magento/framework/GraphQlSchemaStitching/GraphQlReader/Reader/InputObjectType.php | UTF-8 | 2,732 | 2.53125 | 3 | [
"OSL-3.0",
"LicenseRef-scancode-unknown-license-reference",
"AFL-2.1",
"AFL-3.0",
"MIT"
] | permissive | <?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Framework\GraphQlSchemaStitching\GraphQlReader\Reader;
use Magento\Framework\GraphQlSchemaStitching\GraphQlReader\TypeMetaReaderInterface;
use Magento\Framework\GraphQlSchemaStitching\GraphQlReader\MetaReader\TypeMetaWrapperReader;
use Magento\Framework\GraphQlSchemaStitching\GraphQlReader\MetaReader\DocReader;
/**
* Composite configuration reader to handle the input object type meta
*/
class InputObjectType implements TypeMetaReaderInterface
{
/**
* @var TypeMetaWrapperReader
*/
private $typeMetaReader;
/**
* @var DocReader
*/
private $docReader;
/**
* @param TypeMetaWrapperReader $typeMetaReader
* @param DocReader $docReader
*/
public function __construct(TypeMetaWrapperReader $typeMetaReader, DocReader $docReader)
{
$this->typeMetaReader = $typeMetaReader;
$this->docReader = $docReader;
}
/**
* {@inheritdoc}
*/
public function read(\GraphQL\Type\Definition\Type $typeMeta) : array
{
if ($typeMeta instanceof \GraphQL\Type\Definition\InputObjectType) {
$typeName = $typeMeta->name;
$result = [
'name' => $typeName,
'type' => 'graphql_input',
'fields' => [] // Populated later
];
$fields = $typeMeta->getFields();
foreach ($fields as $fieldName => $fieldMeta) {
$result['fields'][$fieldName] = $this->readInputObjectFieldMeta($fieldMeta);
}
if ($this->docReader->read($typeMeta->astNode->directives)) {
$result['description'] = $this->docReader->read($typeMeta->astNode->directives);
}
return $result;
} else {
return [];
}
}
/**
* @param \GraphQL\Type\Definition\InputObjectField $fieldMeta
* @return array
*/
private function readInputObjectFieldMeta(\GraphQL\Type\Definition\InputObjectField $fieldMeta) : array
{
$fieldName = $fieldMeta->name;
$typeMeta = $fieldMeta->getType();
$result = [
'name' => $fieldName,
'required' => false,
'arguments' => []
];
$result = array_merge(
$result,
$this->typeMetaReader->read($typeMeta, TypeMetaWrapperReader::INPUT_FIELD_PARAMETER)
);
if ($this->docReader->read($fieldMeta->astNode->directives)) {
$result['description'] = $this->docReader->read($fieldMeta->astNode->directives);
}
return $result;
}
}
| true |
6e338e22dd0c69667531fed1d551547bde59ce1e | PHP | siefca/pageprotectionplus | /ProtectPage.php | UTF-8 | 3,766 | 2.90625 | 3 | [] | no_license | <?php
/**
* ProtectPage allows to do the following operations:
* - show articles' sections that contain <protect> tags
* - edit articles' sections that contain <protect> tags
* - save articles' sections that contain <protect> tags
* - check whether user has access to the specific objects
*
* PHP version 5
*
* @category Encryption
* @package PageProtectionPlus
* @author Fabian Schmitt <fs@u4m.de>
* @copyright 2006, 2007 Fabian Schmitt
* @license http://www.gnu.org/licenses/gpl.html General Public License version 2 or higher
* @version 2.3b
* @link http://www.mediawiki.org/wiki/Extension:PPP
*/
require_once("AccessList.php");
require_once("Encryption.php");
require_once("ProtectionParser.php");
/**
* Handles showing, editing and saving articles that contain <protect>-tags.
*/
class ProtectPage {
public $mAccess = null;
public $mParser = null;
public $mEnc = null;
private $mParser1 = null;
private $mCipher = null;
private $mDecrypted = false;
private $mShow = "";
/**
* Constructor.
*/
function ProtectPage(&$parser) {
$this->mEnc = new Encryption();
$this->mParser1 = $parser;
}
/**
* Initialises showing a protected area.
* @param params Parameters of tag.
*/
public function initShow($users, $groups, $show) {
$this->mAccess = new AccessList($users, $groups);
$this->mShow = $show;
}
/**
* Checks if the user can read the current object.
* @param user Current User-object.
* @return true if user can read the text, false otherwise.
*/
public function hasAccess(&$user)
{
if ($this->mShow == "text") {
return true;
}
return $this->mAccess->hasAccess($user);
}
/**
* Encrypts all protected tags within a text-block and
* ensures a given username is listed in the list of
* allowed users.
* @param text Text to encrypt protect-tags in.
* @param userName Name of user to ensure to be in permitted list
* (usually current username).
* @param Is_encrypted (default: true) tells how to treat text
* to be parsed.
*/
public function encryptTags(&$text, $userName, $is_encrypted = true) {
$this->mParser = new ProtectionParser($text, $this->mEnc);
$this->mParser->parseText($is_encrypted);
$text = $this->mParser->getEncrypted($userName);
}
/**
* Initialises editing-process by parsing the editpage and getting
* permissions.
* @editpage EditPage object
*/
public function initEdit($editpage) {
$this->mParser = new ProtectionParser($editpage, $this->mEnc);
$this->mParser->parseText();
$this->mAccess = $this->mParser->getAccessList();
}
/**
* Returns decrypted text of editpage initilised with initEdit.
* @return Decrypted text.
*/
public function decryptPage() {
return $this->mParser->getDecrypted();
}
/**
* Decryption wrapper.
* @return Decrypted text.
*/
public function Decrypt($text) {
return $this->mEnc->Decrypt($text);
}
/*
* From Cipe.php
*/
public function parseTag ($text) {
$text = $this->mParser1->parse( $text,
$this->mParser1->mTitle,
$this->mParser1->mOptions,
false, false );
$text = $text->getText();
$text = preg_replace ('~^<p>\s*~', '', $text );
$text = preg_replace ('~\s*</p>\s*~', '', $text );
$text = preg_replace ('~\n$~', '', $text );
return ($text);
}
}
?>
| true |
59993bb64f375599e8abb368d8424195018d5006 | PHP | kaibano/CAZADA | /php/class/clase.php | UTF-8 | 1,301 | 3.25 | 3 | [] | no_license | <?php
class clase
{
private $id_clase;
private $id_centro;
private $turno;
private $alumnos;
private $profesores;
private $id_tutor;
/**
* clase constructor.
* @param $id_clase
* @param $turno
* @param $alumnos
* @param $profesores
* @param $id_tutor
*/
public function __construct($id_clase, $id_centro, $turno, $alumnos, $profesores, $id_tutor)
{
$this->id_clase = $id_clase;
$this->turno = $turno;
$this->alumnos = $alumnos;
$this->profesores = $profesores;
$this->id_tutor = $id_tutor;
}
/**
* @return mixed
*/
public function getIdClase()
{
return $this->id_clase;
}
/**
* @return mixed
*/
public function getIdCentro()
{
return $this->id_centro;
}
/**
* @return mixed
*/
public function getTurno()
{
return $this->turno;
}
/**
* @return mixed
*/
public function getAlumnos()
{
return $this->alumnos;
}
/**
* @return mixed
*/
public function getProfesores()
{
return $this->profesores;
}
/**
* @return mixed
*/
public function getIdTutor()
{
return $this->id_tutor;
}
} | true |
bd1575690a810e18b474b2685fa86e0177c0ad2e | PHP | addisonhall/generatepress-child | /inc/wp-show-posts.php | UTF-8 | 3,058 | 2.78125 | 3 | [] | no_license | <?php
/**
* Modify WP Show Posts output.
*
* Must be included in functions.php
*
* @package GenerateChild
*/
if ( ! defined( 'ABSPATH' ) ) exit;
/**
* Remove permalinks from WP Show Posts output
* @link https://wpshowposts.com/support/topic/selectively-disable-title-link/
*/
// add_filter( 'wpsp_disable_image_link', 'tu_disable_links', 10, 2 );
// add_filter( 'wpsp_disable_title_link', 'tu_disable_links', 10, 2 );
function tu_disable_links( $output, $settings ) {
if ( 1746 === $settings['list_id'] ) {
return true;
}
return $output;
}
/**
* Remove permalinks from WP Show Posts output using DOMDocument and DOMXpath.
* NOTE: This may not be necessary any longer thanks to the built in filters
* as show in the function above. Even if removed, it will live on in the Gist below.
* @link https://gist.github.com/addisonhall/a9d6756de4835018e6ac80a2531e754a
* @link https://stackoverflow.com/questions/36096834/selectivly-replace-certain-html-tags-via-php-while-keeping-some
* @link https://techsparx.com/software-development/wordpress/dom-document-pitfalls.html
*/
// add_filter( 'the_content', 'gpc_remove_wpshowposts_permalinks', 20 );
function gpc_remove_wpshowposts_permalinks( $content ) {
// EDIT HERE!
// Add the ID (as shown) of each WP Show Post entry
// that you want to affect to this array.
// That should be all you need to do.
$which_wpshowposts = array(
'id="wpsp-123"'
);
foreach ( $which_wpshowposts as $wpshowpost ) {
if ( strpos( $content, $wpshowpost ) ) {
$html = new DOMDocument( null, 'UTF-8' );
$html->validateOnParse = false;
@$html->loadHTML( '<meta http-equiv="content-type" content="text/html; charset=utf-8">' . $content );
$xpath = new DOMXPath( $html );
$selectors_array = array(
'//section[@' . $wpshowpost . ']//*[contains(@class,"wp-show-posts-entry-title")]/a',
'//section[@' . $wpshowpost . ']//*[contains(@class,"wp-show-posts-image")]/a',
'//section[@' . $wpshowpost . ']//*[contains(@class,"wp-show-posts-author")]/a',
'//section[@' . $wpshowpost . ']//*[contains(@class,"wp-show-posts-posted-on")]/a'
);
$selectors = implode( '|', $selectors_array );
while ( $node = $xpath->query( $selectors )->item(0) ) {
$fragment = $html->createDocumentFragment();
while ( $node->childNodes->length ) {
$fragment->appendChild( $node->childNodes->item(0) );
}
$node->parentNode->replaceChild( $fragment, $node );
}
// See https://techsparx.com/software-development/wordpress/dom-document-pitfalls.html
$content = str_replace( array( '<body>', '</body>'), '', $html->saveHTML( $html->getElementsByTagName( 'body' )->item(0) ) );
}
}
return $content;
}
| true |
596c1869bc67c02e2e2105bd55833c2bc7cf72c1 | PHP | Anthony-Buisson/PhpMIW | /tp-clean_anthony/pdo/userPdo.php | UTF-8 | 1,516 | 2.984375 | 3 | [] | no_license | <?php
require_once 'GenericPdo.php';
class userPdo extends GenericPdo
{
function create(user $user): bool
{
$req = $this->bdd->prepare('INSERT INTO user (name, email)
VALUES (:name, :email);');
$req->bindValue('name', $user->getName(), PDO::PARAM_STR);
$req->bindValue('email', $user->getEmail(), PDO::PARAM_STR);
return $req->execute();
}
function select($id)
{
$req = $this->bdd->prepare('SELECT * FROM user WHERE id=:id;');
$req->bindValue('id', $id, PDO::PARAM_INT);
$req->execute();
return $req->fetch(PDO::FETCH_ASSOC);
}
function selectAll()
{
$req = $this->bdd->prepare('SELECT * FROM user;');
return $req->execute();
}
function update(user $user): bool
{
$req = $this->bdd->prepare('UPDATE user SET name=:name, email=:email WHERE id=:id');
$req->bindValue('capital', $user->getName(), PDO::PARAM_STR);
$req->bindValue('code2', $user->getEmail(), PDO::PARAM_STR);
return $req->execute();
}
function delete(user $user): bool
{
$articlePdo = new articlePdo();
$toDelete = $articlePdo->selectByUser($user->getId());
foreach ($toDelete as $val){
$articlePdo->delete($val);
}
$req = $this->bdd->prepare('DELETE FROM user WHERE id=:id');
$req->bindValue('id', $user->getId(), PDO::PARAM_INT);
return $req->execute();
}
} | true |
83cb5301a11a473181de129edce458ffa9508153 | PHP | sliker/CakePHP-Counter-Plugin | /Model/Behavior/CountUpBehavior.php | UTF-8 | 3,486 | 2.65625 | 3 | [
"MIT"
] | permissive | <?php
/*
* Count Plugin for CakePHP
*
* PHP version 5
*
* @copyright Copyright 2010, Cake. (http://trpgtools-onweb.sourceforge.jp/)
* @category Behavoir
* @package Count Plugin
* @version 0.1
* @author Cake <cake_67@users.sourceforge.jp>
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
* @link https://github.com/Cake/CakePHP-Counter-Plugin
*/
class CountUpBehavior extends ModelBehavior {
/**
* Settings
* Sample: $setings = array(
* 'ModelName' => array(
* 'SettingName' => 'value',
* ...
* )
* );
*
* countAlias - model alias for Counter model
* foreignKey - foreignKey used in the HABTM association
*
* @var array
*/
public $setings = array(
);
protected $_defaults = array(
'className' => 'Count',
'foreignKey' => 'foreign_key',
'conditions' => '',
'fields' => array(
'COUNT(DISTINCT `Count`.`id`) as `total_count`',
),
'order' => '',
'limit' => null,
'offset' => 0,
'dependent' => true,
'exclusive' => true,
'finderQuery' => '',
);
/**
* Setup
*
* @param AppModel $Model
* @param array $settings
*/
public function setup(Model $Model, $settings = array()) {
if (!isset($this->settings[$Model->alias])) {
$this->settings[$Model->alias] = $this->_defaults;
}
$this->settings[$Model->alias] = array_merge(
$this->settings[$Model->alias],
array(
'countClass' => $Model->name,
'conditions' => array(
'Count.model' => $Model->name,
),
),
$settings
);
// BindModel
$Model->bindModel(
array('hasMany' => array(
'Count' => array(
'className' => $this->settings[$Model->alias]['className'],
'foreignKey' => $this->settings[$Model->alias]['foreignKey'],
'conditions' => $this->settings[$Model->alias]['conditions'],
'fields' => $this->settings[$Model->alias]['fields'],
'order' => $this->settings[$Model->alias]['order'],
'limit' => $this->settings[$Model->alias]['limit'],
'offset' => $this->settings[$Model->alias]['offset'],
'dependent' => $this->settings[$Model->alias]['dependent'],
'exclusive' => $this->settings[$Model->alias]['exclusive'],
'finderQuery' => $this->settings[$Model->alias]['finderQuery'],
)
))
);
}
/**
* Saves a count
*/
public function saveCount(Model $Model, $foreign_key = null) {
$countModel = $Model->Count;
if (empty($this->settings[$Model->alias]['countAlias'])) {
return false;
}
$newCount[$this->settings[$Model->alias]['countAlias']] = array(
'model' => $Model->name,
'foreign_key' => $foreign_key,
'host' => gethostbyaddr($_SERVER["REMOTE_ADDR"]),
);
$countModel->create();
$countModel->save($newCount);
return $countModel->id;
}
/**
* Get total count By Foreign Key
*
* param int $foreign_key
* param array $conditions
*
* return int $total_count
*/
public function getTotalCount(Model $Model, $foreign_key = null, $conditions = array()) {
$countModel = $Model->Count;
$total_count = $this->_getTotalCount($Model, $foreign_key, $conditions);
return array('Count' => array('total_count' => $total_count));
}
protected function _getTotalCount(Model $Model, $foreign_key = null, $conditions = array()) {
$countModel = $Model->Count;
$conditions = array(array(
'model' => $Model->name,
'foreign_key' => $foreign_key,
), (array)$conditions);
return $countModel->find('count', array(
'conditions' => $conditions,
'recursive' => -1,
));
}
}
| true |
f2f8b139f273373764b845754ae1ad72738b692b | PHP | woke221/hello_laravel | /routes/console.php | UTF-8 | 1,126 | 2.65625 | 3 | [
"MIT"
] | permissive | <?php
use Illuminate\Foundation\Inspiring;
/*
|--------------------------------------------------------------------------
| Console Routes
|--------------------------------------------------------------------------
|
| This file is where you may define all of your Closure based console
| commands. Each Closure is bound to a command instance allowing a
| simple approach to interacting with each command's IO methods.
|
*/
Artisan::command('inspire', function () {
$this->comment(Inspiring::quote());
})->describe('Display an inspiring quote');
Artisan::command('create:controller {namespace} {name}', function () {
$namespace = $this->argument('namespace');
$name = $this->argument('name');
$content = File::get("Packages/Controller.txt");
$content = str_replace("{namespace}", $namespace, $content);
$content = str_replace("{name}", $name, $content);
File::put("Packages/Controllers/{$namespace}/{$name}.php", $content);
$this->info("成功创建控制器:Packages/Controllers/{$namespace}/{$name}.php");
})->describe('创建自定义控制器,目录在Packages/Controllers'); | true |
1392bb2b9f43dbdfaca84587447ae32bf962feaa | PHP | magicianlee007/music-house | /app/controllers/LanguageController.php | UTF-8 | 2,575 | 2.6875 | 3 | [
"MIT"
] | permissive | <?php
class LanguageController extends \BaseController {
/**
* Display a listing of the resource.
* GET /pages
*
* @return Response
*/
public function index()
{
$languages = Language::paginate(30);
return View::make('admin.languages', array('languages' => $languages));
}
public function indexPublic()
{
$languages = Language::paginate(30);
return View::make('language.index', array('languages' => $languages));
}
/**
* Show the form for creating a new resource.
* GET /pages/create
*
* @return Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
* POST /pages
*
* @return Response
*/
public function store()
{
//
}
/**
* Display the specified resource.
* GET /pages/{id}
*
* @param int $id
* @return Response
*/
public function show($name)
{
$language = Language::where('slug', $name)->first();
if($language)
{
$ptitle = 'All '. $language->name . ' Albums';
return View::make('album.list', array('data' => $language, 'ptitle' => $ptitle));
}
}
public function showAdmin($slug)
{
$language = Language::where('slug', $slug)->first();
if($language)
{
$ptitle = 'All '. $language->name . ' Albums';
return View::make('admin.album.search', array('data' => $language, 'ptitle' => $ptitle));
}
}
/**
* Show the form for editing the specified resource.
* GET /pages/{id}/edit
*
* @param int $id
* @return Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
* PUT /pages/{id}
*
* @param int $id
* @return Response
*/
public function update($id)
{
$input = Input::all();
$validator = Validator::make(
$input,
array(
'name' => 'required|between:2,100',
)
);
if ($validator->passes()) {
$language = Language::where('id', $id)->first();
$language->name = $input['name'];
$language->slug = Custom::slugify($input['name']);
$language->save();
return json_encode(array('message' => 'successfull', 'status' => 'success'));
} else {
$message = $validator->messages()->all()[0];
return json_encode(array('message' => $message, 'status' => 'error'));
}
}
/**
* Remove the specified resource from storage.
* DELETE /pages/{id}
*
* @param int $id
* @return Response
*/
public function destroy($id)
{
//
}
} | true |
f1b1e265786e3e2aaecbacf5f3c98ad8970d92f7 | PHP | DavorKom/VacationApp | /app/Policies/UserPolicy.php | UTF-8 | 851 | 2.59375 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Policies;
use App\Models\User;
use App\Models\Role;
use Illuminate\Auth\Access\HandlesAuthorization;
class UserPolicy
{
use HandlesAuthorization;
/**
* Determine whether the user can view the model.
*
* @param \App\Models\User $user
* @param \App\Models\User $model
* @return mixed
*/
public function view(User $user, User $model)
{
$project_manager_id = data_get($model->team, 'project_manager_id');
$team_lead_id = data_get($model->team, 'team_lead_id');
if ($user->role->slug == Role::ADMIN) {
return true;
}
if ($user->id == $project_manager_id || $user->id == $team_lead_id) {
return true;
}
if ($user->id == $model->id) {
return true;
}
return false;
}
}
| true |
cffb0f83ea67c29c4b100033cf51daf895fb8ae8 | PHP | SpenserJ/PHPMSN | /example.php | UTF-8 | 960 | 2.796875 | 3 | [] | no_license | <?php
require_once 'msn/msn.php';
$msn = new MSN();
$msn->output = true;
$msn->functions['messageReceived'] = messageReceived;
$msn->signIn('username', 'password', 'display_name');
function messageReceived($messages, $convo) {
if (strpos($messages[3], 'TypingUser') !== false) {
// They are typing
return;
}
// The real messages from the user start in section 5 of the array, 0-4 are headers
for ($i=5; $i<count($messages); $i++) {
$message = $messages[$i];
switch(strtolower($message)) {
case 'what time is it?':
$convo->sendMessage('It is currently ' . date('g:i:sA', mktime()));
break;
case 'what is your name?':
$convo->sendMessage('My name is dot the bot!');
break;
default:
$convo->sendMessage('I don\'t know what to do with your message!');
break;
}
}
}
?> | true |
eddb4361cdd3792606b8858939cbb663d25bb6ae | PHP | Arkitecht/cayan | /src/Arkitecht/Cayan/Response/BalanceInquiryResponse.php | UTF-8 | 841 | 2.5625 | 3 | [] | no_license | <?php
namespace Arkitecht\Cayan\Response;
class BalanceInquiryResponse
{
/**
* @var GiftLoyaltyResponse4 $BalanceInquiryResult
*/
protected $BalanceInquiryResult = null;
/**
* @param GiftLoyaltyResponse4 $BalanceInquiryResult
*/
public function __construct($BalanceInquiryResult = null)
{
$this->BalanceInquiryResult = $BalanceInquiryResult;
}
/**
* @return GiftLoyaltyResponse4
*/
public function getBalanceInquiryResult()
{
return $this->BalanceInquiryResult;
}
/**
* @param GiftLoyaltyResponse4 $BalanceInquiryResult
* @return \Arkitecht\Cayan\BalanceInquiryResponse
*/
public function setBalanceInquiryResult($BalanceInquiryResult)
{
$this->BalanceInquiryResult = $BalanceInquiryResult;
return $this;
}
}
| true |
32de0406d4e7a101223012dd883d80096d6ded2f | PHP | EdwardMartinezH/Soporte_Equipos | /control/SolucionController.php | UTF-8 | 4,940 | 2.828125 | 3 | [] | no_license | <?php
/*
-------Creado por-------
\(°u° )/ Anarchy \( °u°)/
------------------------
*/
// Has encontrado la frase #1024 ¡Felicidades! Ahora tu proyecto funcionará a la primera \\
require_once realpath("..").'\dao\factory\FactoryDao.php';
require_once realpath("..").'\dto\Solucion.php';
require_once realpath("..").'\dao\interfaz\SolucionDao.php';
class SolucionController {
/**
* Crea un objeto Solucion a partir de sus parámetros y lo guarda en base de datos.
* Puede recibir NullPointerException desde los métodos del Dao
* @param idSolucion
* @param problema_idProblema
* @param periféricos_idPeriféricos
* @param software_idSoftware
* @param torre_idTorre
* @param fecha_Solucion
* @param solucion
*/
public static function insert( $idSolucion, $problema_idProblema, $periféricos_idPeriféricos, $software_idSoftware, $torre_idTorre, $fecha_Solucion, $solucion){
$solucion = new Solucion();
$solucion->setIdSolucion($idSolucion);
$solucion->setProblema_idProblema($problema_idProblema);
$solucion->setPeriféricos_idPeriféricos($periféricos_idPeriféricos);
$solucion->setSoftware_idSoftware($software_idSoftware);
$solucion->setTorre_idTorre($torre_idTorre);
$solucion->setFecha_Solucion($fecha_Solucion);
$solucion->setSolucion($solucion);
$solucionDao =FactoryDao::getFactory(self::getGestorDefault())->getSolucionDao(self::getDataBaseDefault());
$rtn = $solucionDao->insert($solucion);
$solucionDao->close();
return $rtn;
}
/**
* Selecciona un objeto Solucion de la base de datos a partir de su(s) llave(s) primaria(s).
* Puede recibir NullPointerException desde los métodos del Dao
* @param idSolucion
* @return El objeto en base de datos o Null
*/
public static function select($idSolucion){
$solucion = new Solucion();
$solucion->setIdSolucion($idSolucion);
$solucionDao =FactoryDao::getFactory(self::getGestorDefault())->getSolucionDao(self::getDataBaseDefault());
$result = $solucionDao->select($solucion);
$solucionDao->close();
return $result;
}
/**
* Modifica los atributos de un objeto Solucion ya existente en base de datos.
* Puede recibir NullPointerException desde los métodos del Dao
* @param idSolucion
* @param problema_idProblema
* @param periféricos_idPeriféricos
* @param software_idSoftware
* @param torre_idTorre
* @param fecha_Solucion
* @param solucion
*/
public static function update($idSolucion, $problema_idProblema, $periféricos_idPeriféricos, $software_idSoftware, $torre_idTorre, $fecha_Solucion, $solucion){
$solucion = self::select($idSolucion);
$solucion->setProblema_idProblema($problema_idProblema);
$solucion->setPeriféricos_idPeriféricos($periféricos_idPeriféricos);
$solucion->setSoftware_idSoftware($software_idSoftware);
$solucion->setTorre_idTorre($torre_idTorre);
$solucion->setFecha_Solucion($fecha_Solucion);
$solucion->setSolucion($solucion);
$solucionDao =FactoryDao::getFactory(self::getGestorDefault())->getSolucionDao(self::getDataBaseDefault());
$solucionDao->update($solucion);
$solucionDao->close();
}
/**
* Elimina un objeto Solucion de la base de datos a partir de su(s) llave(s) primaria(s).
* Puede recibir NullPointerException desde los métodos del Dao
* @param idSolucion
*/
public static function delete($idSolucion){
$solucion = new Solucion();
$solucion->setIdSolucion($idSolucion);
$solucionDao =FactoryDao::getFactory(self::getGestorDefault())->getSolucionDao(self::getDataBaseDefault());
$solucionDao->delete($solucion);
$solucionDao->close();
}
/**
* Lista todos los objetos Solucion de la base de datos.
* Puede recibir NullPointerException desde los métodos del Dao
* @return $result Array con los objetos Solucion en base de datos o Null
*/
public static function listAll(){
$solucionDao =FactoryDao::getFactory(self::getGestorDefault())->getSolucionDao(self::getDataBaseDefault());
$result = $solucionDao->listAll();
$solucionDao->close();
return $result;
}
/**
* Para su comodidad, defina aquí el gestor de conexión predilecto para esta entidad
* @return idGestor Devuelve el identificador del gestor de conexión
*/
private static function getGestorDefault(){
return FactoryDao::$MYSQL_FACTORY;
}
/**
* Para su comodidad, defina aquí el nombre de base de datos predilecto para esta entidad
* @return dbName Devuelve el nombre de la base de datos a emplear
*/
private static function getDataBaseDefault(){
return "soporte";
}
}
//That´s all folks!
| true |
28c7d0ded4e11a8f4fea1905d04aed59d3ed230a | PHP | Siteation/magento2-easymenu | /src/Block/Html/Topmenu.php | UTF-8 | 4,903 | 2.5625 | 3 | [
"MIT"
] | permissive | <?php
/**
* @package AF\EasyMenu
* @author Agata Firlejczyk
* @copyright Copyright (c) 2017 Agata Firlejczyk
* @license See LICENSE for license details.
*/
namespace AF\EasyMenu\Block\Html;
use AF\EasyMenu\Model\Item;
use AF\EasyMenu\Model\Tree;
use Magento\Catalog\Model\Category;
use Magento\Cms\Model\Page;
use Magento\Framework\DataObject\IdentityInterface;
use Magento\Framework\Data\Tree\Node;
use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;
/**
* Class Topmenu
*/
class Topmenu extends Template implements IdentityInterface
{
/**
* @var int
*/
private $storeId;
/**
* @var Tree
*/
private $tree;
/**
* @var \Magento\Framework\Data\Tree\Node
*/
private $menu;
/**
* @var array
*/
private $identities = [
Category::CACHE_TAG,
Page::CACHE_TAG,
];
/**
* Topmenu constructor.
*
* @param \Magento\Framework\View\Element\Template\Context $context
* @param Tree $tree
* @param array $data
*/
public function __construct(
Context $context,
Tree $tree,
array $data = []
) {
parent::__construct($context, $data);
$this->tree = $tree;
}
/**
* @inheritdoc
*/
protected function _construct()
{
parent::_construct();
$this->addData(
[
'cache_lifetime' => 86400,
'cache_tags' => $this->getIdentities(),
]
);
}
/**
* @return array
*/
public function getIdentities()
{
$this->identities[] = Item::CACHE_TAG_STORE . $this->getStoreId();
return $this->identities;
}
/**
* @return array
*/
public function getCacheKeyInfo()
{
$cacheKey = parent::getCacheKeyInfo();
$cacheKey[] = 'TOP_NAVIGATION';
return $cacheKey;
}
/**
* @return string
*/
public function getHtml()
{
$menuTree = $this->getMenu();
return $this->renderMenu($menuTree);
}
/**
* @return Node
*/
public function getMenu()
{
if (null === $this->menu) {
$storeId = $this->_storeManager->getStore()->getId();
$this->menu = $this->tree->getMenuTree($storeId);
}
return $this->menu;
}
/**
* @param Node $menuTree
* @param int $level
*
* @return string
*/
public function renderMenu(
Node $menuTree,
$level = 0
) {
$children = $menuTree->getChildren();
$childrenCount = $children->count();
$html = '';
foreach ($children as $child) {
$url = $child->getUrl();
$html .= '<li ' . $this->getMenuItemAttributes($level, $childrenCount) . '">';
$classAttributes = $this->getLinkClassAttributes($level);
$target = '';
if ($child->getOpenLinkInNewWindow()) {
$target = ' target="_blank" ';
}
$html .= '<a ' . $classAttributes . ' href="' . $url . '"' . $target . 'id="item-' . $child->getId() . '">'
. $child->getName() . '</a>';
$html .= $this->addSubMenu($child, $level + 1);
$html .= '</li>';
}
return $html;
}
/**
* Add sub menu HTML code for current menu item
*
* @param \Magento\Framework\Data\Tree\Node $child
* @param string $childLevel
*
* @return string HTML code
*/
protected function addSubMenu(Node $child, $childLevel)
{
$html = '';
if (!$child->hasChildren()) {
return $html;
}
$html .= '<ul class="level' . $childLevel . ' submenu ' . '">';
$html .= $this->renderMenu($child, $childLevel);
$html .= '</ul>';
return $html;
}
/**
* @param int $level
* @param int $childrenCount
*
* @return string
*/
private function getMenuItemAttributes($level, $childrenCount)
{
$classes = [sprintf('level%d', $level)];
if (0 === $level) {
$classes[] = 'level-top';
}
if ($childrenCount) {
$classes[] .= 'parent';
}
return 'class="' . implode(' ', $classes);
}
/**
* @param int $level
*
* @return string
*/
private function getLinkClassAttributes($level)
{
$attributes = [];
if (0 === $level) {
$attributes[] = 'level-top';
}
return !empty($attributes) ? 'class="' . implode(' ', $attributes) . '"' : '';
}
/**
* @return int
*/
public function getStoreId()
{
if (null === $this->storeId) {
$this->storeId = $this->_storeManager->getStore()->getId();
}
return $this->storeId;
}
}
| true |
b596283e4520bc454b8b39f621bfb366a04c211e | PHP | TimotheOCR/projet4 | /controllers/ControllerUtilisateur.php | UTF-8 | 2,280 | 2.734375 | 3 | [] | no_license | <?php
namespace Controllers;
use Views\View;
use Models\UtilisateurManager;
require_once ('views/View.php');
class ControllerUtilisateur {
private $_view;
private $_articleManager;
private $_utilisateurManager;
public function __construct($url){
$this->init($url);
}
private function init($url){
$methode = $url[1];
if(isset($url[2]) && is_numeric($url[2])){
$this->$methode($url[2]);
}
else{
$this->$methode();
}
}
private function post(){
if(isset($_POST['pseudo'], $_POST['password']) && !empty($_POST['pseudo'] && !empty( $_POST['password']))){
$this->_utilisateurManager = new UtilisateurManager();
$utilisateur = $this->_utilisateurManager->connexionUtilisateur($_POST['pseudo'], $_POST['password']);
if($utilisateur == true){
$this->_view = new View('Utilisateur');
session_start();
$_SESSION['name'] = $_POST['pseudo'];
$this->_view->generate(array('name'=> $_SESSION['name']));
}else {
$this->_view = new View('Reload');
$this->_view->generate(array('wrong' => 'true'));
}
}else{
die("Le formulaire est incomplet");
}
}
private function publicate(){
$this->_view = new View('Publicate');
$this->_view->generate(array());
}
private function view(){
$this->_view = new View('Utilisateur');
$this->_view->generate(array());
}
private function logout(){
session_start();
session_destroy();
$this->_view = new View('Utilisateur');
$this->_view->generate(array());
}
private function mentions(){
$this->_view = new View('Mentions');
$this->_view->generate(array());
}
}
| true |
e16a6fa495ff618ffb6802cd27a8d9346321a9a3 | PHP | ibuildingsnl/qa-tools | /src/Core/IO/Cli/Validator/TextualAnswerValidator.php | UTF-8 | 501 | 2.71875 | 3 | [
"MIT"
] | permissive | <?php
namespace Ibuildings\QaTools\Core\IO\Cli\Validator;
use Ibuildings\QaTools\Core\Assert\Assertion;
use Ibuildings\QaTools\Core\Exception\InvalidAnswerGivenException;
final class TextualAnswerValidator
{
public static function validate($answer)
{
Assertion::nullOrString($answer);
if ($answer === null || trim($answer) === '') {
throw new InvalidAnswerGivenException('No answer given. Please provide an answer.');
}
return $answer;
}
}
| true |
ee3457c7450f8b401c6c3d16a64842ca74be9276 | PHP | acgalia/coffeeculture | /appp/app/controllers/paypal.php | UTF-8 | 1,848 | 2.578125 | 3 | [] | no_license | <?php
session_start();
//Database Info
require_once 'connect.php';
require_once "../../vendor/autoload.php";
use PayPal\Rest\ApiContext;
use PayPal\Auth\OAuthTokenCredential;
use PayPal\Api\Payer;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Details;
use PayPal\Api\Amount;
use PayPal\Api\Transaction;
use PayPal\Api\RedirectUrls;
use PayPal\Api\Payment;
$apiContext = new \PayPal\Rest\ApiContext(
new \PayPal\Auth\OAuthTokenCredential(
'ASkxQ29AAwHW-UGRBSERUAieCbZS-iroT29zIU0dpzaYk6fM-rkQyMvehnnnDIR480dOr3FWPpHJGV15',
'ELpierPGOr13NZ7_skj13NAPw8jqcsdg-33mitgYA4XYa_UaNJLUoV9cvTwgjl4IbfykMsgEikEsXs05'
)
);
$payer = new Payer();
$payer->setPaymentMethod('paypal');
//Create array to contain indiviadual items
$items = []; //on loop: $items += [];
//Create every individual item
$indiv_item = new Item();
$indiv_item ->setName("Laptop")
->setCurrency("PHP")
->setQuantity(1)
->setPrice(15000); //per item
//Add indiv_item to $items[] array
$items[] = $indiv_item;
//Create item list
$item_list = new ItemList();
$item_list ->setItems($items);
//Create amount
$amount = new Amount();
$amount ->setCurrency("PHP")
->setTotal(15000); //grand total
//Create transaction
$transaction = new Transaction();
$transaction ->setAmount($amount)
->setItemList($itemlist)
->setDescription("Transaction from your shop")
->setInvoiceNumber(uniqid("coffeeculture-"));
//where to go after\
$redirectUrls = new RedirectUrls();
$redirectUrls
//Create successful file
->setReturnUrl('https://localhost/sandbox/demo12_paypal/success.php')
//Create unsuccessful file
->setCancelUrl('https://localhost/sandbox/demo12_paypal/failed.php');
$payment = new Payment();
$payment ->setIntent("sale")
->setPayer($payer)
->setRedirectUrls($redirectUrls)
->setTransactions([$transaction]);
try{
$payment->create($apiContext);
}catch(Exception $e){
die($e->getData());
}
$approvalUrl = $payment->getApprovalLink();
header('location: '.$approvalUrl);
?> | true |
e0421593d147456bd66cffd8d4b3d190ac158c52 | PHP | Sajib32/php_blog | /public/home.php | UTF-8 | 2,781 | 2.671875 | 3 | [] | no_license | <?php
session_start();
include_once 'H:\xampp\htdocs\final_attempt_blog\classes\class.user.php';
$user = new User();
if(!isset($_SESSION['uid']) && !isset($_COOKIE['remember']))
{
header("Location:login.php");
}
if(isset($_SESSION['uid']))
{
$uid = $_SESSION['uid'];
}
//$uid = $_SESSION['uid'];
$categories = $user->selectedCategories();
if(isset($_POST['submit'])){
$catName = $_POST['categoryName'];
$user->insert_into_categories_table($catName);
}
if (isset($_GET['q'])){
$user->user_logout();
header("location:login.php");
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Home</title>
<style>
body{
font-family:Arial, Helvetica, sans-serif;
}
h1{
font-family:'Georgia', Times New Roman, Times, serif;
}
</style>
</head>
<body>
<div id="container">
<div id="header">
<a href="home.php?q=logout">LOGOUT</a>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<h1>Folder</h1>
</div>
<div class="panel-body">
<ul>
<?php while($allCategories = $categories->fetch_assoc()) {?>
<li><a href="viewCategoriesPost.php?id=<?php echo $allCategories['id'] ?>"><?php echo $allCategories['cat_name'] ?></a></li>
<?php } ?>
</ul>
</div>
</div>
<div id="main-body">
<br/><br/><br/><br/>
<h1>
<?php
if(isset($_COOKIE['remember']))
{
echo $_COOKIE['remember'];
}
else
{
$user->get_fullname($uid);
}
?>
</h1>
</div>
<div>
<a href="newPost.php">Create Post</a><br>
<a href="newCategory.php">Create Category</a>
<form method="post">
<div class="form-group">
<label for="new_folder">Create a New folder</label>
<input type="text" name="categoryName" class="form-control">
</div>
<div class="form-group">
<input type="submit" name="submit" class="btn btn-success" value="create folder">
</div>
</form>
</div>
<div id="footer"></div>
</div>
</body>
</html>
| true |
d3a8432c7bc1f3f7cfbde4d640e4348085ac1501 | PHP | Christian0102/patterns | /factory.php | UTF-8 | 954 | 2.859375 | 3 | [] | no_license | <?php
/*Factory method Design Patterns*/
abstract class ApptEncoder
{
abstract function encode();
}
class BloggsApptEncoder extends ApptEncoder
{
public function encode(){
return "Appointment data encode in BloggsCall format \n";
}
}
class MeggaApptEncoder extends ApptEncoder
{
public function encode(){
return "Appointment data encode in BloggsCall format \n";
}
}
abstract class CommsManager
{
abstract function getHeaderText();
abstract function getApptEncoder();
abstract function getFooterText();
}
class BloggsCommsManager extends CommsManager
{
public function getHeaderText() {
return "BloggsCall for Header teX \n";
}
public function getApptEncoder() {
return new BloggsApptEncoder();
}
public function getFooterText() {
return "BloggsCal for footerTExt \n";
}
}
$mgr = new BloggsCommsManager();
print_r($mgr->getHeaderText());
print_r($mgr->getApptEncoder());
print_r($mgr->getFooterText());
| true |
affb478a1b8a466f4e2ef55dff61865d25e58594 | PHP | korstiaan/KorsRatioThumbnailBundle | /Filter/Thumbnail.php | UTF-8 | 545 | 2.578125 | 3 | [] | no_license | <?php
namespace Kors\Bundle\RatioThumbnailBundle\Filter;
use Imagine\Image\ImageInterface;
use Imagine\Filter\FilterInterface;
class Thumbnail implements FilterInterface
{
/**
* @var RatioThumbnailBoxInterface
*/
private $box;
/**
* @param RatioThumbnailBox $box
*/
public function __construct(BoxInterface $box)
{
$this->box = $box;
}
/**
* (non-PHPdoc)
* @see Imagine\Filter.FilterInterface::apply()
*/
public function apply(ImageInterface $image)
{
return $image->thumbnail($this->box->getBox($image));
}
} | true |
862a069fb9c587a026914611d67f1e31c08c3ed0 | PHP | XoticRealmsOwnerandDev/CrateSystem | /src/Commands/key.php | UTF-8 | 13,253 | 2.65625 | 3 | [] | no_license | <?php
namespace Commands;
use pocketmine\Server;
use pocketmine\Player;
use pocketmine\command\CommandSender;
use pocketmine\command\ConsoleCommandSender;
use pocketmine\command\PluginCommand;
use pocketmine\item\Item;
use pocketmine\inventory\Inventory;
use pocketmine\item\enchantment\Enchantment;
use pocketmine\item\enchantment\EnchantmentInstance;
use pocketmine\level\Level;
use pocketmine\utils\TextFormat as C;
use CrateSystem\Main;
class key extends PluginCommand{
public function __construct($name, Main $plugin){
parent::__construct($name, $plugin);
$this->setDescription("Get an key for crate");
$this->setAliases(["Key"]);
$this->setPermission("crate.key");
}
public function execute(CommandSender $sender, string $commandLabel, array $args): bool{
if (!$sender->hasPermission("crate.key")) {
$sender->sendMessage("§cYou are not allow to do that.");
return false;
}
$e = Enchantment::getEnchantment((int) 0);
if (count($args) < 1) {
$sender->sendMessage("§b===>§eKeys§b<===");
$sender->sendMessage("§a/key Common <player> §e: §bGet Common key.");
$sender->sendMessage("§c/key Vote <player> §e: §bGet Vote key.");
$sender->sendMessage("§6/key Rare <player> §e: §bGet Rare key.");
$sender->sendMessage("§5/key Mythic <player> §e: §bGet Mythic key.");
$sender->sendMessage("§9/key Legendary <player> §e: §bGet Legendary key.");
$sender->sendMessage("§b===>§eKeys§b<===");
return false;
}
switch ($args[0]){
case "1":
case "common":
case "Common":
if (!$sender->hasPermission("crate.key")) {
$sender->sendMessage("§cYou are not allow to do that.");
return false;
}
if (count($args) < 2) {
$sender->sendMessage("Usage: /key Common <player> <amount>");
return false;
}
if (isset($args[1])) {
$player = $this->getPlugin()->getServer()->getPlayer($args[1]);
}
$player = $this->getPlugin()->getServer()->getPlayer($args[1]);
if (!$player instanceof Player) {
if ($player instanceof ConsoleCommandSender) {
$sender->sendMessage("§cPlease specify a player.");
return false;
}
$sender->sendMessage("§cCould not find player " . $args[1] . ".");
return false;
}
if (count($args) < 3) {
$sender->sendMessage("Usage: /key Common <player> <amount>");
return false;
}
if(isset($args[2])){
$amount = intval($args[2]);
}
$amount = intval($args[2]);
$common = Item::get(131,1,$amount);
$common->addEnchantment(new EnchantmentInstance($e, (int) -0));
$common->setCustomName("§aCommon");
$player->getInventory()->addItem($common);
if($this->getPlugin()->cfg->get("from-user") == true){
$player->sendMessage("§eYou receive ". $args[2] . " §aCommon §eKey from §9" . $sender->getName());
}
if($this->getPlugin()->cfg->get("from-user") == false){
$player->sendMessage("§eYou receive " . $args[2] . " §aCommon §eKey");
}
$sender->sendMessage("§9" . $player->getName() . " §ehas received " . $args[2] . " §aCommon §eKey");
break;
case "2":
case "vote":
case "Vote":
if (!$sender->hasPermission("crate.key")) {
$sender->sendMessage("§cYou are not allow to do that.");
return false;
}
if (count($args) < 2) {
$sender->sendMessage("Usage: /key Vote <player> <amount>");
return false;
}
if (isset($args[1])) {
$player = $this->getPlugin()->getServer()->getPlayer($args[1]);
}
$player = $this->getPlugin()->getServer()->getPlayer($args[1]);
if (!$player instanceof Player) {
if ($player instanceof ConsoleCommandSender) {
$sender->sendMessage("§cPlease specify a player.");
return false;
}
$sender->sendMessage("§cCould not find player " . $args[1] . ".");
return false;
}
if (count($args) < 3) {
$sender->sendMessage("Usage: /key Vote <player> <amount>");
return false;
}
if(isset($args[2])){
$amount = intval($args[2]);
}
$amount = intval($args[2]);
$vote = Item::get(131,2,$amount);
$vote->addEnchantment(new EnchantmentInstance($e, (int) -0));
$vote->setCustomName("§cVote");
$player->getInventory()->addItem($vote);
if($this->getPlugin()->cfg->get("from-user") == true){
$player->sendMessage("§eYou receive " . $args[2] . " §cVote §eKey from §9" . $sender->getName());
}
if($this->getPlugin()->cfg->get("from-user") == false){
$player->sendMessage("§eYou receive " . $args[2] . " §cVote §eKey");
}
$sender->sendMessage("§9" . $player->getName() . " §ehas received " . $args[2] . " §cVote §eKey");
break;
case "3":
case "rare":
case "Rare":
if (!$sender->hasPermission("crate.key")) {
$sender->sendMessage("§cYou are not allow to do that.");
return false;
}
if (count($args) < 2) {
$sender->sendMessage("Usage: /key Rare <player> <amount>");
return false;
}
if (isset($args[1])) {
$player = $this->getPlugin()->getServer()->getPlayer($args[1]);
}
$player = $this->getPlugin()->getServer()->getPlayer($args[1]);
if (!$player instanceof Player) {
if ($player instanceof ConsoleCommandSender) {
$sender->sendMessage("§cPlease specify a player.");
return false;
}
$sender->sendMessage("§cCould not find player " . $args[1] . ".");
return false;
}
if (count($args) < 3) {
$sender->sendMessage("Usage: /key Rare <player> <amount>");
return false;
}
if(isset($args[2])){
$amount = intval($args[2]);
}
$amount = intval($args[2]);
$rare = Item::get(131,3,$amount);
$rare->addEnchantment(new EnchantmentInstance($e, (int) -0));
$rare->setCustomName("§6Rare");
$player->getInventory()->addItem($rare);
if($this->getPlugin()->cfg->get("from-user") == true){
$player->sendMessage("§eYou receive " . $args[2] . " §6Rare §eKey from §9" . $sender->getName());
}
if($this->getPlugin()->cfg->get("from-user") == false){
$player->sendMessage("§eYou receive " . $args[2] . " §6Rare §eKey");
}
$sender->sendMessage("§9" . $player->getName() . " §ehas received " . $args[2] . " §6Rare §eKey");
break;
case "4":
case "mythic":
case "Mythic":
if (!$sender->hasPermission("crate.key")) {
$sender->sendMessage("§cYou are not allow to do that.");
return false;
}
if (count($args) < 2) {
$sender->sendMessage("Usage: /key Mythic <player> <amount>");
return false;
}
if (isset($args[1])) {
$player = $this->getPlugin()->getServer()->getPlayer($args[1]);
}
$player = $this->getPlugin()->getServer()->getPlayer($args[1]);
if (!$player instanceof Player) {
if ($player instanceof ConsoleCommandSender) {
$sender->sendMessage("§cPlease specify a player.");
return false;
}
$sender->sendMessage("§cCould not find player " . $args[1] . ".");
return false;
}
if (count($args) < 3) {
$sender->sendMessage("Usage: /key Mythic <player> <amount>");
return false;
}
if(isset($args[2])){
$amount = intval($args[2]);
}
$amount = intval($args[2]);
$mythic = Item::get(131,4,$amount);
$mythic->addEnchantment(new EnchantmentInstance($e, (int) -0));
$mythic->setCustomName("§5Mythic");
$player->getInventory()->addItem($mythic);
if($this->getPlugin()->cfg->get("from-user") == true){
$player->sendMessage("§eYou receive " . $args[2] . " §5Mythic §eKey from §9" . $sender->getName());
}
if($this->getPlugin()->cfg->get("from-user") == false){
$player->sendMessage("§eYou receive " . $args[2] . " §5Mythic §eKey");
}
$sender->sendMessage("§9" . $player->getName() . " §ehas received " . $args[2] . " §5Mythic §eKey");
break;
case "5":
case "legendary":
case "Legendary":
if (!$sender->hasPermission("crate.key")) {
$sender->sendMessage("§cYou are not allow to do that.");
return false;
}
if (count($args) < 2) {
$sender->sendMessage("Usage: /key Legendary <player><amount>");
return false;
}
if (isset($args[1])) {
$player = $this->getPlugin()->getServer()->getPlayer($args[1]);
}
$player = $this->getPlugin()->getServer()->getPlayer($args[1]);
if (!$player instanceof Player) {
if ($player instanceof ConsoleCommandSender) {
$sender->sendMessage("§cPlease specify a player.");
return false;
}
$sender->sendMessage("§cCould not find player " . $args[1] . ".");
return false;
}
if (count($args) < 3) {
$sender->sendMessage("Usage: /key Legendary <player> <amount>");
return false;
}
if(isset($args[2])){
$amount = intval($args[2]);
}
$amount = intval($args[2]);
$legendary = Item::get(131,5,$amount);
$legendary->addEnchantment(new EnchantmentInstance($e, (int) -0));
$legendary->setCustomName("§9Legendary");
$player->getInventory()->addItem($legendary);
if($this->getPlugin()->cfg->get("from-user") == true){
$player->sendMessage("§eYou receive " . $args[2] . " §9Legendary §eKey from §9" . $sender->getName());
}
if($this->getPlugin()->cfg->get("from-user") == false){
$player->sendMessage("§eYou receive " . $args[2] . " §9Legendary §eKey");
}
$sender->sendMessage("§9" . $player->getName() . " §ehas received " . $args[2] . " §9Legendary §eKey");
break;
default:
$sender->sendMessage("§cPlease use /key <key> <player> <amount>");
break;
}
return true;
}
}
| true |
5590825546db0a950920ad60085e9b3e6735c93d | PHP | rahulyhg/moneyzaurus-api | /web/app/src/Module/Config.php | UTF-8 | 1,113 | 2.5625 | 3 | [] | no_license | <?php
namespace Api\Module;
use SlimApi\Kernel\Config as KernelConfig;
/**
* Class Config
*
* @package Api\Kernel
*/
class Config extends KernelConfig
{
const DATABASE = 'database';
const DATABASE_ENTITIES = 'databaseEntities';
const DATABASE_CONNECTION = 'databaseConnection';
const PASSWORD_DEFAULT_COST = 'defaultPasswordCost';
const EMAIL = 'email';
const SECURITY = 'security';
const BASE_URL = 'baseUrl';
const LOG = 'log';
/**
* @param string $key
* @param string $default
*
* @return string
*/
public function env($key, $default = null)
{
if (is_array($key)) {
foreach ($key as $k) {
$value = $this->env($k, $default);
if (!empty($value) && $value !== $default) {
break;
}
}
} else {
$value = getenv($key);
}
if (empty($value) && !empty($default)) {
return $default;
}
return $value;
}
}
| true |
886384a66ede3d52546686d56ea12760ad67be3e | PHP | TheRealStart/yii2-jsend-response | /jsend/Response.php | UTF-8 | 2,648 | 2.59375 | 3 | [] | no_license | <?php
namespace TRS\RestResponse\jsend;
class Response
{
private $response;
public function __construct($parameters = array(), $statusCode = 200)
{
$this->init();
if (!empty($parameters) && is_array($parameters))
$this->response->setParameters($parameters);
$this->response->setStatusCode($statusCode);
}
private function init()
{
$oauth2service = \Yii::$app->getModule('oauth2');
$this->response = $oauth2service->getServer()->getResponse();
if (!$this->response)
$this->response = new \filsh\yii2\oauth2server\Response();
}
/**
* @return string
*/
protected function getResponseFormat()
{
return 'json';
}
/**
* @param string $name
* @param string $value
* @return void
*/
public function addHeader($name, $value)
{
$this->response->addHttpHeaders([$name => $value]);
}
/**
* @return void
*/
public function clearHeaders()
{
$this->response->setHttpHeaders([]);
}
/**
* @param string $name
* @return void
*/
public function removeHeader($name)
{
$headers = $this->getHeaders();
if (isset($headers[$name]))
delete($headers[$name]);
$this->response->setHttpHeaders($headers);
}
/**
* @return array
*/
public function getHeaders()
{
return $this->response->getHttpHeaders();
}
/**
* @return \filsh\yii2\oauth2server\Response
*/
public function getResponse() {
return $this->response;
}
/**
* @param mixed $data
* @return \filsh\yii2\oauth2server\Response
*/
public static function success($data)
{
return (new Response([
'status' => 'success',
'data' => $data
], 200))->getResponse();
}
/**
* @param string $message
* @param mixed $data
* @param int $code
* @return \filsh\yii2\oauth2server\Response
*/
public static function error($message, $data, $code = 500)
{
return (new Response([
'status' => 'error',
'message' => $message,
'code' => $code,
'data' => $data,
], 500))->getResponse();
}
/**
* @param mixed $data
* @param int $code
* @return \filsh\yii2\oauth2server\Response
*/
public static function fail($data, $code = 400)
{
return (new Response([
'status' => 'fail',
'data' => $data
], $code))->getResponse();
}
}
| true |
0d99c09868c4c7ac7544dc3b507bf9362d591d01 | PHP | trantuyet/c2.php.PrimeNumN | /index.php | UTF-8 | 1,091 | 3.671875 | 4 | [] | no_license | <!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Prime Num</title>
</head>
<body>
<h1 style="color: purple">Hiển thị tất cả các số nguyên tố nhỏ hơn N</h1>
<form action="" method="post">
Hãy nhập vào số N: <input type="number" name="num" value="" style="color: purple">
<button type="submit">Hiển thị</button>
</form>
<?php if(isset($_POST["num"])) {
function isPrime($num)
{
if ($num < 2) {
return false;
}
for ($i = 2; $i <= (sqrt($num)); $i++) {
if ($num % $i == 0) {
return false;
}
}
return true;
}
$n = $_POST["num"];
print ("Các số nguyên tố nhỏ hơn ".$n." là: <br>");
for ($i = 0; $i < $n; $i++) {
if (isPrime($i)) {
echo($i . ", ");
}
}
} ?>
</body>
</html> | true |
44fe6d767a1e47e2bcc73bcf6eaf8abae031f761 | PHP | GuillaumeBande/ExoSymfony | /src/Controller/ArticleController.php | UTF-8 | 2,205 | 2.875 | 3 | [] | no_license | <?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class ArticleController extends AbstractController
{
private $articles = [
1 => [
"title" => "La vaccination c'est trop géniale",
"content" => "bablablblalba",
"id" => 1,
"published" => true,
],
2 => [
"title" => "La vaccination c'est pas trop géniale",
"content" => "blablablabla",
"id" => 2,
"published" => true
],
3 => [
"title" => "Balkany c'est trop génial",
"content" => "balblalblalb",
"id" => 3,
"published" => false
],
4 => [
"title" => "Balkany c'est pas trop génial",
"content" => "balblalblalb",
"id" => 4,
"published" => true
],
5 => [
"title" => "Le PHP c'est trop génial",
"content" => "balblalblalb",
"id" => 5,
"published" => true
],
6 => [
"title" => "Symfony c'est trop génial",
"content" => "balblalblalb",
"id" => 6,
"published" => true
]
];
/**
* @Route("/articles", name="articleList")
*/
public function articleList(): Response
{
return $this->render('article_list.html.twig', [
'articles' => $this->articles
]);
}
/**
* @Route("/articles/{id}", name="articleShow")
*/
public function articleShow($id): Response
{
// j'utilise la méthode render de l'AbstractController
// pour récupérer un fichier Twig, le transformer en HTML
// et le renvoyer en réponse HTTP au navigateur
// Pour utiliser des variables dans le fichier twig, je dois
// lui passer un tableau en second parametre, avec toutes les
// variables que je veux utiliser
return $this->render('article_show.html.twig', [
'article' => $this->articles[$id]
]);
}
} | true |
7383ecf966673366cce6be0af12c00430693842f | PHP | Akkaraphol1/WebProPHP | /SumOfNumber.php | UTF-8 | 4,442 | 3.546875 | 4 | [] | no_license | <!DOCTYPE HTML>
<html>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<center><h1> HW2 : Sum of number </h1></center>
<center><h2> Num 1: <input type="text" name="num1"> </h2></center> <br>
<center><h2> <input type="radio" name="operator" value="+"> + :
<input type="radio" name="operator" value="-"> - :
<input type="radio" name="operator" value="*"> * :
<input type="radio" name="operator" value="/"> / : </h2></center> <br>
<center><h2> Num 2: <input type="text" name="num2"> </h2></center> <br>
<center><h2> <input type="radio" name="operator2" value="+"> + :
<input type="radio" name="operator2" value="-"> - :
<input type="radio" name="operator2" value="*"> * :
<input type="radio" name="operator2" value="/"> / : </h2></center> <br>
<center><h2> Num 3: <input type="text" name="num3"> </center> <h2><br>
<center> <input type="submit"> </center> <br>
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$n1 = $_POST['num1'];
$n2 = $_POST['num2'];
$n3 = $_POST['num3'];
$oper = $_POST['operator'];
if($oper == "+"){
$x = $n1+$n2;
}
else if($oper == "-"){
$x = $n1-$n2;
}
else if($oper == "*"){
$x = $n1*$n2;
}
else if($oper == "/"){
$x = $n1/$n2;
}
$oper2 = $_POST['operator2'];
// Add
if(($oper2 == "+") && ($oper == "+"))
{
$y = $x+$n3;
echo "<center><h2> Sum of Number = " .$y. "</h2></center><br>";
}
else if(($oper2 == "-") && ($oper == "+"))
{
$y = $x-$n3;
echo "<center><h2> Sum and Sub of Number = " .$y. "</h2></center><br>";
}
else if(($oper2 == "*") && ($oper == "+"))
{
$y = $x*$n3;
echo "<center><h2> Sum and Mul of Number = " .$y. "</h2></center><br>";
}
else if(($oper2 == "/") && ($oper == "+"))
{
$y = $x/$n3;
echo "<center><h2> Sum and Div of Number = " .$y. "</h2></center><br>";
}
//Sub
if(($oper2 == "+") && ($oper == "-"))
{
$y = $x+$n3;
echo "<center><h2> Sub and Sum of Number = " .$y. "</h2></center><br>";
}
else if(($oper2 == "-") && ($oper == "-"))
{
$y = $x-$n3;
echo "<center><h2> Sub of Number = " .$y. "</h2></center><br>";
}
else if(($oper2 == "*") && ($oper == "-"))
{
$y = $x*$n3;
echo "<center><h2> Sub and Mul of Number = " .$y. "</h2></center><br>";
}
else if(($oper2 == "/") && ($oper == "-"))
{
$y = $x/$n3;
echo "<center><h2> Sub and Div of Number = " .$y. "</h2></center><br>";
}
//Mul
if(($oper2 == "+") && ($oper == "*"))
{
$y = $x*$n3;
echo "<center><h2> Mul and Sum of Number = " .$y. "</h2></center><br>";
}
else if(($oper2 == "-") && ($oper == "*"))
{
$y = $x-$n3;
echo "<center><h2> Mul and Sub of Number = " .$y. "</h2></center><br>";
}
else if(($oper2 == "*") && ($oper == "*"))
{
$y = $x*$n3;
echo "<center><h2> Mul of Number = " .$y. "</h2></center><br>";
}
else if(($oper2 == "/") && ($oper == "*"))
{
$y = $x/$n3;
echo "<center><h2> Mul and Div of Number = " .$y. "</h2></center><br>";
}
//Div
if(($oper2 == "+") && ($oper == "/"))
{
$y = $x+$n3;
echo "<center><h2> Div and Sum of Number = " .$y. "</h2></center><br>";
}
else if(($oper2 == "-") && ($oper == "/"))
{
$y = $x-$n3;
echo "<center><h2> Div and Sub of Number = " .$y. "</h2></center><br>";
}
else if(($oper2 == "*") && ($oper == "/"))
{
$y = $x*$n3;
echo "<center><h2> Div and Mul of Number = " .$y. "</h2></center><br>";
}
else if(($oper2 == "/") && ($oper == "/"))
{
$y = $x/$n3;
echo "<center><h2> Div of Number = " .$y. "</h2></center><br>";
}
else if(($oper2 == "") || ($oper == "") || (($oper2 == "") && ($oper == "")))
{
$y = 0;
echo "<center><h2> Error Please check Data Try again!!! " .$y. "</h2></center><br>";
}
// code block
}
?>
</body>
</html>
| true |
53d6d83d6c4ab0b7957aaa569ec4c37d1b1d2a3f | PHP | ronyfrias05/Programacion2019_RonyF | /modulo_2/10_registro_de_datos/lista_cartas.php | UTF-8 | 749 | 2.625 | 3 | [] | no_license | <?php
session_start();
// Verificar si el usuario esta logeado
if (! isset($_SESSION['id_user'])) {
header("Location: login.php");
exit;
}
// Incluir la conexion
require_once 'conexion.php';
$sql = "SELECT c.id, c.name, c.link, c.price, u.name AS created_by
FROM cartas c
INNER JOIN users u ON (u.id = c.created_by)
WHERE c.activo = 1 ORDER BY id DESC;";
// Ejecutar el query y traer todos los datos
$datos = $conexion->query($sql)->fetchAll();
//Buscar
if (isset($_GET['buscar'])) {
$busqueda = $_GET['busqueda'];
$sql = "SELECT id, name, link, price, created_by from cartas Where name like '%$busqueda%'";
$datos = $conexion->query($sql)->fetchAll();
}
// Incluir la vista
require_once 'vistas/lista_cartas.html.php'; | true |
e0a5bffefb5d4077adbadd3702530fc8ca2fd729 | PHP | manopiu/TesteMVC | /model/PedidoModel.php | MacCentralEurope | 6,385 | 2.640625 | 3 | [] | no_license | <?php
//include '../config/includes/Conexao.php';
require_once '../objetos/ProdutoDTO.php';
require_once '../objetos/PedidoDTO.php';
require_once '../objetos/ClienteDTO.php';
class PedidoModel{
//buscar taxa de entrega
public function buscarTaxaVigente(){
echo "buscarTaxa";
$sql = "SELECT * FROM `tb_taxa` WHERE tax_status = 'S'";
$conn = new Conexao();
$query = $conn->Conn();
$resultado = $query->query($sql);
if(!$resultado){
die('Consulta Inválida: ' . mysql_errno());
}
$reg = mysqli_fetch_assoc($resultado);
$taxa = $reg["tax_valor"];
mysqli_free_result($resultado);
$conn->fecharConn();
return $taxa;
}
//atualizar taxa
public function atualizarTaxa(){
}
//persistir pedido
public function salvarPedido($pedidoDTO){
echo "Dentro de salvarPedido";
$validado;
//instancia conexao
$conn = new Conexao();
//recebe conexo
$mysqli = $conn->Conn();
//desabilita o autocommit
$mysqli->autocommit(FALSE);
try {
//pegar data do sistema
date_default_timezone_set("Etc/GMT+3");
$data = date("d-m-Y H:i:s");
echo "<br><br> total = ".$pedidoDTO->getValorTotal()." formatado = ".
str_replace(",",".",$pedidoDTO->getValorTotal())."<br>";
$sql = "INSERT INTO `tb_pedidos` (`usu_id`, `pedi_sessao`, `pedi_status`,
`pedi_troco`, `pedi_valorTotal`, `pedi_dataPedido`,
`pedi_formaPagamento`, `pedi_taxa`)
VALUES (".$pedidoDTO->getClienteDTO()->getUsu_id().",'test teste','P',".
str_replace(",",".",$pedidoDTO->getTroco()).",".
str_replace(",",".",$pedidoDTO->getValorTotal()).
",now(),'".$pedidoDTO->getFormaPagamento()."',".
str_replace(",",".",$pedidoDTO->getTaxa()).");";
echo $sql;
$mysqli->query($sql);
//pegar ultimo id inserido
$pedidoId = $mysqli->insert_id;
echo "<br>Pedido ID: ".$pedidoId."<br>";
//inserir os produtos na tabela tb_produtos_pedidos
$arrayProdutos = $pedidoDTO->getArrayProdutos();
foreach($arrayProdutos as $produtoDTO) {
echo "produto - ".$produtoDTO->getId()."<br>";
$sql = "INSERT INTO `tb_produtos_pedidos`(`pedi_id`, `prod_id`, `prpe_qtd`)
VALUES ('".$pedidoId."','".$produtoDTO->getId()."','".
$produtoDTO->getQuantidade()."');";
$mysqli->query($sql);
}
/* commit insert */
$mysqli->commit();
$validado = true;
} catch (Exception $e) {
/* Rollback */
$mysqli->rollback();
echo "catch";
$validado = false;
}finally {
$conn->fecharConn();
return $validado;
}
}
//recuperar os pedidos de um cliente
public function recuperarPedidos($usuarioId){
echo "<br>Dentro de recuperarPedidos<br>";
//criar um array d epedidos
$arrayPedidos = array();
$sql = "SELECT *, DATE_FORMAT(pedi_dataPedido,'%d/%m/%Y %H:%i') as data,
DATE_FORMAT(pedi_dataEntraga,'%d/%m/%Y %H:%i') as dataEntrega
FROM `tb_pedidos` WHERE usu_id = $usuarioId AND pedi_status <> 'C';";
echo "<br>".$sql."<br>";
$conn = new Conexao();
$mysqli = $conn->Conn();
if($resultado = $mysqli->query($sql)){
while ($row = mysqli_fetch_array($resultado)) {
//echo "dentro ".$row['prod_id']." - ".$row['prod_nome']."<br>";
$pedidoDTO = new PedidoDTO();
$pedidoDTO->setId($row['pedi_id']);
$pedidoDTO->setSessao($row['pedi_sessao']);
$pedidoDTO->setStatus($this->verificarStatus($row['pedi_status']));
$pedidoDTO->setTroco($row['pedi_troco']);
$pedidoDTO->setValorTotal($row['pedi_valorTotal']);
$pedidoDTO->setDataPedido($row['data']);
$pedidoDTO->setTaxa($row['pedi_taxa']);
if($row['dataEntrega'] == null || $row['dataEntrega'] == ""){
$pedidoDTO->setDataEntrega("");
}else{
$pedidoDTO->setDataEntrega($row['dataEntrega']);
}
$pedidoDTO->setFormaPagamento($row['pedi_formaPagamento']);
$arrayPedidos[] = ($pedidoDTO);
//echo "id: $genero[0], Genero: $genero[1]<br>";
//echo "Final";
//echo "<br>$i<br>";
}
//buscar os produtos dos pedidos
foreach($arrayPedidos as $pedido2DTO) {
//echo "<br> dentro";
//$pedido2DTO->getTaxa()." taxa".$pedido2DTO->getId()."<br>";
$pedido2DTO->setArrayProdutos($this->produtosPedido($pedido2DTO->getId()));
}
//buscar cliente
//buscar entregador
mysqli_free_result($resultado);
}
$conn->fecharConn();
return $arrayPedidos;
}
//Formatar status do pedido
//Se for E = Entregue
//Se for P = Pendente
//Se for T = Transito
//Se for C = Cancelado
public function verificarStatus($foo){
$status = "";
if($foo == "E"){
$status = "Encerrado";
}elseif ($foo == "P"){
$status = "Processando";
}elseif ($foo == "T"){
$status = "Em trnsito";
}elseif ($foo == "C"){
$status = "Cancelado";
}
//echo "<br>".$status;
return $status;
}
//retornar um array de produtos de um determinado pedido
public function produtosPedido($pedidoId){
echo "<br>dentro de produtosPedido";
$sql = "SELECT * FROM tb_produtos_pedidos, tb_produto
WHERE tb_produtos_pedidos.prod_id = tb_produto.prod_id
AND tb_produtos_pedidos.pedi_id = $pedidoId";
echo "<br>".$sql;
$conn = new Conexao();
$mysqli = $conn->Conn();
//criar um array que ir receber a lista de produtos
$produtosArray = array();
if($resultado = $mysqli->query($sql)){
while ($row = mysqli_fetch_array($resultado)) {
//echo "dentro ".$row['prod_id']." - ".$row['prod_nome']."<br>";
$produtoDTO = new ProdutoDTO();
$produtoDTO->setId($row['prod_id']);
$produtoDTO->setNome($row['prod_nome']);
$produtoDTO->setTamanho($row['prod_tamanho']);
$produtoDTO->setCusto($row['prod_custo']);
$produtoDTO->setStatus($row['prod_status']);
$produtoDTO->setDescricao($row['prod_descricao']);
$produtoDTO->setQuantidade($row['prpe_qtd']);
$produtosArray[] = ($produtoDTO);
//echo "id: $genero[0], Genero: $genero[1]<br>";
//echo ;
//echo "<br>$i<br>";
}
mysqli_free_result($resultado);
}
$conn->fecharConn();
return $produtosArray;
}
}
?>
| true |
0461e1ff81714a48c02550029107a791fc499797 | PHP | kylephillips/loopsylist | /app/Loopsy/Entities/DollType/DollType.php | UTF-8 | 272 | 2.515625 | 3 | [] | no_license | <?php namespace Loopsy\Entities\DollType;
class DollType extends \Eloquent {
protected $table = 'dolltypes';
protected $fillable = array(
'title', 'slug', 'description'
);
public function dolls()
{
return $this->belongsToMany('Doll', 'dolls_dolltypes');
}
} | true |
1cd204263e2739be7fd22ae25c20b00baea2580b | PHP | phpstan/phpstan-src | /e2e/phpstan-phpunit-190/test.php | UTF-8 | 413 | 2.703125 | 3 | [
"MIT"
] | permissive | <?php // lint >= 8.1
namespace PhpstanPhpUnit190;
class FoobarTest
{
public function testBaz(): int
{
$matcher = new self();
$this->acceptCallback(static function (string $test) use ($matcher): string {
match ($matcher->testBaz()) {
1 => 1,
2 => 2,
default => new \LogicException()
};
return $test;
});
return 1;
}
public function acceptCallback(callable $cb): void
{
}
}
| true |
df18fa12484eb2f4ed4bc6110488f09e78305c62 | PHP | AdamJDuggan/brad-php | /shorthands.php | UTF-8 | 660 | 3.8125 | 4 | [] | no_license | <?php
//Ternary
$loggedIn = false;
echo($loggedIn) ? "Logged in" : "Not logged in"; //Logged in
echo "<br/>";
$isRegistered = ($loggedIn == true);
echo($isRegistered) ? true : false; //1 php prints 1 if true
$age = 20;
$score = 15;
echo "Yout score is: ". ($score > 10 ? ($age > 10 ? "Average" : "Exceptional") : ($age > 10 ? "Horrible" : "Average"));
echo "<br/>";
$array = [1,2,3,4,5];
?>
<div>
<?php if($loggedIn){
?>
<h1>Welcome user</h1>
<?php
}else{
?><h1>Welcome Guest</h1><?php
} ?></div>
<div>
<?php foreach($array as $val): ?>
<?php echo $val; ?>
<?php endforeach; ?>
</div>
| true |
b06b09df5667a7122e8d224ffbe62141cea29daa | PHP | auralifiar/PWPB | /looping/perulangan.php | UTF-8 | 909 | 4.28125 | 4 | [] | no_license | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Looping</title>
</head>
<body>
<!-- 1. FOR -->
<?php
for ($i = 0; $i <= 10; $i++) {
echo "ini perulangan ke-".$i."<br>";
}
?>
<br>
<!-- 2. WHILE -->
<?php
$ulang = 0;
while($ulang < 10) {
echo "ini adalah perulangan ke-".$ulang."<br>";
$ulang++;
}
?>
<br>
<!-- 3. DO WHILE -->
<?php
$ulang = 0;
do {
echo "ini adalah perulangan ke-".$ulang."<br>";
$ulang++;
} while ($ulang <= 10);
?>
<br>
<!-- 4. FOREACH -->
<?php
$buah = ["mangga", "apel", "pisang", "nanas", "pepaya"];
foreach($buah as $fruits) {
echo $fruits."<br>";
}
?>
</body>
</html> | true |
92de93b4de9d31fc352539de41675f0d68b7909b | PHP | pleonasm/bsg | /src/ColorsTrait.php | UTF-8 | 1,176 | 3.25 | 3 | [] | no_license | <?php
namespace Pleo\BSG;
use UnexpectedValueException;
trait ColorsTrait
{
private $colors = [
Colors::YELLOW,
Colors::GREEN,
Colors::PURPLE,
Colors::RED,
Colors::BLUE,
Colors::BROWN
];
public function getColorsFromBitMap($bitmap)
{
$colorsInBitmap = [];
foreach ($this->colors as $color) {
if ($color & $bitmap) {
$colorsInBitmap[] = $color;
}
}
return $colorsInBitmap;
}
/**
* Function that enforces that a bitmap must have only 1 color in it
*/
public function getSingleColor($bitmap)
{
$colors = $this->getColorsFromBitMap($bitmap);
if (count($bitmap) > 1) {
throw new UnexpectedValueException('Given bitmap has more than 1 color bitmap number: ' . $bitmap);
}
return array_pop($colors);
}
/**
* @param array $colors
* @return int
*/
public function createBitMapFromColorsArray(array $colors)
{
$result = 0;
foreach ($colors as $color) {
$result += $color;
}
return $result;
}
} | true |
7cd0eee93e9a8534970a3a10e9034eeddecc5c50 | PHP | anzerr/LiteAdmin | /entity/class.DB.php | UTF-8 | 915 | 2.984375 | 3 | [] | no_license | <?php
namespace Jinx\Entity;
class DB
{
protected static $_pdo;
protected static $_table;
public function __construct($pdo, $table = "")
{
self::$_pdo = $pdo;
self::$_table = $table;
}
public function query($sql)
{
return $this->_pdo->query($sql);
}
public function exec($sql)
{
return $this->_pdo->exec($sql);
}
public function prepare($sql)
{
return $this->_pdo->prepare($sql);
}
public function lastInsertId()
{
return $this->_pdo->lastInsertId($this->_table . "_id_seq");
}
public function getObject($where = array())
{
$sql = "SELECT * FROM " . $this->_table . " WHERE id = " . $where['id'] . ";";
if ($req = $this->query($sql))
{
return $req;
}
return false;
}
public function getObjects($where = array())
{
$sql = $sql = "SELECT * FROM " . $this->_table . ";";
if ($req = $this->query($sql))
{
return $req;
}
return false;
}
}
?> | true |
2495ee086f07be25c2f21c77d794e9b9a632d033 | PHP | laraform/laraform-laravel | /src/Contracts/Authorization/Permission.php | UTF-8 | 514 | 2.859375 | 3 | [
"MIT"
] | permissive | <?php
namespace Laraform\Contracts\Authorization;
use Laraform\Contracts\User\User;
interface Permission
{
/**
* Return new Permission instance
*
* @param string $role
* @param callable $callback
*/
public function __construct($role, callable $callback = null);
/**
* Determine if user is allowed to perform an action
*
* @param User $user
* @param object $entity
* @return boolean
*/
public function allowed(User $user, $entity = null);
} | true |
eea36cfd4a91e8e3a467bb63c5ff90188aad154f | PHP | johnrobox/angular-crud | /add.php | UTF-8 | 1,144 | 2.890625 | 3 | [] | no_license | <?php
include 'connection.php';
$data = json_decode( file_get_contents('php://input') );
if (!isset($data->firstname) || empty($data->firstname)) {
$response = array(
'valid' => false,
'message' => 'Firstname is required.'
);
} else if (!isset($data->lastname) || empty($data->lastname)) {
$response = array(
'valid' => false,
'message' => 'Lastname is required.'
);
} else if (!isset($data->address) || empty($data->address)) {
$response = array(
'valid' => false,
'message' => 'Address is required.'
);
} else {
$firstname = $data->firstname;
$lastname = $data->lastname;
$address = $data->address;
$insert = $connection->query('INSERT INTO employees (firstname, lastname, address) VALUES ("'.$firstname.'","'.$lastname.'","'. $address.'")');
if ($insert) {
$response = array(
'valid' => true,
'message' => 'Employee add success'
);
} else {
$response = array(
'valid' => false,
'message' => 'Error in adding employee .'
);
}
}
echo json_encode($response); | true |
44deaefc4f47e0402657a3e8d20c8f7e68ddcb1e | PHP | jaimeirazabal1/facturacion | /ajax/nueva_empresa.php | UTF-8 | 1,092 | 2.859375 | 3 | [] | no_license | <?php
include('is_logged.php');//Archivo verifica que el usario que intenta acceder a la URL esta logueado
/*Inicia validacion del lado del servidor*/
if (empty($_POST['nombre'])) {
$errors[] = "Nombre vacío";
} else if (!empty($_POST['nombre'])){
/* Connect To Database*/
require_once ("../config/db.php");//Contiene las variables de configuracion para conectar a la base de datos
require_once ("../config/conexion.php");//Contiene funcion que conecta a la base de datos
require_once ("../classes/empresa.php");//Contiene funcion que conecta a la base de datos
$empresa = new Empresa($con);
if (count($empresa->buscar(array("nombre"=>$_POST['nombre'])))) {
?>
<div class="alert alert-danger">
<?php echo "El nombre de la empresa ya fue usado!" ?>
</div>
<?php
}else{
if($r = $empresa->nueva($_POST['nombre'],$_POST['rif'])){
?>
<div class="alert alert-success">
La empresa ha sido creada
</div>
<?php
}else{
?>
<div class="alert alert-danger">
<?php echo $r ?>
</div>
<?php
}
}
}
?> | true |
c936042009e9e5474524e327523863fa3c9ff2af | PHP | brm-barreraj/appVendedores | /server/class/class.Usuario.inc.php | UTF-8 | 6,442 | 2.734375 | 3 | [
"MIT"
] | permissive | <?php
class Usuario{
private $limite=10;
/*metodos para los usuarios*/
function getLimit(){
return $this->limite;
}
function getCountUsuarios(){
DB_DataObject::debugLevel(0);
$obj = DB_DataObject::Factory('VenUsuario');
$ret = $obj->count();
//printVar($ret);
return $ret;
}
//obtiene todos los usuarios
function getAllUsuarios(){
DB_DataObject::debugLevel(0);
$obj = DB_DataObject::Factory('VenUsuario');
$obj->find();
$i = 0;
$data='';
while($obj->fetch()){
$data[$i]['idUsuario']=$obj->idUsuario;
$data[$i]['idCargo']=$obj->idCargo;
$nombreCargo=$this->getCargoById($obj->idCargo);
$nombreCargo=utf8_encode($nombreCargo['nombre']);
$data[$i]['cargo']= $nombreCargo;
$data[$i]['nombre']=utf8_encode($obj->nombre);
$data[$i]['apellido']=utf8_encode($obj->apellido);
$data[$i]['email']=$obj->email;
$data[$i]['usuario']=utf8_encode($obj->usuario);
$data[$i]['contrasena']=utf8_encode($obj->contrasena);
$data[$i]['puntos']=$obj->puntos;
$data[$i]['estado']=$obj->estado;
$data[$i]['fechaMod']=$obj->fechaMod;
$data[$i]['fecha']=$obj->fecha;
$i++;
}
$obj->free();
//printVar($data,'getAllUsuarios');
return $data;
}
//llamada desde el goUsuarios.php
function getUsuariosLimit(){
DB_DataObject::debugLevel(0);
$obj = DB_DataObject::Factory('VenUsuario');
//$obj->limit($this->limite);
$obj->estado = 'A';
$obj->find();
$i = 0;
$data='';
while($obj->fetch()){
$data[$i]['idUsuario']=$obj->idUsuario;
$data[$i]['idCargo']=$obj->idCargo;
$nombreCargo=$this->getCargoById($obj->idCargo);
$nombreCargo=utf8_encode($nombreCargo['nombre']);
$data[$i]['cargo']= $nombreCargo;
$data[$i]['nombre']=utf8_encode($obj->nombre);
$data[$i]['apellido']=utf8_encode($obj->apellido);
$data[$i]['email']=$obj->email;
$data[$i]['usuario']=utf8_encode($obj->usuario);
$data[$i]['contrasena']=utf8_encode($obj->contrasena);
$data[$i]['puntos']=$obj->puntos;
$data[$i]['estado']=$obj->estado;
$data[$i]['fechaMod']=$obj->fechaMod;
$data[$i]['fecha']=$obj->fecha;
$i++;
}
$obj->free();
//printVar($data,'getUsuariosLimit');
return $data;
}
//llamado desde ajax para el paginador
function getUsuariosLimitRange($ini){
DB_DataObject::debugLevel(0);
$obj = DB_DataObject::Factory('VenUsuario');
$obj->limit($ini,$this->limite);
$obj->find();
$i = 0;
$data='';
while($obj->fetch()){
$data[$i]['idUsuario']=$obj->idUsuario;
$data[$i]['idCargo']=$obj->idCargo;
$nombreCargo=$this->getCargoById($obj->idCargo);
$nombreCargo=utf8_encode($nombreCargo['nombre']);
$data[$i]['cargo']= $nombreCargo;
$data[$i]['nombre']=utf8_encode($obj->nombre);
$data[$i]['apellido']=utf8_encode($obj->apellido);
$data[$i]['email']=$obj->email;
$data[$i]['usuario']=utf8_encode($obj->usuario);
$data[$i]['contrasena']=utf8_encode($obj->contrasena);
$data[$i]['puntos']=$obj->puntos;
$data[$i]['estado']=$obj->estado;
$data[$i]['fechaMod']=$obj->fechaMod;
$data[$i]['fecha']=$obj->fecha;
$i++;
}
$obj->free();
//printVar($data,'getUsuariosLimitRange');
return $data;
}
function serchTermUser($termino){
$control = (is_numeric($termino) )? 'numb': 'stri';
DB_DataObject::debugLevel(0);
$obj = DB_DataObject::Factory('VenUsuario');
$data='';
switch ($control) {
case 'numb':
$obj->whereAdd('puntos LIKE "'.$obj->escape($termino).'%"');
//$obj->whereAdd('age > 30', 'OR');
$obj->find();
$i=0;
while($obj->fetch()){
$data[$i]['idUsuario']=$obj->idUsuario;
$data[$i]['idCargo']=$obj->idCargo;
$nombreCargo=$this->getCargoById($obj->idCargo);
$nombreCargo=utf8_encode($nombreCargo['nombre']);
$data[$i]['cargo']= $nombreCargo;
$data[$i]['nombre']=utf8_encode($obj->nombre);
$data[$i]['apellido']=utf8_encode($obj->apellido);
$data[$i]['email']=$obj->email;
$data[$i]['usuario']=utf8_encode($obj->usuario);
$data[$i]['puntos']=$obj->puntos;
$data[$i]['estado']=$obj->estado;
$data[$i]['fechaMod']=$obj->fechaMod;
$data[$i]['fecha']=$obj->fecha;
$i++;
}
//printVar($data);
return $data;
break;
case 'stri':
$obj->whereAdd('nombre LIKE "'.$obj->escape($termino).'%"');
$obj->whereAdd('apellido LIKE "'.$obj->escape($termino).'%"', 'OR');
$obj->find();
$i=0;
while($obj->fetch()){
$data[$i]['idUsuario']=$obj->idUsuario;
$data[$i]['idCargo']=$obj->idCargo;
$nombreCargo=$this->getCargoById($obj->idCargo);
$nombreCargo=utf8_encode($nombreCargo['nombre']);
$data[$i]['cargo']= $nombreCargo;
$data[$i]['nombre']=utf8_encode($obj->nombre);
$data[$i]['apellido']=utf8_encode($obj->apellido);
$data[$i]['email']=$obj->email;
$data[$i]['usuario']=utf8_encode($obj->usuario);
$data[$i]['puntos']=$obj->puntos;
$data[$i]['estado']=$obj->estado;
$data[$i]['fechaMod']=$obj->fechaMod;
$data[$i]['fecha']=$obj->fecha;
$i++;
}
//printVar($data);
$obj->free();
return $data;
break;
}
$obj->limit($ini,$this->limite);
$obj->find();
$i = 0;
$data='';
while($obj->fetch()){
}
}
/*medotos para los cargos*/
//obtiene un cargo por su id
function getCargoById($idCargo){
DB_DataObject::debugLevel(0);
$obj = DB_DataObject::Factory('VenCargo');
$data=false;
$obj->idCargo=$idCargo;
$obj->find();
if($obj->fetch()){
$data['idCargo']=$obj->idCargo;
$data['nombre']=utf8_encode($obj->nombre);
$data['estado']=$obj->estado;
$data['fechaMod']=$obj->fechaMod;
$data['fecha']=$obj->fecha;
}
$obj->free();
//printVar($data,'getCargoById');
return $data;
}
//obtiene todos los cargos
function getAllCargos(){
DB_DataObject::debugLevel(0);
$obj = DB_DataObject::Factory('VenCargo');
$data=false;
$obj->find();
$i=0;
while($obj->fetch()){
$data[$i]['idCargo']=$obj->idCargo;
$data[$i]['nombre']=utf8_encode($obj->nombre);
$data[$i]['estado']=$obj->estado;
$data[$i]['fechaMod']=$obj->fechaMod;
$data[$i]['fecha']=$obj->fecha;
$i++;
}
$obj->free();
//printVar($data,'getAllCargos');
return $data;
}
}
?> | true |
1b29d11b635876cd9f09c8e964be9f50e431d723 | PHP | kevbry/pa-habitat | /app/tests/R4-Tests/R4S18-Tests/VolunteerInterestAddTest.php | UTF-8 | 2,857 | 2.671875 | 3 | [] | no_license | <?php
class VolunteerInterestAddTest extends TestCase
{
protected $mockedVolunteerInterestRepo;
protected $mockedVolunteerInterestController;
protected $volunteerInteretsInput;
protected $invalidDataException;
public function setUp()
{
parent::setUp();
//TODO - Populate array with a dummy entry for the projectitem table
$this->volunteerInteretsInput = [];
// Set up the Volunteer Interest Item Mocked Repository
$this->mockedVolunteerInterestRepo = Mockery::mock('App\Repositories\EloquentVolunteerInterestRepository');
$this->app->instance('App\Repositories\EloquentVolunteerInterestRepository', $this->mockedVolunteerInterestRepo);
$this->mockedVolunteerInterestController = Mockery::mock('App\Controllers\VolunteerInterestController');
$this->app->instance('App\Controllers\VolunteerInterestController', $this->mockedVolunteerInterestController);
}
/**
* Test that the controller can sucessfully add items to the database
*/
public function testStoreSingleEntrySuccess()
{
$this->volunteerInteretsInput = [
'id'=>'5',
'volunteer_id' => 2,
'interest' => 5,
'comments'=>'Interesting!'
];
$this->mockedVolunteerInterestRepo->shouldReceive('saveVolunteerInterest')->once()->with(Mockery::type('VolunteerInterest'));
// Act
$response = $this->route("POST", "storeInterests", $this->volunteerInteretsInput);
// Assert
$this->assertRedirectedToAction('ContactController@show',2);
}
//TODO: Finish this test so it properly tests for failing to store a single entry
public function OFF_testStoreSingleEntryFailure()
{
$this->volunteerInteretsInput = [];
// // Assemble
// $this->mockedProjectItemController
// ->shouldReceive('store')
// ->once()
// ->with($this->projectItemInput)
// ->andThrow(new Exception());
// This test does not appear to be finished.
$this->markTestIncomplete('This test has not been properly implemented yet');
}
public function testCreate()
{
$this->mockedVolunteerInterestRepo
->shouldReceive('getVolunteerInterests')->once()->with(2)
->passthru();
//Call the method
$response = $this->call('GET', 'volunteer/2/interest/create');
//Make assertions
$this->assertContains('Interests for', $response->getContent());
$this->assertTrue($this->client->getResponse()->isOk());
}
/*
* Test clean up
*/
public function tearDown()
{
parent::tearDown();
Mockery::close();
}
}
| true |
f31ee70f8099fe39ad66e4727c57327c0038a2ad | PHP | katsiaryina/gringotts | /config/Database.php | UTF-8 | 574 | 3.21875 | 3 | [
"MIT"
] | permissive | <?php
class Database {
private $host = 'localhost';
private $username = 'fakeuser';
private $password = 'fakepassword';
private $dbname = 'fakedb';
private $conn;
public function connect() {
$this->conn = new mysqli(
$this->host,
$this->username,
$this->password,
$this->dbname
);
if ($this->conn->connect_error) {
die("Connection failed: " . $this->conn->connect_error);
}
return $this->conn;
}
public function close() {
$this->conn->close();
}
}
?> | true |
2cc44128ab3257245b2cfa05717ec83c969a9956 | PHP | ravi-dwivedi/php-operation | /php1.php | UTF-8 | 610 | 2.578125 | 3 | [] | no_license | <?php
if(isset($_COOKIE['user']))
{
echo $_COOKIE['user'];
}
else
{
echo "cookie not created";
}
/*
if(isset($_COOKIE['id']))
{
echo $_COOKIE['id'];
}
else
{
echo "cookie not created";
}
session_start();
echo "<br><br><br>";
if(isset($_SESSION['cnt']))
{
echo $_SESSION['cnt'];
}
else
{
echo "SESSION not created";
}
echo session_id('cnt');
echo "<br><br><br>";
if(isset($_SESSION['cnt1']))
{
echo $_SESSION['cnt1'];
}
else
{
echo "SESSION not created";
}
session_destroy();
unset($_SESSION['cnt']);
unset($_SESSION['cnt1']); */
?> | true |
08d1571a6b1e12e5c45f5669a83e5d19d8633f95 | PHP | Bencute/tt-books | /system/application/WebUser.php | UTF-8 | 8,663 | 3 | 3 | [] | no_license | <?php
namespace system\application;
use Exception;
use Sys;
use frontend\model\User;
/**
* Class WebUser
* Класс представляет собой сущность пользователя который взаимодействует с приложением
*
* @package frontend\model
*/
class WebUser implements WebUserInterface
{
/**
* Время хранения хранилища данных в секундах до уничтожения по умолчанию
*/
const DEFAULT_LIFETIME_STORAGE = 86400;
/**
* Ключ в хранилище для хранения быстрых сообщений
*/
const STORAGE_FLASHES_KEY = 'flash';
/**
* Ключ в хранилище для хранения языка пользователя
*/
const STORAGE_LANG_KEY = 'lang';
/**
* Время хранения авторизации в секундах по умолчанию
* Если 0 то до закрытия браузера
*/
const DEFAULT_LIFETIME_LOGIN = self::DEFAULT_LIFETIME_STORAGE;
/**
* Ключ в хранилище для хранения токена csrf
*/
const STORAGE_CSRF_KEY = 'csrf';
/**
* Ключ в _POST массиве для токена csrf
*/
const POST_CSRF_KEY = 'csrf_token';
/**
* Идентификатор в хоранилище имени параметра для идентификации пользователя
*
* lgi -> LoGin Id
*/
const LOGIN_PARAM = 'lgi';
/**
* @var StorageInterface|null
*/
protected ?StorageInterface $storage = null;
/**
* Идентификатор авторизованного пользователя.
* Не авторизованного хранится null
*
* @var string|null
*/
protected ?string $id = null;
/**
* Время хранения хранилища данных до уничтожения по умолчанию
* В секундах
*
* @var int
*/
protected int $lifetimeStorage;
/**
* Текущий csrf токен
*
* @var string|null
*/
private ?string $csrfToken = null;
/**
* Показывает валидный был передан токен или нет
* Инициализируется в конструкторе
*
* @var bool
*/
private bool $stateValidCsrf;
/**
* WebUser constructor.
*
* @param int $lifetimeStorage
* @throws Exception
*/
public function __construct(int $lifetimeStorage = self::DEFAULT_LIFETIME_STORAGE)
{
$this->lifetimeStorage = $lifetimeStorage;
$this->stateValidCsrf = $this->checkCsrf();
$this->getCsrfToken(true);
}
/**
* $id идентификатор пользователя
* $lifetime время хранения авторизации в секундах
*
* @param string $id
* @param int $lifetime
* @throws Exception
* @return bool
*/
public function login(string $id, int $lifetime = self::DEFAULT_LIFETIME_LOGIN): bool
{
$this->setId($id);
$storage = $this->getStorage();
if (!$this->getStorage()->setLifetime($lifetime) || !$storage->add(self::LOGIN_PARAM, $this->getId()))
return false;
return $this->getStorage()->sessionRegenerateId();
}
/**
* Снятие авторизации
*
* @throws Exception
* @return bool
*/
public function logout(): bool
{
if ($this->isGuest())
return true;
if (!$this->getStorage()->delete(self::LOGIN_PARAM))
return false;
return $this->getStorage()->sessionRegenerateId();
}
/**
* @throws Exception
* @return StorageInterface
*/
public function getStorage(): StorageInterface
{
if (is_null($this->storage))
$this->storage = new SessionStorage(['cookie_lifetime' => $this->lifetimeStorage]);
return $this->storage;
}
/**
* Возвращает авторизован ли пользователь
*
* @throws Exception
* @return bool
*/
public function isGuest(): bool
{
return !$this->getStorage()->isset(self::LOGIN_PARAM) || empty($this->getStorage()->get(self::LOGIN_PARAM));
}
/**
* Получает модель пользователя
*
* @throws Exception
* @return User|null
*/
public function getUser(): ?LoginInterface
{
if ($this->isGuest())
return null;
return Sys::getApp()->getUserById($this->getId());
}
/**
* @param string $id
* @return bool
*/
public function setId(string $id): bool
{
$this->id = $id;
return true;
}
/**
* @throws Exception
* @return string
*/
public function getId(): ?string
{
if (is_null($this->id))
$this->id = $this->getStorage()->get(self::LOGIN_PARAM);
return $this->id;
}
/**
* Добавляет быстрое сообщение по ключу по группе
*
* @param string $message
* @param string $key
* @param string $group
* @throws Exception
*/
public function addFlash(string $message, string $key, string $group = 'general'): void
{
$flashes = $this->getStorage()->get(self::STORAGE_FLASHES_KEY);
$flashes[$group][$key] = $message;
$this->getStorage()->add(self::STORAGE_FLASHES_KEY, $flashes);
}
/**
* Получает быстрое сообщение по ключу и группе, затем удаляет его
*
* @param $group
* @param bool $delete
* @throws Exception
* @return array
*/
public function getFlashesGroup($group, bool $delete = true): array
{
$flashes = $this->getStorage()->get(self::STORAGE_FLASHES_KEY);
$flashesGroup = $flashes[$group] ?? [];
if ($delete && isset($flashes[$group])) {
unset($flashes[$group]);
$this->getStorage()->add(self::STORAGE_FLASHES_KEY, $flashes);
}
return $flashesGroup;
}
/**
* Получает текущий csrf токен
* Если токен еще не генерировался, то генерирует новый
*
* @param bool $regenerate
* @throws Exception
* @return string
*/
public function getCsrfToken(bool $regenerate = false): string
{
$this->csrfToken = $this->getStorage()->get(self::STORAGE_CSRF_KEY);
if ($regenerate || is_null($this->csrfToken)) {
$this->csrfToken = $this->generateCsrfToken();
$this->getStorage()->add(self::STORAGE_CSRF_KEY, $this->csrfToken);
}
return $this->csrfToken;
}
/**
* @throws Exception
* @return string
*/
private function generateCsrfToken(): string
{
return hash('sha3-512', $this->getId() . microtime());
}
/**
* Сверяет переданный csrf токен с хранимым от предыдущей генерации
*
* @throws Exception
* @return bool
*/
private function checkCsrf(): bool
{
if (!isset($_POST[$this->getCsrfKey()]))
return false;
return $_POST[$this->getCsrfKey()] === $this->getCsrfToken();
}
/**
* Получает ключ csrf токена в _POST массиве
*
* @return string
*/
public function getCsrfKey(): string
{
return self::POST_CSRF_KEY;
}
/**
* Возвращает валидный ли был передан токен в запросе
*
* @return bool
*/
public function isValidCsrf(): bool
{
return $this->stateValidCsrf;
}
/**
* Записывает язык пользователя в хранилище
*
* @param string $lang
* @throws Exception
* @return bool
*/
public function setLang(string $lang): bool
{
return $this->getStorage()->add(self::STORAGE_LANG_KEY, $lang);
}
/**
* Возвращает язык пользователя, или null если еще не устанавливался
*
* @throws Exception
* @return string|null
*/
public function getLang(): ?string
{
return $this->getStorage()->get(self::STORAGE_LANG_KEY);
}
} | true |
9a668f597bd907a930db12e112b08ecc7948b346 | PHP | p1ratrulezzz/php-telegram-bot-core | /src/Entities/ProximityAlertTriggered.php | UTF-8 | 945 | 2.828125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | <?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Longman\TelegramBot\Entities;
/**
* Class ProximityAlertTriggered
*
* Represents the content of a service message, sent whenever a user in the chat triggers a proximity alert set by another user.
*
* @link https://core.telegram.org/bots/api#proximityalerttriggered
*
* @method User getTraveler() User that triggered the alert
* @method User getWatcher() User that set the alert
* @method int getDistance() The distance between the users
*/
class ProximityAlertTriggered extends Entity
{
/**
* {@inheritdoc}
*/
protected function subEntities(): array
{
return [
'traveler' => User::class,
'watcher' => User::class,
];
}
}
| true |
ac6e0ebb8b5d25a83272452af7dd6446e5a77d7b | PHP | KamalW13/job | /updateProduct.php | UTF-8 | 2,103 | 2.6875 | 3 | [] | no_license | <?php
include 'functions.php';
$id = $_GET['id'];
$data = fetchData("SELECT * FROM product WHERE id = $id")[0];
$categories = fetchData("SELECT * FROM categories");
if (isset($_POST['submit'])) {
$gambarLama = $data['image'];
if (updateProduct($_POST, $gambarLama) >= 1) {
echo "
<script>
alert('Data berhasil diubah!');
document.location.href = 'CPanel.php';
</script>";
} else {
echo "Ada";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Update Product</title>
</head>
<body>
<form method="post" enctype="multipart/form-data">
<!-- mengirim id untuk di Set Database nya (TYPE HIDDEN) -->
<input type="text" name="id" value="<?= $id ?>" hidden="">
<!-- Munculin Gambar sesuai Nama di database -->
<img src="img/<?= $data['image'] ?>" width="150">
<!-- Kalo mau ngubah gambar -->
<input type="file" name="gambarBaru">
<br>
<input type="text" name="name" value="<?= $data['name']; ?>" placeholder="name">
<br>
<!-- Pemilihan Categorie -->
<select class="selectUpdate" name="categorie">
<?php foreach($categories as $categorie): ?>
<option><?= $categorie['categories']; ?></option>
<?php endforeach; ?>
</select>
<!-- Deskripsi -->
<input type="text" name="desc" value="<?= $data['desc']; ?>" placeholder="Description">
<!-- Price -->
<input type="number" name="price" value="<?= $data['price']; ?>">
<button type="reset">Reset</button>
<button type="submit" name="submit">Submit</button>
</form>
<script type="text/javascript">
const selects = document.querySelectorAll('select.selectUpdate option');
selects.forEach( select => {
if (select.innerHTML === "<?= $data['categories'] ?>") {
select.setAttribute('selected', '');
}
})
</script>
</body>
</html>
| true |
189c4dc2a06fa97d05c9a8ac5813daa8e5e99587 | PHP | bigmoletos/TP_SOFTEAM | /PHP/TP/tp2_php_session/listearticle.php | UTF-8 | 2,366 | 3.359375 | 3 | [] | no_license | <!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
echo'<ul>';
$listeFichiers = glob("news/politique/*.news");//tableau contenant les noms des fichiers d'un repertoire
$listeFichiers[] = "nouvel article"; //rajoute un article en derniere ligne
unset($listeFichiers[1]);//on supprime une entrée dans le tableau
var_dump($listeFichiers);
foreach ($listeFichiers as $key => $value) {
echo 'article: ' . $key;
echo'<li><a href=' . $value . '>' . $value . ' </a></li>';
// echo $key.'='.$value.'<br>';
}
echo'</ul>';
////////////////////////////
echo "deuxieme tableau <br/>";
//va chercher les noms des dossiers avec GLOB_ONLYDIR
$listeDossiers = glob("news/*", GLOB_ONLYDIR);
var_dump($listeDossiers);
//on va ensuite afficher les fichiers de chaque dossiers du repertoire news
// pour cela on utilise de foreach imbriqués
echo'<ul>'; //on prepare la liste non indexée
foreach ($listeDossiers as $key => $dossier) {
//on refait un glob sur les fichiers dans chaque dossiers
$listeFichiers2 = glob("$dossier/*");
$listeFichiers2[] = "nouvel article bis"; //rajoute un article en derniere ligne
unset($listeFichiers2[0]);//on supprime une entrée dans le tableau
//var_dump($listeFichiers2);
echo'<li>' . $dossier . ' </li>';//on affiche les dossiers
foreach ($listeFichiers2 as $key => $fichier) {
//on rajoute une sous liste avec le <u>
echo'<ul>';
echo'<li><a href=' . $fichier . '>' . $fichier . ' </a></li>';
echo'</ul>';
}
}
echo'</ul>'; //on ferme la liste non indexée
?>
<!--<p><?php echo "$listeFichiers"; ?></p>-->
</body>
</html>
| true |
fdb0abca3187be6103acbd41df5c606b376442e9 | PHP | techart/io | /src/IO/Stream/SeekInterface.php | UTF-8 | 1,214 | 3.15625 | 3 | [] | no_license | <?php
namespace Techart\IO\Stream;
/**
* Интерфейс позиционирования в потоке
*
* <p>Интерфейс должен быть реализован классами потоков, допускающих позиционирование,
* например, файловыми потоками.</p>
* <p>Интерфейс определяет набор констант, задающих тип смещения:</p>
* SEEK_SET
* абсолютное позицинировние;
* SEEK_CUR
* позиционирование относительно текущего положения;
* SEEK_END
* позиционирование относительно конца файла.
*
*/
interface SeekInterface
{
const SEEK_SET = 0;
const SEEK_CUR = 1;
const SEEK_END = 2;
/**
* Устанавливает текущую позицию в потоке
*
* @param int $offset
* @param int $whence
*
* @return number
*/
public function seek($offset, $whence);
/**
* Возвращает текущую позицию в потоке
*
* @return number
*/
public function tell();
}
| true |
b751338ad26c6d15bfd4e2c62d24da8edc096944 | PHP | khrlimam/installer | /src/extract/Extractor.php | UTF-8 | 207 | 2.546875 | 3 | [] | no_license | <?php namespace KhairulImam\Installer\Extract;
/**
* Extractor class responsible for extracts compressed file
*/
interface Extractor
{
public function extract($file);
public function getExtractProgram();
} | true |
27d707eeb06799449e226ddb06e8c7f65c391193 | PHP | beaver64/biarritz-202006-php-poec-checkpoint1 | /public/book.php | UTF-8 | 2,377 | 2.546875 | 3 | [] | no_license | <!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="css/main.css">
<link rel="stylesheet" href="css/book.css">
<title>Checkpoint PHP 1</title>
<?php
$debug = $error = "";
require '../connec.php';
require 'header.php';
require 'add.php';
?>
</head>
<body>
<main class="container">
<section class="desktop">
<img src="image/whisky.png" alt="a whisky glass" class="whisky"/>
<img src="image/empty_whisky.png" alt="an empty whisky glass" class="empty-whisky"/>
<div class="pages">
<div class="page leftpage">
<h1>Compte habileté</h1>
<form action="" method="post">
<div>
<label for="name">Name :</label>
<input type="text" id="name" name="name" required>
</div>
<div>
<label for="payment">payment :</label>
<input type="int" id="payment" name="payment" required></input>
</div>
<input type="submit">
</form>
</div>
<div class="page rightpage">
<?php
$pdo = new \PDO(DSN, USER, PASS);
//Afficher les erreurs captées par try et catch
//echo $debug; // only in dev mode for dev
if (isset($_POST['add.php'])) {
if ($error != '') {
echo "<div class=\"error\">" . $error . "</div>"; // for user
}
if (isset($_POST['payment'])) {
$payment = trim($_POST['payment']);
}
$totalCum = "SELECT SUM(payment) FROM bribe;";
$pdo->prepare($totalCum);
$Total = $totalCum->execute();
}
?>
</div>
</div>
</section>
</main>
</body>
<tfoot>
<td><?php
echo "The total of accountning is reaching $Total €";
?>
</td>
<img src="image/inkpen.png" alt="an ink pen" class="inkpen"/>
</tfoot>
</html>
| true |
412be590a3eb74e43fadb2a172a8860f42772335 | PHP | joohongpark/2017_IoT_project | /WebApp/graph_data.php | UTF-8 | 994 | 2.609375 | 3 | [] | no_license | <?php
date_default_timezone_set('Asia/Seoul');
$db = new SQLite3('dbdb.db',SQLITE3_OPEN_READWRITE);
if (!$_GET["id"]) {
die("return");
}
if (!$_GET["day"]) {
$now_time = date('ymd', time());
} else {
$now_time = $_GET["day"];
}
$id = $_GET["id"];
$pow_arr = array();
$pow_result_arr = array();
$pow_result_sum_arr = array();
$i = 0;
$stack = 0;
$sql = "SELECT time_data, energy FROM POWER_INT WHERE ".$now_time."00 <= time_data AND ".($now_time + 1)."00 >=time_data AND id = ".$id;
$result = $db->query($sql);
while ($row = $result->fetchArray()) {
$pow_arr[($row[0] - $now_time * 100)] = $row[1];
}
for($i = 0; $i <= 23; $i++) {
if(!$pow_arr[$i]) {
$pow_arr[$i] = 0;
}
$stack += $pow_arr[$i];
array_push($pow_result_arr, array(str_pad($i, 2, "0", STR_PAD_LEFT).":00", $pow_arr[$i]));
array_push($pow_result_sum_arr, array(str_pad($i, 2, "0", STR_PAD_LEFT).":00", $stack));
}
echo json_encode(array("pow"=>$pow_result_arr, "sum"=>$pow_result_sum_arr));
$query = $db->close();
?> | true |
71c334d7b7c8dae2bcc5b7497d4d961e2304f45a | PHP | VJ-KAZUMiX/chivalry-server-browser | /Browser.php | UTF-8 | 9,997 | 2.546875 | 3 | [] | no_license | <?php
/**
* Created by IntelliJ IDEA.
* User: KAZUMiX
* Date: 13/04/21
* Time: 17:54
* To change this template use File | Settings | File Templates.
*/
require_once 'config.php';
require_once 'GameServerManager.php';
require_once 'MySmarty.php';
class Browser {
/**
* @var GameServerManager
*/
private $gameServerManager;
private $mySmarty;
public $pageTitle = "Chivalry Server Browser";
public $appRoot;
public $countryCodeAssoc;
public $continentCodeAssoc;
public $numberOfActiveServersPerCountry;
public $errorList = array();
public $targetCountryCode = null;
public $serverList = null;
public $serverInfo = null;
public $statistics = null;
public $statisticsHeader = null;
public $multiCountries = null;
public function __construct() {
$this->gameServerManager = GameServerManager::sharedManager();
$this->mySmarty = new MySmarty();
$this->countryCodeAssoc = $this->gameServerManager->makeCountryAssoc();
$this->continentCodeAssoc = $this->gameServerManager->continentAssoc;
$this->appRoot = 'https://' . HTTP_HOST . HTTP_PATH;
if (isset($_GET['serverId'])) {
$this->viewServerInfo($_GET['serverId']);
} elseif (isset($_GET['statistics'])) {
$this->viewStatistics();
} else {
$countryCodeArray = $this->getTargetCountryCodeArray();
$this->viewServerList($countryCodeArray);
}
}
private function getTargetCountryCodeArray() {
$result = null;
// if the target is a continent, return a list of countries in the continent
if (isset($_GET['country']) && isset($this->continentCodeAssoc[$_GET['country']])) {
$continentCode = $_GET['country'];
$this->targetCountryCode = $continentCode;
$this->pageTitle = "{$this->continentCodeAssoc[$continentCode]} - {$this->pageTitle}";
$result = $this->gameServerManager->getCountryCodesInContinent($continentCode);
$this->storeNumberOfActiveServersPerCountry($continentCode);
return $result;
}
$splitCountryCodeList = false;
if (isset($_GET['country'])) {
$splitCountryCodeList = explode(',', $_GET['country']);
}
$validateCountryCodeList = array();
if ($splitCountryCodeList) {
foreach ($splitCountryCodeList as $code) {
if (isset($this->countryCodeAssoc[$code])) {
$validateCountryCodeList[] = $code;
}
}
}
switch (count($validateCountryCodeList)) {
case 1:
$this->targetCountryCode = $validateCountryCodeList[0];
$this->pageTitle = "{$this->countryCodeAssoc[$validateCountryCodeList[0]]} - {$this->pageTitle}";
$result = $validateCountryCodeList;
$this->storeNumberOfActiveServersPerCountry($validateCountryCodeList[0]);
break;
case 0:
$countryCode = geoip_country_code_by_addr(GameServerManager::getGeoIp(), $_SERVER['REMOTE_ADDR']);
if (!$countryCode) {
$countryCode = 'JP';
}
$this->targetCountryCode = $countryCode;
$result = array($countryCode);
$this->storeNumberOfActiveServersPerCountry($countryCode);
break;
default:
$this->multiCountries = $validateCountryCodeList;
$this->pageTitle = implode(', ', $validateCountryCodeList) . " - {$this->pageTitle}";
$result = $validateCountryCodeList;
break;
}
return $result;
}
private function storeNumberOfActiveServersPerCountry($necessaryCountryCode) {
$list = $this->gameServerManager->getNumberOfActiveServersPerCountry();
// continents
$gi = $this->gameServerManager->getGeoIp();
$GEOIP_COUNTRY_CODE_TO_NUMBER = $gi->GEOIP_COUNTRY_CODE_TO_NUMBER;
$GEOIP_CONTINENT_CODES = $gi->GEOIP_CONTINENT_CODES;
$continentList = array();
foreach ($list as $countryServerInfo) {
$countryCode = $countryServerInfo['country'];
$numberOfServers = $countryServerInfo['number_of_servers'];
if (!isset($GEOIP_COUNTRY_CODE_TO_NUMBER[$countryCode])) {
continue;
}
$countryNumber = $GEOIP_COUNTRY_CODE_TO_NUMBER[$countryCode];
$continentCode = 'CONTINENT_' . $GEOIP_CONTINENT_CODES[$countryNumber];
if (isset($continentList[$continentCode])) {
$continentList[$continentCode] += $numberOfServers;
} else {
$continentList[$continentCode] = +$numberOfServers;
}
}
ksort($continentList);
$continentRecordList = array();
foreach ($continentList as $countryCode => $servers) {
$continentRecordList[] = array('country' => $countryCode, 'number_of_servers' => $servers);
}
$list = array_merge($continentRecordList, $list);
$this->numberOfActiveServersPerCountry = array();
$necessaryFound = false;
foreach ($list as $record) {
$this->numberOfActiveServersPerCountry[] = array('country' => $record['country'], 'servers' => $record['number_of_servers']);
if ($record['country'] == $necessaryCountryCode) {
$necessaryFound = true;
}
}
if ($necessaryFound) {
return;
}
$this->numberOfActiveServersPerCountry[] = array('country' => $necessaryCountryCode, 'servers' => 0);
}
private function viewServerList($countryCodeArray) {
$this->serverList = $this->gameServerManager->getServerList($countryCodeArray);
$this->mySmarty->assign('data', $this);
$this->mySmarty->display('list.html');
}
private function viewServerInfo($serverId) {
$this->serverInfo = $this->gameServerManager->getServerInfo($serverId);
if (!$this->serverInfo) {
header("HTTP/1.0 404 Not Found");
$this->pageTitle = "Error - {$this->pageTitle}";
$this->errorList[] = 'The Information about the server is not available.';
} else {
$this->pageTitle = "{$this->serverInfo['server_name']} - {$this->pageTitle}";
$this->serverInfo['country_name'] = $this->countryCodeAssoc[$this->serverInfo['country']];
$lastUpdate = $this->convertSecToHMS(time() - $this->serverInfo['game_server_update']);
$this->serverInfo['last_update'] = "{$lastUpdate} ago";
}
$this->mySmarty->assign('data', $this);
$this->mySmarty->display('list.html');
}
public function convertSecToHMS($time) {
$sec = $time % 60;
$time = floor($time / 60);
if ($time == 0) {
return $sec . 's';
}
$result = $this->makeZerofillNumber($sec, 2) . 's';
$min = $time % 60;
$hour = floor($time / 60);
if ($hour == 0) {
$result = $min . 'm ' . $result;
return $result;
}
$result = $hour . 'h ' . $this->makeZerofillNumber($min, 2) . 'm ' . $result;
return $result;
}
public function makeZerofillNumber($number, $digit) {
$result = '00000000' . $number;
$result = substr($result, -$digit);
return $result;
}
private function makeStatistics() {
$baseTime = time();
$baseHour = $baseTime - $baseTime % 3600;
if ($baseTime - $baseHour >= 60 * 2) {
$baseTime = $baseHour + 3600;
} else {
$baseTime = $baseHour;
}
$baseTotalNumOfPlayersList = $this->gameServerManager->getTotalNumberOfPlayersPerCountry($baseTime - 86399, $baseTime);
if (!count($baseTotalNumOfPlayersList)) {
return array();
}
$this->statisticsHeader = array();
$this->statisticsHeader[] = '';
$totalNumOfPlayersAssoc = array();
foreach ($baseTotalNumOfPlayersList as $record) {
$totalNumOfPlayersAssoc[$record['country']] = $record;
}
$outputTable = array();
$numOfColumns = 24;
foreach ($baseTotalNumOfPlayersList as $record) {
$columns = array();
for ($i = 0; $i < $numOfColumns; $i++) {
$columns[] = 0;
}
$country = $record['country'];
$outputTable[$country] = $columns;
}
$interval = 60 * 60;
for ($i = 0; $i < $numOfColumns; $i++) {
$this->statisticsHeader[] = $i;
$fromTime = $baseTime - $interval * ($i + 1) + 1;
$toTime = $baseTime - $interval * $i;
$numOfPlayersList = $this->gameServerManager->getNumberOfPlayersPerCountry($fromTime, $toTime);
foreach ($numOfPlayersList as $record) {
$country = $record['country'];
if ($i === 0) {
$numOfPlayers = ceil($record['avg']);
} else {
$numOfPlayers = ceil($record['max']);
}
$outputTable[$country][$i] = $numOfPlayers;
}
}
// $numOfSamples = $baseTotalNumOfPlayersList[0]['count'];
// foreach ($baseTotalNumOfPlayersList as $record) {
// $country = $record['country'];
// $sum = $record['sum'];
// $avg = $sum / $numOfSamples;
// $outputTable[$country] = $avg;
// }
//var_dump($outputTable);
return $outputTable;
}
public function viewStatistics() {
$this->pageTitle = "Statistics - {$this->pageTitle}";
$this->statistics = $this->makeStatistics();
$this->mySmarty->assign('data', $this);
$this->mySmarty->display('list.html');
}
} | true |
7c33cb541cc4aaf3a04eef507b057db9b958f25b | PHP | sobwoofer/icrm | /app/Services/Crawlers/MatroluxCrawler.php | UTF-8 | 3,973 | 2.71875 | 3 | [] | no_license | <?php
namespace App\Services\Crawlers;
use App\Events\ProductCrawled;
use Symfony\Component\DomCrawler\Crawler;
/**
* Class MatroluxCrawler
* @package App\Services\Crawlers
*/
class MatroluxCrawler extends CrawlerAbstract
{
/**
* @param string $categoryUrl
* @param bool $firstPage
* @return array
* @throws \GuzzleHttp\Exception\GuzzleException
*/
protected function getProductLinksByCategoryUrl(string $categoryUrl, bool $firstPage = true)
{
$crawler = $this->crawlUrl($categoryUrl);
$productLinks = $crawler->filter('.product-block > a')->each(function (Crawler $node, $i) {
return $node->attr('href');
});
if ($crawler->filter('.paginationControl a')->count() && $firstPage) {
$paginationLinks = $crawler->filter('.paginationControl a')->each(function (Crawler $node, $i) use ($categoryUrl) {
return is_numeric($node->text()) ? $categoryUrl . $node->attr('href') : false;
});
foreach ($paginationLinks as $paginationLink) {
if ($paginationLink) {
$nextProductLinks = $this->getProductLinksByCategoryUrl($paginationLink, false);
$productLinks = array_merge($nextProductLinks, $productLinks);
}
}
}
return $productLinks;
}
/**
* @param string $url
* @param int $categoryId
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function crawlProductByUrl(string $url, int $categoryId): void
{
$crawler = $this->crawlUrl($url);
$name = trim(str_replace('\n', '', $crawler->filter('.form-title h1')->text()));
$price = str_replace(['грн', ' ', ' '], '', $crawler->filter('#productCardPrice .price-variant strong')->text());
$description = $crawler->filter('#tabs-1')->html();
$imageUrl = urldecode($crawler->filter('.sliderkit-panels meta')->attr('content'));
$article = $crawler->filter('.form-title meta')->first()->attr('content');
$images = $crawler->filter('.sliderkit-panels .sliderkit-panel')->each(function (Crawler $node, $i) {
return urldecode($node->filter('a')->attr('href'));
});
//options manipulations
$priceOptions = $crawler
->filter('#configurableParams select#size option, #configurableParams select.select-param option')
->each(function (Crawler $node) {
$name = trim($node->text());
$price = $node->attr('data-price');
return ['name' => $name, 'price' => $price];
});
$optionPricesNull = 0;
foreach ($priceOptions as $priceOption) {
if ($priceOption['price'] === null) {
$optionPricesNull++;
}
}
$optionsWithoutPrice = $optionPricesNull === count($priceOptions);
$priceVariantsExists = count($priceOptions) === $crawler->filter('#productCardPrice .price .price-variant')->count();
if ($optionsWithoutPrice && $priceVariantsExists) {
$priceOptions = $crawler->filter('#productCardPrice .price .price-variant')->each(function (Crawler $node, $i) use ($priceOptions) {
$price = trim(str_replace(['грн', ' '],'', $node->text()));
return ['name' => $priceOptions[$i]['name'], 'price' => $price];
});
} elseif ($optionsWithoutPrice && !$priceVariantsExists) {
\Log::error('all options without prices url ' . $url);
$priceOptions = [];
}
//options manipulations
event(new ProductCrawled($name, $description, $url, $imageUrl, $article, $price, $images, $priceOptions, $categoryId));
}
private function prepareUrl(string $rawUrl): string
{
$parsedUrl = parse_url($rawUrl);
return $parsedUrl['scheme'] . '://' . $parsedUrl['host'] . $parsedUrl['path'];
}
}
| true |
2462d990110b9b15c3acb581029eff93546b50c1 | PHP | yannickfogang/ntauhLabs | /src/User/Domain/UserCase/Auth/Register/RegisterResponse.php | UTF-8 | 558 | 2.609375 | 3 | [] | no_license | <?php
declare(strict_types=1);
namespace NtauhLabs\User\Domain\UserCase\Auth\Register;
use NtauhLabs\SharedService\Response;
use NtauhLabs\User\Domain\Entity\User;
final class RegisterResponse extends Response
{
private ?User $user;
/**
* RegisterResponse constructor.
*/
public function __construct()
{
parent::__construct();
$this->user = null;
}
public function setUser(User $user)
{
$this->user = $user;
}
public function User(): ?User {
return $this->user;
}
}
| true |
b50ef8ca9d8479ce95729bf98f046c829f6cf97d | PHP | maneymarkus/SV-Tora | /sv-tora/app/Http/Controllers/DocumentController.php | UTF-8 | 3,459 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers;
use App\Helper\GeneralHelper;
use App\Helper\NotificationTypes;
use App\Mail\GenericMail;
use App\Models\Document;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use SebastianBergmann\LinesOfCode\LinesOfCode;
class DocumentController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$documents = Document::all();
return view("documents", ["documents" => $documents]);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
if ($request->hasFile("documents")) {
foreach ($request->file("documents") as $file) {
$fileName = $file->getClientOriginalName();
$fileExt = $file->getClientOriginalExtension();
$copyCounter = 2;
if (Document::where("name", "=", $fileName)->first() !== null) {
$fileName = substr($fileName, 0, strlen($fileName) - 1 - strlen($fileExt));
$fileName .= " " . $copyCounter++ . ".";
$fileName .= $fileExt;
while (Document::where("name", "=", $fileName)->first() !== null) {
$fileName = substr($fileName, 0, strlen($fileName) - 1 - strlen($fileExt) - 2);
$fileName .= " " . $copyCounter++ . ".";
$fileName .= $fileExt;
}
}
$path = $file->store("/public/documents");
$newDocument = Document::create([
"name" => $fileName,
"path" => $path,
"ext" => $fileExt,
]);
}
}
return $this->index();
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\Document $document
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Document $document)
{
if ($document === null) {
return GeneralHelper::sendNotification(NotificationTypes::ERROR, "Dieses Dokument existiert nicht.");
}
$document->name = $request->input("name");
$document->save();
return GeneralHelper::sendNotification(NotificationTypes::SUCCESS, "Das Dokument \"" . $document->name . "\" wurde erfolgreich umbenannt!");
}
public function download(Document $document) {
return Storage::download($document->path, $document->name);
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Document $document
* @return \Illuminate\Http\Response
*/
public function destroy(Document $document)
{
if ($document === null) {
return GeneralHelper::sendNotification(NotificationTypes::ERROR, "Dieses Dokument existiert nicht.");
}
$documentName = $document->name;
Storage::delete($document->path);
$document->delete();
return GeneralHelper::sendNotification(NotificationTypes::SUCCESS, "Das Dokument \"" . $documentName . "\" wurde erfolgreich gelöscht.");
}
}
| true |
a11996e3e094b772c108ec4475404b7a03f9b93c | PHP | zmudzinski/rabbitmq_rpc | /src/Consumer.php | UTF-8 | 3,517 | 2.828125 | 3 | [
"MIT"
] | permissive | <?php
namespace Tzm\Rpc;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
abstract class Consumer
{
/**
* @var string
*/
private $queueName;
private $result;
/**
* Consumer constructor.
* @param string $queueName
* @param $handleClass
* @throws \Exception
*/
public function __construct(string $queueName = 'default')
{
$this->queueName = $queueName;
}
/**
* Set the queue name
*
* @param string $queueName
* @return $this
*/
public function setQueueName(string $queueName)
{
$this->queueName = $queueName;
return $this;
}
/**
* Get the message from Queue
*
* @param string $message
* @return mixed
*/
abstract protected function handleMessage($message);
/**
* Handle the error from handle message method
*
* @param \Exception $e
* @return mixed
*/
abstract protected function handleError(\Exception $e);
/**
* Return the result of operation
*
* @return mixed
*/
protected function getResult()
{
return $this->result ?? true;
}
/**
* Set a response for the Producer
*
* @param string $result
* @return mixed
*/
protected function setResult(string $result)
{
$this->result = $result;
}
/**
* Message displayed when request received
*
* @param $req
* @param string|null $additional
* @return string
* @throws \Exception
*/
protected function consoleInfo($req, string $additional = null)
{
$date = new \DateTime();
echo sprintf(" [%s] %s %s\n", $date->format('d.m H:i:s'), $additional, $this->consoleMessage($req));
}
/**
* Custom message for console info
*
* @param $req
* @return string
*/
protected function consoleMessage($req)
{
return "New request";
}
/**
* Run worker
*
* @throws \ErrorException
*/
public function run()
{
$connection = new AMQPStreamConnection(
getenv('RABBTIMQ_HOST'),
getenv('RABBTIMQ_PORT'),
getenv('RABBTIMQ_USERNAME'),
getenv('RABBTIMQ_PASSWORD')
);
$channel = $connection->channel();
$channel->queue_declare($this->queueName, false, true, false, false);
echo "[x] Awaiting RPC requests (Queue: {$this->queueName})\n";
$callback = function ($req) {
echo $this->consoleInfo($req, '[-NEW-]');
try {
$this->handleMessage($req->body);
echo $this->consoleInfo($req, '[-DONE-]');
} catch (\Exception $e) {
echo $this->consoleInfo($req, '[-ERR-]: ' . $e->getMessage());
$this->handleError($e);
}
$msg = new AMQPMessage($this->getResult(), array('correlation_id' => $req->get('correlation_id')));
$req->delivery_info['channel']->basic_publish($msg, '', $req->get('reply_to'));
$req->delivery_info['channel']->basic_ack($req->delivery_info['delivery_tag']);
};
$channel->basic_qos(null, 1, null);
$channel->basic_consume($this->queueName, '', false, false, false, false, $callback);
while ($channel->is_consuming()) {
$channel->wait();
}
$channel->close();
$connection->close();
}
}
| true |
65e274ca1637b993ffb71df77d14ce0b7ee96c1e | PHP | c-ifeorah/ftrader | /user-profile-update.php | UTF-8 | 3,625 | 2.796875 | 3 | [
"MIT"
] | permissive | <!--
Description: Script for updating user's profile
Author: Michael Ifeorah
-->
<?php
include_once('signon/session.php');
include_once("signon/pdo-connect.php");
$i_uID = $_SESSION["user_id"]; // This is the id of the user
// Retrieving the variables sent by submitting the user form
$firstname = strtolower($_POST['first_name']); // Variable for the user's first name
$lastname = strtolower($_POST['last_name']); // Variable for the user's last name
$email = strtolower($_POST['email']); // Variable for the user's email
$phone = strtolower($_POST['phone']); // Variable for the user's phone
$password = strtolower($_POST['password']); // Variable for the user's password
$confirm_password = strtolower($_POST['confirm_password']); // Variable for the user's password confirmation field
// Set conditions to update the table. If there is no password entered, update other fields except the password
if ($password == "") {
// Code to store the inputed data into th database table
try {
// We Will prepare SQL Query
$str_query = " UPDATE tbl_user
SET firstname=:firstname, lastname=:lastname, email=:email, phone=:phone
WHERE user_id = :id;";
$str_stmt = $r_Db->prepare($str_query);
// bind paramenters, Named paramenters alaways start with colon(:)
$str_stmt->bindParam(':id', $i_uID);
$str_stmt->bindParam(':firstname', $firstname);
$str_stmt->bindParam(':lastname', $lastname);
$str_stmt->bindParam(':email', $email);
$str_stmt->bindParam(':phone', $phone);
// For Executing prepared statement we will use below function
$str_stmt->execute();
$status = "success"; // This variable will be sent back to the user profile page to enable the success display
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
$status = "fail"; // This variable will be sent back to the user profile page to enable the failure display
}
} else {
// Code to store the inputed data into th database table
try {
// We Will prepare SQL Query
$str_query = " UPDATE tbl_user
SET firstname=:firstname, lastname=:lastname, email=:email, phone=:phone, password=:password
WHERE user_id = :id;";
$str_stmt = $r_Db->prepare($str_query);
// bind paramenters, Named paramenters alaways start with colon(:)
$str_stmt->bindParam(':id', $i_uID);
$str_stmt->bindParam(':firstname', $firstname);
$str_stmt->bindParam(':lastname', $lastname);
$str_stmt->bindParam(':email', $email);
$str_stmt->bindParam(':phone', $phone);
$str_stmt->bindParam(':password', $password); // Password is saved here
// For Executing prepared statement we will use below function
$str_stmt->execute();
$status = "success"; // This variable will be sent tback to the user profile page to enable the success display
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
$status = "fail"; // This variable will be sent back to the user profile page to enable the failure display
}
}
// Closing MySQL database connection
$r_Db = null;
// Redirect to the user profile page
header("location:user-profile.php?status=$status");
?> | true |
11f84edc702816b02dd7f5ef818f7ee68fbf4193 | PHP | mikljohansson/syndicate | /core/model/workflow/activity/save.class.inc | UTF-8 | 417 | 2.5625 | 3 | [
"GPL-1.0-or-later",
"MIT"
] | permissive | <?php
require_once 'core/model/workflow/WorkflowActivity.class.inc';
/**
* Calls the save method on the subject
*/
class synd_workflow_save extends AbstractWorkflowActivity {
protected $_option = null;
function __toString() {
return SyndLib::translate('Save to database');
}
function process(Workflow $workflow, $subjects, Response $response) {
foreach ($subjects as $subject)
$subject->save();
}
}
| true |
18d49efdc0bb14ba74427eeac085ddc3b01d8cbe | PHP | layla/cody | /src/Layla/Cody/Compilers/Php/Laravel/Migration/Change.php | UTF-8 | 1,720 | 2.8125 | 3 | [] | no_license | <?php namespace Layla\Cody\Compilers\Php\Laravel\Migration;
use Exception;
class Change {
protected $method;
protected $arguments = array();
public function __construct($action, $name, $configuration)
{
$this->name = $name;
$this->configuration = $configuration;
$this->$action();
}
public function createColumn()
{
if( ! isset($this->name))
{
throw new Exception("Syntax error: migration column configuration does not contain 'name' attribute. Given configuration is: ".json_encode($this->configuration, JSON_PRETTY_PRINT));
}
$this->method = $this->configuration['type'];
if(isset($this->name))
{
$this->arguments[] = "'".$this->name."'";
}
if(isset($this->configuration['size']))
{
$this->arguments[] = $this->configuration['size'];
}
if(isset($this->configuration['precision']))
{
$this->arguments[] = $this->configuration['precision'];
}
$this->default = isset($this->configuration['default']) ? $this->configuration['default'] : null;
}
public function renameColumn()
{
$this->method = 'renameColumn';
$this->arguments[] = "'".$this->configuration['old']."'";
$this->arguments[] = "'".$this->configuration['new']."'";
}
public function dropColumn()
{
if( ! isset($this->name))
{
throw new Exception("Syntax error: migration column configuration does not contain 'name' attribute. Configuration is: ".json_encode($this->configuration, JSON_PRETTY_PRINT));
}
$this->method = 'dropColumn';
$this->arguments[] = "'".$this->name."'";
}
public function compile()
{
return '$table->'.$this->method.'('.implode(', ', $this->arguments).')'.
(empty($this->default) ? '' : "->default('".$this->default."')").";\n";
}
}
| true |
67e04699762a7aba72c53ff737283343b0f819e5 | PHP | larseijman/fmp-api-sdk | /src/InstitutionalFunds/CusipMapper.php | UTF-8 | 1,120 | 2.828125 | 3 | [
"MIT"
] | permissive | <?php
namespace Leijman\FmpApiSdk\InstitutionalFunds;
use Leijman\FmpApiSdk\Contracts\Fmp;
use Leijman\FmpApiSdk\Exceptions\InvalidData;
use Leijman\FmpApiSdk\Requests\BaseRequest;
class CusipMapper extends BaseRequest
{
const ENDPOINT = 'cusip/{cusip}';
/**
* @var string
*/
private $cusip;
/**
* Create constructor.
*
* @param Fmp $api
*/
public function __construct(Fmp $api)
{
parent::__construct($api);
}
/**
*
* @return string
*/
protected function getFullEndpoint(): string
{
return str_replace('{cusip}', $this->cusip, self::ENDPOINT);
}
/**
* @param string $cusip
*
* @return CusipMapper
*/
public function setCusip(string $cusip): self
{
$this->cusip = $cusip;
return $this;
}
/**
* @return bool|void
* @throws InvalidData
*/
protected function validateParams(): void
{
if (empty($this->cusip)) {
throw InvalidData::invalidDataProvided('Please provide a cusip to the query!');
}
}
}
| true |
8d6641ace8978831b05f822d9d2787ce8a6da38b | PHP | JasperLichte/CMS-for-personal-websites | /server/projects/ProjectsHelper.php | UTF-8 | 5,438 | 2.890625 | 3 | [
"MIT"
] | permissive | <?php
namespace projects;
use base\config\Config;
use database\Connection;
use database\QueryHelper;
use templates\HtmlHelper;
class ProjectsHelper
{
const GITHUB_ENDPOINT = 'https://api.lichte.info/repos/github/';
/**
* @return array
*/
private static function getGithubProjects()
{
$ch = curl_init(self::GITHUB_ENDPOINT);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
$obj = json_decode($data, true);
$obj = (array)$obj;
if (isset($obj['success']) && $obj['success'] === true && is_array($obj['repos'])) {
return $obj['repos'];
}
return [];
}
/**
* @return array
*/
public static function getProjects()
{
return [
'github' => self::getGithubProjects(),
];
}
/**
* @return string
*/
public static function buildGithubProjectsHtml()
{
$githubProjects = self::getGithubProjects();
usort($githubProjects, function($a, $b) {
if ($a['stargazers_count'] == $b['stargazers_count']) {
if ($a['watchers_count'] == $b['watchers_count']) {
return $a['forks'] < $b['forks'];
}
return $a['watchers_count'] < $b['watchers_count'];
}
return $a['stargazers_count'] < $b['stargazers_count'];
});
$html = [];
foreach ($githubProjects as $key => $repo) {
$name = (isset($repo['name']) && !empty($repo['name']) ? $repo['name'] : '');
$description = (isset($repo['description']) && !empty($repo['description']) ? $repo['description'] : '');
$repoUrl = (isset($repo['html_url']) && !empty($repo['html_url']) ? $repo['html_url'] : '');
$stars = (isset($repo['stargazers_count']) && !empty($repo['stargazers_count']) ? $repo['stargazers_count'] : 0);
$watchers = (isset($repo['watchers_count']) && !empty($repo['watchers_count']) ? $repo['watchers_count'] : 0);
$forks = (isset($repo['forks']) && !empty($repo['forks']) ? $repo['forks'] : 0);
$mainLanguage = (isset($repo['language']) && !empty($repo['language']) ? $repo['language'] : '');
$repoHtml = [];
$repoHtml[] = HtmlHelper::element(
'h3',
['class' => 'repo-name'],
$name . ($mainLanguage
? HtmlHelper::element(
'span',
['class' => 'repo-main-language'],
' (' . $mainLanguage . ')'
)
: '')
);
$repoHtml[] = HtmlHelper::element('p', ['class' => 'repo-description'], $description);
$repoHtml[] = HtmlHelper::element('div', ['class' => 'repo-stats'], implode('', [
HtmlHelper::element('span', ['title' => 'Stars'], HtmlHelper::inlineImg(Config::MEDIA_ROOT_URL() . 'assets/star.svg') . $stars),
HtmlHelper::element('span', ['title' => 'Watching'], HtmlHelper::inlineImg(Config::MEDIA_ROOT_URL() . 'assets/eye.svg') . $watchers),
HtmlHelper::element('span', ['title' => 'Forks'], HtmlHelper::inlineImg(Config::MEDIA_ROOT_URL() . 'assets/fork.svg') . $forks),
]));
$html[] = HtmlHelper::element(
'li',
[
'class' => 'repo',
'id' => 'repo-' . ($key + 1),
],
HtmlHelper::textLink(
$repoUrl,
[
'target' => 'blank',
'style' => 'display: block; text-decoration: none;'
],
implode('', $repoHtml)
)
);
}
return HtmlHelper::element('ul', ['id' => 'projects-github-repos-list'], implode('', $html));
}
/**
* @return array
*/
private static function getLiveProjects()
{
return QueryHelper::getTableFields(
Connection::getInstance(),
'live_projects',
['url', 'description'],
'project_index > -1',
'project_index ASC'
) ?: [];
}
/**
* @return string
*/
public static function buildLiveProjectsHtml()
{
$html = [];
foreach (self::getLiveProjects() as $project) {
$frameWrapper = HtmlHelper::element(
'div',
[
'data-frame-url' => $project['url'],
'class' => 'live-project-wrapper',
],
HtmlHelper::element('span', ['class' => 'loading-spinner'])
);
$html[] = HtmlHelper::element(
'div',
['class' => 'live-project'],
$frameWrapper
. HtmlHelper::element(
'div',
['class' => 'info-box'],
($project['description']
? HtmlHelper::element('p', [], $project['description'])
: '')
. HtmlHelper::textLink($project['url'], ['target' => '_blank'], 'Full Version')
)
);
}
return implode('', $html);
}
}
| true |