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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
1448a76e6624f84698460f79a75c4617e8ebd274 | PHP | chenBiyi/STOCK-TRANSACTIONS | /createdatabase.php | UTF-8 | 1,300 | 3.046875 | 3 | [] | no_license | <?php
ini_set('display_errors',1);
$servername = "localhost";
$username = "root";
$password = "3wmV4iVKvdF9";
$Databasename = "myDBbiyi";
// Create connection
$conn = new mysqli($servername, $username, $password, $Databasename);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql = "CREATE TABLE IF NOT EXISTS Stocktransaction (" .
"id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, " .
"name VARCHAR(30) NOT NULL, " .
"email VARCHAR(30) NOT NULL, " .
"num VARCHAR(30) NOT NULL, ".
"price VARCHAR(30) NOT NULL, ".
"currency VARCHAR(30) NOT NULL,".
"state VARCHAR(30) NOT NULL)";
echo "<br/>";
echo "sql for create table: " . $sql;
if ($conn->query($sql) === TRUE) {
echo "<br/>";
echo "Table created successfully";
} else {
echo "<br/>";
echo "Error creating table: " . $conn->error;
}
//insert data and get last id
$sql = "INSERT INTO Stocktransaction (name, email, num, price, currency, state) ".
"VALUES ('JessMariana', 'JessMariana@gmail.com', '3152176604', '3890', 'dollars', 'AL')";
if ($conn->query($sql) === TRUE) {
$last_id = $conn->insert_id;
echo "New record created successfully. Last inserted ID is:". $last_id;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
| true |
728e061bfee81863492ba64a0b1f6ef0551404a1 | PHP | il-yes/pimp | /src/UserBundle/Entity/Client.php | UTF-8 | 1,245 | 2.5625 | 3 | [] | no_license | <?php
namespace UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use UserBundle\Model\UserTrait;
/**
* Client
*
* @ORM\Table(name="user_client")
* @ORM\Entity(repositoryClass="UserBundle\Repository\ClientRepository")
*/
class Client extends User
{
use UserTrait;
public function __construct()
{
parent::__construct();
// your own logic
$this->setType(parent::TYPE_CLIENT);
$this->addRole("ROLE_CLIENT");
}
/**
* @ORM\OneToMany(targetEntity="EventBundle\Entity\Event", mappedBy="client", cascade={"persist"})
*/
private $events;
/**
* Add event
*
* @param \EventBundle\Entity\Event $event
*
* @return Client
*/
public function addEvent(\EventBundle\Entity\Event $event)
{
$this->events[] = $event;
return $this;
}
/**
* Remove event
*
* @param \EventBundle\Entity\Event $event
*/
public function removeEvent(\EventBundle\Entity\Event $event)
{
$this->events->removeElement($event);
}
/**
* Get events
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getEvents()
{
return $this->events;
}
}
| true |
b40aabf875b8954ac6bd3b00a51120e53457d05b | PHP | AyushWebDev/Batman-Shopping-Site | /product.php | UTF-8 | 2,456 | 2.578125 | 3 | [
"MIT"
] | permissive | <?php
session_start();
include "helper.php";
if(!isset($_SESSION['_login']))
{
flash("danger","please login");
header("location:login.php");
die();
}
?>
<?php
include "header2.php";
include "connect.php";
try{
$conn=connect();
$sql="select * from category;";
$stmt=$conn->prepare($sql);
$stmt->execute();
$category=$stmt->fetchAll();
$sql="select products.*,category.name as category_name from products join category ON products.c_id=category.id where c_id=:id";
$stmt=$conn->prepare($sql);
$stmt->bindParam(':id',$c_id);
$c_id=$_GET['category'];
$stmt->execute();
$product=$stmt->fetchAll();
}
catch(PDOException $e)
{
echo $e->getmessage();
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="stylepage.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-3">
<div class="panel panel-default">
<div class="panel-heading"><a data-toggle="collapse" href="#mycollapse">Browse</a></div>
<div class="panel-content panel-collapse collapse" id="mycollapse">
<ul>
<?php foreach($category as $c){ ?>
<li><a href="<?php echo "product.php"."?category=".$c['id'];?>"> <?php echo $c['name'];?></a></li>
<?php } ?>
</ul>
</div>
</div>
</div>
<?php foreach($product as $p){ ?>
<div class="col-md-3">
<div class="thumbnail">
<img src="<?php echo $p['image'];?>" class="img-responsive">
<div class="caption">
<h3><?php echo $p['name'];?></h3>
<p>Category: <?php echo $p['category_name'];?></p>
<div class="col-md-12 text-right">
<strong><h5>Rs <?php echo $p['price'];?></h6></strong>
</div>
<span class="text-right"><a href="<?php echo "addtocart.php"."?prod_id=".$p['id']?>" class="btn btn-success" style="margin-right: 5px">Add To Cart</a>
<a href="<?php echo "productdetail.php"."?prod_id=".$p['id']?>" class="btn btn-info" style="margin-left: 5px">View Product</a>
</span>
</div>
</div>
</div>
<?php }?>
</div>
</div>
</div>
<?php include "footer.php";?>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="bootstrap.min.js"></script>
</body>
</html> | true |
7dd1d0a351532fc91df30ed6931c3146ff92c150 | PHP | eru123/NoEngine | /src/ListType.php | UTF-8 | 5,907 | 3.109375 | 3 | [
"MIT"
] | permissive | <?php
namespace eru123\NoEngine;
use \Iterator;
class ListType implements Iterator
{
private $index = 0;
private $position = null;
private $array = [];
public function __construct($arr = [])
{
$this->rewind();
$this->array = $arr;
}
public function rewind(): void
{
if (is_array($this->array) && count($this->array) > 0) {
$this->position = array_keys($this->array)[0];
} else $this->position = null;
}
public function current()
{
return $this->array[$this->position];
}
public function key()
{
return $this->position;
}
public function next(): void
{
++$this->index;
if ($this->index < count($this->array)) {
$this->position = array_keys($this->array)[$this->index];
} else {
$this->position = null;
}
}
public function keys(): array
{
return array_keys($this->array);
}
public function values(): array
{
return array_values($this->array);
}
public function getIndex(): int
{
return $this->index;
}
public function valid(): bool
{
return isset($this->array[$this->position]);
}
public function implode($separator = ',')
{
return implode($separator, $this->array);
}
public function to_string()
{
return "[{$this->implode(', ')}]";
}
public function size(): int
{
return count($this->array);
}
public function first()
{
foreach ($this->array as $key => $item) return ['key' => $key, 'value' => $item];
}
public function last()
{
$reverse_keys = array_reverse(array_keys($this->array));
foreach ($reverse_keys as $key) return ['key' => $key, 'value' => $this->array[$key]];
}
public function map($callback)
{
$new_array = [];
foreach ($this->array as $key => $item) $new_array[$key] = $callback($key, $item);
return new self($new_array);
}
public function filter($callback)
{
$new_array = [];
foreach ($this->array as $key => $item) if ($callback($item)) $new_array[$key] = $item;
return new self($new_array);
}
public function reduce($callback, $initial = NULL)
{
$result = $initial;
foreach ($this->array as $item) $result = $callback($result, $item);
return $result;
}
public function reverse()
{
$new_array = [];
$reverse_keys = array_reverse(array_keys($this->array));
foreach ($reverse_keys as $key) $new_array[$key] = $this->array[$key];
return new self($new_array);
}
public function sort($callback)
{
$new_array = [];
$keys = array_keys($this->array);
usort($keys, $callback);
foreach ($keys as $key) $new_array[$key] = $this->array[$key];
return new self($new_array);
}
public function slice($offset, $length = NULL)
{
$new_array = [];
$keys = array_keys($this->array);
$keys = array_slice($keys, $offset, $length);
foreach ($keys as $key) $new_array[$key] = $this->array[$key];
return new self($new_array);
}
public function splice($offset, $length = NULL, $replacement = NULL)
{
$new_array = [];
$keys = array_keys($this->array);
$keys = array_splice($keys, $offset, $length, $replacement);
foreach ($keys as $key) $new_array[$key] = $this->array[$key];
return new self($new_array);
}
public function pop()
{
$keys = array_keys($this->array);
$key = array_pop($keys);
$value = $this->array[$key];
unset($this->array[$key]);
return ['key' => $key, 'value' => $value];
}
public function shift()
{
$keys = array_keys($this->array);
$key = array_shift($keys);
$value = $this->array[$key];
unset($this->array[$key]);
return ['key' => $key, 'value' => $value];
}
public function push(...$args)
{
if (count($args) == 2 && is_string($args[0])) {
$this->array[$args[0]] = $args[1];
} else {
foreach ($args as $item) $this->array[] = $item;
}
return $this;
}
public function unshift(...$args)
{
if (count($args) == 2 && is_string($args[0])) {
$this->array[$args[0]] = $args[1];
} else {
foreach ($args as $item) $this->array[] = $item;
}
return $this;
}
public function is_array()
{
return array_keys($this->array) === range(0, count($this->array) - 1);
}
public function is_object()
{
return !$this->is_array();
}
public function mask($mask = "?")
{
$masks = [];
foreach ($this as $key => $v) {
$masks[$key] = $mask;
}
return new self($masks);
}
public function toArray()
{
return $this->array;
}
public function get($key, $default = NULL)
{
return isset($this->array[$key]) ? $this->array[$key] : $default;
}
public function has($value)
{
foreach ($this->array as $v) {
if ($v == $value) return true;
}
return false;
}
public function hasStrict($value)
{
foreach ($this->array as $v) {
if ($v === $value) return true;
}
return false;
}
public function hasKey($key)
{
return isset($this->array[$key]);
}
public function delete($key)
{
unset($this->array[$key]);
return $this;
}
public function remove($value)
{
foreach ($this->array as $key => $v) {
if ($v == $value) unset($this->array[$key]);
}
return $this;
}
}
| true |
7f6a05efd9ad1fb18e5aab19601a0456f58a7818 | PHP | navdeepsingh/object-oriented-bootcamp | /Inheritance/Animal2.php | UTF-8 | 522 | 3.6875 | 4 | [] | no_license | <?php
// If I dont want you to instantiate the Parent class Animal then i will make it abstract
abstract class Animal{
abstract protected function getCategory();
}
class Tiger extends Animal{
public function getCategory()
{
return 'Wild';
}
}
class Lizard extends Animal{
public function getCategory()
{
return 'Reptile';
}
}
class Cow extends Animal{
public function getCategory()
{
return 'Pet';
}
}
//echo (new Tiger('wild'))->getCategory();
echo (new Cow)->getCategory();
//new Animal;
?> | true |
77f79a2397a0055c0e8020ec116de2b6ae4ca47f | PHP | goran-olbina/personalLibrary | /models/RoomModel.php | UTF-8 | 850 | 2.546875 | 3 | [] | no_license | <?php
namespace App\Models;
use App\Core\Field;
use App\Validators\NumberValidator;
use App\Validators\StringValidator;
use App\Validators\BitValidator;
class RoomModel extends \App\Core\Model {
protected function getFields(): array {
return [
'room_id' => new Field((new NumberValidator())->setRequired(), false),
'location' => new Field((new StringValidator()), true),
'is_deleted' => new Field((new BitValidator()), true)
];
}
public function isActive($room) {
if (!$room) {
return false;
}
if ($room->is_deleted == 1) {
return false;
}
return true;
}
} | true |
ec22ab4bd8b9c4719c4d6848438851a0a562c504 | PHP | bartbart2003/LibreAnswer | /next.php | UTF-8 | 13,784 | 2.65625 | 3 | [
"MIT"
] | permissive | <?php
session_start();
// Main
require_once 'private/main.php';
// Translations
require_once 'lang.php';
(isset($_SESSION['gameStarted']) && $_SESSION['gameStarted']) or die("Error: Game not started!<br><a href='index.php'>Return</a>");
?>
<!DOCTYPE html>
<html>
<head>
<title>LibreAnswer</title>
<link rel="shortcut icon" href="favicon.ico" >
<link rel='stylesheet' type='text/css' href='css/style.css'>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
<?php include 'stats.php'; ?>
</head>
<body>
<?php
$queManager = new questionsManager();
$contentCount = $queManager->getContentCount($_SESSION['packname']);
($_GET['contentNumber'] <= $_SESSION['contentNumber'] && $_GET['contentNumber'] > 0) or die("Error: Incorrect content number!");
($_GET['contentNumber'] <= $contentCount) or die("<script>window.location.href = 'afterlast.php'</script>");
$row = $queManager->getContent($_SESSION['packname'], $_GET['contentNumber']);
echo "<div style='text-align: center'>";
echo "<div id='checkDiv' style='border-width: 1px 1px 0px 1px; border-radius: 10px 10px 0px 0px;'>LibreAnswer</div>";
if ($row['contentType'] == 'abcd')
{
// IF: abcd question
if (isset($_GET['formAnswer']) && ($_GET['formAnswer'] == '1' || $_GET['formAnswer'] == '2' || $_GET['formAnswer'] == '3' || $_GET['formAnswer'] == '4'))
{
// IF: valid answer
if ($row['correctAnswer'] == $_GET['formAnswer'])
{
// IF: correct answer
echo "<div id='checkDiv' style='color: limegreen; font-weight: bold;'>".gettext('Correct answer!')."</div>";
if ($_GET['contentNumber'] == $_SESSION['contentNumber'])
{
// IF: current content
$_SESSION['contentNumber']++;
$_SESSION['questionNumber']++;
$_SESSION['correctUserAnswers']++;
if ($_SESSION['contentNumber'] > $contentCount)
{
echo "<div id='checkDiv' style='font-weight: bold'><a href='afterlast.php' style='color: black'>".gettext('End game')."</a></div>";
}
else
{
echo "<div id='checkDiv' style='font-weight: bold'><a href='question.php' style='color: black'>".gettext('Next')."</a></div>";
}
}
else
{
// IF: not current content
if ($_SESSION['contentNumber'] > $contentCount)
{
echo "<div id='checkDiv' style='font-weight: bold'><a href='afterlast.php' style='color: black'>".gettext('End game')."</a></div>";
}
else
{
echo "<div id='checkDiv' style='font-weight: bold'><a href='question.php' style='color: black'>".gettext('OK')."</a></div>";
}
}
}
else
{
// IF: incorrect answer
echo "<div id='checkDiv' style='color: crimson; font-weight: bold; text-align: center;'>".gettext('Incorrect answer!')."</div>";
$correctAnswer = $row['correctAnswer'];
$correctAnswerText = htmlentities($row['answer'.$correctAnswer]);
echo "<div id='checkDiv'>".gettext("Correct answer:")." <b>".chr(96 + $correctAnswer)."</b> (".$correctAnswerText.")</div>";
if ($_GET['contentNumber'] == $_SESSION['contentNumber'])
{
if ($_SESSION['hardcoreMode'])
{
// IF: hardcore mode
$_SESSION['gameStarted'] = false;
echo "<div id='checkDiv' style='text-align: center'><a href='endgame.php' style='color: black;'>".gettext('End game')."</a></div>";
}
else
{
$_SESSION['contentNumber']++;
$_SESSION['questionNumber']++;
if ($_SESSION['contentNumber'] > $contentCount)
{
echo "<div id='checkDiv' style='font-weight: bold'><a href='afterlast.php' style='color: black'>".gettext('End game')."</a></div>";
}
else
{
echo "<div id='checkDiv' style='font-weight: bold'><a href='question.php' style='color: black'>".gettext('Next')."</a></div>";
}
}
}
else
{
if ($_SESSION['contentNumber'] > $contentCount)
{
echo "<div id='checkDiv' style='font-weight: bold'><a href='afterlast.php' style='color: black'>".gettext('End game')."</a></div>";
}
else
{
echo "<div id='checkDiv' style='font-weight: bold'><a href='question.php' style='color: black'>".gettext('OK')."</a></div>";
}
}
}
}
else
{
// IF: invalid answer
echo "<div id='checkDiv' style='color: crimson; font-weight: bold; text-align: center;'>".gettext('Invalid/no answer passed!')."</div>";
$correctAnswer = $row['correctAnswer'];
$correctAnswerText = htmlentities($row['answer'.$correctAnswer]);
echo "<div id='checkDiv'>".gettext("Correct answer:")." <b>".chr(96 + $correctAnswer)."</b> (".$correctAnswerText.")</div>";
if ($_GET['contentNumber'] == $_SESSION['contentNumber'])
{
if ($_SESSION['hardcoreMode'])
{
// IF: hardcore mode
$_SESSION['gameStarted'] = false;
echo "<div id='checkDiv' style='text-align: center'><a href='endgame.php' style='color: black;'>".gettext('End game')."</a></div>";
}
else
{
$_SESSION['contentNumber']++;
$_SESSION['questionNumber']++;
if ($_SESSION['contentNumber'] > $contentCount)
{
echo "<div id='checkDiv' style='font-weight: bold'><a href='afterlast.php' style='color: black'>".gettext('End game')."</a></div>";
}
else
{
echo "<div id='checkDiv' style='font-weight: bold'><a href='question.php' style='color: black'>".gettext('Next')."</a></div>";
}
}
}
else
{
if ($_SESSION['contentNumber'] > $contentCount)
{
echo "<div id='checkDiv' style='font-weight: bold'><a href='afterlast.php' style='color: black'>".gettext('End game')."</a></div>";
}
else
{
echo "<div id='checkDiv' style='font-weight: bold'><a href='question.php' style='color: black'>".gettext('OK')."</a></div>";
}
}
}
if ($row['questionExtra'] != '')
{
echo "<div id='checkDiv' style='background-color: peachpuff'>".str_replace("|n|", "<br>", htmlentities($row['questionExtra'])).'</div>';
}
}
if ($row['contentType'] == 'tf')
{
$isValidAnswer = false;
$userAnswer = '';
// IF: tf question
if (isset($_GET['tfAnswer1']) && isset($_GET['tfAnswer2']) && isset($_GET['tfAnswer3']) && isset($_GET['tfAnswer4']))
{
$userAnswer = $_GET['tfAnswer1'].$_GET['tfAnswer2'].$_GET['tfAnswer3'].$_GET['tfAnswer4'];
}
// Check if answer is valid
if (strlen($userAnswer) == '4')
{
$isValidAnswer = true;
for ($i = 0; $i<4; $i++)
{
if ($userAnswer[$i] != 't' && $userAnswer[$i] != 'f')
{
$isValidAnswer = false;
}
}
}
if ($isValidAnswer)
{
echo "<div id='checkDiv' style='background-color: goldenrod; font-weight: bold;'>".gettext("Correct answers:")."</div>";
echo "<div id='checkDiv' style='background-color: khaki'>".$queManager->getContent($_SESSION['packname'], $_GET['contentNumber'])['question']."</div>";
$correctAnswer = $queManager->getContent($_SESSION['packname'], $_GET['contentNumber'])['correctAnswer'];
$isAllCorrect = true;
for ($i = 0; $i<4; $i++)
{
echo "<div id='checkDiv'>";
$answerText = htmlentities($queManager->getContent($_SESSION['packname'], $_GET['contentNumber'])['answer'.($i+1)]);
echo "<div style='border: 1px solid black; padding: 1px; background-color: antiquewhite; width: 50vw; display: inline-block; margin: auto; text-align: center;'>";
echo $answerText." - ";
if ($correctAnswer[$i] != $userAnswer[$i])
{
echo "<b>";
$isAllCorrect = false;
}
if ($correctAnswer[$i] == 't')
{
echo gettext("true");
}
else
{
echo gettext("false");
}
if ($correctAnswer[$i] != $userAnswer[$i])
{
echo "</b>";
}
echo "</div>";
echo "</div>";
}
if ($isAllCorrect)
{
// IF: correct answer
echo "<div id='checkDiv' style='color: limegreen; font-weight: bold;'>".gettext('All answers are correct!')."</div>";
if ($_GET['contentNumber'] == $_SESSION['contentNumber'])
{
// IF: current content
$_SESSION['contentNumber']++;
$_SESSION['questionNumber']++;
$_SESSION['correctUserAnswers']++;
if ($_SESSION['contentNumber'] > $contentCount)
{
echo "<div id='checkDiv' style='font-weight: bold'><a href='afterlast.php' style='color: black'>".gettext('End game')."</a></div>";
}
else
{
echo "<div id='checkDiv' style='font-weight: bold'><a href='question.php' style='color: black'>".gettext('Next')."</a></div>";
}
}
else
{
// IF: not current content
if ($_SESSION['contentNumber'] > $contentCount)
{
echo "<div id='checkDiv' style='font-weight: bold'><a href='afterlast.php' style='color: black'>".gettext('End game')."</a></div>";
}
else
{
echo "<div id='checkDiv' style='font-weight: bold'><a href='question.php' style='color: black'>".gettext('OK')."</a></div>";
}
}
}
else
{
// IF: incorrect answer
echo "<div id='checkDiv' style='color: crimson; font-weight: bold; text-align: center;'>".gettext('Incorrect answer(s)!')."</div>";
if ($_GET['contentNumber'] == $_SESSION['contentNumber'])
{
// IF: current content
if ($_SESSION['hardcoreMode'])
{
// IF: hardcore mode
$_SESSION['gameStarted'] = false;
echo "<div id='checkDiv' style='text-align: center'><a href='endgame.php' style='color: black;'>".gettext('End game')."</a></div>";
}
else
{
$_SESSION['contentNumber']++;
$_SESSION['questionNumber']++;
if ($_SESSION['contentNumber'] > $contentCount)
{
echo "<div id='checkDiv' style='font-weight: bold'><a href='afterlast.php' style='color: black'>".gettext('End game')."</a></div>";
}
else
{
echo "<div id='checkDiv' style='font-weight: bold'><a href='question.php' style='color: black'>".gettext('Next')."</a></div>";
}
}
}
else
{
// IF: not current content
if ($_SESSION['contentNumber'] > $contentCount)
{
echo "<div id='checkDiv' style='font-weight: bold'><a href='afterlast.php' style='color: black'>".gettext('End game')."</a></div>";
}
else
{
echo "<div id='checkDiv' style='font-weight: bold'><a href='question.php' style='color: black'>".gettext('OK')."</a></div>";
}
}
}
}
else
{
// IF: invalid answer
echo "<div id='checkDiv' style='color: crimson; font-weight: bold; text-align: center;'>".gettext('Invalid/no answer passed!')."</div>";
echo "<div id='checkDiv' style='background-color: goldenrod; font-weight: bold;'>".gettext("Correct answers:")."</div>";
echo "<div id='checkDiv' style='background-color: khaki'>".$queManager->getContent($_SESSION['packname'], $_GET['contentNumber'])['question']."</div>";
$correctAnswer = $queManager->getContent($_SESSION['packname'], $_GET['contentNumber'])['correctAnswer'];
for ($i = 0; $i<4; $i++)
{
echo "<div id='checkDiv'>";
$answerText = htmlentities($queManager->getContent($_SESSION['packname'], $_GET['contentNumber'])['answer'.($i+1)]);
echo "<div style='border: 1px solid black; padding: 1px; background-color: antiquewhite; width: 50vw; display: inline-block; margin: auto; text-align: center;'>";
echo $answerText." - ";
echo "<b>";
if ($correctAnswer[$i] == 't')
{
echo gettext("true");
}
else
{
echo gettext("false");
}
echo "</b>";
echo "</div>";
echo "</div>";
}
if ($_GET['contentNumber'] == $_SESSION['contentNumber'])
{
// IF: current content
if ($_SESSION['hardcoreMode'])
{
// IF: hardcore mode
$_SESSION['gameStarted'] = false;
echo "<div id='checkDiv' style='text-align: center'><a href='endgame.php' style='color: black;'>".gettext('End game')."</a></div>";
}
else
{
$_SESSION['contentNumber']++;
$_SESSION['questionNumber']++;
if ($_SESSION['contentNumber'] > $contentCount)
{
echo "<div id='checkDiv' style='font-weight: bold'><a href='afterlast.php' style='color: black'>".gettext('End game')."</a></div>";
}
else
{
echo "<div id='checkDiv' style='font-weight: bold'><a href='question.php' style='color: black'>".gettext('Next')."</a></div>";
}
}
}
else
{
// IF: not current content
if ($_SESSION['contentNumber'] > $contentCount)
{
echo "<div id='checkDiv' style='font-weight: bold'><a href='afterlast.php' style='color: black'>".gettext('End game')."</a></div>";
}
else
{
echo "<div id='checkDiv' style='font-weight: bold'><a href='question.php' style='color: black'>".gettext('OK')."</a></div>";
}
}
}
if ($row['questionExtra'] != '')
{
echo "<div id='checkDiv' style='background-color: peachpuff'>".str_replace("|n|", "<br>", htmlentities($row['questionExtra'])).'</div>';
}
}
if ($row['contentType'] == 'info')
{
// IF: info-card
echo "<div id='checkDiv' style='color: #855628; font-weight: bold; padding-top: 10px; font-size: 25px;'>".$row['title']."</div>";
echo "<div id='checkDiv' style='color: black; padding-bottom: 10px;'>".$row['description']."</div>";
if ($_GET['contentNumber'] == $_SESSION['contentNumber'])
{
// IF: current content
$_SESSION['contentNumber']++;
if ($_SESSION['contentNumber'] > $contentCount)
{
echo "<div id='checkDiv' style='font-weight: bold'><a href='afterlast.php' style='color: black'>".gettext('End game')."</a></div>";
}
else
{
echo "<div id='checkDiv' style='font-weight: bold'><a href='question.php' style='color: black'>".gettext('Next')."</a></div>";
}
}
else
{
// IF: not current content
if ($_SESSION['contentNumber'] > $contentCount)
{
echo "<div id='checkDiv' style='font-weight: bold'><a href='afterlast.php' style='color: black'>".gettext('End game')."</a></div>";
}
else
{
echo "<div id='checkDiv' style='font-weight: bold'><a href='question.php' style='color: black'>".gettext('OK')."</a></div>";
}
}
}
echo "<div id='checkDiv' style='border-width: 0px 1px 1px 1px; border-radius: 0px 0px 10px 10px; height: 20px;'></div>";
echo "</div>";
?>
</body>
</html>
| true |
997ec9a802e1cca5ec695a3525f2bbfc1a55b6ef | PHP | flixbeat/cubictalk | /_paging handler - dave/sample_with_search.php | UTF-8 | 2,128 | 2.515625 | 3 | [] | no_license | <?php
function x($pageNumber=null){
$pageNumber = $pageNumber==null ? 1:$pageNumber;
if( isset($this->data) ){
$this->Session->write('searchInfo',$this->data);
}
$searchInfo = $this->Session->read('searchInfo');
# SEARCH
if( isset($searchInfo) ) {
$teaName = $searchInfo['GroupLesson']['tea_name'];
$startDate = $searchInfo['GroupLesson']['start_date'];
$endDate = $searchInfo['GroupLesson']['end_date'];
$q = "SELECT *,
(SELECT count(DISTINCT user_id) FROM lessons where group_lesson_id = gl.id and lesson_status = 'R') as students_reserved,
(select img_file from teachers where id = gl.teacher_id) as teacher_img
FROM group_lessons as gl
INNER JOIN teachers ON gl.teacher_id = teachers.id";
$whereClause = " WHERE 1";
if($teaName != '') $whereClause .= " AND teachers.tea_name LIKE '$teaName' ";
if($startDate != null && $endDate != null ) $whereClause .= " AND ( SUBSTRING(lesson_time, 1, 10) BETWEEN '$startDate' AND '$endDate')";
if($startDate != null && $endDate == null ) $whereClause .= " AND SUBSTRING(lesson_time, 1, 10) LIKE '$startDate'";
$startRow = ($pageNumber * 10) - 10;
$whereClause .= " ORDER BY lesson_time DESC";
$q .= $whereClause;
$res = $this->GroupLesson->query($q . " LIMIT $startRow,10");
# get all rows divided by 10
$totalRows = $this->GroupLesson->query("SELECT count(*)/10 as page_count,
(SELECT count(DISTINCT user_id) FROM lessons where group_lesson_id = gl.id and lesson_status = 'R') as students_reserved,
(select img_file from teachers where id = gl.teacher_id) as teacher_img
FROM group_lessons as gl
INNER JOIN teachers ON gl.teacher_id = teachers.id" . $whereClause );
# initialize paging
$pages = $this->PagingHandler->createPaging($pageNumber,$totalRows);
echo $pages;
# store paging
$this->set('paging',$this->PagingHandler->writePaging($pageNumber,$pages));
# give page number to view for numbering
if($pageNumber == null) $this->set('pageNumber',1);
else $this->set('pageNumber',$pageNumber);
$this->set('groupLessons',$res);
}
}
?> | true |
e5476b65657f78a2fece41bd3fd18c18cd314728 | PHP | romandots/dc-core | /app/Repository/Exceptions/ScheduleSlotIsOccupied.php | UTF-8 | 761 | 2.640625 | 3 | [] | no_license | <?php
/**
* File: ScheduleExists.php
* Author: Roman Dots <romandots@brainex.co>
* Date: 2020-2-21
* Copyright (c) 2020
*/
declare(strict_types=1);
namespace App\Repository\Exceptions;
use App\Exceptions\BaseException;
use App\Models\Schedule;
class ScheduleSlotIsOccupied extends BaseException
{
/**
* @var Schedule[]
*/
private array $schedules;
/**
* ScheduleSlotIsOccupied constructor.
* @param Schedule[] $schedules
*/
public function __construct(array $schedules)
{
parent::__construct('schedule_slot_is_occupied', $schedules, 409);
$this->schedules = $schedules;
}
/**
* @return Schedule[]
*/
public function getSchedules(): array
{
return $this->schedules;
}
} | true |
cf9e6d42e193e9c6de85234c8ab30f1f22a71ea0 | PHP | cavalcanti22/mantosdofutebol | /application/models/Cupons_model.php | UTF-8 | 1,651 | 2.609375 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Cupons_model extends CI_Model {
public $title;
public $value;
public $code;
public $button;
public $link;
public $text1;
public $text2;
public $text3;
public $text4;
public function __construct(){
parent::__construct();
}
public function getAllCupons(){
$this->db->order_by('tempo','DESC');
return $this->db->get('cupons')->result();
}
public function insertCupom($title,$value,$code,$button,$link,$text1,$text2,$text3,$text4){
$data['title'] = $title;
$data['value'] = $value;
$data['code'] = $code;
$data['button'] = $button;
$data['link'] = $link;
$data['text1'] = $text1;
$data['text2'] = $text2;
$data['text3'] = $text3;
$data['text4'] = $text4;
return $this->db->insert('cupons',$data);
}
public function getCupom($id){
$this->db->from('cupons');
$this->db->where('md5(id)',$id);
return $this->db->get()->unbuffered_row();
}
public function updateCupom($title,$value,$code,$button,$link,$text1,$text2,$text3,$text4,$id){
$data['title'] = $title;
$data['value'] = $value;
$data['code'] = $code;
$data['button'] = $button;
$data['link'] = $link;
$data['text1'] = $text1;
$data['text2'] = $text2;
$data['text3'] = $text3;
$data['text4'] = $text4;
return $this->db->update('cupons', $data, array('md5(id)' => $id));
}
public function excluir($id){
$this->db->where('md5(id)',$id);
return $this->db->delete('cupons');
}
public function totalCupons(){
$query = $this->db->query('SELECT * FROM cupons');
return $query->num_rows();
}
}
| true |
93a267d365b89fbb4ec7f0662e45c66bfa814a49 | PHP | anhnguyen1996/php-basic | /mvc/models/ProductModel.php | UTF-8 | 441 | 2.6875 | 3 | [] | no_license | <?php
require_once('./mvc/core/Database.php');
use Core\Database;
class ProductModel extends Database
{
public function __construct()
{
$this->table = 'products';
parent::__construct();
}
public function getProducts()
{
$sql = "SELECT * FROM $this->table";
return $this->executeQuery($sql);
}
public function getTable()
{
return $this->table;
}
} | true |
39a31cd4ba759dc3e571d5d9159f0f28a6c64b46 | PHP | ChenTsu/GB_Practice | /PHP/PHP1/DZ4_Vaidakovich/sumForm2.php | UTF-8 | 2,729 | 2.921875 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: chentsu
* Date: 21.05.2016
* Time: 16:03
*/
error_reporting(E_ALL);
$firstTime = true;
$result ='';
require 'sum.php';
$requestMethod = "_{$_SERVER['REQUEST_METHOD']}";
if (isset(${$requestMethod}['x']) && isset(${$requestMethod}['y']) && isset(${$requestMethod}['operation']))
{
$firstTime = false;
if ( ( ${$requestMethod}['x'] !== '') && (${$requestMethod}['y'] !== '') )
{
$result = mathOperation( ${$requestMethod}['x'], ${$requestMethod}['y'], ${$requestMethod}["operation"] );
// var_dump($_POST['operation']);
}
else
$result = "Введите значения и выберите операцию.";
if ( $_SERVER['REQUEST_METHOD'] == 'POST' )
header('location:'.${$requestMethod}['PHP_SELF'] . '?x='.${$requestMethod}['x'] . '&y=' . ${$requestMethod}['y'] . '&operation=' . ${$requestMethod}['operation']); // то что нужно, но всё равно не понятно,
// header('location:'.$_SERVER['HTTP_REFERER'] . '?x='.$_POST['x'] . '&y=' . $_POST['y'] . '&operation=' . $_POST['operation']); // REFERER нам не подходит т.к. происходит наращивание параметров
}
$requestMethod = "_{$_SERVER['REQUEST_METHOD']}";
//var_dump($method);
?>
<html>
<head>
<title>Калькулятор с памятью</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Калькулятор с кнопками выбора действия, и сохранением введённых данных.</h1>
<form method="post">
<input type="text" name="x" value="<?php !$firstTime ? print ( ${$requestMethod}['x'] ) : false; ?>" />
<?php
if ( isset( $$requestMethod ) )
{
// var_dump(${$method}['operation']);
// var_dump($firstTime);
(!$firstTime && (${$requestMethod}['operation'] == 'ADD') ) ? print '+' : false;
(!$firstTime && (${$requestMethod}['operation'] == 'SUB') ) ? print '-' : false;
(!$firstTime && (${$requestMethod}['operation'] == 'MUL') ) ? print '*' : false;
(!$firstTime && (${$requestMethod}['operation'] == 'DIV') ) ? print '/' : false;
}
?>
<input type="text" name="y" value="<?php !$firstTime ? print ${$requestMethod}['y'] : false; ?>"/>
<?php echo " = " . $result . "<br>\n";
?>
<button type="submit" name="operation" value="ADD">+</button>
<button type="submit" name="operation" value="SUB">-</button>
<button type="submit" name="operation" value="MUL">*</button>
<button type="submit" name="operation" value="DIV">/</button>
</form>
</body>
</html>
| true |
0680ff2cb8181d07999b43953dcf4d589275b267 | PHP | ApprecieOpenSource/Apprecie | /app/library/Adapters/BaseGetSetAdapter.php | UTF-8 | 1,955 | 3.09375 | 3 | [
"MIT"
] | permissive | <?php
/**
* Created by PhpStorm.
* User: Gavin
* Date: 01/07/15
* Time: 11:24
*/
namespace Apprecie\Library\Adapters;
abstract class BaseGetSetAdapter
{
protected $_object = null;
protected $_excludes = array();
function __construct($object, $excludes = null)
{
if(! is_object($object)) {
throw new \LogicException('GetSetAdapter needs an object');
}
$this->setObject($object);
if($excludes != null) {
$this->setExcludes($excludes);
}
}
public function setExcludes(array $excludes)
{
$this->_excludes = $excludes;
}
public function getObject()
{
return $this->_object;
}
public function setObject($object)
{
$this->_object = $object;
}
function __call($func, $args)
{
return $this->process($func, $args);
}
/**
* Processes get and set methods out to getResult and setResult which are expected to return the ultimate
* return value.
*
* Override me to implement more specific method intercepts.
*
* @param $func
* @param $args
* @return mixed
*/
protected function process($func, $args)
{
$result = call_user_func_array(array($this->_object, $func), $args);
if(in_array($func, $this->_excludes)) {
return $result;
}
if($this->startsWith($func, 'get')) {
$result = $this->getResult($func, $args, $result);
} elseif($this->startsWith($func, 'set')) {
$result = $this->setResult($func, 'set', $result);
}
return $result;
}
private function startsWith($haystack, $needle)
{
return $needle === "" || strripos($haystack, $needle, -strlen($haystack)) !== false;
}
abstract protected function getResult($function, $args, $value);
abstract protected function setResult($function, $args, $value);
} | true |
3cf522f24721d702f1b5c28a46396127949a6663 | PHP | DeveloperTheExplorer/SelfBased | /feed.php | UTF-8 | 12,911 | 2.546875 | 3 | [] | no_license | <?php
include_once("php_includes/check_login_status.php");
include_once("classes/develop_php_library.php");
// If user is logged in, header them away
if(!isset($_SESSION['username'])) {
header('location: /');
}
?><?php
// Initialize any variables that the page might echo
$u = "";
$userlevel = "";
$avatar = "";
$country = "";
$bio = "";
$joindate = "";
$lastsession = "";
// Select the member from the users table
$sql = "SELECT * FROM users WHERE username='$log_username' LIMIT 1";
$user_query = mysqli_query($db_conx, $sql);
// Now make sure that user exists in the table
$numrows = mysqli_num_rows($user_query);
if($numrows < 1){
echo "The User that you have entered does not exist.";
exit();
}
// Fetch the user row from the query above
while ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
$profile_id = $row["id"];
$name = $row["name"];
$city = $row["city"];
$country = $row["country"];
$bio = $row["Bio"];
$userlevel = $row["userlevel"];
$avatar = $row["avatar"];
$signup = $row["signup"];
$lastlogin = $row["lastlogin"];
$joindate = strftime("%b %d, %Y", strtotime($signup));
$lastsession = strftime("%b %d, %Y", strtotime($lastlogin));
}
$pieces = explode(" ", $name);
$firstName = $pieces[0];
if ($bio == "") {
$bio = $firstName." has not written a bio yet.";
}
if($avatar != "") {
$profilePhoto = '<span class="profile-main profile_p short-animation" style="'.$avatar.'"></span>
';
} else {
$profilePhoto = '<span class="profile-main profile_p short-animation"></span>';
}
if(isset($_SESSION["username"])){
$jvVar = "$('.stars')";
$tooltip = "";
} else {
$jvVar = "$('.nonexistance')";
$tooltip = "data-tooltip='Please log in or sign up to rate.'";
}
$sql = "SELECT ptid FROM enroll WHERE username='$log_username'";
$query = mysqli_query($db_conx, $sql);
$statusnumrows = mysqli_num_rows($query);
$enrolledIn = $firstName." has enrolled in ".$statusnumrows." different sources.";
if($statusnumrows == 1) {
$enrolledIn = $firstName." has enrolled in ".$statusnumrows." source.";
}
?><?php
$statuslist = "";
$statuslist1 = "";
$sql = "SELECT interest FROM interests WHERE username='$log_username' ORDER BY postdate DESC LIMIT 3";
$query = mysqli_query($db_conx, $sql);
$statusnumrows = mysqli_num_rows($query);
if($statusnumrows >= 1){
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$interest = $row["interest"];
$sql68 = "SELECT * FROM post WHERE tags LIKE '%$interest%' OR blurb LIKE '%$interest%' ORDER BY postdate DESC LIMIT 10";
$query68 = mysqli_query($db_conx, $sql68);
$statusnumrows68 = mysqli_num_rows($query68);
if($statusnumrows68 > 0){
while ($row68 = mysqli_fetch_array($query68, MYSQLI_ASSOC)) {
$statusid = $row68["id"];
$author = $row68["author"];
$title = $row68["title"];
$title = nl2br($title);
$title = str_replace("&","&",$title);
$title = stripslashes($title);
$category = $row68["category"];
$web = $row68["web"];
$web = nl2br($web);
$web = str_replace("&","&",$web);
$web = stripslashes($web);
$blurb = $row68["blurb"];
$blurb = nl2br($blurb);
$blurb = str_replace("&","&",$blurb);
$blurb = stripslashes($blurb);
$price = $row68["price"];
$apple = $row68["apple"];
$android = $row68["android"];
$image = $row68["image"];
$rating = $row68["rating"];
$postdate = $row68["postdate"];
if($android == "" && $apple == "") {
$androidIcon = '<span class="android float-left med-opacity med-large-font center-text bold small-padding-top font-red"></span>';
$appleIcon = '<span class="apple float-left med-opacity med-large-font center-text bold small-padding-top font-red"></span>';
} else if($android != '' && $apple != '') {
$androidIcon = '<a href="'.$android.'" target="_blank"><span class="android float-left med-large-font opacity-hover center-text bold small-padding-top font-red"></span></a>';
$appleIcon = '<a href="'.$apple.'" target="_blank"><span class="apple float-left med-large-font opacity-hover center-text bold small-padding-top font-red"></span></a>';
} else if($android != '' && $apple == '') {
$androidIcon = '<a href="'.$android.'" target="_blank"><span class="android float-left med-large-font opacity-hover center-text bold small-padding-top font-red"></span></a>';
$appleIcon = '<span class="apple float-left med-opacity med-large-font center-text bold small-padding-top font-red"></span>';
} else if($android == '' && $apple != '') {
$androidIcon = '<span class="android float-left med-opacity med-large-font center-text bold small-padding-top font-red"></span>';
$appleIcon = '<a href="'.$apple.'" target="_blank"><span class="apple float-left med-large-font opacity-hover center-text bold small-padding-top font-red"></span></a>';
}
// $timeAgoObject = new convertToAgo;
// $convertedTime = ($timeAgoObject -> convert_datetime($postdate)); // Convert Date Time
// $when = ($timeAgoObject -> makeAgo($convertedTime));
if ($image == 'na') {
$photo = 'style/no-photo1.svg';
} else {
$photo = 'permUploads/'.$image;
}
$percentage = 0;
if ($price != 0) {
$price1 = number_format($price);
$price = '$'.$price1;
} else if($price == 0) {
$price = "FREE";
}
if($rating != 0) {
$total = $rating * 20;
$percentage = round($total, 1, PHP_ROUND_HALF_UP);
}
$reviews = "";
$sql2 = "SELECT * FROM review WHERE postid='$statusid' LIMIT 999999999";
$query2 = mysqli_query($db_conx, $sql2);
$statusnumrows2 = mysqli_num_rows($query2);
if($statusnumrows2 == 0){
$reviews = "0 Reviews";
} else if($statusnumrows2 == 1){
$reviews = "1 Review";
} else if($statusnumrows2 > 1){
$reviews = "".$statusnumrows2." Reviews";
}
if ($image != 'na') {
$photo = 'background-image: url(permUploads/'.$image.');';
} else {
$photo = "";
}
$statuslist .= '
<div class="full-width border-lightgray border-top-bottom relative med-padding flex-box-between postarea">
<span class="fake-img float-left postimg med-margin-right" style="'.$photo.'">
</span>
<div class="textbox">
<h2 class="margin-none flex-box-between"><a href="source.php?id='.$statusid.'">'.$title.'</a> <span><a data-id="'.$statusid.'" href="'.$web.'" class="underline font-gray med-font narrow-font enroll">Visit Website</a></span></h2>
<div class="block font-blue italic bold">
'.$price.'
</div>
<div class="flex-box-between">
<div class="margin-none display-flex">
'.$androidIcon.'
'.$appleIcon.'
</div>
<div class="relative star-size" '.$tooltip.'>
<span class="yellow-background short-animation star-size absolute left top" data-starRating="'.$percentage.'%" style="z-index: 20; width: '.$percentage.'%;"></span>
<div class="star-rating relative" style="z-index: 21;" data-statusid="'.$statusid.'"></div>
<span class="transparent absolute cursor-pointer star-size top stars star1" data-rate="1"></span>
<span class="transparent absolute cursor-pointer star-size top stars star2" data-rate="2"></span>
<span class="transparent absolute cursor-pointer star-size top stars star3" data-rate="3"></span>
<span class="transparent absolute cursor-pointer star-size top stars star4" data-rate="4"></span>
<span class="transparent absolute cursor-pointer star-size top stars star5" data-rate="5"></span>
<span class="small-font reviews">'.$reviews.'</span>
<span class="med-font float-right font-blue final-rating">'.$rating.'</span>
</div>
</div>
<div class="block relative small--margin-bottom">
<p class="margin-none padding-none">'.$blurb.'</p>
</div>
</div>
</div>';
}
$statuslist1 .= '
<h3 class="center-text font-gray margin-none med-margin-top">'.$interest.'</h3><br>'.$statuslist;
$statuslist = "";
}
}
} else {
$statuslist1 = '<h2 class="font-lightgray center-text">Hmmm... Looks Like You Haven\'t added your interests yet.</h2><p class="font-gray bold center-text">You Can Do That At The <a href="setting.php">Settings</a> Page.</p></div><div class="dummy-space">
</div>';
}
if($statuslist1 == "") {
$statuslist1 = "<h2 class='font-lightgray center-text'>Whoops!<br>No Data Was Found Based On Your Current Interest.</h2><p class='center-text font-gray bold'>Add Some More <a href='setting.php'>Here</a>!</p><div class='dummy-space'></div>";
}
$sql = "SELECT interest FROM interests WHERE username='$log_username' ORDER BY postdate DESC";
$query = mysqli_query($db_conx, $sql);
$feeds = mysqli_num_rows($query);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title><?php echo $name; ?></title>
<?php include_once("head.php"); ?>
<?php include_once("stars.php"); ?>
</head>
<body data-pageName="feed">
<?php include_once("template_PageTop.php"); ?>
<!-- <div class="fixed user-pop">
<h1 class="margin-none center-text"><i class="profile-main gray-background"></i><?php echo $name; ?></h1>
</div> -->
<main>
<div class="parallax" style="padding-bottom: 0;">
<div class="profile-background border-top-bottom border-gray large-padding padding-top-bottom" >
<div class="pageMiddle">
<div class="flex-box-between profile-info profile-contain transparent-dark-background">
<div class="align-bottom relative profile-first">
<?php echo $profilePhoto ?>
<h3 class="inline-block"><?php echo $name; ?></h3>
</div>
<div class="flex-box-between profile-second">
<div class="align-bottom relative small-padding">
<?php echo $city;?>, <?php echo $country;?>
</div>
<div class="align-bottom relative small-padding">
<?php echo $enrolledIn; ?>
</div>
<div class="full-width">
<p class=""><strong>Bio:</strong> <?php echo $bio; ?></p>
</div>
</div>
</div>
</div>
</div>
<div class="parallax-user">
<div class="pageMiddle med-margin-top relative feedresults" style="z-index: 20;">
<h2 class="large-font center-text font-lightgray">Your Feed</h2>
<?php echo $statuslist1; ?>
</div>
</div>
</div>
</main>
<?php include_once("template_PageBottom.php"); ?>
</body>
</html>
<script type="text/javascript">
$(function() {
function profileSize() {
var widthFul = $('.profile-contain').width();
var width1 = $('.profile-first').width();
var wWidth = $(window).width();
var flexWidth = widthFul - width1 - 50;
if (wWidth > 640) {
$('.profile-second').width(flexWidth);
$('.full-width').css('width', flexWidth * 0.99);
} else {
$('.profile-second').css('width', 'auto');
$('.full-width').css('min-width', 0);
$('.full-width').css('width', widthFul * 0.98);
}
var profileHeight = $('.profile-background').height();
$('.parallax-user').css('margin-top', profileHeight + 100);
var headerHeight = $('header').height();
$('.user-pop').css('margin-top', headerHeight + 10);
}
profileSize();
$(window).resize(function() {
profileSize();
});
$(window).scroll(function() {
var wScroll = $(window).scrollTop();
if(wScroll > $('.profile-background').height() + 100) {
$('.profile-background').css('display', 'none');
} else {
$('.profile-background').css('display', 'block');
}
});
$('body').on('click','.enroll', function() {
var statusid = $(this).attr('data-id');
var action = "enroll";
$.post('php_parsers/status_system.php', {
statusid: statusid,
action: action
}, function(data) {
if(data == "success") {
} else {
alert(data);
alert('Sorry, there\'s a problem in the system. Please contact us, so we can fix it! Thank you!');
}
})
});
var post_nm = '<?php echo $statusnumrows; ?>';
$(window).scroll(function() {
var sc = $(window).scrollTop();
var wh = $(window).height();
var dh = $(document).height();
if(sc >= dh - (wh + 400) ) {
if(post_nm < +'<?php echo $feeds ?>'){
$('.background-loader').fadeIn(100);
$('body').css('overflow-y', 'hidden');
$.post('php_parsers/loadmore.php', {
post_nm: post_nm,
action: 'load more feed'
}, function(data) {
var datArray = data.split("|");
var stage = datArray[0];
var info = datArray[1];
if(stage != "success") {
alert('Whoops. Something is wrong. Please contact us and tell us about it. Thank you!');
// alert(data);
} else {
$('.background-loader').fadeOut(100);
$('body').css('overflow-y', 'scroll');
$('.feedresults').append(info);
post_nm = +post_nm + 10;
var textboxWidth = $('.postarea').width() - $('.postimg').width() - 21;
$('.textbox').css({'width': textboxWidth});
}
});
}
}
});
})
</script>
| true |
380025524150b7b844cb6f55f3c6874ca30b174f | PHP | senasistencia/prototipo | /clases/notificacion.php | UTF-8 | 524 | 2.703125 | 3 | [] | no_license | <?php
//clase inicializada
class Notificacion{
//atributos de la tabla
private $id_notificacion;
private $mensaje;
private $fecha;
#las siguientes variables corresponden
#a llaves foraneas de la tabla
private $id_formato;
private $id_cliente;
private $documento_cliente;
private $id_aprendiz;
private $documento_aprendiz;
//metodos
public function __SET($atributo,$valor)
{
return $this->$atributo = $valor;
}
public function __GET($atributo)
{
return $this->$atributo;
}
}
?>
| true |
124f7b2e9b822c4b377d0bfc6c47280a163afddd | PHP | hank7618/ERP | /epsquad.php | UTF-8 | 4,927 | 2.578125 | 3 | [] | no_license | <?php
require_once(dirname(__FILE__)."/Connections/DB_config.php");
require_once(dirname(__FILE__)."/Connections/DB_class.php");
$command=$_POST["command"];
if ($command=="小組代碼資料" || $command=="返回") {
display_first_page($db);
}
elseif ($command=="查詢") {
display_search_page($db);
}
elseif ($command=="新增") {
display_insert_page($db);
display_first_page($db);
}
elseif ($command=="更新") {
display_modify_page($db);
}
elseif ($command=="刪除") {
display_delete_page($db);
display_first_page($db);
}
elseif ($command=="確認") {
display_confirm_page($db);
display_first_page($db);
}
function display_first_page($db) {
echo "<html><head><title>小組代碼資料</title>
<link rel='stylesheet' type='text/css' href='style.css'>
</head><body><center>
<table><form method='post' action=''>
<tr class='alt0'><td colspan=2>小組代碼資料</td></tr>
<tr><td class='alt1'>小組代碼</td>
<td><input type='text' name='squad_id' /></td></tr>
<tr><td class='alt1'>小組名稱</td>
<td><input type='text' name='name' /></td></tr></table>
<input class='cmd' type='submit' name='command' value='查詢'>
<input class='cmd' type='submit' name='command' value='新增'>
</form></center></body></html>";
}
function display_search_page($db) {
$squad_id=trim($_POST["squad_id"]);
$name=trim($_POST["name"]);
if ($squad_id=="") $squad_id="%";
else $squad_id="%".$squad_id."%";
if ($name=="") $name="%";
else $name="%".$name."%";
// 準備查詢命令按班級學號排序
$sql ="SELECT * FROM test.squad WHERE squad_id LIKE '$squad_id' AND name LIKE '$name' ORDER BY squad_id ";
$db->query($sql);
echo "<html><head><title>小組代碼資料</title>
<link rel='stylesheet' type='text/css' href='style.css'>
</head><body><center>
<table><form method='post' action=''>
<tr class='alt0'><td colspan=3>小組代碼資料</td></tr>
<tr class='alt1'><td>小組代碼</td><td>小組名稱</td><td>選擇</td></tr>";
$cnt=0;
while ($myrow = $db->fetch_array()) {
$squad_id=$myrow["squad_id"];
$name=$myrow["name"];
$bg=$cnt % 2 + 2;
echo "<tr class='alt$bg'><td>$squad_id</td><td>$name</td>
<td><input type='radio' name='squad_id' value='$squad_id'></td></tr>";
$cnt++;
}
echo "</table>
<input class='cmd' type='submit' name='command' value='更新'>
<input class='cmd' type='submit' name='command' value='刪除'
onclick=\"return confirm('確定要刪除嗎?');\" >
<input class='cmd' type='submit' name='command' value='返回'>
</center></body></html>";
}
function display_insert_page($db) {
$squad_id=trim($_POST["squad_id"]);
$name=trim($_POST["name"]);
if ($squad_id=="" || $name=="") {
display_first_page($db); exit();
}
$sql="INSERT INTO `test`.`squad` (`squad_id`, `name`) VALUES ('$squad_id','$name')";
$db->query($sql);
}
function display_delete_page($db) {
$squad_id=trim($_POST["squad_id"]);
if ($squad_id=="") {
display_first_page($db); die();
}
$sql="delete from test.squad where squad_id='$squad_id' ";
$db->query($sql);
}
function display_modify_page($db) {
$squad_id=$_POST["squad_id"];
if ($squad_id=="") {
display_first_page($db); die();
}
$sql="SELECT * FROM test.squad WHERE squad_id='$squad_id' ";
$db->query($sql);
$myrow = $db->fetch_array();
$name=$myrow["name"];
echo "<html><head><title>小組代碼資料</title>
<link rel='stylesheet' type='text/css' href='style.css'>
</head><body><center>
<table> <form method='post' action=''>
<tr class='alt0'><td colspan=4>小組代碼資料</td></tr>
<tr><td class='alt1'>小組代碼</td>
<td><input type='text' name='squad_id' value='$squad_id' readonly/></td>
<tr><td class='alt1'>小組名稱</td>
<td><input type='text' name='name' value='$name' /></td></tr>
</table>
<input class='cmd' type='submit' name='command' value='確認'
onclick=\"return confirm('確定更新嗎?');\" />
<input class='cmd' type='submit' name='command' value='返回'>
</form></center></body></html>";
}
function display_confirm_page($db) {
$squad_id=trim($_POST["squad_id"]);
$name=trim($_POST["name"]);
$sql="UPDATE test.squad SET name='$name' WHERE squad_id='$squad_id' ";
$db->query($sql);
}
?>
| true |
880740d7a34cf6e31bd306e597deb556ae421d05 | PHP | wsuwebteam/wsuwp-plugin-blocks | /classes/class-query-rest.php | UTF-8 | 2,101 | 2.75 | 3 | [] | no_license | <?php namespace WSUWP\Plugin\Blocks;
class Query_Rest {
protected static $rest_base = 'wp-json/wp/v2/';
public static function get_posts( $remote_site_url, $args = array() ) {
$post_query = array(
'posts' => array(),
);
if ( ! empty( $remote_site_url ) && ( false !== strpos( $remote_site_url, 'wsu.edu' ) || false !== strpos( $remote_site_url, '.local' ) ) ) {
$query_url = self::get_build_query_url( $remote_site_url, $args );
$response = self::get_remote_response( $query_url );
if ( is_array( $response ) && ! empty( $response ) ) {
foreach ( $response as $key => $response_post ) {
$post_query['posts'][] = new WP_Post( $response_post, 'rest' );
}
}
}
return $post_query;
}
protected static function get_remote_response( $query_url ) {
$response = wp_remote_get( esc_url_raw( $query_url ) );
$api_response = json_decode( wp_remote_retrieve_body( $response ), true );
return $api_response;
}
protected static function get_query_args( $atts ) {
$default_fields = array( 'author', 'id', 'excerpt', 'title', 'link', '_embedded', '_links', 'date' );
$query_args = array(
'_embed' => 'author,wp:featuredmedia',
'per_page' => ( ! empty( $atts['count'] ) ) ? $atts['count'] : 5,
'_fields' => ( ! empty( $atts['fields'] ) ) ? $atts['fields'] : implode( ',', $default_fields ),
);
self::set_taxonomy_query_args( $query_args, $atts );
return $query_args;
}
protected static function get_build_query_url( $host, $args ) {
$base_url = trailingslashit( $host ) . self::$rest_base . 'posts/';
$query_args = self::get_query_args( $args );
return $base_url . '?' . http_build_query( $query_args );
}
protected static function set_taxonomy_query_args( &$query_args, $atts ) {
if ( ! empty( $atts['term_ids'] ) ) {
$taxonomy = ( ! empty( $atts['taxonomy'] ) ) ? $atts['taxonomy'] : 'category';
if ( 'category' === $taxonomy ) {
$query_args['categories'] = $atts['term_ids'];
}
}
if ( ! empty( $atts['and_logic'] ) ) {
$query_args['term_relation'] = 'AND';
}
}
}
| true |
5c29f334ba699366c6a0bb3600ba8ae618f1081b | PHP | surnin/frontpad.ru-sdk | /src/Frontpad.php | UTF-8 | 4,830 | 2.71875 | 3 | [
"MIT"
] | permissive | <?php
namespace Kolirt\Frontpad;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Response;
class Frontpad
{
private $client;
private $api_endpoint = 'https://app.frontpad.ru/api/index.php';
private $secret;
public function __construct($secret)
{
$this->secret = $secret;
$this->client = new Client([
'base_uri' => $this->api_endpoint,
'headers' => [
'Accept' => 'application/json'
]
]);
}
/**
* Метод предназначен для передачи заказа из интернет-магазина или приложения.
*
* @param Order $order
* @return object
*/
public function newOrder(Order $order)
{
return $this->call(function () use ($order) {
$form_params = $order->render();
$form_params['secret'] = $this->secret;
$request = $this->client->post('?new_order', [
'form_params' => $form_params
]);
return $this->prepareResponse($request);
});
}
/**
* Метод предназначен для передачи заказа из интернет-магазина или приложения.
*
* @param array $order
* @return object
*/
public function newOrderFromArray(array $order)
{
return $this->call(function () use ($order) {
$form_params = $order;
$form_params['secret'] = $this->secret;
$request = $this->client->post('?new_order', [
'form_params' => $form_params
]);
return $this->prepareResponse($request);
});
}
/**
* Метод предназначен для получения информации о клиенте, форма проверки может быть установлена
* в личном кабинете интернет-магазина.
* Запрещается циклический поиск клиентов.
*
* @param $client_phone
* @return object
*/
public function getClient($client_phone)
{
return $this->call(function () use ($client_phone) {
$request = $this->client->post('?get_client', [
'form_params' => [
'secret' => $this->secret,
'client_phone' => $client_phone
]
]);
return $this->prepareResponse($request);
});
}
/**
* Метод предназначен для проверки сертификата, форма проверки может
* быть установлена в личном кабинете интернет-магазина.
* Запрещается циклическая проверка сертификата.
*
* @param $certificate
* @return object
*/
public function getCertificate($certificate)
{
return $this->call(function () use ($certificate) {
$request = $this->client->post('?get_certificate', [
'form_params' => [
'secret' => $this->secret,
'certificate' => $certificate
]
]);
return $this->prepareResponse($request);
});
}
/**
* Метод предназначен для получения списка товаров и синхронизации их с интернет-магазином.
* Выгружаются только товары, имеющие артикул.
*
* @return object
*/
public function getProducts()
{
return $this->call(function () {
$request = $this->client->post('?get_products', [
'form_params' => [
'secret' => $this->secret,
]
]);
return $this->prepareResponse($request);
});
}
private function prepareResponse(Response $response)
{
$data = $response->getBody()->getContents();
$data = is_json($data) ? json_decode($data) : $data;
return (object)[
'ok' => $data->result === 'success',
'status_code' => $response->getStatusCode(),
'response' => $response,
'data' => $data
];
}
private function call($function)
{
try {
return $function();
} catch (\Exception $exception) {
$response = $exception->getResponse();
return $this->prepareResponse($response);
}
}
}
| true |
6149e810240198f90f5bfa412cd52e40e05b958b | PHP | NullCodeXx/project-chat | /controler/chat.php | UTF-8 | 571 | 3.109375 | 3 | [
"MIT"
] | permissive | <?php
//Si erreur applique ce qu'il y a dans !empty sinon continue
if(empty($_POST["text"])) {
http_response_code(400);
//change le header que l'on renvoie au client donc du text.
header("content-type: text/plain");
//test page.
echo "Erreur pas de contenue récupérer";
//Quitte ici / sort de cette function.
exit(1);
}
//Récup post de ajax.
$textarea = $_POST["text"];
//Pour envoyer a SQL.
include_once "../modele/Data.php";
$db = new Data();
//Récup function de la Class Data.php
$db->sendToSQL($textarea);
$db->seekFromSQL();
?> | true |
f80ca3aa7d66fd9dcfa9ea59c7204420f796d763 | PHP | joan-arteaga/proyecto-ceven | /Ceven1/vistas/vistasEventos/vistaActualizarEventos.php | UTF-8 | 8,234 | 2.578125 | 3 | [] | no_license | <?php
//@session_start();
if (isset($_SESSION['mensaje'])) {
$mensaje = $_SESSION['mensaje'];
echo "<script languaje='javascript'>alert('$mensaje')</script>";
unset($_SESSION['mensaje']);
}
if (isset($_SESSION['actualizarDatosEventos'])) {
$actualizarDatosEventos = $_SESSION['actualizarDatosEventos'];
unset($_SESSION['actualizarEventos']);
}
if (isset($_SESSION['registroCategoriasEventos'])) { /* * ************************ */
$registroCategoriasEventos = $_SESSION['registroCategoriasEventos'];
$cantCategorias = count($registroCategoriasEventos);
}
if (isset($_GET['erroresValidacion'])) {
$erroresValidacion = json_decode($_GET['erroresValidacion'], true); //true para que convierta un json a "array" y no a objeto
}
?>
<div class="panel-heading">
<h3 class="panel-title">Actualización del Evento.</h3>
</div>
<form role="form" method="POST" action="controladores/ControladorPrincipal.php" id="formRegistro">
<table>
<fieldset>
<tr>
<td>
<input class="form-control" placeholder="Id_Evento" name="eveId" type="number" pattern="" required="required" autofocus readonly="readonly"
value="<?php
if (isset($actualizarDatosEventos->eveId))
echo $actualizarDatosEventos->eveId;
if (isset($erroresValidacion['datosViejos']['eveId']))
echo $erroresValidacion['datosViejos']['eveId'];
if (isset($_SESSION['eveId']))
echo $_SESSION['eveId'];
unset($_SESSION['eveId']);
?>">
<?php if (isset($erroresValidacion['marcaCampo']['eveId'])) echo "<font color='red'>" . $erroresValidacion['marcaCampo']['eveId'] . "</font>"; ?>
<?php if (isset($erroresValidacion['mensajesError']['eveId'])) echo "<font color='red'>" . $erroresValidacion['mensajesError']['eveId'] . "</font>"; ?>
<!--<p class="help-block">Example block-level help text here.</p>-->
</td>
</tr>
<tr>
<td>
<input class="form-control" placeholder="Fecha_Inicial" name="eveFechaInicial" type="date" required="required"
value="<?php
if (isset($actualizarDatosEventos->eveFechaInicial))
echo $actualizarDatosEventos->eveFechaInicial;
if (isset($erroresValidacion['datosViejos']['eveFechaInicial']))
echo $erroresValidacion['datosViejos']['eveFechaInicial'];
if (isset($_SESSION['eveFechaInicial']))
echo $_SESSION['eveFechaInicial'];
unset($_SESSION['eveFechaInicial']);
?>">
<?php if (isset($erroresValidacion['marcaCampo']['eveFechaInicial'])) echo "<font color='red'>" . $erroresValidacion['marcaCampo']['eveFechaInicial'] . "</font>"; ?>
<?php if (isset($erroresValidacion['mensajesError']['eveFechaInicial'])) echo "<font color='red'>" . $erroresValidacion['mensajesError']['eveFechaInicial'] . "</font>"; ?>
<!--<p class="help-block">Example block-level help text here.</p>-->
</td>
</tr>
<tr>
<td>
<input class="form-control" placeholder="Cantidad_de_Personas" name="eveCantidadPax" type="number" required="required"
value="<?php
if (isset($actualizarDatosEventos->eveCantidadPax))
echo $actualizarDatosEventos->eveCantidadPax;
if (isset($erroresValidacion['datosViejos']['eveCantidadPax']))
echo $erroresValidacion['datosViejos']['eveCantidadPax'];
if (isset($_SESSION['eveCantidadPax']))
echo $_SESSION['eveCantidadPax'];
unset($_SESSION['eveCantidadPax']);
?>">
<?php if (isset($erroresValidacion['marcaCampo']['eveCantidadPax'])) echo "<font color='red'>" . $erroresValidacion['marcaCampo']['eveCantidadPax'] . "</font>"; ?>
<?php if (isset($erroresValidacion['mensajesError']['eveCantidadPax'])) echo "<font color='red'>" . $erroresValidacion['mensajesError']['eveCantidadPax'] . "</font>"; ?>
</td>
</tr>
<tr>
<td>
<input class="form-control" placeholder="Documento_Cliente" name="Clientes_cliDocumento" type="number" required="required"
value="<?php
if (isset($actualizarDatosEventos->Clientes_cliDocumento))
echo $actualizarDatosEventos->Clientes_cliDocumento;
if (isset($erroresValidacion['datosViejos']['Clientes_cliDocumento']))
echo $erroresValidacion['datosViejos']['Clientes_cliDocumento'];
if (isset($_SESSION['Clientes_cliDocumento']))
echo $_SESSION['Clientes_cliDocumento'];
unset($_SESSION['Clientes_cliDocumento']);
?>">
<?php if (isset($erroresValidacion['marcaCampo']['Clientes_cliDocumento'])) echo "<font color='red'>" . $erroresValidacion['marcaCampo']['Clientes_cliDocumento'] . "</font>"; ?>
<?php if (isset($erroresValidacion['mensajesError']['Clientes_cliDocumento'])) echo "<font color='red'>" . $erroresValidacion['mensajesError']['Clientes_cliDocumento'] . "</font>"; ?>
</td>
</tr>
<tr>
<td>
<input class="form-control" placeholder="Estado_Evento" name="eveEstado" type="number" required="required"
value="<?php
if (isset($actualizarDatosEventos->eveEstado))
echo $actualizarDatosEventos->eveEstado;
if (isset($erroresValidacion['datosViejos']['eveEstado']))
echo $erroresValidacion['datosViejos']['eveEstado'];
if (isset($_SESSION['eveEstado']))
echo $_SESSION['eveEstado'];
unset($_SESSION['eveEstado']);
?>">
<?php if (isset($erroresValidacion['marcaCampo']['eveEstado'])) echo "<font color='red'>" . $erroresValidacion['marcaCampo']['eveEstado'] . "</font>"; ?>
<?php if (isset($erroresValidacion['mensajesError']['eveEstado'])) echo "<font color='red'>" . $erroresValidacion['mensajesError']['eveEstado'] . "</font>"; ?>
</td>
</tr>
<input type="hidden" name="ruta" value="confirmaActualizarEventos">
<!--<input type="hidden" name="contenido" value="controlarRegistro">-->
<tr>
<td>
<!--<button onclick="valida_registro()">Actualizar </button>-->
<button type="submit" >Actualizar Evento</button>
</td>
</tr>
</table>
</form>
<?php if (isset($erroresValidacion)) $erroresValidacion = NULL; ?>
| true |
e158e9f2cdc95ee8f6a578d2758163a133da3260 | PHP | jonathansadler/mechedit | /1.0 Release/editManager.php | UTF-8 | 5,453 | 2.765625 | 3 | [] | no_license | <?php
/*******************************************************************************
Mech Edit Copyright 2009 Robert W. Mech
($Rev: 0 $)
Website: http://www.mechedit.com/
Author: Robert W. Mech
Mech Edit is available for use in all personal or commercial projects under both
MIT and GPL licenses. This means that you can choose the license that best suits
your project, and use it accordingly.
Redistributions of files must retain the above copyright notice.
*******************************************************************************/
include 'configure.php';
include('simple_html_dom.php');
require_once 'authentication.php';
session_start();
if(isset($_GET['action']) && !processLogin()){
echo NOT_AUTHENTICATED;
exit;
}
// Actions for this XHR File
if($_GET['action']=='get')
getPageJSON();
// Actions for this XHR File
if($_GET['action']=='update')
updatePage();
function updatePage(){
// First decode the received data
$pageData=base64_decode($_POST['data']);
// Get the page we need to edit
$html=getPage();
// Iterate HTML, look for the editable region and make sure it's count matches the one being sent.
$eid=0; // Assign logical number to each found class tag
foreach($html->find('.clienteditor') as $e){ // TODO: change this to variable defined topic for edit regions
if($eid==$_GET['id']){
$e->innertext=$pageData;
}
$eid++;
}
// Post Back the updated HTML object.
$result=postData($html);
echo "{'status':'$result'}";
}
function postData($html){
$pageData=getPages();
for($i=0;$i<sizeof($pageData);$i++){
if($pageData[$i]['key']==$_GET['key']){
$page=$pageData[$i];
}
}
// Return on empty/not found page
if(!isset($page)){
return PAGE_NOT_FOUND;
}
// Access Site Info
$siteData=getSites();
for($i=0;$i<sizeof($siteData);$i++){
if($siteData[$i]['id']==$page['id']){
$site=$siteData[$i];
}
}
// Return on empty/not found page
if(!isset($site)){
return SITE_NOT_FOUND;
}
// Real Work Done Here
// FTP Connection Setup
$ftp_server=$site['site'];
$ftp_user_name=$site['user'];
$ftp_user_pass=$site['password'];
$local_file = tempnam("/tmp", "tmp");
$source_file=$local_file;
$server_file=$site['path'].$page['path'];
// set up basic connection
$conn_id = ftp_connect($ftp_server);
// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
// check connection
if ((!$conn_id) || (!$login_result)) {
return FTP_CONNECT_FAILURE . "$ftp_user_name @ $ftp_server";
}
file_put_contents($source_file,$html);
// upload the file
$upload = ftp_put($conn_id, $server_file, $source_file, FTP_BINARY);
// close the FTP stream
ftp_close($conn_id);
unlink($source_file);
// check upload status
if (!$upload) {
return FTP_UPLOAD_FAILURE;
} else {
return FTP_UPLOAD_SUCCESS;
}
}
/*
* Change the HTML DOM object into an array for those editable items
* and echo the JSON data back to the client.
*/
function getPageJSON(){
$html=getPage();
$eid=0; // Assign logical number to each found class in linear order
foreach($html->find('.clienteditor') as $e){ // TODO: change this to variable defined topic for edit regions
if(isset($e->attr['title']))
$title=$e->attr['title'];
else
$title='';
// Type Checking (to see what sort of editor box we need)
if(array_search(strtoupper($e->tag),array('H1','H2','H3','H4','H5','H6'))!==false){
$type=TXT_HEADING_TAG;
}elseif(array_search(strtoupper($e->tag),array('pre'))!==false){
$type=TXT_FIXED_WIDTH;
}else{
$type=TXT_STANDARD;
}
$pageHTML[]=array('id'=> $eid, 'HTML'=>base64_encode($e->innertext),'title'=>$title,'tag'=>$e->tag,'type'=>$type);
$eid++;
}
echo json_encode($pageHTML);
}
/*
* Function to retreive the file VIA FTP and then return a DOM object for further processing
* TODO: Clean up procedure and add error handling.
* @returns a DOM object from the FTP file.
*/
function getPage(){
$pageData=getPages();
for($i=0;$i<sizeof($pageData);$i++){
if($pageData[$i]['key']==$_GET['key']){
$page=$pageData[$i];
}
}
// Return on empty/not found page
if(!isset($page)){
return;
}
// Access Site Info
$siteData=getSites();
for($i=0;$i<sizeof($siteData);$i++){
if($siteData[$i]['id']==$page['id']){
$site=$siteData[$i];
}
}
// Return on empty/not found page
if(!isset($site)){
return;
}
// Real Work Done Here
// FTP Connection Setup
$ftp_server=$site['site'];
$ftp_user_name=$site['user'];
$ftp_user_pass=$site['password'];
$local_file = tempnam("/tmp", "tmp");
$server_file=$site['path'].$page['path'];
// set up basic connection
$conn_id = ftp_connect($ftp_server);
// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
// check connection
if ((!$conn_id) || (!$login_result)) {
echo "FTP connection has failed!";
echo "Attempted to connect to $ftp_server for user $ftp_user_name";
exit;
}
if (ftp_get($conn_id, $local_file, $server_file, FTP_BINARY)) {
// echo "Successfully written to $local_file\n";
} else {
echo "There was a problem\n";
}
// close the FTP stream
ftp_close($conn_id);
$html = file_get_html($local_file);
unlink($local_file);
return $html;
}
?>
| true |
c06fcb92b1c5176c5c0c946812e45bb5493e2bd7 | PHP | JunIkeda-AIM/nishiHP | /need_pass_to_enter/database/search_db_pass.php | UTF-8 | 5,577 | 2.71875 | 3 | [] | no_license | <?php
$gobackURL = "../data/team_member_pass.php";
$dsn = 'mysql:dbname=nishi_swimming_club;charset=utf8;host=localhost';
$user = 'nishi';
$password = 'Onepiece2015';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- BootstrapのCSS読み込み -->
<link href="../../css/bootstrap.min.css" rel="stylesheet">
<!-- jQuery読み込み -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- BootstrapのJS読み込み -->
<script src="../../js/bootstrap.min.js"></script>
<title>member</title>
</head>
<body>
<?php
try {
$pdo = new PDO($dsn, $user, $password, array(PDO::ATTR_EMULATE_PREPARES => false));
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'データベース接続失敗。';
exit();
}
try{
$name = $_POST["name"];
$class = $_POST["class"];
$sex = $_POST["sex"];
$s1 = $_POST["s1"];
if ($name===NULL) {
switch ($class) {
case 0:
switch ($sex) {
case '0':
switch ($s1) {
case '0':
$sql = "SELECT * FROM team_member";
$stm = $pdo->query($sql);
break;
default:
$sql = "SELECT * FROM team_member WHERE s1=:s1";
$stm = $pdo->prepare($sql);
$stm->bindValue(':s1', $s1, PDO::PARAM_STR);
$stm->execute();
break;
}
break;
default:
switch ($s1) {
case '0':
$sql = "SELECT * FROM team_member WHERE sex=:sex";
$stm = $pdo->prepare($sql);
$stm->bindValue(':sex', $sex, PDO::PARAM_STR);
$stm->execute();
break;
default:
$sql = "SELECT * FROM team_member WHERE sex=:sex AND s1=:s1";
$stm = $pdo->prepare($sql);
$stm->bindValue(':sex', $sex, PDO::PARAM_STR);
$stm->bindValue(':s1', $s1, PDO::PARAM_STR);
$stm->execute();
break;
}
break;
}
break;
default:
switch ($sex) {
case '0':
switch ($s1) {
case '0':
$sql = "SELECT * FROM team_member WHERE class=:class";
$stm = $pdo->prepare($sql);
$stm->bindValue(':class', $class, PDO::PARAM_INT);
$stm->execute();
break;
default:
$sql = "SELECT * FROM team_member WHERE class=:class AND s1=:s1";
$stm = $pdo->prepare($sql);
$stm->bindValue(':class', $class, PDO::PARAM_INT);
$stm->bindValue(':s1', $s1, PDO::PARAM_STR);
$stm->execute();
break;
}
break;
default:
switch ($s1) {
case '0':
$sql = "SELECT * FROM team_member WHERE class=:class AND sex=:sex";
$stm = $pdo->prepare($sql);
$stm->bindValue(':class', $class, PDO::PARAM_INT);
$stm->bindValue(':sex', $sex, PDO::PARAM_STR);
$stm->execute();
break;
default:
$sql = "SELECT * FROM team_member WHERE class=:class AND sex=:sex AND s1=:s1";
$stm = $pdo->prepare($sql);
$stm->bindValue(':class', $class, PDO::PARAM_INT);
$stm->bindValue(':sex', $sex, PDO::PARAM_STR);
$stm->bindValue(':s1', $s1, PDO::PARAM_STR);
$stm->execute();
break;
}
break;
}
break;
}
} else {
$sql = "SELECT * FROM team_member WHERE name LIKE :name0";
$stm = $pdo->prepare($sql);
$name0 = '%'.$name.'%';
$stm->bindValue(':name0', $name0, PDO::PARAM_STR);
$stm->execute();
}
$pdo=null;
} catch (Exception $e) {
echo 'データ受信失敗。';
exit();
}
?>
<div class="container" style="padding-top:50px;">
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Sex</th>
<th>Class</th>
<th>S1</th>
</tr>
</thead>
<tbody>
<?php
foreach ($stm as $row) {
echo "<tr>";
echo "<th>", $row['id'], "</th>";
echo "<td>", $row['name'], "</td>";
echo "<td>", $row['sex'], "</td>";
echo "<td>", $row['class'], "</td>";
echo "<td>", $row['s1'], "</td>";
echo "</tr>";
} ?>
</tbody>
</table>
</div>
<a href="../data/team_member_pass.php" class="btn btn-success" role="button">戻る</a>
</div>
</body>
</html>
| true |
56d8832da3fb1c07a507f25bb253730d637d223a | PHP | VenoVX/php-pro | /annonce_delete.php | UTF-8 | 1,506 | 2.703125 | 3 | [] | no_license | <?php
require("class/database.php");
session_start();
$db = new database();
$stmtgetAnnoncen = $db->getConnection()->prepare("select titel from annonce;");
$stmtgetAnnoncen->execute();
$annoncen = $stmtgetAnnoncen->fetchall();
?>
<html>
<head>
<meta charset="UTF-8">
<title>Annoncen löschen</title>
<link rel="stylesheet" type="text/css" href="w3-schools.css">
<link rel="stylesheet" type="text/css" href="kleinanzeigen.css">
</head>
<body>
<header>
<h1 class="w3-indigo">Annoncen Löschen</h1>
<form action="kleinanzeigen.php" method="post">
<div class="w3-row">
<button type="submit" name="send" class="w3-btn-block w3-indigo w3-quarter backbutton">Zurück</button>
</div>
</form>
</header>
<main class="w3-margin">
<div class="divPadding w3-row">
<p class="w3-large">Hier können sie ihre Annoncen löschen.</p>
</div>
<div class="divPadding">
<form action="deleteAnnonce.php" method="POST" class="formPadding">
<?php
foreach ($annoncen as $items)
{
$item=$items['titel'];
echo "<input type='radio' name='annonce' value='$item' class='w3-row w3-large w3-check w3-indigo'>$item</br></input>";
}
?>
</div>
<div class="w3-row divPadding">
<button type='submit' name='$item' value='$item' class='w3-btn-block w3-indigo'>Löschen</button>
</div>
</form>
</main>
</body>
</html>
| true |
75d6fda43f8df449b3efb675d2450584705556af | PHP | zed0rb/crypto-api | /database/seeds/CurrenciesSeeder.php | UTF-8 | 479 | 2.65625 | 3 | [
"MIT"
] | permissive | <?php
use App\Currency;
use Illuminate\Database\Seeder;
class CurrenciesSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
if (Currency::count()) {
return;
}
$currenciesToCreate = ['BTC', 'ETH', 'IOTA'];
foreach ($currenciesToCreate as $currency) {
Currency::create([
'ticker' => $currency
]);
}
}
}
| true |
96fc9eb6fbd306a47a9433cf58ef3feea4bb37db | PHP | AMNP76/php-gaming-website | /src/Chat/Application/Command/InitiateChatCommand.php | UTF-8 | 607 | 3.09375 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types=1);
namespace Gaming\Chat\Application\Command;
final class InitiateChatCommand
{
private string $ownerId;
/**
* @var string[]
*/
private array $authors;
/**
* @param string[] $authors
*/
public function __construct(string $ownerId, array $authors)
{
$this->ownerId = $ownerId;
$this->authors = $authors;
}
public function ownerId(): string
{
return $this->ownerId;
}
/**
* @return string[]
*/
public function authors(): array
{
return $this->authors;
}
}
| true |
bbd2bb59f7efe36f6667f385c9f09dc31c7e4937 | PHP | guolei0601/php-test | /testTime.php | UTF-8 | 164 | 2.78125 | 3 | [] | no_license | <?php
$t = '2015-06-25';
$t= date('Y-m-d H:i:s',strtotime($t) - 60*15);
echo $t;
echo '<br/>';
$ctime = date ( 'Y-m-d', strtotime ( "-1 month" ) );
echo $ctime; | true |
20b42951beec9ac3bfc2e88cb9ea23668ac06161 | PHP | mops1k/benchmarks | /benchmarks/ArrayUnique.php | UTF-8 | 880 | 3.015625 | 3 | [] | no_license | <?php
declare(strict_types=1);
use PhpBench\Benchmark\Metadata\Annotations\Iterations;
use PhpBench\Benchmark\Metadata\Annotations\Revs;
/**
* Class ArrayUnique
*/
class ArrayUnique
{
private $array = ['a', 'b', 'c', 'b', 'd', 'a'];
/**
* @Revs(1000)
* @Iterations(100)
*/
public function benchUnique()
{
array_unique($this->array);
}
/**
* @Revs(1000)
* @Iterations(100)
*/
public function benchFlipUnique()
{
array_flip(array_flip($this->array));
}
/**
* @Revs(1000)
* @Iterations(100)
*/
public function benchForeachUnique()
{
$uniqueArray = [];
foreach ($this->array as $key => $value) {
if (\in_array($value, $uniqueArray, true)) {
continue;
}
$uniqueArray[$key] = $value;
}
}
}
| true |
a16e29a9a34292130faa4fd3267c12e297268589 | PHP | WasserEsser/Cachet | /app/Composers/StatusComposer.php | UTF-8 | 1,230 | 2.828125 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
/*
* This file is part of Cachet.
*
* (c) Alt Three Services Limited
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace CachetHQ\Cachet\Composers;
use CachetHQ\Cachet\Integrations\Contracts\System;
use Illuminate\Contracts\View\View;
/**
* This is the status composer.
*
* @author James Brooks <james@alt-three.com>
* @author Connor S. Parks <connor@connorvg.tv>
*/
class StatusComposer
{
/**
* The system instance.
*
* @var \CachetHQ\Cachet\Integrations\Contracts\System
*/
protected $system;
/**
* Create a new status composer instance.
*
* @param \CachetHQ\Cachet\Integrations\Contracts\System $system
*
* @return void
*/
public function __construct(System $system)
{
$this->system = $system;
}
/**
* Bind data to the view.
*
* @param \Illuminate\Contracts\View\View $view
*
* @return void
*/
public function compose(View $view)
{
$status = $this->system->getStatus();
$view->withSystemStatus(array_get($status, 'system_status'));
$view->withSystemMessage(array_get($status, 'system_message'));
}
}
| true |
677f0f926521890480dd274d813932fceed84ed9 | PHP | doDomoGu/yun.songtang.net | /components/FileFunc.php | UTF-8 | 11,822 | 2.53125 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
namespace app\components;
use app\models\Dir;
use app\models\File;
use yii\base\Component;
use yii\helpers\ArrayHelper;
use yii\helpers\BaseArrayHelper;
use yii;
class FileFunc extends Component {
Const ORDER_TYPE_1 = 'ord Desc,id Desc';
/*
* 函数getDropDownList ,实现根据is_leaf(Position表 is_leaf字段) 判断是部门还是职位
*
* @param integer p_id 父id (默认 0 )
* @param boolean showLeaf 是否显示叶子层级的标志位 (默认true)
* @param boolean includeSelf 是否包含自己本身的标志位 (默认false)
* @param integer level 显示层级数限制 (默认false,不限制)
* return string/null
*/
//public function getDropDownListOne($pid,$type,$showLeaf,$includeSelf=false){
public static function getDropDownList($dir_id,$p_id=0,$includeSelf=false,$level=false){
$arr = [];
$list = self::getListArr($dir_id,$p_id,false,$includeSelf,$level);
if(!empty($list)){
foreach($list as $l){
$prefix = '';
if($l->p_id>0){
/*for($i=0;$i<$l->level;$i++){
$prefix .=' ';
}
if($l->is_last>0){
$prefix .='└';
}else{
$prefix .='├';
}*/
}
$arr[$l->id] = $prefix.$l->filename;
}
}
return $arr;
}
/*
* 函数getDropDownList ,实现根据is_leaf(Dir表 is_leaf字段) 底层
*
* @param integer p_id 父id (默认 0 )
* @param boolean showLeaf 是否显示叶子层级的标志位 (默认true)
* @param boolean includeSelf 是否包含自己本身的标志位 (默认false)
* @param integer level 显示层级数限制 (默认false,不限制)
* return array
*/
public static function getListArr($dir_id,$p_id=0,$showTree=false,$includeSelf=false,$level=false){
$arr = [];
$file_dir = NULL;
$selfChildrenIds = [];
$dir = Dir::find()->where(['id'=>$dir_id,'is_leaf'=>1,'status'=>1])->one();
if($dir){
if($p_id>0){
//根据p_id(父id)查找对应父对象
$file_dir = File::find()->where(['id'=>$p_id,'filetype'=>0])->one();
if($file_dir==NULL || $file_dir->status==0){ //不存在或者状态禁用则返回空数组
return [];
}else if($includeSelf===true){ //将自己本身添加至数组
$arr[$file_dir->id]= $file_dir;
}
}/*else{
$file_dir = File::find()->where(['dir_id'=>$p_id,'filetype'=>0])->one();
}*/
$level = $level===false?false:intval($level);
if($level>0 || $level===false){ //level正整数 或者 false不限制
$list = self::getChildren($dir_id,$p_id);
if(!empty($list)){
$nlevel = $level===false?false: intval($level - 1);
foreach($list as $l){
$arr[$l->id] = $l;
if($showTree){
$prefix = '';
/*if($l->level>1){
for($i=1;$i<$l->level;$i++){
$prefix.=' ';
}
if($l->is_last>0){
$prefix.='└─ ';
} else{
$prefix.='├─ ';
}
}*/
$arr[$l->id]->filename = $prefix.$l->filename;
}
if($nlevel === false || $nlevel > 0){
$children = self::getListArr($dir_id,$l->id,$showTree,false,$nlevel);
$childrenIds = array();
if(!empty($children)){
foreach($children as $child){
$arr[$child->id] = $child;
$childrenIds[]=$child->id;
}
}
$arr[$l->id]->childrenIds = $childrenIds;
if($includeSelf===true){
$selfChildrenIds = ArrayHelper::merge($selfChildrenIds,$childrenIds);
}
}
if($includeSelf===true){
$selfChildrenIds = ArrayHelper::merge($selfChildrenIds,[$l->id]);
}
}
}
}
if($file_dir && $includeSelf===true){
$arr[$file_dir->id]->childrenIds = $selfChildrenIds;
}
}
return $arr;
}
/*
* 函数getDropDownArr ,实现根据is_leaf(Dir表 is_leaf字段) 底层
*
* @param integer p_id 父id (默认 0 )
* @param boolean showLeaf 是否显示叶子层级的标志位 (默认true)
* @param boolean includeSelf 是否包含自己本身的标志位 (默认false)
* @param integer level 显示层级数限制 (默认false,不限制)
* return array 递归
*/
public static function getChildrenArr($p_id=0,$showLeaf=true,$showTree=false,$includeSelf=false,$level=false){
$arr = [];
$dir = NULL;
if($p_id>0){
//根据p_id(父id)查找对应父对象
$dir = self::getOneByCache($p_id);
if($dir==NULL || $dir->status==0){ //不存在或者状态禁用则返回空数组
return [];
}else if($includeSelf===true){ //将自己本身添加至数组
$arr[$dir->id]= $dir;
}
}
$level = $level===false?false:intval($level);
if($level>0 || $level===false){ //level正整数 或者 false不限制
$list = self::getChildren($p_id,$showLeaf);
if(!empty($list)){
$nlevel = $level===false?false: intval($level - 1);
foreach($list as $l){
$arr[$l->id] = $l;
if($showTree){
$prefix = '';
if($l->level>1){
for($i=1;$i<$l->level;$i++){
$prefix.=' ';
}
if($l->is_last>0){
$prefix.='└─ ';
} else{
$prefix.='├─ ';
}
}
$arr[$l->id]->name = $prefix.$l->name;
}
if($nlevel === false || $nlevel > 0){
$children = self::getChildrenArr($l->id,$showLeaf,$showTree,false,$nlevel);
$childrenIds = [];
$childrenList = [];
if(!empty($children)){
foreach($children as $child){
//$arr[$child->id] = $child;
$childrenIds[]=$child->id;
$childrenList[]=$child;
}
}
$arr[$l->id]->childrenIds = $childrenIds;
$arr[$l->id]->childrenList = $childrenList;
}
}
}
}
return $arr;
}
/*
* 函数getChildren ,实现根据 p_id 获取子层级 (单层)
*
* @param integer p_id 父id (默认 0 )
* @param boolean showLeaf 是否显示叶子层级的标志位 (默认true)
* @param boolean status 状态 (默认1)
* @param string orderBy 排序方法
* return array
*/
public static function getChildren($dir_id,$p_id,$status=1,$orderBy=1,$limit=false){
$where['dir_id'] = $dir_id;
$where['p_id'] = $p_id;
$where['filetype'] = 0;
$where['status'] = $status;
$orderByStr = self::ORDER_TYPE_1;
//其他排序类型赋值;
/*if($orderBy==1){
$orderByStr = self::ORDER_TYPE_1;
}*/
$result = [];
$list = File::find()->where($where)->orderBy($orderByStr)->limit($limit)->asArray()->all();
if(!empty($list)){
foreach($list as $l){
$result[] = (object)$l;
}
}
return $result;
}
/*
* 函数getChildrenByCache ,实现根据 p_id 获取子层级 (单层)
* 读取数据缓存,有则直接返回缓存内容,没有则获取模型数据,并添加至缓存
* @param integer p_id 父id (默认 0 )
* @param boolean showLeaf 是否显示叶子层级的标志位 (默认true)
* @param boolean status 状态 (默认1)
* @param string orderBy 排序方法
* return array
*/
public static function getChildrenByCache($p_id,$showLeaf=true,$status=1,$orderBy=1,$limit=false){
$cache = yii::$app->cache;
$cacheExist = true;
$dirChildrenDataId = [];
$dirChildrenData = NULL;
$key = $p_id.'_'.($showLeaf==true?'1':'0').'_'.($status==1?'1':'0').'_'.$orderBy.'_'.($limit==false?'f':$limit);
//var_dump($key);exit;
if(isset($cache['dirChildrenDataId'])){
$dirChildrenDataId = $cache['dirChildrenDataId'];
if(isset($dirChildrenDataId[$key])){
$dirChildrenData = $cache['dirChildrenData_'.$key];
}else{
$cacheExist = false;
}
}else{
$cacheExist = false;
}
if($cacheExist == false){
$dirChildrenData = self::getChildren($p_id,$showLeaf,$status,$orderBy,$limit);
$cache['dirChildrenDataId'] = \yii\helpers\ArrayHelper::merge($dirChildrenDataId,[$key=>1]);
$cache['dirChildrenData_'.$key]=$dirChildrenData;
}
return $dirChildrenData;
}
/*
* 函数getOneByCache ,实现根据 id 读取数据缓存,有则直接返回缓存内容,没有则获取模型数据,并添加至缓存
*
* @param integer id dir:id
* return DirModel
*/
public static function getOneByCache($id){
$cache = yii::$app->cache;
$cacheExist = true;
$dirDataId = [];
$dirData = NULL;
if(isset($cache['dirDataId'])){
$dirDataId = $cache['dirDataId'];
if(isset($dirDataId[$id])){
$dirData = $cache['dirData_'.$id];
}else{
$cacheExist = false;
}
}else{
$cacheExist = false;
}
if($cacheExist == false){
$dirData = (object)(Dir::find()->where(['id'=>$id])->one()->toArray());
$cache['dirDataId'] = \yii\helpers\ArrayHelper::merge($dirDataId,[$id=>1]);
$cache['dirData_'.$id]=$dirData;
}
return $dirData;
}
/*
* 函数getParents ,实现根据 当前dir_id 递归获取全部父层级 id
*
* @param integer dir_id
* return array
*/
public static function getParents($dir_id,$p_id){
$arr = [];
$curDir = File::find()->where(['id'=>$p_id,'dir_id'=>$dir_id,'status'=>1])->one();
if($curDir){
$arr[] = $curDir;
$arr2 = self::getParents($dir_id,$curDir->p_id);
$arr = BaseArrayHelper::merge($arr,$arr2);
}
$arr = array_reverse($arr);
ksort($arr);
return $arr;
}
} | true |
c85aefbea0b7830da55e06f6e65e9a7c59dfe0f6 | PHP | roshansourav/CPIS | /functionality/removedoctordb.php | UTF-8 | 1,156 | 2.640625 | 3 | [
"MIT"
] | permissive | <?php
session_start();
$serverName = "localhost";
$userName = "root";
$password = "";
$dbname = "CPIS";
$conn = new mysqli($serverName, $userName, $password, $dbname);
if($conn->connect_error)
{
die("Connection Failed :" .$conn->connect_error);
}
$doctorid = $_POST['doctorid'];
$hpassword = $_POST['hpassword'];
$hbranchcode = $_SESSION['hbranchcode'];
$sql1 = "SELECT * from DOCTORS WHERE uniqueid = '$doctorid'";
$result = $conn->query($sql1);
if($result->num_rows > 0)
{}
else
{
die("Sorry. The ID you entered, doesn't exist.");
}
$sql2 = " SELECT password from HOSPITAL where branchcode = '$hbranchcode'";
$result = $conn->query($sql2);
if($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
if($row['password'] == $hpassword)
{
$sql = "DELETE from DOCTORS WHERE password='$hpassword'";
$result = $conn->query($sql);
header('Location: ../html/rightmark.html');
}
else
{
echo "Incorrect Password. Please try again..";
}
}
}
else
{
echo "Incorrect Password. Please try again..";
}
$conn->close();
?> | true |
96509e3642f6b09489e198711d2dcbf3fe9a60e1 | PHP | avinash2115/zentry | /zentry-api/app/Components/CRM/SyncLog/Mutators/DTO/Mutator.php | UTF-8 | 705 | 2.703125 | 3 | [] | no_license | <?php
namespace App\Components\CRM\SyncLog\Mutators\DTO;
use App\Components\CRM\SyncLog\SyncLogDTO;
use App\Components\CRM\SyncLog\SyncLogReadonlyContract;
/**
* Class Mutator
*
* @package App\Components\CRM\SyncLog\Mutators\DTO
*/
final class Mutator
{
public const TYPE = 'crms_sync_logs';
/**
* @param SyncLogReadonlyContract $entity
*
* @return SyncLogDTO
*/
public function toDTO(SyncLogReadonlyContract $entity): SyncLogDTO
{
$dto = new SyncLogDTO();
$dto->id = $entity->identity()->toString();
$dto->syncLogType = $entity->type();
$dto->createdAt = dateTimeFormatted($entity->createdAt());
return $dto;
}
}
| true |
849d521b0acc10ba7669d83cf63820eb2ce36117 | PHP | adoy/php-src | /ext/standard/tests/serialize/typed_property_ref_overwrite.phpt | UTF-8 | 253 | 2.625 | 3 | [
"PHP-3.01",
"IJG",
"Zlib",
"OLDAP-2.8",
"BSD-4-Clause-UC",
"ISC",
"BSD-3-Clause",
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-public-domain",
"TCL",
"BSD-2-Clause",
"GD"
] | permissive | --TEST--
Overwriting a typed property reference
--FILE--
<?php
class Test {
public ?object $prop;
}
$s = <<<'STR'
O:4:"Test":2:{s:4:"prop";R:1;s:4:"prop";N;}
STR;
var_dump(unserialize($s));
?>
--EXPECT--
object(Test)#1 (1) {
["prop"]=>
NULL
}
| true |
392900e91dcbd8d43789e5c74cad46c8d5160a70 | PHP | AlvarezKevin/QuickCover | /server_php/update_field.php | UTF-8 | 1,307 | 2.90625 | 3 | [] | no_license | <?php
/*
* Following code will update a user information
* A user is identified by user id (pid)
*/
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['db_name']) && isset($_POST['db_field_ref']) && isset($_POST['val_ref']) && isset($_POST['db_field_rep']) && isset($_POST['val_rep']) ) {
$db_name = $_POST['db_name'];
$db_field_ref = $_POST['db_field_ref'];
$val_ref = $_POST['val_ref'];
$db_field_rep = $_POST['db_field_rep'];
$val_rep = $_POST['val_rep'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql update row with matched pid
$result = mysql_query("UPDATE $db_name SET $db_field_rep = '$val_rep' WHERE $db_field_ref = '$val_ref' ");
// check if row inserted or not
if ($result) {
// successfully updated
$response["success"] = 1;
$response["message"] = "User successfully updated.";
// echoing JSON response
echo json_encode($response);
} else {
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
| true |
d85e23f8c7a0e7f4d92768ba69e6c1c503848d3f | PHP | jrmontoya/birdmash | /plugin.php | UTF-8 | 4,966 | 2.8125 | 3 | [] | no_license | <?php
/*
Plugin Name: Birdmash
Version: 1.0
Author: Haxor
*/
class Birdmash_Widget extends WP_Widget {
/**
* Sets up the widgets name etc
*/
public function __construct() {
$widget_ops = array(
'classname' => 'birdmash_widget',
'description' => 'Multiuser Twitter Mashup',
);
parent::__construct( 'birdmash_widget', 'Birdmash Widget', $widget_ops );
}
/**
* Outputs the content of the widget
*
* @param array $args
* @param array $instance
*/
public function widget( $args, $instance ) {
//Twitter API Settings
$url = 'https://api.twitter.com/1.1/statuses/user_timeline.json';
$requestMethod = 'GET';
$settings = array(
'oauth_access_token' => "204855451-1PYYPzkfDH0ow8sZFLwn3XuGW0Znb6dMw8cmh3ly",
'oauth_access_token_secret' => "zpS7OW8VUPU6RRrmC8arsGK9grckcnrXcAmkxXSx7jPP5",
'consumer_key' => "lrf22drvht235ROffWGbEwpXM",
'consumer_secret' => "HZ2Sx0KfWvbPBYOYoUrLTV358f0bw1rBpUwB50MkQNq1WXZ7rp"
);
//Include & Initialize TwitterAPIExchange Class
include( plugin_dir_path( __FILE__ ) . '/TwitterAPIExchange.php');
$twitter = new TwitterAPIExchange($settings);
$output = '';
//If title is empty
if (!empty($instance['title'])){
echo '<h4>' . $instance['title'] . '</h4>';
}
//If username is not empty, get the tweets data
if (!empty($instance['usernames'])) {
$arrAccounts = explode(",",$instance['usernames']);
for($i=0;$i<sizeof($arrAccounts);$i++){
$getfield = '?exclude_replies=true&include_rts=false&count=3&trim_user=true&screen_name=' . trim($arrAccounts[$i]);
//Data for current account
$objData = json_decode($twitter->setGetfield($getfield)->buildOauth($url, $requestMethod)->performRequest());
echo '<h5>@'.$arrAccounts[$i].'</h5>';
if(sizeof($objData)>0){
for($j=0;$j<sizeof($objData);$j++){
$tweet = $objData[$j]->text;
//Convert urls to <a> links
$tweet = preg_replace("/([\w]+\:\/\/[\w-?&;#~=\.\/\@]+[\w\/])/", "<a target=\"_blank\" href=\"$1\">$1</a>", $tweet);
//Convert hashtags to twitter searches in <a> links
$tweet = preg_replace("/#([A-Za-z0-9\/\.]*)/", "<a target=\"_new\" href=\"http://twitter.com/search?q=$1\">#$1</a>", $tweet);
//Convert attags to twitter profiles in <a> links
$tweet = preg_replace("/@([A-Za-z0-9\/\.]*)/", "<a href=\"http://www.twitter.com/$1\">@$1</a>", $tweet);
echo '<p>'.$tweet.'</p>';
}
}
else{//If not data available
echo '<p>No data available</p>';
}
}
}
}
/**
* Outputs the options form on admin
*
* @param array $instance The widget options
*/
public function form( $instance ) {
// outputs the options form on admin
$title = ! empty( $instance['title'] ) ? $instance['title'] : '';
$usernames = ! empty( $instance['usernames'] ) ? $instance['usernames'] : '';
$output = '';
if(isset($instance['error'])){
$output .= '<p>'.$instance['error'].'</p>';
}
$output .= '<p><label for="'.$this->get_field_id('title').'">Title:</label><br>';
$output .= '<input type="text" id="'.$this->get_field_id('title').'" name="'.$this->get_field_name('title').'" value="'.esc_attr($title).'" /></p>';
$output .= '<p><label for="'.$this->get_field_id('usernames').'">Twitter Usernames:</label><br>';
$output .= '<input type="text" id="'.$this->get_field_id('usernames').'" name="'.$this->get_field_name('usernames').'" value="'.esc_attr($usernames).'" />';
$output .= '<br><small>Enter a comma-separated list of own accounts.</small></p>';
echo $output;
}
/**
* Processing widget options on save
*
* @param array $new_instance The new options
* @param array $old_instance The previous options
*/
public function update( $new_instance, $old_instance ) {
// processes widget options to be saved
$instance['title'] = strip_tags( $new_instance[ 'title' ] );
if (empty($new_instance['usernames'])) {
$instance['error'] = "You must enter at least one Twitter account.";
}
else{
$instance['usernames'] = strip_tags( $new_instance[ 'usernames' ] );
}
return $instance;
}
}
add_action( 'widgets_init', function(){
register_widget( 'Birdmash_Widget' );
});
| true |
a3643c54597a0110a7b97835ec50503cc0c8e45f | PHP | milanezlucas/move-it | /dashboard/class/MI_Form.php | UTF-8 | 6,189 | 2.859375 | 3 | [] | no_license | <?php
// Form Fiedls for dashboard
class MI_Forms
{
protected $id;
protected $field;
protected $value;
protected $slug;
public function field( $form_id, $form_field, $form_value=null, $form_widget_id=null )
{
$this->id = $form_id;
$this->value = $form_value ? $form_value : '';
$this->slug = $form_widget_id ? '--' . $form_widget_id : '';
$this->fields_supports( $form_field );
$form = new stdClass();
switch ( $this->field->type ) {
case 'text':
$form->field = $this->text_field();
break;
case 'textarea':
$form->field = $this->textarea();
break;
case 'editor':
$form->field = $this->editor();
break;
case 'date':
$form->field = $this->date();
break;
case 'select':
$form->field = $this->select();
break;
case 'radio':
$form->field = $this->radio();
break;
case 'checkbox':
$form->field = $this->checkbox();
break;
case 'number':
$form->field = $this->number();
break;
case 'file':
$form->field = $this->file();
break;
}
$form->label = $this->field->label;
$form->desc = $this->field->desc;
$form->name = $this->id;
return $form;
}
// Text field
protected function text_field()
{
$html .= '<input name="' . $this->id . '" id="' . $this->field->name . '" value="' . esc_attr( stripslashes( $this->value ) ) . '" class="regular-text" type="text" ' . $this->fields->required . '>';
return $html;
}
// Textarea
protected function textarea()
{
$html .= '
<textarea name="' . $this->id . '" id="' . $this->fields->name . '" class="large-text" rows="3" ' . $this->fields->required . '>' . esc_attr( stripslashes( $this->value ) ) . '</textarea>
';
return $html;
}
// editor
protected function editor()
{
ob_start();
wp_editor( stripslashes( $this->value ), $this->id . $this->slug, array( 'media_buttons' => true, 'editor_class' => 'widget_editor' ) );
$html .= ob_get_clean();
ob_end_flush();
$html .= '<input type="hidden" name="' . $this->id . $this->slug . '_text" id="' . $this->field->name . $this->slug . '_text">';
return $html;
}
// Date
protected function date()
{
$html .= '<input name="' . $this->id . $this->slug . '" id="' . $this->field->name . $this->slug . '" value="' . esc_attr( $this->value ) . '" class="regular-text date-field" type="text" ' . $this->required . '>';
return $html;
}
// Select
protected function select()
{
$opt_name_array = $this->field->multiple ? '[]' : '';
$html .= '
<select name="' . $this->id . $opt_name_array .'" id="' . $this->field->name . '" ' . $this->field->multiple . ' class="postform">
<option value=""></option>
';
$values = ( is_array( $this->value ) ) ? $this->value : array( $this->value );
foreach ( $this->field->opt as $label => $val ) {
$html .= '<option value="' . $val . '"';
if ( $values ) {
$html .= ( in_array( $val, $values ) ) ? 'selected="selected"' : '';
}
$html .= '>' . $label . '</option>';
}
$html .= '
</select>
';
return $html;
}
// Radio
protected function radio()
{
foreach ( $this->field->opt as $label => $val ) {
$html .= '
<p>
<label>
<input name="' . $this->id . '" value="' . $val . '" class="tog"';
$html .= ( $val == $this->value ) ? 'checked="checked"' : '';
$html .= 'type="radio">
' . $label . '
</label>
</p>
';
}
return $html;
}
// Checkbox
protected function checkbox()
{
$values = ( is_array( $this->value ) ) ? $this->value : array( $this->value );
if ( $this->field->opt ) {
foreach ( $this->field->opt as $label => $val ) {
$html .= '
<p>
<label>
<input name="' . $this->id;
$html .= $this->field->multiple ? '[]' : '';
$html .= '" value="' . $val . '" class="tog" ';
if ( $values ) {
$html .= ( in_array( $val, $values ) ) ? 'checked="checked"' : '';
}
$html .= ' type="checkbox">
' . $label . '
</label>
</p>
';
}
}
return $html;
}
// Number
protected function number()
{
$min = $field[ 'min' ] ? 'min="' . $field[ 'min' ] . '"' : '';
$max = $field[ 'max' ] ? 'max="' . $field[ 'max' ] . '"' : '';
$html .= '
<input name="' . $this->id . '" id="' . $this->field->name . '" value="' . esc_attr( $this->value ) . '"
';
$html .= $this->field->min ? 'min="' . $this->field->min . '"' : '';
$html .= $this->field->max ? 'max="' . $this->field->max . '"' : '';
$html .= ' class="small-text" type="number" ' . $this->field->required . '>';
return $html;
}
// File (upload)
protected function file()
{
$html .= '
<ul class="upload-field-view-' . $this->field->name . $this->slug . ' upload-sortable">
';
$html .= $this->value ? mi_get_upload_button( $this->value, $this->field->name . $this->slug ) : '';
$html .= '
</ul>
<input type="hidden" name="' . $this->id . $this->slug . '" id="' . $this->field->name . $this->slug . '" value="' . esc_attr( $this->value ) . '" class="upload_field">
<input id="' . $this->field->name . $this->slug . '_button" type="button" class="button button_upload" value="Biblioteca" />
';
return $html;
}
/*
Fields supports
type: text, textarea, editor, select, checkbox, radio, file, date, number
label: Label for field
opt: array, select, checkbox, radio
desc: Description for field
required: Field required
name: Nem id for field
min: Min number
max: Max number
*/
private function fields_supports( $form_field )
{
$this->field = new stdClass();
foreach ( $form_field as $prop => $value ) {
switch ( $prop ) {
case 'opt':
if ( $value ) {
$this->field->$prop = new stdClass();
foreach ( $value as $val => $label ) {
if ( !empty( $val ) ) {
$this->field->$prop->$label = $val;
}
}
}
break;
case 'required':
$this->field->$prop = $value ? 'required="true"' : '';
break;
case 'name':
$this->field->$prop = $value ? $value : $this->id;
break;
case 'multiple':
$this->field->$prop = $value ? 'multiple="true"' : '';
break;
default:
$this->field->$prop = $value;
break;
}
}
}
}
| true |
ff6722e61a0502910087b45070af59534d96808a | PHP | armandojanssen1993/pdoTest | /check.php | UTF-8 | 937 | 2.65625 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: armandojanssen
* Date: 3/16/18
* Time: 10:00 AM
*/
session_start();
$user = "root";
$pass = "root";
try {
$conn = new PDO("mysql:host=localhost;dbname=test", $user, $pass);
} catch (PDOException $e) {
echo $e->getMessage();
}
$username = $_POST['username'];
$password = $_POST['password'];
$passhash = password_hash($password, PASSWORD_DEFAULT);
$test = false;
$selectUser = $conn->prepare("SELECT * FROM user");
$selectUser->execute();
$results = $selectUser->fetchAll(PDO::FETCH_OBJ);
//var_dump($results);
foreach ($results as $result){
if ($username === $result->username && password_verify($password, $result->password)){
echo "Je bent ingelogd";
$_SESSION["inlog"] = true;
$test = true;
if ($result->role_id == 2){
$_SESSION['admin'] = true;
}
}
}
if ($test === false){
echo "Niet ingelogd";
} | true |
7de10c75d64e628f2094da9970258ba9fce11afd | PHP | ajpadilla/rigorTalks | /src/Testing/CreationMethods/ProductCategory/Product.php | UTF-8 | 1,172 | 3.109375 | 3 | [] | no_license | <?php
namespace RigorTalks\Testing\CreationMethods\ProductCategory;
use RigorTalks\Testing\CreationMethods\ObjectMothers\CategoryMother;
use RigorTalks\Testing\CreationMethods\ObjectMothers\TaxMother;
class Product
{
/**
* @var string
*/
private $name;
/**
* @var string
*/
private $category;
/**
* @var float
*/
private $tax;
/**
* Product constructor.
* @param string $name
* @param string $category
* @param float $tax
*/
public function __construct(string $name,string $category)
{
$this->name = $name;
$this->category = CategoryMother::create($category);
$this->tax = TaxMother::random();
}
/**
* @return string
*/
public function getCategory()
{
return $this->category;
}
/**
* @return float
*/
public function getTax()
{
return $this->tax;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
public function getCategoryName()
{
return $this->category ? $this->category->getName() : null;
}
} | true |
ad667ee0b4ddd2c714e85619ee985dc69b65768a | PHP | kimkj2017/ScreenDisplay | /sign3-final/views/addDisplayItems.php | UTF-8 | 6,875 | 2.921875 | 3 | [] | no_license | <?php
require_once('./cse383-f16-screen/models/displayItems.php');
// Upload file function is from W3Schools,
// http://www.w3schools.com/php/php_file_upload.asp
function uploadFile($id) {
//var_dump($_FILES);
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES[$id]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
//if(isset($_POST["submit"])) {
$check = getimagesize($_FILES[$id]["tmp_name"]);
if($check !== false) {
//echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
//echo "File is not an image.";
//$uploadOk = 0;
}
//}
// Check if file already exists
//if (file_exists($target_file)) {
// echo "Sorry, file already exists.";
// $uploadOk = 0;
// $target_file = $target_dir.'copy_'.basename($_FILES[$id]["name"]);
//}
// Check file size
//if ($_FILES[$id]["size"] > 500000) {
// echo "Sorry, your file is too large.";
// $uploadOk = 0;
//}
// Allow certain file formats
if(strtolower($imageFileType) != "jpg" && strtolower($imageFileType) != "png"
&& strtolower($imageFileType) != "jpeg" && strtolower($imageFileType) != "gif" ) {
//echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed. Your img ext: $imageFileType";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
//echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
echo $target_file;
if (move_uploaded_file($_FILES[$id]["tmp_name"], $target_file)) {
//echo "The file ". basename( $_FILES[$id]["name"]). " has been uploaded.";
} else {
//echo "Sorry, there was an error uploading your file.";
$uploadOk = 0;
}
}
return $uploadOk;
}
function printForm($data=array('textValue'=>'','startDate'=>'','endDate'=>'','fileName'=>'','imgValue'=>'', 'version'=>0, 'content'=>''), $mode='addItem') {
echo("<div class='form-group'>\r\n");
echo("<form action='' method='post'");
if ($mode === 'addItem') {
echo(' enctype=\'multipart/form-data\'');
}
echo(">\r\n");
echo("<label for='textValue'>Text Value</label>\r\n");
echo("<input type='text' class='form-control' id='textValue' name='textValue' value='".$data['textValue']."'>\r\n");
echo("<label for='startDate'>Start Date</label>\r\n");
echo("<input type='text' class='form-control' id='startDate' name='startDate' value='".$data['startDate']."'>\r\n");
echo("<label for='endDate'>End Date</label>\r\n");
echo("<input type='text' class='form-control' id='endDate' name='endDate' value='".$data['endDate']."'>\r\n");
// echo("<label for='creator'>Creator</label>\r\n");
echo("<input type='hidden' id='creator' name='creator' value='".$_SESSION['user']."'>\r\n"); // Automatically gets username from SESSION
echo("<label for='fileName'>File Name</label>\r\n");
echo("<input type='text' class='form-control' id='fileName' name='fileName' value='".$data['fileName']."'>\r\n");
if ($mode !== 'editItem') {
echo("<label for='imgValue'>Image Upload</label>\r\n");
echo("<input type='file' id='imgValue' name='imgValue'>\r\n");
}
echo("<label>Text Content (Please use HTML code)</label>\r\n");
echo("<textarea class='form-control' id='content' name='content' style='font-family: \"Courier New\"; height: 300px;'>".$data['content']."</textarea>");
echo("<input type='hidden' id='version' name='version' value='".($data['version'])."'>\r\n");
echo("<input type='hidden' id='cmd' name='cmd' value='displayItemSubmit'>\r\n");
echo("<input type='hidden' id='mode' name='mode' value='$mode'>\r\n");
echo("<input type='submit' style='margin-top: 10px;' class='btn btn-primary'>\r\n");
echo("</form>\r\n</div>\r\n");
exit();
}
$cmd = getVar('cmd');
// block unauthorized access
if ($cmd == '') {
printForm();
exit();
}
$imgPk = getVar('pk');
// if it is an edit item, it should reflect the previous data
if ($cmd === 'editItem') {
$imgData = getDisplayItem($imgPk);
printForm($imgData, 'editItem');
exit();
}
// if it is an add item,
if ($cmd !== 'displayItemSubmit') {
if ($cmd !== 'addItem') {
// using bogus way to access php, we will block here
echo('<div class=\'alert alert-warning\'>Unauthorized access.</div>');
}
printForm();
exit();
}
$textValue = getVar('textValue');
// FOrmat the start date
$startDate = strtotime(getVar('startDate'));
if (!$startDate) {
echo('<div class=\'alert alert-danger\'>Unrecognized date: '.getVar('startDate').'</div>');
printForm();
exit();
}
$startDate = date('Y-m-d', $startDate);
// Format the end date
$endDate = strtotime(getVar('endDate'));
if (!$endDate) {
echo('<div class=\'alert alert-danger\'>Unrecognized date: '.getVar('endDate').'</div>');
printForm();
exit();
}
$endDate = date('Y-m-d', $endDate);
$creator = getVar('creator');
$fileName = getVar('fileName');
//$imgValue = getVar('imgValue');
$version = getVar('version'); // get version
$content = getVar('content');
// Get submit mode
$submitMode = getVar('mode');
// If the submit mode is editItem
if ($submitMode === 'editItem') {
$dataSubmit = array('textValue'=>$textValue, 'startDate'=>$startDate, 'endDate'=>$endDate, 'creator'=>$creator, 'fileName'=>$fileName, 'version'=>$version, 'content'=>$content);
$addEditItem = updateDisplayItemVersionCheck($imgPk, $dataSubmit); // Blocking the race condition
if (!$addEditItem) {
echo('<div class=\'alert alert-danger\'>Error on updateDisplayItemVersionCheck(). Invalid form data error OR version expired.</div>');
printForm($dataSubmit, 'editItem');
exit;
}
}
else {
//require_once('upload.php');
if ($_FILES['imgValue']['name'] != '') {
$imgValue = $_FILES['imgValue']['name'];
$upload = uploadFile('imgValue'); // save file into the server
if ($upload == 0) {
echo('<div class=\'alert alert-danger\'>Failed to upload the image file '.$imgValue.'<br>Make sure you upload the VALID image file.</div>');
//var_dump($_FILES['imgValue']);
exit();
}
}
$addEditItem = addDisplayItem($textValue, $startDate, $endDate, $creator, $fileName, $imgValue, $content);
if (!$addEditItem) { // failure to add the item into the database
echo('<div class=\'alert alert-danger\'>Error on addDisplayItem() => '.json_encode(array($textValue, $startDate, $endDate, $creator, $fileName, $imgValue, $content)).'</div>');
printForm();
exit();
}
}
$successcode = 0;
if ($submitMode === 'editItem') {
$successcode = 2; // edit successful
}
else {
$successcode = 1; // add successful
}
header('Location: index.php?cmd=displayItems&result='.$successcode);
?>
| true |
8a9bd75572b74640f45f0b24ed04931ccff5f80d | PHP | vanilla/garden-daemon | /src/ErrorException.php | UTF-8 | 544 | 2.796875 | 3 | [
"MIT"
] | permissive | <?php
/**
* @license MIT
* @copyright 2016 Tim Gunter
*/
namespace Garden\Daemon;
/**
* Daemon error exception
*
* @author Tim Gunter <tim@vanillaforums.com>
* @package garden-daemon
*/
class ErrorException extends \ErrorException {
protected $_context;
public function __construct($message, $errorNumber, $file, $line, $context, $backtrace = null) {
parent::__construct($message, $errorNumber, 0, $file, $line, null);
$this->_context = $context;
}
public function getContext() {
return $this->_context;
}
} | true |
66dfbc2c435ef6a0d7c157452dd1b7d7d82b5a53 | PHP | phpbenchmarks/benchmark-kit | /src/Command/Validate/Configuration/Composer/ValidateConfigurationComposerJsonCommand.php | UTF-8 | 3,369 | 2.578125 | 3 | [] | no_license | <?php
declare(strict_types=1);
namespace App\Command\Validate\Configuration\Composer;
use App\{
Command\AbstractCommand,
Command\Behavior\GetComposerConfigurationTrait,
Command\Configure\Composer\ConfigureComposerJsonCommand,
Benchmark\Benchmark
};
final class ValidateConfigurationComposerJsonCommand extends AbstractCommand
{
use GetComposerConfigurationTrait;
/** @var string */
protected static $defaultName = 'validate:configuration:composer:json';
protected function configure(): void
{
parent::configure();
$this->setDescription('Validate composer.json');
}
protected function doExecute(): int
{
$this->outputTitle('Validation of composer.json');
$composerConfiguration = $this->getComposerConfiguration();
$this
->validateName($composerConfiguration)
->validateLicense($composerConfiguration)
->validateRequireComponent($composerConfiguration);
return 0;
}
/** @param array<mixed> $composerConfiguration */
private function validateName(array $composerConfiguration): self
{
if (($composerConfiguration['name'] ?? null) !== ConfigureComposerJsonCommand::getComposerName()) {
throw new \Exception(
'Repository name must be "' . ConfigureComposerJsonCommand::getComposerName() . '".'
);
}
return $this->outputSuccess('Name ' . $composerConfiguration['name'] . ' is valid.');
}
/** @param array<mixed> $composerConfiguration */
private function validateLicense(array $composerConfiguration): self
{
if (($composerConfiguration['license'] ?? null) !== ConfigureComposerJsonCommand::LICENSE) {
throw new \Exception('License must be "' . ConfigureComposerJsonCommand::LICENSE . '".');
}
return $this->outputSuccess('License ' . $composerConfiguration['license'] . ' is valid.');
}
/** @param array<mixed> $composerConfiguration */
private function validateRequireComponent(array $composerConfiguration): self
{
if (is_null($composerConfiguration['require'][Benchmark::getCoreDependencyName()] ?? null)) {
throw new \Exception(
'It should require '
. Benchmark::getCoreDependencyName()
. '. See README.md for more informations.'
);
}
if (
$composerConfiguration['require'][Benchmark::getCoreDependencyName()]
=== Benchmark::getCoreDependencyVersion()
|| $composerConfiguration['require'][Benchmark::getCoreDependencyName()]
=== 'v' . Benchmark::getCoreDependencyVersion()
) {
$this->outputSuccess(
'Require '
. Benchmark::getCoreDependencyName()
. ':'
. $composerConfiguration['require'][Benchmark::getCoreDependencyName()]
. '.'
);
} else {
throw new \Exception(
'It should require '
. Benchmark::getCoreDependencyName()
. ':'
. Benchmark::getCoreDependencyVersion()
. '. See README.md for more informations.'
);
}
return $this;
}
}
| true |
79ddf9a716cc33a2fcdef2fd1d3541adb9880ab3 | PHP | KevinGT/edCalc | /checkContent.php | UTF-8 | 3,381 | 2.640625 | 3 | [] | no_license | <!DOCTYPE html>
<html>
<head>
<title>Elite Dangerous Market Data Entry and Profit Calculating System</title>
<meta lang="en" charset="UTF-8">
<link rel="stylesheet" type="text/css" href="style.css" />
<script></script>
</head>
<body>
<header>
<h2>Clive Rambo's Basic Elite Dangerous Market Calculation Tool</h2>
</header>
<nav id="menu">
<ul>
<li class="nav"><a href="index.php">Input</a></li>
<li class="nav"><a href="amend.php">Amend</a></li>
<li class="nav"><a href="marketData.php">Market data</a></li>
<li class="nav"><a href="profitLoss.php">Profit/Loss</a></li>
</ul>
</nav>
<?PHP
// market_input.php
//get new market details:
$station = trim($_POST['station']);
$goods = trim($_POST['good']);
$type = trim($_POST['type']);
$sell = trim($_POST['sell']);
$buy = trim($_POST['buy']);
$demandNo = trim($_POST['demandNo']);
$demandLvl = trim($_POST['demandLvl']);
$supplyNo = trim($_POST['supplyNo']);
$supplyLvl = trim($_POST['supplyLvl']);
$galacticAv = trim($_POST['galacticAv']);
echo $station;
echo $goods;
echo $type;
echo $sell;
echo $buy;
echo $demandNo;
echo $demandLvl;
echo $supplyNo;
echo $supplyLvl;
echo $galacticAv;
//connect to database and add new customer details
$dbh = mysqli_connect("localhost","root","","edmarket")
or die("Unable to select database");
//check if needing to add a new customer, or amend exiting customer
if(empty($_POST['method'])
/* || ($_POST['good']) || ($_POST['type']) || ($_POST['sell']) || ($_POST['buy']) || ($_POST['demandNo']) || $_POST['demandLvl']) || ($_POST['supplyNo']) || ($_POST['supplyLvl']) || ($_POST['galacticAv'])*/
) {
echo "<p>you have an empty cell and your information cannot be processed. Please complete all fields at this time</p>";
echo "<p><a href='index.html'>click here to return to the data entry page</a></p>";
} else {
$sql = "INSERT INTO mkt_data(Station,Goods,Type,Sell,Buy,Demand,Demand_Level,Supply,Supply_Level,Galactic_Average) VALUES (('$station'),('$goods'),('$type'),('$sell'),('$buy'),('$demandNo'),('$demandLvl'),('$supplyNo'),('$supplyLvl'),('$galacticAv'))";
}
// ************************************************************
// ***Logic section to test whether a station already exists***
// ************************************************************
$stationNameCheck = "SELECT * FROM station";
// ************************************************************
// ************************************************************
// ************************************************************
$sql1 = "INSERT INTO station VALUES ((''),('$station'))";
// insert in mkt_data
$result=mysqli_query($dbh,$sql);
$num=mysqli_affected_rows($dbh);
echo $num;
// insert into station
$result=mysqli_query($dbh,$sql1);
$num=mysqli_affected_rows($dbh);
echo $num;
$i=0;
while($i<$num){
$row = mysqli_fetch_assoc($stationNameCheck);
$stationID = $row["stationName"];
if($station == $row){
echo "<p>That station name already exists in the specific table</p>";
} else {
$sql1 = "INSERT INTO station VALUES ((''),('$station'))";
}
$i++;
};
//close database
mysqli_close($dbh);
echo "<p><a href='index.php'>click here to enter more data</a></p>";
// redirect to main menu page:
// header("Location: index.html");
?>
</body>
</html> | true |
b69654108567299b8c0e5c3cd92fe690edae6d63 | PHP | ysbaddaden/misago | /test/unit/active_record/test_errors.php | UTF-8 | 7,146 | 2.53125 | 3 | [
"MIT"
] | permissive | <?php
require_once __DIR__.'/../../unit.php';
use Misago\ActiveRecord;
class Test_ActiveRecord_Errors extends Misago\Unit\TestCase
{
function test_add()
{
$errors = new ActiveRecord\Errors();
$errors->add('id');
$this->assert_equal($errors->messages, array('id' => array(':invalid')));
$errors->add('name');
$this->assert_equal($errors->messages, array(
'id' => array(':invalid'),
'name' => array(':invalid')
));
$errors->add('name', ':blank');
$this->assert_equal($errors->messages, array(
'id' => array(':invalid'),
'name' => array(':invalid', ':blank')
));
}
function test_add_on_blank()
{
$errors = new ActiveRecord\Errors();
$errors->add_on_blank('id');
$this->assert_equal($errors->messages, array('id' => array(':blank')));
}
function test_add_on_empty()
{
$errors = new ActiveRecord\Errors();
$errors->add_on_empty('id');
$this->assert_equal($errors->messages, array('id' => array(':empty')));
}
function test_add_to_base()
{
$errors = new ActiveRecord\Errors();
$errors->add_to_base('error message');
$this->assert_equal($errors->base_messages, array('error message'));
$errors->add_to_base('another error message');
$this->assert_equal($errors->base_messages, array('error message', 'another error message'));
}
function test_count()
{
$errors = new ActiveRecord\Errors();
$this->assert_equal($errors->count(), 0);
$errors->add('id');
$this->assert_equal($errors->count(), 1);
$errors->add('name');
$this->assert_equal($errors->count(), 2);
$errors->add_on_blank('id');
$this->assert_equal($errors->count(), 3, 'second error on a single field, thus 3 errors');
$errors->add_on_blank('id');
$this->assert_equal($errors->count(), 4, 'third error on a field');
$errors->add_to_base('there was an error');
$this->assert_equal($errors->count(), 5, 'error added on base');
}
function test_clear()
{
$errors = new ActiveRecord\Errors();
$this->assert_equal($errors->count(), 0);
$errors->add('id');
$errors->add_to_base('there was an error');
$this->assert_equal($errors->count(), 2);
$errors->clear();
$this->assert_equal($errors->count(), 0);
}
function test_is_empty()
{
$errors = new ActiveRecord\Errors();
$this->assert_true($errors->is_empty());
$errors->add('id');
$errors->add_to_base('there was an error');
$this->assert_false($errors->is_empty());
$errors->clear();
$this->assert_true($errors->is_empty());
$errors->clear();
$errors->add_to_base('there was an error');
$this->assert_false($errors->is_empty());
}
function test_is_invalid()
{
$errors = new ActiveRecord\Errors();
$this->assert_false($errors->is_invalid('title'));
$errors->add('title');
$this->assert_true($errors->is_invalid('title'));
$errors->clear();
$this->assert_false($errors->is_invalid('title'));
}
function test_on()
{
$errors = new ActiveRecord\Errors();
$this->assert_type($errors->on('title'), 'NULL');
$errors->add('title');
$this->assert_equal($errors->on('title'), 'Title is invalid');
$errors->add('title', 'error msg');
$this->assert_equal($errors->on('title'), array('Title is invalid', 'error msg'));
$errors->clear();
$this->assert_null($errors->on('title'));
}
function test_on_base()
{
$errors = new ActiveRecord\Errors();
$this->assert_type($errors->on_base(), 'NULL');
$errors->add_to_base('error msg');
$this->assert_equal($errors->on_base(), 'error msg');
$errors->add_to_base('another error msg');
$this->assert_equal($errors->on_base(), array('error msg', 'another error msg'));
$errors->clear();
$this->assert_null($errors->on_base());
}
function test_full_messages()
{
$errors = new ActiveRecord\Errors();
$this->assert_equal($errors->full_messages(), array());
$errors->add_to_base('generic error msg');
$this->assert_equal($errors->full_messages(), array('generic error msg'));
$errors->add('title', 'title is invalid');
$this->assert_equal($errors->full_messages(), array('generic error msg', 'title is invalid'));
$errors->add('title', 'title is blank');
$this->assert_equal($errors->full_messages(), array('generic error msg', 'title is invalid', 'title is blank'));
$errors->clear();
$this->assert_equal($errors->full_messages(), array());
}
function test_translated_error_messages()
{
$errors = new ActiveRecord\Errors(new Monitoring());
$errors->add('title2', ':required');
$this->assert_equal($errors->on('title2'), 'please fill this', 'attribute as its own translation');
$errors->add('title3', ':required');
$this->assert_equal($errors->on('title3'), 'Title3 in monitoring cannot be blank', 'model has its own translation');
}
function test_translated_full_messages()
{
$errors = new ActiveRecord\Errors(new Monitoring());
$errors->add('title2', ':required');
$errors->add('title3', ':required');
$test = $errors->full_messages();
$this->assert_equal($test, array('please fill this', 'Title3 in monitoring cannot be blank'));
}
function test_translated_error_messages_with_interpolation()
{
$error = new Error();
$error = $error->create(array(
'title' => 'my title',
'subtitle' => 'my sub-title',
));
$errors = new ActiveRecord\Errors($error);
$errors->add('title', ':taken');
$this->assert_equal($errors->on('title'), "Title 'my title' is already taken");
$errors->add('subtitle', ':taken');
$this->assert_equal($errors->on('subtitle'), "Subtitle 'my sub-title' is already taken");
$errors->add('domain', ':reserved');
$this->assert_equal($errors->on('domain'), "Already reserved in Error");
}
function test_to_xml()
{
$error = new Error();
$error = $error->create(array(
'title' => 'my title',
'domain' => '',
));
$errors = new ActiveRecord\Errors($error);
$errors->add_to_base('Error on record');
$errors->add('title', ':taken');
$errors->add('domain', ':reserved');
$this->assert_equal($errors->to_xml(), '<?xml version="1.0" encoding="UTF-8"?>'.
'<errors>'.
"<error>Error on record</error>".
"<error>Title 'my title' is already taken</error>".
'<error>Already reserved in Error</error>'.
'</errors>'
);
}
function test_to_json()
{
$error = new Error();
$error = $error->create(array(
'title' => 'my title',
'domain' => '',
));
$errors = new ActiveRecord\Errors($error);
$errors->add_to_base('Error on record');
$errors->add('title', ':taken');
$errors->add('domain', ':reserved');
$this->assert_equal($errors->to_json(),
'["Error on record","Title \'my title\' is already taken","Already reserved in Error"]');
}
}
?>
| true |
9c8a48c54741b8997e4cc57d817cfadf2b6bf4db | PHP | RafaelSSilveira/Event-Sourcing | /src/Controllers/Entry/NewEntry.php | UTF-8 | 1,132 | 2.8125 | 3 | [] | no_license | <?php namespace Controllers;
require_once './src/Events/Event.php';
require_once './src/Controllers/AbstractSubject.php';
use Events\Event;
class NewEntry extends AbstractSubject
{
private $observers = array();
public function __construct()
{
}
public function attach(Event $observer_in)
{
$this->observers[] = $observer_in;
}
public function detach(Event $observer_in)
{
foreach ($this->observers as $okey => $oval) {
if ($oval == $observer_in) {
unset($this->observers[$okey]);
}
}
}
public function notify($data)
{
foreach ($this->observers as $obs) {
$obs->newEvent($data);
}
}
public function newEntry($params, $id)
{
$id_entry = $id === null ? time() : $id;
$data = [
'id_entry' => $id_entry,
'value' => $params->value ? $params->value : 0,
'date' => date("Y-m-d H:i:s"),
'status' => $params->status ? $params->status : false
];
$this->notify($data);
return $id_entry;
}
}
| true |
bcb1e73774883a69e20eec0e1b4cdb4ff45c6495 | PHP | ivankuzma911/yii2 | /models/RegistrationForm.php | UTF-8 | 1,111 | 2.78125 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
namespace app\models;
use yii\base\Model;
use Yii;
/**
* LoginForm is the model behind the login form.
*/
class RegistrationForm extends Model
{
public $username;
public $password;
private $_user = false;
public function rules()
{
return [
[['username', 'password'],'filter', 'filter' => 'trim'],
[['username', 'password'],'required'],
['username', 'string', 'min' => 2, 'max' => 255],
['password', 'string', 'min' => 6, 'max' => 255],
['username', 'unique',
'targetClass' => User::className(),
'message' => 'This username is already taken'],
];
}
public function attributeLabels()
{
return [
'username' => 'Username',
'password' => 'Password'
];
}
public function reg()
{
$user = new User();
$user->username = $this->username;
$user->setPassword($this->password);
return $user->save() ? $user : null;
}
}
| true |
25bdc395dd5051cc38b47897f8093e87ad3268d1 | PHP | weslyFei2018/learning_php | /day02/mysql.php | UTF-8 | 617 | 2.921875 | 3 | [] | no_license | <?php
try{
//解析config.ini文件
$config = parse_ini_file(realpath(dirname(__FILE__) . '/config.ini'));
//对mysqli类进行实例化
$mysqli = new mysqli($config['host'], $config['username'], $config['password'], $config['dbname']);
if(mysqli_connect_errno()){ //判断是否成功连接上MySQL数据库
throw new Exception('数据库连接错误!'); //如果连接错误,则抛出异常
}else{
echo '数据库连接成功!'; //打印连接成功的提示
}
}catch (Exception $e){ //捕获异常
echo $e->getMessage(); //打印异常信息
}
| true |
67f2d98c0291b833d465ee8b1448585e829d4b47 | PHP | getpoirot/Module-Content | /src/Content/Interfaces/Model/Repo/iRepoComments.php | UTF-8 | 1,143 | 2.75 | 3 | [
"MIT"
] | permissive | <?php
namespace Module\Content\Interfaces\Model\Repo;
use Module\Content\Interfaces\Model\Entity\iEntityComment;
interface iRepoComments
{
/**
* Insert Comment Entity
*
* @param iEntityComment $entity
*
* @return iEntityComment Include persistence insert identifier
*/
function insert(iEntityComment $entity);
/**
* Save Entity By Insert Or Update
*
* @param iEntityComment $entity
*
* @return mixed
*/
function save(iEntityComment $entity);
/**
* Remove a Comment Entity
*
* @param iEntityComment $entity
*
* @return int
*/
function remove(iEntityComment $entity);
/**
* Find Match By Given UID
*
* @param string|mixed $uid
*
* @return iEntityComment|false
*/
function findOneMatchUid($uid);
/**
* Find Entities Match With Given Expression
*
* @param array $expression Filter expression
* @param int|null $offset
* @param int|null $limit
*
* @return \Traversable
*/
function findAll($expression, $offset = null, $limit = null);
}
| true |
55d2f893933837683c7a129aa2ebc9a089b15ca8 | PHP | Lankron/La_Biolangerie | /application/controllers/signup/SignupController.class.php | UTF-8 | 1,404 | 3.09375 | 3 | [] | no_license | <?php
class SignupController
{
public function httpGetMethod(Http $http, array $queryFields)
{
session_start();
// j'appelle ma fonction ou j'ai mis toute mes catégories
/*
* Méthode appelée en cas de requête HTTP GET
*
* L'argument $http est un objet permettant de faire des redirections etc.
* L'argument $queryFields contient l'équivalent de $_GET en PHP natif.
*/
}
public function httpPostMethod(Http $http, array $formFields)
{
$Signup = new LoginModel();
$login = $formFields["user"];
$password = $formFields["password"];
$email = $formFields["email"];
$lastname = $formFields["lastname"];
$firstname = $formFields["firstname"];
$userVerify = $Signup->VerifyUserOnRegister($login);
if($userVerify) {
$http->sendJsonResponse($userVerify);
}
else{
$Signup->Register($firstname,$lastname,$login,$password,$email);
$http->sendJsonResponse("Success");
}
/*
* Méthode appelée en cas de requête HTTP POST
*
* L'argument $http est un objet permettant de faire des redirections etc.
* L'argument $formFields contient l'équivalent de $_POST en PHP natif.
*/
}
} | true |
7b23a9871f11b12842aa19249019988e57163606 | PHP | RazaChohan/Experimentation-Repo | /Ready2Serve/code/controllers/OrderController.php | UTF-8 | 1,363 | 2.984375 | 3 | [] | no_license | <?php
/**
* Contains definition of Order Controller class namely OrderController
*
* This file contains one class implementation
* named Order Controller class.
*
* @category Training/Learning PHP
* @package Ready2Serve
* @version v 1.0
*/
/**
* Contains Order Controller class
*
* This Class gets a specific request from the Dispatcher class
* and performs functions according to the request.
*
* @package Ready2Serve
* @author Muhammad Raza <muhammad.raza@coeus-solutions.de>
* @category Training/Learning PHP
* @version v 1.0
*/
class OrderController
{
/**
* @var view 'View class object'
*/
public $view;
/**
* @var object 'Object of Order Model Class'
*/
private $orderModel;
/**
*
* Constructor of class
*/
public function __construct()
{
$this->view=new View();
$this->orderModel=new orderModel();
}
/**
*
* Gets the values from respective model class and passes the view class by
* calling its specific function and passing data.
*
* @access public
*/
public function updateView()
{
}
/**
*
* gets the order line items using order Model Class
*
* @access public
*
* @param integer $orderID 'ID of order'
*/
public function getOrderLineItems($orderID)
{
}
}
| true |
81e388c545c43cd23ec8550f94be66b02e6a50af | PHP | madchops1/meetup-facebook-sync | /facebook-redirect.php | UTF-8 | 13,479 | 2.640625 | 3 | [] | no_license | <?php
session_start();
include 'config.php';
//die($_REQUEST['code']);
// -- Step 2, Get access token from user
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/oauth/access_token?'.
'client_id=588715921194851'.
'&redirect_uri=http://mfbsync.karlsteltenpohl.com/facebook-redirect.php'.
'&client_secret=5509ae4d80411edb07787535d55e144f'.
'&code='.$_REQUEST['code']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//execute the request
$return = curl_exec($ch);
curl_close($ch);
if(strstr($return, "access_token")){
$returnArray = explode("&",$return);
$tokenArray = explode("=",$returnArray[0]);
$access_token = $tokenArray[1];
// -- Exchange for a long-lived token
/*
GET /oauth/access_token?
grant_type=fb_exchange_token&
client_id={app-id}&
client_secret={app-secret}&
fb_exchange_token={short-lived-token}*/
// -- Step 2, Get access token from user
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/oauth/access_token?'.
'grant_type=fb_exchange_token'.
'&client_id='.$fb_app_id.''.
'&client_secret='.$fb_app_secret.''.
'&fb_exchange_token='.$access_token);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//execute the request
$return = curl_exec($ch);
curl_close($ch);
//echo "Long-Term Token:<br>";
//var_dump($return);
//die();
// -- If there is a long-term token, we need that long term token ;)
if(strstr($return, "access_token")){
$returnArray = explode("&",$return);
$tokenArray = explode("=",$returnArray[0]);
$access_token = $tokenArray[1];
// -- Successfully retreived and exchanged access tokens from Meetup and Facebook at this point
// so we are going to save it to the database.
// -- Check User
$user_select = " SELECT * FROM users WHERE email='".$_SESSION['user_email']."' LIMIT 1";
if($user_result = mysql_fetch_object(mysql_query($user_select))){
$_SESSION['user_object'] = $user_result;
}
// -- Insert User
else {
$query = " INSERT INTO users SET email='".$_SESSION['user_email']."'";
mysql_query($query);
//$uid = mydql_insert_id;
$user_select = " SELECT * FROM users WHERE email='".$_SESSION['user_email']."' LIMIT 1";
$user_result = mysql_fetch_object(mysql_query($user_select));
$_SESSION['user_object'] = $user_result;
}
// -- The Page Relationships are per user.
// -- Loop Through this users relationships and see if this one already exists for this user
$rel_exists = 0;
$rel_select = " SELECT * FROM fb_meetup_rel WHERE uid='".$_SESSION['user_object']->id."'";
$rel_result = mysql_query($rel_select);
while($rel = mysql_fetch_object($rel_result)){
// -- Check the meetup and facebook pages
$fselect = " SELECT * FROM fb_pages WHERE id='".$rel->fid."' LIMIT 1";
$fobj = mysql_fetch_object(mysql_query($fselect));
$mselect = " SELECT * FROM meetup_pages WHERE id='".$rel->mid."' LIMIT 1";
$mobj = mysql_fetch_object(mysql_query($mselect));
// -- If Meetup and facegook pages exist
if($mobj->name == $_SESSION['meetup_name'] && $fobj->name == $_SESSION['fb_page_id']){
$rel_exists = 1;
// -- Update Meetup
$update = " UPDATE meetup_pages
SET
access_token='".$_SESSION['meetup_token']."',
refresh_token='".$_SESSION['refresh_token']."'
WHERE id='".$mobj->id."'";
mysql_query($update);
// -- Update Facebook
$update = " UPDATE facebook_pages
SET
access_token='".$access_token."'
WHERE id='".$fobj->id."'";
}
}
// If the relationship doesn't exist then insert it into the database
if($rel_exists == 0){
// -- Insert FB Page
$query = " INSERT INTO `fb_pages`
SET
`name`='".$_SESSION['fb_page_id']."',
`access_token`='".$access_token."'";
mysql_query($query);
$fid = mysql_insert_id();
// -- Insert MU page
$query = " INSERT INTO meetup_pages
SET
name='".$_SESSION['meetup_name']."',
access_token='".$_SESSION['meetup_token']."',
refresh_token='".$_SESSION['refresh_token']."'";
mysql_query($query);
$mid = mysql_insert_id();
// -- Connect With the Relational Table
$query = " INSERT INTO fb_meetup_rel
SET
fid='".$fid."',
mid='".$mid."',
uid='".$_SESSION['user_object']->id."'";
mysql_query($query);
}
// -- Get Facebook Page Events
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/'.$_SESSION['fb_page_id'].'/events?access_token='.$access_token.'');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$return = curl_exec($ch);
curl_close($ch);
$return = json_decode($return);
//echo "<pre>";
//var_dump($return);
//echo "</pre>";
//die();
// -- Loop the fb event results and put into array
if(isset($return->data)){
foreach($return->data as $result){
// -- Get the Event Details
$ch = curl_init();
//Set the URL to work with
curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/'.$result->id.'?access_token='.$access_token.'');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$detailed_return = curl_exec($ch);
curl_close($ch);
$detailed_return = json_decode($detailed_return);
// -- Make sure event is not in the past
$_SESSION['fb_events'][] = $detailed_return;
}
}
// -- Success, format events
// ...format facebooks
$i=0;
foreach($_SESSION['fb_events'] AS $facebook_event){
// -- Start Time Processing
// If there is a time in the facebook time
if(strstr($facebook_event->start_time,"T")){
$date_time_array = explode("T",$facebook_event->start_time);
$date = $date_time_array[0];
$time = $date_time_array[1];
$his = substr($time, 0,8);
$zone = substr($time, -5);
$formatdate = date("m/d/Y", strtotime($date));
$new_time = round(strtotime( $formatdate . " " . $his . " " . $zone . "") * 1000);
}
// -- else Just date Y-m-d...
else {
$time = $facebook_event->start_time;
$new_time = round(strtotime($facebook_event->start_time) * 1000);
}
//echo "Time: ".$time." ".strtotime($time)."<br>";
// -- Make sure the date is not earlier than now...
echo "<br>".$facebook_event->name."<br>";
echo strtotime($time)." - ".strtotime("now");
if(strtotime($time) > strtotime("now")){
$_SESSION['formatted_fb_events'][$i]->title = $facebook_event->name;
$_SESSION['formatted_fb_events'][$i]->start = $new_time;
$_SESSION['formatted_fb_events'][$i]->location = $facebook_event->location;
$_SESSION['formatted_fb_events'][$i]->description = '';
$i++;
}
}
// -- Format Meetups
$i=0;
foreach($_SESSION['meetups'] as $meetup_event){
$_SESSION['formatted_meetups'][$i]->title = $meetup_event->name;
// -- Process Time
$meetup_event->time = date("Y-m-dXXXXh:i:s",($meetup_event->time/1000))."-0000";
$meetup_event->time = str_replace("XXXX","T",$meetup_event->time);
$_SESSION['formatted_meetups'][$i]->start = $meetup_event->time;
$_SESSION['formatted_meetups'][$i]->location = $meetup_event->venue->name;
$_SESSION['formatted_meetups'][$i]->description = '';
$i++;
}
echo "<br><br>MEETUPS<br><pre>";
var_dump($_SESSION['formatted_meetups']);
echo "</pre>";
echo "<br><br>FACEBOOKS<br><pre>";
var_dump($_SESSION['formatted_fb_events']);
echo "</pre>";
// -- SYNC here...
// ... Start with facebook...
$synced_facebook_events=0;
// -- Loop the Facebook events and add them to meetup if necessary
foreach($_SESSION['formatted_fb_events'] as $facebook_event){
// -- Loop throuhg each meetup event
$fb_event_synced = 0;
foreach($_SESSION['formatted_meetups'] as $meetup_event){
//echo $meetup_event->title." == ".$facebook_event->title."<br>";
if($meetup_event->title == $facebook_event->title){
$fb_event_synced = 1;
break;
}
}
// -- If the fb event doesn't exist in meetup
if($fb_event_synced == 0){
$synced_facebook_events++;
// -- Venue Processing
// Get the Meetup Group's Venues...
//init curl
$ch = curl_init();
//Set the URL to work with
curl_setopt($ch, CURLOPT_URL, 'https://api.meetup.com/2/venues?group_id='.$_SESSION['meetup_group_object']->id.'&access_token='.$meetup_response->access_token.'');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$return = curl_exec($ch);
curl_close($ch);
$return = json_decode($return);
// -- Loop the venue results to check for a match
$location_found = 0;
$venue = '';
if(isset($return->results)){
foreach($return->results as $result){
if($result->name == $facebook_event->location){
$location_found = 1;
$venue_id = $result->id;
$venue='&venue_id='.$venue_id.'';
}
}
}
// -- POST FB EVENT to Meetup
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.meetup.com/2/event');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'group_id='.$_SESSION['meetup_group_object']->id.''.
'&group_urlname='.$_SESSION['meetup_name'].''.
'&name='.urlencode($facebook_event->title) .
'&time='.$facebook_event->start.''.
$venue.
'&access_token='.$_SESSION['meetup_token']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$return = curl_exec($ch);
curl_close($ch);
//echo "Post FB to Meetup Response:<br>";
//var_dump($return);echo "<br>";
//$output .= $facebook_event->title . " (".$facebook_event->start.") => Meetup";
/*$output .= '<br>group_id='.$_SESSION['meetup_group_object']->id.''.
'&group_urlname='.$_SESSION['meetup_name'].''.
'&name='.urlencode($facebook_event->title) .
'&time='.$facebook_event->start.''.
$venue.
'&access_token='.$_SESSION['meetup_token'].'<br>';*/
}
}
// --Loop the Meetup events and add them to Facebook if necessary
$synced_meetup_events=0;
foreach($_SESSION['formatted_meetups'] as $meetup_event){
// -- Loop through each facebook event
$mu_event_synced = 0;
foreach($_SESSION['formatted_fb_events'] as $facebook_event){
if($facebook_event->title == $meetup_event->title){
$mu_event_synced = 1;
break;
}
}
if($mu_event_synced == 0){
$synced_meetup_events++;
// -- Post Meetup to Facebook Page as Event...
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/'.$_SESSION['fb_page_id'].'/events');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'name='.$meetup_event->title.
'&start_time='.$meetup_event->start.''.
'&description='.$meetup_event->description.''.
'&location='.$meetup_event->location.''.
'&access_token='.$access_token);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$return = curl_exec($ch);
curl_close($ch);
}
}
include 'includes/header.php';
// -- Debriefing
echo "<div class='wrapper-content content'>";
echo "<br><Br>SUCCESS!<br>";
echo $synced_facebook_events . " facebook events synced to meetup.<br>";
echo $synced_meetup_events . " meetup events synced to facebook.<br>";
//echo $output;
echo "</div>";
include 'includes/footer.php';
}
// Could not exchange long-term token
else {
$facebook_response = json_decode($return);
// If Error
if(isset($facebook_response->error)){
die("<br>**FACEBOOK ERROR**<br>");
}
}
}
// Could not get short-term token
else {
$facebook_response = json_decode($return);
// If Error
if(isset($facebook_response->error)){
die("<br>**FACEBOOK ERROR**<br>");
}
}
?> | true |
b8c36921140e0da0a4b27e59cec6c1d005738767 | PHP | MenonVishnu/phpmysqlworkshopiitb | /Assignment-3/q1.php | UTF-8 | 1,278 | 2.90625 | 3 | [] | no_license | <?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "result";
//connecting to database:
$conn = mysqli_connect($servername, $username, $password,$database);
if (!$conn){
mysqli_connect_error();
}else{
echo "Connected To Database!";
}
?>
<form action="q1.php" method="post">
Name: <input type="text" name="name">
<br>Marks in Each Subject<br>
Subject 1: <input type="number" name="s1"><br>
Subject 2: <input type="number" name="s2"><br>
Subject 3: <input type="number" name="s3"><br>
Subject 4: <input type="number" name="s4"><br>
Subject 5: <input type="number" name="s5"><br>
<input type="submit" name="submit" value="Post Data">
</form>
<?php
@$name = $_POST['name'];
@$s1 = $_POST['s1'];
@$s2 = $_POST['s2'];
@$s3 = $_POST['s3'];
@$s4 = $_POST['s4'];
@$s5 = $_POST['s5'];
@$total = $s1 + $s2 + $s3 + $s4 + $s5;
$full = 500;
$percentage = ($total/$full)*100;
if($name && $s1 && $s2 && $s3 && $s4 && $s5)
{
$sql = "INSERT INTO class1 VALUES ('','$name',$s1,$s2,$s3,$s4,$s5,$total,$full,$percentage)";
if (mysqli_query($conn, $sql))
{
echo "Successfully Updated Database";
}
else{
echo "Unable to Update, ERROR!!!";
}
}
mysqli_close($conn);
?>
| true |
03c0ab0e52aad95ac820d619c0a8c0481bc96527 | PHP | lhorente/php-messaging-test | /publisher.php | UTF-8 | 1,327 | 2.625 | 3 | [] | no_license | <?php
include(__DIR__ . '/config.php');
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Exchange\AMQPExchangeType;
use PhpAmqpLib\Message\AMQPMessage;
$exchange = 'router';
$queue = 'msgs_queue';
$connection = new AMQPStreamConnection(HOST, PORT, USER, PASS, VHOST);
$channel = $connection->channel();
/*
Definir a fila em que as mensagens serão publicadas.
*/
$channel->queue_declare($queue, false, true, false, false);
$channel->exchange_declare($exchange, AMQPExchangeType::DIRECT, false, true, false);
// Adiciona fila ao canal da conexão atual
$channel->queue_bind($queue, $exchange);
/*
Gera um loop para enviar mensagens a cada 5 segundos.
Solução provivória com finalidade teste do funcionamento.
*/
while (true){
$microservice_id = bin2hex(openssl_random_pseudo_bytes(16));
$random_request_id = bin2hex(openssl_random_pseudo_bytes(16));
$messageBody = "Hello World";
$msgObj = [
'microservice_id' => $microservice_id,
'message' => $messageBody,
'timestamp' => time(),
'random_request_id' => $random_request_id
];
$message = new AMQPMessage(json_encode($msgObj), array('content_type' => 'application/json', 'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT));
$channel->basic_publish($message, $exchange);
sleep(5);
}
$channel->close();
$connection->close();
| true |
0be5a7f8f514dabed6b09f182e68846751148fa3 | PHP | Fahrenheit451Tecnologia/tmjsonapibundle | /Model/UuidInterface.php | UTF-8 | 333 | 2.875 | 3 | [] | no_license | <?php declare(strict_types=1);
namespace TM\JsonApiBundle\Model;
interface UuidInterface
{
/**
* @param string $uuid
* @return bool
*/
public static function isValid(string $uuid);
/**
* @param string $uuid
* @return UuidInterface
*/
public static function fromString(string $uuid);
} | true |
19445c2076c7aed73b74c9c2f34ffda534b3e69e | PHP | webeweb/core-library | /src/quadratus/Model/Proprete/DevisDescriptifLocaux.php | UTF-8 | 6,047 | 2.71875 | 3 | [
"MIT"
] | permissive | <?php
/*
* This file is part of the core-library package.
*
* (c) 2018 WEBEWEB
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace WBW\Library\Quadratus\Model\Proprete;
/**
* Devis descriptif locaux.
*
* @author webeweb <https://github.com/webeweb>
* @package WBW\Library\Quadratus\Model\Proprete
*/
class DevisDescriptifLocaux {
/**
* Code affaire.
*
* @var string|null
*/
private $codeAffaire;
/**
* Code chantier.
*
* @var string|null
*/
private $codeChantier;
/**
* Code client.
*
* @var string|null
*/
private $codeClient;
/**
* Libelle.
*
* @var string|null
*/
private $libelle;
/**
* Niveau noeud.
*
* @var int|null
*/
private $niveauNoeud;
/**
* Noeud local.
*
* @var bool|null
*/
private $noeudLocal;
/**
* Num devis.
*
* @var string|null
*/
private $numDevis;
/**
* Numero noeud.
*
* @var int|null
*/
private $numeroNoeud;
/**
* Uniq id noeud.
*
* @var string|null
*/
private $uniqIdNoeud;
/**
* Constructor.
*/
public function __construct() {
// NOTHING TO DO
}
/**
* Get the code affaire.
*
* @return string|null Returns the code affaire.
*/
public function getCodeAffaire(): ?string {
return $this->codeAffaire;
}
/**
* Get the code chantier.
*
* @return string|null Returns the code chantier.
*/
public function getCodeChantier(): ?string {
return $this->codeChantier;
}
/**
* Get the code client.
*
* @return string|null Returns the code client.
*/
public function getCodeClient(): ?string {
return $this->codeClient;
}
/**
* Get the libelle.
*
* @return string|null Returns the libelle.
*/
public function getLibelle(): ?string {
return $this->libelle;
}
/**
* Get the niveau noeud.
*
* @return int|null Returns the niveau noeud.
*/
public function getNiveauNoeud(): ?int {
return $this->niveauNoeud;
}
/**
* Get the noeud local.
*
* @return bool|null Returns the noeud local.
*/
public function getNoeudLocal(): ?bool {
return $this->noeudLocal;
}
/**
* Get the num devis.
*
* @return string|null Returns the num devis.
*/
public function getNumDevis(): ?string {
return $this->numDevis;
}
/**
* Get the numero noeud.
*
* @return int|null Returns the numero noeud.
*/
public function getNumeroNoeud(): ?int {
return $this->numeroNoeud;
}
/**
* Get the uniq id noeud.
*
* @return string|null Returns the uniq id noeud.
*/
public function getUniqIdNoeud(): ?string {
return $this->uniqIdNoeud;
}
/**
* Set the code affaire.
*
* @param string|null $codeAffaire The code affaire.
* @return DevisDescriptifLocaux Returns this Devis descriptif locaux.
*/
public function setCodeAffaire(?string $codeAffaire): DevisDescriptifLocaux {
$this->codeAffaire = $codeAffaire;
return $this;
}
/**
* Set the code chantier.
*
* @param string|null $codeChantier The code chantier.
* @return DevisDescriptifLocaux Returns this Devis descriptif locaux.
*/
public function setCodeChantier(?string $codeChantier): DevisDescriptifLocaux {
$this->codeChantier = $codeChantier;
return $this;
}
/**
* Set the code client.
*
* @param string|null $codeClient The code client.
* @return DevisDescriptifLocaux Returns this Devis descriptif locaux.
*/
public function setCodeClient(?string $codeClient): DevisDescriptifLocaux {
$this->codeClient = $codeClient;
return $this;
}
/**
* Set the libelle.
*
* @param string|null $libelle The libelle.
* @return DevisDescriptifLocaux Returns this Devis descriptif locaux.
*/
public function setLibelle(?string $libelle): DevisDescriptifLocaux {
$this->libelle = $libelle;
return $this;
}
/**
* Set the niveau noeud.
*
* @param int|null $niveauNoeud The niveau noeud.
* @return DevisDescriptifLocaux Returns this Devis descriptif locaux.
*/
public function setNiveauNoeud(?int $niveauNoeud): DevisDescriptifLocaux {
$this->niveauNoeud = $niveauNoeud;
return $this;
}
/**
* Set the noeud local.
*
* @param bool|null $noeudLocal The noeud local.
* @return DevisDescriptifLocaux Returns this Devis descriptif locaux.
*/
public function setNoeudLocal(?bool $noeudLocal): DevisDescriptifLocaux {
$this->noeudLocal = $noeudLocal;
return $this;
}
/**
* Set the num devis.
*
* @param string|null $numDevis The num devis.
* @return DevisDescriptifLocaux Returns this Devis descriptif locaux.
*/
public function setNumDevis(?string $numDevis): DevisDescriptifLocaux {
$this->numDevis = $numDevis;
return $this;
}
/**
* Set the numero noeud.
*
* @param int|null $numeroNoeud The numero noeud.
* @return DevisDescriptifLocaux Returns this Devis descriptif locaux.
*/
public function setNumeroNoeud(?int $numeroNoeud): DevisDescriptifLocaux {
$this->numeroNoeud = $numeroNoeud;
return $this;
}
/**
* Set the uniq id noeud.
*
* @param string|null $uniqIdNoeud The uniq id noeud.
* @return DevisDescriptifLocaux Returns this Devis descriptif locaux.
*/
public function setUniqIdNoeud(?string $uniqIdNoeud): DevisDescriptifLocaux {
$this->uniqIdNoeud = $uniqIdNoeud;
return $this;
}
}
| true |
fd710aa7354d702db567eb6743e8196e97d0aca4 | PHP | proger150/RealForceTest | /tests/Calculator/SalaryCalculatorTest.php | UTF-8 | 1,647 | 2.578125 | 3 | [] | no_license | <?php
namespace App\Tests\Calculator;
use App\Calculator\DeductionsCalculator;
use App\Calculator\ExtraChargeCalculator;
use App\Calculator\SalaryCalculator;
use App\Calculator\TaxesCalculator;
use App\Tests\BaseTestCase;
class SalaryCalculatorTest extends BaseTestCase
{
public function testForAlice()
{
$salary = (new SalaryCalculator($this->aliceEmployee))
->setChargesPercent((new ExtraChargeCalculator($this->aliceEmployee))->calculate())
->setTaxesPercent((new TaxesCalculator($this->aliceEmployee))->calculate())
->setDeductions((new DeductionsCalculator($this->aliceEmployee))->calculate())
->calculate();
$this->assertEquals(4800, $salary);
}
public function testForBob()
{
$salary = (new SalaryCalculator($this->bobEmployee))
->setChargesPercent((new ExtraChargeCalculator($this->bobEmployee))->calculate())
->setTaxesPercent((new TaxesCalculator($this->bobEmployee))->calculate())
->setDeductions((new DeductionsCalculator($this->bobEmployee))->calculate())
->calculate();
$this->assertEquals(2924, $salary);
}
public function testForCharlie()
{
$salary = (new SalaryCalculator($this->charlieEmployee))
->setChargesPercent((new ExtraChargeCalculator($this->charlieEmployee))->calculate())
->setTaxesPercent((new TaxesCalculator($this->charlieEmployee))->calculate())
->setDeductions((new DeductionsCalculator($this->charlieEmployee))->calculate())
->calculate();
$this->assertEquals(3600, $salary);
}
} | true |
0146ba1467852f6d229ae32adfe0ad938b2ea669 | PHP | QuantiCZ/MailQ-PHP-Library | /src/MailQ/MailQ.php | UTF-8 | 1,286 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
namespace MailQ;
use MailQ\Resources\CampaignResource;
use MailQ\Resources\CompanyResource;
use MailQ\Resources\LogMessageResource;
use MailQ\Resources\NewsletterResource;
use MailQ\Resources\NotificationResource;
use MailQ\Resources\RecipientListResource;
use MailQ\Resources\SenderEmailResource;
use MailQ\Resources\SmsNotificationResource;
use MailQ\Resources\UnsubscriberResource;
use MailQ\Resources\UserResource;
class MailQ
{
use CompanyResource,
CampaignResource,
LogMessageResource,
NewsletterResource,
NotificationResource,
RecipientListResource,
SenderEmailResource,
SmsNotificationResource,
UnsubscriberResource,
UserResource;
/**
* @var Connector
*/
private $connector;
private $companyId;
public function __construct(Connector $connector, $companyId)
{
$this->connector = $connector;
$this->companyId = $companyId;
}
public function setCompanyId($companyId)
{
$this->companyId = $companyId;
}
/**
*
* @return Connector
*/
protected function getConnector()
{
return $this->connector;
}
protected function getCompanyId()
{
return $this->companyId;
}
}
| true |
193525bfcea236c8b1980af63e50761125410a54 | PHP | sendz/jelajah | /application/models/Getfrontpage.php | UTF-8 | 1,399 | 2.640625 | 3 | [] | no_license | <?php
/**
* Model for frontpage
*/
class Getfrontpage extends CI_Model
{
/* Declaration of Variables */
public $id;
public $title;
public $content;
public $section;
public $date;
public $author;
public $custom;
public $show;
public function __construct()
{
/* CI Model constructor */
parent::__construct();
}
public function getEntries()
{
$query = $this->db->get_where('frontpage',array('show'=>'published'),'','');
return $query->result();
}
public function insertEntry()
{
$this->title = $_POST['title'];
$this->content = $_POST['content'];
$this->section = $_POST['section'];
$this->date = date() . time();
$this->author = $_POST['author'];
$this->custom = $_POST['custom'];
$this->show = $_POST['show'];
$this->db->insert('frontpage',$this);
}
public function updateEntry()
{
$this->title = $_POST['title'];
$this->content = $_POST['content'];
$this->section = $_POST['section'];
$this->date = date() . time();
$this->author = $_POST['author'];
$this->custom = $_POST['custom'];
$this->show = $_POST['show'];
$this->db->update('frontpage',$this,array('section'=>$_POST['section']));
}
public function getEntry($section)
{
$newsection = $section;
$query = $this->db->get_where('frontpage',array('section'=>$section));
return $query->result();
}
}
?> | true |
d5fd07c93257c8ed22e0904d18713bb945031c30 | PHP | SelrahcD/fizzbuzz | /src/DivisibleSayer.php | UTF-8 | 524 | 3.5 | 4 | [] | no_license | <?php
namespace SelrahcD\FizzBuzz;
final class DivisibleSayer implements Sayer
{
private $toSay;
private $divisor;
/**
* DivisibleSayer constructor.
* @param $divisor
* @param $toSay
*/
public function __construct($divisor, $toSay)
{
$this->divisor = $divisor;
$this->toSay = $toSay;
}
public function canHandle($value)
{
return $value % $this->divisor === 0;
}
public function say($value)
{
return $this->toSay;
}
} | true |
9d6abeff3988199dd694f3dadb5e380f74388253 | PHP | Pod-Point/reviews-php | /src/Providers/ReviewsIo/Request/Merchant/GetMerchantReviews.php | UTF-8 | 1,058 | 2.640625 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | <?php
namespace PodPoint\Reviews\Providers\ReviewsIo\Request\Merchant;
use GuzzleHttp\Psr7\Request;
use PodPoint\Reviews\Request\BaseRequestWrapper;
/**
* Class GetMerchantReviews.
*/
class GetMerchantReviews extends BaseRequestWrapper
{
/**
* List of required fields.
*
* @return array
*/
public function requiredFields(): array
{
return ['store'];
}
/**
* Builds the request.
*
* @return Request
*/
public function getRequest(): Request
{
$store = $this->getOption('store');
$query = http_build_query($this->options + ['store' => $store]);
return new Request('GET', '/merchant/reviews?' . $query);
}
/**
* Sends the request and parses response into array.
*
* @return array|mixed
*/
public function send()
{
$response = $this->apiClient->sendRequest(
$this->getRequest(),
$this->withAuthentication
);
return $this->apiClient->getResponseJson($response);
}
}
| true |
92e97073df59622cb64bc77fcbf42b2ffb5e8dd1 | PHP | idezdigital/laravel-bankly-sdk | /src/Data/Account.php | UTF-8 | 1,181 | 2.65625 | 3 | [
"MIT"
] | permissive | <?php
namespace Idez\Bankly\Data;
use Idez\Bankly\Enums\AccountType;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class Account extends Data
{
use HasFactory;
public string $branch = '0001';
public string $number;
public ?string $document = null;
public ?AccountType $type = AccountType::Checking;
public ?Bank $bank = null;
public ?Holder $holder = null;
public function __construct(mixed $data = [], string $branch = '0001')
{
if (isset($data['holder']) && ! $data['holder'] instanceof Holder) {
$data['holder'] = new Holder($data['holder']);
}
if (isset($data['bank']) && ! $data['bank'] instanceof Bank) {
$data['bank'] = new Bank($data['bank']);
} else {
$data['bank'] = new Bank();
}
if (isset($data['type']) && is_string($data['type'])) {
$data['type'] = AccountType::tryFrom($data['type']);
}
if (isset($data['account'])) {
$data['branch'] = $data['account']['branch'] ?? $branch ;
$data['number'] = $data['account']['number'];
}
parent::__construct($data);
}
}
| true |
eb7a03188f54e5715eb4beeda29ba803467e4aed | PHP | paslandau/data-filtering | /src/Transformation/ArrayFlipTransformer.php | UTF-8 | 709 | 2.75 | 3 | [
"MIT"
] | permissive | <?php
namespace paslandau\DataFiltering\Transformation;
class ArrayFlipTransformer extends AbstractBaseTransformer implements ArrayTransformerInterface
{
/**
* @param ArrayTransformerInterface $predecessor . Default: null.
* @param boolean $dataCanBeNull . Default: null (false).
*/
public function __construct(ArrayTransformerInterface $predecessor = null, $dataCanBeNull = null)
{
parent::__construct($predecessor, $dataCanBeNull);
}
/**
* @var mixed[] $data
* @throws \UnexpectedValueException
* @return mixed[]
*/
protected function processData(/* array */ $data)
{
$res = array_flip($data);
return $res;
}
}
| true |
dcd42c25a017feec9080f413a75591ef1a6f2b07 | PHP | jamesdube/mps-server | /app/Http/Middleware/JsonMiddleware.php | UTF-8 | 644 | 2.65625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Response;
use Intersect\Api\Response\Json;
class JsonMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if($request->isJson())
{
return $next($request);
}
else
{
return Json::response(['error'=>true,'message_info' => 'invalid input format, make sure your requests are in json'],Response::HTTP_BAD_REQUEST);
}
}
}
| true |
b9d3b4db1d7f218316def7fe192740853786a873 | PHP | aykilic/baver | /database/migrations/2018_04_08_212314_sablonii.php | UTF-8 | 711 | 2.546875 | 3 | [] | no_license | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class sablonii extends Migration
{
public function up() {
Schema::create('sablon', function (Blueprint $table) {
$table->increments('sblid');
$table->integer('sblturuid');
$table->string('sblad',15);
$table->string('id',15);
$table->string('data-name',15);
$table->string('text',100);
$table->integer('top');
$table->integer('left');
$table->integer('width');
$table->integer('height');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('sablon');
}
}
| true |
edb1095fee7ab8c02373f3faa525e617af0fa955 | PHP | octalmage/wib | /php-7.3.0/ext/spl/tests/recursive_tree_iterator_005.phpt | UTF-8 | 1,973 | 2.828125 | 3 | [
"BSD-4-Clause-UC",
"BSD-3-Clause",
"LicenseRef-scancode-other-permissive",
"TCL",
"ISC",
"Zlib",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"blessing",
"MIT"
] | permissive | --TEST--
SPL: RecursiveTreeIterator and binary vs unicode (PHP 6.0+)
--INI--
error_reporting=E_ALL&~E_NOTICE
--FILE--
<?php
$ary = array(
0 => array(
(binary) "binary",
"abc2",
1,
),
(binary) "binary" => array(
2,
"b",
3 => array(
4,
"c",
),
"4abc" => array(
4,
"c",
),
),
);
$it = new RecursiveTreeIterator(new RecursiveArrayIterator($ary), 0);
foreach($it as $k => $v) {
var_dump($v);
}
echo "\n----------------\n\n";
foreach($it as $k => $v) {
var_dump($k);
}
echo "\n----------------\n\n";
echo "key, getEntry, current:\n";
foreach($it as $k => $v) {
var_dump($it->key(), $it->getEntry(), $it->current());
}
?>
===DONE===
--EXPECT--
string(7) "|-Array"
string(10) "| |-binary"
string(8) "| |-abc2"
string(5) "| \-1"
string(7) "\-Array"
string(5) " |-2"
string(5) " |-b"
string(9) " |-Array"
string(7) " | |-4"
string(7) " | \-c"
string(9) " \-Array"
string(7) " |-4"
string(7) " \-c"
----------------
string(3) "|-0"
string(5) "| |-0"
string(5) "| |-1"
string(5) "| \-2"
string(8) "\-binary"
string(5) " |-0"
string(5) " |-1"
string(5) " |-3"
string(7) " | |-0"
string(7) " | \-1"
string(8) " \-4abc"
string(7) " |-0"
string(7) " \-1"
----------------
key, getEntry, current:
string(3) "|-0"
string(5) "Array"
string(7) "|-Array"
string(5) "| |-0"
string(6) "binary"
string(10) "| |-binary"
string(5) "| |-1"
string(4) "abc2"
string(8) "| |-abc2"
string(5) "| \-2"
string(1) "1"
string(5) "| \-1"
string(8) "\-binary"
string(5) "Array"
string(7) "\-Array"
string(5) " |-0"
string(1) "2"
string(5) " |-2"
string(5) " |-1"
string(1) "b"
string(5) " |-b"
string(5) " |-3"
string(5) "Array"
string(9) " |-Array"
string(7) " | |-0"
string(1) "4"
string(7) " | |-4"
string(7) " | \-1"
string(1) "c"
string(7) " | \-c"
string(8) " \-4abc"
string(5) "Array"
string(9) " \-Array"
string(7) " |-0"
string(1) "4"
string(7) " |-4"
string(7) " \-1"
string(1) "c"
string(7) " \-c"
===DONE===
| true |
59a06c8bfa99519694ba636817b6c89865d963d0 | PHP | rodesta2212/app-when | /includes/ujian.inc.php | UTF-8 | 2,479 | 2.90625 | 3 | [
"MIT"
] | permissive | <?php
class Ujian {
private $conn;
private $table_ujian = 'ujian';
public $id_ujian;
public $nama;
public $nilai_lulus;
public function __construct($db) {
$this->conn = $db;
}
function insert() {
$query = "INSERT INTO {$this->table_ujian} VALUES(?, ?, ?)";
$stmt = $this->conn->prepare($query);
$stmt->bindParam(1, $this->id_ujian);
$stmt->bindParam(2, $this->nama);
$stmt->bindParam(3, $this->nilai_lulus);
if ($stmt->execute()) {
return true;
} else {
return false;
}
}
function getNewID() {
$query = "SELECT MAX(id_ujian) AS code FROM {$this->table_ujian}";
$stmt = $this->conn->prepare($query);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($row) {
return $this->genCode($row["code"], '');
} else {
return $this->genCode($nomor_terakhir, '');
}
}
function genCode($latest, $key, $chars = 0) {
$new = intval(substr($latest, strlen($key))) + 1;
$numb = str_pad($new, $chars, "0", STR_PAD_LEFT);
return $key . $numb;
}
function genNextCode($start, $key, $chars = 0) {
$new = str_pad($start, $chars, "0", STR_PAD_LEFT);
return $key . $new;
}
function readAll() {
$query = "SELECT id_ujian, nama, nilai_lulus FROM {$this->table_ujian} ORDER BY id_ujian ASC";
$stmt = $this->conn->prepare( $query );
$stmt->execute();
return $stmt;
}
function readOne() {
$query = "SELECT * FROM {$this->table_ujian} WHERE id_ujian=:id_ujian LIMIT 0,1";
$stmt = $this->conn->prepare($query);
$stmt->bindParam(':id_ujian', $this->id_ujian);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$this->id_ujian = $row['id_ujian'];
$this->nama = $row['nama'];
$this->nilai_lulus = $row['nilai_lulus'];
}
function update() {
$query = "UPDATE {$this->table_ujian}
SET
nama = :nama,
nilai_lulus = :nilai_lulus
WHERE
id_ujian = :id";
$stmt = $this->conn->prepare($query);
$stmt->bindParam(':nama', $this->nama);
$stmt->bindParam(':nilai_lulus', $this->nilai_lulus);
$stmt->bindParam(':id', $this->id_ujian);
if ($stmt->execute()) {
return true;
} else {
return false;
}
}
function delete() {
$query = "DELETE FROM {$this->table_ujian} WHERE id_ujian = ?";
$stmt = $this->conn->prepare($query);
$stmt->bindParam(1, $this->id_ujian);
if ($result = $stmt->execute()) {
return true;
} else {
return false;
}
}
}
| true |
0c89b610f7493361ae0431c3303b33373342ff02 | PHP | thecomputermanonline/discussionapi | /src/GraphQL/Schema/Mutation/AddMetadataField.php | UTF-8 | 1,137 | 2.515625 | 3 | [] | no_license | <?php
namespace App\GraphQL\Schema\Mutation;
use App\Entity\Message;
use App\Entity\Thread;
use App\Entity\User;
use App\GraphQL\DataProvider;
use App\GraphQL\Schema\Type\MessageType;
use App\GraphQL\Schema\Type\MessageInputType;
use App\GraphQL\Schema\Type\MetadataInputType;
use App\GraphQL\Schema\Type\MetadataType;
use Youshido\GraphQL\Config\Field\FieldConfig;
use Youshido\GraphQL\Execution\ResolveInfo;
use Youshido\GraphQL\Field\AbstractField;
use Youshido\GraphQL\Type\ListType\ListType;
use Youshido\GraphQL\Type\NonNullType;
use Youshido\GraphQL\Type\Object\AbstractObjectType;
use Youshido\GraphQL\Type\Scalar\IdType;
use Youshido\GraphQL\Type\Scalar\StringType;
class AddMetadataField extends AbstractField
{
public function build(FieldConfig $config)
{
$config->addArgument('metadata' , new MetadataInputType());
}
public function getType()
{
return new MetadataType();
}
public function resolve($value, array $args, ResolveInfo $info )
{
$dp = new DataProvider( $info );
$metadata = $dp->AddMetadata($args);
return $metadata;
}
} | true |
9fddb994689030ad2b86c741579d83796e791774 | PHP | joysingh123/SAFTL | /app/Http/Controllers/WebHookController.php | UTF-8 | 746 | 2.5625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Webhook;
class WebHookController extends Controller
{
public function handle(Request $request){
$data = json_decode($request->getContent(), true);
if(count($data) > 0){
foreach ($data AS $d){
$email = $d['email'];
$event = $d['event'];
$reason = (isset($d['reason'])) ? $d['reason'] : NULL;
$webhook = new Webhook();
$webhook->email = $email;
$webhook->email_status = $event;
$webhook->reason = $reason;
$webhook->response = json_encode($d);
$webhook->save();
}
}
}
}
| true |
5a0fa6831783bd4688b1e8f4f238ea0a64ec2c21 | PHP | mlocati/concrete5-since-tagger | /src/Console/Command.php | UTF-8 | 848 | 2.6875 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types=1);
namespace MLocati\C5SinceTagger\Console;
use MLocati\C5SinceTagger\Application;
use Symfony\Component\Console\Command\Command as SymfonyCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
/**
* @method \MLocati\C5SinceTagger\Application getApplication()
*/
abstract class Command extends SymfonyCommand
{
protected $input;
protected $output;
public function __construct(Application $application)
{
parent::__construct();
$this->setApplication($application);
}
final protected function execute(InputInterface $input, OutputInterface $output): int
{
$this->input = $input;
$this->output = $output;
return $this->handle();
}
abstract protected function handle(): int;
}
| true |
bb1d31f5e434bac34873d25e20cf966e1ba9fb79 | PHP | ko-ko-ko/php-assert | /src/exceptions/LengthNotGreaterException.php | UTF-8 | 1,180 | 3.046875 | 3 | [
"MIT"
] | permissive | <?php
/**
* @link https://github.com/ko-ko-ko/php-assert
* @copyright Copyright (c) 2015 Roman Levishchenko <index.0h@gmail.com>
* @license https://raw.github.com/ko-ko-ko/php-assert/master/LICENSE
*/
namespace KoKoKo\assert\exceptions;
class LengthNotGreaterException extends ArgumentException
{
/**
* @param string $variableName
* @param string $variableValue
* @param int $length
* @throws InvalidIntException
* @throws InvalidStringException
*/
public function __construct($variableName, $variableValue, $length)
{
if (!is_string($variableName)) {
throw new InvalidStringException('variableName', $variableName);
} elseif (!is_string($variableValue)) {
throw new InvalidStringException('variableValue', $variableValue);
} elseif (!is_int($length)) {
throw new InvalidIntException('length', $length);
}
parent::__construct(
sprintf(
'Variable "$%s" must have length greater than "%d", actual length: "%d"',
$variableName,
$length,
mb_strlen($variableValue)
)
);
}
} | true |
d632f6e164a81c07f1a757ce53ebe25be9c8bf41 | PHP | ambu550/php_course | /34_.php | UTF-8 | 778 | 3.4375 | 3 | [] | no_license |
<?php
/*
* 34) Назовите пары ключ\значение в массиве $array.
* Добавьте значение 'Jeanne d'Arc' в массив NULL.
* Используйте теги "<pre>" для структурированного отображения.
* Выведите массив 3-мя различными способами.
*/
$array = array(FALSE => TRUE, TRUE => FALSE, NULL =>
array(PHP_OS, "PHP_VERSION"));
$array2 = 'Jeanne d\'Arc';
array_push($array[NULL],$array2);
/*
echo ("<pre>");
echo ("</pre>");
*/
print_r($array);
var_dump($array);
foreach($array as $key => $res)
{
if($key|| $key===0){
echo "$key => $res \n";}else{
foreach($res as $in_key => $value)
{
echo "[$key][$in_key] = $value \n";
}}
}
?>
| true |
4af80f5f5e176b3bf51f1ddaca13dbe37f1bafee | PHP | reinvdv/Gastenboek | /process.php | UTF-8 | 1,398 | 2.6875 | 3 | [] | no_license | <?php
error_reporting();
//$dbc = mysqli_connect('localhost', 'root', 'root', 'jaar2') or die ('ERROR!');
$dbc = mysqli_connect('localhost', '22810_wall', '22810', 'rein_db') or die ('ERROR!');
if(isset($_POST['submit'])){
$voornaam = mysqli_real_escape_string($dbc, trim($_POST['voornaam']));
$review = mysqli_real_escape_string($dbc, trim($_POST['review']));
$verbodenwoorden = array('hoer', 'kanker', 'bartanus', 'gvd');
$reviewcheck = strtolower($review);
$geenverbodenwoorden = true;
foreach ($verbodenwoorden as $verbodenwoord) {
if (preg_match("/\b$verbodenwoord\b/", $reviewcheck)) {
$geenverbodenwoorden = false;
break;
}
}
if ($geenverbodenwoorden) {
$query = "INSERT INTO reviews VALUES(0, '$voornaam', '$review')";
$result = mysqli_query($dbc,$query) or die ("er is een four opgetreden");
$to = "22810@ma-web.nl";
$subject = "Er is een nieuw bericht geplaatst";
$msg = $voornaam . " heeft een nieuw bericht geplaatst.</br><p>
Het bericht is: <br>" . $review;
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= 'From: Gastenboek@ma-web.nl' . "\r\n";
$headers .= '' . "\r\n";
mail($to,$subject,$msg,$headers);
header("location: ./index.php");
}else {
echo "je hebt geen nette woorden gebruikt";
}
}
?>
| true |
e1c5a5110650d6d0c712fc58aff7a4d6203f5c3e | PHP | zhengkai/soulogic.com-legacy | /inc/pageheader.php | UTF-8 | 3,894 | 2.59375 | 3 | [] | no_license | <?php
settype($_SERVER["HTTP_HOST"], "string");
settype($_SERVER["REQUEST_URI"], "string");
class PageHeader {
protected static $_aAlias = array(
"wiki" => "knowlege",
"passport" => "platform",
"forum" => "group",
);
protected static $_aControl = array(
/*
"wiki" => array(
"css" => array("abc.css", "def.css")
),
*/
);
protected static $_sInsert = "\n";
protected static $_sDir;
protected static $_aCSS = array();
protected static $_aJS = array();
protected static $_bWebfont = FALSE;
public static function setWebfont() {
self::$_bWebfont = TRUE;
}
public static function getWebfont() {
return self::$_bWebfont;
}
public static function addCSS($sCSS) {
self::$_aCSS[] = $sCSS;
}
public static function addJS($sJS) {
self::$_aJS[] = $sJS;
}
public static function addExt($sContent) {
self::$_sInsert .= $sContent;
}
public static function getExt($sContent) {
return self::$_sInsert;
}
public static function getResDomain() {
return "res.soulogic.com";
}
public static function get() {
$sResDir = dirname(dirname(__DIR__))."/res/";
$sDir = self::getDir();
if (isset(self::$_aAlias[$sDir])) {
$sDir = self::$_aAlias[$sDir];
}
if (preg_match("/^[a-z\\_]+$/", $sDir)) {
if (file_exists($sResDir.$sDir.".css")) {
self::addCSS($sDir.".css");
}
if (file_exists($sResDir.$sDir.".js")) {
self::addJS($sDir.".js");
}
$sControl =& self::$_aControl[$sDir];
if (is_array($sControl)) {
if (isset($sControl["css"])) {
foreach ($sControl["css"] as $sCSS) {
self::addCSS($sCSS.".css");
}
}
if (isset($sControl["js"])) {
foreach ($sControl["js"] as $sJS) {
self::addCSS($sJS.".js");
}
}
}
}
$aCSS = array(
"init.css",
"common.css",
);
$aCSS = array_unique(array_merge($aCSS, self::$_aCSS));
if (!empty(self::$_aJS)) {
$aJS = array(
"jquery-1.8.3.min.js",
);
$aJS = array_unique(array_merge($aJS, self::$_aJS));
}
$sReturn = "\n";
if (TANGO_DEV) {
$sResPath = dirname(__DIR__)."/res/";
$aCSS = scandir($sResPath);
$aFirst = array(
"init.css",
"common.css",
);
$aCSS = array_filter($aCSS, function($sFile) use ($aFirst) {
if (in_array($sFile, $aFirst)) {
return FALSE;
}
if (pathinfo($sFile, PATHINFO_EXTENSION) !== "css") {
return FALSE;
}
return TRUE;
});
$aCSS = array_merge($aFirst, $aCSS);
foreach ($aCSS as $sCSS) {
$sReturn .= "<link rel=\"stylesheet\" href=\"//".self::getResDomain()."/".$sCSS."?tmp=".md5_file($sResPath.$sCSS)."\" type=\"text/css\" />\n";
}
if (!empty($aJS)) {
foreach ($aJS as $sJS) {
$sReturn .= "<script type=\"text/javascript\" src=\"//".self::getResDomain()."/".$sJS."?tmp=".md5_file($sResPath.$sCSS)."\"></script>\n";
}
}
} else {
$aCSS = array("default");
$sReturn .= "<link rel=\"stylesheet\" href=\"".self::_getResLink($aCSS, "css")."\" type=\"text/css\" />\n";
if (!empty($aJS)) {
$sReturn .= "<script type=\"text/javascript\" src=\"".self::_getResLink($aJS, "js")."\"></script>\n";
}
}
return $sReturn;
}
protected static function _getResLink($aRes, $sType = "js") {
$sFilterPattern = "/^(\\/)?(.*?)(\\.js|\\.css)?(\\.)?$/";
$aRes = preg_replace($sFilterPattern, "\\2", $aRes);
$sRes = implode(",", $aRes);
$iVersion = getResVersion();
$sHash = hash("crc32", $sRes."O0WPmINmROtIBL2AO3Fu".$iVersion);
return $sLink = "//".self::getResDomain()."/combo/".$sRes."_v".$iVersion."_".$sHash.".".$sType;
}
public static function setDir($sDir) {
self::$_sDir = $sDir;
}
public static function getDir() {
if (self::$_sDir === NULL) {
$sDir = strstr(substr($_SERVER["REQUEST_URI"], 1), '/', true);
if (isset(self::$_aAlias[$sDir])) {
$sDir = self::$_aAlias[$sDir];
}
self::setDir($sDir);
}
return self::$_sDir;
}
}
| true |
440cb8594c662332de7b659a709fde623f230f36 | PHP | SamuGS/Proyecto---Sistema-Planilla | /Proyecto - Sistema/action/horario.php | UTF-8 | 2,081 | 2.578125 | 3 | [] | no_license | <?php include 'config.php'; ?>
<?php
if(isset($_POST['agregar'])){
$entrada = $_POST['entrada'];
$salida = $_POST['salida'];
if(empty($entrada) || empty($salida)){
echo '<div class="alert alert-danger" data-dismiss="alert">Campos vacios!</div>';
}else{
$sql = "insert into horario(time_in,time_out) value (\"$entrada\",\"$salida\")";
$query_new_insert = mysqli_query($con,$sql);
if ($query_new_insert){
$msgag[] = "Datos ingresados satisfactoriamente.";
} else{
$errag []= "Lo siento algo ha salido mal intenta nuevamente.";
}
}
}
if (isset($errag)){
?>
<div class="alert alert-danger icons-alert" role="alert" data-dismiss="alert">
<strong>Error!</strong>
<?php
foreach ($errag as $erag) {
echo $erag;
}
?>
</div>
<?php
}
if (isset($msgag)){
?>
<div class="alert alert-primary icons-alert" role="alert" data-dismiss="alert">
<strong>¡Bien hecho!</strong>
<?php
foreach ($msgag as $mess) {
echo $mess;
}
?>
</div>
<?php
}
?>
<?php
if(isset($_POST['eliminar'])){
$ide = $_POST['id'];
$sql = "DELETE FROM horario WHERE id=".$ide;
$query_new_insert = mysqli_query($con,$sql);
if ($query_new_insert){
$messages[] = "Datos eliminados satisfactoriamente.";
} else{
$errors []= "Lo siento algo ha salido mal intenta nuevamente.";
}
}
if (isset($errors)){
?>
<div class="alert alert-danger icons-alert" role="alert" data-dismiss="alert">
<strong>Error!</strong>
<?php
foreach ($errors as $error) {
echo $error;
}
?>
</div>
<?php
}
if (isset($messages)){
?>
<div class="alert alert-primary icons-alert" role="alert" data-dismiss="alert">
<strong>¡Bien hecho!</strong>
<?php
foreach ($messages as $message) {
echo $message;
}
?>
</div>
<?php
}
?> | true |
0b225917e116dc1fffafbb282bef57c7f160326d | PHP | ouabel/OCP5 | /src/AppBundle/Repository/ProfileRepository.php | UTF-8 | 1,719 | 2.609375 | 3 | [] | no_license | <?php
namespace AppBundle\Repository;
use AppBundle\Entity\Profile;
use AppBundle\Entity\Tag;
use AppBundle\Entity\Specialty;
use AppBundle\Entity\District;
use AppBundle\Entity\Province;
use Doctrine\ORM\Query;
use Pagerfanta\Adapter\DoctrineORMAdapter;
use Pagerfanta\Pagerfanta;
/**
* ProfileRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class ProfileRepository extends \Doctrine\ORM\EntityRepository
{
public function getProfiles(?array $properties, int $page = 1)
{
$queryBuilder = $this->createQueryBuilder('p');
if ($specialty = $properties['specialty']) {
$queryBuilder->andWhere(':specialty = p.specialty')->setParameter('specialty', $specialty);
}
if ($tag = $properties['tag']) {
$queryBuilder->andWhere(':tag MEMBER OF p.tags')->setParameter('tag', $tag);
}
if ($district = $properties['district']) {
$queryBuilder->andWhere(':district = p.district')->setParameter('district', $district);
}
if ($province = $properties['province']) {
$queryBuilder->andWhere(':province = p.province')->setParameter('province', $province);
}
$query = $queryBuilder
->andWhere('p.isPublished = 1')
->orderBy('p.lastName', 'DESC')
->getQuery();
return $this->createPaginator($query, $page);
}
private function createPaginator(Query $query, int $page): Pagerfanta
{
$paginator = new Pagerfanta(new DoctrineORMAdapter($query));
$paginator->setMaxPerPage(Profile::NUM_ITEMS);
$paginator->setCurrentPage($page);
return $paginator;
}
}
| true |
105ace73349c9441067e8c27909abdd51e40ffdf | PHP | KJIACCUK/rep-test | /protected/models/PointUser.php | UTF-8 | 2,280 | 2.671875 | 3 | [] | no_license | <?php
/**
* This is the model class for table "point_user".
*
* The followings are the available columns in table 'point_user':
* @property integer $pointUserId
* @property integer $pointId
* @property integer $userId
* @property integer $pointsCount
* @property string $params
* @property integer $dateCreated
*
* The followings are the available model relations:
* @property User $user
* @property Point $point
*/
class PointUser extends CActiveRecord
{
public $pointsSum;
/**
* Returns the static model of the specified AR class.
* @param string $className active record class name.
* @return PointUser the static model class
*/
public static function model($className = __CLASS__)
{
return parent::model($className);
}
/**
* @return string the associated database table name
*/
public function tableName()
{
return 'point_user';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
return array(
array('pointId, userId, pointsCount, dateCreated', 'required'),
array('pointId, userId, pointsCount', 'length', 'max' => 11),
array('dateCreated', 'length', 'max' => 10),
array('params', 'safe')
);
}
/**
* @return array relational rules.
*/
public function relations()
{
return array(
'user' => array(self::BELONGS_TO, 'User', 'userId'),
'point' => array(self::BELONGS_TO, 'Point', 'pointId'),
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'pointUserId' => 'Point User',
'pointId' => 'Point',
'userId' => 'User',
'pointsCount' => 'Points Count',
'params' => 'Params',
'dateCreated' => 'Date Created',
);
}
}
| true |
b033f2d2cdd9fa11dc2252c4e8c20e2f2e393b80 | PHP | donzepedro/laive-cam | /models/Account.php | UTF-8 | 894 | 2.71875 | 3 | [] | no_license | <?php
namespace app\models;
use Yii;
use yii\base\Model;
/**
* ContactForm is the model behind the contact form.
*/
class Account extends Model
{
public $first_name;
public $phone;
public $surname;
public $country;
public $city;
/**
* @return array the validation rules.
*/
public function rules()
{
return [
// first_name, phone are required
[['first_name', 'phone'], 'required'],
// validate
['phone', 'string'],
['first_name', 'string'],
['surname', 'string'],
['country', 'string'],
['city', 'string']
];
}
public function attributeLabels()
{
return [
'first_name'=>'',
'phone'=>'',
'surname'=>'',
'country'=>'',
'city'=>''
];
}
}
| true |
95499a0ecd423d8799d9887414d8ad613fade0ea | PHP | ondraczsk/MCPELANDCore | /src/legionpe/games/spleef/SpleefArenaConfig.php | UTF-8 | 1,506 | 2.578125 | 3 | [] | no_license | <?php
namespace legionpe\games\spleef;
use pocketmine\block\Block;
use pocketmine\level\Location;
use pocketmine\math\Vector3;
class SpleefArenaConfig{
public $name;
/** @var Location */
public $spectatorSpawnLoc; // ssl? xD
/** @var Location */
public $playerPrepLoc;
/** @var Location[] */
public $playerStartLocs = [];
/** @var int */
public $fromx, $tox, $fromz, $toz;
/** @var int */
public $floors;
/** @var int includes the floor layer */
public $floorHeight;
/** @var int */
public $lowestY;
/** @var Block[] */
public $floorMaterials;
/** @var \pocketmine\item\Item[][] */
public $playerItems;
/** @var int */
public $minPlayers;
/** @var int */
public $minWaitTicks;
/** @var int */
public $maxWaitTicks;
/** @var int */
public $maxGameTicks;
public function getMaxPlayers(){
return count($this->playerStartLocs);
}
public function build(){
$materialMaxKey = count($this->floorMaterials) - 1;
$level = $this->playerPrepLoc->getLevel();
// $level->getServer()->getLogger()->debug("Start rebuilding of spleef $this->name");
for($floor = 0; $floor < $this->floors; $floor++){
$y = $this->lowestY + $floor * $this->floorHeight;
for($x = $this->fromx; $x <= $this->tox; $x++){
for($z = $this->fromz; $z <= $this->toz; $z++){
$level->setBlock(new Vector3($x, $y, $z), $this->floorMaterials[mt_rand(0, $materialMaxKey)], false, false);
}
}
}
// $level->getServer()->getLogger()->debug("Finished rebuilding of spleef $this->name");
}
}
| true |
f0638a70fe6e60fc216e7d7c8fd80db794d89e65 | PHP | cedtanghe/elixir | /src/framework/Elixir/Form/Field/Input.php | UTF-8 | 3,428 | 2.671875 | 3 | [] | no_license | <?php
namespace Elixir\Form\Field;
use Elixir\Form\Field\FieldAbstract;
/**
* @author Cédric Tanghe <ced.tanghe@gmail.com>
*/
class Input extends FieldAbstract
{
/**
* @var string
*/
const BUTTON = 'button';
/**
* @var string
*/
const CHECKBOX = 'checkbox';
/**
* @var string
*/
const FILE = 'file';
/**
* @var string
*/
const HIDDEN = 'hidden';
/**
* @var string
*/
const IMAGE = 'image';
/**
* @var string
*/
const PASSWORD = 'password';
/**
* @var string
*/
const RADIO = 'radio';
/**
* @var string
*/
const RESET = 'reset';
/**
* @var string
*/
const SUBMIT = 'submit';
/**
* @var string
*/
const TEXT = 'text';
/**
* @var string
*/
const COLOR = 'color';
/**
* @var string
*/
const DATE = 'date';
/**
* @var string
*/
const DATETIME = 'datetime';
/**
* @var string
*/
const DATETIME_LOCAL = 'datetime-local';
/**
* @var string
*/
const EMAIL = 'email';
/**
* @var string
*/
const MONTH = 'month';
/**
* @var string
*/
const NUMBER = 'number';
/**
* @var string
*/
const RANGE = 'range';
/**
* @var string
*/
const SEARCH = 'search';
/**
* @var string
*/
const TEL = 'tel';
/**
* @var string
*/
const TIME = 'time';
/**
* @var string
*/
const URL = 'url';
/**
* @var string
*/
const WEEK = 'week';
/**
* @var array
*/
protected static $_excludes = [
self::FILE => '\Elixir\Form\Field\File',
self::CHECKBOX => '\Elixir\Form\Field\Checkbox',
self::RADIO => '\Elixir\Form\Field\Radio'
];
/**
* @see FieldAbstract::__construct()
*/
public function __construct($pName = null)
{
parent::__construct($pName);
$this->_helper = 'input';
}
/**
* @param string $pValue
*/
public function setType($pValue)
{
$this->setAttribute('type', $pValue);
}
/**
* @return string
*/
public function getType()
{
return $this->getAttribute('type');
}
/**
* @see FieldAbstract::setAttribute()
* @throws \LogicException
*/
public function setAttribute($pKey, $pValue)
{
if($pKey == 'type')
{
if(array_key_exists($pValue, static::$_excludes))
{
throw new \LogicException(
sprintf(
'The class "%s" class is better predisposed to such use.',
static::$_excludes[$pValue]
)
);
}
}
parent::setAttribute($pKey, $pValue);
}
/**
* @see FieldAbstract::setValue()
*/
public function setValue($pValue, $pFiltered = true)
{
$old = $this->_value;
parent::setValue($pValue, $pFiltered);
if(in_array($this->getType(), [self::BUTTON, self::SUBMIT, self::RESET]))
{
if(empty($this->_value))
{
$this->_value = $old;
}
}
}
}
| true |
74a9a9c843ac60be6a049300729648862a7b6c18 | PHP | pucene/old | /src/Component/QueryBuilder/Query/Specialized/MoreLikeThis/DocumentLike.php | UTF-8 | 690 | 2.75 | 3 | [
"MIT"
] | permissive | <?php
namespace Pucene\Component\QueryBuilder\Query\Specialized\MoreLikeThis;
class DocumentLike
{
/**
* @var string
*/
private $id;
/**
* @var string
*/
private $type;
/**
* @var string
*/
private $index;
public function __construct(string $id, ?string $type = null, ?string $index = null)
{
$this->id = $id;
$this->type = $type;
$this->index = $index;
}
public function getId(): string
{
return $this->id;
}
public function getType(): ?string
{
return $this->type;
}
public function getIndex(): ?string
{
return $this->index;
}
}
| true |
a5ade82cebe4fe95d8de26766607b71a2dbe4465 | PHP | nickimnick/crawler | /setMovieData.php | UTF-8 | 7,760 | 2.59375 | 3 | [] | no_license | <?php
header('Content-type: text/html; charset=utf-8');
ini_set('max_execution_time', 0);
//
//function logger($data){
//
// $dt = new DateTime();
// $now = $dt->format('d-m-Y H:i:s');
// $data = strip_tags($data);
// $logFile = fopen("logs/logs.txt", "a+") or die("Unable to open file!");
//
// fwrite($logFile, "- ".$data." --> ".$now."\r\n");
// fclose($logFile);
//
//}
//function check_url($url){
// $result = false;
// if($page = @file_get_contents($url)) {
// $result = $page;
// }
//
// return $result;
//}
//DATABASE INFO
$host = "localhost";
$user = "root";
$pass = "1079";
$dbName = "crawler_db";
$table = 'movies';
$result = '';
if(isset($_GET['id'])) $urlId = $_GET['id'];
$check = FALSE;
$mysqli = new mysqli($host,$user,$pass,$dbName);
if ($mysqli->connect_errno){
$result = $mysqli->connect_error;
exit();
}else{
$sqlChk = "SELECT imdb_id FROM ".$table." WHERE imdb_id ='".$urlId."'";
$q = $mysqli->query($sqlChk);
if($q->num_rows > 0) $check = TRUE;
$mysqli->close();
if($check){
$imdb_url = 'http://www.imdb.com/title/'.$urlId;
//$omdb_url = "http://www.omdbapi.com/?i=".$urlId."&tomatoes=true";
//$omdb_res = check_url($omdb_url);
//if($omdb_res){
include_once('simple_html_dom/simple_html_dom.php');
//$json = json_decode(file_get_contents($omdb_url));
$html = file_get_html($imdb_url);
//function checkStr($data){
//
// if($data == "N/A")
// return "";
// else
// return $data;
//
//}
//if($json->Response == "True"){
//DATA FROM OMDB API
//$title = str_replace("'", "\'", $json->Title);
//$year = $json->Year;
//$audience = checkStr(str_replace("'", "\'", $json->Rated), false);
//$release_date = checkStr($json->Released, false);
//$runtime = checkStr(str_replace(" min", "", $json->Runtime), false);
//$genre = '|'.str_replace(", ", "||", $json->Genre).'|';
//$plot = checkStr(str_replace("'", "\'", $json->Plot), false);
//$country = checkStr(str_replace(", ", "||", str_replace("'", "\'", $json->Country)), true);
//$languages = checkStr(str_replace("'", "\'", str_replace(", ", "||", $json->Language)), true);
//$awards = checkStr(str_replace("'", "\'", $json->Awards), false);
//$poster = checkStr($json->Poster, false);
//$metascore = checkStr($json->Metascore, false);
//$imdb_rating = checkStr($json->imdbRating, false);
//$imdb_votes = checkStr($json->imdbVotes, false);
//$tomato_meter = checkStr($json->tomatoMeter, false);
//$box_office = str_replace("'", "\'", checkStr($json->BoxOffice, false));
//$poster_path = '';
//
//if($poster != ''){
// file_put_contents("data/movies/".$urlId.".jpg", fopen($poster, 'r'));
// $poster_path = "/data/movies/".$urlId.".jpg";
//}
//
//if($release_date != ''){
// $release_date = date("Y-m-d", strtotime($release_date));
//}
//DATA FROM IMDB
foreach($html->find('#pagecontent') as $tag){
//$original_title = ($tag->find('h1.header span', 0) != NULL) ? trim(str_replace("'", "\'", $tag->find('h1.header span', 0)->plaintext), ' ') : '';
//
//if($title == $original_title) $original_title = "";
//
//if($country == ''){
//
// foreach($tag->find('#titleDetails .txt-block a[href^=/country/]') as $subtag){
//
// $country .= '|'.str_replace("'", "\'", $subtag->plaintext).'|';
//
// }
//
//}
//
//if($languages == ''){
//
// if($tag->find('#titleDetails .txt-block a[href^=/language/]', 0) != ''){
//
// foreach($tag->find('#titleDetails .txt-block a[href^=/language/]') as $subtag){
//
// $languages .= '|'.str_replace("'", "\'", $subtag->plaintext).'|';
//
// }
//
// }
//
//}
//$cast = '';
$director = '';
$writer = '';
//$characters = '';
//$cast_imdb_id = '';
$director_imdb_id = '';
$writer_imdb_id = '';
//$tagline = '';
//foreach($tag->find('#titleStoryLine .txt-block') as $subtag){
//
// if($subtag->find('h4', 0) != '' && $subtag->find('h4', 0)->plaintext == "Taglines:")
// $tagline = trim(str_replace("'", "\'", str_replace("See more »", "", str_replace("Taglines:", "", $subtag->plaintext))), " ");
//
//}
//
//foreach($tag->find('#titleCast .cast_list td.primary_photo') as $subtag){
//
// $cast .= '|'.trim(str_replace("'", "\'", $subtag->find('img', 0)->getAttribute('alt')), ' ').'|';
// $temp = explode('/', $subtag->find('a', 0)->href);
// $cast_imdb_id .= '|'.$temp[2].'|';
//
//}
foreach($tag->find('[itemprop=director] a[href^=/name/]') as $subtag){
$director .= '|'.trim(str_replace("'", "\'", $subtag->find('span[itemprop=name]', 0)->plaintext), ' ').'|';
$temp = explode('/', $subtag->href);
$temp = explode('?', $temp[2]);
$director_imdb_id .= '|'.$temp[0].'|';
}
foreach($tag->find('[itemprop=creator] a[href^=/name/]') as $subtag){
$writer .= '|'.trim(str_replace("'", "\'", $subtag->find('span[itemprop=name]', 0)->plaintext), ' ').'|';
$temp = explode('/', $subtag->href);
$temp = explode('?', $temp[2]);
$writer_imdb_id .= '|'.$temp[0].'|';
}
//foreach($tag->find('#titleCast .cast_list td.character') as $subtag){
//
// $characters .= '|'.trim(str_replace("'", "\'", trim($subtag->find('div', 0)->plaintext, ' ')), ' ').'|';
//
//}
$mysqli = new mysqli($host,$user,$pass,$dbName);
if($mysqli->connect_errno){
$result = '<span class="error">Movie: <i>'.$title.' ('.$urlId.')</i> is failed!!! -> '.$mysqli->connect_error.'</span>';
exit();
}else{
$sql = "UPDATE ".$table." SET director = N'".$director."', director_imdb_id = N'".$director_imdb_id."', writer = N'".$writer."', writer_imdb_id = N'".$writer_imdb_id."' WHERE imdb_id = '".$urlId."'";
//$sql = "INSERT INTO ".$table."(title, original_title, poster_path, year, plot, tagline, runtime, genre, country, languages, imdb_rating, imdb_votes, director, director_imdb_id, writer, writer_imdb_id, cast, cast_imdb_id, characters, audience, imdb_id, release_date, awards, metascore, tomato_meter, box_office) VALUES (N'".$title."',N'".$original_title."','".$poster_path."','".$year."',N'".$plot."',N'".$tagline."','".$runtime."',N'".$genre."',N'".$country."',N'".$languages."','".$imdb_rating."','.$imdb_votes.',N'".$director."','".$director_imdb_id."',N'".$writer."','".$writer_imdb_id."',N'".$cast."','".$cast_imdb_id."',N'".$characters."','".$audience."','".$urlId."','".$release_date."',N'".$awards."','".$metascore."','".$tomato_meter."',N'".$box_office."')";
if($mysqli->query($sql)){
$result = 'Movie: <i> ('.$urlId.')</i> is done!!!';
}else{
$result = '<span class="error">Movie: <i>'.$title.' ('.$urlId.')</i> is failed!!! -> '.$mysqli->error.'</span>';
}
$mysqli->close();
}
}
$html->clear();
unset($html);
//}else{
//
// $result = 'Movie: <i>'.$urlId.'</i> not found in OMDB API!!!';
//
//}
//}else{
// $result = 'Can`t reach OMDB API!!!';
//}
}else{
$result = 'Movie not exist!!!';
}
echo $result;
//logger($result);
}
?>
| true |
a8fd9f5656d4097ca65edb61038bcfbb5260f857 | PHP | alex070609/Veville | /choix_vehicule.php | UTF-8 | 4,123 | 2.59375 | 3 | [
"MIT"
] | permissive | <?php
require_once('inc/init.php');
if( !isConnected() ){
$_SESSION['message'] = '<div class="alert alert-danger">Vous devez être connecté pour consulter cette page ! <a href="" data-toggle="modal" data-target="#inscription">cliquez ici</a> pour vous en créer un</div>';
header('location:'.URL.'index.php');
exit();
}
if( isset($_POST['titre']) ){
$title = $_POST['titre'];
} else {
$title = $_GET['titre'];
}
if( !empty($_GET['action']) && $_GET['action'] == "reserver" ){
$nb_de_jour_timestamp = $_GET['datef'] - $_GET['dated'];
$nb_de_jour = $nb_de_jour_timestamp/86400;
$prix_journalier = $nb_de_jour * $_GET['prix_journalier'];
$_SESSION['panier'] = $_GET;
$_SESSION['prix_journalier'] = $prix_journalier;
header('location:'.URL.'panier.php');
exit();
}
require_once('inc/header.php');
if( isset($_SESSION['panier']) ){
var_dump($_SESSION['panier']);
}
if( !empty($_POST) ):
?>
<div class="row">
<div class="col-4">
<h2>Véhicule sélectionné</h2>
<div class="card" style="width: 100%">
<img src="<?= URL . 'photo/vehicule/' . $_POST['photo'] ?>" class="card-img-top" alt="voiture">
<div class="card-body">
<h5 class="card-title"><?= $_POST['titre'] ?></h5>
<p class="card-text">description : <?= $_POST['desc'] ?><br>prix journalier : <?= $_POST['prix_journalier'] ?> €<br> </p>
</div>
</div>
</div>
<div class="col-8">
<h3>Réservation :</h3>
<?php
$timestamp1 = strtotime($_POST['dated']);
$timestamp2 = strtotime($_POST['datef']);
$date_deja_prise = execReq( "SELECT * FROM commande WHERE vehicule_idvehicule=:idvehicule", array(
'idvehicule' => $_POST['vehicule']
));
$texte = '';
$color = '';
while ($date = $date_deja_prise->fetch() ){
$date_debut = strtotime($date['date_heure_depart']);
$date_fin = strtotime($date['date_heure_fin']);
if( ($date_debut <= $timestamp2 && $timestamp1 <= $date_fin) ){
$texte = 'Véhicule indisponible';
$color = 'danger';
?><p class="alert alert-info">Ce véhicule est déjà réserver du <?= $date['date_heure_depart'] ?> au <?= $date['date_heure_fin'] ?></p><?php
}
} ?>
<div class="row">
<form action="" method="get" class="ml-4">
<input type="hidden" name="dated" value="<?= $timestamp1 ?>">
<input type="hidden" name="titre" value="<?= $_POST['titre'] ?>">
<input type="hidden" name="datef" value="<?= $timestamp2 ?>">
<input type="hidden" name="agence" value="<?= $_POST['agence'] ?>">
<input type="hidden" name="vehicule" value="<?= $_POST['vehicule'] ?>">
<input type="hidden" name="prix_journalier" value="<?= $_POST['prix_journalier'] ?>">
<?php
if( empty($texte) ){
?><input type="hidden" name="action" value="reserver"><?php
}
?>
<button type="submit" class="btn btn-<?= !empty($color) ? $color : 'success' ?>" <?= ($texte == 'Véhicule indisponible') ? 'disabled' : '' ?>><?= !empty($texte) ? $texte : 'Réserver' ?></button>
</form>
<form action="index.php" method="get" class="ml-4">
<input type="hidden" name="action" value="ok">
<input type="hidden" name="action2" value="ok">
<input type="hidden" name="agence" value="<?= $_POST['agence'] ?>">
<input type="hidden" name="idmembre" value="<?= $_SESSION['membre']['idmembre'] ?>">
<input type="hidden" name="date_heure_debut" value="<?= $_POST['dated'] ?>">
<input type="hidden" name="date_heure_fin" value="<?= $_POST['datef'] ?>">
<input type="submit" class="btn btn-info" value="Retour">
</form>
</div>
</div>
</div>
<?php
endif;
require_once('inc/footer.php'); | true |
27b5932b6339eb9678f56e5389f44d8cf008646a | PHP | naoyama88/Laravel-Scraping-LineApi | /app/Libs/Util.php | UTF-8 | 1,567 | 2.859375 | 3 | [] | no_license | <?php
namespace App\Libs;
use Illuminate\Support\Facades\Log;
class Util
{
/**
* judge current time whether it's between 23:20 and 8:00
*
* @param string $now made by function date('xx:xx:xx')
* @return bool
*/
public static function isMidnight(string $now)
{
$nowTimestamp = strtotime($now);
$startMidnight = strtotime(date(env('DO_NOT_DISTURB_FROM', '23:20:00')));
$endMidnight = strtotime(date(env('DO_NOT_DISTURB_TO', '08:00:00')));
return $startMidnight < $nowTimestamp || $nowTimestamp < $endMidnight;
}
/**
* judge a number whether it's even number
*
* @param string $minuteStr
* @return bool
* @throws \Exception
*/
public static function isEvenNumber(string $minuteStr)
{
$tenPlaceMinute = intval(substr($minuteStr, 0, 1));
switch ($tenPlaceMinute) {
case 0 :
case 2 :
case 4 :
return true;
case 1 :
case 3 :
case 5 :
return false;
}
throw new \Exception('This is not between 0 and 6. Number is ' . $minuteStr);
}
/**
* @param bool $isRunFromCli
* @param null $globalVarServer
* @return string
*/
public function getSentType(bool $isRunFromCli, $globalVarServer = null)
{
if ($isRunFromCli) {
// return $globalVarServer['argv'][1];
return 'sent_01';
}
Log::info('run not from cli');
return 'sent_01';
}
} | true |
b2e6cdb546ac61f86420fda872192fee406ba9d3 | PHP | Smashkat12/Camagru_Playground | /classes/image.inc.php | UTF-8 | 1,094 | 2.796875 | 3 | [] | no_license | <?php
class Image {
public static function uploadImage($formname, $query, $params) {
//return encoded image as string
$image = base64_encode(file_get_contents($_FILES[$formname]['tmp_name']));
//create stream
$options = array('http'=>array(
'method'=>"POST",
'header'=>"Authorization: Bearer 8f071a0c68940eb80440a1315f56c5d0b5657ca2\n".
"Content-Type: application/x-www-form-urlencoded",
'content'=>$image
));
$context = stream_context_create($options);
$imgurURL = "https://api.imgur.com/3/image";
//check if size of image is less then 10mb
if ($_FILES[$formname]['size'] > 10240000) {
die('Image size too big, must be 10mb or less!');
}
//open img file ussing HTTP headers set when creating stream
$response = file_get_contents($imgurURL, false, $context);
//return json object
$response = json_decode($response);
//get the url link to image from JSON as associative array
$preparams = array($formname=>$response->data->link);
//prepare arameters to match how parameters appear in the query
$params = $preparams + $params;
DB::query($query, $params);
}
}
?> | true |
65d90c817ae3f564b8ba0087f014c4252aa4659f | PHP | Mbuelo/zendesk | /Model/CustomerOrderRepository.php | UTF-8 | 5,521 | 2.5625 | 3 | [] | no_license | <?php
/**
* Copyright Wagento Creative LLC ©, All rights reserved.
* See COPYING.txt for license details.
*/
namespace Wagento\Zendesk\Model;
use Magento\Customer\Api\GroupRepositoryInterface;
use Magento\Customer\Model\CustomerFactory;
use Magento\Framework\Api\DataObjectHelper;
use Magento\Framework\Exception\InputException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Sales\Model\OrderFactory;
use Wagento\Zendesk\Api\CustomerOrderRepositoryInterface;
use Wagento\Zendesk\Api\Data\CustomerOrderInterface;
/**
* Class CustomerOrderRepository
* @package Wagento\Zendesk\Model
*/
class CustomerOrderRepository implements CustomerOrderRepositoryInterface
{
/**
* @var CustomerOrderInterface
*/
protected $customerOrder;
/**
* @var CustomerFactory
*/
protected $customerFactory;
/**
* @var OrderFactory
*/
private $orderFactory;
/**
* @var DataObjectHelper
*/
private $dataObjectHelper;
/**
* @var GroupRepositoryInterface
*/
private $groupRepository;
/**
* CustomerOrderRepository constructor.
* @param CustomerOrderInterface $customerOrder
* @param CustomerFactory $customerFactory
* @param OrderFactory $orderFactory
* @param GroupRepositoryInterface $groupRepository
* @param DataObjectHelper $dataObjectHelper
*/
public function __construct(
CustomerOrderInterface $customerOrder,
CustomerFactory $customerFactory,
OrderFactory $orderFactory,
GroupRepositoryInterface $groupRepository,
DataObjectHelper $dataObjectHelper
) {
$this->customerFactory = $customerFactory;
$this->customerOrder = $customerOrder;
$this->orderFactory = $orderFactory;
$this->dataObjectHelper = $dataObjectHelper;
$this->groupRepository = $groupRepository;
}
/**
* Loads a specified customer order information.
*
* @param string $email
* @return \Wagento\Zendesk\Api\Data\CustomerOrderInterface Customer Order Interface.
*/
public function get($email)
{
if (!$email) {
throw new InputException(__('Email required'));
}
$customerInfo = $this->getCustomerData($email);
if (!$customerInfo) {
throw new NoSuchEntityException(__('Requested customer doesn\'t exist'));
}
$this->dataObjectHelper->populateWithArray(
$this->customerOrder,
$customerInfo,
\Wagento\Zendesk\Api\Data\CustomerOrderInterface::class
);
return $this->customerOrder;
}
/**
* @param string $email
* @return array | false
*/
private function getCustomerData($email)
{
/* Get customer info from table customer_entity */
$customer = $this->customerFactory->create();
$customerResource = $customer->getResource();
$customerConnection = $customerResource->getConnection();
$customerTable = $customerResource->getEntityTable();
$select = $customerConnection->select()->from(
$customerTable,
[
'email',
'firstname',
'lastname',
'created_at',
'group_id'
]
)->where(
'email LIKE ?',
$email
);
$customerData = $customerConnection->fetchRow($select);
// Order Connection
$order = $this->orderFactory->create();
$orderResource = $order->getResource();
$orderConnection = $orderResource->getConnection();
$orderTable = $orderResource->getMainTable();
/** Maybe customer is Guest try to load from order */
if (!$customerData) {
$select = $orderConnection->select()->from(
$orderTable,
[
'email' => 'customer_email',
'firstname' => 'customer_firstname',
'lastname' => 'customer_lastname',
'group_id' => 'customer_group_id'
]
)->where(
'customer_email = ?',
$email
)->order(['entity_id DESC'])
->limit(1);
$customerData = $orderConnection->fetchRow($select);
}
// get group name
try {
if (isset($customerData['group_id']) && $customerData['group_id'] !== null) {
$customerData['group'] = $this->groupRepository->getById($customerData['group_id'])->getCode();
}
} catch (NoSuchEntityException $e) {
$customerData['group'] = null;
}
// lifetime sales
$select = $orderConnection->select()->from(
$orderTable,
['lifetime_sales' => 'SUM(subtotal_invoiced)']
)->where('customer_email LIKE ?', $email);
$select_res = $orderConnection->fetchOne($select);
$lifetimeSales = isset($select_res) && is_numeric($select_res) ? $select_res : 0;
$customerData['lifetime_sales'] = $this->customerOrder->formatPrice($lifetimeSales);
// format created_at
if (isset($customerData['created_at']) && $customerData['created_at']) {
$customerData['created_at'] = $this->customerOrder->formatDate($customerData['created_at'], \IntlDateFormatter::MEDIUM);
} else {
$customerData['created_at'] = '-';
}
return $customerData;
}
}
| true |
b8d12cae6d347f0586121ff9ff283d30c9c569eb | PHP | DanielTorres31/miaudote-api | /utils/routeUtils.php | UTF-8 | 371 | 2.515625 | 3 | [] | no_license | <?php
function getIdNaRequisicao() {
$path = $_SERVER['REQUEST_URI'];
$path = removeParametrosPath($path);
$paths = explode("/", $path);
return $paths[count($paths) - 1];
}
function removeParametrosPath($path) {
return explode("?", $path)[0];
}
function getBody() {
$body = file_get_contents("php://input");
return json_decode($body);
}
?> | true |
6e95922a984415f733ebe92a7058e14ba129a1cb | PHP | kamaslau/doc4apis | /src/application/controllers/User.php | UTF-8 | 11,917 | 2.609375 | 3 | [] | no_license | <?php
defined('BASEPATH') or exit('此文件不可被直接访问');
/**
* User 类
*
* 用户相关功能
*
* @version 1.0.0
* @author Kamas 'Iceberg' Lau <kamaslau@dingtalk.com>
* @copyright ICBG <www.bingshankeji.com>
*/
class User extends CI_Controller
{
/* 类名称小写,应用于多处动态生成内容 */
public $class_name;
/* 类名称中文,应用于多处动态生成内容 */
public $class_name_cn;
/* 主要相关表名 */
public $table_name;
/* 主要相关表的主键名*/
public $id_name;
/* 视图文件所在目录名 */
public $view_root;
/* 需要显示的字段 */
public $data_to_display;
public function __construct()
{
parent::__construct();
// $this->output->enable_profiler(TRUE);
// 未登录用户转到登录页
if ($this->session->logged_in !== TRUE) redirect(base_url('login'));
// 向类属性赋值
$this->class_name = strtolower(__CLASS__);
$this->class_name_cn = '用户'; // 改这里……
$this->table_name = 'user'; // 和这里……
$this->id_name = 'user_id'; // 还有这里,OK,这就可以了
$this->view_root = $this->class_name;
// 设置需要自动在视图文件中生成显示的字段
$this->data_to_display = array(
'mobile' => '手机号',
'lastname' => '姓',
'firstname' => '名',
'role' => '角色',
'level' => '级别',
);
// 设置并调用Basic核心库
$basic_configs = array(
'table_name' => $this->table_name,
'id_name' => $this->id_name,
'view_root' => $this->view_root,
);
$this->load->library('basic', $basic_configs);
}
/**
* 列表页
*/
public function index()
{
// 若角色为成员,则转到相应的详情页面
if ($this->session->role === '成员')
redirect(base_url('user/detail?id=' . $this->session->user_id));
// 页面信息
$data = array(
'title' => $this->class_name_cn . '列表',
'class' => $this->class_name . ' ' . $this->class_name . '-index',
);
// 将需要显示的数据传到视图以备使用
$data['data_to_display'] = $this->data_to_display;
// 筛选条件
$condition = NULL;
// 非系统级管理员仅可看到自己企业相关的信息,否则可接收传入的参数
if (!empty($this->session->biz_id)) :
$condition['biz_id'] = $this->session->biz_id;
elseif ($this->session->role === '管理员') :
$condition['biz_id'] = $this->input->get_post('biz_id');
endif;
// 排序条件
$order_by['biz_id'] = 'DESC';
$order_by['role'] = 'DESC';
$order_by['level'] = 'DESC';
// Go Basic!
$this->basic->index($data, array_filter($condition), $order_by);
}
/**
* 详情页
*/
public function detail()
{
// 检查是否已传入必要参数
$id = $this->input->get_post('id');
if (empty($id))
redirect(base_url('error/code_404'));
// 页面信息
$data = array(
'title' => NULL,
'class' => $this->class_name . ' ' . $this->class_name . '-detail',
);
// 获取页面数据
$data['item'] = $this->basic_model->select_by_id($id);
// 若存在相关数据
if (!empty($data['item'])) :
// 若存在所属企业,则获取企业信息
if (!empty($data['item']['biz_id'])) :
$data['biz'] = $this->basic->get_by_id($data['item']['biz_id'], 'biz', 'biz_id');
endif;
// 生成页面标题
$data['title'] = $data['item']['lastname'] . $data['item']['firstname'];
endif;
$this->load->view('templates/header', $data);
$this->load->view($this->view_root . '/detail', $data);
$this->load->view('templates/footer', $data);
}
/**
* 个人主页(详情页)
*/
public function mine()
{
// 检查是否已传入必要参数
$id = $this->session->user_id;
if ($id === NULL)
redirect(base_url('error/code_404'));
// 页面信息
$data = array(
'title' => '我的',
'class' => $this->class_name . ' ' . $this->class_name . '-mine',
);
// 获取页面数据
$data['item'] = $this->basic_model->select_by_id($id);
// 若存在所属企业,则获取企业信息
if (!empty($data['item']) && !empty($data['item']['biz_id'])) :
$data['biz'] = $this->basic->get_by_id($data['item']['biz_id'], 'biz', 'biz_id');
endif;
$this->load->view('templates/header', $data);
$this->load->view($this->view_root . '/mine', $data);
$this->load->view('templates/footer', $data);
}
/**
* 回收站
*/
public function trash()
{
// 操作可能需要检查操作权限
$role_allowed = array('管理员', '经理'); // 角色要求
$min_level = 30; // 级别要求
$this->basic->permission_check($role_allowed, $min_level);
// 页面信息
$data = array(
'title' => $this->class_name_cn . '回收站',
'class' => $this->class_name . ' ' . $this->class_name . '-trash',
);
// 将需要显示的数据传到视图以备使用
$data['data_to_display'] = $this->data_to_display;
// 筛选条件
$condition = NULL;
// 非系统级管理员仅可看到自己企业相关的信息
if (!empty($this->session->biz_id))
$condition['biz_id'] = $this->session->biz_id;
// 排序条件
$order_by['time_delete'] = 'DESC';
// Go Basic!
$this->basic->trash($data, $condition, $order_by);
}
/**
* 创建
*/
public function create()
{
// 操作可能需要检查操作权限
$role_allowed = array('管理员', '经理'); // 角色要求
$min_level = 30; // 级别要求
$this->basic->permission_check($role_allowed, $min_level);
// 页面信息
$data = array(
'title' => '创建' . $this->class_name_cn,
'class' => $this->class_name . ' ' . $this->class_name . '-create',
);
// 获取所属企业数据
$biz_id = $this->input->get_post('biz_id') ? $this->input->get_post('biz_id') : NULL;
if (!empty($biz_id))
$data['biz'] = $this->basic->get_by_id($biz_id, 'biz', 'biz_id');
// 待验证的表单项
// 验证规则 https://www.codeigniter.com/user_guide/libraries/form_validation.html#rule-reference
$this->form_validation->set_rules('biz_id', '所属企业', 'trim|is_natural_no_zero');
$this->form_validation->set_rules('mobile', '手机号', 'trim|required|is_natural|exact_length[11]');
$this->form_validation->set_rules('lastname', '姓', 'trim|required');
$this->form_validation->set_rules('firstname', '名', 'trim|required');
$this->form_validation->set_rules('gender', '性别', 'trim');
$this->form_validation->set_rules('email', 'Email', 'trim|valid_email');
$this->form_validation->set_rules('role', '角色', 'trim');
$this->form_validation->set_rules('level', '等级', 'trim|is_natural|max_length[2]|less_than_equal_to[' . $this->session->level . ']');
// 需要存入数据库的信息
$data_to_create = array(
'biz_id' => $this->input->post('biz_id'),
'mobile' => $this->input->post('mobile'),
'password' => SHA1(substr($this->input->post('mobile'), -6)),
'lastname' => $this->input->post('lastname'),
'firstname' => $this->input->post('firstname'),
'gender' => $this->input->post('gender'),
'email' => $this->input->post('email'),
'role' => $this->input->post('role'),
'level' => $this->input->post('level'),
);
// Go Basic!
$this->basic->create($data, $data_to_create);
}
/**
* 编辑单行
*/
public function edit()
{
// 操作可能需要检查操作权限
$role_allowed = array('管理员', '经理', '成员', '设计师', '工程师'); // 角色要求
$min_level = 10; // 级别要求
$this->basic->permission_check($role_allowed, $min_level);
// 非管理员、经理角色的用户仅可修改自己的信息
if (!in_array($this->session->role, array('管理员', '经理')) && $this->session->user_id !== $this->input->get_post('id'))
redirect(base_url('error/permission_role'));
// 页面信息
$data = array(
'title' => '编辑' . $this->class_name_cn,
'class' => $this->class_name . ' ' . $this->class_name . '-edit',
);
// 待验证的表单项
// "成员"角色的用户仅可修改部分信息
if ($this->session->role === '管理员' || $this->session->role === '经理') :
$this->form_validation->set_rules('mobile', '手机号', 'trim|required|is_natural|exact_length[11]');
$this->form_validation->set_rules('lastname', '姓', 'trim|required');
$this->form_validation->set_rules('firstname', '名', 'trim|required');
$this->form_validation->set_rules('role', '角色', 'trim');
// 不可授予他人比自己高的等级
if ($this->session->user_id !== $this->input->get_post('id')) :
$max_level = $this->session->level - 1;
else :
$max_level = $this->session->level;
endif;
$this->form_validation->set_rules('level', '等级', 'trim|is_natural|max_length[2]|less_than_equal_to[' . $max_level . ']');
endif;
$this->form_validation->set_rules('nickname', '昵称', 'trim');
$this->form_validation->set_rules('gender', '性别', 'trim');
$this->form_validation->set_rules('dob', '生日(公历)', 'trim');
$this->form_validation->set_rules('avatar', '头像URL', 'trim|valid_url');
$this->form_validation->set_rules('email', 'Email', 'trim|valid_email');
// 对生日做特别处理
$dob = $this->input->post('dob');
if ($dob === '0000-00-00' || empty($dob)) $dob = NULL;
// 需要编辑的信息
$data_to_edit = array(
'nickname' => $this->input->post('nickname'),
'gender' => $this->input->post('gender'),
'dob' => $dob,
'avatar' => $this->input->post('avatar'),
'email' => $this->input->post('email'),
);
if ($this->session->role === '管理员' || $this->session->role === '经理') :
$data_to_edit['mobile'] = $this->input->post('mobile');
$data_to_edit['lastname'] = $this->input->post('lastname');
$data_to_edit['firstname'] = $this->input->post('firstname');
$data_to_edit['role'] = $this->input->post('role');
$data_to_edit['level'] = $this->input->post('level');
endif;
// Go Basic!
$this->basic->edit($data, $data_to_edit);
}
/**
* 删除单行或多行项目
*/
public function delete()
{
// 操作可能需要检查操作权限
$role_allowed = array('管理员', '经理'); // 角色要求
$min_level = 30; // 级别要求
$this->basic->permission_check($role_allowed, $min_level);
$op_name = '删除'; // 操作的名称
$op_view = 'delete'; // 视图文件名
// 页面信息
$data = array(
'title' => $op_name . $this->class_name_cn,
'class' => $this->class_name . ' ' . $this->class_name . '-' . $op_view,
);
// 将需要显示的数据传到视图以备使用
$data['data_to_display'] = $this->data_to_display;
// 待验证的表单项
$this->form_validation->set_rules('password', '密码', 'trim|required|min_length[6]|max_length[20]');
// 需要存入数据库的信息
$data_to_edit = array(
'time_delete' => date('Y-m-d H:i:s'), // 批量删除
);
// Go Basic!
$this->basic->bulk($data, $data_to_edit, $op_name, $op_view);
}
/**
* 恢复单行或多行项目
*/
public function restore()
{
// 操作可能需要检查操作权限
$role_allowed = array('管理员', '经理'); // 角色要求
$min_level = 30; // 级别要求
$this->basic->permission_check($role_allowed, $min_level);
$op_name = '恢复'; // 操作的名称
$op_view = 'restore'; // 视图文件名
// 页面信息
$data = array(
'title' => $op_name . $this->class_name_cn,
'class' => $this->class_name . ' ' . $this->class_name . '-' . $op_view,
);
// 将需要显示的数据传到视图以备使用
$data['data_to_display'] = $this->data_to_display;
// 待验证的表单项
$this->form_validation->set_rules('password', '密码', 'trim|required|min_length[6]|max_length[20]');
// 需要存入数据库的信息
$data_to_edit = array(
'time_delete' => NULL, // 批量恢复
);
// Go Basic!
$this->basic->bulk($data, $data_to_edit, $op_name, $op_view);
}
}
/* End of file User.php */
/* Location: ./application/controllers/User.php */
| true |
78ccd23bc840c87ef92f2c82c79153818d7fb64f | PHP | joelk123/SuiviTR | /data.php | UTF-8 | 1,766 | 2.9375 | 3 | [] | no_license | <?php
$hostname="localhost";
$database="suivitr";
$login = "root";
$password ="";
try{
$db=new \PDO("mysql:host=$hostname;dbname=$database",$login, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $ex)
{
throw new Error("Erreur de connexion à la base de données : ".$ex->getMessage());
}
$sql = "SELECT code_tr,titre "
." FROM tr";
$req = $db->prepare($sql);
try {
$req->execute();
} catch (PDOException $ex) {
die($ex->getMessage());
throw new Error("Erreur SQL ".$ex->getMessage());
}
$donnee[] = array(
'Nom' => "",
'Type' => "",
'ID' => ""
);
$array = $req->fetchAll( PDO::FETCH_ASSOC );
foreach($array as $row){
$donnee[] = array(
'Nom' => utf8_encode($row['titre']),
'Type' => 'TR',
'ID' => $row["code_tr"]
);
}
$sql2 = "SELECT nom,prenom,num "
." FROM eleves";
$req2 = $db->prepare($sql2);
try {
$req2->execute();
} catch (PDOException $ex) {
die($ex->getMessage());
throw new Error("Erreur SQL ".$ex->getMessage());
}
$array2 = $req2->fetchAll( PDO::FETCH_ASSOC );
foreach($array2 as $row){
$donnee[] = array(
'Nom' => utf8_encode($row['nom']." ".$row['prenom']),
'Type' => 'Eleve',
'ID' => $row["num"]
);}
echo json_encode($donnee);
?> | true |
d55692a70de59e3901db9100de5ee4f0722046c3 | PHP | abaumer/php-login | /4-full-mvc-framework/controllers/user.php | UTF-8 | 2,850 | 2.875 | 3 | [
"MIT"
] | permissive | <?php
class User extends Controller {
public function __construct() {
// a little note on that (seen on StackOverflow):
// "As long as myChild has no constructor, the parent constructor will be called / inherited."
// This means wenn a class thats extends another class has a __construct, it needs to construct
// the parent in that constructor, like this:
parent::__construct();
// VERY IMPORTANT: All controllers/areas that should only be useable by logged-in users
// need this line! Otherwise not-logged in users could do actions
// if all of your pages should only be useable by logged-in users: Put this line into
// libs/Controller->__construct
// TODO: test this!
Auth::handleLogin();
}
public function index() {
// get all users (of the logged in user)
$this->view->users = $this->model->getAllUsers();
$this->view->errors = $this->model->errors;
$this->view->render('users/index');
}
public function create() {
$registration_successful = $this->model->registerNewUser();
// TODO: find a better solution than always doing this by hand
// put the errors from the login model into the view (so we can display them in the view)
$this->view->errors = $this->model->errors;
if ($registration_successful == true) {
$this->view->users = $this->model->getAllUsers();
$this->view->render('users/index');
} else {
$this->view->users = $this->model->getAllUsers();
$this->view->render('users/index');
}
// $this->model->registerNewUser();
// header('location: ' . URL . 'user');
}
public function edit($user_id) {
$this->view->user = $this->model->getUser($user_id);
$this->view->errors = $this->model->errors;
$this->view->render('users/edit');
}
public function editSave($user_id) {
if(!$_POST){
header('location: ' . URL . 'user');
}
// do editSave() in the note_model, passing user_id from URL and note_text from POST via params
$save_successful = $this->model->editSave();
if($save_successful === true) {
$this->view->success = $this->model->errors;
$this->view->users = $this->model->getAllUsers();
$this->view->render('users/index');
} else {
$this->view->errors = $this->model->errors;
$this->view->user = $this->model->getUser($user_id);
$this->view->render('users/edit');
}
}
public function delete($note_id) {
$this->model->delete($note_id);
header('location: ' . URL . 'user');
}
} | true |
e85bf581eb48ae5df22923c4a46a724d8ff6bca2 | PHP | PasDeBras/openclassrooms_p4 | /model/CommentManager.php | UTF-8 | 1,939 | 2.75 | 3 | [] | no_license | <?php
namespace OpenClassrooms\P4\Model;
require_once('model/Manager.php');
class CommentManager extends Manager
{
public function getComments($postId)
{
$db = $this->dbConnect();
$comments = $db->prepare('SELECT id, author, comment, DATE_FORMAT(comment_date, \'%d/%m/%Y à %Hh%imin%ss\') AS comment_date_fr FROM comments WHERE post_id = ? ORDER BY comment_date DESC');
$comments->execute(array($postId));
return $comments;
}
public function postComment($postId, $author, $comment)
{
$db = $this->dbConnect();
$comments = $db->prepare('INSERT INTO comments(post_id, author, comment, comment_date) VALUES(?, ?, ?, NOW())');
$affectedLines = $comments->execute(array($postId, $author, $comment));
return $affectedLines;
}
public function deleteComment($commentId)
{
$db = $this->dbConnect();
$comment = $db->prepare('DELETE FROM `comments` WHERE `id` = ?');
$deleteComment = $comment->execute(array($commentId));
return $deleteComment;
}
public function flagComment($commentId)
{
$db = $this->dbConnect();
$flag = $db->prepare('UPDATE comments SET flagged = flagged + 1 WHERE ID = ?');
$flagged = $flag->execute(array($commentId));
return $flagged;
}
public function unflagComment($commentId)
{
$db = $this->dbConnect();
$unflag = $db->prepare('UPDATE comments SET flagged = 0 WHERE ID = ?');
$unflagged = $unflag->execute(array($commentId));
return $unflagged;
}
public function getFlaggedComments()
{
$db = $this->dbConnect();
$req = $db->query('SELECT id, flagged, post_id, author, comment, DATE_FORMAT(comment_date, \'%d/%m/%Y à %Hh%imin%ss\') AS comment_date_fr FROM comments WHERE flagged > 0 ORDER BY flagged DESC');
return $req;
}
} | true |
05ee7beff3f4bb760531298a0c4ebddb68c60942 | PHP | CityNexus/CNMultiTenant | /packages/CityNexus/DataStore/src/helpers/AWS.php | UTF-8 | 2,677 | 2.765625 | 3 | [
"MIT"
] | permissive | <?php
/**
* Created by PhpStorm.
* User: sean
* Date: 10/25/16
* Time: 5:02 PM
*/
namespace CityNexus\DataStore;
class AWS
{
public function getS3Details($s3Bucket, $region, $acl = 'private') {
// Options and Settings
$awsKey = (!empty(config('datastore.S3_key')) ? config('datastore.S3_key') : S3_KEY);
$awsSecret = (!empty(config('datastore.S3_secret')) ? config('datastore.S3_secret') : S3_SECRET);
$algorithm = "AWS4-HMAC-SHA256";
$service = "s3";
$date = gmdate("Ymd\THis\Z");
$shortDate = gmdate("Ymd");
$requestType = "aws4_request";
$expires = "86400"; // 24 Hours
$successStatus = "201";
$url = "//{$s3Bucket}.{$service}-{$region}.amazonaws.com";
// Step 1: Generate the Scope
$scope = [
$awsKey,
$shortDate,
$region,
$service,
$requestType
];
$credentials = implode('/', $scope);
// Step 2: Making a Base64 Policy
$policy = [
'expiration' => gmdate('Y-m-d\TG:i:s\Z', strtotime('+2 hours')),
'conditions' => [
['bucket' => $s3Bucket],
['acl' => $acl],
['starts-with', '$key', ''],
['starts-with', '$Content-Type', ''],
['success_action_status' => $successStatus],
['x-amz-credential' => $credentials],
['x-amz-algorithm' => $algorithm],
['x-amz-date' => $date],
['x-amz-expires' => $expires],
]
];
$base64Policy = base64_encode(json_encode($policy));
// Step 3: Signing your Request (Making a Signature)
$dateKey = hash_hmac('sha256', $shortDate, 'AWS4' . $awsSecret, true);
$dateRegionKey = hash_hmac('sha256', $region, $dateKey, true);
$dateRegionServiceKey = hash_hmac('sha256', $service, $dateRegionKey, true);
$signingKey = hash_hmac('sha256', $requestType, $dateRegionServiceKey, true);
$signature = hash_hmac('sha256', $base64Policy, $signingKey);
// Step 4: Build form inputs
// This is the data that will get sent with the form to S3
$inputs = [
'Content-Type' => '',
'acl' => $acl,
'success_action_status' => $successStatus,
'policy' => $base64Policy,
'X-amz-credential' => $credentials,
'X-amz-algorithm' => $algorithm,
'X-amz-date' => $date,
'X-amz-expires' => $expires,
'X-amz-signature' => $signature
];
return compact('url', 'inputs');
}
} | true |
625736c0ee30822863c3ae677d757770e18f7382 | PHP | yangp6/laravel_blog | /app/Model/Config.php | UTF-8 | 480 | 2.53125 | 3 | [] | no_license | <?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
/**
* Class Config 网站配置模型
* @package App\Model
*/
class Config extends Model
{
protected $table = "configs";
protected $primaryKey = "id";
public $timestamps = false;
protected $guarded = [];
//修改排序
public function changeOrder($data)
{
$conf = $this->find($data['id']);
$conf->order = $data['order'];
return $conf->update();
}
}
| true |
cf1b9c050b9ce1db67d196b72793732e5dbf2661 | PHP | MKelm/papaya-cms | /papaya-lib/system/Papaya/Ui/Dialog/Errors.php | UTF-8 | 2,134 | 2.734375 | 3 | [] | no_license | <?php
/**
* Simple error collector for dialogs
*
* @copyright 2010 by papaya Software GmbH - All rights reserved.
* @link http://www.papaya-cms.com/
* @license http://www.gnu.org/licenses/old-licenses/gpl-2.0.html GNU General Public License, version 2
*
* You can redistribute and/or modify this script under the terms of the GNU General Public
* License (GPL) version 2, provided that the copyright and license notes, including these
* lines, remain unmodified. papaya is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
*
* @package Papaya-Library
* @subpackage Ui
* @version $Id: Errors.php 35573 2011-03-29 10:48:18Z weinert $
*/
/**
* Simple error collector for dialogs.
*
* Holds a list of errors and allows to iterate them.
*
* @package Papaya-Library
* @subpackage Ui
*/
class PapayaUiDialogErrors implements IteratorAggregate, Countable {
/**
* Error list
* @var array
*/
protected $_errors = array();
/**
* add a new error to the list.
*
* @param Exception $exception
* @param Object $source
*/
public function add(Exception $exception, $source = NULL) {
$this->_errors[] = array(
'exception' => $exception,
'source' => $source,
);
}
/**
* clear internal error list.
*/
public function clear() {
$this->_errors = array();
}
/**
* Countable interface, return element count.
*
* @return integer
*/
public function count() {
return count($this->_errors);
}
/**
* IteratorAggregate interface, return ArrayIterator for internal array.
*
* @return ArrayIterator
*/
public function getIterator() {
return new ArrayIterator($this->_errors);
}
public function getSourceCaptions() {
$result = array();
foreach ($this->_errors as $error) {
if (isset($error['source']) &&
$error['source'] instanceOf PapayaUiDialogField) {
$caption = $error['source']->getCaption();
if (!empty($caption)) {
$result[] = $caption;
}
}
}
return $result;
}
} | true |
2b94b90567f17043c8b5493895e91149ce49c113 | PHP | jucarozu/fiscal | /app/Http/Controllers/PropietarioController.php | UTF-8 | 7,280 | 2.546875 | 3 | [] | no_license | <?php
namespace App\Http\Controllers;
use App\Http\Requests;
use Illuminate\Http\Request;
use App\Http\Requests\PropietarioAddForm;
use App\Http\Requests\PropietarioEditForm;
use App\Models\Propietario;
use App\Models\VTPropietario;
use App\Services\GeneralService;
class PropietarioController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$propietarios = VTPropietario::orderBy('desde')
->get();
return response()->json(['propietarios' => $propietarios]);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$propietario = VTPropietario::find($id);
return response()->json(['propietario' => $propietario]);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\PropietarioAddForm $request
* @return \Illuminate\Http\Response
*/
public function store(PropietarioAddForm $request)
{
$placa = $request->input('placa');
$valid_desde = strtotime($request->input('desde'));
$valid_hasta = !empty($request->input('hasta')) ? strtotime($request->input('hasta')) : null;
// Validar si existen propietarios registrados para el vehículo en el rango de fechas especificado.
$propietarios = Propietario::where('placa', $placa)
->orderBy('desde')
->get();
$cruceFechas = false;
foreach ($propietarios as $prop)
{
$base_desde = strtotime($prop->desde);
$base_hasta = !empty($prop->hasta) ? strtotime($prop->hasta) : null;
if ($valid_desde == null || $base_desde == null)
{
$cruceFechas = true;
break;
}
if ($base_desde <= $valid_desde && ($base_hasta == null || $base_hasta >= $valid_desde))
{
$cruceFechas = true;
break;
}
if ($valid_hasta != null)
{
if ($base_desde <= $valid_hasta && ($base_hasta == null || $base_hasta >= $valid_hasta))
{
$cruceFechas = true;
break;
}
}
if ($valid_desde <= $base_desde && ($valid_hasta == null || $valid_hasta >= $base_desde))
{
$cruceFechas = true;
break;
}
if ($base_hasta != null)
{
if ($valid_desde <= $base_hasta && ($valid_hasta == null || $valid_hasta >= $base_hasta))
{
$cruceFechas = true;
break;
}
}
}
if ($cruceFechas)
{
return response()->json(['error' => 'Ya existe un propietario registrado para el vehículo de placas '.$placa.' en este rango de fechas.'], 422);
}
// Registrar el propietario asociado al vehículo especificado.
if ($request->ajax())
{
$propietario = new Propietario();
$propietario->placa = $request->input('placa');
$propietario->persona = $request->input('persona');
$propietario->fuente = $request->input('fuente');
$propietario->tipo = $request->input('tipo');
$propietario->locatario = $request->input('locatario');
$propietario->desde = $request->input('desde');
$propietario->hasta = $request->input('hasta');
$propietario->usuario = $request->input('usuario');
if (!$propietario->save())
{
return response()->json(['error' => 'internal_error'], 500);
}
return response()->json(['mensaje' => 'Propietario registrado', 'propietario' => $propietario]);
}
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\PropietarioEditForm $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(PropietarioEditForm $request, $id)
{
$persona = $request->input('persona');
$placa = $request->input('placa');
$desde = $request->input('desde');
$hasta = $request->input('hasta');
if (!empty($hasta))
{
$condicion = "(DESDE BETWEEN TO_DATE('".$desde."','YYYY-MM-DD') AND TO_DATE('".$hasta."','YYYY-MM-DD') OR
HASTA BETWEEN TO_DATE('".$desde."','YYYY-MM-DD') AND TO_DATE('".$hasta."','YYYY-MM-DD'))";
}
else
{
$condicion = "(DESDE >= TO_DATE('".$desde."','YYYY-MM-DD') OR
HASTA IS NULL)";
}
$validaFechas = Propietario::where('persona', '<>', $persona)
->where('placa', $placa)
->whereRaw($condicion)
->get();
if (count($validaFechas) > 0)
{
return response()->json(['error' => 'Ya existe un propietario registrado para el vehículo de placas '.$placa.' en este rango de fechas.'], 422);
}
if ($request->ajax())
{
$propietario = Propietario::find($id);
$propietario->persona = $request->input('persona');
$propietario->fuente = $request->input('fuente');
$propietario->tipo = $request->input('tipo');
$propietario->locatario = $request->input('locatario');
$propietario->desde = $request->input('desde');
$propietario->hasta = $request->input('hasta');
$propietario->fecha_registra = GeneralService::getFechaActual('Y-m-d h:i:s');
if (!$propietario->save())
{
return response()->json(['error' => 'internal_error'], 500);
}
return response()->json(['mensaje' => 'Propietario actualizado', 'propietario' => $propietario]);
}
}
/**
* Display the specified resource by filters.
*
* @param int $placa
* @param int $tipo_doc
* @param int $numero_doc
* @return \Illuminate\Http\Response
*/
public function getByFilters($placa, $tipo_doc, $numero_doc)
{
// Obtener los propietarios con información actualizada.
$propietarios = VTPropietario::whereRaw($placa != "0" ? ('LOWER(PLACA) = \''.strtolower($placa).'\'') : ('PLACA = PLACA'))
->whereRaw($tipo_doc != 0 ? ('TIPO_DOC = '.$tipo_doc) : ('TIPO_DOC = TIPO_DOC'))
->whereRaw($numero_doc != "0" ? ('NUMERO_DOC = '.$numero_doc) : ('NUMERO_DOC = NUMERO_DOC'))
->orderBy('placa')
->orderBy('desde', 'DESC')
->get();
return response()->json(['propietarios' => $propietarios]);
}
}
| true |
bb0eabfb06c28f1481f521068d57d4d68d5dfd11 | PHP | vicpril/idea-lv-vue | /app/Models/Issue.php | UTF-8 | 1,742 | 2.53125 | 3 | [] | no_license | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Issue extends Model
{
protected $fillable = [
'year',
'tom',
'no',
'part',
'full_no',
'file_title_ru',
'file_title_en',
];
protected $appends = [
'editLink',
];
public $timestamps = false;
public function articles()
{
return $this->hasMany('App\Models\Article')->orderBy('position');
}
/*
* Get links
*/
public function getEditLinkAttribute()
{
return route('issues.edit', $this->id);
}
public function getLocTitleAttribute()
{
switch (app()->getLocale()) {
case 'ru':return $this->file_title_ru;
break;
case 'en':return $this->file_title_en;
break;
}
}
/*
* Scopes
*/
public function scopeWithStatus($query, $status)
{
$query->whereHas('articles', function ($query) use ($status) {
$query->whereHas('status', function ($query) use ($status) {
$query->where('title_en', $status);
});
})->get();
}
/*
* Filters
*/
public function filterArticlesByStatus($status)
{
$this->loadMissing(['articles', 'articles.status']);
$this->articles = $this->articles->filter(function ($article) use ($status) {
return $article->status->title_en == $status;
})->values();
return $this;
}
public function published()
{
return $this->filterArticlesByStatus('public');
}
public function unpublished()
{
return $this->filterArticlesByStatus('private');
}
}
| true |
e101e9293cfaeb0282210c0356ffee8fbf36136b | PHP | hashshura/line-bot-tutorial | /handler/memeid.php | UTF-8 | 950 | 2.640625 | 3 | [] | no_license | <?php
use \LINE\LINEBot\MessageBuilder\TextMessageBuilder as TextMessageBuilder;
function memeid($query, $userId){
$URL = 'http://version1.api.memegenerator.net/Generators_Search';
$apiKey = 'YOUR_MEMEGENERATOR_API_KEY';
if ($query == null){
$result = new TextMessageBuilder("Meme Generator\n\nUsage:\n/memeid query\n/meme memeid topText|bottomText\n\nExample:\n/memeid One Does Not Simply\n/meme 689854 one does not simply|make memes using line messenger");
} else {
$query = urlencode($query);
$URL = $URL . '?q=' . $query;
$URL = $URL . '&apiKey=' . $apiKey;
$json = file_get_contents($URL);
$json = json_decode($json, true);
$generatorID = $json['result'][0]['generatorID'];
if ($generatorID == null){
$result = new TextMessageBuilder('GeneratorID not found.');
} else {
$result = new TextMessageBuilder('GeneratorID: ' . $generatorID);
}
}
return $result;
}
| true |
07d41b994ce33ea952251faa6bcc92e4c8fe1ea0 | PHP | lanmediaservice/lms-video-2.x | /src/app/libs/lib/Lms/Ufs/Index.php | UTF-8 | 1,064 | 2.59375 | 3 | [] | no_license | <?php
class Lms_Ufs_Index {
static $shemaList = array(
':\\' => array('pos' => 1, 'name' => 'local'),
':/' => array('pos' => 1, 'name' => 'local'),
"/" => array('pos' => 0, 'name' => 'local'),
"smb://" => array('pos' => 0, 'name' => 'smb'),
"ftp://" => array('pos' => 0, 'name' => 'ftp'),
"file://" => array('pos' => 0, 'name' => 'local'),
"file:///" => array('pos' => 0, 'name' => 'local'),
"file://localhost/" => array('pos' => 0, 'name' => 'local'),
"file:///localhost/" => array('pos' => 0, 'name' => 'local'),
);
static private $defaultModule = 'local';
static public function findModule($uri)
{
foreach (self::$shemaList as $partUri => $uriConfig)
{
if (Lms_Text::pos($uri, $partUri) === $uriConfig['pos'])
{
return $uriConfig['name'];
}
}
return self::$defaultModule;
}
}
?> | true |
888b4e529019a74132864a61f3de0bab439b5299 | PHP | felipecarioca/ForumPHP | /model/Login.php | UTF-8 | 1,435 | 2.84375 | 3 | [] | no_license | <?
class Login extends DB {
private $usuario;
public function Logar($usuario, $senha) {
if(empty($usuario) || empty($senha))
return $this->DadosNaoPreenchidos();
$sql = "SELECT * FROM usuario
WHERE usuario = :usuario AND senha = :senha";
$query = $this->db()->prepare($sql);
$query->execute(array(
':usuario' => $usuario,
':senha' => md5($senha)
));
$dados = $query->fetchAll();
if($query->rowCount()) {
$usuario = new Usuario('', '', '');
$usuario->Find($dados[0]['id_usuario']);
$this->setUsuario($usuario);
return $this->DadosValidados();
}
return $this->DadosInvalidos();
}
private function getUsuario() {
return $this->usuario;
}
private function setUsuario($usuario) {
$this->usuario = $usuario;
}
private function DadosNaoPreenchidos() {
$_SESSION['loginError'] = "Usuário ou senha não preenchidos!";
carregaPagina("../view/index.php");
}
private function DadosInvalidos() {
$_SESSION['loginError'] = "Usuário ou senha inválidos!";
carregaPagina("../view/index.php");
}
private function DadosValidados() {
$_SESSION['user_data']['nome'] = $this->getUsuario()->getNome();
$_SESSION['user_data']['senha'] = $this->getUsuario()->getSenha();
$_SESSION['user_data']['usuario'] = $this->getUsuario()->getUsuario();
$_SESSION['user_data']['id_usuario'] = $this->getUsuario()->getId();
carregaPagina('../view/forum.php');
}
} | true |
236e3a9db9a0f6901d38783c93f22a39a71043d8 | PHP | LinioPay/idle | /src/Job/Jobs/MessageJob.php | UTF-8 | 2,547 | 2.515625 | 3 | [] | permissive | <?php
declare(strict_types=1);
namespace LinioPay\Idle\Job\Jobs;
use LinioPay\Idle\Config\IdleConfig;
use LinioPay\Idle\Job\Exception\InvalidJobParameterException;
use LinioPay\Idle\Job\Worker as WorkerInterface;
use LinioPay\Idle\Job\WorkerFactory as WorkerFactoryInterface;
use LinioPay\Idle\Message\Message as MessageInterface;
use LinioPay\Idle\Message\MessageFactory as MessageFactoryInterface;
class MessageJob extends DefaultJob
{
public const IDENTIFIER = 'message';
/** @var MessageInterface */
protected $message;
/** @var MessageFactoryInterface */
protected $messageFactory;
public function __construct(IdleConfig $idleConfig, MessageFactoryInterface $messageFactory, WorkerFactoryInterface $workerFactory)
{
$this->idleConfig = $idleConfig;
$this->messageFactory = $messageFactory;
$this->workerFactory = $workerFactory;
}
public function setParameters(array $parameters = []) : void
{
$this->message = $parameters['message'] = is_a($parameters['message'] ?? [], MessageInterface::class)
? $parameters['message']
: $this->messageFactory->createMessage($parameters['message'] ?? []);
$config = $this->getMessageJobSourceConfig();
parent::setParameters(array_merge_recursive($config['parameters'] ?? [], $parameters));
}
public function validateParameters() : void
{
if (!is_a($this->message, MessageInterface::class)) {
throw new InvalidJobParameterException($this, 'message');
}
}
protected function buildWorker(string $workerIdentifier, array $workerParameters) : WorkerInterface
{
return $this->workerFactory->createWorker($workerIdentifier, array_merge(
$workerParameters,
['job' => $this, 'message' => $this->message]
));
}
/**
* Obtain the list of workers which will be responsible for processing the given Message.
*/
protected function getJobWorkersConfig() : array
{
$config = $this->getMessageJobSourceConfig();
return $config['parameters']['workers'] ?? [];
}
protected function getMessageJobSourceConfig() : array
{
$messageJobParameters = $this->idleConfig->getJobParametersConfig(self::IDENTIFIER);
$messageTypeIdentifier = $this->message->getIdleIdentifier();
$messageSourceIdentifier = $this->message->getSourceName();
return $messageJobParameters[$messageTypeIdentifier][$messageSourceIdentifier] ?? [];
}
}
| true |
80a8bbabb2793f87251b45932e7eac42b6a87354 | PHP | jjbc93/EntornoServidor | /privada/CurriculumVitae/Validaciones.php | UTF-8 | 1,616 | 3.171875 | 3 | [] | no_license | <?php
class Validaciones{
public static function validarUsuario($usuario){
$errores=false;
$min=5;
$max=12;
if(empty($usuario)){
$errores="Debe introducir un usuario";
}else if(strlen(trim($usuario))<min || strlen(trim($usuario))>$max){
$errores="Debe tener entre $min y $max caracteres";
}
if($errores){
return $errores;
}else{
return true;
}
}
public static function validarClave($clave){
$errores=false;
$min=5;
$max=12;
if(empty($clave)){
$errores="Debe introducir una clave";
}else if(strlen(trim($clave))<$min || strlen(trim($clave))>$max){
$errores="Debe tener entre $min y $max caracteres";
}
if($errores){
return $errores;
}else{
return true;
}
}
//Recorro el array $campos donde estan guardados, los campos del formulario y entonces digo si el array$entrada que es como $_POST[] en la posición donde hay un value del formulario no tiene valor que la inicialize a ""
/*$campos=["campo1" => "usuario", "campo2" => "clave"];
$entrada['usuario']*/
public static function validarEntrada($entrada,$campos){
foreach ($campos as $clave=>$valor){
if(!isset($entrada[$valor])){
$entrada[$valor]="";
}
}
return $entrada;
}
public static function mostrarDatos($dato){
if(!empty($dato)){
return $dato;
}
}
} | true |
ab3fa7401b12af45b597ba840207ea10381a2f7d | PHP | zhujiangtao123/script | /php/www/product/Taomee/Lib/Util/Page.class.php | UTF-8 | 10,505 | 3 | 3 | [] | no_license | <?php
// +----------------------------------------------------------------------
// | ThinkPHP
// +----------------------------------------------------------------------
// | Copyright (c) 2008 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id$
/**
+------------------------------------------------------------------------------
* 分页显示类
+------------------------------------------------------------------------------
* @category ORG
* @package ORG
* @subpackage Util
* @author liu21st <liu21st@gmail.com>
* @version $Id$
* @example $page = new Page(100, 10) ; echo $page->show() ;
+------------------------------------------------------------------------------
*/
class Page extends Base
{ //类定义开始
/**
+----------------------------------------------------------
* 分页起始行数
+----------------------------------------------------------
* @var integer
* @access protected
+----------------------------------------------------------
*/
protected $first_row;
/**
+----------------------------------------------------------
* 列表每页显示行数
+----------------------------------------------------------
* @var integer
* @access protected
+----------------------------------------------------------
*/
protected $list_rows;
/**
+----------------------------------------------------------
* 页数跳转时要带的参数
+----------------------------------------------------------
* @var integer
* @access protected
+----------------------------------------------------------
*/
protected $parameter;
/**
+----------------------------------------------------------
* 分页总页面数
+----------------------------------------------------------
* @var integer
* @access protected
+----------------------------------------------------------
*/
protected $total_pages;
/**
+----------------------------------------------------------
* 总行数
+----------------------------------------------------------
* @var integer
* @access protected
+----------------------------------------------------------
*/
protected $total_rows;
/**
+----------------------------------------------------------
* 当前页数
+----------------------------------------------------------
* @var integer
* @access protected
+----------------------------------------------------------
*/
protected $now_page;
/**
+----------------------------------------------------------
* 分页的栏的总页数
+----------------------------------------------------------
* @var integer
* @access protected
+----------------------------------------------------------
*/
protected $cool_pages;
/**
+----------------------------------------------------------
* 分页栏每页显示的页数
+----------------------------------------------------------
* @var integer
* @access protected
+----------------------------------------------------------
*/
protected $roll_page;
/**
+----------------------------------------------------------
* 分页记录名称
+----------------------------------------------------------
* @var integer
* @access protected
+----------------------------------------------------------
*/
// 分页显示定制
protected $config = array(
'header' => '条记录', 'prev' => '上一页', 'next' => '下一页', 'first' => '第一页', 'last' => '最后一页'
);
/**
+----------------------------------------------------------
* 架构函数
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param int $total_rows 总的记录数
* @param int $now_page 要的显示的页码
* @param int $list_rows 每页显示记录数
* @param string $parameter 分页跳转的参数
* @return string html
+----------------------------------------------------------
*/
public function __construct($total_rows, $now_page=1, $list_rows = '10', $parameter = '')
{
$this->total_rows = $total_rows;
$this->parameter = $parameter;
$this->roll_page = 5;
$this->list_rows = $list_rows;
$this->total_pages = ceil($this->total_rows / $this->list_rows); //总页数
$this->cool_pages = ceil($this->total_pages / $this->roll_page);
$this->now_page = !empty($now_page) && ($now_page > 0) ?
($now_page > $this->total_pages ?
$this->total_pages : $now_page) : 1;
if (! empty($this->total_pages) && $this->now_page > $this->total_pages) {
$this->now_page = $this->total_pages;
}
$this->first_row = $this->list_rows * ($this->now_page - 1);
}
public function set_config($name, $value)
{
if (isset($this->config[$name])) {
$this->config[$name] = $value;
}
}
/**
+----------------------------------------------------------
* 分页显示
* 用于在页面显示的分页栏的输出
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function show($is_array = false)
{
if (0 == $this->total_rows)
return;
$now_cool_page = ceil($this->now_page / $this->roll_page);
//$url = $_SERVER['REQUEST_URI'] . (strpos($_SERVER['REQUEST_URI'], '?') ? '' : "?") . $this->parameter;
$url = 'http://'.$_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] .'?'. $this->parameter;
//上下翻页字符串
$up_row = $this->now_page - 1;
$down_row = $this->now_page + 1;
if ($up_row > 0) {
$up_page = "[<a href='" . $url . "&page=$up_row'>" . $this->config['prev'] . "</a>]";
}
else {
$up_page = "";
}
if ($down_row <= $this->total_pages) {
$down_page = "[<a href='" . $url . "&page=$down_row'>" . $this->config['next'] . "</a>]";
}
else {
$down_page = "";
}
// << < > >>
if ($now_cool_page == 1) {
$theFirst = "";
$pre_page = "";
}
else {
$pre_row = $this->now_page - $this->roll_page;
$pre_page = "[<a href='" . $url . "&page=$pre_row' >上" . $this->roll_page . "页</a>]";
$theFirst = "[<a href='" . $url . "&page=1' >" . $this->config['first'] . "</a>]";
}
if ($now_cool_page == $this->cool_pages) {
$next_page = "";
$the_end = "";
}
else {
$next_row = $this->now_page + $this->roll_page;
$the_end_row = $this->total_pages;
$next_page = "[<a href='" . $url . "&page=$next_row' >下" . $this->roll_page . "页</a>]";
$the_end = "[<a href='" . $url . "&page=$the_end_row' >" . $this->config['last'] . "</a>]";
}
// 1 2 3 4 5
$link_page = "";
for($i = 1; $i <= $this->roll_page; $i ++) {
$page = ($now_cool_page - 1) * $this->roll_page + $i;
if ($page != $this->now_page) {
if ($page <= $this->total_pages) {
$link_page .= " <a href='" . $url . "&page=$page'> " . $page . " </a>";
}
else {
break;
}
}
else {
if ($this->total_pages != 1) {
$link_page .= " [" . $page . "]";
}
}
}
$page_str = '共' . $this->total_rows . ' ' . $this->config['header'] . '/' . $this->total_pages . '页 ' . $up_page . ' ' . $down_page . ' ' . $theFirst . ' ' . $pre_page . ' ' . $link_page . ' ' . $next_page . ' ' . $the_end;
if ($is_array) {
$page_array['total_rows'] = $this->total_rows;
$page_array['up_page'] = $url . "&page=$up_row";
$page_array['down_page'] = $url . "&page=$down_row";
$page_array['total_pages'] = $this->total_pages;
$page_array['first_page'] = $url . "&page=1";
$page_array['end_page'] = $url . "&page=$the_end_row";
$page_array['next_pages'] = $url . "&page=$next_row";
$page_array['pre_pages'] = $url . "&page=$pre_row";
$page_array['link_pages'] = $link_page;
$page_array['now_page'] = $this->now_page;
return $page_array;
}
return $page_str;
}
/**
* 跳转到第几页
*
* @param string $method form method get or post .
* @return string
*/
public function goto_page($method="get")
{
$url = 'http://'.$_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] .'?'. $this->parameter;
if(false !== strpos($this->parameter, '&')) {
$temp = explode('&', $this->parameter) ;
$hidden = '' ;
foreach ($temp as $val) {
if(!trim($val)) continue ;
$pos = strpos($val, '=') ;
$hidden .= (false === strpos($val, '=')) ? '' : '<input type="hidden" name="'.substr($val, 0, $pos).'" value="'.substr($val, $pos + 1).'" />' ;
}
}
$str = '<form name="frm_page_goto" id="frm_page_goto" method="'.$method.'" action="'.$url.'">' ;
$str.= '第 <input type="text" name="page" id="page_goto" value="" style="width:30px" /> 页' ;
$str.= $hidden ;
$str.= ' <input type="submit" name="frm_page_goto_submit" id="frm_page_goto_submit" value="GO" /> ' ;
$str.= '</form>' ;
return $str ;
}
} //类定义结束
?>
| true |
f8560fa4f93c1799301fd75a10571de180af5325 | PHP | ARCANEDEV/LaravelMetrics | /src/Metrics/Concerns/HasExpressions.php | UTF-8 | 1,004 | 2.6875 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types=1);
namespace Arcanedev\LaravelMetrics\Metrics\Concerns;
use Arcanedev\LaravelMetrics\Expressions\{Expression, Factory};
/**
* Trait HasExpressions
*
* @author ARCANEDEV <arcanedev.maroc@gmail.com>
*/
trait HasExpressions
{
/* -----------------------------------------------------------------
| Main Methods
| -----------------------------------------------------------------
*/
/**
* Get an database expression.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $name
* @param mixed|null $value
* @param array $params
*
* @return \Arcanedev\LaravelMetrics\Expressions\Expression|mixed
*/
protected static function getExpression($query, string $name, $value = null, array $params = []): Expression
{
return Factory::resolveExpression($query, $name, $value, $params);
}
}
| true |