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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
07f61041c717c521afeab2604c3b2535b033a1a8 | PHP | cocoonprojects/welo-backend | /module/TaskManagement/src/TaskManagement/TaskInterface.php | UTF-8 | 1,315 | 2.515625 | 3 | [] | permissive | <?php
namespace TaskManagement;
use Application\Entity\BasicUser;
use Zend\Permissions\Acl\Resource\ResourceInterface;
interface TaskInterface extends ResourceInterface
{
const STATUS_IDEA = 0;
const STATUS_OPEN = 10;
const STATUS_ONGOING = 20;
const STATUS_COMPLETED = 30;
const STATUS_ACCEPTED = 40;
const STATUS_CLOSED = 50;
const STATUS_DELETED = -10;
const STATUS_ARCHIVED = -20;
const ROLE_MEMBER = 'member';
const ROLE_OWNER = 'owner';
/**
* @return string
*/
public function getId();
/**
* @return string
*/
public function getType();
/**
* @return string
*/
public function getOrganizationId();
/**
* @return string
*/
public function getSubject();
/**
* @return string
*/
public function getDescription();
/**
* @return \DateTime
*/
public function getCreatedAt();
/**
* @return User
*/
public function getCreatedBy();
/**
* @return \DateTime
*/
public function getAcceptedAt();
/**
* @return int
*/
public function getStatus();
/**
* @return string
*/
public function getStreamId();
/**
* @return array
*/
public function getMembers();
/**
* @return array
*/
public function getApprovals();
/**
* @param id|BasicUser $user
* @return boolean
*/
public function hasMember($user);
} | true |
ee922506c04aacedaf73f29db2281d8fd86c5766 | PHP | chopins/tklib | /type/src/StringFixedArray.php | UTF-8 | 773 | 2.6875 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
/**
* Toknot (http://toknot.com)
*
* @copyright Copyright (c) 2011 - 2021 Toknot.com
* @license http://toknot.com/GPL-2,0.txt GPL-2.0
* @link https://github.com/chopins/toknot
*/
namespace Toknot\Type;
use Toknot\Type\Text;
/**
* StringArray
*
* @author chopin
*/
class StringFixedArray extends FixedArray
{
protected $head = false;
protected $headOffset = 0;
/**
*
* @param string $str
* @return \SplFixedArray
*/
public static function fromString($str)
{
return self::fromArray(self::split($str));
}
public static function __callStatic($name, $args)
{
return Text::$name(...$args);
}
public function onlyStringTail()
{
$this->head = true;
}
}
| true |
bc21c96cc7ef7ad89d508193f4ed02c7142bcb25 | PHP | Igor-kor/php_patterns | /Prototype/index.php | UTF-8 | 957 | 3.015625 | 3 | [] | no_license | <?php
/**
* Прототип (Prototype)
*
* Порождающий шаблон
*
* Когда необходим объект, похожий на существующий объект,
* либо когда создание будет дороже клонирования.
*/
use Prototype\Sheep;
include "../spl_autoloader.php";
echo "Прототип (Prototype)<br>";
$original = new Sheep('Джолли');
echo $original->getName()."<br>"; // Джолли
echo $original->getCategory()."<br>"; // Горная овечка
echo $original->getLifetime()."<br>"; // Продолжительность жизни
// Клонируем и модифицируем то что нужно
$cloned = clone $original;
$cloned->setName('Долли');
echo $cloned->getName()."<br>"; // Долли
echo $cloned->getCategory()."<br>"; // Горная овечка
echo $cloned->getLifetime()."<br>"; // Продолжительность жизни | true |
8654ec6a8de38d4c4d52675d2024d95f5480d593 | PHP | Shofiul-Alam/magento-app | /src/vendor/magento/framework/Intl/DateTimeFactory.php | UTF-8 | 512 | 2.6875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"AFL-2.1",
"AFL-3.0",
"OSL-3.0",
"MIT"
] | permissive | <?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Framework\Intl;
/**
* Class DateTimeFactory
* @package Magento\Framework
*/
class DateTimeFactory
{
/**
* Factory method for \DateTime
*
* @param string $time
* @param \DateTimeZone $timezone
* @return \DateTime
*/
public function create($time = 'now', \DateTimeZone $timezone = null)
{
return new \DateTime($time, $timezone);
}
}
| true |
8d7b737a455427fcb62dea8cf21bb53fde80d695 | PHP | a707937337/np_cal | /php/post.php | UTF-8 | 858 | 2.65625 | 3 | [] | no_license | <?php
require_once 'lib.php';
$conn = null;
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
echo "ERROR";
} else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = empty($_POST['name']) ? null : $_POST['name'];
$date = empty($_POST['date']) ? null : $_POST['date'];
$event = empty($_POST['value']) ? null : $_POST['value'];
$conn = connect();
$pre_sql = "SELECT * FROM event WHERE name = '$name' AND date = '$date' ";
$res = mysql_query($pre_sql, $conn);
$row = mysql_fetch_assoc($res);
if(!$row) {
$sql = "INSERT INTO event (`name`, `date`, `notes`) VALUES ('$name', '$date', '$event')";
} else {
$id = $row['id'];
$sql = "UPDATE event SET notes = '$event' WHERE id = '$id'";
}
var_dump($sql);
if (!mysql_query($sql, $conn)) {
die('Error: ' . mysql_error());
}
mysql_close($conn);
} | true |
c598c9822c2548731857b1acb3bf4669995dd47d | PHP | rumur/pimpled | /app/Api/Http/Controllers/Auth/RegisterController.php | UTF-8 | 1,330 | 2.71875 | 3 | [
"MIT"
] | permissive | <?php
namespace Pmld\App\Api\Http\Controllers\Auth;
use Pmld\App\Api\Transform\User;
use Pmld\Http\Controller\BaseController;
use Pmld\Http\Exceptions\UnauthorizedException;
class RegisterController extends BaseController
{
/**
* Registered user into the system.
*
* @return mixed|\WP_REST_Response
*
* @throws UnauthorizedException
*/
public function register()
{
$create_from = $this->request->get_body_params();
$input = (object) array_intersect_key( $create_from,
array_fill_keys(['username', 'password', 'email'], false)
);
$update = [
'first_name',
'last_name',
];
/** @var \WP_Error|integer $user */
$user_id = \wp_create_user($input->username, $input->password, $input->email);
if (\is_wp_error($user_id)) {
throw new UnauthorizedException($user_id->get_error_message());
}
/** @var \WP_User $user */
$user = \get_userdata($user_id);
foreach ($update as $att) {
$user->$att = $create_from[$att];
}
\wp_update_user($user);
return $this->response->ok([
'message' => sprintf(__('Hello %s', PMLD_TD), $user->nickname),
'user' => User::make($user),
]);
}
}
| true |
79d1c58d581fa7cddc271a37623d64b9b4e65a63 | PHP | OpenMageModuleFostering/mage_laposta_connect | /app/code/community/Laposta/Connect/controllers/WebhookController.php | UTF-8 | 6,463 | 2.640625 | 3 | [] | no_license | <?php
/**
* Laposta webhooks controller
*
* @category Laposta
* @package Laposta_Connect
*/
class Laposta_Connect_WebhookController extends Mage_Core_Controller_Front_Action
{
/**
* Entry point for all webhook operations
*/
public function indexAction()
{
$listToken = Mage::app()->getRequest()->getParam('t');
$data = $this->getInputStream();
$this->consumeEvents($listToken, $data);
}
/**
* Consume the given events to update contacts in google.
*
* @param string $listToken
* @param string $eventsJson
*
* @throws \RuntimeException
* @throws \Exception
* @return $this
*/
public function consumeEvents($listToken, $eventsJson)
{
$listToken = filter_var($listToken, FILTER_SANITIZE_STRING);
$decoded = json_decode($eventsJson, true);
/** @var $lists Laposta_Connect_Model_Mysql4_List_Collection */
$lists = Mage::getModel('lapostaconnect/list')->getCollection();
/** @var $list Laposta_Connect_Model_List */
$list = array_shift(
$lists->getItemsByColumnValue('webhook_token', $listToken)
);
$this->log("Found list using webhook token '$listToken'", $list);
if (!$list instanceof Laposta_Connect_Model_List) {
return $this->log("Unable to consume events. '$listToken' is not a valid webhook token.");
}
$this->log("Consuming events for client '$listToken'", $eventsJson);
if ($decoded === false) {
return $this->log("Events data could not be parsed. Input is not valid JSON.");
}
if (!isset($decoded['data']) || !is_array($decoded['data'])) {
return $this;
}
foreach ($decoded['data'] as $event) {
try {
$this->consumeEvent($event, $list);
}
catch (Exception $e) {
$this->log("{$e->getMessage()} on line '{$e->getLine()}' of '{$e->getFile()}'");
}
}
return $this;
}
/**
* Retrieve date from the input stream
*
* @return mixed
* @throws InvalidArgumentException
*/
public function getInputStream()
{
$source = @fopen('php://input', 'r');
if (!is_resource($source)) {
throw new InvalidArgumentException('Expected parameter 1 to be an open-able resource');
}
$data = null;
while ($buffer = fread($source, 1024)) {
$data .= $buffer;
}
fclose($source);
return $data;
}
/**
* Submit a log entry
*
* @param string $message
* @param mixed $data
*
* @return $this
*/
protected function log($message, $data = null)
{
Mage::helper('lapostaconnect')->log(
array(
'message' => $message,
'data' => $data,
)
);
return $this;
}
/**
* Consume an event from Laposta
*
* @param array $event
* @param Laposta_Connect_Model_List $list
*
* @return $this
*/
protected function consumeEvent($event, Laposta_Connect_Model_List $list)
{
if (empty($event['type']) || $event['type'] !== 'member' || !isset($event['data'])) {
return $this;
}
if (!isset($event['data']['list_id']) || !isset($event['data']['member_id'])) {
return $this;
}
$listId = $event['data']['list_id'];
$memberId = $event['data']['member_id'];
$status = isset($event['data']['state']) ? $event['data']['state'] : 'cleaned';
if ($list->getData('laposta_id') !== $listId) {
return $this->log("Resolved list id '{$list->getData('laposta_id')}' does not match provided list id '$listId'.");
}
/** @var $subscribers Laposta_Connect_Model_Mysql4_Subscriber_Collection */
$subscribers = Mage::getModel('lapostaconnect/subscriber')->getCollection();
/** @var $subscriber Laposta_Connect_Model_Subscriber */
$subscriber = $subscribers->getItemByColumnValue('laposta_id', $memberId);
if (!$subscriber instanceof Laposta_Connect_Model_Subscriber) {
return $this->log("Subscriber for laposta id '$memberId' not found.");
}
/** @var $customer Mage_Customer_Model_Customer */
$customer = Mage::getModel('customer/customer')->load($subscriber->getData('customer_id'));
if (!$customer instanceof Mage_Customer_Model_Customer) {
return $this->log("Customer for subscriber with laposta id '$memberId' not found.");
}
/** @var $fieldsHelper Laposta_Connect_Helper_Fields */
$fieldsHelper = Mage::helper('lapostaconnect/Fields');
$fields = $fieldsHelper->getByListId($subscriber->getListId());
/** @var $customerHelper Laposta_Connect_Helper_Customer */
$customerHelper = Mage::helper('lapostaconnect/customer');
$customerHelper->setCustomer($customer);
$customerHelper->email = $event['data']['email'];
foreach ($fields as $fieldName => $lapostaTag) {
$customerHelper->$fieldName = $event['data']['custom_fields'][$lapostaTag];
}
/** @var $newsletterSubscriberModel Mage_Newsletter_Model_Subscriber */
$newsletterSubscriberModel = Mage::getModel('newsletter/subscriber');
/** @var $newsletterSubscriber Mage_Newsletter_Model_Subscriber */
$newsletterSubscriber = $newsletterSubscriberModel->loadByCustomer($customer);
$newsletterSubscriber->setCustomerId($subscriber->getData('customer_id'));
$newsletterSubscriber->setEmail($customer->getEmail());
$newsletterSubscriber->setStoreId($customer->getStore()->getId());
if ($status !== 'active') {
$customer->setIsSubscribed(false);
$newsletterSubscriber->unsubscribe();
$this->log("Customer '{$customer->getEmail()}' for subscriber with laposta id '$memberId' has been unsubscribed.");
}
else {
$customer->setIsSubscribed(true);
$newsletterSubscriber->subscribeCustomer($customer);
$this->log("Customer '{$customer->getEmail()}' for subscriber with laposta id '$memberId' has been subscribed.");
}
$customer->save();
return $this;
}
}
| true |
daa103818ea8ded7f44b2ebb3aed40297790f817 | PHP | crude-forum/crude-forum | /spec/Iterator/Wrapper.spec.php | UTF-8 | 3,055 | 2.953125 | 3 | [
"MIT"
] | permissive | <?php
use CrudeForum\CrudeForum\Iterator\Wrapper;
use CrudeForum\CrudeForum\Iterator\WrapperTrait;
use CrudeForum\CrudeForum\Iterator\ProxyTrait;
use CrudeForum\CrudeForum\Iterator\Utils;
use \Iterator as Iterator;
class TestWrapper implements Wrapper, Iterator
{
use ProxyTrait;
use WrapperTrait;
private $_name = '';
public function __construct(string $name)
{
$this->_name = $name;
}
public function getName(): string
{
return $this->_name;
}
public function getStack(): string
{
if (($inner = $this->iter()) === null)
{
return $this->_name . '->null';
}
$innerName = ($inner instanceof TestWrapper) ? $inner->getStack() : get_class($inner);
return $this->_name . '->' . $innerName;
}
public function current(): string
{
$stack = $this->getStack();
//echo "called {$stack}::current()\n";
return $this->_name . ': ' . $this->iter()->current();
}
}
describe('CrudeForum\CrudeForum\Iterator\Wrapper', function () {
describe('::wrap', function () {
it('wrapped iterator uses the outer class method', function () {
// prepare object to test with
$obj0 = new ArrayIterator(['hello', 'world']);
$obj1 = (new TestWrapper('wrapper1'))->wrap($obj0);
$obj2 = (new TestWrapper('wrapper2'))->wrap($obj1);
$obj3 = (new TestWrapper('wrapper3'))->wrap($obj2);
$objects = [$obj1, $obj2, $obj3];
$expectedPrefix = '';
foreach ($objects as $objkey => $obj) {
$expectedPrefix = 'wrapper' . ($objkey + 1) . ': ' . $expectedPrefix;
foreach ($obj as $value) {
expect($value)->toMatch('/^' . preg_quote($expectedPrefix) . '/');
}
}
});
});
});
describe('CrudeForum\CrudeForum\Iterator\Utils', function () {
describe('::chainWrappers', function () {
it('wrapped iterator uses the outer class method', function () {
// prepare object to test with
$obj0 = new ArrayIterator(['hello', 'world']);
$obj1 = Utils::chainWrappers(
new TestWrapper('wrapper1')
)->wrap($obj0);
$obj2 = Utils::chainWrappers(
new TestWrapper('wrapper1'),
new TestWrapper('wrapper2')
)->wrap($obj0);
$obj3 = Utils::chainWrappers(
new TestWrapper('wrapper1'),
new TestWrapper('wrapper2'),
new TestWrapper('wrapper3')
)->wrap($obj0);
$objects = [$obj1, $obj2, $obj3];
$expectedPrefix = '';
foreach ($objects as $objkey => $obj) {
$expectedPrefix = 'wrapper' . ($objkey + 1) . ': ' . $expectedPrefix;
foreach ($obj as $value) {
expect($value)->toMatch('/^' . preg_quote($expectedPrefix) . '/');
}
}
});
});
});
| true |
df1b9790abada29c3e125db8e70659a6911c8a03 | PHP | maiglonl/Finapp | /app/Events/IuguSubscriptionCreatedEvent.php | UTF-8 | 627 | 3.015625 | 3 | [
"MIT"
] | permissive | <?php
namespace Finapp\Events;
class IuguSubscriptionCreatedEvent{
private $iuguSubscription;
private $userId;
private $planId;
/**
* Create a new event instance.
*
* @param $iuguSubscription
* @param $iuguSubscriptionOld
* @return void
*/
public function __construct($iuguSubscription, $userId, $planId){
$this->iuguSubscription = $iuguSubscription;
$this->userId = $userId;
$this->planId = $planId;
}
public function getIuguSubscription(){
return $this->iuguSubscription;
}
public function getUserId(){
return $this->userId;
}
public function getPlanId(){
return $this->planId;
}
}
| true |
0bcc4e525c9d3b323ee4ccd8e2c3faee51f80140 | PHP | omisai-tech/laravel-szamlazzhu | /src/Language.php | UTF-8 | 1,557 | 2.828125 | 3 | [
"MIT"
] | permissive | <?php
namespace Omisai\Szamlazzhu;
enum Language: string
{
case HU = 'hu';
case EN = 'en';
case DE = 'de';
case IT = 'it';
case RO = 'ro';
case SK = 'sk';
case HR = 'hr';
case FR = 'fr';
case ES = 'es';
case CZ = 'cz';
case PL = 'pl';
public static function getDefault(): self
{
return self::HU;
}
public static function getLanguageName(Currency $language): string
{
switch ($language) {
case self::HU:
$result = 'magyar';
break;
case self::EN:
$result = 'angol';
break;
case self::DE:
$result = 'német';
break;
case self::IT:
$result = 'olasz';
break;
case self::RO:
$result = 'román';
break;
case self::SK:
$result = 'szlovák';
break;
case self::HR:
$result = 'horvát';
break;
case self::FR:
$result = 'francia';
break;
case self::ES:
$result = 'spanyol';
break;
case self::CZ:
$result = 'cseh';
break;
case self::PL:
$result = 'lengyel';
break;
default:
$result = 'ismeretlen';
break;
}
return $result;
}
}
| true |
e5f8db260cd14b8537013cd43bac5c756dff7268 | PHP | vallauri-ict/ajax-playground-palumbovalerio | /RegistroElettronico/libraries/library.php | UTF-8 | 2,135 | 2.828125 | 3 | [] | no_license | <?php
define ("SCADENZA", 3600);
function connection($dbName){
define('DBHOST', 'localhost');
define('DBUSER', 'root');
define('DBPASS', '');
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try
{
$con = new mysqli(DBHOST, DBUSER, DBPASS, $dbName);
$con->set_charset("utf8");
return $con;
}
catch (mysqli_sql_exception $ex)
{
error(503, "Errore connessione db: " . $ex->getMessage());
}
}
function selectDatas($con, $sql, $parameter, $onlyOne=true){
$data=runQuery($con, $sql);
if($onlyOne) return $data[0][$parameter];
else return $data;
}
function runQuery($con, $sql){
try{
$rs=$con->query($sql);
}
catch (mysqli_sql_exception $ex)
{
$con->close();
error(500, "Errore esecuzione query. " . $ex->getMessage());
}
if(!is_bool($rs))
$data=$rs->fetch_all(MYSQLI_ASSOC);
else
$data=$rs;
return $data;
}
function checkSession($key){
session_start();
// Il server NON può spedire una pagina HTML !!
if (!isset($_SESSION[$key]))
error(403, "Sessione scaduta");
else if (!isset($_SESSION["scadenza"]) || time() > $_SESSION["scadenza"] )
{
destroySession();
error(403, "Sessione scaduta");
}
else{
$_SESSION["scadenza"] = time() + SCADENZA;
// Aggiorno la scadenza dei cookie
setcookie(session_name(), session_id(), $_SESSION["scadenza"], "/");
}
}
function parameterControl($parameter, $responseCode, $secondaryCondition=true)
{
if(!isset($_REQUEST["$parameter"]) && $secondaryCondition)
error($responseCode, "Parametro mancante ($parameter)");
else
return $_REQUEST["$parameter"];
}
function isNumericControl($parameterName, $con)
{
$parameter = $con->real_escape_string($_REQUEST["$parameterName"]);
if (!is_numeric($parameter))
{
$con->close();
error(400, "Il parametro $parameterName deve essere numerico.");
}
return $parameter;
}
function error($responseCode, $message){
http_response_code($responseCode);
die($message);
}
function destroySession(){
session_unset();
session_destroy();
}
?> | true |
24ca621de9e43fdc54de44696ec188e6e6b16b8c | PHP | malierjia/Ejercicio-1-MariaAlejandraMoreno | /estudiantes.php | UTF-8 | 1,438 | 3.109375 | 3 | [] | no_license | <html>
<head>
<title> ESTUDIANTES </title>
<meta charset = "utf-8">
</head>
<body>
<?php
//se conecta
include_once("includes/database.php");
//query descrito en word
$query= "SELECT * FROM claseweb.estudiantes ORDER BY apellido";
//se coloca en una variable (arreglo)
$result= mysqli_query($con,$query);
//creo tabla para mostrar estudiantes existentes
echo "<br />";
echo"<h1>Estudiantes existentes</h1>";
echo "<table border='1'>
<tr>
<th>Nombre</th>
<th>Apellido</th>
<th>Codigo</th>
<th>Correo</th>
</tr>";
//muestro los datos recorriendo el arreglo
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['nombre'] ." </td>";
echo "<td>" . $row['apellido'] . " </td>";
echo "<td>" . $row['codigo'] ." </td>";
echo "<td>" . $row['correo'] ." </td>";
}
echo "</table>";
mysqli_close($con);
?>
<form action="notas.php">
<br>
<input type="submit" value="Agregar Notas de estudiante">
</form>
<h1>Crea un nuevo estudiante</h1>
<form action="AgregaDatos.php" method ="POST">
<label>Nombre:</label><input type="text" name="nombre" value"" ><br>
<label>Apellido:</label><input type="text" name="apellido" value"" ><br>
<label>Codigo:</label><input type="number" name="codigo" value"" ><br>
<label>Correo:</label><input type="mail" name="correo" value""><br>
<h4>*Todos los campos son oblligatorios</h4>
<input type="submit" name="Enviar" value="Enviar" >
</form>
</body>
</html> | true |
d8c23bf87fdd5aa58da24eaf6aa87f3abb27064c | PHP | ssnepenthe/clockwork-for-wp | /tests/trait-creates-config.php | UTF-8 | 400 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
namespace Clockwork_For_Wp\Tests;
use League\Config\Configuration;
use League\Config\ConfigurationInterface;
trait Creates_Config {
public function create_config( array $user_config = [] ): ConfigurationInterface {
$schema = include dirname( __DIR__ ) . '/config/schema.php';
$config = new Configuration( $schema );
$config->merge( $user_config );
return $config->reader();
}
}
| true |
ad3a6a645771d4274c6e26c094620d8c80165d1e | PHP | ziprandom/nntpboard | /classes/board/memcachednntp.class.php | UTF-8 | 659 | 2.515625 | 3 | [] | no_license | <?php
require_once(dirname(__FILE__) . "/cachednntp.class.php");
require_once(dirname(__FILE__) . "/../connection/itemcache/mem.class.php");
class MemCachedNNTPBoard extends CachedNNTPBoard {
private $memcache;
public function __construct($boardid, $parentid, $name, $desc, $anonMayPost, $authMayPost, $isModerated, $memcache, $host, $group) {
parent::__construct($boardid, $parentid, $name, $desc, $anonMayPost, $authMayPost, $isModerated, $host, $group);
$this->memcache = $memcache;
}
public function getConnection() {
return new MemItemCacheConnection(
$this->memcache,
parent::getConnection()
);
}
}
?>
| true |
b08c3c822f8fb8ea0da17c686a95f3cdfa310eb6 | PHP | jasarsoft/ad-turist | /sys/Controller.php | UTF-8 | 541 | 2.890625 | 3 | [
"MIT"
] | permissive | <?php
abstract class Controller {
private $podaci = [];
protected function set($name, $value) {
if (preg_match('|^[A-z0-9_]+$|', $name)) {
$this->podaci[$name] = $value;
}
}
protected function del() {
$this->podaci = [];
}
public function getData() {
return $this->podaci;
}
function index() {
}
public function __pre() {
}
}
| true |
4223bb24369ea032ec08274d854cb60d8d0c0488 | PHP | algo26-matthias/phlymail | /phlymail/handlers/files/configapi.php | UTF-8 | 8,848 | 2.578125 | 3 | [] | no_license | <?php
/**
* Offering API calls for the Config interface
* @package phlyMail Nahariya 4.0+ Default branch
* @subpackage Handler: Files
* @copyright 2004-2013 phlyLabs, Berlin (http://phlylabs.de)
* @version 4.0.8 2013-07-07
*/
// Only valid within phlyMail
defined('_IN_PHM_') || die();
class handler_files_configapi
{
private $STOR = false;
private $uid = 0;
private $errortext = false;
public $sysfolders = array
('root' => array('root' => 1, 'de' => 'Dateien', 'en' => 'Files', 'icon' => ':files')
,'waste' => array('root' => 0, 'de' => 'Papierkorb', 'en' => 'Trash', 'icon' => ':waste')
);
public $perm_handler_available = 'files_see_files';
/**
* Constructor method, this special constructor also attempts to create the required
* docroot of the email storage for the given user
*
* @param array reference public settings structure
* @param int ID of the user to perform the operation for
* @return boolean true on success, false otherwise
* @since 0.0.1
*/
public function __construct(&$_PM_, $uid)
{
$this->_PM_ = $_PM_;
$this->uid = intval($uid);
$this->STOR = new handler_files_driver($uid, '', true);
}
/**
* Returns errors which happened
* @return string error message(s)
* @since 0.0.3
*/
public function get_errors() { return $this->errortext; }
public function check_user_installed()
{
// Never try to install anything for uid 0!
if ($this->uid == 0) {
return true;
}
$exists = $this->STOR->get_folder_id_from_path('waste');
if (empty($exists)) {
$this->create_user();
}
}
/**
* This encapsulates the necessary operations on creating a new user from the Config interface.
* In case of the Email handler this includes creating the system folders in the file system and
* the index and internal folders in the file system.
*
* @return boolean true on success, false otherwise
* @since 0.0.1
*/
public function create_user()
{
$root = 0;
foreach ($this->sysfolders as $path => $data) {
$dispname = ($this->_PM_['core']['language'] == 'de') ? $data['de'] : $data['en'];
if ($data['root']) {
$root = $this->STOR->create_mailbox($dispname, 0, $data['icon'], true, true);
if (!$root) {
$this->errortext = $this->STOR->get_errors('<br />');
return false;
}
} else {
$state = $this->STOR->create_folder($dispname, $root, 0, $data['icon'], true, true, $path);
if (!$state) {
$this->errortext = $this->STOR->get_errors('<br> /');
return false;
}
}
}
return true;
}
/**
* This encapsulates the necessary operations on removing a user from the Config interface.
* In case of the Email handler this includes removing the system folders from the file system and
* the index and internal folders from the file system.
*
* @return boolean true on success, false otherwise
* @since 0.0.2
*/
public function remove_user() { return $this->STOR->remove_user(); }
/**
* Called on installing the handler from the Config interface
* @param void
* @return boolean
* @since 0.0.7
*/
public function handler_install() { return $this->STOR->handler_install(); }
/**
* Called on uninstalling the handler from the Config interface
* @param void
* @return boolean
* @since 0.0.7
*/
public function handler_uninstall() { return $this->STOR->handler_uninstall(); }
/**
* This method allows the Config to query the available actions of this handlers
* for managing access permissions to them. This allows for user level access permissions
* to anything functional phlyMail offers - even complete readonly access and disabling
* of single functions in the frontend (sending emails, adding profiles and stuff).
* @param void
* @return array Key => Translated action name
* @since 1.0.0
*/
public function get_perm_actions($lang = 'en')
{
// For a correct translation we unfortunately have to read in a messages file
$d = opendir($this->_PM_['path']['handler'].'/files');
while (false !== ($f = readdir($d))) {
if ('.' == $f) continue;
if ('..' == $f) continue;
if (preg_match('!^lang\.'.$lang.'(.*)\.php$!', $f)) {
require_once($this->_PM_['path']['handler'].'/files/'.$f);
break;
}
}
return array
('see_files' => $WP_msg['PermSeeFiles']
,'add_file' => $WP_msg['PermAddFile']
,'update_file' => $WP_msg['PermUpdateFile']
,'delete_file' => $WP_msg['PermDeleteFile']
,'import_file' => $WP_msg['PermImportFile']
,'export_file' => $WP_msg['PermExportFile']
,'add_folder' => $WP_msg['PermAddFolder']
,'edit_folder' => $WP_msg['PermEditFolder']
,'delete_folder' => $WP_msg['PermDeleteFolder']
);
}
/**
* This method delivers a list of quota settings, this handler defines. The list contains the
* internal identifier for this definition, the human readable name of it and a few helpful bits
* of information, so that the Config knows, which types of values are allowed.
*
* This method queries global values!
*
* @param string $lang The language of the Config interface for the display name of the setting
* @return array
* @since 0.0.8
*/
public function get_quota_definitions($lang = 'en')
{
// For a correct translation we unfortunately have to read in a messages file, that fits, since
// the frontend allows to have de_Du, de_Sie, while the Config jsut has de as language...
$d = opendir($this->_PM_['path']['message']);
while (false !== ($f = readdir($d))) {
if ('.' == $f) continue;
if ('..' == $f) continue;
if (preg_match('!^'.$lang.'(.*)\.php$!', $f)) {
require($this->_PM_['path']['message'].'/'.$f);
break;
}
}
//require_once($this->_PM_['path']['handler'].'/files/lang.'.$lang.'.php');
// Give definitions
return array
('traffic_limit' => array
('type' => 'filesize'
,'min_value' => 0 // Beware: 0 means unlimited ...
,'on_zero' => 'drop' // How to behave on zero values (drop or keep)
,'name' => '' // $WP_msg['ConfigQuotaTrafficLimit']
,'query' => false // Whether this feature can be set at the moment (false: not yet implemented)
)
,'size_storage' => array
('type' => 'filesize'
,'min_value' => 0
,'on_zero' => 'drop'
,'name' => $WP_msg['ConfigQuotaStorageSize']
,'query' => true
)
,'number_items' => array
('type' => 'int'
,'min_value' => 0
,'on_zero' => 'drop'
,'name' => $WP_msg['ConfigQuotaNumItems']
,'query' => true
)
,'number_folders' => array
('type' => 'int'
,'min_value' => 0 // Here 0 means to not allow to add any folders
,'on_zero' => 'keep'
,'name' => $WP_msg['ConfigQuotaNumFolders']
,'query' => true
)
);
}
/**
* This method allows Config to query the current usage for a specific definition and
* a specific user
*
* @param string $what The definition to query for the current user
* @return mixed The current usage for that quota definition
* @since 0.0.8
*/
public function get_quota_usage($what, $stats = false)
{
switch ($what) {
case 'size_storage':
return $this->STOR->quota_getitemsize($stats);
break;
case 'number_items':
return $this->STOR->quota_getitemnum($stats);
break;
case 'number_folders':
return $this->STOR->quota_getfoldernum($stats);
break;
default: return false;
}
}
}
| true |
a722d1a2478b5853e2fc96b163fafdecb6e658a0 | PHP | RodolfoTerra/guzzleExemple | /app/control/index.php | UTF-8 | 1,413 | 2.765625 | 3 | [] | no_license | <?php
namespace App\Control;
/**
* Class: Salario
*/
use GuzzleHttp\Client as Client;
class Salario
{
private $url;
private $myObj;
function __construct()
{
$this->url = 'http://www.guiatrabalhista.com.br/guia/salario_minimo.htm';
$this->myObj = new Client([
'headers' => ['User-Agent' => 'MyReader']
]);
$this::pushPage();
}
private function pushPage()
{
$feedPage = $this->myObj->request('GET', $this->url);
if ($feedPage->getStatusCode() == 200) {
if ($feedPage->hasHeader('Content-Length')) {
$contentlength = $feedPage->getHeader('Content-Length')[0];
echo "<p> $contentlength bytes lidos.</p>";
}
$body = $feedPage->getBody();
$bodyString = (string) $body;
$array1 = explode("<td width=\"150\" align=\"center\" style=\"margin: 0px;\" padding=\"0px;\">", $bodyString);
$array2 = explode("</td>", $array1[0]);
$request = [];
$array = [];
$limit = count($array2);
$lines = round($limit/7);
$i = 0;
$a = 6;
while ($i < $lines) {
$array = [
'vigencia' => $array2[$a++],
'valor_mensal' => $array2[$a++],
'valor_diario' => $array2[$a++],
'valor_hora' => $array2[$a++],
'normal_legal' => $array2[$a++],
'dou' => $array2[$a++]
];
array_push($request, $array);
$i++;
}
print_r($request);
}
}
}
| true |
426f078f1d0f54660f7f3d004e816db908767107 | PHP | JorgeSidgo/crudsini | /app/dao/DaoBase.php | UTF-8 | 180 | 2.625 | 3 | [] | no_license | <?php
class DaoBase {
protected $con;
public $objeto;
public function __construct() {
$obj = new Conexion();
$this->con = $obj->conectar();
}
} | true |
b104c7a585d29a43d30e94cd145f333860e31a23 | PHP | Ponera-Lab/wcore-repo | /src/Manager/Site/SectionManager.php | UTF-8 | 6,751 | 2.640625 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: DanielSimangunsong
* Date: 2/23/2017
* Time: 1:24 PM
*/
namespace Webarq\Manager\Site;
use DB;
use Illuminate\Contracts\Support\Htmlable;
use Wa;
use Webarq\Manager\SetPropertyManagerTrait;
use Webarq\Model\NoModel;
class SectionManager implements Htmlable
{
use SetPropertyManagerTrait;
/**
* @var
*/
protected $data = false;
/**
* @var
*/
protected $id;
/**
* @var
*/
protected $key;
/**
* Model options
*
* @var array
*/
protected $model = [];
/**
* @var
*/
protected $name;
/**
* @var number
*/
protected $paginate;
/**
* @var array
*/
protected $table;
/**
* @var
*/
protected $template;
/**
* @var
*/
protected $view;
/**
* Others data
*
* @var array
*/
protected $viewVars = [];
/**
* Section is static raw html, it does not need data
*
* @var bool
*/
protected $raw = false;
public function __construct(array $options)
{
$this->setPropertyFromOptions($options);
// Append non property options in to $viewVars property
foreach ($options as $k => $v) {
$this->viewVars[camel_case('opt ' . $k)] = $v;
}
// Check for string model was given
if (is_string($this->model)) {
if (str_contains($this->model, ':')) {
// Separate class from parameters
list($class, $params) = explode(':', $this->model, 2);
// Separate method from parameters
$params = explode(',', $params);
// Beware with reference array pull action
$this->model = array_combine(['class', 'method', 'attr'], array($class, array_pull($params, 0), $params));
} else {
$this->model = ['class' => $this->model];
}
}
if ([] !== $this->model) {
$this->model += [
'class' => 'mustBeFilled',
'method' => 'getDataSection',
'attr' => []
];
}
if (null === $this->view) {
$this->view = $this->key;
}
}
/**
* @return string
*/
public function __toString()
{
return $this->toHtml();
}
/**
* @param null|string $view
* @return string
*/
public function toHtml($view = null)
{
// Get menu template
$template = Wa::menu()->getActive()->template;
if (is_null($view)) {
if (is_callable($this->raw)) {
return call_user_func($this->raw);
}
$view = 'webarq::themes.front-end.sections.' . $template . '.' . $this->view;
if (!view()->exists($view)) {
$view = 'webarq::themes.front-end.sections.' . $this->view;
}
}
if (!view()->exists($view)) {
return '<div style="font-size:50px;">Section '
. $this->template . ' ' . $this->key . ' does not have respected view</div>';
} else {
$this->viewVars += [
'shareData' => $this->getData(),
'pagingView' => $this->paginate,
'shareTemplate' => $this->template
];
if (true === $this->raw) {
return view($view, $this->viewVars)->render();
} elseif ($this->getData()->count()) {
return view($view, $this->viewVars)->render();
}
}
return '';
}
/**
* @return mixed
*/
public function getData()
{
if (false === $this->data) {
if (isset($this->model['class']) && null !== ($model = Wa::model($this->model['class']))) {
$this->data = $model->{$this->model['method']}($this->id, array_get($this->model, 'attr'));
} elseif (is_array($this->table)) {
$model = Wa::model(str_singular($this->table['name'])) ?: NoModel::instance($this->table['name']);
$builder = $model->whereSectionId($this->id);
if (null !== ($column = array_get($this->table, 'select'))) {
$builder->select($column);
}
if (null !== ($column = array_get($this->table, 'translate'))) {
if (!is_bool(last($column))) {
array_push($column, true);
}
call_user_func_array([$builder, 'selectTranslate'], $column);
}
$builder
->makeWhereFromOptions(array_get($this->table, 'where', []))
->makeSequenceFromOptions(array_get($this->table, 'sequence'));
// Only active record
if (true === array_get($this->table, 'activeness')) {
$builder->whereIsActive(1);
}
// Limit the record
if (isset($this->table['limit'])) {
$builder->limit($this->table['limit']);
}
if (!isset($this->paginate)) {
$this->data = $builder->get();
} else {
$arr = explode(':', $this->paginate);
$this->data = $builder->paginate((int)$arr[0]);
}
} else {
return $this;
}
}
return $this->data;
}
/**
* Always return 0, because if you hit this, its mean you do not set the proper configuration
*
* @return int
*/
public function count()
{
return 0;
}
/**
* Share something with view
*
* @param $key
* @param $value
* @return $this
*/
public function with($key, $value)
{
if (is_array($key)) {
$this->viewVars = $key + $this->viewVars;
} else {
$this->viewVars[$key] = $value;
}
return $this;
}
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @return mixed
*/
public function getKey()
{
return $this->key;
}
/**
* @return mixed
*/
public function getModel()
{
return $this->model;
}
/**
* @return array
*/
public function getTable()
{
return $this->table;
}
/**
* @return mixed
*/
public function getTemplate()
{
return $this->template;
}
/**
* @return mixed
*/
public function getName()
{
return $this->name;
}
} | true |
675842947645f92874ec829b961866120e8ec2de | PHP | VivienG-Dev/Fetch-API-Training | /fetch/articles.php | UTF-8 | 279 | 2.515625 | 3 | [] | no_license | <?php
// Create Connection
$conn = mysqli_connect('localhost', 'root', 'root', 'ajaxtest');
$query = 'SELECT * FROM articles';
// Get Result
$result = mysqli_query($conn, $query);
// Fetch Data
$articles = mysqli_fetch_all($result, MYSQLI_ASSOC);
echo json_encode($articles); | true |
d54991d5886d15d3e4ab352b9b3c98edd54c01a2 | PHP | axelPZ/carrito-compras | /models/sale.php | UTF-8 | 4,194 | 2.859375 | 3 | [] | no_license | <?php
require_once 'core/crud.php';
class Sale extends Crud{
private $id;
private $date;
private $userId;
private $ahorra;
private $neto;
private $iva;
private $total;
protected const TABLE='sales';
protected const ID='sal_id';
protected $pdo;
public function __construct(){
parent::__construct(self::TABLE, self::ID);
$this->pdo = parent::conexion();
}
public function __get($name){
return $this->$name;
}
public function __set($name, $value){
$this->$name = $value;
}
//fucniones
//llamar las compras a detalle
public function getUserSale($idUser){
try{
$stm = $this->pdo->prepare("SELECT sal_id, sal_date, sal_ahorra, sal_neto, sal_IVA, sal_Total, SUM(det_Quantity) AS cantidad
FROM sales
JOIN sale_detail ON det_SaleID = sal_id
WHERE sal_userId=?
GROUP BY det_saleId
ORDER BY sal_id DESC");
$stm->execute(array($idUser));
return $stm->feTchAll(PDO::FETCH_OBJ);
}catch(PDOException $e){
echo $e->getMessage();
return false;
}
}
//de las compras del usuario
public function getDetalleCompra($idUser){
try{
$stm = $this->pdo->prepare("SELECT (SELECT SUM(sal_total) FROM sales WHERE sal_userid=$idUser) AS total,
(SELECT SUM(sal_ahorra) FROM sales WHERE sal_userid=$idUser) AS ahorra,
MAX(sal_total) as maximo, SUM(det_Quantity) AS cantidad
FROM SALES
JOIN sale_detail ON det_SaleID = sal_id
WHERE sal_userid=$idUser");
$stm->execute();
return $stm->feTchAll(PDO::FETCH_OBJ);
}catch(PDOException $e){
echo $e->getMessage();
return false;
}
}
//agregar compra
public function add(){
try{
$stm = $this->pdo->prepare("INSERT INTO ".self::TABLE." (sal_date, sal_userId, sal_ahorra, sal_neto, sal_iva, sal_total) VALUES (?,?,?,?,?,?)");
$stm->execute(array($this->date, $this->userId, $this->ahorra, $this->neto, $this->iva, $this->total ));
return true;
}catch(PDOException $e){
echo $e->getMessage();
return false;
}
}
//editar compra
public function update(){
try{
$stm = $this->pdo->prepare("UPDATE ".self::TABLE." sal_date=?, sal_userId=?, sal_ahorra=?, sal_neto=?, sal_iva=?, sal_total=? WHERE sal_id=?");
$stm->execute(array($this->date, $this->userId, $this->ahorra, $this->neto, $this->iva, $this->total, $this->id ));
return true;
}catch(PDOException $e){
echo $e->getMessage();
return false;
}
}
//eliminar compra
public function delete($id){
try{
$stm = $this->pdo->prepare("DELETE ".self::TABLE." WHERE ".self::ID."=?");
$stm->execute(array($id));
return true;
}catch(PDOException $e){
echo $e->getMessage();
return false;
}
}
//hacer el pago de la compra
public function pagoCompra($numTarjeta, $cvv, $vigencia){
$tarjeta = substr($numTarjeta,0,16);
if($tarjeta && $cvv && $vigencia){
return true;
}else
{
return false;
}
die();
}
}
?> | true |
022e5aacce4a0d8e77e8ac7dff8187a1dfc930e3 | PHP | xinonghost/patterns | /Creational/AbstractFactory/PHP/products/WinCheckbox.php | UTF-8 | 522 | 3.21875 | 3 | [] | no_license | <?php
require_once(__DIR__.'/../interfaces/ICheckbox.php');
/**
* Concrette object of family.
*/
class WinCheckbox implements ICheckbox
{
/**
* @override
*/
public function paint()
{
print("Painting checkbox in Windows style.\n");
}
/**
* @override
*/
public function setPosition($x, $y)
{
print("Setting checkbox position to ({$x}, {$y}) in Windows style.\n");
}
/**
* @override
*/
public function getValue()
{
print("Getting checkbox value in Windows style.\n");
return false;
}
}
| true |
f0637ebb4de86d9d65d518ef8777223919351b5c | PHP | nuostudio/nuostudio.com | /proxySRC.php | UTF-8 | 3,715 | 2.640625 | 3 | [] | no_license | <?php
session_start();
/*
* Proxy de Chevismo.com
* Desarrollado integramente por Chevi para Chevismo
* No usar con fines malos.. ;)
*/
// Inicio del Proxy:
if($_SESSION['proxy']['URL']) $_POST['url'] = $_SESSION['proxy']['URL'];
// Check URL and add www where necesary:
$weburl = $_POST['url'];
if(substr($weburl,0,6)=='http://'){
$weburl = 'http://'.$weburl;
}
if(substr($weburl,0,10)=='http://www.'){
$weburl = 'http://www.'.$weburl;
}
$_SESSION['proxy']['URL'] = $weburl;
// Setup del User Agent:
if(!isset($_SESSION['proxy']['agent'])){ $_SESSION['proxy']['agent'] = 'Nuostudio (http://nuostudio.com/proxy)'; }
// FUNCIONES:
function genLink($link,$host,$url){
if($url['host']){
$ret = $link;
}else if(substr($link,0,1)=='/'){
$ret = 'http://'.$host['host'].$link;
}else{
$ret = 'http://'.$host['host'].dirname($host['path']).'/'.$link;
}
return $ret;
}
function parseUrl($url){
//print_r($url);
$link = $url[3];
$url = @parse_url($link);
if(!$url){
return $link;
}
$host = parse_url($_GET['url']);
$imgs = array('jpg','jpeg','gif','png','tif','ico');
$ext = substr(strrchr($url['path'], '.'), 1);
//echo '|EXT: '.$ext.'|';
if(in_array($ext,$imgs)){
//this is an image:
//echo '|Image|';
$ret = genLink($link,$host,$url);
return 'src="'.$ret.'"';
}else if($ext=='css' || $ext=='js'){
//echo '|CSS|';
// Now check wether it is absolute, relative, or http:
$ret = genLink($link,$host,$url);
}else if(substr(strtolower($link),0,6)=='mailto'){
//echo '|Email|';
$ret = $link;
}else{
//echo '|Link|';
if(strpos($link,'embed')){
$ret = genLink($link,$host,$url);
}else{
if($url['host']){
$ret = 'http://nuostudio.com/proxySRC?url='.$link;
}else if(substr($link,0,1)=='/'){
$ret = 'http://nuostudio.com/proxySRC?url=http://'.$host['host'].$link;
}else{
$ret = 'http://nuostudio.com/proxySRC?url=http://'.$host['host'].dirname($host['path']).'/'.$link;
}
}
}
//echo 'href="'.$ret.'"<br />';
return 'href="'.$ret.'"';
}
function parseForms($url){
$link = $url[3];
$url = @parse_url($link);
if(!$url){
return $link;
}
$host = parse_url($_GET['url']);
if($url['host']){
$ret = 'http://nuostudio.com/proxySRC?url='.$link;
}else if(substr($link,0,1)=='/'){
$ret = 'http://nuostudio.com/proxySRC?url=http://'.$host['host'].$link;
}else{
$ret = 'http://nuostudio.com/proxySRC?url=http://'.$host['host'].dirname($host['path']).'/'.$link;
}
return 'action="'.$ret.'"';
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
curl_setopt($ch, CURLOPT_URL,$weburl);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_COOKIESESSION, false);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$html = curl_exec($ch);
if (!$html) {
echo 'No he podido abrir la URL '.$weburl.' :(';
echo "<br />cURL error number: " .curl_errno($ch);
echo "<br />cURL error: " . curl_error($ch);
exit;
}
curl_close($ch);
$url = parse_url($_GET['url']);
preg_match("@[a-zA-Z0-9]{1,}?@",$html,$m);
$html = var_dump($m);
$html = str_replace(array('erotica','sex','sexy','dick','cock'),array('e','s**','s***','d***','c***'),$html);
$html = str_replace('SWFObject("/','SWFObject("http://'.$url['host'].'/',$html);
$html = preg_replace_callback('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.-]*(\?\S+)?)?)?)@', 'parseUrl', $html);
$html = preg_replace("@(href|src)[\s]*=[\s]*('|\")([^\"']+)*('|\")@", 'href="http://nuostudio.com"', $html);
$html = preg_replace_callback("@(action)[\s]*=[\s]*('|\")([^\"']+)*('|\")@", 'parseForms', $html);
echo $html; | true |
c36b51a30537dbf06373df7c7bf06abab64646e2 | PHP | solo-framework/miga | /src/Miga/Command/Commit.php | UTF-8 | 3,500 | 2.671875 | 3 | [
"MIT"
] | permissive | <?php
/**
*
*
* PHP version 5
*
* @package
* @author Andrey Filippov <afi@i-loto.ru>
*/
namespace Miga\Command;
use Miga\Application;
use Miga\Migration;
use Miga\MigrationManager;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use zpt\anno\Annotations;
class Commit extends BaseCommand
{
protected function configure()
{
$this->setName("commit")
->setDescription("Commit a migration")
->addOption(
'env',
"e",
InputOption::VALUE_REQUIRED,
'Name of environment'
)
//->addArgument("comment", InputArgument::REQUIRED, "Comment for migration")
->setHelp(sprintf('%sCommit migration.%s', PHP_EOL, PHP_EOL));
}
protected function execute(InputInterface $input, OutputInterface $output)
{
//$comment = $input->getArgument("comment");
$envName = $input->getOption("env");
$conn = $this->getConnection($envName);
$uid = MigrationManager::getCurrentTime();
$mm = new MigrationManager($this->config, $conn);
//
$output->write("\n<comment>Creating new migraton {$uid}...</comment>");
$className = "";
if (is_file(Application::NEW_MIGRATION_FILE))
{
$php = file_get_contents(Application::NEW_MIGRATION_FILE);
// переименовать класс
$clsUid = str_replace(".", "_", $uid);
$php = str_replace("NewMigration", "Migration_{$clsUid}", $php);
// получить parent из аннотаций
$rf = new \ReflectionClass("Miga\\Migrations\\NewMigration");
$annotations = new Annotations($rf);
// $rf = new \ReflectionClass("Miga\\Migrations\\NewMigration");
// $ar = new AnnotationReader();
// $annotations = $ar->getClassAnnotations($rf);
// вставим служебную информацию
$serviceData = $mm->generateServiceData($uid, $annotations["comment"], $annotations["parent"]);
$php = str_replace("//{SERVICE_DATA}", $serviceData, $php);
// перезаписать содержимое файла
$className = "Miga\\Migrations\\Migration_" . $clsUid;
file_put_contents(Application::MIGRATIONS_DIR . DIRECTORY_SEPARATOR . "Migration_" . $clsUid . ".php", $php);
@unlink(Application::NEW_MIGRATION_FILE);
}
else
{
throw new \Exception("Can't find a file with new migration. Run command 'create'");
}
$conn->beginTransaction();
try
{
// сохранение миграции в БД
//$mm->insertMigration($uid, $comment);
// $className = "Miga\\Migrations\\Migration_1413831508_0655";
//
/** @var $cls Migration */
$cls = $mm->getMigrationInstance($className);
$cls->insertServiceData();
$mm->setCurrentMigration($uid);
//
// $rf = new \ReflectionClass($className);
// $ar = new AnnotationReader();
// $annotations = $ar->getClassAnnotations($rf);
// $mm->insertMigration($uid, $comment, $annotations["parent"]);
$conn->commit();
}
catch (\Exception $e)
{
$conn->rollBack();
throw $e;
}
// $this->migrator->entityManager->beginTransaction();
// try
// {
// $this->migrator->exportDump($uid);
// $this->migrator->putDelta($uid, $comment);
// $this->migrator->insertMigration($uid, $comment);
//
// $this->migrator->entityManager->commit();
// }
// catch (\Exception $e)
// {
// $this->migrator->entityManager->rollback();
// throw DBMigratorException::create($e);
// }
$output->writeln("<info>Done</info>\n");
}
}
| true |
a2f7747ca8d446f6db84f3e523018195fcf6b63d | PHP | sufiyanpk7/iptables | /analyze-ip-relationships.php | UTF-8 | 972 | 2.71875 | 3 | [
"Apache-2.0"
] | permissive | <!-- Take a list of IPs from file blacklist and analyze for relationships -->
<?php
$file='blacklist';
$closeness=32768; // 65536 131072;
$minrelated=6;
$sorted=array();
$ips=file($file);
echo '<pre style="white-space:pre-wrap;">',count($ips)," IPs <br>\r\n"; flush();
foreach ($ips as $ip) {
$ip=ip2long(trim($ip)); if ($ip) { $ip=sprintf('%u',$ip); } else { continue; }
foreach ($sorted as $sortkey=>$array) {
if (isset($array[$ip])) { continue 2; }
foreach ($array as $key=>$ignore) {
if (abs($key-$ip)<$closeness) { $sorted[$sortkey][$ip]=''; continue 3; }
}
} $sorted[][$ip]=0;
}
unset($ips); foreach ($sorted as $key=>$array) { if (count($array)<$minrelated) { unset($sorted[$key]); } }
echo count($sorted)," IP groups ($closeness apart, with minimum $minrelated related)<br>\r\n";
foreach ($sorted as $array) {
ksort($array,SORT_NUMERIC);
foreach ($array as $key=>$ignore) { echo long2ip((float)$key),"\t"; }
echo "<br>\r\n";
}
| true |
2d503484149ebfb9c203b6622275a69c1f1d5bc1 | PHP | brufreitas/colec | /classes/thing.class.php | UTF-8 | 682 | 3.015625 | 3 | [] | no_license | <?php
require_once("classes/item.class.php");
require_once("classes/user.class.php");
require_once("func/ConexaoLocal.php");
class thing extends item
{
public $thingUUID;
public $owner;
public function __construct($uuid) {
$q = "SELECT HEX(ownerUUID) AS ownerUUID, itemID FROM tb_thing WHERE thingUUID = 0x{$uuid}";
$con = new ConexaoLocal();
$con->query($q);
if ($con->count == 0) {
echo "Não reconheço thing {$uuid}\n";
unset($con);
return false;
}
parent::__construct($con->result["itemID"]);
$this->owner = new user($con->result["ownerUUID"]);
$this->thingUUID = $uuid;
unset($con);
return true;
}
}
?> | true |
f0808c8edad5a1ad80df10d32a8b1b466ca9188b | PHP | hymns/telegram-php | /src/Traits/Configurable.php | UTF-8 | 621 | 2.828125 | 3 | [
"MIT"
] | permissive | <?php namespace Evdb\TelegramPhp\Traits;
trait Configurable {
protected $defaults = [];
protected $config = [];
public function getDefaults()
{
return $this->defaults;
}
public function getConfig()
{
return $this->config;
}
public function getOption($key, $defaultValue = null)
{
if(isset($this->config[$key])) {
return $this->config[$key];
}
return $defaultValue;
}
public function setOption($key, $value)
{
$this->config[$key] = $value;
return $this;
}
} | true |
5f81a6b32d7d39c212369bae844a60d6a1d52dec | PHP | evolvewebtech/comm-alpha | /commander_alpha/manager/HTTPSession.php | UTF-8 | 14,245 | 3.03125 | 3 | [] | no_license | <?php
require_once dirname(__FILE__).'/AppConfig.php';
/**
*
* Description of HTTPSession
* It will be an entirely self-contained class
* that hides all of PHP’s session_ functions from your application’s main body.
*
* It also provides session variable handling, which bypasses PHP’s own.
* Rather than store multiple variables in a single serialized hash,
* your methodology will use separate table rows for each variable.
* This could speed up access immensely.
* Note, however, that the previous session-handling instruction method
* was not designed to cope with class methods, so you have to be rather cunning in your implementation.
*
* @author francesco
*/
class HTTPSession {
private $php_session_id;
private $native_session_id;
private $dbhandle;
private $logged_in;
private $user_id;
// private $session_timeout = 10800; # 180 minute - 3 hour inactivity timeout
// private $session_lifespan = 18000; # 5 hour session duration
/*
* Edit the following variables
*/
// private $db_host = 'localhost'; // Database Host
// private $db_user = 'root'; // Username
// private $db_pass = ''; // Password
// private $db_name = 'commander'; // Database
/*
*
* Sets up the database connection. This would normally be handled by another class
* in a production environment.
*
* Tells PHP how to handle session events
* in the custom class (discussed in further detail shortly)
*
* Checks whether an existing session identifier is being offered
* by the client before PHP has a chance to get its hands on it
* (which would be the case if the user is in the middle of a session
* instead of starting a new one).
* It also performs various checks on age, inactivity, and the consistency
* of the reported HTTP user agent.
* If it fails, remove it altogether (and any garbage found) so that
* PHP can issue a new session from scratch.
*
* Sets up the session lifespan parameter (which PHP will obey when issuing the cookie itself)
*
* Tells PHP to go ahead and start the session in the normal way
*
*/
public function __construct() {
# Connect to database
$this->dbhandle = mysql_connect(AppConfig::instance()->DB_HOST,AppConfig::instance()->DB_USER,AppConfig::instance()->DB_PASS);
if (!$this->dbhandle) {
die('Could not connect: ' . mysql_error());
}
$seldb = mysql_select_db(AppConfig::instance()->DB_NAME, $this->dbhandle);
if (!$seldb){
die('Could not connect: ' . mysql_error());
}
/*
* The function instructs PHP as to which custom functions to call
* when certain session behavior takes place (such as when a session is started,
* finished, read to, written from, or destroyed)
*
* Set up the handler
*
*/
session_set_save_handler(
array(&$this, '_session_open_method'),
array(&$this, '_session_close_method'),
array(&$this, '_session_read_method'),
array(&$this, '_session_write_method'),
array(&$this, '_session_destroy_method'),
array(&$this, '_session_gc_method')
);
# Check the cookie passed - if one is - if it looks wrong we'll
# scrub it right away
$strUserAgent = $_SERVER["HTTP_USER_AGENT"];
if ($_COOKIE["PHPSESSID"]) {
# Security and age check
$this->php_session_id = $_COOKIE["PHPSESSID"];
/*
$stmt_old = "SELECT id FROM http_session WHERE ascii_session_id = '" .
$this->php_session_id . "' AND ((now() - created) < ' " .
$this->session_lifespan . " seconds') AND user_agent='" .
$strUserAgent . "' AND ((now() - last_impression) <= '".
$this->session_timeout ." seconds' OR last_impression IS NULL)";
*/
$stmt = "SELECT id FROM http_session WHERE ascii_session_id = '" .
$this->php_session_id . "' AND (( TIME_TO_SEC( TIMEDIFF( NOW( ) , created ) )) < ' " .
AppConfig::instance()->SESSION_LIFESPAN . " seconds') AND (( TIME_TO_SEC( TIMEDIFF( NOW( ) , last_impression ) )) <= '".
AppConfig::instance()->SESSION_TIMEOUT ." seconds' OR last_impression IS NULL) AND user_agent='" .
$strUserAgent . "'";
$result = mysql_query($stmt);
if (!$result) {
die('1 - Invalid query: ' . mysql_error());
}
if (mysql_num_rows($result)==0) {
# Set failed flag
$failed = 1;
# Delete from database - we do garbage cleanup at the same time
$maxlifetime = AppConfig::instance()->SESSION_LIFESPAN;
$del_query = "DELETE FROM http_session WHERE (ascii_session_id = '".
$this->php_session_id . "') OR ( TIME_TO_SEC( TIMEDIFF( NOW( ) , created ) ) > '$maxlifetime seconds')";
$result = mysql_query($del_query);
if (!$result) {
die('2 - Invalid query: ' . mysql_error());
}
# Clean up stray session variables
$result = mysql_query("DELETE FROM session_variable WHERE session_id NOT IN (SELECT id FROM http_session)");
if (!$result) {
die('3 - Invalid query: ' . mysql_error());
}
# Get rid of this one... this will force PHP to give us another
unset($_COOKIE["PHPSESSID"]);
};
};
# Set the life time for the cookie
session_set_cookie_params(AppConfig::instance()->SESSION_LIFESPAN);
# Call the session_start method to get things started
session_start();
}
/*
*
* This method touches the session to indicate that a new page impression has taken place.
* Generally, this method would be called on any page that uses
* the session class directly after it has been instantiated.
*
*/
public function Impress() {
if ($this->native_session_id) {
$result = mysql_query("UPDATE http_session SET last_impression = NOW() WHERE id = " . $this->native_session_id);
//var_dump($result);
if (!$result) {
die('4 - Invalid query: ' . mysql_error());
}
}
}
/**
*
* @return <type>
*/
public function IsLoggedIn() {
/*
$stmt = "SELECT logged_in FROM http_session WHERE ascii_session_id = '" .
$this->php_session_id . "' AND ((now() - created) < ' " .
$this->session_lifespan . " seconds') AND ((now() - last_impression) <= '".
$this->session_timeout ." seconds' OR last_impression IS NULL) AND user_agent='" .
$strUserAgent . "'";
*/
$stmt = 'SELECT logged_in'.
' FROM http_session'.
' WHERE ascii_session_id = "'.$this->php_session_id.'"'.
' AND ((TIME_TO_SEC( TIMEDIFF( NOW( ) , created ) )) < \''.AppConfig::instance()->SESSION_LIFESPAN.' seconds\')'.
' AND ((TIME_TO_SEC( TIMEDIFF( NOW( ) , last_impression ) )) <= \''.AppConfig::instance()->SESSION_TIMEOUT.' seconds\')'.
' OR last_impression IS NULL'.
' AND user_agent=\''.$_SERVER["HTTP_USER_AGENT"].'\'';
//print_r($stmt);
$result = mysql_query($stmt);
if(!$result){
return false;
}
$row = mysql_fetch_Row($result);
//var_dump($row);
$this->logged_in = $row;
/*
* -------------------------------------------------
* -------------------------------------------------
*
* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
*
* sistemare! attenzione!
*
*/
if ($this->logged_in[0]==1){
return(true);
}
else
return(false);
}
/**
*
* @return <type>
*/
public function GetUserID() {
if ($this->logged_in) {
return($this->user_id);
} else {
return(false);
};
}
/**
*
* @return <type>
*/
public function GetUserObject() {
if ($this->logged_in) {
require_once dirname(__FILE__).'/DataManager.php';
$objUser = DataManager::getUserAsObject($this->user_id);
if ($objUser) {
return($objUser);
} else {
return(false);
};
}
}
/**
*
* @return <type>
*/
public function GetSessionIdentifier() {
return($this->php_session_id);
}
/**
*
* @param <type> $strUsername
* @param <type> $strPlainPassword
* @return <type>
*/
public function Login($strUsername, $strPlainPassword) {
$strMD5Password = md5($strPlainPassword);
$stmt = "select id FROM cmd_utente_registrato WHERE username='$strUsername' AND md5_pw='$strMD5Password'";
$result = mysql_query($stmt);
if (mysql_num_rows($result)>0) {
$row = mysql_fetch_array($result);
$this->user_id = $row["id"];
$this->logged_in = true;
$result = mysql_query("UPDATE http_session SET logged_in = true, user_id = " . $this->user_id . " WHERE id = " . $this->native_session_id);
return(true);
} else {
return(false);
};
}
/**
*
* @return <type>
*/
public function LogOut() {
if ($this->logged_in == true) {
$result = mysql_query("UPDATE http_session SET logged_in = false, user_id = 0 WHERE id = " . $this->native_session_id);
$this->logged_in = false;
$this->user_id = 0;
return(true);
} else {
return(false);
}
}
public function __get($nm) {
$result = mysql_query("SELECT variable_value FROM session_variable WHERE session_id = " .
$this->native_session_id . " AND variable_name = '" . $nm . "'");
if (mysql_num_rows($result)>0) {
$row = mysql_fetch_array($result);
return(unserialize($row["variable_value"]));
} else {
return(false);
};
}
public function __set($nm, $val) {
$strSer = serialize($val);
$stmt = "INSERT INTO session_variable(session_id, variable_name, variable_value) VALUES(" .
$this->native_session_id . ", '$nm', '$strSer')";
$result = mysql_query($stmt);
}
private function _session_open_method($save_path, $session_name) {
# Do nothing
return(true);
}
public function _session_close_method() {
mysql_close($this->dbhandle);
return(true);
}
/*
* The read()function is used whenever an attempt to retrieve
* a variable from the $_SESSION hash is made.
* It takes the session identifier as its sole operand, and expects
* a serialized representation of $_ SESSION in its entirety to be returned.
*
*/
public function _session_read_method($id) {
# We use this to determine whether or not our session actually exists.
$strUserAgent = $_SERVER["HTTP_USER_AGENT"];
$this->php_session_id = $id;
# Set failed flag to 1 for now
$failed = 1;
# See if this exists in the database or not.
$sel = 'SELECT id, logged_in, user_id FROM http_session WHERE ascii_session_id="' . $id . '"';
$result = mysql_query($sel);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
if (mysql_num_rows($result)>0) {
$row = mysql_fetch_array($result);
$this->native_session_id = $row["id"];
if ($row["logged_in"]==1) {
$this->logged_in = true;
$this->user_id = $row["user_id"];
} else {
$this->logged_in = false;
}
} else {
$this->logged_in = false;
# We need to create an entry in the database
$result = mysql_query("INSERT INTO http_session(ascii_session_id, logged_in,user_id, created, user_agent) VALUES ('$id','f',0,now(),'$strUserAgent')");
# Now get the true ID
$result = mysql_query("SELECT id FROM http_session WHERE ascii_session_id='$id'");
$row = mysql_fetch_array($result);
$this->native_session_id = $row["id"];
}
# Just return empty string
return("");
}
/*
*
* The write()function is used whenever an attempt to change
* or add to $_SESSION is made. It takes the session identifier,
* followed by the preserialized representation of $_SESSION, as its two parameters.
* It expects true to be returned if the data is successfully committed.
* This method is called even if no session variables are registered,
* and it is the first time the generated session ID is revealed to you.
*
*/
public function _session_write_method($id, $sess_data) {
return(true);
}
private function _session_destroy_method($id) {
$result = mysql_query("DELETE FROM http_session WHERE ascii_session_id = '$id'");
return($result);
}
/*
*
* The gc()(garbage cleanup) function should be able to accept the
* “maximum lifetime of session cookies” parameter as its only operand
* and get rid of any sessions older than that lifetime.
* It should return true when it’s done. This function appears
* to be called just before open()so that PHP rids itself
* of any expired sessions before they may be used.
*
*/
private function _session_gc_method($maxlifetime) {
return(true);
}
}
?> | true |
23b1ceda5c3c09073f45f2d38ecd885e2c9382e0 | PHP | tolik505/at | /frontend/widgets/openGraphMetaTags/Widget.php | UTF-8 | 1,524 | 2.609375 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
/**
* Author: Pavel Naumenko
*/
namespace frontend\widgets\openGraphMetaTags;
/**
* Class Widget
*
* @package frontend\widgets\openGraphMetaTags
*/
class Widget extends \yii\base\Widget
{
/**
* @var string
*/
public $title;
/**
* @var string
*/
public $description;
/**
* @var string
*/
public $url;
/**
* @var string
*/
public $image;
/**
*
*/
public function run()
{
$view = $this->getView();
// $this->getView()->registerMetaTag(['property' => 'fb:app_id', 'content' => '']);
$view->registerMetaTag(['property' => 'og:title', 'content' => $this->title]);
$view->registerMetaTag(['property' => 'og:description', 'content' => $this->description]);
$view->registerMetaTag(['property' => 'og:url', 'content' => $this->url]);
$view->registerMetaTag(['property' => 'og:image', 'content' => $this->image]);
$view->registerMetaTag(['property' => 'og:image:width', 'content' => 1024]);
$view->registerMetaTag(['property' => 'og:image:height', 'content' => 512]);
//Twitter
$view->registerMetaTag(['name' => 'twitter:card', 'content' => 'summary_large_image']);
$view->registerMetaTag(['name' => 'twitter:title', 'content' => $this->title]);
$view->registerMetaTag(['name' => 'twitter:description', 'content' => $this->description]);
$view->registerMetaTag(['name' => 'twitter:image', 'content' => $this->image]);
}
}
| true |
a386621fe6e72c9823872f7f37640cd0d980c653 | PHP | indodelta/versi2018 | /database/seeds/BotSeeder.php | UTF-8 | 484 | 2.703125 | 3 | [
"MIT"
] | permissive | <?php
use Illuminate\Database\Seeder;
class BotSeeder extends Seeder
{
const BOT_COUNT = 30;
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$current_count = count(\App\User::bots());
for ($i = $current_count; $i < self::BOT_COUNT; $i++) {
$user = new \App\User([
'name' => 'Bot',
'email' => str_random(40).'@bot.com',
'role' => \App\User::ROLE_BOT
]);
$user->password = str_random(60);
$user->save();
}
}
}
| true |
429a80dff9d0ca0de1ea54a7a0cc57319aa6ef24 | PHP | chuganghong/PHP | /2014/10/10/Sort.class.php | UTF-8 | 2,995 | 3.5 | 4 | [] | no_license | <?php
/**
*排序算法
*/
class Sort
{
private $num = 5;
private $min = 0;
private $max = 20000;
/**
*生成数组
*/
public function generateArr()
{
$arr = array();
for($i=0;$i<$this->num;$i++)
{
$arr[] = mt_rand($this->min,$this->max);
}
return $arr;
}
/**
*insert sort asc
*/
public function insertSortAsc($arr)
{
$count = count($arr);
if($count>1)
{
for($i=1;$i<$count;$i++)
{
$k = $arr[$i];
$j = $i-1;
while( ($j>=0)&&($arr[$j]>$k) )
{
$arr[$j+1] = $arr[$j];
$j--;
}
$arr[$j+1] = $k;
}
}
return $arr;
}
/**
*bubble sort asc---不能理解
*/
public function bubbleSortAsc($arr)
{
$count = count($arr);
for($i=0;$i<$count-1;$i++)
{
for($j=$i+1;$j<$count;$j++)
{
if($arr[$j]<$arr[$i])
{
$tmp = $arr[$i];
$arr[$i] = $arr[$j];
$arr[$j] = $tmp;
}
}
}
return $arr;
}
/**
*select sort asc---记错了,把select sort 记成了bubble sort
*/
public function selectSortAsc($arr)
{
$count = count($arr);
if($count>1)
{
for($i=0;$i<$count-1;$i++)
{
$min = $i;
for($j=$i+1;$j<$count;$j++)
{
if($arr[$j]<$arr[$min])
{
$min = $j;
}
}
if($i != $min)
{
$tmp = $arr[$i];
$arr[$i] = $arr[$min];
$arr[$min] = $tmp;
}
}
}
return $arr;
}
/**
*快速排序
*/
public function quickSortAsc($arr)
{
$count = count($arr);
if($count>1)
{
$k = $arr[0];
$x = array();
$y = array();
for($i=1;$i<$count;$i++)
{
if($arr[$i]<$k)
{
$x[] = $arr[$i];
}
else
{
$y[] = $arr[$i];
}
}
$x = $this->quickSortAsc($x);
$y = $this->quickSortAsc($y);
$arr = array_merge($x,array($k),$y);
}
return $arr;
}
/**
*merge sort asc 归并排序,副程序
*/
public function mergeArr($arr1,$arr2)
{
$arr = array();
while( count($arr1)&&count($arr2) )
{
$arr[] = $arr1[0]<$arr2[0]?array_shift($arr1):array_shift($arr2);
}
return array_merge($arr,$arr1,$arr2);
}
/**
*merge sort asc 归并排序,主程序
*/
public function mergeSortAsc($arr)
{
$count = count($arr);
if($count>1)
{
$mid = intval($count/2);
$arr_left = array_slice($arr,0,$mid);
$arr_right = array_slice($arr,$mid);
$arr_left = $this->mergeSortAsc($arr_left);
$arr_right = $this->mergeSortAsc($arr_right);
$arr = $this->mergeArr($arr_left,$arr_right);
}
return $arr;
}
}
//test
$s = new Sort();
$arr = $s->generateArr();
var_dump($arr);
$arr1 = $s->insertSortAsc($arr);
var_dump($arr1);
$arr2 = $s->selectSortAsc($arr);
var_dump($arr2);
$arr3 = $s->bubbleSortAsc($arr);
var_dump($arr3);
$arr4 = $s->quickSortAsc($arr);
var_dump($arr4);
for($i=0;$i<240;$i++)
{
if($i/120==1)
{
printf('%s','new');
}
printf('%s','-');
}
$arr11 = array(1,2,3);
$arr22 = array(5,7,9);
$arr33 = $s->mergeArr($arr11,$arr22);
var_dump($arr3);
$arr5 = $s->mergeSortAsc($arr);
var_dump($arr5); | true |
589d8dfff275f9a7e8f38f0a7a1da1244603517c | PHP | ankitamit/php_own_code | /book/typeerror.php | UTF-8 | 147 | 2.75 | 3 | [] | no_license | <?php
function xc(array $a){
}
try{
xc(4);
}catch (TypeError $e){
echo 'it is '.$e->getMessage();
}
?>
| true |
d15a74401be900220af6a8bbba5a56edb7cdcdc0 | PHP | yeehaoo/vetapp | /php-scripts/getPetDetailsJson.php | UTF-8 | 1,655 | 2.578125 | 3 | [] | no_license | <?php
if (isset($_POST["pet_id"])) {
$pet_id = $_POST["pet_id"];
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
$db->connect();
$sqlCommand = "SELECT * FROM pets WHERE pet_id = '$pet_id'";
$result = mysqli_query($db->myconn,"$sqlCommand");
if (mysqli_num_rows($result) > 0) {
$response["pets"] = array();
while ($row = mysqli_fetch_array($result)) {
$pet = array();
$pet["pet_id"] = $row["pet_id"];
$pet["pet_name"] = $row["pet_name"];
$pet["pet_userid"] = $row["pet_userid"];
$pet["pet_type"] = $row["pet_type"];
$pet["pet_dob"] = $row["pet_dob"];
$pet["pet_sex"] = $row["pet_sex"];
$pet["visits"] = array();
$sqlCommand2 = "SELECT * FROM visits WHERE visit_petid = '$pet_id'";
$result2 = mysqli_query($db->myconn,"$sqlCommand2");
while($row = mysqli_fetch_array($result2)) {
$visit = array();
$visit["visit_id"] = $row["visit_id"];
$visit["visit_petid"] = $row["visit_petid"];
$visit["visit_userid"] = $row["visit_userid"];
$visit["visit_date"] = $row["visit_date"];
$visit["visit_comments"] = $row["visit_comments"];
$pet["visits"][] = $visit;
}
array_push($response["pets"], $pet);
}
$response["success"] = 1;
} else {
$response["success"] = 0;
$response["message"] = "No pets found";
}
echo json_encode($response);
$db->close($db->myconn);
}
?> | true |
739a58b2ca768c3373ec44489a505fe61cdfaf1f | PHP | Viitainen/Obesethings | /app/Http/Controllers/PlayerController.php | UTF-8 | 2,383 | 2.5625 | 3 | [] | no_license | <?php
namespace App\Http\Controllers;
use App\Player;
use App\Thing;
use Illuminate\Http\Request;
use App\Http\Requests\StorePlayer;
class PlayerController extends Controller
{
public function __construct() {
$this->middleware('auth', ['except' => ['index', 'show']]);
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$players = Player::all();
return view('player.index', compact('players'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('player.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(StorePlayer $request)
{
Player::create($request->all());
return redirect()->action('PlayerController@index')->with('status', 'Player created');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$player = Player::findOrFail($id);
$things = $player->things()->paginate(5);
return view('player.show', compact('player', 'things'));
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$player = Player::findOrFail($id);
return view('player.edit', compact('player'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(StorePlayer $request, $id)
{
$player = Player::find($id);
$player->update($request->all());
return redirect()->action('PlayerController@show', $id)->with('status', 'Player Edited.');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
Player::findOrFail($id)->delete();
return back();
}
}
| true |
1a962bf173cd8262835e704845e3f052c1c8e75d | PHP | vjroby/MarketTradeProcessor | /app/Repositories/EloquentMessageRepository.php | UTF-8 | 2,951 | 2.734375 | 3 | [
"MIT"
] | permissive | <?php
/**
* Created for MarketTradeProcessor.
* User: Robert Gabriel Dinu
* Date: 8/13/15
* Time: 13:52
*/
namespace App\Repositories;
use App\Exceptions\ValidationException;
use App\Models\Message;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Collection;
use LRedis;
use Symfony\Component\HttpFoundation\ParameterBag;
use Validator;
class EloquentMessageRepository implements MessageRepositoryInterface
{
/**
* @var Message
*/
private $messages;
/**
* @param Message $messages
*/
public function __construct(Message $messages)
{
$this->messages = $messages;
}
/**
* @return Collection
*/
public function getAllMessages()
{
return $this->messages->orderBy('messages.created_at','DESC')->get([
self::ID,
self::USER_ID,
self::CURRENCY_FROM,
self::CURRENCY_TO,
self::AMOUNT_SELL,
self::AMOUNT_BUY,
self::RATE,
self::TIME_PLACED,
self::ORIGINATING_COUNTRY,
]);
}
/**
* Method for proce
* @param array $message
* @return mixed
*/
public function manageMessages(ParameterBag $message)
{
$this->sendMessageToRedis($this->saveMessageToDatabase($message->all()));
}
protected function saveMessageToDatabase( $message)
{
$this->validateMessage($message);
$message[self::TIME_PLACED] = new Carbon($message[self::TIME_PLACED]);
$dataBseMessage = $this->messages->newInstance($message);
$dataBseMessage->save();
return $dataBseMessage;
}
protected function sendMessageToRedis(Message $message)
{
$message[self::TIME_PLACED] = $message[self::TIME_PLACED]->toDateTimeString();
$message[self::AMOUNT_BUY] = number_format($message[self::AMOUNT_BUY],2,'.','');
$message[self::AMOUNT_SELL] = number_format($message[self::AMOUNT_SELL],2,'.','');
$message[self::RATE] = number_format($message[self::RATE],4,'.','');
$redis = LRedis::connection();
$redis->publish('message', $message->toJson());
}
protected function validateMessage($message)
{
$validator = Validator::make(
$message,
[
self::USER_ID => ['required', 'numeric'],
self::CURRENCY_FROM => ['required', 'alpha_num','max:3'],
self::CURRENCY_TO => ['required', 'alpha_num','max:3'],
self::AMOUNT_SELL => ['required', 'numeric'],
self::AMOUNT_BUY => ['required', 'numeric'],
self::RATE => ['required', 'numeric'],
self::TIME_PLACED => ['required', 'date'],
self::ORIGINATING_COUNTRY => ['required', 'alpha_num'],
]
);
if ($validator->fails()){
throw new ValidationException($validator->messages());
}
}
} // end of class | true |
675e7630009c56e081af855870ebbd42f21275e0 | PHP | AC32006-Team11/delivrhyno | /DBMSAdvancedQuery1.php | UTF-8 | 1,551 | 2.640625 | 3 | [
"MIT"
] | permissive | <?php include 'header.php'; ?>
<?php
/**
* Displays the results of the first DBMS Advanced MySQL query.
*/
function advancedQuery1()
{
include 'dbConnect.php';
$city = $_GET["city"];
?>
<div class="container">
<div class="row">
<div class="col-md-12">
<h2 style="text-align:center;">You have searched for all staff at the Delivrhyno branch
in <?php echo "$city" ?></h2>
<br>
</div>
</div>
<div class="row">
<div class="col-md-12">
<table class="table table-striped table-bordered table-condensed" style="width:100%";>
<thead>
<tr>
<th>Forename</th>
<th>Surname</th>
<th>Role</th>
<th>Salary</th>
</tr>
</thead>
<?php
if (!empty($city)) {
$query = "SELECT forename, surname, role, salary
FROM employee e, payroll s
WHERE e.employee_id = s.employee_id AND EXISTS
(SELECT * FROM branch b
WHERE e.branch_id = b.branch_id
AND city = '$city') ORDER BY surname ASC;";
$result = mysqli_query($db, $query) or die(mysqli_error($db));
while ($row = mysqli_fetch_array($result)) {
echo '
<tbody>
<td>' . $row[0] . '</td>
<td>' . $row[1] . '</td>
<td>' . $row[2] . '</td>
<td>' . $row[3] . '</td>
</tbody>';
}
}
}
if (isset($_GET["performquery"])) {
advancedQuery1();
} ?>
</tbody>
</table>
</div>
</div>
</div>
<?php include 'footer.php'; ?> | true |
d46070eeaa1768fdd3eef9d2ca7eee838e221504 | PHP | bulb03/ssat | /TRAINER_SALARY_REAL.php | UTF-8 | 21,147 | 2.8125 | 3 | [] | no_license | <?php
//這行要放外面
include_once dirname(__FILE__).'/Utils.php';
class TRAINER_SALARY_REAL
{
private $modelName = "TRAINER_SALARY_REAL";
function connect_db()
{
$servername = "localhost";
$dbname = "guardian";
$account = "root";
$password = "1234";
try{
//資料庫連線
$conn = new PDO("mysql:host=$servername;dbname=$dbname",$account,$password);
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
return $conn;
}
catch(PDOException $e)
{
echo $e->getMessage()."<br>";
}
}
/**
* 新增防護員年度薪資資料
* @param sid 學校編號
* @param tid 防護員編號
* @param year 學年度
* @param grade 學歷
* @param salary 薪資
* @param labor 公提勞保費
* @param injury 公提職災費
* @param employment_insurance 普通事故9.5%及就業保險費1%
* @param NHI 公提健保費
* @param retirement 公提勞退金
* @param bonus 年終獎金
* @param insurance 補充保費
* @return id 防護員年度薪資資料編號(long)
*/
function create($conn, $sid,$tid,$year,$grade,$salary,$labor,$injury,$employment_insurance,$NHI,$retirement,$nominator_bonus,$nominator_insurance,$month,$bonusMonth)
{
date_default_timezone_set('Asia/Taipei');
$date_Year = date("Y");
$date_Month = date("m");
$date_Day = date("d");
$timestamp = strtotime($date_Year.$date_Month.$date_Day);
try{
//輸入mysql指令,使用prepare
$usepdo = $conn->prepare("INSERT INTO ".$this->modelName."(sid, tid, year, grade, salary, labor, injury, employment_insurance, NHI, retirement, bonus, insurance, month, bonus_month,createAt) VALUES(:sid, :tid, :year, :grade, :salary, :labor, :injury, :employment_insurance, :NHI, :retirement, :bonus, :insurance, :month, :bonus_month,:createAt)");
$usepdo->bindParam(':sid',$sid);
$usepdo->bindParam(':tid',$tid);
$usepdo->bindParam(':year',$year);
$usepdo->bindParam(':grade',$grade);
$usepdo->bindParam(':salary',$salary);
$usepdo->bindParam(':labor',$labor);
$usepdo->bindParam(':injury',$injury);
$usepdo->bindParam(':employment_insurance',employment_insurance);
$usepdo->bindParam(':NHI',$NHI);
$usepdo->bindParam(':retirement',$retirement);
$usepdo->bindParam(':bonus',$bonus);
$usepdo->bindParam(':insurance',$insurance);
$usepdo->bindParam(':month',$month);
$usepdo->bindParam(':bonus_month',$bonus_month);
$usepdo->bindParam(':createAt',$timestamp);
$usepdo->execute();
}
catch(PDOException $e)
{
echo $e->getMessage()."<br>";
header("Location:campus_add.php");
}
}
function getCostsTotal($conn,$salaryList)
{
$total = 0;
for ($i = 0; $i < count($salaryList); $i++)
{
$bonus = $salaryList[$i]["bonus"] * $salaryList[$i]["bonus_month"] / 12;
$insurance = $salaryList[$i]["insurance"] * $salaryList[$i]["bonus_month"] / 12;
$total += (
(int)$salaryList[$i]["salary"] * (int)$salaryList[$i]["month"]+
(int)$salaryList[$i]["labor"] * (int)$salaryList[$i]["month"] +
(int)$salaryList[$i]["injury"] * (int)$salaryList[$i]["month"] +
(int)$salaryList[$i]["NHI"] * (int)$salaryList[$i]["month"] +
(int)$salaryList[$i]["retirement"] * (int)$salaryList[$i]["month"] +
(int)$bonus[0]["f0"] +
(int)$insurance[0]["f0"]
);
}
return $total;
}
function getCostsTotal_($conn,$salaryRow)
{
$bonus = (int)$salaryRow[0]["bonus"] * (int)$salaryRow[0]["bonus_month"] / 12;
$insurance = (int)$salaryRow[0]["insurance"] * (int)$salaryRow[0]["bonus_month"] / 12;
$total = (
(int)($salaryRow[0]["salary"]) * (int)($salaryRow[0]["month"]) +
(int)($salaryRow[0]["labor"]) * (int)($salaryRow[0]["month"]) +
(int)($salaryRow[0]["injury"]) * (int)($salaryRow[0]["month"]) +
(int)($salaryRow["NHI"]) * (int)($salaryRow["month"]) +
(int)($salaryRow["retirement"]) * (int)($salaryRow["month"]) +
(int)($bonus("f0")) +
(int)($insurance.ToString("f0"))
);
return total;
}
/**
* 使用 證書號 取得防護員年資
* @param sid 學校編號
* @param year 學年度
* @return
* success : 工作人員資料(DataTable)
* fail : null
*/
function getYearByCertificateNo($conn,$certificateNo)
{
$salaryInfo = $this->listByCertificateNo($conn,$certificateNo);
$year = 0;
$month = 0;
for ($i = 0; $i < count($salaryInfo[0]); $i++)
{
if ($salaryInfo[$i]["year"] != null && (int)$salaryInfo[$i]["year"] != 0 && (int)$salaryInfo[$i]["year"] != (int)$utils->currentSchoolYear())
$month += $salaryInfo[$i]["month"];
}
return ($month % 12 >= 10) ? ($month/12 + 1) : $month/12;
}
/**
* 使用 證書號 取得防護員年資
* @param sid 學校編號
* @param year 學年度
* @return
* success : 工作人員資料(DataTable)
* fail : null
*/
function getYearByTid($conn,$tid)
{
$utils = new Utils;
$salaryInfo = $this->listByTID($conn,$tid);
$year = 0;
$month = 0;
for ($i = 0; $i < count($salaryInfo[0]); $i++)
{
// if ($salaryInfo[$i]["year"] != null && (int)$salaryInfo[$i]["year"] != 0 && (int)$salaryInfo[$i]["year"] != (int)$utils->currentSchoolYear())
// $month += (int)$salaryInfo[$i]["month"];
}
return ($month % 12 >= 10) ? ($month / 12 + 1) : $month / 12;
}
/**
* 使用 學校編號 & 學年度 取得防護員薪資資料
* @param sid 學校編號
* @param year 學年度
* @return
* success : 工作人員資料(DataTable)
* fail : null
*/
function getTrainerSalaryBySIDAndYear($conn, $sid, $year)
{
try
{
$usepdo = $conn->prepare("SELECT * FROM ".$this->modelName." WHERE sid=:sid AND year = :year;");
$usepdo->bindParam(':sid',$sid);
$usepdo->bindParam(':year',$year);
$usepdo->execute();
//取得傳回值
$sql = $usepdo->fetchAll();
if($sql)
{
return $sql;
}
}
catch(PDOException $e){
echo "<script>alert('".$e->getMessage()."')</script>";
header("Location:campus_add.php");
}
}
/**
* 使用 學校編號 & 學年度 取得防護員薪資差額表
* @param sid 學校編號
* @param year 學年度
* @return
* success : 工作人員資料(DataTable)
* fail : null
*/
function getTrainerSalaryDiffBySIDAndYear($conn,$sid,$year)
{
try
{
$usepdo = $conn->prepare("SELECT sid,year,tid,real_tid,grade,real_grade,salary,real_salary,(salary - if (isnull(real_salary), 0, real_salary)) as diff_salary,labor,real_labor,(labor - if (isnull(real_labor), 0, real_labor)) as diff_labor,injury,real_injury,(injury - if (isnull(real_injury), 0, real_injury)) as diff_injury,employment_insurance,real_employment_insurance,(employment_insurance - if (isnull(real_employment_insurance), 0, real_employment_insurance)) as diff_employment_insurance,NHI,real_NHI,(NHI - if (isnull(real_NHI), 0, real_NHI)) as diff_NHI,retirement,real_retirement,(retirement - if (isnull(real_retirement), 0, real_retirement)) as diff_retirement,bonus,real_bonus,(bonus - if (isnull(real_bonus), 0, real_bonus)) as diff_bonus,insurance,real_insurance,(insurance - if (isnull(real_insurance), 0, real_insurance)) as diff_insurance,month,real_month,real_bonus_month FROM trainer_salary_difference WHERE sid = :sid AND year = :year;");
$usepdo->bindParam(':sid',$sid);
$usepdo->bindParam(':year',$year);
$usepdo->execute();
//取得傳回值
$sql = $usepdo->fetchAll();
if($sql)
{
return $sql;
}
}
catch(PDOException $e){
echo "<script>alert('".$e->getMessage()."')</script>";
header("Location:.php");
}
}
/**
* 使用 tid 取得防護員薪資資料
* @param tid 防護員編號(不是證書號)
* @return
* success : 工作人員資料(DataTable)
* fail : null
*/
function getTrainerSalaryByTID($conn,$tid)
{
try
{
$usepdo = $conn->prepare("SELECT * FROM ".$this->modelName." WHERE tid=:tid;");
$usepdo->bindParam(':tid',$tid);
$usepdo->execute();
//取得傳回值
$sql = $usepdo->fetchAll();
if($sql)
{
return $sql;
}
}
catch(PDOException $e){
echo "<script>alert('".$e->getMessage()."')</script>";
header("Location:.php");
}
}
/**
* 使用 證書號 取得單年度防護員薪資資料
* @param certificateNo 證書號
* @param year 學年度
* @return
* success : 工作人員資料(DataTable)
* fail : null
*/
function getTrainerSalaryByCertificateNo($conn,$certificateNo,$year)
{
try
{
$usepdo = $conn->prepare("SELECT a.certificate_no, a.name, a.grade, b.* FROM TRAINER a INNER JOIN TRAINER_SALARY_REAL b ON(a.tid = b.tid) WHERE a.certificate_no = :certificate_no AND b.year = :year;");
$usepdo->bindParam(':certificate_no',$certificate_no);
$usepdo->bindParam(':year',$year);
$usepdo->execute();
//取得傳回值
$sql = $usepdo->fetchAll();
if($sql)
{
return $sql;
}
}
catch(PDOException $e){
echo "<script>alert('".$e->getMessage()."')</script>";
header("Location:.php");
}
}
/**
* 取得全部防護員薪資資料
* @return
* success : 防護員資料(DataTable)
* fail : null
*/
function list_($conn)
{
try
{
$usepdo = $conn->prepare("SELECT * FROM ".$this->modelName);
$usepdo->execute();
//取得傳回值
$sql = $usepdo->fetchAll();
if($sql)
{
return $sql;
}
}
catch(PDOException $e){
echo "<script>alert('".$e->getMessage()."')</script>";
header("Location:.php");
}
}
/**
* 取得單年度全部防護員薪資資料
* @return
* success : 防護員資料(DataTable)
* fail : null
*/
function listByYear($conn,$year)
{
try
{
$usepdo = $conn->prepare("SELECT * FROM ".$this->modelName." WHERE year = :year");
$usepdo->bindParam(':year',$year);
$usepdo->execute();
//取得傳回值
$sql = $usepdo->fetchAll();
if($sql)
{
return $sql;
}
}
catch(PDOException $e){
echo "<script>alert('".$e->getMessage()."')</script>";
header("Location:.php");
}
}
/**
* 取得特定學校全部防護員薪資資料
* @param sid 學校編號
* @return
* success : 防護員資料(DataTable)
* fail : null
*/
function listBySID($conn,$sid)
{
try
{
$usepdo = $conn->prepare("SELECT * FROM ".$this->modelName." WHERE sid = :sid");
$usepdo->bindParam(':sid',$sid);
$usepdo->execute();
//取得傳回值
$sql = $usepdo->fetchAll();
if($sql)
{
return $sql;
}
}
catch(PDOException $e){
echo "<script>alert('".$e->getMessage()."')</script>";
header("Location:.php");
}
}
/**
* 取得特定防護員歷年薪資資料
* @param tid 防護員編號
* @return
* success : 防護員資料(DataTable)
* fail : null
*/
function listByTID($conn,$tid)
{
try
{
$usepdo = $conn->prepare("SELECT * FROM ".$this->modelName." WHERE tid = :tid");
$usepdo->bindParam(':tid',$tid);
$usepdo->execute();
//取得傳回值
$sql = $usepdo->fetchAll();
if($sql)
{
return $sql;
}
}
catch(PDOException $e){
echo "<script>alert('".$e->getMessage()."')</script>";
header("Location:.php");
}
}
/**
* 取得縣市內所有防護員薪資資料
* @param year 學年度
* @param country 縣市
* @return
* success : 防護員資料(DataTable)
* fail : null
*/
function listByCountry($conn,$year,$country)
{
try
{
$usepdo = $conn->prepare("SELECT B.* FROM SCHOOL A INNER JOIN TRAINER_SALARY_REAL B ON ( A.sid = B.sid ) WHERE A.country = :country AND B.year = :year;");
$usepdo->bindParam(':country',$country);
$usepdo->bindParam(':year',$year);
$usepdo->execute();
//取得傳回值
$sql = $usepdo->fetchAll();
if($sql)
{
return $sql;
}
}
catch(PDOException $e){
echo "<script>alert('".$e->getMessage()."')</script>";
header("Location:.php");
}
}
/**
* 取得特定防護員歷年薪資資料 By 證書號
* @param certificateNo 防護員證書號
* @return
* success : 防護員資料(DataTable)
* fail : null
*/
function listByCertificateNo($conn,$certificateNo)
{
try
{
$usepdo = $conn->prepare("SELECT a.certificate_no, a.name, a.grade, b.* FROM TRAINER a INNER JOIN TRAINER_SALARY_REAL b ON(a.tid = b.tid) WHERE a.certificate_no = :certificate_no;");
$usepdo->bindParam(':certificate_no',$certificate_no);
$usepdo->execute();
//取得傳回值
$sql = $usepdo->fetchAll();
if($sql)
{
return $sql;
}
}
catch(PDOException $e){
echo "<script>alert('".$e->getMessage()."')</script>";
header("Location:.php");
}
}
/**
* 取得特定防護員歷年薪資資料 By 證書號 (不包含當學年度)
* @param certificateNo 防護員證書號
* @return
* success : 防護員資料(DataTable)
* fail : null
*/
function listHistoryByCertificateNo($conn,$certificateNo)
{
$utils = new Utils;
$year = $utils->currentSchoolYear();
try
{
$usepdo = $conn->prepare("SELECT a.certificate_no, a.name, a.grade, b.* FROM TRAINER a INNER JOIN TRAINER_SALARY_REAL b ON(a.tid = b.tid) WHERE a.certificate_no = :certificate_no AND b.year < :year;");
$usepdo->bindParam(':certificate_no',$certificate_no);
$usepdo->bindParam(':year',$year);
$usepdo->execute();
//取得傳回值
$sql = $usepdo->fetchAll();
if($sql)
{
return $sql;
}
}
catch(PDOException $e){
echo "<script>alert('".$e->getMessage()."')</script>";
header("Location:.php");
}
}
/**
* 修改防護員薪資資料
* @param id 防護員薪資資料編號
* ### 欄位陣列 與 資料陣列 順序必須對齊 ###
* @param fields 欄位(陣列) e.g. : string[] fields = { "name", "country" };
* @param values 資料(陣列) e.g. : object[] fields = { "中原大學", "桃園市" };
*/
function updateByID($conn, $id, $fields, $values)
{
for ($i=0; $i < count($fields)-1; $i++) {
if ($fields[$i]=="id")
{
throw new Exception("不可變更特定欄位");
}
if ($fields[$i]=="sid")
{
throw new Exception("不可變更特定欄位");
}
if ($fields[$i]=="year")
{
throw new Exception("不可變更特定欄位");
}
}
try
{
$set_update_value = "";
for ($i=0; $i < count($fields)-1; $i++) {
$set_update_value += $fields[$i]."=:".$values[$i]." ";
}
$usepdo = $conn->prepare("UPDATE ".$this->modelName." SET ".$set_update_value."WHERE id=:id;");
for ($i=0; $i < count($values); $i++) {
$usepdo->bindParam($fields[$i],$values[$i]);
}
$usepdo->bindParam(':id',$id);
$usepdo->execute();
return true;
}
catch(Exception $e)
{
echo "<script>alert('".$e->getMessage()."')</script>";
header('Location:coach_visit_rec_revise.php');
}
}
/**
* 刪除單筆防護員薪資資料
* @param id 防護員薪資資料編號
*/
function deleteByID($conn,$id)
{
try
{
$usepdo = $conn->prepare("DELETE FROM ".$this->modelName." WHERE id = :id;");
$usepdo->bindParam(":id",$id);
$usepdo->execute();
if($code){
return true;
}
}
catch(PDOException $e)
{
echo $e->getMessage()."<br>";
}
}
/**
* 刪除學校年度防護員薪資資料
*/
function deleteByYearAndSID($conn,$year,$sid)
{
try
{
$usepdo = $conn->prepare("DELETE FROM ".$this->modelName." WHERE sid = :sid AND year=:year;");
$usepdo->bindParam(":sid",$sid);
$usepdo->bindParam(":year",$year);
$usepdo->execute();
if($code){
return true;
}
}
catch(PDOException $e)
{
echo $e->getMessage()."<br>";
}
}
}
?> | true |
fa013b6a1cb0cc1173ed8c406d01c927f18e0c6e | PHP | octalmage/wib | /php-7.3.0/Zend/tests/const_dereference_003.phpt | UTF-8 | 342 | 2.703125 | 3 | [
"Zend-2.0",
"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--
Const array deference
--FILE--
<?php
error_reporting(E_ALL);
var_dump([1, 2, 3, 4,][3]);
var_dump([1, 2, 3, 4]['foo']);
var_dump([array(1,2,3), [4, 5, 6]][1][2]);
foreach (array([1, 2, 3])[0] as $var) {
echo $var;
}
?>
--EXPECTF--
int(4)
Notice: Undefined index: foo in %sconst_dereference_003.php on line %d
NULL
int(6)
123
| true |
7d239102d95b40e4f9dec46ba5ce9fbe135456b4 | PHP | mondalamit/newsfeed | /login.php | UTF-8 | 845 | 3.140625 | 3 | [] | no_license | <?php
// get username and password
$username = $_POST["usernameLogin"];
$password = $_POST["passwordLogin"];
// create our data object
$data = array();
// decode the accounts file to associative array
$accounts = json_decode(file_get_contents("accounts.json"), True);
// if the username doesn't exist, throw an error
if (!isset($accounts[$username])) {
$data["success"] = False;
$data["message"] = "Incorrect username or password.";
// if the password doesn't match, throw an error
} elseif (!($password == $accounts[$username])) {
$data["success"] = False;
$data["message"] = "Incorrect username or password.";
// otherwise they both match
} else {
$data["username"] = $username;
$data["success"] = True;
$data["message"] = "Login successful.";
}
// final output
header('Content-Type: application/json');
echo json_encode($data);
?> | true |
582078895eb26757ff6d47c8fc31704346d7901e | PHP | xlogix/CP2-android | /clientproj/include/db_connect.php | UTF-8 | 619 | 2.9375 | 3 | [] | no_license | <?php
/**
* A class file to connect to database
*/
class db_connect {
private $conn;
/**
* Function to connect with database
*/
function connect() {
// import database connection variables
require_once __DIR__ . '/db_config.php';
// Connecting to mysql database
$this->conn = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
// return database handler
return $this->conn;
}
/**
* Function to close db connection
*/
function close() {
// closing db connection
mysql_close();
}
}
?> | true |
b51c902f4be27a72e0181d60c6d2a4bfcbec12ca | PHP | ucassh/joeapi | /src/User/About.php | UTF-8 | 1,977 | 2.984375 | 3 | [
"MIT"
] | permissive | <?php
namespace Joe\User;
use Joe\User;
class About
{
/** @var User */
private $user;
private $properties;
private $helloMessage;
private $basicInfo;
private $localization;
private $id;
/**
* @return array
*/
public function getProperties()
{
return $this->properties;
}
/**
* @return mixed
*/
public function getHelloMessage()
{
return $this->helloMessage;
}
/**
* @return array
*/
public function getBasicInfo()
{
return $this->basicInfo;
}
/**
* @return mixed
*/
public function getLocalization()
{
return $this->localization;
}
public function getId()
{
return $this->id;
}
/**
* @param User $user
* @return $this
*/
public function setUser($user)
{
$this->user = $user;
return $this;
}
/**
* @param mixed $properties
* @return $this
*/
public function setProperties($properties)
{
$this->properties = $properties;
return $this;
}
/**
* @param mixed $helloMessage
* @return $this
*/
public function setHelloMessage($helloMessage)
{
$this->helloMessage = $helloMessage;
return $this;
}
/**
* @param mixed $basicInfo
* @return $this
*/
public function setBasicInfo($basicInfo)
{
$this->basicInfo = $basicInfo;
return $this;
}
/**
* @param mixed $localization
* @return $this
*/
public function setLocalization($localization)
{
$this->localization = $localization;
return $this;
}
/**
* @param mixed $id
* @return $this
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* @return User
*/
public function getUser()
{
return $this->user;
}
}
| true |
d72ebfd47c9e72b4ef3afe390707fec1158b374e | PHP | Laghoub/TDW | /Projet_TDW/model/ArticleM.php | UTF-8 | 2,434 | 2.78125 | 3 | [] | no_license | <?php
function delete($id){
try
{
$dbd = new PDO('mysql:host=localhost;dbname=tdw;charset=utf8', 'root', '');
}
catch(Exception $e)
{
die('Erreur : '.$e->getMessage());
}
$articles = $dbd->prepare('DELETE FROM articles WHERE id=?');
$affectedLines = $articles->execute(array($id));
return $affectedLines;
}
function postArticle($nom, $description, $cycle, $image)
{
try
{
$dbd = new PDO('mysql:host=localhost;dbname=tdw;charset=utf8', 'root', '');
}
catch(Exception $e)
{
die('Erreur : '.$e->getMessage());
}
$articles = $dbd->prepare('INSERT INTO articles(nom,description,cycle,image,date_creation) VALUES(?, ?, ?,?,NOW())');
$affectedLines = $articles->execute(array($nom, $description, $cycle,$image));
return $affectedLines;
}
function getarticle()
{
try
{
$db = new PDO('mysql:host=localhost;dbname=tdw;charset=utf8', 'root', '');
}
catch(Exception $e)
{
die('Erreur : '.$e->getMessage());
}
$pdostat = $db->prepare('SELECT * FROM articles ORDER BY date_creation DESC');
$exok= $pdostat->execute();
$forms = $pdostat->fetchAll();
return $forms;
}
function getarticleP()
{
try
{
$db = new PDO('mysql:host=localhost;dbname=tdw;charset=utf8', 'root', '');
}
catch(Exception $e)
{
die('Erreur : '.$e->getMessage());
}
$pdostat = $db->prepare('SELECT * FROM articles WHERE cycle="Primaire" ORDER BY date_creation ASC');
$exok= $pdostat->execute();
$forms = $pdostat->fetchAll();
return $forms;
}
function getarticleM()
{
try
{
$db = new PDO('mysql:host=localhost;dbname=tdw;charset=utf8', 'root', '');
}
catch(Exception $e)
{
die('Erreur : '.$e->getMessage());
}
$pdostat = $db->prepare('SELECT * FROM articles WHERE cycle="Moyen" ORDER BY date_creation ASC');
$exok= $pdostat->execute();
$forms = $pdostat->fetchAll();
return $forms;
}
function getarticleS()
{
try
{
$db = new PDO('mysql:host=localhost;dbname=tdw;charset=utf8', 'root', '');
}
catch(Exception $e)
{
die('Erreur : '.$e->getMessage());
}
$pdostat = $db->prepare('SELECT * FROM articles WHERE cycle="Secondaire" ORDER BY date_creation ASC');
$exok= $pdostat->execute();
$forms = $pdostat->fetchAll();
return $forms;
}
?>
| true |
78cb45e827debec8c4fd0be68ca9700fb53a1602 | PHP | karanbhogle/php | /22.01.2020/q0factorial/index.php | UTF-8 | 263 | 4.1875 | 4 | [] | no_license | <?php
function factorial($number){
$originalNumber = $number;
$factorial = 1;
while($number > 0){
$factorial = $factorial * $number;
$number--;
}
echo 'The Factorial of '.$originalNumber.' is '.$factorial;
}
factorial(5);
?> | true |
f47dbaaa3b0a58a69c49b72905488c242a1c5ee1 | PHP | DeBoerTool/timeline-path-graph | /Tests/UnitTestCase.php | UTF-8 | 853 | 2.59375 | 3 | [
"MIT"
] | permissive | <?php
namespace Dbt\Timeline\Tests;
use Carbon\Carbon;
use PHPUnit\Framework\TestCase;
class UnitTestCase extends TestCase
{
public function ts (int $minutes = 0): Carbon
{
static $now = null;
if (!$now) {
$now = Carbon::now();
}
return $now->copy()->addMinutes($minutes);
}
public static function rs (int $chars): string
{
$string = '';
while (($len = strlen($string)) < $chars) {
$size = $chars - $len;
$bytes = random_bytes($size);
$string .= substr(
str_replace(['/', '+', '='], '', base64_encode($bytes)),
0,
$size
);
}
return $string;
}
public static function ri (int $min, int $max): int
{
return rand($min, $max);
}
}
| true |
04ea7eb16da0f5a1e0153ed28d594ab6494e2805 | PHP | Johanquintero/rredsi | /app/Models/Event.php | UTF-8 | 1,449 | 2.53125 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
class Event extends Model
{
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'location',
'description',
'start_date',
'end_date',
'register_link',
'info_link',
];
protected $appends = ['datesForHumans'];
public function projects() {
return $this->belongsToMany('App\Models\Project', 'event_project', 'event_id', 'project_id');
}
public function educationalInstitutionEvent() {
return $this->hasOne('App\Models\EducationalInstitutionEvent', 'id');
}
public function nodeEvent() {
return $this->hasOne('App\Models\NodeEvent', 'id');
}
public function knowledgeSubareaDisciplines() {
return $this->belongsToMany('App\Models\KnowledgeSubareaDiscipline', 'event_knowledge_subarea_discipline', 'event_id', 'knowledge_subarea_discipline_id');
}
public function getDatesForHumansAttribute()
{
$start_date = Carbon::parse($this->start_date, 'UTC')->locale('es')->isoFormat('DD [de] MMMM [de] YYYY');
$end_date = Carbon::parse($this->end_date, 'UTC')->locale('es')->isoFormat('DD [de] MMMM [de] YYYY');
return "Del $start_date al $end_date";
}
}
| true |
b992887b5740357776271c9503250b9965c4833b | PHP | DarlingXwl/TP-Basic-message-board | /application/index/controller/Index.php | UTF-8 | 2,509 | 2.71875 | 3 | [
"Apache-2.0"
] | permissive | <?php
namespace app\index\controller;
use think\Controller;
use think\View;
class Index extends Controller
{
public function index(){
//调用函数
$arr = show("./mysql.txt");
if($arr){
$newarr=array_reverse($arr);
}else{
$newarr= array(array("没有数据","",""));
}
//设置时区
ini_set('date.timezone','Asia/Shanghai');
//获取页数
if(isset($_GET['page'])){
$page=$_GET['page'];
}else{
$page=1;
}
//前一页
$prepage=$page-1;
if($prepage<=1){
$prepage=1;
}
//最后一页
$lastpage=ceil(count($newarr)/5);
//下一页
$nextpage=$page+1;
if($nextpage>$lastpage){
$nextpage=$lastpage;
}
//截取的数组的开始的下标
$start=($page-1)*5;
//截取数组
$arr=array_slice($newarr,$start,5);
//传值
$this->assign('page',$page);
$this->assign('prepage',$prepage);
$this->assign('nextpage',$nextpage);
$this->assign('lastpage',$lastpage);
$this->assign('arr',$arr);
if(isset($_POST['username'])){
//获取数据
$username = $_POST['username'];
$message = $_POST['message'];
$username=trim($username);
$message=trim($message);
if(strlen($username)==0||strlen($message)==0){
echo "请输入正确的用户名与留言!等待三秒后自动返回首页";
echo '<meta http-equiv="refresh" content="3; url=./index" />';
echo '<a href="./index">首页</a>';
}else{
//时间格式
$date = date("Y-m-d H:i:s");
//拼接数据
$str = $username.'^_^'.$message.'^_^'.$date.'*_*';
//打开文件
$handle = fopen('./mysql.txt','a');
//写入数据
$bool = fwrite($handle,$str);
//判断
if($bool){
echo "留言成功!等待三秒后自动返回首页";
echo '<meta http-equiv="refresh" content="3; url=./index" />';
echo '<a href="./index">首页</a>';
}else{
echo "留言失败!";
}
//关闭数据流
fclose($handle);
}
}else{
//跳转
return $this->fetch('index');
}
}
}
function show($file){
//获取资源
if(file_exists($file)){
$str = file_get_contents($file);
if($str==""){
return FALSE;
}
//分割字符串
$arr = explode("*_*",$str);
//判断数组是否为空
if(count($arr)==0){
return FALSE;
}
//二次分割
$newarry=[];
for($i = 0 ; $i<count($arr)-1; $i++){
$newarry[$i] = explode("^_^",$arr[$i]);
}
return $newarry;
}else{
return FALSE;
}
}
| true |
cfe00e718ad2b93e0f2bcd1fdb805192588cc0e5 | PHP | huize/nicePHP | /src/Request.php | UTF-8 | 5,887 | 2.71875 | 3 | [
"MIT"
] | permissive | <?php
/*LICENSE
+-----------------------------------------------------------------------+
| SilangPHP Framework |
+-----------------------------------------------------------------------+
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by |
| the Free Software Foundation. You should have received a copy of the |
| GNU General Public License along with this program. If not, see |
| http://www.gnu.org/licenses/. |
| Copyright (C) 2020. All Rights Reserved. |
+-----------------------------------------------------------------------+
| Supports: http://www.github.com/silangtech/SilangPHP |
+-----------------------------------------------------------------------+
*/
declare(strict_types=1);
namespace SilangPHP;
class Request
{
// 用户的cookie
public $cookies = [];
// _GET 变量
public $gets = [];
// _POST 变量
public $posts = [];
public $header = [];
public $server = [];
public $method = 'GET';
public $files;
public $raw = '';
public $request;
public $validator = null;
public $hander = null;
public $uri_target = '';
public $uri = '';
public function __construct()
{
if(\SilangPHP\SilangPHP::$http == 1)
{
$this->posts = $_POST ?? [];
$this->gets = $_GET ?? [];
// $this->server = $_SERVER ?? [];
$this->cookies = $_COOKIE ?? [];
$this->request = $_REQUEST ?? [];
$this->files = $_FILES ?? [];
$this->raw = file_get_contents("php://input") ?? '';
$this->withMethod($_SERVER['REQUEST_METHOD']);
$this->withUri($_SERVER["REQUEST_URI"]);
$this->withRequestTarget($_SERVER['REQUEST_URI']);
// 跑取获得的header
foreach ($_SERVER as $key => $val) {
$this->server[strtolower($key)] = $val;
if (substr($key, 0, 5) === 'HTTP_') {
$key = substr($key, 5);
$key = str_replace('_', ' ', $key);
$key = str_replace(' ', '-', $key);
$key = strtolower($key);
$this->header[$key] = $val;
}
}
}
}
public function isAjax()
{
return $this->header["X-Requested-With"] === "XMLHttpRequest";
}
public function getRequestTarget()
{
return $this->uri_target;
}
public function withRequestTarget($requestTarget)
{
$this->uri_target = $requestTarget;
}
public function getMethod()
{
return $this->method;
}
public function withMethod($method)
{
$this->method = $method;
}
public function getUri()
{
return $this->uri;
}
public function withUri($uri, $preserveHost = false)
{
$this->uri = $uri;
}
public function getUploadedFiles()
{
}
/**
* 获得get表单值
*/
public function get( $formname, $defaultvalue = '', $filter_type='' )
{
if( isset( $this->gets[$formname] ) ) {
return $this->filter( $this->gets[$formname], $filter_type );
} else {
return $defaultvalue;
}
}
/**
* 获得post表单值
*/
public function post( $formname, $defaultvalue = '', $filter_type='' )
{
if( isset( $this->posts[$formname] ) ) {
return $this->filter( $this->posts[$formname], $filter_type );
} else {
return $defaultvalue;
}
}
/**
* 获得指定cookie值
*/
public function cookie( $key, $defaultvalue = '', $filter_type='' )
{
if( isset( $this->cookies[$key] ) ) {
return $this->filter( $this->cookies[$key], $filter_type);
} else {
$value = $defaultvalue;
}
return $value;
}
/**
* 获得raw
* postjson
*/
public function getRaw()
{
return $this->raw;
}
/**
* Alias getRaw
* @return false|string
*/
public function postjson()
{
$data = $this->getRaw();
if($data)
{
$data = json_decode($data,true);
}
return $data;
}
/**
* 获取所有
* @param $formname
* @param string $defaultvalue
* @param string $filter_type
* @return mixed|string
*/
public function item($formname, $defaultvalue = '', $filter_type='')
{
// 因为获取有可能是0的情况,所以不判断为空
if( isset( $this->posts[$formname] ) ) {
return $this->filter($this->posts[$formname], $filter_type);
}elseif( isset( $this->gets[$formname] ) ) {
return $this->filter( $this->gets[$formname], $filter_type);
}else{
$value = $defaultvalue;
}
return $value;
}
/**
* 强制转换类型
* @param $value
* @param string $type
*/
public function filter($value, $type = '')
{
switch($type)
{
case 'int':
$value = intval($value);
break;
case 'float':
$value = floatval( $value );
break;
case 'array':
$value = (array)$value;
break;
default:
break;
}
return $value;
}
}
| true |
de512b354a934a3ce584043f6659afce75f6baa9 | PHP | MateHelpers/LemonBundle | /Generator/ViewGenerator.php | UTF-8 | 2,206 | 2.640625 | 3 | [] | no_license | <?php
/**
* This file is part of the MateLemonBundle package.
*
* (c) Mohamed Radhi Guennichi <https://www.mate.tn> <https://github.com/MateHelpers/LemonBundle>
*
* Email: rg@mate.tn - contact@mate.tn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mate\LemonBundle\Generator;
use Mate\LemonBundle\Element\ElementInterface;
use Mate\LemonBundle\Element\EntityProperty;
use Mate\LemonBundle\Element\View;
class ViewGenerator extends GeneratorAbstraction
{
/** @var ElementInterface */
protected $element;
public function __construct(View $view)
{
$this->element = $view;
}
public function buildPattern()
{
$entityLowerName = $this->element->getEntity()->getLowerName();
$entityLowerPluralName = $this->element->getEntity()->getLowerPluralName();
$entityThTag = '';
$entityTdTag = '';
$allowedTypes = [
'string',
'text',
'date',
'datetime',
'boolean'
];
/** @var EntityProperty $property */
foreach ($this->element->getEntity()->getDesiredProperties() as $property) {
if (in_array($propertyType = $property->getType(), $allowedTypes)) {
$propertyName = $property->getName();
$entityThTag.= str_repeat("\t", 5) . "<th>$propertyName</th>" . PHP_EOL;
$dateFormat = '';
if ($propertyType == 'date' || $propertyType == 'datetime')
$dateFormat = '|date(\'Y/m/d\')';
$entityTdTag.= str_repeat("\t", 6) . "<td>{{ $entityLowerName.$propertyName"."$dateFormat"." }}</td>" . PHP_EOL;
}
}
$this->pattern = [
'entityLowerName' => $entityLowerName,
'entityLowerPluralName' => $entityLowerPluralName,
'entityThTag' => $entityThTag,
'entityTdTag' => $entityTdTag,
'updateRoutePath' => $this->element->getController()->getMethod('update')->getRouteName(),
'deleteRoutePath' => $this->element->getController()->getMethod('delete')->getRouteName(),
];
}
} | true |
db779c735cf7a60638a23a047e48413654bb87e3 | PHP | leogoes/GoogleAPI | /app/Http/Controllers/GoogleController.php | UTF-8 | 1,011 | 2.5625 | 3 | [] | no_license | <?php
namespace App\Http\Controllers;
use function GuzzleHttp\json_decode;
use function GuzzleHttp\json_encode;
use phpDocumentor\Reflection\DocBlock\Tags\Return_;
class GoogleController extends Controller
{
public function jsonToPhp($json)
{
$results = json_encode($json, 15, 512);
$results = json_decode($results, false, 512, 15);
$jsonSize = sizeof($json);
// dd($results[0]->created);
return $results;
}
}
// $jsonData = '[
// {
// "nome":"Jason Jones",
// "idade":38,
// "sexo": "M"
// },
// ' .
// '{
// "nome":"Ada Pascalina",
// "idade":35,
// "sexo": "F"
// },'
// .
// '{
// "nome":"Delphino da Silva",
// "idade":26,
// "sexo": "M"
// }';
// $json = '{"empregados": ' .
// $jsonData .
// ']}';
// $url = $json; // path to your JSON file
// $results = json_decode($url); // decode the JSON feed
// return view('index', ['results' => $results]);
| true |
985154de7f3bbf2c3bd34841d3467b9e190c7514 | PHP | c3rberuss/Web-Service-PHP | /application/controllers/Access.php | UTF-8 | 946 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
class Access extends CI_Controller{
function index(){
$usuario = $this->input->post('usuario');
$pass = $this->input->post('password');
$result = $this->User->login($usuario, $pass);
if($result > 0){
$sesion = array(
'username' => $usuario,
'logged_in' => TRUE
);
$this->session->set_userdata($sesion);
header('Location: '.base_url().'home');
}else{
echo "<script>alert('Datos Incorrectos');</script>";
echo "<script>location.href ='".base_url()."';</script>";
}
}
function logout(){
$this->session->unset_userdata('logged_in');
$this->session->unset_userdata('username');
header('Location: '.base_url());
}
}
| true |
824ee1df17d5e77f9cd4e943595c656767907137 | PHP | EasyLinux/LesGumes | /www/_Old/liste_attente_legumes.php | UTF-8 | 5,735 | 2.703125 | 3 | [] | no_license | <?php
include_once("webmaster/define.php");
$ok=-1;/* pas identifier */
if (isset($_COOKIE['identification_amap'])) // Si la variable existe
{
$ok=0; //identifié mais déjà inscrit aux légumes
mysqli_connect(hote, login, mot_passe_sql); // Connexion à MySQL
mysqli_select_db(base_de_donnees); // Sélection de la base
$id=$_COOKIE['identification_amap'];
echo "id cockie=".$id ." et id requete=".$_GET['id'];
$question="SELECT * FROM amap_legumes WHERE id='".$id."'";
$reponse = mysqli_query($question) or die(mysqli_error());
$ligne = mysqli_num_rows($reponse);
if($ligne==0) {
$ok=1; //identifié et non inscrit aux légumes
$question="SELECT * FROM amap_legumes_liste_attente WHERE id='".$id."'";
$reponse = mysqli_query($question) or die(mysqli_error());
$ligne = mysqli_num_rows($reponse);
if($ligne>0) {
$ok=2;} //déjà inscrit sur la liste d'attente
if (isset($_GET['id'])) // Si la variable existe
{
$question="SELECT * FROM amap_legumes_liste_attente WHERE id='".$_GET['id']."'";
echo $question;
$reponse = mysqli_query($question) or die(mysqli_error());
$ligne = mysqli_num_rows($reponse);
if(($ligne==0) && ($_GET['reponse']=='oui')) {
$ok=3; //inscription réussi
$question="SELECT * FROM amap_generale WHERE id='".$_GET['id']."'";
$reponse = mysqli_query($question) or die(mysqli_error());
$donnees = mysqli_fetch_array($reponse);
$question = "INSERT INTO amap_legumes_liste_attente VALUES ('".$_GET['id']."', '".$donnees['Nom']."', '".$donnees['Prenom']."'";
$question.=", '".date('Y-m-d H:m:s')."')";
$reponse = mysqli_query($question) or die(mysqli_error());
}
elseif ($ligne>0 && $_GET['reponse']=='non') {
$ok=4; // désinscription réussi
$question = "DELETE FROM amap_legumes_liste_attente WHERE id='".$_GET['id']."'";
$reponse = mysqli_query($question) or die(mysqli_error());
}
}
}
mysqli_close();
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" >
<!-- xmlns indique une adresse traitant du xHTML -->
<!-- xml:lang : sert à indiquer dans quelle langue est rédigée votre page -->
<head>
<title>AMAP Saint-Sébastien/Loire</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<!-- meta indique que l'on utilise des caractères spécifiques au français éèêà... -->
<link rel="stylesheet" media="screen" type="text/css" title="css_style" href="style.css" />
<link rel="icon" type="image/jpeg" href="images/favicone-2.jpeg" />
</head>
<body>
<div id="en_tete">
<?php include_once("includes/en_tete.php") ?>
</div>
<div id="bandeau">
<?php include_once("includes/bandeau.php") ?>
</div>
<div id="page_principale">
<?php include_once("includes/menu_gauche.php");
if($ok==-1 || $ok==0) {
if($ok==-1) {?>
<h3 class="mot_passe_recette">Il faut vous identifier pour accéder à ce service !!</h3>
<?php }
if($ok==0) { ?>
<h3 class="mot_passe_recette">Vous êtes déjà inscrit à l'AMAP <?php echo $_GET['amap'] ?><br />Allez dans <em style="color:blue"> accès contrat </em>pour vérifier/modifier !!</h3>
<?php } ?>
<?php }
if($ok==1 || $ok==2) { ?>
<?php if($ok==1) { ?><h3 class="mot_passe_recette">Cliquez pour vous inscrire sur la liste d'attente légumes</h3> <?php } ?>
<?php if($ok==2) { ?><h3 class="mot_passe_recette">Cliquez pour vous désinscrire de la liste d'attente légumes</h3> <?php } ?>
<form class="mot_passe_recette" method="post" action="index.php" >
<p class="mot_passe_recette">
<?php if($ok==1) { ?><input type="button" value="Je veux m'inscrire sur la liste d'attente légumes" onclick="window.location.href='liste_attente_legumes.php?id=<?php echo $id; ?>&reponse=oui'" /> <?php } ?>
<?php if($ok==2) { ?><input type="button" value="Je veux me désinscrire de la liste d'attente légumes" onclick="window.location.href='liste_attente_legumes.php?id=<?php echo $id; ?>&reponse=non'" /> <?php } ?>
</p>
</form>
<?php
}
if($ok==3) { ?>
<h3 class="mot_passe_recette">Vous venez d'être ajouté à la liste d'attente légumes.</h3>
<?php }
if($ok==4) { ?>
<h3 class="mot_passe_recette">Vous venez d'être retiré de la liste d'attente légumes.</h3>
<?php }
if($ok>0) {
mysqli_connect(hote, login, mot_passe_sql); // Connexion à MySQL
mysqli_select_db(base_de_donnees); // Sélection de la base
$question="SELECT * FROM amap_legumes_liste_attente ORDER BY Date_inscription";
$reponse = mysqli_query($question) or die(mysqli_error());
$ligne = mysqli_num_rows($reponse);
$n=0;?>
<table class="h3">
<caption class="h3">Le nombre de personnes sur la liste d'attente est de <?php echo $ligne; ?></caption>
<tr>
<th>Nom</th><th>Date d'inscription</th><th>Votre ordre dans la liste</th>
</tr> <?php
while($donnees=mysqli_fetch_array($reponse)) {
$n++;?>
<tr>
<td class="h3"><?php echo $donnees['Nom']." ".$donnees['Prenom']; ?></td>
<td class="h3"><?php echo date("d-M-Y H:m:s",strtotime($donnees['Date_inscription'])); ?></td>
<td class="h3"><?php echo $n; ?></td>
</tr>
<?php } ?>
</table>
<?php
mysqli_close();
} ?>
</div>
<div id="pied_page">
<!--<?php include_once("includes/pied_page.php") ?>-->
</div>
<p>
<!--<img src="images/logo_lesgumes.jpeg" alt="Logo de l'AMAP" title="Groupement Uni pour un Meilleur Environnement Solidaire" /> -->
<!-- alt indique un texte alternatif au cas où l'image ne peut pas être téléchargée -->
</p>
</body>
</html>
| true |
fbbdbd6fb2f72292f72e871ded4cb8b868f99fa2 | PHP | fil-blue/avcms | /src/AVCMS/Bundles/Games/Model/FeedGamesFinder.php | UTF-8 | 1,023 | 2.53125 | 3 | [
"MIT"
] | permissive | <?php
/**
* User: Andy
* Date: 09/02/15
* Time: 17:03
*/
namespace AVCMS\Bundles\Games\Model;
use AV\Model\Finder;
class FeedGamesFinder extends Finder
{
public function status($status = null)
{
if ($status !== 'pending' && $status !== 'rejected' && $status !== 'imported' && $status !== 'all') {
$status = 'pending';
}
if ($status !== 'all') {
$this->currentQuery->where('status', $status);
}
return $this;
}
public function feed($feed = null)
{
if ($feed) {
$this->currentQuery->where('provider', $feed);
}
return $this;
}
public function fileType($filetype = null)
{
if ($filetype) {
$this->currentQuery->where('file_type', $filetype);
}
return $this;
}
public function category($term)
{
if (!$term) {
return $this;
}
$this->currentQuery->where('category', 'LIKE', '%'.$term.'%');
}
}
| true |
3e6edbe410291c66f89e3adc963f002cb1639261 | PHP | excelwebzone/EWZFormBuilderBundle | /Model/Field.php | UTF-8 | 4,334 | 2.859375 | 3 | [
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] | permissive | <?php
namespace EWZ\Bundle\FormBuilderBundle\Model;
use DateTime;
/**
* Storage agnostic field object.
*/
abstract class Field implements FieldInterface
{
// form tools
const TYPE_HEAD = 'head';
const TYPE_TEXT = 'text';
const TYPE_TEXTBOX = 'textbox';
const TYPE_TEXTAREA = 'textarea';
const TYPE_DROPDOWN = 'dropdown';
const TYPE_RADIO = 'radio';
const TYPE_CHECKBOX = 'checkbox';
// quick tools
const TYPE_FULLNAME = 'fullname';
const TYPE_EMAIL = 'email';
const TYPE_PHONE = 'phone';
const TYPE_DATETIME = 'datetime';
const TYPE_TIME = 'time';
const TYPE_BIRTHDAY = 'birthday';
const TYPE_NUMBER = 'number';
// power tools
const TYPE_FORMCOLLAPSE = 'formcollapse';
const TYPE_MATRIX = 'matrix';
const TYPE_CALCULATION = 'calculation';
/**
* Field id
*
* @var integer
*/
protected $id;
/**
* Field name
*
* @var string
*/
protected $name;
/**
* Field type
*
* @var string
*/
protected $type;
/**
* Field attributes
*
* @var array
*/
protected $attributes;
/**
* List of cells
*
* @var array
*/
protected $cells = array();
/**
* @var DateTime
*/
protected $dateCreated;
/**
* @var DateTime
*/
protected $lastModified;
/**
* @return string
*/
public function __toString()
{
return $this->getName();
}
/**
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @param string $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* @return string
*/
public function getType()
{
return $this->type;
}
/**
* @param string $type
*/
public function setType($type)
{
$this->type = $type;
}
/**
* @param string $key
* @param string $default
*
* @return mix
*/
public function getAttribute($key, $default = null)
{
return isset($this->attributes[$key]) ? $this->attributes[$key] : $default;
}
/**
* @return array
*/
public function getAttributes()
{
return $this->attributes ?: $this->attributes = array();
}
/**
* @param array $attributes
*/
public function setAttributes(array $attributes = array())
{
$this->attributes = $attributes;
}
/**
* @param string $key
* @param string $value
*/
public function setAttribute($key, $value)
{
$this->attributes[$key] = $value;
}
/**
* @param string $key
*/
public function removeAttribute($key)
{
if (isset($this->attributes[$key])) {
unset($this->attributes[$key]);
}
}
/**
* Gets the form cells.
*
* @return array
*/
public function getCells()
{
return $this->cells ?: $this->cells = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Gets the forms.
*
* @return array
*/
public function getForms()
{
$forms = array();
foreach ($this->getCells() as $cell) {
$forms[] = $cell->getForm();
}
return $forms;
}
/**
* @return DateTime
*/
public function getDateCreated()
{
return $this->dateCreated;
}
/**
* @param DateTime $dateCreated
*/
public function setDateCreated(DateTime $dateCreated)
{
$this->dateCreated = $dateCreated;
}
/**
* @return DateTime
*/
public function getLastModified()
{
return $this->lastModified;
}
/**
* @param DateTime $lastModified
*/
public function setLastModified(DateTime $lastModified)
{
$this->lastModified = $lastModified;
}
}
| true |
7bc57c6927f00dddbdd94a50974c7e313c5d0f72 | PHP | kmarshall95/main-site-mock-up | /v6.0/php/c.php | UTF-8 | 2,534 | 2.5625 | 3 | [] | no_license | <?php
if(isset($_POST['email']))
{
$email_to = "kyle28marshall@gmail.com";
$email_subject = 'BBD New Client Email';
function died($error){
echo "We are very sorry, but there were error(s) found with the form<br />";
echo "There errors appeared below.<br /><br />";
echo $error."<br /><br />";
echo "Please go back and fix these errors<br /><br />";
die();
}
if(!isset($_POST['firstname']) ||
!isset($_POST['lastname']) ||
!isset($_POST['email']) ||
!isset($_POST['phone']) ||
!isset($_POST['message'])) {
died('We are very sorry, but there were error(s) found with the form');
}
$fname = $_POST['firstname'];
$lname = $_POST['lastname'];
$email = $_POST['email'];
$num = $_POST['phone'];
$mes = $_POST['message'];
$cur = $_POST['curSite'];
$devType = $_POST['developmentType'];
$gdevType = $_POST['gdevelopmentType'];
$finishDate = $_POST['startdate'];
$error_message ="";
$email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error_message .= "Email is not valid" .$email."\n";
died('We are very sorry, but there were error(s) found with the form');
}
if(strlen($mes) < 2 ){
$error_message .= 'The Message does not appear to be valid. Length must be greater than 2 characters.<br />';
}
if(strlen($error_message) > 0 ){
died($error_message);
}
$email_message = "Form details below.\n\n";
function clean_string($string){
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "First Name: ".clean_string($fname)."\n";
$email_message .= "Last Name: ".clean_string($lname)."\n";
$email_message .= "Email: ".clean_string($email)."\n";
$email_message .= "Message: ".clean_string($mes)."\n";
$email_message .= "Current Website Link: ".clean_string($cur)."\n";
$email_message .= "Development Type: ".clean_string($devType)."\n";
$email_message .= "Graphic Design: ".clean_string($gdevType)."\n";
$email_message .= "Expected Finish Date: ".clean_string($finishDate)."\n";
$headers = 'From: '.$email."\r\n".
'Reply-To: '.$email."\r\n".
'X-Mailer:PHP/'.phpversion();
mail($email_to,$email_subject,$email_message, $headers);
echo "Thank you for contacting us. We will be in touch with you very soon.";
?>
<?php
}
?>
| true |
ad3a092c3460ccca1437a5e6fa802ff121f630eb | PHP | bigr/newmap1 | /data/stylesheets/general/inc/utils.php | UTF-8 | 6,520 | 2.609375 | 3 | [] | no_license | <?php
require_once dirname(__FILE__)."/colors.php";
function getPixelSize($zoom) {
return 40079171.1277036*cos(0.0174532925*50)/pow(2,($zoom+8));
}
function interpolate($def,$zoom, $transport, $transportI) {
if ( !is_array($def) )
throw new Exception("Need definition");
$convert = function ($z,$a) use($transport) {
if ( is_array($a) ) {
return array_map(function($x) use($transport,$z) {return $transport($z,floatval($x));}, $a);
}
else if ( $a[0] == '#' )
return array_map(function($x) use($transport,$z) {return $transport($z,floatval(hexdec($x)));}, str_split(substr($a,1),2));
else
return array($transport($z,floatval($a)));
};
$deconvert = function ($z,$a) use($transportI) {
if ( count($a) == 3 )
return '#'.implode(array_map(function ($x) use($transportI,$z) {return str_pad(dechex(intval($transportI($z,$x))),2,'0',STR_PAD_LEFT);},$a),'');
else if ( count($a) == 1 ) {
return $transportI($z,$a[0]);
}
else
return array_map(function ($x) use($transportI,$z) {return ceil($transportI($z,$x));},$a);
};
$lv = null;
$lk = ~PHP_INT_MAX;
if ( empty($def) ) {
throw new Exception('Empty definition in interpolate.');
}
foreach ( $def as $k => $v ) {
$hex = $v[0] == '#';
$v = $convert($k,$v);
if ( $lv == null )
$lv = $v;
if ( $zoom > $lk and $zoom <= $k ) {
for ( $i = 0; $i < count($v); ++$i ) {
$ret[$i] = ($lv[$i] * ($k-$zoom))/($k - $lk) + ($v[$i] * ($zoom-$lk))/($k - $lk);
}
return $deconvert($zoom,$ret);
}
$lk = $k;
$lv = $v;
}
return $deconvert($zoom,$convert($lk,$def[$lk]));
}
function blackandwhite($color) {
$rgb = array_map(function($x) {return floatval(hexdec($x));}, str_split(substr($color,1),2));
$c = str_pad(dechex(intval((0.3 * $rgb[0] + 0.59*$rgb[1] + 0.11 * $rgb[2]))),2,'0',STR_PAD_LEFT);
return "#$c$c$c";
}
function darken($color,$percent) {
$hsl = RGBToHSL(HTMLToRGB($color));
$l = ($hsl & 0xFF) * (1 - $percent/100.0);
if ( $l > 0xFF ) $l = 0xFF;
$hsl = $hsl & (0xFFFF00 & $hsl) | $l;
return RGBToHTML(HSLToRGB($hsl));
}
function darken_a($color_a,$percent) {
return array_map(function($_c) use($percent) { return darken($_c,$percent); },$color_a);
}
function linear($def,$zoom) {
return interpolate(
$def, $zoom,
function($zoom,$x) {return $x;},
function($zoom,$x) {return $x;}
);
}
function exponential($def,$zoom) {
return interpolate(
$def, $zoom,
function($zoom,$x) {return $x < 0.01 ? log(0.01) : log($x);},
function($zoom,$x) {return exp($x);}
);
}
function meterlengthes($def,$zoom) {
return interpolate(
$def, $zoom,
function($z,$x) {return $x;},
function($z,$x) {return $x/getPixelSize($z);}
);
}
function pixelareas($def,$zoom) {
return interpolate(
$def, $zoom,
function($z,$x) {return $x;},
function($z,$x) {return $x*pow(getPixelSize($z),2);}
);
}
function svg2png($file, $svg) {
$im = new Imagick();
$im->setBackgroundColor(new ImagickPixel('transparent'));
$im->readImageBlob($svg);
$im->setImageFormat("png24");
$im->writeImage($file);
$im->clear();
$im->destroy();
}
function propertyToSql($string) {
$array = explode(',',$string);
$query = array();
foreach ( $array as $item) {
$item = ltrim($item,'[');
$item = rtrim($item,']');
$subarray = explode('][',$item);
$subquery = array();
foreach( $subarray as $subitem ) {
if ( $subitem[0] == '.' )
continue;
if ( !preg_match('/[\"]?([\w:]+)[\"]?\s*(=|\!=|\<|\>)\s*[\']?([^\']+)[\']?/',$subitem, $matches) ) {
throw new Exception("Error during parsint properties: $subitem");
}
$operator = $matches[2];
$column = $matches[1];
$value = addslashes($matches[3]);
if ( $value == 'no' && $operator == '=' ) {
$subquery[] = "( \"$column\" IS NULL OR \"$column\" = 'no' )";
}
else if ( $value == 'no' && $operator == '!=' ) {
$subquery[] = "( \"$column\" IS NOT NULL AND \"$column\" <> 'no' )";
}
else {
if ( $operator == '!=' ) $operator = '<>';
$subquery[] = "(COALESCE(\"$column\",'') $operator '$value')";
}
}
if ( !empty($subquery) ) {
$query[] = '('.implode(" AND ",$subquery).')';
}
$ret = '('.implode(" OR ",$query).')';
}
return $ret;
}
function getPropertyWhereQuery($conf) {
$query = array();
foreach ( array_keys($conf) as $string ) {
$query[] = '('.propertyToSql($string).')';
}
$query = implode(' OR ',$query);
return $query;
}
function getPropertyTypeQuery($conf) {
$ret = " (CASE ";
$i = 0;
foreach ( array_keys($conf) as $string ) {
$ret .= " WHEN ";
$ret .= '('.propertyToSql($string).')';
$ret .= " THEN " . ($i+1) ."\n";
++$i;
}
$ret .= " END) ";
return $ret;
}
function interval2selector($intervals,$field, $function = null) {
if ( empty($function) ) {
$function = function($x) {return $x;};
}
list($values,$items) = array(array_keys($intervals), array_values($intervals));
$ret = array();
for ( $i = 1; $i<count($values); ++$i ) {
$from = round($function($values[$i-1])) .'.1';
$to = round($function($values[$i])) .'.1';
$ret["[$field >= $from][$field < $to]"] = $items[$i-1];
}
$from = round($function(end($values))) .'.1';
$ret["[$field >= $from]"] = end($items);
return $ret;
}
function pixelarea2selector($areas,$zoom) {
return interval2selector($areas, 'way_area',function($x) use($zoom) { return $x*pow(getPixelSize($zoom),2); });
}
function expex($coefs,$value) {
$ret = 1;
for ( $i = 0; $i <= $value; ++$i ) {
$ret *= linear($coefs,$i);
}
return $ret;
}
function text_limiter($size) {
$size = $size >= 19
? $size
: 19 + 0.4 * ($size - 19);
$size = $size >= 14
? $size
: 14 + 0.3 * ($size - 14);
$size = $size >= 12
? $size
: 12 + 0.2 * ($size - 12);
$size = $size <= 30.0
? $size
: 30.0 + 0.7 * ($size - 30.0);
$size = $size <= 45.0
? $size
: 45.0 + 0.8 * ($size - 45.0);
$size = $size <= 120.0
? $size
: 120.0 + 0.75 * ($size - 120.0);
return $size;
}
function justModulo($col,$modulo) {
switch ( $modulo ) {
case 2:
return "$col =~ \"^\\d*[2468](\\.[0]*$|$)\"";
case 5:
return "$col =~ \"^\\d*[5](\\.[0]*$|$)\"";
case 10:
return "$col =~ \"^\\d*[1379]0(\\.[0]*$|$)\"";
case 20:
return "$col =~ \"^\\d*[2468]0(\\.[0]*$|$)\"";
case 50:
return "$col =~ \"^\\d*[5]0(\\.[0]*$|$)\"";
case 100:
return "$col =~ \"^\\d*[1379]00(\\.[0]*$|$)\"";
case 200:
return "$col =~ \"^\\d*[2468]00(\\.[0]*$|$)\"";
case 500:
return "$col =~ \"^\\d*[5]00(\\.[0]*$|$)\"";
}
}
| true |
9e8fdd86c1d4ba5fb3d68f8fca481b193a5e2c7f | PHP | norse-blue/php-prim | /src/Extensions/Scalars/String/StringIsUrlExtension.php | UTF-8 | 1,332 | 2.9375 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types=1);
namespace NorseBlue\Prim\Extensions\Scalars\String;
use NorseBlue\ExtensibleObjects\Contracts\ExtensionMethod;
use NorseBlue\Prim\Types\Scalars\BoolObject;
use NorseBlue\Prim\Types\Scalars\IntObject;
use NorseBlue\Prim\Types\Scalars\StringObject;
use function NorseBlue\Prim\Functions\bool;
final class StringIsUrlExtension extends StringObject implements ExtensionMethod
{
/**
* @return callable(int|IntObject $flags = FILTER_FLAG_NONE): BoolObject
*/
public function __invoke(): callable
{
/**
* Checks if the string is an url.
*
* @param int|IntObject $flags Allowed flags:
* - FILTER_FLAG_SCHEME_REQUIRED
* - FILTER_FLAG_HOST_REQUIRED
* - FILTER_FLAG_PATH_REQUIRED
* - FILTER_FLAG_QUERY_REQUIRED
*
* @return \NorseBlue\Prim\Types\Scalars\BoolObject
*
* @see https://www.php.net/manual/en/function.filter-var.php
*/
return function ($flags = FILTER_FLAG_NONE): BoolObject {
return bool(
filter_var($this->value, FILTER_VALIDATE_URL, IntObject::unwrap($flags)) !== false
);
};
}
}
| true |
21a434b59300748ea0970d1c651e9969b46724bd | PHP | diego-mi/skeleton-front | /site/Config/Connection.php | UTF-8 | 246 | 3.015625 | 3 | [] | no_license | <?php
//File for connection, is recommended using PDO library.
function connection()
{
try
{
$pdo = new PDO('mysql:host=localhost;dbname=skeleton', 'root', '');
return $pdo;
}
catch (PDOException $e)
{
return $e->getMessage();
}
} | true |
4e25295e448cf04e29ca571b2b81ab81f568592a | PHP | Zeeshan-H/LaravelChatApp | /app/Http/Middleware/Login.php | UTF-8 | 550 | 2.59375 | 3 | [] | no_license | <?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Auth;
use DB;
class Login
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
if(DB::table('users')->where('email', 'zeeshan@gmail.com')->where('password', 1234)->first())
{
return $next($request);
}
return redirect()->route('home.error');
}
}
| true |
5758367cc3fc396726a272f6143dd65d5e4cf9bd | PHP | rdijana/kvizgradovi | /modules/kontaktPoruka.php | UTF-8 | 1,526 | 2.53125 | 3 | [] | no_license | <?php
include "../konekcija/konekcija.php";
header("Content-Type:application/json");
$podaci=null;
if(isset($_POST["send"])){
$ime=$_POST['ime'];
$prezime=$_POST['prezime'];
$email=$_POST['email'];
$poruka=$_POST["poruka"];
$greske=[];
$reImePrezime="/^[A-ZĆČŽŠĐ]{1}[a-zćčžšđ]{2,14}(\s[A-ZĆČŽŠĐ]{1}[a-zćčžšđ]{2,14})?$/";
$reEmail="/^[a-z][a-z\d\.\-\_]+\@[a-z\d]+(\.[a-z]{2,4})+$/";
$rePoruka="/^([\w\d\n\s\,\.\!\?])+$/";
if(!preg_match($reImePrezime,$ime)){
array_push($greske,"Ime nije u dobrom formatu");
}
if(!preg_match($reImePrezime,$prezime)){
array_push($greske,"Prezime nije dobrog formata");
}
if(!preg_match($rePoruka,$poruka)){
array_push($greske,"Lozinka nije u dobrom formatu");
}
if(!preg_match($reEmail,$email)){
array_push($greske,"Email nije ok");
}
if(count($greske)){
$podaci=$greske;
}else{
$upit="UPDATE korisnik SET poruka=:poruka WHERE ime=:ime AND prezime=:prezime AND email=:email";
$pripremi=$konekcija->prepare($upit);
$pripremi->bindParam(":ime",$ime);
$pripremi->bindParam(":prezime",$prezime);
$pripremi->bindParam(":email",$email);
$pripremi->bindParam(":poruka",$poruka);
try{
$kod=$pripremi->execute()?201:300;
}catch(PDOException $e){
$podaci=$e;
}
}
}
http_response_code($kod);
echo json_encode($podaci);
?> | true |
85de6048a90bc79a7a1da64cfcc142bebb031892 | PHP | callcocam/core-flexe-framework | /v1/src/Validate/Rules/MaxLength.php | UTF-8 | 546 | 2.8125 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: caltj
* Date: 01/09/2018
* Time: 21:13
*/
namespace Flexe\Validate\Rules;
class MaxLength extends AbstractRules
{
protected $message = 'must be shorter than %s characters';
public function validate($key, $value, $ruleValue)
{
$this->prepare($ruleValue);
if(strlen($value) > $this->ruleValue)
{
if(!empty($value))
{
return sprintf($this->message, $this->ruleValue);
}
}
return null;
}
} | true |
5f5182da8301f25908cfc6b85cbe2764f3746993 | PHP | jcgut/AN-GCS | /script_objetos_digitales/createDigitalObjects.php | UTF-8 | 2,990 | 2.5625 | 3 | [] | no_license | <?php
$servername = "localhost";
$username = "greencore";
$password = "greencore";
$conn = new mysqli($servername, $username, $password);
$result = mysqli_query($conn, "SELECT * from isad_g_clean.unidades_descriptivas_h2 where Codigo='CR-AN-AH-PREP-DPRES-EXPFTG'");
sqlToCSV($result);
function sqlToCSV($queryResult){
$CSVData = "identifier,filename\n";
while($record = mysqli_fetch_object($queryResult)){
$identificador = "";
if(!empty($record->Codigo) && $record->Codigo!="NULL")
$identificador .= "$record->Codigo";
else
$identificador .= "";
if(!empty($record->Signatura_Inicial))
$identificador .= "-$record->Signatura_Inicial";
else
$identificador .= "";
if(!empty($record->Signatura_Final))
$identificador .= "-$record->Signatura_Final";
else
$identificador .= "";
if(!empty($record->Tomo_Folio))
$identificador .= "-$record->Tomo_Folio";
else
$identificador .= "";
if(!empty($record->Folio))
$identificador .= "-$record->Folio";
else
$identificador .= "";
if(!empty($record->Escritura))
$identificador .= "-$record->Escritura";
else
$identificador .= "";
if(!empty($record->Signatura_Inicial) && empty($record->Signatura_Final)){
foreach(glob("/home/adminatom/FedericoTinocoGranados/$record->Signatura_Inicial/*.*") as $filename){
if($filename != "/home/adminatom/FedericoTinocoGranados/$record->Signatura_Inicial/Thumbs.db")
$CSVData .= "$identificador,$filename\n";
}
}
elseif(!empty($record->Signatura_Inicial) && !empty($record->Signatura_Final)){
$c = $record->Signatura_Inicial;
$d = $record->Signatura_Final;
$a = (int)$c;
$b = (int)$d;
for($i=$a; $i<=$b; $i++) {
$num = str_pad($i,6,"0",STR_PAD_LEFT);
foreach(glob("/home/adminatom/FedericoTinocoGranados/$num/*.*") as $filename){
$CSVData .= "$identificador,$filename\n";
}
}
}else
$identificador .= "";
$identificador = "";
}
$myfile = fopen('/home/adminatom/directorio-cargas-objetos-digitales/outputs/file-CR-AN-AH-PREP-DPRES-EXPFTG.csv', 'w') or die('Unable to open file!');
fwrite($myfile, $CSVData);
fclose($myfile);
}
| true |
a45117eab7ec80b5d9959a9832245f250e2f80a3 | PHP | znarf/blogmarks3 | /classes/registry.php | UTF-8 | 1,326 | 2.75 | 3 | [] | no_license | <?php namespace blogmarks;
class registry
{
static $services = [];
static function service($name)
{
if (isset(self::$services[$name])) {
return self::$services[$name];
}
else {
return self::$services[$name] = blogmarks::instance("\\blogmarks\\service\\{$name}");
}
}
static $models = [];
static function model($name)
{
if (isset(self::$models[$name])) {
return self::$models[$name];
}
else {
return self::$models[$name] = blogmarks::instance("\\blogmarks\\model\\{$name}");
}
}
static $tables = [];
static function table($name)
{
if (isset(self::$tables[$name])) {
return self::$tables[$name];
}
else {
return self::$tables[$name] = blogmarks::instance("\\blogmarks\\model\\table\\{$name}");
}
}
static $feeds = [];
static function feed($name)
{
if (isset(self::$feeds[$name])) {
return self::$feeds[$name];
}
else {
return self::$feeds[$name] = blogmarks::instance("\\blogmarks\\model\\feed\\{$name}");
}
}
static $searchs = [];
static function search($name)
{
if (isset(self::$searchs[$name])) {
return self::$searchs[$name];
}
else {
return self::$searchs[$name] = blogmarks::instance("\\blogmarks\\model\\search\\{$name}");
}
}
}
| true |
e25bcfec8c04408bf6e5ca667e58a115dcefbe0c | PHP | yuandehong/laravel-smart | /database/migrations/2017_10_20_100900_create_sys_func_privilege_table.php | UTF-8 | 707 | 2.546875 | 3 | [] | no_license | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateSysFuncPrivilegeTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('sys_func_privilege', function (Blueprint $table) {
$table->increments('id');
$table->integer('func_id');
$table->enum('name' , ['read' , 'create' , 'update' , 'delete']);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('sys_func_privilege');
}
}
| true |
b93b2b98605ad833f76c26913fc1837a83e8f634 | PHP | webdev498/laravel-marionette-tutora | /app/Observers/ImageObserver.php | UTF-8 | 510 | 2.65625 | 3 | [] | no_license | <?php namespace App\Observers;
use App\Image;
use App\FileHandlers\Image\ImageUploader;
class ImageObserver
{
/**
* @var ImageUploader
*/
protected $uploader;
/**
* Create an instance of the observer.
*
* @param ImageUploader $uploader
*/
public function __construct(
ImageUploader $uploader
)
{
$this->uploader = $uploader;
}
public function deleting(Image $image)
{
$this->uploader->removeImage($image);
}
}
| true |
158fc4eb616029cf323f83a56d0fb6dcac4bc4df | PHP | kabachello/phpOLAPi | /src/phpOLAPi/Xmla/Metadata/CellData.php | UTF-8 | 1,440 | 2.796875 | 3 | [
"MIT"
] | permissive | <?php
/*
* This file is part of phpOlap.
*
* (c) Julien Jacottet <jjacottet@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace phpOLAPi\Xmla\Metadata;
use phpOLAPi\Metadata\CellDataInterface;
use phpOLAPi\Xmla\Metadata\MetadataBase;
/**
* CellData
*
* @package Xmla
* @subpackage Metadata
* @author Julien Jacottet <jjacottet@gmail.com>
*/
class CellData implements CellDataInterface
{
protected $value;
protected $formatedValue;
protected $formatString;
/**
* Return cell value
*
* @return float Cell value
*
*/
public function getValue()
{
return $this->value;
}
/**
* Return formated value
*
* @return String Cell formated value
*
*/
public function getFormatedValue()
{
return $this->formatedValue;
}
/**
* Return format
*
* @return String Cell format
*
*/
public function getFormatString()
{
return $this->formatString;
}
/**
* Hydrate Element
*
* @param DOMNode $node Node
* @param Connection $connection Connection
*
*/
public function hydrate(\DOMNode $node)
{
$this->value = MetadataBase::getPropertyFromNode($node, 'Value', true);
$this->formatedValue = MetadataBase::getPropertyFromNode($node, 'FmtValue', true);
$this->formatString = MetadataBase::getPropertyFromNode($node, 'FormatString', true);
}
} | true |
738ab93dd3021c45e05cb658d953189fd663bec8 | PHP | Ognestraz/lumen-admin | /model/Traits/Path.php | UTF-8 | 350 | 2.6875 | 3 | [
"MIT"
] | permissive | <?php namespace Model\Traits;
trait Path {
static public function findPath($path, $act = true, $fail = false)
{
$model = self::where('path', '=', $path == '/' ? '' : $path);
if (isset($act)) {
$model->where('act', $act);
}
return $fail ? $model->firstOrFail() : $model->first();
}
}
?>
| true |
edf3cd7ffa032637fa3400425e94afba04e5446f | PHP | operaantap/ajax | /oop.php | UTF-8 | 1,218 | 4.125 | 4 | [] | no_license | <?php
//creating a Class
class cars{
//creating it's properties(variables)
public $colour="blue";
public $speed=100;
//creating it's method(functions)
function get_colour() {
return $this->colour;
}
function set_colour($colour) {
$this->colour = $colour;
}
function get_speed() {
return $this->speed;
}
function set_speed($speed) {
$this->speed = $speed;
}
//All the above Methods are used in setting up the characteristics of the class cars
}
//now we create an object from the class above
$benz = new cars();
//The benz will come bearing the original colour declared in the Class "cars"
echo "The original colour of our benz is ".$benz->get_colour()."<br/>";
//now we set a new colour
$benz->set_colour('indigo');
echo "Our Benz's new colour is ". $benz->get_colour()."<br/>";
//now we create an object from the class above
$benz = new cars();
//The benz will come bearing the original speed declared in the Class "cars"
echo "The original speed of our benz is ".$benz->get_speed()."<br/>";
//now we set a new speed
$benz->set_speed('200');
echo "Our Benz's new speed is ". $benz->get_speed();
?>
| true |
0e0eb057c2d8c40e4e2f9199d4b9fba900c59bb0 | PHP | icultivator/notebook | /protected/models/User.php | UTF-8 | 4,039 | 2.625 | 3 | [] | no_license | <?php
/**
* This is the model class for table "{{user}}".
*
* The followings are the available columns in table '{{user}}':
* @property string $id
* @property string $username
* @property string $password
* @property string $email
* @property string $avatar
* @property string $contact
* @property string $register_time
* @property string $register_ip
* @property integer $status
*/
class User extends CActiveRecord
{
const NO_VERIFY = 0;
const NORMAL = 1;
const ABNORMAL = 2;
public $repass;
/**
* @return string the associated database table name
*/
public function tableName()
{
return '{{user}}';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('username, password, email,repass', 'required','on'=>'register,create'),
array('email','email'),
array('username,email','unique'),
array('username', 'length', 'max'=>16),
array('password, email', 'length', 'max'=>32),
array('repass','compare','compareAttribute'=>'password'),
array('avatar', 'length', 'max'=>100),
array('register_time', 'length', 'max'=>10),
array('register_ip', 'length', 'max'=>15),
// The following rule is used by search().
// @todo Please remove those attributes that should not be searched.
array('id, username, password, email, avatar, contact, register_time, register_ip, status', 'safe', 'on'=>'search'),
);
}
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'ID',
'username' => 'Username',
'password' => 'Password',
'email' => 'Email',
'avatar' => 'Avatar',
'contact' => 'Contact',
'register_time' => 'Register Time',
'register_ip' => 'Register Ip',
'status' => 'Status',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
*
* Typical usecase:
* - Initialize the model fields with values from filter form.
* - Execute this method to get CActiveDataProvider instance which will filter
* models according to data in model fields.
* - Pass data provider to CGridView, CListView or any similar widget.
*
* @return CActiveDataProvider the data provider that can return the models
* based on the search/filter conditions.
*/
public function search()
{
// @todo Please modify the following code to remove attributes that should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id,true);
$criteria->compare('username',$this->username,true);
$criteria->compare('password',$this->password,true);
$criteria->compare('email',$this->email,true);
$criteria->compare('avatar',$this->avatar,true);
$criteria->compare('contact',$this->contact,true);
$criteria->compare('register_time',$this->register_time,true);
$criteria->compare('register_ip',$this->register_ip,true);
$criteria->compare('status',$this->status);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
/**
* Returns the static model of the specified AR class.
* Please note that you should have this exact method in all your CActiveRecord descendants!
* @param string $className active record class name.
* @return User the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
public function beforeSave(){
if($this->isNewRecord){
$this->register_time = time();
$this->register_ip = Utils::getRemoteIp();
$this->status = self::NO_VERIFY;
$this->password = md5($this->getSalt().$this->password);
}
return parent::beforeSave();
}
public function getSalt(){
return 'YJB_PASS_SALT_';
}
}
| true |
f65ab0067e8ff9d9dd1a18e294d1214411cc79b5 | PHP | nTrouvain/Quest | /PageAcceuilCampagne.php | UTF-8 | 1,949 | 2.515625 | 3 | [] | no_license | <?php
require('connect_to_quest.php');
?>
<!doctype html>
<html>
<?php require_once "head.php";
$idCampagne = $_GET['id'];
$requete = $BDD->prepare('select * from campagne where camp_id=?');
$requete->execute(array($idCampagne));
$campagne = $requete->fetch();
$stmt = $BDD->prepare('select * from questaire where qutaire_camp=?');
$stmt->execute(array($idCampagne));
?>
<body id="bodyaccueilcampagne">
<?php require_once "headerQuest.php"; ?>
<br/>
<br/>
<br/>
<br/>
<br/>
<div class="container">
<div class="row">
<div class="container">
<div class="row">
<div class="col-md-4">
</div>
<div class="col-md-4" id="creation">
<h1 class="text-center">Gestion de campagnes</h1>
</div>
<div class="col-md-4">
</div>
</div>
</div>
<br/>
<br/>
<br/>
<br/>
<br/>
<div class="container">
<div class="row">
<div class="col-md-4-offset-md-2 col-sm-5" id="titreaccueilcamp">
<h2><?= $campagne['camp_nom'] ?></h2>
<p>
<small><?= $campagne['camp_desc'] ?></small>
</p>
</div>
<div class="col-md-4-offset-md-2 col-sm-5" id="conteneraccueilcamp">
<h2>Questionnaires(s) de cette campagne :</h2>
<?php foreach ($stmt as $questionnaire) { ?>
<article>
<h5><a class="nom_questionnaire"><?= $questionnaire["qutaire_titre"] ?></a></h5>
</article>
<?php } ?>
<h3><a href="CreerQuestionnaire.php?id=<?= $idCampagne ?>">Ajouter un questionnaire</a></h3>
</h2>
</div>
</div>
</body>
</html> | true |
34d173b1afafbe23616975324e74d9d5fb024003 | PHP | rogerapras/laravel-repository | /src/Torann/LaravelRepository/AbstractValidator.php | UTF-8 | 2,136 | 2.875 | 3 | [
"BSD-2-Clause"
] | permissive | <?php namespace Torann\LaravelRepository;
use Illuminate\Validation\Factory;
abstract class AbstractValidator
{
/**
* The Validator instance
*
* @var \Illuminate\Validation\Factory
*/
protected $validator;
/**
* Inject the Validator instance
*
* @param \Illuminate\Validation\Factory $validator
*/
public function __construct(Factory $validator)
{
$this->validator = $validator;
}
/**
* Replace placeholders with attributes
*
* @return array
*/
public function replace($rules, $data)
{
array_walk($rules, function(&$rule) use ($data)
{
preg_match_all('/\{(.*?)\}/', $rule, $matches);
foreach($matches[0] as $key => $placeholder)
{
if(isset($data[$matches[1][$key]]))
{
$rule = str_replace($placeholder, $data[$matches[1][$key]], $rule);
}
}
});
return $rules;
}
/**
* Validates the data
*
* @param string $method
* @param array $data
*
* @return boolean
*/
public function validate($method, array $data)
{
$rules = [];
$property = lcfirst($method) . 'Rules';
// Get general rules
if (isset($this->rules) && is_array($this->rules)) {
$rules = $this->replace($this->rules, $data);
}
// Get rules for method
if (isset($this->$property) && is_array($this->$property)) {
$rules = array_merge(
$rules,
$this->replace($this->$property, $data)
);
}
$validator = $this->validator->make($data, $rules);
if ($validator->passes()) {
return true;
}
$this->errors = $validator->messages();
}
/**
* Return errors
*
* @return \Illuminate\Support\MessageBag
*/
public function getErrors()
{
return $this->errors;
}
} | true |
2ee96b28c8b7514b792f83d6494d0c5642eed7e6 | PHP | nattsdaff/DH-FS-Clases | /PHP/Clase14/ejercitacion/Banco/Entidades/Clientes/Pyme.php | UTF-8 | 833 | 2.8125 | 3 | [
"MIT"
] | permissive | <?php
class Pyme extends Cliente implements Liquidable
{
private $CUIT;
private $razonSocial;
public function __construct(Cuenta $cuenta, $email, $pass, $CUIT, $razonSocial)
{
parent::__construct($cuenta, $email, $pass);
$this->CUIT = $CUIT;
$this->razonSocial = $razonSocial;
}
public function setCUIT($CUIT)
{
$this->CUIT = $CUIT;
}
public function getCUIT()
{
return $this->CUIT;
}
public function setrazonSocial($razonSocial)
{
$this->razonSocial = $razonSocial;
}
public function getrazonSocial()
{
return $this->razonSocial;
}
public function liquidarHaberes(Persona $persona, $monto)
{
$persona->getCuenta()->acreditar($monto);
$this->cuenta->debitar($monto * 1.01, Cuenta::ORIGEN_LIQUIDACION_HABERES);
}
}
| true |
9ad43e2c904449ff081b55b4b267215bea7a85ba | PHP | rougin/windstorm | /tests/Eloquent/UpdateTest.php | UTF-8 | 546 | 2.671875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | <?php
namespace Rougin\Windstorm\Eloquent;
/**
* Update Test
*
* @package Windstorm
* @author Rougin Gutib <rougingutib@gmail.com>
*/
class UpdateTest extends TestCase
{
/**
* Tests UpdateInterface::set.
*
* @return void
*/
public function testSetMethod()
{
$expected = 'update "users" set "name" = ? where "id" = ?';
$query = $this->query->update('users')->set('name', 'Windstorm');
$result = (string) $query->where('id')->equals(1)->sql();
$this->assertEquals($expected, $result);
}
}
| true |
f1fc993ed62f2711c9aef3b0079dba0118ce159d | PHP | arbory/arbory | /src/Admin/Widgets/Breadcrumbs.php | UTF-8 | 1,613 | 2.796875 | 3 | [
"MIT"
] | permissive | <?php
namespace Arbory\Base\Admin\Widgets;
use Arbory\Base\Html\Html;
use Illuminate\Support\Collection;
use Illuminate\Contracts\Support\Renderable;
/**
* Class Breadcrumbs.
*/
class Breadcrumbs implements Renderable
{
/**
* @var Collection
*/
protected $items;
/**
* Breadcrumbs constructor.
*/
public function __construct()
{
$this->items = new Collection();
$this->addItem(trans('arbory::breadcrumbs.home'), route('admin.dashboard.index'));
}
/**
* @return string
*/
public function __toString()
{
return (string) $this->render();
}
/**
* @param $title
* @param $url
* @return Breadcrumbs
*/
public function addItem($title, $url)
{
$this->items->push([
'title' => $title,
'url' => $url,
]);
return $this;
}
/**
* @return \Arbory\Base\Html\Elements\Element
*/
public function render()
{
$total = $this->items->count();
$list = $this->items->map(function (array $item, $key) use ($total) {
$listItem = Html::li(
Html::link($item['title'])
->addAttributes([
'href' => $item['url'],
])
);
if ($key !== $total - 1) {
$listItem->append(Html::i('arrow_right')->addClass('mt-icon'));
}
return $listItem;
});
return Html::nav(
Html::ul($list->toArray())->addClass('block breadcrumbs')
);
}
}
| true |
f7d904b36b3630a94cff2ce69c9b5f0c8ff6679f | PHP | RobertGard/OOP-MVC-SHOP | /components/Router.php | UTF-8 | 2,423 | 3.171875 | 3 | [] | no_license | <?php
/*
* Получение адреса из url и подключение нужных файлов
*/
/**
* Description of Router
*
* @author wakka
*/
class Router {
public $routes;
public function __construct() {
$this->routes = include (PathPrefix.'/config/routes.php');
}
//Получение данных из URI
private function getFromUri() {
if(!empty($_SERVER['QUERY_STRING'])){
$uri = trim($_SERVER['QUERY_STRING'],'/');
}
return $uri;
}
public function run() {
$uri = $this->getFromUri();
//Прокручивание массива путей
foreach ($this->routes as $itemKey => $itemValue){
//Проверка на совпадение ключей из массива с URI данными
if(preg_match("~$itemKey~", $uri)){
$itemValue = preg_replace("~$itemKey~", $itemValue, $uri);
//Разбиваем путь-строку и закидываем в массив
$segments = explode("/",$itemValue);
//Получение названия сонтроллера
$controllerName = ucfirst(array_shift($segments)."Controller");
//Получение названия Action
$actionName = array_shift($segments)."Action";
//Подключение файла-контроллера
$controllerFile = PathPrefix."/Controllers/".$controllerName.".php";
if(file_exists($controllerFile)){
include_once $controllerFile;
}
//То что осталось - это параметры
$parameters = $segments;
//Создаём объект класса контроллера и вызываем нужный метод-action
$controllerObject = new $controllerName();
$key = $controllerObject->$actionName($parameters);
//При удачном нахождении выбросит из прокрутки массива путей
if($key !== FALSE){
break;
}
}
}
}
}
| true |
a7fb79fe29b18344bb81aabcf6446b025e801c93 | PHP | guidepilot/php-lottie | /examples/dotLottie_readMeta.php | UTF-8 | 454 | 2.8125 | 3 | [
"MIT"
] | permissive | <?php
use GuidePilot\PhpLottie\DotLottieFile;
require_once '../vendor/autoload.php';
$file = new DotLottieFile('animation.lottie');
foreach ($file->getAnimations() as $aAnimation) {
echo "Animation Id: {$aAnimation->getId()}".PHP_EOL;
echo "Size: {$aAnimation->getWidth()}x{$aAnimation->getHeight()}".PHP_EOL;
echo "FrameRate: {$aAnimation->getFrameRate()}".PHP_EOL;
echo "Duration: {$aAnimation->getDuration()} seconds".PHP_EOL;
}
| true |
7ce69e55c10b5d6043b13c132859106fda41b260 | PHP | gumonet/hytorc-encuestas | /process-request.php | UTF-8 | 1,038 | 2.609375 | 3 | [] | no_license | <?php
require_once './includes/class-gm-Database.php';
require_once './includes/class-gm-mailer.php';
$post = $_POST;
if( isset( $post['action'] ) ) {
$controller = new GMDatabase();
switch ( $post['action'] ) {
case 'save_register':
//Validar que la factura, no esté registrada
$tipo_encuesta = $_POST['tipo_encuesta'];
$register_id = $controller->save_register( $post );
if ( $register_id !== false ){
//obtener tipo de encuestas
header('Location: encuesta-' . $tipo_encuesta . '.php?survey=' . $register_id);
} else {
echo '<h1>Ocurrio un error al almacenar el registro</h1>';
}
break;
case 'update_register':
$surver_id = $_POST['id'];
$transaction = $controller->update_register( $post );
if ( $transaction !== false ) {
$receptor = $controller->getEmail( $surver_id );
if ( $receptor !== false) {
SendEmail::send( $receptor );
}
header( 'Location: gracias.php' );
} else{
echo '<h1>Ocurrio un error al almacenar el registro</h1>';
}
break;
}
} | true |
277539bfa8e7e7ab847e66329ef51619ac8ea618 | PHP | alexzer0/inkatours | /mkt/admin/addons/surveys/api/surveys.php | UTF-8 | 19,191 | 3.171875 | 3 | [] | no_license | <?php
/**
* Addons_surveys_api
* API functions for surveys
*/
class Addons_survey_api extends API
{
/**
* Holds the different question types. Values are loaded in __construct
* @var Array
*/
public $question_types;
/**
* Holds values set using __set
* @var Array
*/
private $data = array();
/**
* validSorts
* Valid columns to sort surveys by. The first column is the default
* @var Array
*/
public static $validSorts = array('name','created','updated','responsecount');
/**
* __construct
* Sets the question_types, loads the specified surveys and questions if given.
*
* @param Array $survey The survey to load
* @param Array $questions The questions to load
*
* @see _loadData
*
* @return Void Returns nothing
*/
public function __construct()
{
parent::__construct();
}
/**
* __set
* Handles setting of members
*/
public function __set($var,$val)
{
$this->data[$var] = $val;
}
/**
* __get
* Returns members
*/
public function __get($var)
{
if (array_key_exists($var,$this->data)) {
return $this->data[$var];
}
return false;
}
/**
* populateFormData
* @param $table_keys - the key structure of the table
* @param $form- the actual form
* Populating all the data variable with the form.
*/
public function populateFormData($table_keys, $form)
{
$this->_columns = $table_keys;
if (is_array($form)) {
foreach ($form as $key => $val) {
if (in_array($key, $table_keys)){
$this->$key = $val;
}
}
}
}
/**
* Load
* Loads a survey from the database
*
* @param Int $surveyid The surveyid to load
*
* @return Boolean Returns true on success, false on failure
*/
public function Load($surveyid)
{
$surveyid = (int)$surveyid;
$prefix = $this->Db->TablePrefix;
$query = "SELECT * FROM {$prefix}surveys WHERE id = $surveyid";
$result = $this->Db->Query($query);
$survey = $this->Db->Fetch($result);
return $this->_loadData($survey);
}
/**
* _loadData
* Loads a specified survey and questions
*
* @param Array $survey The survey to load. Supported fields are:
* array(
* 'name' => 'Name of survey'
* )
* @param Array $questions The questions to load. Supported fields are:
* array(
* 1 => // The id of the question
* array(
* 'new' => 'true', // Specify this if the question is to be added (ie it doesn't yet exist in the database)
* 'title' => 'Title of question',
* 'type' => 'type', // One of the types from $question_types
* 'required' => 'on', // This question is required, omit this for a non-required question
*
* // For multiple choice questions:
* 'choices' => 'one,two,three', // List of choices
* 'multiplechoices' => 'on', // More than one choice is allowed (omit if only one is allowed)
*
* // For number questions:
* 'range' => '1-100', // Range of numbers, leave blank for any range
*
* // For file questions:
* 'filetypes' => 'jpg,gif', // File types that are accepted, leave blank for any file types
*
* // For country questions:
* 'country' => 'United States', // Default selection (leave blank to select instructional text)
* )
* )
*/
private function _loadData($survey = false)
{
if (!is_array($survey)) {
return false;
} else {
foreach ($survey as $key => $val) {
if ($key == 'id') {
$this->data[$key] = (int)$val;
} else {
$this->data[$key] = $val;
}
}
}
return true;
}
/**
* Get
* @param $varname
*
* Overide the parent function to look inside the data container
*
* @return void
*/
public function Get($varname)
{
if (isset($this->data[$varname])) {
return $this->data[$varname];
}
}
public function GetData()
{
return $this->data;
}
/**
* Create
* Creates a new survey.
*
* @return Int Returns the surveyid of the new survey
*/
public function Create()
{
$prefix = $this->Db->TablePrefix;
$this->created = $this->GetServerTime();
$user = GetUser();
$userid = $user->userid;
$tablefields = implode(',', $this->_columns);
//$_columns = array('name','userid','description','created','surveys_header','surveys_header_text','email','email_feedback','after_submit','show_message','show_uri','error_message','submit_button_text');
$query = "INSERT INTO {$prefix}surveys ({$tablefields})
VALUES ('" . $this->Db->Quote($this->name) . "',"
. $userid . ",'"
. $this->Db->Quote($this->description) . "','"
. $this->Db->Quote($this->created) . "','"
. $this->Db->Quote($this->surveys_header) . "','"
. $this->Db->Quote($this->surveys_header_text) . "','"
. $this->Db->Quote($this->surveys_header_logo) . "','"
. $this->Db->Quote($this->email) . "','"
. $this->Db->Quote($this->email_feedback) . "','"
. $this->Db->Quote($this->after_submit) . "','"
. $this->Db->Quote($this->show_message) . "','"
. $this->Db->Quote($this->show_uri) . "','"
. $this->Db->Quote($this->error_message) . "','"
. $this->Db->Quote($this->submit_button_text) . "')";
if (SENDSTUDIO_DATABASE_TYPE == 'pgsql') {
$query .= ' RETURNING id;';
}
$results = $this->Db->Query($query);
if ($results === false) {
return false;
}
if (SENDSTUDIO_DATABASE_TYPE == 'pgsql') {
$surveyid = $this->Db->FetchOne($results);
} else {
$surveyid = $this->Db->LastId();
}
return $surveyid;
}
/**
* Deleting all widgets ID that is no longer used,
* this is used when updating / saving process..
*/
public function deleteWidgetsNotIn(Array $widgetsIds)
{
$prefix = $this->Db->TablePrefix;
// now delete the widgets
$sql = "DELETE FROM {$prefix}surveys_widgets
WHERE surveys_id = {$this->id} AND
id NOT IN (" . implode(',', $widgetsIds) . ");";
return $this->Db->Query($sql);
}
/**
* Getwidgets
* @
* If the current form has any widgets associated to it, then it will
* return them as an array of objects. If none are found, it returns
* false.
*
* @return Mixed
*/
public function getWidgets($formId=0)
{
// if formId is not supplied then
// get the current ID from the Load
if ($formId == 0) {
$formId = $this->id;
}
$formId = intval($formId);
$widgets = array();
$prefix = $this->Db->TablePrefix;
$sql = "SELECT * FROM {$prefix}surveys_widgets
WHERE surveys_id = $formId
ORDER BY display_order ASC;";
$results = $this->Db->Query($sql);
if ($results === false || empty($results)) {
return false;
}
while ($row = $this->Db->Fetch($results)) {
foreach ($row as &$value) {
$value = htmlspecialchars($value);
}
$widgets[] = $row;
}
return $widgets;
}
/**
* getFields
* @param $widgetId
*
* Returns the field given a specific widget ID
*/
public function getFields($widgetId)
{
$widgetId = intval($widgetId);
$fields = array();
$prefix = $this->Db->TablePrefix;
$sql = "SELECT *
FROM {$prefix}surveys_fields
WHERE
surveys_widget_id = {$widgetId}";
$results = $this->Db->Query($sql);
if ($results === false || empty($results)) {
return false;
}
while ($row = $this->Db->Fetch($results)) {
$fields[] = $row;
}
return $fields;
}
/**
* setId
* @param $formId
*
* Setting the form ID variable..
*/
public function setId($formId)
{
$this->id = (int)$formId;
}
/**
* getId
* @param void
*
* Return the ID of the survey
*/
public function getId()
{
return (int)$this->id;
}
/**
* Update function
* Update the survey table with the new values from the table POST
* Please refer to function Load and function populateDataForm
* @return unknown_type
*/
public function Update()
{
$prefix = $this->Db->TablePrefix;
$user = GetUser();
$userid = $user->userid;
$where = 'id = ' . $this->id;
$surveys_data = $this->data;
if (isset($surveys_data['_columns'])) {
unset($surveys_data['_columns']);
}
if (isset($surveys_data['id'])) {
unset($surveys_data['id']);
}
$surveys_data['updated'] = $this->GetServerTime();
$this->Db->UpdateQuery('surveys', $surveys_data, $where);
}
/**
* getSurveyContent
* Render the actual survey question for the specified form id that passed .
*
* @return string rendered template
*
* @param int $formId The id of the survey to get the content for.
* @param tpl $tpl This is the actual template system parsed from the front end
*/
public function getSurveyContent($surveyId , $tpl)
{
// give the form an action to handle the submission
// $tpl->Assign('action', 'admin/index.php?Page=Addons&Addon=surveys&Action=Submit&ajax=1&formId=' . $surveyId);
$success_message = IEM::sessionGet('survey.addon.' . $surveyId . '.successMessage');
if ($success_message) {
IEM::sessionRemove('survey.addon.' . $surveyId . '.successMessage');
$tpl->Assign('successMessage', $success_message);
return $tpl->ParseTemplate('survey_success');
}
$tpl->Assign('action', 'surveys_submit.php?ajax=1&formId=' . $surveyId);
// check for valid ID
if (!isset($surveyId)) {
return;
}
require_once('widgets.php');
$widgets_api = new Addons_survey_widgets_api();
$loadRes = $this->Load($surveyId);
if ($loadRes === false) {
echo 'invalid form id';
return;
}
$surveyData = $this->GetData();
$widgets = $this->getWidgets($this->id);
// and if there are widgets
// iterate through each one
$widgetErrors = array();
if ($widgets) {
$widgetErrors = IEM::sessionGet('survey.addon.' . $surveyId . '.widgetErrors');
foreach ($widgets as $k => &$widget) {
if ($widget['is_visible'] == 1 || $widget['type'] == 'section.break') {
// $widget->className = Interspire_String::camelCase($widget->type, true);
// Getting error from form..
$widgets_api->SetId($widget['id']);
$widget['fields'] = $widgets_api->getFields(false);
// if there are errors for this widget, set them
if ($widgetErrors && count($widgetErrors[$widget['id']]) > 0) {
$widget['errors'] = $widgetErrors[$widget['id']];
}
// randomize the fields if told to do so
if ($widget['is_random'] == 1) {
shuffle($widget['fields']);
}
// tack on an other field if one exists
if ($otherField = $widgets_api->getOtherField()) {
$otherField['value'] = '__other__';
$widget['fields'][] = $otherField;
}
// if it is a file widget, then grab the file types
if ($widget['type'] == 'file') {
$widget['fileTypes'] = preg_split('/\s*,\s*/', $widget['allowed_file_types']);
$widget['lastFileType'] = array_pop($widget['fileTypes']);
}
// assign the widget information to the view
$tpl->Assign('widget', $widget);
// render the widget template
$widget['template'] = $tpl->parseTemplate('widget.front.' . $widget['type'], true);
} else {
unset($widgets[$k]);
}
}
// clear the widget errors session variable
IEM::sessionRemove('survey.addon.' . $surveyId . '.widgetErrors');
}
// assign the form, widget and widget-field data to the template
$tpl->Assign('errorMessage', IEM::sessionGet('survey.addon.' . $surveyId . '.errorMessage'));
$tpl->Assign('successMessage', IEM::sessionGet('survey.addon.' . $surveyId . '.successMessage'));
$tpl->Assign('survey', $surveyData);
$tpl->Assign('widgets', $widgets);
// unset the message that was set, so it doesn't get displayed again
IEM::sessionRemove('survey.addon.' . $surveyId . '.errorMessage');
IEM::sessionRemove('survey.addon.' . $surveyId . '.successMessage');
//return $this->template->parseTemplate('form', true);
return $tpl->ParseTemplate('survey');
}
/**
* GetSurveys
* Retrieves a list of surveys from the database
*
* @param Int $ownerid The user to fetch surveys for
* @param Int $pageid The page to start retrieving results from. This is ignored if perpage is set to 'all'
* @param Int $perpage The number of entries per page. Specify 'all' to retrieve all results.
* @param Array $search_info Restrict results to certain values. Key names should be the column names. Example:
* array(
* 'eventtype' => 'Email', 'listid' => 4
* )
* Specify an array to select multiple values:
* array(
* 'eventtype' => array('Email','Phone Call')
* )
* Date restrictions are specified using the 'restrictions' key:
* array(
* 'restrictions' => 'eventdate >= 1216250000 AND eventdate < 1216252570'
* )
* @param Array $sort_details Column and direction to sort the results by
* @param Boolean $count_only Specify true to return the number of surveys. Specify false (default) to return a list of surveys
*
* @return Array Returns an array of results
*/
public function GetSurveys($ownerid = 0,$pageid=1,$perpage=20,$search_info = false,$sort_details = array(),$count_only = false)
{
$prefix = $this->Db->TablePrefix;
$ownerid = (int)$ownerid;
$sortby = (isset($sort_details['SortBy'])) ? $sort_details['SortBy'] : '';
$sortdirection = (isset($sort_details['Direction'])) ? strtolower($sort_details['Direction']) : '';
if (!in_array($sortby, self::$validSorts)) {
$sortby = self::$validSorts[0];
}
if (!in_array($sortdirection,array('asc','desc'))) {
$sortdirection = 'asc';
}
if ($perpage == 'all') {
$perpage = 0;
$offset = 0;
} else {
$perpage = (int)$perpage;
$offset = ($pageid - 1) * $perpage;
}
$user = GetUser($ownerid);
$query_user = "";
if (empty($user->group->systemadmin)) {
$query_user = " s.userid = $ownerid AND";
}
if ($count_only) {
$query = "SELECT COUNT(*) FROM {$prefix}surveys s WHERE s.userid = $ownerid";
} else {
$query = "SELECT s.*,u.username as username, (SELECT count(id) FROM {$prefix}surveys_response WHERE {$prefix}surveys_response.surveys_id = s.id) as responseCount
FROM {$prefix}surveys s, {$prefix}users u
WHERE {$query_user} u.userid = s.userid
ORDER BY $sortby $sortdirection";
if ($perpage) {
$query .= " LIMIT $perpage";
}
if ($offset) {
$query .= " OFFSET $offset";
}
}
$result = $this->Db->Query($query);
if ($count_only) {
$count = $this->Db->FetchOne($result);
return $count;
}
$return = array();
while ($row = $this->Db->Fetch($result)) {
$return[] = $row;
}
return $return;
}
/**
* Deletes a surveys, together with its Widgets and Fields
*
* @param Int $surveyid The surveyid to delete
*
* @return Void Returns nothing
*/
public function Delete($surveyid)
{
$surveyid = (int)$surveyid;
$prefix = $this->Db->TablePrefix;
// First Delete all Widgets Associated with the form,
$widgets = $this->getWidgets($surveyid);
foreach ($widgets as $key=>$widget) {
// for each widget delete all the fields related ..
$query = "DELETE FROM {$prefix}surveys_fields WHERE surveys_widget_id = {$widget['id']}";
$this->Db->Query($query);
}
// Delete the actual widget,
$query = "DELETE FROM {$prefix}surveys_widgets WHERE surveys_id = {$surveyid}";
$this->Db->Query($query);
// Lastly delete the actual suvey
$query = "DELETE FROM {$prefix}surveys WHERE id = $surveyid";
$this->Db->Query($query);
// Delete all the responses and response value as well..
$query = "DELETE sr, srv
FROM {$prefix}surveys_response as sr, {$prefix}surveys_response_value as srv
WHERE sr.id = srv.surveys_response_id and
sr.surveys_id = {$surveyid}";
// Delete all the files uploaded from the survey folders..
$survey_images_dir = TEMP_DIRECTORY . DIRECTORY_SEPARATOR . 'surveys' . DIRECTORY_SEPARATOR . $surveyid;
if (is_dir($survey_images_dir)) {
// Delete using our library file
$dir = new IEM_FileSystem_Directory($survey_images_dir);
$dir->delete();
}
$this->Db->Query($query);
}
/***
* _deleteDirectory
* Recursively delete the directory
*
*/
private function _deleteDirectory($dir) {
if (!file_exists($dir)) return true;
if (!is_dir($dir)) return unlink($dir);
foreach (scandir($dir) as $item) {
if ($item == '.' || $item == '..') continue;
if (!$this->_deleteDirectory($dir.DIRECTORY_SEPARATOR.$item)) return false;
}
return rmdir($dir);
}
/**
* getResponses
* Retrieves a list of responses for this form.
*
* @return Mixed
*/
public function getResponses()
{
$prefix = $this->Db->TablePrefix;
$query = "
SELECT *
FROM {$prefix}surveys_response
WHERE
surveys_id = {$this->id}
ORDER BY
datetime
;";
$result = $this->Db->Query($query);
$return = array();
while ($row = $this->Db->Fetch($result)) {
$return[] = $row;
}
// get a list of responses
return $return;
}
/**
* getResponses
* Retrieves a list of responses ID associated with the Survey.
* This is later use to create Responses number based on index
*
* @return Mixed
*/
public function getResponsesId()
{
$prefix = $this->Db->TablePrefix;
$query = "
SELECT id
FROM {$prefix}surveys_response
WHERE
surveys_id = {$this->id}
ORDER BY
id
;";
$result = $this->Db->Query($query);
$return = array();
$counter = 1;
while ($row = $this->Db->Fetch($result)) {
$return[$counter] = $row['id'];
$counter++;
}
// get a list of responses
return $return;
}
/**
* Retrieves the number of responses that are associated to this form.
*
* @return Integer
*/
public function getResponseCount()
{
$responses = $this->getResponses();
if ($responses) {
return count($responses);
} else {
return 0;
}
}
/***
* checkValidSurvey
*/
public function checkValidSurveyAccess($user)
{
$prefix = $this->Db->TablePrefix;
if (!$user->isAdmin()) {
$userId = $user->userid;
$query = "
SELECT *
FROM {$prefix}surveys
WHERE
id = {$this->id} and
userid = {$user->userid}
;";
$result = $this->Db->Query($query);
$return = array();
if (!empty($result)) {
while ($row = $this->Db->Fetch($result)) {
$return[] = $row;
}
if (empty($return)) {
return false;
}
}
}
return true;
}
/**
* getResponseByIndex
* Retrieves a response by its index.
*
* @param Mixed $index - An integer or string number of the response to retrieve by its index.
*
* @return Mixed
*/
public function getResponseByIndex($index = 0)
{
// get a list of responses
$prefix = $this->Db->TablePrefix;
$query = "
SELECT *
FROM {$prefix}surveys_response
WHERE
surveys_id = {$this->id}
ORDER BY
datetime
LIMIT {$index}, 1
;";
$result = $this->Db->Query($query);
$return = array();
while ($row = $this->Db->Fetch($result)) {
$return[] = $row;
}
// get a list of responses
return $return;
}
/**
* Retrieves a response by its index.
*
* @param Mixed $number - An integer or string number of the response to retrieve by its number.
*
* @return Mixed
*/
public function getResponseByNumber($number = 1)
{
return $this->getResponseByIndex($number - 1);
}
}
| true |
6c90811c988670a8e784391bcf1fcce35765f71b | PHP | fbsoftware/alberi-1.4.2 | /z-garbage/mail2.php | UTF-8 | 2,078 | 2.671875 | 3 | [] | no_license | <?php
// definisco mittente e destinatario della mail
$nome_mittente = "Mio Nome";
$mail_mittente = "mittente@sito.com";
$mail_destinatario = "fbsoftware@libero.it";
// definisco il subject
$mail_oggetto = "Messaggio di prova";
// definisco il messaggio formattato in HTML
$mail_corpo = <<<HTML
<html>
<head>
<title>Una semplice mail con PHP formattata in HTML</title>
</head>
<body>
<h1>Elba 2007</h1>
<p><span style="font-size: 14px;">Isola d'Elba, Marina di Campo in campeggio, una baia con vicino un paese tipico e pulito (5 minuti in bici). Con tempo bello la temperatura è ideale ai primi di Giugno, l'umidità è quasi assente e l'acqua bella e gradevole.</span></p>
<div><span style="font-size: 14px;">Al largo era parcheggiato un panfilo di un "povero Cristo" con mezzo speciale di trasporto a terra! Zoomare per credere! Sai ... la barchetta è scomoda ... bisogna remare ... metti che il mare sia mosso ... se hai dimenticato di comperare lo zucchero ... vuoi mettere la comodità di un elicottero che ti cala proprio davanti al supermercato?</span></div>
<div><span style="font-size: 14px;"><span style="font-family: arial,helvetica,sans-serif;">C\'è anche chi molto più modesto,ma dignitosamente, affronta il mare con altri mezzi!</span></span></div></body>
</html>
HTML;
// aggiusto un po' le intestazioni della mail
// E' in questa sezione che deve essere definito il mittente (From)
// ed altri eventuali valori come Cc, Bcc, ReplyTo e X-Mailer
$mail_headers = "From: " . $nome_mittente . " <" . $mail_mittente . ">\r\n";
$mail_headers .= "Reply-To: " . $mail_mittente . "\r\n";
$mail_headers .= "X-Mailer: PHP/" . phpversion() . "\r\n";
// Aggiungo alle intestazioni della mail la definizione di MIME-Version,
// Content-type e charset (necessarie per i contenuti in HTML)
$mail_headers .= "MIME-Version: 1.0\r\n";
$mail_headers .= "Content-type: text/html; charset=iso-8859-1";
if (mail($mail_destinatario, $mail_oggetto, $mail_corpo, $mail_headers))
echo "Messaggio inviato con successo a " . $mail_destinatario;
else
echo "Errore. Nessun messaggio inviato.";
?> | true |
4b726cb68a6c350b41ac392bfc031e63f56d9661 | PHP | kvinagui7/PHP-Calculator | /index.php | UTF-8 | 1,591 | 3.4375 | 3 | [] | no_license | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Calculator</title>
</head>
<body>
<form method="post">
<input type="text" name="$x" placeholder="Number 1">
<input type="text" name="$y" placeholder="Number 2">
<select name="operator">
<option>None</option>
<option>Add</option>
<option>Subtract</option>
<option>Multiply</option>
<option>Divide</option>
</select>
<br>
<button type="submit" name="submit">Calculate</button>
</form>
<p>The answer is:</p>
<?php
if (isset($_POST['submit'])) {
$result1 = $_POST['$x'];
$result2 = $_POST['$y'];
$operator = $_POST['operator'];
switch ($operator) {
case "None":
echo "You need to select an operator!";
break;
case "Add":
echo $result1 + $result2;
break;
case "Subtract":
echo $result1 - $result2;
break;
case "Multiply":
echo $result1 * $result2;
break;
case "Divide":
echo $result1 / $result2;
break;
default:
echo "Error!";
break;
}
}
?>
<style>
body {
background-color: red;
}
button{
color: blue;
}
form {
text-align: center;
font-family:sans-serif;
}
p{
text-align: center;
text-decoration: underline;
text-emphasis-color: Green;
}
</style>
</body>
</html>
| true |
67b76c07454305e310c5ae5b15099559da8afc20 | PHP | delinktech/ssm | /routes/api.php | UTF-8 | 5,122 | 2.515625 | 3 | [
"ISC"
] | permissive | <?php
use Illuminate\Http\Request;
use Carbon\Carbon;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::middleware('auth:api')->get('/user/login', function (Request $request) {
return $request->user();
});
/* user auth routes */
Route::post('/user', ['uses' => 'UserController@signup']); // user signup
Route::post('/user/login', ['uses' => 'UserController@signin']); // user login
Route::get('/user/list', ['uses' => 'UserController@index']); // user login
Route::get('/user/info', ['uses' => 'UserController@userInfo']); // get authenticated user info
Route::post('/user/logout', function() { return JWTAuth::parseToken()->invalidate(); }); // user logout
/* Students routes */
Route::get('students', ['uses' => 'StudentController@index', 'middleware' => 'auth.jwt']); // get all the students
Route::get('student/{id}', ['uses' => 'StudentController@show', 'middleware' => 'auth.jwt']); // get a single student
Route::post('student', ['uses' => 'StudentController@store', 'middleware' => 'auth.jwt']); // add a single student
Route::put('student', ['uses' => 'StudentController@store', 'middleware' => 'auth.jwt']); // update a single student
Route::delete('student/{id}', ['uses' => 'StudentController@destroy', 'middleware' => 'auth.jwt']); // delete a single student
/* Teachers routes */
Route::get('teachers', ['uses' => 'TeacherController@index', 'middleware' => 'auth.jwt']); // get all teachers
Route::get('teacher/{id}', ['uses' => 'TeacherController@show', 'middleware' => 'auth.jwt']); // get a single teacher
Route::post('teacher', ['uses' => 'TeacherController@store', 'middleware' => 'auth.jwt']); // add a teacher
Route::put('teacher', ['uses' => 'TeacherController@store', 'middleware' => 'auth.jwt']); // update a teacher
Route::delete('teacher/{id}', ['uses' => 'TeacherController@destroy', 'middleware' => 'auth.jwt']); // delete a teacher
/* Parents routes */
Route::get('parents', ['uses' => 'ParentController@index', 'middleware' => 'auth.jwt']); // get all the parents
Route::get('parent/{id}', ['uses' => 'ParentController@show', 'middleware' => 'auth.jwt']); // get a single parent
Route::post('parent', ['uses' => 'ParentController@store', 'middleware' => 'auth.jwt']); // add a single parent
Route::put('parent', ['uses' => 'ParentController@store', 'middleware' => 'auth.jwt']); // update a single parent
Route::delete('parent/{id}', ['uses' => 'ParentController@destroy', 'middleware' => 'auth.jwt']); // delete a single parent
/* Result routes */
Route::get('results', ['uses' => 'ResultsController@index', 'middleware' => 'auth.jwt']); // get all the results
Route::get('results/{id}', ['uses' => 'ResultsController@show', 'middleware' => 'auth.jwt']); // get a single result
Route::post('results', ['uses' => 'ResultsController@store', 'middleware' => 'auth.jwt']); // add a single result
Route::put('result', ['uses' => 'ResultsController@store', 'middleware' => 'auth.jwt']); // update a single result
Route::delete('result/{id}', ['uses' => 'ResultsController@destroy', 'middleware' => 'auth.jwt']); // delete result
/* School routes */
Route::get('schools', ['uses' => 'SchoolController@index', 'middleware' => 'auth.jwt']); // get all the schools
Route::get('school/{id}', ['uses' => 'SchoolController@show', 'middleware' => 'auth.jwt']); // get a single school
Route::post('school', ['uses' => 'SchoolController@store', 'middleware' => 'auth.jwt']); // add a single school
Route::put('school', ['uses' => 'SchoolController@store', 'middleware' => 'auth.jwt']); // update a single school
Route::delete('school/{id}', ['uses' => 'SchoolController@destroy', 'middleware' => 'auth.jwt']); // delete school
/* Classes routes */
Route::get('classes', ['uses' => 'ClassController@index', 'middleware' => 'auth.jwt']); // get all the schools
Route::get('class/{id}', ['uses' => 'ClassController@show', 'middleware' => 'auth.jwt']); // get a single school
Route::post('class', ['uses' => 'ClassController@store', 'middleware' => 'auth.jwt']); // add a single school
Route::put('class', ['uses' => 'ClassController@store', 'middleware' => 'auth.jwt']); // update a single school
Route::delete('class/{id}', ['uses' => 'ClassController@destroy', 'middleware' => 'auth.jwt']); // delete school
/** Send emails routes */
Route::post('resultsnotification', ['uses' => 'NotificationController@notifyByEmail', 'middleware' => 'auth.jwt']);
Route::get('sendhtmlemail','MailController@html_email');
Route::get('sendattachmentemail','MailController@attachment_email');
// Route::get('sparkpost','MailController@sendMail'); // send mail
//Email Qeue test route
Route::get('SendResultsEmail', function(){
$job = (new SendResultsEmail($message))
->delay(Carbon::now()->addSeconds(5));
dispatch($job);
return 'Results sent successfully';
});
| true |
329fad13b5f5d08e955fdaac50347ae2953b151b | PHP | ram-izaap/GPS | /application/helpers/common_helper.php | UTF-8 | 1,823 | 2.78125 | 3 | [] | no_license | <?php
function is_logged_in()
{
$CI = get_instance();
$user_data = get_user_data();
if( is_array($user_data) && $user_data )
return TRUE;
return FALSE;
}
function get_user_data()
{
$CI = get_instance();
if($CI->session->userdata('user_data'))
{
return $CI->session->userdata('user_data');
}
else
{
return FALSE;
}
}
function get_user_role( $user_id = 0 )
{
$CI= & get_instance();
if(!$user_id)
{
$user_data = get_user_data();
return $user_data['role'];
}
$CI->load->model('user_model');
$row = $CI->user_model->get_where(array('id' => $user_id))->row_array;
if( !$row )
return FALSE;
return $row['role'];
}
function str_to_lower($str) {
$ret_str ="";
$ret_str = strtolower($str);
return $ret_str;
}
function convert_latlon($address)
{
$address = str_replace(",","",$address);
$address = str_replace(" ","+",$address);
$geolocation = array();
$url = "http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);
$response_a = json_decode($response);
$geolocation[0] = $response_a->results[0]->geometry->location->lat;
$geolocation[1] = $response_a->results[0]->geometry->location->lng;
return $geolocation;
}
function customPrint( $data = array(), $die = TRUE )
{
echo '<pre>';
print_r($data);
if( $die ) die;
}
| true |
bea193ea59ff6a2ceceebfae10ddc68f1b6d6327 | PHP | xavierauana/cms | /src/Plugin/Plugin.php | UTF-8 | 2,764 | 2.671875 | 3 | [] | no_license | <?php
/**
* Author: Xavier Au
* Date: 2019-07-12
* Time: 20:19
*/
namespace Anacreation\Cms\Plugin;
use Illuminate\Console\Application as Artisan;
class Plugin
{
/**
* @var string
*/
private $pluginName;
/**
* @var string
*/
private $entryPath;
/**
* @var string
*/
private $entryPathName;
/**
* @var callable|null
*/
private $scheduleFunctions = null;
/**
* @var callable|null
*/
private $routes = null;
/**
* @var array
*/
private $commands = [];
/**
* @return callable
*/
public function getScheduleFunction(): ?callable {
return $this->scheduleFunctions;
}
/**
* @param callable $scheduleFunction
* @return \Anacreation\Cms\Plugin\Plugin
*/
public function setScheduleFunction(callable $scheduleFunction): Plugin {
$this->scheduleFunctions = $scheduleFunction;
if (config('cms.enable_scheduler', false)) {
app()->booted(function () {
($this->scheduleFunctions)();
});
}
return $this;
}
/**
* Plugin constructor.
* @param string $pluginName
*/
public function __construct(string $pluginName) {
}
/**
* @return string
*/
public function getPluginName(): string {
return $this->pluginName;
}
/**
* @param string $entryPath
* @param string $pathName
* @return Plugin
*/
public function setEntryPath(string $entryPath, string $pathName): Plugin {
$this->entryPath = $entryPath;
$this->entryPathName = $pathName;
return $this;
}
/**
* @return string
*/
public function getEntryPath(): string {
return $this->entryPath;
}
/**
* @return string
*/
public function getEntryPathName(): string {
return $this->entryPathName;
}
/**
* @param callable $routes
* @return \Anacreation\Cms\Plugin\Plugin
*/
public function setRoutes(callable $routes): Plugin {
$this->routes = $routes;
return $this;
}
/**
* @return callable|null
*/
public function getRoutes(): ?callable {
return $this->routes;
}
/**
* @return array
*/
public function getCommands(): array {
return $this->commands;
}
/**
* @param array $commands
*/
public function setCommands(array $commands): Plugin {
$this->commands = $commands;
if (app()->runningInConsole()) {
Artisan::starting(function ($artisan) {
$artisan->resolveCommands($this->commands);
});
}
return $this;
}
} | true |
3cc3ac3dd5e224f1408eaf67bff3481f41366e09 | PHP | DustinHartzler/PharmToTable | /wp-content/plugins/thrive-leads/thrive-dashboard/inc/automator/actions/class-facebook-event-custom-action.php | UTF-8 | 2,085 | 2.515625 | 3 | [] | no_license | <?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
namespace TVE\Dashboard\Automator;
use Thrive\Automator\Items\Action;
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
class Facebook_Event_Custom extends Action {
protected $event_name;
protected $custom_fields;
public static function get_id() {
return 'fb/custom_event';
}
public static function get_app_id() {
return Facebook_App::get_id();
}
public static function get_name() {
return __( 'Fire Facebook custom event', 'thrive-dash' );
}
public static function get_description() {
return __( 'Send a custom event to Facebook', 'thrive-dash' );
}
public static function get_image() {
return 'tap-facebook-logo';
}
public static function get_required_action_fields() {
return [
Facebook_Event_Name_Field::get_id(),
Facebook_Custom_Options_Field::get_id(),
];
}
public function prepare_data( $data = array() ) {
$this->event_name = $data[ Facebook_Event_Name_Field::get_id() ]['value'];
$this->custom_fields = Main::extract_mapping( $data[ Facebook_Custom_Options_Field::get_id() ]['value'] );
}
public static function get_required_data_objects() {
return [];
}
public function do_action( $data ) {
/**
* @var \Thrive_Dash_Api_FacebookPixel $api_instance
*/
$api_instance = Facebook::get_api();
if ( $api_instance ) {
$event_fields = [
'event_name' => $this->event_name,
];
$user_data = $api_instance->prepare_user_data();
$event_fields['user_data'] = $user_data;
$custom_properties = [];
if ( ! empty( $this->custom_fields ) ) {
$custom_properties['custom_properties'] = $this->custom_fields;
}
$event_fields['custom_data'] = $api_instance->prepare_custom_data( $custom_properties );
$event = $api_instance->prepare_event_data( $event_fields );
$response = $api_instance->send_events( $event );
if ( $response['success'] !== true ) {
Facebook::log_error_request( $this->get_automation_id(), $response );
}
}
}
}
| true |
29384afeca80cffd76be703f10f1e1c603de221f | PHP | masterx2/Commander | /src/Commander/Base.php | UTF-8 | 1,360 | 3.046875 | 3 | [] | no_license | <?php
namespace Commander;
use Exception;
use Requests;
class Base {
public $options;
public function __construct($options=[]) {
$this->options = $options;
}
public function getParam($name) {
return isset($this->options[$name]) ? $this->options[$name] : null;
}
/**
* Выполнить запрос
* @param $url
* @param string $type
* @param array $data
* @return array
* @throws Exception
*/
public function request($url, $type=Requests::GET, $data=[]) {
echo "API Request to $url...".PHP_EOL;
echo "Data: ".var_export($data, true).PHP_EOL;
$headers = [];
$options = [];
$request = Requests::request($url, $headers, $data, $type, $options);
$code = $request->status_code;
$contentType = $request->headers['content-type'];
$body = $request->body;
if ($code !== 200) throw new Exception("Request Failed", $code);
if (strpos($contentType, 'json') !== false) {
$response = json_decode($body, true);
} else {
$response = $body;
}
return [
"response" => $response,
"content-type" => $contentType,
"code" => $code,
"raw_body" => $body
];
}
} | true |
2317de6c74df0bab16e06109dc19fb3c3668cd25 | PHP | mestryaditya13/roadside_vehicle_assistance | /includes/registration.php | UTF-8 | 3,271 | 2.53125 | 3 | [] | no_license | <html>
<head>
<title>Registration page</title>
<link type="text/css" rel="stylesheet" href="reg.css" />
<style>
/* Full-width inputs */
input[type=email],input[type=text],input[type=tel], input[type=password] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
box-sizing: border-box;
}
/* Add a hover effect for buttons */
button:hover {
opacity: 0.8;
}
footer{
text-align:center;
font-family:cursive;
font-size:10px;
}
button {
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 30%;
align:center;
}
</style>
</head>
<body>
<?php
include "header.php";
$servername = "localhost";
$username = "root";
$db="user";
// Create connection
$conn = new mysqli("$servername", "$username", "", "$db");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['submit']))
{
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$city=$_POST['city'];
$phno=$_POST['phno'];
$email=$_POST['email'];
$pass=$_POST['psw'];
$error1="";
$error2="";
$reppass=$_POST['psw-repeat'];
if($pass==$reppass)
{
//include "conn.php";
$sql = "INSERT INTO register VALUES ('$fname', '$lname','$city','$phno','$email','$pass')";
$cmd1=mysqli_query($conn,$sql);
if ($cmd1) {
echo '<script>alert("Registration successfull")</script>';
header("location:/project/includes/user.php");
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
}
else
{
echo "Password should be same";
}
}
?>
<form action="#" method="post">
<div class="container">
<center>
<h1>Register</h1>
<p>Please fill in this form to create an account.</p>
<hr>
<table>
<tr>
<td><label for="fname"> <b>First Name</b></label></td>
<td><input type="text" placeholder="Enter First Name" name="fname" required></td>
</tr>
<tr>
<td><label for="lname"> <b>Last Name</b></label></td>
<td> <input type="text" placeholder="Enter Last Name name" name="lname" required></td>
</tr>
<tr>
<td><label for="city"> <b>City</b></label></td>
<td> <input type="text" placeholder="Enter City" name="city" required></td>
</tr>
<tr>
<td><label for="phno"> <b>Phone Number</b></label></td>
<td><input type="tel" placeholder="Enter Mobile Number" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" name="phno" required></td>
</tr>
<tr>
<td><label for="email"> <b>Email</b></label></td>
<td><input type="email" placeholder="Enter Email" name="email" required></td>
</tr>
<tr>
<td><label for="psw"><b>Password</b></label></td>
<td colspan=2> <input type="password" placeholder="Enter Password" name="psw" required></td>
</tr>
<tr>
<td><label for="psw-repeat"><b>Repeat Password</b></label></td>
<td colspan=2><input type="password" placeholder="Repeat Password" name="psw-repeat" required></td>
</tr>
<tr><td> <p>By creating an account you agree to our <a href="#">Terms & Privacy</a>.</p>
<br>
</table>
<button type="submit" name="submit">Register</button>
</div>
<hr>
</form>
</body><br><br>
<footer style=color:black;>
Developed by aadtiya<br>
@copywight by aditya</footer>
</html> | true |
5e6827e0895d7bb8be82dd68d451a74b52033bbb | PHP | szeber/yapep_base | /src/Exception/RedirectException.php | UTF-8 | 719 | 2.828125 | 3 | [] | no_license | <?php
declare(strict_types=1);
namespace YapepBase\Exception;
/**
* RedirectException class.
*
* Not descendant of YapepBase\Exception\Exception, and it should only be catched by the Application
* or a controller if necessary.
*/
class RedirectException extends \Exception
{
const TYPE_INTERNAL = 1;
const TYPE_EXTERNAL = 2;
/** @var string */
protected $target;
public function __construct(string $target, int $type, ?\Exception $previous = null)
{
$message = 'Redirecting to: ' . $target;
$this->target = $target;
parent::__construct($message, $type, $previous);
}
public function getTarget(): string
{
return $this->target;
}
}
| true |
01cd9eb9e4d610335473c1ddd850130435dbcc68 | PHP | freadblangks/Website | /src/10/WarCry CMS by jump-cms/engine/core_modules/forums.parser.php | UTF-8 | 49,243 | 2.65625 | 3 | [] | no_license | <?php
if (!defined('init_engine'))
{
header('HTTP/1.0 404 not found');
exit;
}
/**
* SSBBCodeParser
*
* BBCode parser classes.
*
* @copyright (C) 2011 Sam Clarke (samclarke.com)
* @license http://www.gnu.org/licenses/lgpl.html LGPL version 3 or higher
*
* @TODO: Have options for limiting nesting of tags
* @TODO: Have whitespace trimming options for tags
*/
/* This library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation, either
* version 3 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
class SBBCodeParser_Exception extends Exception
{
}
class SBBCodeParser_MissingEndTagException extends SBBCodeParser_Exception
{
}
class SBBCodeParser_InvalidNestingException extends SBBCodeParser_Exception
{
}
abstract class SBBCodeParser_Node
{
/**
* Nodes parent
* @var SBBCodeParser_ContainerNode
*/
protected $parent;
/**
* Nodes root parent
* @var SBBCodeParser_ContainerNode
*/
protected $root;
/**
* Sets the nodes parent
* @param SBBCodeParser_Node $parent
*/
public function set_parent(SBBCodeParser_ContainerNode $parent=null)
{
$this->parent = $parent;
if($parent instanceof SBBCodeParser_Document)
$this->root = $parent;
else
$this->root = $parent->root();
}
/**
* Gets the nodes parent. Returns null if there
* is no parent
* @return SBBCodeParser_Node
*/
public function parent()
{
return $this->parent;
}
/**
* @return string
*/
public function get_html()
{
return null;
}
/**
* Gets the nodes root node
* @return SBBCodeParser_Node
*/
public function root()
{
return $this->root;
}
/**
* Finds a parent node of the passed type.
* Returns null if none found.
* @param string $tag
* @return SBBCodeParser_TagNode
*/
public function find_parent_by_tag($tag)
{
$node = $this->parent();
while($this->parent() != null
&& !$node instanceof SBBCodeParser_Document)
{
if($node->tag() === $tag)
return $node;
$node = $node->parent();
}
return null;
}
}
abstract class SBBCodeParser_ContainerNode extends SBBCodeParser_Node
{
/**
* Array of child nodes
* @var array
*/
protected $children = array();
/**
* Adds a SBBCodeParser_Node as a child
* of this node.
* @param $child The child node to add
* @return void
*/
public function add_child(SBBCodeParser_Node $child)
{
$this->children[] = $child;
$child->set_parent($this);
}
/**
* Replaces a child node
* @param SBBCodeParser_Node $what
* @param mixed $with SBBCodeParser_Node or an array of SBBCodeParser_Node
* @return bool
*/
public function replace_child(SBBCodeParser_Node $what, $with)
{
$replace_key = array_search($what, $this->children);
if($replace_key === false)
return false;
if(is_array($with))
foreach($with as $child)
$child->set_parent($this);
array_splice($this->children, $replace_key, 1, $with);
return true;
}
/**
* Removes a child fromthe node
* @param SBBCodeParser_Node $child
* @return bool
*/
public function remove_child(SBBCodeParser_Node $child)
{
$key = array_search($what, $this->children);
if($key === false)
return false;
$this->children[$key]->set_parent();
unset($this->children[$key]);
return true;
}
/**
* Gets the nodes children
* @return array
*/
public function children()
{
return $this->children;
}
/**
* Gets the last child of type SBBCodeParser_TagNode.
* @return SBBCodeParser_TagNode
*/
public function last_tag_node()
{
$children_len = count($this->children);
for($i=$children_len-1; $i >= 0; $i--)
if($this->children[$i] instanceof SBBCodeParser_TagNode)
return $this->children[$i];
return null;
}
/**
* Gets a HTML representation of this node
* @return string
*/
public function get_html($nl2br=false)
{
$html = '';
foreach($this->children as $child)
$html .= $child->get_html($nl2br);
if($this instanceof SBBCodeParser_Document)
return $html;
$bbcode = $this->root()->get_bbcode($this->tag);
if(is_callable($bbcode->handler()) && ($func = $bbcode->handler()) !== false)
return $func($html, $this->attribs, $this);
//return call_user_func($bbcode->handler(), $html, $this->attribs, $this);
return str_replace('%content%', $html, $bbcode->handler());
}
/**
* Gets the raw text content of this node
* and it's children.
*
* The returned text is UNSAFE and should not
* be used without filtering!
* @return string
*/
public function get_text()
{
$text = '';
foreach($this->children as $child)
$text .= $child->get_text();
return $text;
}
}
class SBBCodeParser_TextNode extends SBBCodeParser_Node
{
protected $text;
public function __construct($text)
{
$this->text = $text;
}
public function get_html($nl2br=false)
{
if(!$nl2br)
return str_replace(" ", " ", htmlentities($this->text, ENT_QUOTES | ENT_IGNORE, "UTF-8"));
return str_replace(" ", " ", nl2br(htmlentities($this->text, ENT_QUOTES | ENT_IGNORE, "UTF-8")));
}
public function get_text()
{
return $this->text;
}
}
class SBBCodeParser_TagNode extends SBBCodeParser_ContainerNode
{
/**
* Tag name of this node
* @var string
*/
protected $tag;
/**
* Assoc array of attributes
* @var array
*/
protected $attribs;
public function __construct($tag, $attribs)
{
$this->tag = $tag;
$this->attribs = $attribs;
}
/**
* Gets the tag of this node
* @return string
*/
public function tag()
{
return $this->tag;
}
/**
* Gets the tags attributes
* @return array
*/
public function attributes()
{
return $this->attribs;
}
}
class SBBCodeParser_BBCode
{
/**
* The tag this BBCode applies to
* @var string
*/
protected $tag;
/**
* The BBCodes handler
* @var mixed string or function
*/
protected $handler;
/**
* If the tag is a self closing tag
* @var bool
*/
protected $is_self_closing;
/**
* Array of tags which will cause this tag to close
* if they are encountered before the end of it.
* Used for [*] which may not have a closing tag so
* other [*] or [/list] tags will cause it to be closed·
* @var array
*/
protected $closing_tags;
/**
* Valid child nodes for this tag. Tags like list, table,
* ect. will only accept li, tr, ect. tags and not text nodes
* @var array
*/
protected $accepted_children;
/**
* Which auto detections this BBCode should be excluded from
* @var int
*/
protected $is_inline;
const AUTO_DETECT_EXCLUDE_NONE = 0;
const AUTO_DETECT_EXCLUDE_URL = 2;
const AUTO_DETECT_EXCLUDE_EMAIL = 4;
const AUTO_DETECT_EXCLUDE_EMOTICON = 8;
const AUTO_DETECT_EXCLUDE_ALL = 15;
const BLOCK_TAG = false;
const INLINE_TAG = true;
/**
* Creates a new BBCode
* @param string $tag Tag this BBCode is for
* @param mixed $handler String or function, should return a string
* @param bool $is_inline If this tag is an inline tag or a block tag
* @param array $is_self_closing If this tag is self closing, I.E. doesn't need [/tag]
* @param array $closing_tags Tags which will close this tag
* @param int $accepted_children Tags allowed as children of this BBCode. Can also include text_node
* @param int $auto_detect_exclude Which auto detections to exclude this BBCode from
*/
public function __construct($tag,
$handler,
$is_inline=SBBCodeParser_BBCode::INLINE_TAG,
$is_self_closing=false,
$closing_tags=array(),
$accepted_children=array(),
$auto_detect_exclude=SBBCodeParser_BBCode::AUTO_DETECT_EXCLUDE_NONE)
{
$this->tag = $tag;
$this->is_inline = $is_inline;
$this->handler = $handler;
$this->is_self_closing = $is_self_closing;
$this->closing_tags = $closing_tags;
$this->accepted_children = $accepted_children;
$this->auto_detect_exclude = $auto_detect_exclude;
}
/**
* Gets the tag name this BBCode is for
* @return string
*/
public function tag()
{
return $this->tag;
}
/**
* Gets if this BBCode is inline or if it's block
* @return bool
*/
public function is_inline()
{
return $this->is_inline;
}
/**
* Gets if this BBCode is self closing
* @return bool
*/
public function is_self_closing()
{
return $this->is_self_closing;
}
/**
* Gets the format string/handler for this BBCode
* @return mixed String or function
*/
public function handler()
{
return $this->handler;
}
/**
* Gets an array of tags which will cause this tag to be closed
* @return array
*/
public function closing_tags()
{
return $this->closing_tags;
}
/**
* Gets an array of tags which are allowed as children of this tag
* @return array
*/
public function accepted_children()
{
return $this->accepted_children;
}
/**
* Which auto detections this BBCode should be excluded from
* @return int
*/
public function auto_detect_exclude()
{
return $this->auto_detect_exclude;
}
}
class SBBCodeParser_Document extends SBBCodeParser_ContainerNode
{
/**
* Current Tag
* @var SBBCodeParser_ContainerNode
*/
protected $current_tag = null;
/**
* Assoc array of all the BBCodes for this document
* @var array
*/
protected $bbcodes = array();
/**
* Base URI to be used for links, images, ect.
* @var string
*/
protected $base_uri = null;
/**
* Assoc array of emoticons in smiley_code => smiley_url format
* @var array
*/
protected $emoticons = array();
/*
* If to throw errors when encountering bad BBCode or
* to silently try and fix
* @var bool
*/
protected $throw_errors = false;
public function __construct($load_defaults=true, $throw_errors=false)
{
$this->throw_errors = $throw_errors;
// Load default BBCodes
if ($load_defaults)
{
$this->add_bbcodes($this->default_bbcodes());
$this->add_emoticons($this->default_emoticons());
}
}
/**
* Gets an array of the default Emoticons
* @return array
*/
public static function default_emoticons()
{
global $config;
return array(
":)" => $config['BaseURL'] . "/template/style/images/emoticons/smile.png",
":angel:" => $config['BaseURL'] . "/template/style/images/emoticons/angel.png",
":angry:" => $config['BaseURL'] . "/template/style/images/emoticons/angry.png",
"8-)" => $config['BaseURL'] . "/template/style/images/emoticons/cool.png",
":'(" => $config['BaseURL'] . "/template/style/images/emoticons/cwy.png",
":ermm:" => $config['BaseURL'] . "/template/style/images/emoticons/ermm.png",
":D" => $config['BaseURL'] . "/template/style/images/emoticons/grin.png",
"<3" => $config['BaseURL'] . "/template/style/images/emoticons/heart.png",
":(" => $config['BaseURL'] . "/template/style/images/emoticons/sad.png",
":O" => $config['BaseURL'] . "/template/style/images/emoticons/shocked.png",
":P" => $config['BaseURL'] . "/template/style/images/emoticons/tongue.png",
";)" => $config['BaseURL'] . "/template/style/images/emoticons/wink.png",
":alien:" => $config['BaseURL'] . "/template/style/images/emoticons/alien.png",
":blink:" => $config['BaseURL'] . "/template/style/images/emoticons/blink.png",
":blush:" => $config['BaseURL'] . "/template/style/images/emoticons/blush.png",
":cheerful:" => $config['BaseURL'] . "/template/style/images/emoticons/cheerful.png",
":devil:" => $config['BaseURL'] . "/template/style/images/emoticons/devil.png",
":dizzy:" => $config['BaseURL'] . "/template/style/images/emoticons/dizzy.png",
":getlost:" => $config['BaseURL'] . "/template/style/images/emoticons/getlost.png",
":happy:" => $config['BaseURL'] . "/template/style/images/emoticons/happy.png",
":kissing:" => $config['BaseURL'] . "/template/style/images/emoticons/kissing.png",
":ninja:" => $config['BaseURL'] . "/template/style/images/emoticons/ninja.png",
":pinch:" => $config['BaseURL'] . "/template/style/images/emoticons/pinch.png",
":pouty:" => $config['BaseURL'] . "/template/style/images/emoticons/pouty.png",
":sick:" => $config['BaseURL'] . "/template/style/images/emoticons/sick.png",
":sideways:" => $config['BaseURL'] . "/template/style/images/emoticons/sideways.png",
":silly:" => $config['BaseURL'] . "/template/style/images/emoticons/silly.png",
":sleeping:" => $config['BaseURL'] . "/template/style/images/emoticons/sleeping.png",
":unsure:" => $config['BaseURL'] . "/template/style/images/emoticons/unsure.png",
":woot:" => $config['BaseURL'] . "/template/style/images/emoticons/w00t.png",
":wassat:" => $config['BaseURL'] . "/template/style/images/emoticons/wassat.png",
":whistling:" => $config['BaseURL'] . "/template/style/images/emoticons/whistling.png",
":love:" => $config['BaseURL'] . "/template/style/images/emoticons/wub.png"
);
}
/**
* Gets an array of the default BBCodes
* @return array
*/
public static function default_bbcodes()
{
return array(
new SBBCodeParser_BBCode('b', '<strong>%content%</strong>'),
new SBBCodeParser_BBCode('i', '<em>%content%</em>'),
new SBBCodeParser_BBCode('strong', '<strong>%content%</strong>'),
new SBBCodeParser_BBCode('em', '<em>%content%</em>'),
new SBBCodeParser_BBCode('u', '<span style="text-decoration: underline">%content%</span>'),
new SBBCodeParser_BBCode('s', '<span style="text-decoration: line-through">%content%</span>'),
new SBBCodeParser_BBCode('blink', '<span style="text-decoration: blink">%content%</span>'),
new SBBCodeParser_BBCode('sub', '<sub>%content%</sub>'),
new SBBCodeParser_BBCode('sup', '<sup>%content%</sup>'),
new SBBCodeParser_BBCode('ins', '<ins>%content%</ins>'),
new SBBCodeParser_BBCode('del', '<del>%content%</del>'),
new SBBCodeParser_BBCode('right', '<div style="text-align: right">%content%</div>', SBBCodeParser_BBCode::BLOCK_TAG),
new SBBCodeParser_BBCode('left', '<div style="text-align: left">%content%</div>', SBBCodeParser_BBCode::BLOCK_TAG),
new SBBCodeParser_BBCode('center', '<div style="text-align: center">%content%</div>', SBBCodeParser_BBCode::BLOCK_TAG),
new SBBCodeParser_BBCode('justify', '<div style="text-align: justify">%content%</div>', SBBCodeParser_BBCode::BLOCK_TAG),
// notes only show in editing so ignore it
new SBBCodeParser_BBCode('note', ''),
new SBBCodeParser_BBCode('hidden', ''),
new SBBCodeParser_BBCode('abbr', function($content, $attribs)
{
return '<abbr title="' . $attribs['default'] . '">' . $content . '</abbr>';
}),
new SBBCodeParser_BBCode('acronym', function($content, $attribs)
{
return '<acronym title="' . $attribs['default'] . '">' . $content . '</acronym>';
}),
new SBBCodeParser_BBCode('icq', '<a href="http://www.icq.com/people/about_me.php?uin=%content%">
<img src="http://status.icq.com/online.gif?icq=%content%&img=5"> %content%</a>',
SBBCodeParser_BBCode::INLINE_TAG, false, array(), array('text_node'), SBBCodeParser_BBCode::AUTO_DETECT_EXCLUDE_ALL),
new SBBCodeParser_BBCode('skype', '<a href="skype:jovisa737590?call">
<img src="http://mystatus.skype.com/bigclassic/%content%" style="border: none;" width="182"
height="44" alt="My status" /></a>',
SBBCodeParser_BBCode::INLINE_TAG, false, array(), array('text_node'), SBBCodeParser_BBCode::AUTO_DETECT_EXCLUDE_ALL),
new SBBCodeParser_BBCode('bing', '<a href="http://www.bing.com/search?q=%content%">%content%</a>',
SBBCodeParser_BBCode::INLINE_TAG, false, array(), array('text_node'), SBBCodeParser_BBCode::AUTO_DETECT_EXCLUDE_ALL),
new SBBCodeParser_BBCode('google', '<a href="http://www.google.com/search?q=%content%">%content%</a>',
SBBCodeParser_BBCode::INLINE_TAG, false, array(), array('text_node'), SBBCodeParser_BBCode::AUTO_DETECT_EXCLUDE_ALL),
new SBBCodeParser_BBCode('wikipedia', '<a href="http://www.wikipedia.org/wiki/%content%">%content%</a>',
SBBCodeParser_BBCode::INLINE_TAG, false, array(), array('text_node'), SBBCodeParser_BBCode::AUTO_DETECT_EXCLUDE_ALL),
new SBBCodeParser_BBCode('youtube', function($content, $attribs)
{
if(substr($content, 0, 23) === 'http://www.youtube.com/')
$uri = $content;
else
$uri = 'http://www.youtube.com/v/' . $content;
return '<iframe width="480" height="390" src="' . $uri . '" frameborder="0"></iframe>';
}, SBBCodeParser_BBCode::BLOCK_TAG, false, array(), array('text_node'), SBBCodeParser_BBCode::AUTO_DETECT_EXCLUDE_ALL),
new SBBCodeParser_BBCode('vimeo', function($content, $attribs)
{
if(substr($content, 0, 24) === 'http://player.vimeo.com/')
$uri = $content;
else if(substr($content, 0, 17) === 'http://vimeo.com/'
|| substr($content, 0, 21) === 'http://www.vimeo.com/'
&& preg_match("/http:\/\/(?:www\.)?vimeo\.com\/([0-9]{4,10})/", $content, $matches))
{
preg_match("/http:\/\/(?:www\.)?vimeo\.com\/([0-9]{4,10})/", $content, $matches);
$uri = 'http://player.vimeo.com/video/' . $matches[1] . '?title=0&byline=0&portrait=0';
}
else
$uri = 'http://player.vimeo.com/video/' . $content . '?title=0&byline=0&portrait=0';
return '<iframe src="' . $uri . '" width="400" height="225" frameborder="0"></iframe>';
}, SBBCodeParser_BBCode::BLOCK_TAG, false, array(), array('text_node'), SBBCodeParser_BBCode::AUTO_DETECT_EXCLUDE_ALL),
new SBBCodeParser_BBCode('flash', function($content, $attribs)
{
$width = 640;
$height = 385;
if(substr($content, 0, 4) !== 'http')
$content = $node->root()->get_base_uri() . $content;
if(isset($attribs['width']) && is_numeric($attribs['width']))
$width = $attribs['width'];
if(isset($attribs['height']) && is_numeric($attribs['height']))
$height = $attribs['height'];
// for [flash=200,100] format
if(!empty($attribs['default']))
{
list($w, $h) = explode(',', $attribs['default']);
if($w > 20 && is_numeric($w))
$width = $w;
if($h > 20 && is_numeric($h))
$height = $h;
}
return '<object width="' . $width. '" height="' . $height. '">
<param name="movie" value="' . $content . '"></param>
<embed src="' . $content . '"
type="application/x-shockwave-flash"
width="' . $width. '" height="' . $height. '">
</embed>
</object>';
}, SBBCodeParser_BBCode::BLOCK_TAG),
new SBBCodeParser_BBCode('paypal', function($content, $attribs)
{
$content = urlencode($content);
return '<a href="https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business='
. $content . '&lc=US&no_note=0¤cy_code=USD&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHostedGuest">
<img src="https://www.paypal.com/en_US/i/btn/x-click-but21.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!"/></a>';
},
SBBCodeParser_BBCode::INLINE_TAG, false, array(), array('text_node'), SBBCodeParser_BBCode::AUTO_DETECT_EXCLUDE_ALL),
new SBBCodeParser_BBCode('pastebin', function($content, $attribs)
{
if(!preg_match("/^[a-zA-Z0-9]$/", $content))
{
preg_match("#http://pastebin.com/([a-zA-Z0-9]+)#", $content, $matches);
$content = '';
if(isset($matches[1]))
$content = $matches[1];
}
return '<script src="http://pastebin.com/embed_js.php?i=' . $content . '"></script>';
}, SBBCodeParser_BBCode::INLINE_TAG, false, array(), array('text_node'), SBBCodeParser_BBCode::AUTO_DETECT_EXCLUDE_ALL),
new SBBCodeParser_BBCode('gist', function($content, $attribs)
{
if($content != (string)intval($content))
{
preg_match("#https://gist.github.com/([0-9]+)#", $content, $matches);
$content = '';
if(isset($matches[1]))
$content = $matches[1];
}
else
$content = intval($content);
return '<script src="http://gist.github.com/' . $content . '.js"></script>';
}, SBBCodeParser_BBCode::INLINE_TAG, false, array(), array('text_node'), SBBCodeParser_BBCode::AUTO_DETECT_EXCLUDE_ALL),
new SBBCodeParser_BBCode('twitter', '<a href="https://twitter.com/%content%"
class="twitter-follow-button" data-show-count="false">Follow @%content%</a>
<script src="http://platform.twitter.com/widgets.js" type="text/javascript"></script>',
SBBCodeParser_BBCode::INLINE_TAG, false, array(), array('text_node'), SBBCodeParser_BBCode::AUTO_DETECT_EXCLUDE_ALL),
new SBBCodeParser_BBCode('tweets', "<script src=\"http://widgets.twimg.com/j/2/widget.js\"></script>
<script>
new TWTR.Widget({
version: 2,
type: 'profile',
rpp: 3,
interval: 6000,
width: 400,
height: 150,
theme: {
shell: {
background: '#333333',
color: '#ffffff'
},
tweets: {
background: '#000000',
color: '#ffffff',
links: '#4aed05'
}
},
features: {
scrollbar: false,
loop: false,
live: false,
hashtags: true,
timestamp: true,
avatars: false,
behavior: 'all'
}
}).render().setUser('%content%').start();
</script>",
SBBCodeParser_BBCode::INLINE_TAG, false, array(), array('text_node'), SBBCodeParser_BBCode::AUTO_DETECT_EXCLUDE_ALL),
new SBBCodeParser_BBCode('googlemaps', '<iframe src="http://maps.google.com/maps?q=%content%&output=embed"
scrolling="no" width="100%" height="350" frameborder="0"></iframe>',
SBBCodeParser_BBCode::BLOCK_TAG, false, array(), array('text_node'), SBBCodeParser_BBCode::AUTO_DETECT_EXCLUDE_ALL),
new SBBCodeParser_BBCode('pdf', '<iframe src="http://docs.google.com/gview?url=%content%&embedded=true"
width="100%" height="500" frameborder="0"></iframe>',
SBBCodeParser_BBCode::BLOCK_TAG, false, array(), array('text_node'), SBBCodeParser_BBCode::AUTO_DETECT_EXCLUDE_ALL),
new SBBCodeParser_BBCode('scribd', function($content, $attribs)
{
if(!isset($attribs['id'])
|| !($attribs['id'] = intval($attribs['id'])) > 1)
return 'Invalid scribd ID.';
if(!isset($attribs['key']))
return 'Missing scribd key.';
return '<iframe src="http://www.scribd.com/embeds/' . $attribs['id'] . '/content?start_page=1&view_mode=list&access_key=' . $attribs['key'] . '"
data-auto-height="true" data-aspect-ratio="1" scrolling="no" width="100%"
height="500" frameborder="0"></iframe>
<script type="text/javascript">(function() {
var scribd = document.createElement("script");
scribd.type = "text/javascript";
scribd.async = true;
scribd.src = "http://www.scribd.com/javascripts/embed_code/inject.js";
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(scribd, s);
})();</script>';
}, SBBCodeParser_BBCode::BLOCK_TAG, true, array(), array(), SBBCodeParser_BBCode::AUTO_DETECT_EXCLUDE_ALL),
new SBBCodeParser_BBCode('spoiler', '<div class="spoiler" style="margin:5px 15px 15px 15px">
<div style="margin:0 0 2px 0; font-weight:bold;">Spoiler:
<input type="button" value="Show"
onclick="if (this.value == \'Show\')
{
this.parentNode.parentNode.getElementsByTagName(\'div\')[1].getElementsByTagName(\'div\')[0].style.display = \'block\';
this.value = \'Hide\';
} else {
this.parentNode.parentNode.getElementsByTagName(\'div\')[1].getElementsByTagName(\'div\')[0].style.display = \'none\';
this.value = \'Show\';
}" />
</div>
<div style="margin:0; padding:6px; border:1px inset;">
<div style="display: none;">
%content%
</div>
</div>
</div>'),
new SBBCodeParser_BBCode('tt', '<span style="font-family: monospace">%content%</span>'),
new SBBCodeParser_BBCode('pre', function($content, $attribs, $node)
{
$content = '';
foreach($node->children() as $child)
$content .= $child->get_html(false);
return "<pre>{$content}</pre>";
}, SBBCodeParser_BBCode::BLOCK_TAG),
new SBBCodeParser_BBCode('code', '<code>%content%</code>',
SBBCodeParser_BBCode::BLOCK_TAG, false, array(), array('text_node'), SBBCodeParser_BBCode::AUTO_DETECT_EXCLUDE_EMOTICON),
new SBBCodeParser_BBCode('php', function($content, $attribs, $node)
{
ob_start();
highlight_string($node->get_text());
$content = ob_get_contents();
ob_end_clean();
return "<code class=\"php\">{$content}</code>";
}, SBBCodeParser_BBCode::BLOCK_TAG, false, array(), array('text_node'), SBBCodeParser_BBCode::AUTO_DETECT_EXCLUDE_EMOTICON),
new SBBCodeParser_BBCode('quote', function($content, $attribs, $node)
{
$cite = '';
if(!empty($attribs['default']))
$cite = "<cite>{$attribs['default']}:</cite>";
if($node->find_parent_by_tag('quote') !== null)
return "</p><blockquote><p>{$cite}{$content}</p></blockquote><p>";
return "<blockquote><p>{$cite}{$content}</p></blockquote>";
}, SBBCodeParser_BBCode::BLOCK_TAG),
new SBBCodeParser_BBCode('font', function($content, $attribs)
{
// Font can have letters, spaces, quotes, - and commas
if(!isset($attribs['default'])
|| !preg_match("/^([A-Za-z\'\",\- ]+)$/", $attribs['default']))
$attribs['default'] = 'Arial';
return '<span style="font-family: ' . $attribs['default'] . '">' . $content . '</span>';
}),
new SBBCodeParser_BBCode('size', function($content, $attribs)
{
$size = 'xx-small';
/*
Font tag sizes 1-7 should be:
1 = xx-small
2 = small
3 = medium
4 = large
5 = x-large
6 = xx-large
7 = ?? in chrome it's 48px
*/
if(!isset($attribs['default']))
$size = 'xx-small';
else if($attribs['default'] == 2)
$size = 'small';
else if($attribs['default'] == 3)
$size = 'medium';
else if($attribs['default'] == 4)
$size = 'large';
else if($attribs['default'] == 5)
$size = 'x-large';
else if($attribs['default'] == 6)
$size = 'xx-large';
else if($attribs['default'] == 7)
$size = '48px';
else if($attribs['default'][strlen($attribs['default']) - 1] === '%'
&& is_numeric(substr($attribs['default'], 0, -1)))
$size = $attribs['default'];
else
{
if(!is_numeric($attribs['default']))
$attribs['default'] = 13;
if($attribs['default'] < 6)
$attribs['default'] = 6;
if($attribs['default'] > 48)
$attribs['default'] = 48;
$size = $attribs['default'] . 'px';
}
return '<span style="font-size: ' . $size . '">' . $content . '</span>';
}),
new SBBCodeParser_BBCode('color', function($content, $attribs)
{
// colour must be either a hex #xxx/#xxxxxx or a word with no spaces red/blue/ect.
if(!isset($attribs['default'])
|| !preg_match("/^(#[a-fA-F0-9]{3,6}|[A-Za-z]+)$/", $attribs['default']))
$attribs['default'] = '#000';
return '<span style="color: ' . $attribs['default'] . '">' . $content . '</span>';
}),
new SBBCodeParser_BBCode('list', function($content, $attribs)
{
$style = 'circle';
$type = 'ul';
switch($attribs['default'])
{
case 'd':
$style = 'disc';
$type = 'ul';
break;
case 's':
$style = 'square';
$type = 'ul';
break;
case '1':
$style = 'decimal';
$type = 'ol';
break;
case 'a':
$style = 'lower-alpha';
$type = 'ol';
break;
case 'A':
$style = 'upper-alpha';
$type = 'ol';
break;
case 'i':
$style = 'lower-roman';
$type = 'ol';
break;
case 'I':
$style = 'upper-roman';
$type = 'ol';
break;
}
return "<{$type} style=\"list-style: {$style}\">{$content}</{$type}>";
}, SBBCodeParser_BBCode::BLOCK_TAG, false, array(), array('*', 'li', 'ul', 'li', 'ol', 'list')),
new SBBCodeParser_BBCode('ul', '<ul>%content%</ul>', SBBCodeParser_BBCode::BLOCK_TAG),
new SBBCodeParser_BBCode('ol', '<ol>%content%</ol>', SBBCodeParser_BBCode::BLOCK_TAG),
new SBBCodeParser_BBCode('li', '<li>%content%</li>'),
new SBBCodeParser_BBCode('*', '<li>%content%</li>', SBBCodeParser_BBCode::BLOCK_TAG, false,
array('*', 'li', 'ul', 'li', 'ol', '/list')),
new SBBCodeParser_BBCode('table', '<table>%content%</table>', SBBCodeParser_BBCode::BLOCK_TAG,
false, array(), array('table', 'th', 'h', 'tr', 'row', 'r', 'td', 'col', 'c')),
new SBBCodeParser_BBCode('th', '<th>%content%</th>'),
new SBBCodeParser_BBCode('h', '<th>%content%</th>'),
new SBBCodeParser_BBCode('tr', '<tr>%content%</tr>', SBBCodeParser_BBCode::BLOCK_TAG, false,
array(), array('table', 'th', 'h', 'tr', 'row', 'r', 'td', 'col', 'c')),
new SBBCodeParser_BBCode('row', '<tr>%content%</tr>', SBBCodeParser_BBCode::BLOCK_TAG, false,
array(), array('table', 'th', 'h', 'tr', 'row', 'r', 'td', 'col', 'c')),
new SBBCodeParser_BBCode('r', '<tr>%content%</tr>', SBBCodeParser_BBCode::BLOCK_TAG, false,
array(), array('table', 'th', 'h', 'tr', 'row', 'r', 'td', 'col', 'c')),
new SBBCodeParser_BBCode('td', '<td>%content%</td>'),
new SBBCodeParser_BBCode('col', '<td>%content%</td>'),
new SBBCodeParser_BBCode('c', '<td>%content%</td>'),
new SBBCodeParser_BBCode('notag', '%content%', SBBCodeParser_BBCode::INLINE_TAG, false, array(), array('text_node'),
SBBCodeParser_BBCode::AUTO_DETECT_EXCLUDE_ALL),
new SBBCodeParser_BBCode('nobbc', '%content%', SBBCodeParser_BBCode::INLINE_TAG, false, array(), array('text_node'),
SBBCodeParser_BBCode::AUTO_DETECT_EXCLUDE_ALL),
new SBBCodeParser_BBCode('noparse', '%content%', SBBCodeParser_BBCode::INLINE_TAG, false, array(), array('text_node'),
SBBCodeParser_BBCode::AUTO_DETECT_EXCLUDE_ALL),
new SBBCodeParser_BBCode('h1', '<h1>%content%</h1>'),
new SBBCodeParser_BBCode('h2', '<h2>%content%</h2>'),
new SBBCodeParser_BBCode('h3', '<h3>%content%</h3>'),
new SBBCodeParser_BBCode('h4', '<h4>%content%</h4>'),
new SBBCodeParser_BBCode('h5', '<h5>%content%</h5>'),
new SBBCodeParser_BBCode('h6', '<h6>%content%</h6>'),
new SBBCodeParser_BBCode('big', '<span style="font-size: large">%content%</span>'),
new SBBCodeParser_BBCode('small', '<span style="font-size: x-small">%content%</span>'),
// tables use this tag so can't be a header.
//new SBBCodeParser_BBCode('h', '<h5>%content%</h5>'),
new SBBCodeParser_BBCode('br', '<br />', SBBCodeParser_BBCode::INLINE_TAG, true),
new SBBCodeParser_BBCode('sp', ' ', SBBCodeParser_BBCode::INLINE_TAG, true),
new SBBCodeParser_BBCode('hr', '<hr />', SBBCodeParser_BBCode::INLINE_TAG, true),
new SBBCodeParser_BBCode('anchor', function($content, $attribs, $node)
{
if(empty($attribs['default']))
{
$attribs['default'] = $content;
// remove the content for [anchor]test[/anchor]
// usage as test is the anchor
$content = '';
}
$attribs['default'] = preg_replace('/[^a-zA-Z0-9_\-]+/', '', $attribs['default']);
return "<a name=\"{$attribs['default']}\">{$content}</a>";
}),
new SBBCodeParser_BBCode('goto', function($content, $attribs, $node)
{
if(empty($attribs['default']))
$attribs['default'] = $content;
$attribs['default'] = preg_replace('/[^a-zA-Z0-9_\-#]+/', '', $attribs['default']);
return "<a href=\"#{$attribs['default']}\">{$content}</a>";
}),
new SBBCodeParser_BBCode('jumpto', function($content, $attribs, $node)
{
if(empty($attribs['default']))
$attribs['default'] = $content;
$attribs['default'] = preg_replace('/[^a-zA-Z0-9_\-#]+/', '', $attribs['default']);
return "<a href=\"#{$attribs['default']}\">{$content}</a>";
}),
new SBBCodeParser_BBCode('img', function($content, $attribs, $node)
{
$attrs = '';
// for when default attrib is used for width x height
if(isset($attribs['default']) && preg_match("/[0-9]+[Xx\*][0-9]+/", $attribs['default']))
{
list($attribs['width'],$attribs['height']) = explode('x', $attribs['default']);
$attribs['default'] = '';
}
// for when width & height are specified as the default attrib
else if(isset($attribs['default']) && is_numeric($attribs['default']))
{
$attribs['width'] = $attribs['height'] = $attribs['default'];
$attribs['default'] = '';
}
// add alt tag if is one
if(isset($attribs['default']) && !empty($attribs['default']))
$attrs .= " alt=\"{$attribs['default']}\"";
else if(isset($attribs['alt']))
$attrs .= " alt=\"{$attribs['alt']}\"";
else
$attrs .= " alt=\"{$content}\"";
// width and height can only be numeric, anything else should be ignored to prevent XSS
if(isset($attribs['width']) && is_numeric($attribs['width']))
$attrs .= " width=\"{$attribs['width']}\"";
if(isset($attribs['height']) && is_numeric($attribs['height']))
$attrs .= " height=\"{$attribs['height']}\"";
// add http:// to www starting urls
if(strpos($content, 'www') === 0)
$content = 'http://' . $content;
// add the base url to any urls not starting with http or ftp as they must be relative
else if(substr($content, 0, 4) !== 'http'
&& substr($content, 0, 3) !== 'ftp')
$content = $node->root()->get_base_uri() . $content;
return "<img{$attrs} src=\"{$content}\" />";
}, SBBCodeParser_BBCode::INLINE_TAG, false, array(), array('text_node'), SBBCodeParser_BBCode::AUTO_DETECT_EXCLUDE_ALL),
new SBBCodeParser_BBCode('email', function($content, $attribs, $node)
{
if(empty($attribs['default']))
$attribs['default'] = $content;
return "<a href=\"mailto:{$attribs['default']}\">{$content}</a>";
}, SBBCodeParser_BBCode::INLINE_TAG, false, array(), array('text_node'), SBBCodeParser_BBCode::AUTO_DETECT_EXCLUDE_ALL),
new SBBCodeParser_BBCode('url', function($content, $attribs, $node)
{
if(empty($attribs['default']))
$attribs['default'] = $content;
// add http:// to www starting urls
if(strpos($attribs['default'], 'www') === 0)
$attribs['default'] = 'http://' . $attribs['default'];
// add the base url to any urls not starting with http or ftp as they must be relative
else if(substr($attribs['default'], 0, 4) !== 'http'
&& substr($attribs['default'], 0, 3) !== 'ftp')
$attribs['default'] = $node->root()->get_base_uri() . $attribs['default'];
return "<a href=\"{$attribs['default']}\">{$content}</a>";
}, SBBCodeParser_BBCode::INLINE_TAG, false, array(), array('text_node'), SBBCodeParser_BBCode::AUTO_DETECT_EXCLUDE_ALL)
);
}
/**
* Adds an emoticon to the parser.
* @param string $key
* @param string $url
* @param bool $replace If to replace another emoticon with the same key
* @return bool
*/
public function add_emoticon($key, $url, $replace=true)
{
if(isset($this->emoticons[$key]) && !$replace)
return false;
$this->emoticons[$key] = $url;
return true;
}
/**
* Adds multipule emoticons to the parser. Should be in
* emoticon_key => image_url format.
* @param Array $emoticons
* @param bool $replace If to replace another emoticon with the same key
*/
public function add_emoticons(Array $emoticons, $replace=true)
{
foreach($emoticons as $key => $url)
$this->add_emoticon($key, $url, $replace);
}
/**
* Removes an emoticon from the parser.
* @param string $key
* @return bool
*/
public function remove_emoticon($key, $url)
{
if(!isset($this->emoticons[$key]))
return false;
unset($this->emoticons[$key]);
return true;
}
/**
* Adds a bbcode to the parser
* @param SBBCodeParser_BBCode $bbcode
* @param bool $replace If to replace another bbcode which is for the same tag
* @return bool
*/
public function add_bbcode(SBBCodeParser_BBCode $bbcode, $replace=true)
{
if(!$replace && isset($this->bbcodes[$bbcode->tag()]))
return false;
$this->bbcodes[$bbcode->tag()] = $bbcode;
return true;
}
/**
* Adds an array of SBBCodeParser_BBCode's to the document
* @param array $bbcodes
* @param bool $replace
* @see add_bbcode
*/
public function add_bbcodes(Array $bbcodes, $replace=true)
{
foreach($bbcodes as $bbcode)
$this->add_bbcode($bbcode, $replace);
}
/**
* Removes a BBCode from the document
* @param mixed $bbcode String tag name or SBBCodeParser_BBCode
*/
public function remove_bbcode($bbcode)
{
if($bbcode instanceof SBBCodeParser_BBCode)
$bbcode = $bbcode->tag();
unset($this->bbcodes[$bbcode]);
}
/**
* Gets an array of bbcode tags that will currently be processed
* @return array
*/
public function list_bbcodes()
{
return array_keys($this->bbcodes);
}
/**
* Returns the SBBCodeParser_BBCode object for the passed
* tag.
* @param string $tag
* @return SBBCodeParser_BBCode
*/
public function get_bbcode($tag)
{
if(!isset($this->bbcodes[$tag]))
return null;
return $this->bbcodes[$tag];
}
/**
* Gets the base URI to be used in links, images, ect.
* @return string
*/
public function get_base_uri()
{
if($this->base_uri != null)
return $this->base_uri;
return htmlentities(dirname($_SERVER['PHP_SELF']), ENT_QUOTES | ENT_IGNORE, "UTF-8") . '/';
}
/**
* Sets the base URI to be used in links, images, ect.
* @param string $uri
*/
public function set_base_uri($uri)
{
$this->base_uri = $uri;
}
/**
* Parses a BBCode string into the current document
* @param string $str
* @return SBBCodeParser_Document
*/
public function parse($str)
{
$str = preg_replace('/[\r\n|\r]/', "\n", $str);
$len = strlen($str);
$tag_open = false;
$tag_text = '';
$tag = '';
// set the document as the current tag.
$this->current_tag = $this;
for($i=0; $i<$len; ++$i)
{
if($str[$i] === '[')
{
if($tag_open)
$tag_text .= '[' . $tag;
$tag_open = true;
$tag = '';
}
else if($str[$i] === ']' && $tag_open)
{
if($tag !== '')
{
$bits = preg_split('/([ =])/', trim($tag), 2, PREG_SPLIT_DELIM_CAPTURE);
$tag_attrs = (isset($bits[2]) ? $bits[1] . $bits[2] : '');
$tag_closing = ($bits[0][0] === '/');
$tag_name = ($bits[0][0] === '/' ? substr($bits[0], 1) : $bits[0]);
if(isset($this->bbcodes[$tag_name]))
{
$this->tag_text($tag_text);
$tag_text = '';
if($tag_closing)
{
if(!$this->tag_close($tag_name))
$tag_text = "[{$tag}]";
}
else
{
if(!$this->tag_open($tag_name, $this->parse_attribs($tag_attrs)))
$tag_text = "[{$tag}]";
}
}
else
$tag_text .= "[{$tag}]";
}
else
$tag_text .= '[]';
$tag_open = false;
$tag = '';
}
else if($tag_open)
$tag .= $str[$i];
else
$tag_text .= $str[$i];
}
$this->tag_text($tag_text);
if($this->throw_errors && !$this->current_tag instanceof SBBCodeParser_Document)
throw new SBBCodeParser_MissingEndTagException("Missing closing tag for tag [{$this->current_tag->tag()}]");
return $this;
}
/**
* Handles a BBCode opening tag
* @param string $tag
* @param array $attrs
* @return bool
*/
private function tag_open($tag, $attrs)
{
if($this->current_tag instanceof SBBCodeParser_TagNode)
{
$closing_tags = $this->bbcodes[$this->current_tag->tag()]->closing_tags();
if(in_array($tag, $closing_tags))
$this->tag_close($this->current_tag->tag());
}
if($this->current_tag instanceof SBBCodeParser_TagNode)
{
$accepted_children = $this->bbcodes[$this->current_tag->tag()]->accepted_children();
if(!empty($accepted_children) && !in_array($tag, $accepted_children))
return false;
// if throw errors and this is a block element and the parent is inline throw an error
if($this->throw_errors && !$this->bbcodes[$tag]->is_inline()
&& $this->bbcodes[$this->current_tag->tag()]->is_inline())
throw new SBBCodeParser_InvalidNestingException("Block level tag [{$tag}] was opened within an inline tag [{$this->current_tag->tag()}]");
}
$node = new SBBCodeParser_TagNode($tag, $attrs);
$this->current_tag->add_child($node);
if(!$this->bbcodes[$tag]->is_self_closing())
$this->current_tag = $node;
return true;
}
/**
* Handles tag text
* @param string $text
* @return void
*/
private function tag_text($text)
{
if($this->current_tag instanceof SBBCodeParser_TagNode)
{
$accepted_children = $this->bbcodes[$this->current_tag->tag()]->accepted_children();
if(!empty($accepted_children) && !in_array('text_node', $accepted_children))
return;
}
$this->current_tag->add_child(new SBBCodeParser_TextNode($text));
}
/**
* Handles BBCode closing tag
* @param string $tag
* @return bool
*/
private function tag_close($tag)
{
if(!$this->current_tag instanceof SBBCodeParser_Document
&& $tag !== $this->current_tag->tag())
{
$closing_tags = $this->bbcodes[$this->current_tag->tag()]->closing_tags();
if(in_array($tag, $closing_tags) || in_array('/' . $tag, $closing_tags))
$this->current_tag = $this->current_tag->parent();
}
if($this->current_tag instanceof SBBCodeParser_Document)
return false;
else if($tag !== $this->current_tag->tag())
{
// check if this is a tag inside another tag like
// [tag1] [tag2] [/tag1] [/tag2]
$node = $this->current_tag->find_parent_by_tag($tag);
if($node !== null)
{
$this->current_tag = $node->parent();
while(($node = $node->last_tag_node()) !== null)
{
$new_node = new SBBCodeParser_TagNode($node->tag(), $node->attributes());
$this->current_tag->add_child($new_node);
$this->current_tag = $new_node;
}
}
else
return false;
}
else
$this->current_tag = $this->current_tag->parent();
return true;
}
/**
* Parses a bbcode attribute string into an array
* @param string $attribs
* @return array
*/
private function parse_attribs($attribs)
{
$ret = array('default' => null);
$attribs = trim($attribs);
if($attribs == '')
return $ret;
// if this tag only has one = then there is only one attribute
// so add it all to default
if($attribs[0] == '=' && strrpos($attribs, '=') === 0)
$ret['default'] = htmlentities(substr($attribs, 1), ENT_QUOTES | ENT_IGNORE, "UTF-8");
else
{
preg_match_all('/(\S+)=((?:(?:(["\'])(?:\\\3|[^\3])*?\3))|(?:[^\'"\s]+))/',
$attribs,
$matches,
PREG_SET_ORDER);
foreach($matches as $match)
$ret[$match[1]] = htmlentities($match[2], ENT_QUOTES | ENT_IGNORE, "UTF-8");
}
return $ret;
}
private function loop_text_nodes($func, array $exclude=array(), SBBCodeParser_ContainerNode $node=null)
{
if($node === null)
$node = $this;
foreach($node->children() as $child)
{
if($child instanceof SBBCodeParser_TagNode)
{
if(!in_array($child->tag(), $exclude))
$this->loop_text_nodes($func, $exclude, $child);
}
else if($child instanceof SBBCodeParser_TextNode)
{
$func($child);
}
}
}
/**
* Detects any none clickable links and makes them clickable
* @return SBBCodeParserDdocument
*/
public function detect_links()
{
$this->loop_text_nodes(function($child) {
preg_match_all("/(?:(?:https?|ftp):\/\/|(?:www|ftp)\.)(?:[a-zA-Z0-9\-\.]{1,255}\.[a-zA-Z]{1,20})(?::[0-9]{1,5})?(?:\/[^\s'\"]*)?(?:(?<![,\)\.])|[\S])/",
$child->get_text(),
$matches,
PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE);
if(count($matches[0]) == 0)
return;
$replacment = array();
$last_pos = 0;
foreach($matches[0] as $match)
{
if(substr($match[0], 0, 3) === 'ftp' && $match[0][3] !== ':')
$url = 'ftp://' . $match[0];
else if($match[0][0] === 'w')
$url = 'http://' . $match[0];
else
$url = $match[0];
$url = new SBBCodeParser_TagNode('url', array('default' => htmlentities($url, ENT_QUOTES | ENT_IGNORE, "UTF-8")));
$url_text = new SBBCodeParser_TextNode($match[0]);
$url->add_child($url_text);
$replacment[] = new SBBCodeParser_TextNode(substr($child->get_text(), $last_pos, $match[1] - $last_pos));
$replacment[] = $url;
$last_pos = $match[1] + strlen($match[0]);
}
$replacment[] = new SBBCodeParser_TextNode(substr($child->get_text(), $last_pos));
$child->parent()->replace_child($child, $replacment);
}, $this->get_excluded_tags(SBBCodeParser_BBCode::AUTO_DETECT_EXCLUDE_URL));
return $this;
}
/**
* Detects any none clickable emails and makes them clickable
* @return SBBCodeParserDdocument
*/
public function detect_emails()
{
$this->loop_text_nodes(function($child) {
preg_match_all("/(?:[a-zA-Z0-9\-\._]){1,}@(?:[a-zA-Z0-9\-\.]{1,255}\.[a-zA-Z]{1,20})/",
$child->get_text(),
$matches,
PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE);
if(count($matches[0]) == 0)
return;
$replacment = array();
$last_pos = 0;
foreach($matches[0] as $match)
{
$url = new SBBCodeParser_TagNode('email', array());
$url_text = new SBBCodeParser_TextNode($match[0]);
$url->add_child($url_text);
$replacment[] = new SBBCodeParser_TextNode(substr($child->get_text(), $last_pos, $match[1] - $last_pos));
$replacment[] = $url;
$last_pos = $match[1] + strlen($match[0]);
}
$replacment[] = new SBBCodeParser_TextNode(substr($child->get_text(), $last_pos));
$child->parent()->replace_child($child, $replacment);
}, $this->get_excluded_tags(SBBCodeParser_BBCode::AUTO_DETECT_EXCLUDE_EMAIL));
return $this;
}
/**
* Detects any emoticons and replaces them with their images
* @return SBBCodeParserDdocument
*/
public function detect_emoticons()
{
if(empty($this->emoticons))
return $this;
$pattern = '';
foreach($this->emoticons as $key => $url)
$pattern .= ($pattern === ''? '/(?:':'|') . preg_quote($key, '/');
$pattern .= ')/';
$emoticons = $this->emoticons;
$this->loop_text_nodes(function($child) use ($pattern, $emoticons) {
preg_match_all($pattern,
$child->get_text(),
$matches,
PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE);
if(count($matches[0]) == 0)
return;
$replacment = array();
$last_pos = 0;
foreach($matches[0] as $match)
{
$url = new SBBCodeParser_TagNode('img', array('alt'=>$match[0]));
$url_text = new SBBCodeParser_TextNode($emoticons[$match[0]]);
$url->add_child($url_text);
$replacment[] = new SBBCodeParser_TextNode(substr($child->get_text(), $last_pos, $match[1] - $last_pos));
$replacment[] = $url;
$last_pos = $match[1] + strlen($match[0]);
}
$replacment[] = new SBBCodeParser_TextNode(substr($child->get_text(), $last_pos));
$child->parent()->replace_child($child, $replacment);
}, $this->get_excluded_tags(SBBCodeParser_BBCode::AUTO_DETECT_EXCLUDE_EMOTICON));
return $this;
}
/**
* Gets an array of tages to be excluded from
* the elcude param
* @param int $exclude What to gets excluded from i.e. SBBCodeParser_BBCode::AUTO_DETECT_EXCLUDE_EMOTICON
* @return array
*/
private function get_excluded_tags($exclude)
{
$ret = array();
foreach($this->bbcodes as $bbcode)
if($bbcode->auto_detect_exclude() & $exclude)
$ret[] = $bbcode->tag();
return $ret;
}
} | true |
2969f1df78f688419f2b3bd2f65d0fca99a95d96 | PHP | onshop/beegame | /src/Game/Bee/Queen.php | UTF-8 | 160 | 2.546875 | 3 | [] | no_license | <?php
namespace Game\Bee;
class Queen extends AbstractBee
{
protected $lifeSpan = 100;
protected $hitDeduction = 8;
protected $type = 'Queen';
} | true |
a64cc30fe9b36b8986d90dc2a1aaf2c8b60884c9 | PHP | 1992abdo/Porte-Folio | /confing/update.php | UTF-8 | 3,833 | 2.515625 | 3 | [] | no_license | <?php
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Update product</title>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css"
integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="../css/contact.css">
</head>
<body>
<div class="container">
<h1 class="text-center mt-3 text-secondary">UP DATE THIS ITEM</h1>
<form action="<?php echo $_SERVER["PHP_SELF"];?>" class="controle-form" method="post">
<input type="text" name="description" placeholder="Type the description" class="form-control my-4">
<input type="text" name="lienGithub" placeholder="Type lien of Github" class="form-control">
<input type="file" name="photo" class="my-4">
<input type="submit" class="btn btn-primary btn-block" name="submit" value="Valid">
<i class="fas fa-paper-plane "></i>
</form>
</div>
<?php
// will get the id with the methode GET lock to the url you will see the id
if($_SERVER['REQUEST_METHOD'] == "GET"){
$_SESSION["id"] =$_GET['id'];
}
if($_SERVER["REQUEST_METHOD"] == "POST"){
$description=$_POST["description"];
$photo=$_POST["photo"];
$lienGithub=$_POST["lienGithub"];
$host = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName="abdo";
$conn = mysqli_connect($host, $dbUsername, $dbPassword, $dbName);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}else{
if(!empty($description)){
$sql = "UPDATE portefolio SET description='$description' WHERE id='".$_SESSION['id']."'";
if ($conn->query($sql) === TRUE) {
echo "<script> alert(\"New record created successfully\")</script>";
}
} elseif(!empty($photo)){
$sql = "UPDATE portefolio SET photo='$photo' WHERE id='".$_SESSION['id']."'";
if ($conn->query($sql) === TRUE) {
echo "<script> alert(\"New record created successfully\")</script>";
}
} elseif(!empty($lienGithub)){
$sql = "UPDATE portefolio SET lienGithub='$lienGithub' WHERE id='".$_SESSION['id']."'";
if ($conn->query($sql) === TRUE) {
echo "<script> alert(\"New record created successfully\")</script>";
}
} else {
echo "<script> alert(\"There is some errors\")</script>";
}
$conn->close();
session_unset($_SESSION['id']);
header('Location: ../dashbord.php');
}
}
// }
?>
<!-- bootstrap CDN -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous">
</script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous">
</script>
</body>
</html> | true |
70395949b9490771159b448def6dabbdcbef1fe2 | PHP | P79N6A/hd | /.svn/pristine/70/70395949b9490771159b448def6dabbdcbef1fe2.svn-base | UTF-8 | 1,445 | 2.640625 | 3 | [] | no_license | <?php
class DeptController extends InteractionBaseController {
public function initialize()
{
parent::initialize(); // TODO: Change the autogenerated stub
}
/**
* 获取所有部门并建树
*/
public function getDeptAction(){
$channel_id = intval(Request::getQuery('channel_id','int',1));
$dept = GovernmentDepartment::getDeptByChannelId($channel_id);
$dept_tree = $this->_tree($dept);
$this->_json($dept_tree);
}
/**
* 构建树
* @param $res
* @return array
*/
protected function _tree($res)
{
$items = array();
foreach ($res as $val) {
if(isset($val['id'])){
$items[$val['id']] = $val;
}
}
$tree = array();
foreach ($items as $key => $item) {
if (isset($items[$item['father_id']])) {
$items[$item['father_id']]['sons'][] = &$items[$item['id']];
} else {
$tree[] = &$items[$item['id']];
}
}
return $tree;
}
/**
* @param $data
* @param int $code
* @param string $msg
*/
protected function _json($data, $code = 200, $msg = "success")
{
header('Content-type: application/json');
echo json_encode([
'code' => $code,
'msg' => $msg,
'data' => $data,
]);
exit;
}
} | true |
7b54b393ba8a6809f52d8cdefefef2f413dca963 | PHP | taichunmin/UnitTest-20180731-OTP | /src/RsaTokenDao.php | UTF-8 | 263 | 2.734375 | 3 | [] | no_license | <?php
namespace OTP;
interface IToken
{
public function getRandom(string $account) : string;
}
class RsaTokenDao implements IToken
{
public function getRandom(string $account) : string
{
return sprintf('%06d', mt_rand(0, 999999));
}
}
| true |
e32efb28a92f0421dd313ca7d2257bccea76c5bd | PHP | elu-dev/weeber | /controllers/utils.php | UTF-8 | 225 | 2.625 | 3 | [] | no_license | <?php
function sanity_check($data, $flag=TRUE) {
$data = trim($data);
if ($flag) $data = stripslashes($data);
else $data = str_replace("\\", "\\\\", $data);
$data = htmlspecialchars($data);
return $data;
} | true |
a8bcea2f5a0fb839bfa368259303bbaf4d1f2c6a | PHP | chequeado/vos-y-cuantos-mas | /app/Http/Controllers/Backend/StatsController.php | UTF-8 | 900 | 2.609375 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers\Backend;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Repositories\Backend\Category\CategoryRepositoryContract;
/**
* Class StatsController
* @package App\Http\Controllers\Backend
*/
class StatsController extends Controller
{
protected $categories;
/**
* @param CategoryRepositoryContract $categories
* @param PermissionRepositoryContract $permissions
*/
public function __construct(
CategoryRepositoryContract $categories
)
{
$this->categories = $categories;
}
/**
* @return \Illuminate\View\View
*/
public function index(Request $request)
{
$cat = ($request->has('cat'))?$request->input('cat'):1;
$cats = $this->categories->getAllCategories();
return view('backend.stats.votes')->withCat($cat)->withCats($cats);
}
} | true |
736997bd2e5f32144df102ad3167766b52c0cd6b | PHP | Eneylton/php-carrinho-2 | /index.php | UTF-8 | 1,002 | 2.65625 | 3 | [] | no_license | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Carrinho</title>
</head>
<body>
<?php
require("conexao.php");
$resultado = '';
$sql = mysqli_query($connect, "Select * from produtos");
foreach ($sql as $key) {
$resultado .= '
<tr>
<td>'.$key["nome"].'</td>
<td>'.$key["qtd"].'</td>
<td>'.$key["preco"].'</td>
<td> <a href="carrinho.php?acao=add&id='.$key["id"].'"> Comprar </a> </td>
</tr>
';
}
?>
</body>
<table style="border:1px #e1e1e1 solid">
<thead>
<tr>
<th>Nome</th>
<th>Qtd</th>
<th>Preço</th>
<th>Ação</th>
</tr>
</thead>
<tbody>
<?=$resultado ?>
</tbody>
</table>
</html> | true |
077ba8594b9c9b99d46b327c3d067392adbf99cf | PHP | octalmage/wib | /php-7.3.0/ext/standard/tests/array/array_map_basic.phpt | UTF-8 | 1,275 | 3.703125 | 4 | [
"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--
Test array_map() function : basic functionality
--FILE--
<?php
/* Prototype : array array_map ( callback $callback , array $arr1 [, array $... ] )
* Description: Applies the callback to the elements of the given arrays
* Source code: ext/standard/array.c
*/
echo "*** Testing array_map() : basic functionality ***\n";
function multiply($p, $q) {
return ($p * $q);
}
function square($p) {
return ($p * $p);
}
function concatenate($a, $b) {
return "$a = $b";
}
// integer array
$arr1 = array(1, 2, 3);
$arr2 = array(4, 5, 6);
echo "-- With two integer array --\n";
var_dump( array_map('multiply', $arr1, $arr2) );
echo "-- With single integer array --\n";
var_dump( array_map('square', $arr1) );
// string array
$arr1 = array("one", "two");
$arr2 = array("single", "double");
echo "-- With string array --\n";
var_dump( array_map('concatenate', $arr1, $arr2) );
echo "Done";
?>
--EXPECT--
*** Testing array_map() : basic functionality ***
-- With two integer array --
array(3) {
[0]=>
int(4)
[1]=>
int(10)
[2]=>
int(18)
}
-- With single integer array --
array(3) {
[0]=>
int(1)
[1]=>
int(4)
[2]=>
int(9)
}
-- With string array --
array(2) {
[0]=>
string(12) "one = single"
[1]=>
string(12) "two = double"
}
Done
| true |
6423135a6ef1d1ae2de3d03aa131e1b2a954ba3c | PHP | SagLara/ArdAccess | /login/controller_ConsultUsr.php | UTF-8 | 675 | 2.640625 | 3 | [] | no_license | <?php
require 'conexion.php';
$idUser="";
$idUser = $mysqli->real_escape_string($_POST['idUser']);
$sql = "SELECT IDUSER,NOMBRE,FECHA_Registros FROM users WHERE IDUSER='$idUser'";
$resultado=$mysqli->query($sql);
if ($resultado->num_rows > 0) {
echo "<table class='table table-bordered table-hover'><thead><th>ID</th><th>Nombre</th><th>Registro</th></thead>";
while($row = $resultado->fetch_assoc()) {
echo "<tr><td>".$row["IDUSER"]."</td><td>".$row["NOMBRE"]."</td><td>".$row["FECHA_Registros"]."</td></tr>";
}
echo "</table>";
} else {
echo "<p class='alert alert-primary'>No hay resultados</p>";
}
$mysqli->close();
?> | true |
78979c28b68bdaf16e75dfd11effce05a36d6f6b | PHP | qingzhong110/Lge | /src/system/default/_ctl/Gitdeploy.class.php | UTF-8 | 5,596 | 2.671875 | 3 | [] | no_license | <?php
/**
* Git方式自动部署程序到服务器。
* 使用说明:
* 1、项目客户端应当已经保存密码;
* 2、如果是ssh push那么应当保证客户端与服务端已经通过ssh的authorized_keys授权,或者,安装sshpass工具,并在配置文件中对服务器指定密码;
* 3、在项目根目录下执行;
* 配置文件格式如下:
*
* array(
* '配置项名称' => array(
* array('服务器地址', '默认push分支名称', 'ssh push用户对应的服务器密码(非必须)')
* ),
* );
*
* @author john
*/
namespace Lge;
if (!defined('LGE')) {
exit('Include Permission Denied!');
}
/**
* Git方式自动部署.
*/
class Controller_Gitdeploy extends BaseController
{
/**
* 入口函数.
*
* @return void
*/
public function index()
{
$pwd = $this->_server['PWD'];
if (empty($pwd)) {
echo "当前工作目录地址不能为空!\n";
exit();
}
$option = Lib_ConsoleOption::instance();
$deployKey = $option->getOption('key', 'default');
$deployConfig = $option->getOption('config');
if (!empty($deployConfig) && file_exists($deployConfig)) {
$configArray = include($deployConfig);
$deployArray = isset($configArray[$deployKey]) ? $configArray[$deployKey] : array();
} else {
$deployArray = Config::get($deployKey, 'git-deploy', true);
}
if (empty($deployArray)) {
echo "找不到\"{$deployKey}\"对应的配置项!\n";
exit();
} else {
chdir($pwd);
foreach ($deployArray as $k => $item) {
$resp = $item[0];
$branch = empty($deployBranch) ? $item[1] : $deployBranch;
if ($branch == '*') {
exec('git config push.default matching');
$branch = '';
}
echo ($k + 1).": {$resp} {$branch}\n";
if (empty($item[2])) {
exec("git push {$resp} {$branch}");
} else {
$this->_checkAndInitGitRepoForRemoteServer($resp, $item[2]);
exec("sshpass -p {$item[2]} git push {$resp} {$branch}");
$this->_checkAndChangeRemoteRepoToSpecifiedBranch($resp, $branch, $item[2]);
}
echo "\n";
}
}
}
/**
* 检查目标服务器是否已经初始化。
*
* @param string $resp 版本库地址。
* @param string $pass 服务器SSH密码。
*
* @return void
*/
private function _checkAndInitGitRepoForRemoteServer($resp, $pass)
{
$parsed = $this->_parseRepository($resp);
if (!empty($parsed)) {
$user = $parsed['user'];
$host = $parsed['host'];
$port = $parsed['port'];
$path = $parsed['path'];
$ssh = new Lib_Network_Ssh($host, $port, $user, $pass);
$result = $ssh->syncCmd("if [ -d \"{$path}/.git\" ]; then echo 1; else echo 0; fi");
$result = trim($result);
if ($result == "0") {
// 如果服务器的git目录不存在那么初始化目录
$ssh->syncCmd("mkdir -p \"{$path}\" && cd \"{$path}\" && git init && git config receive.denyCurrentBranch ignore");
$ssh->sendFile($this->_getGitPostReceiveHookFilePath(), $path.'/.git/hooks/post-receive', 0777);
$ssh->disconnect();
}
}
}
/**
* 切换服务器上的分支为指定分支.
*
* @param string $resp 版本库地址。
* @param string $branch 分支名称。
* @param string $pass 服务器SSH密码。
*
* @return void
*/
private function _checkAndChangeRemoteRepoToSpecifiedBranch($resp, $branch, $pass)
{
$parsed = $this->_parseRepository($resp);
if (!empty($parsed)) {
$user = $parsed['user'];
$host = $parsed['host'];
$port = $parsed['port'];
$path = $parsed['path'];
$ssh = new Lib_Network_Ssh($host, $port, $user, $pass);
$ssh->syncCmd("cd \"{$path}\" && git checkout {$branch} -f");
$ssh->disconnect();
}
}
/**
* 解析版本库,将ssh的版本库解析为用户账号、地址、端口、路径的形式。
*
* @param string $resp 版本库地址。
*
* @return array
*/
private function _parseRepository($resp)
{
// 仓库格式形如: ssh://john@120.76.249.69//home/john/www/lge
$result = array();
if (preg_match("/ssh:\/\/(.+?)@([^:]+):{0,1}(\d*)\/(\/.+)/", $resp, $match)) {
$result['user'] = $match[1];
$result['host'] = $match[2];
$result['port'] = empty($match[3]) ? 22 : $match[3];
$result['path'] = rtrim($match[4], '/');
}
return $result;
}
/**
* 获得自动部署所需的hook文件。
*
* @return string
*/
private function _getGitPostReceiveHookFilePath()
{
$hookFilePath = '/tmp/lge_auto_git_repo_post-receive';
if (!file_exists($hookFilePath)) {
$hookContent = <<<MM
#!/bin/sh
export GIT_WORK_TREE=\${PWD}/..
export GIT_DIR=\${GIT_WORK_TREE}/.git
cd \${GIT_WORK_TREE} && git checkout -f;
MM;
file_put_contents($hookFilePath, $hookContent);
}
return $hookFilePath;
}
}
| true |
7cac91301b4bf56ffc0faa389a9acf18216801c8 | PHP | lohuvie/zhaibuqi | /vo/Fan.php | UTF-8 | 1,463 | 2.703125 | 3 | [] | no_license | <?php
/**
* Created by JetBrains PhpStorm.
* User: Lohuvie
* Date: 13-5-19
* Time: 上午12:12
* To change this template use File | Settings | File Templates.
*/
class Fan {
public $portrait;
public $id;
public $af_id;
public $href;
public $name;
public $academy;
public $status;
function __construct(){
$this -> academy = '';
}
public function setPortrait($portrait)
{
$this->portrait = $portrait;
}
public function getPortrait()
{
return $this->portrait;
}
public function setAcademy($academy)
{
$this->academy = $academy;
}
public function getAcademy()
{
return $this->academy;
}
public function setAfId($af_id)
{
$this->af_id = $af_id;
}
public function getAfId()
{
return $this->af_id;
}
public function setHref($href)
{
$this->href = $href;
}
public function getHref()
{
return $this->href;
}
public function setId($id)
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
public function setStatus($status)
{
$this->status = $status;
}
public function getStatus()
{
return $this->status;
}
} | true |
fa983433d00c53e83840e4805c88551056c276c5 | PHP | andreaskasper/alexa-php-endpoint | /examples/01_hello-world.php | UTF-8 | 195 | 2.6875 | 3 | [] | no_license | <?php
/*
* This is a easy example for Alexa to say "Hello World!"
*/
require_once(__DIR__."/../src/Response.php");
$r = new \Alexa\Endpoint\Response();
$r->say("Hello World!");
$r->send();
| true |
09ad87e2ac22c2b000de0fe0709ad87bfeb586c4 | PHP | MercerMorning/carsharing | /src/Rate.php | UTF-8 | 1,915 | 3.578125 | 4 | [] | no_license | <?php
namespace App;
/**
* Класс с основными свойствами и методами, которые имеются во всех тарифах
*/
abstract class Rate implements RateInt
{
/**
* Стоимость услуги "Дополнительный водитель"
*/
const COST_OF_DRIVER = 100;
/**
* Стоимость услуги gps за час
*/
const GPS_PRICE_FOR_HOUR = 15;
/**
* Пройденное расстояние во время использования тарифа
*/
protected $distance;
/**
* Пройденное время во время использования тарифа
*/
protected $time;
/**
* Общая цена за использование тарифа и дополнительных услуг
*/
protected $price;
/**
* Rate constructor.
* пройденное расстояние
* @param $transmittedDistance
* пройденное время
* @param $transmittedTime
* Установка пройденного расстояния и времени
*/
public function __construct($transmittedDistance, $transmittedTime)
{
$this->distance = $transmittedDistance;
$this->time = $transmittedTime;
}
/**
* Получение общей цены
*/
public function getPrice()
{
if ($this->onDriver) {
$this->price += self::COST_OF_DRIVER;
}
if ($this->time >= 60 && $this->onGps) {
$this->price += self::GPS_PRICE_FOR_HOUR * $this->roundPrice($this->time);
}
}
/**
* Округление до часа
*/
protected function roundPrice($price)
{
if (is_double($price / 60)) {
return ceil($price / 60);
}
return $price / 60;
}
}
| true |