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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
8fff53d7a7e7203fac530ea307c8cd8438c2fd37 | PHP | erevan22/wildrider | /sources/config/app.config.php | UTF-8 | 719 | 2.5625 | 3 | [] | no_license | <?php
/**
* Paramètres de connexion
* Création : 05/08/2014
* Stephan GIULIANI
*/
/* Récupération du fichier paramètres */
require("app.parametres.php");
/* Connexion base de données */
$db_name = "wildrider";
$db_user = "root";
$db_password = "troiswa";
//Test sur serveur (Développement / Production)
if($_SERVER['SERVER_NAME'] == "127.0.0.1" || substr($_SERVER['SERVER_NAME'], 0 ,8) == "192.168.")
{
//Serveur de développement
$db_host = "localhost";
}
else
{
//Serveur de production
$db_host = "";
}
//Connecteur de base de données
$db_link = mysqli_connect($db_host, $db_user, $db_password, $db_name) OR die($db_connexion_error);
?> | true |
cbe066403facf3527ddcee76b589be97747ae0ef | PHP | FastyBird/gateway-node | /src/Models/Keys/KeyRepository.php | UTF-8 | 1,796 | 2.59375 | 3 | [
"Apache-2.0"
] | permissive | <?php declare(strict_types = 1);
/**
* KeyRepository.php
*
* @license More in license.md
* @copyright https://www.fastybird.com
* @author Adam Kadlec <adam.kadlec@fastybird.com>
* @package FastyBird:GatewayNode!
* @subpackage Models
* @since 0.1.3
*
* @date 14.04.20
*/
namespace FastyBird\GatewayNode\Models\Keys;
use Doctrine\Common;
use Doctrine\Persistence;
use FastyBird\GatewayNode\Entities;
use Nette;
/**
* Key repository
*
* @package FastyBird:GatewayNode!
* @subpackage Models
*
* @author Adam Kadlec <adam.kadlec@fastybird.com>
*/
final class KeyRepository implements IKeyRepository
{
use Nette\SmartObject;
/** @var Common\Persistence\ManagerRegistry */
private Common\Persistence\ManagerRegistry $managerRegistry;
/** @var Persistence\ObjectRepository<Entities\Keys\Key>|null */
private ?Persistence\ObjectRepository $repository = null;
public function __construct(Common\Persistence\ManagerRegistry $managerRegistry)
{
$this->managerRegistry = $managerRegistry;
}
/**
* {@inheritDoc}
*/
public function findOneByIdentifier(string $identifier): ?Entities\Keys\IKey
{
/** @var Entities\Keys\IKey|null $key */
$key = $this->getRepository()->findOneBy(['id' => $identifier]);
return $key;
}
/**
* {@inheritDoc}
*/
public function findOneByKey(string $key): ?Entities\Keys\IKey
{
/** @var Entities\Keys\IKey|null $key */
$key = $this->getRepository()->findOneBy(['key' => $key]);
return $key;
}
/**
* @return Persistence\ObjectRepository<Entities\Keys\Key>
*/
private function getRepository(): Persistence\ObjectRepository
{
if ($this->repository === null) {
$this->repository = $this->managerRegistry->getRepository(Entities\Keys\Key::class);
}
return $this->repository;
}
}
| true |
8210185859671f1368ba1ca47abd93d44edcbb40 | PHP | google-code/acp3 | /ACP3/Core/View/Renderer/Smarty/Functions/WYSIWYG.php | UTF-8 | 1,364 | 2.515625 | 3 | [] | no_license | <?php
namespace ACP3\Core\View\Renderer\Smarty\Functions;
use ACP3\Core;
use Symfony\Component\DependencyInjection\Container;
/**
* Class WYSIWYG
* @package ACP3\Core\View\Renderer\Smarty\Functions
*/
class WYSIWYG extends AbstractFunction
{
/**
* @var \Symfony\Component\DependencyInjection\Container
*/
protected $container;
/**
* @param \Symfony\Component\DependencyInjection\Container $container
*/
public function __construct(Container $container)
{
$this->container = $container;
}
/**
* @inheritdoc
*/
public function getPluginName()
{
return 'wysiwyg';
}
/**
* @inheritdoc
*/
public function process(array $params, \Smarty_Internal_Template $smarty)
{
$params['id'] = !empty($params['id']) ? $params['id'] : $params['name'];
$serviceId = 'core.wysiwyg.' . $this->container->get('core.config')->getSettings('system')['wysiwyg'];
if ($this->container->has($serviceId) === true) {
/** @var Core\WYSIWYG\AbstractWYSIWYG $wysiwyg */
$wysiwyg = $this->container->get($serviceId);
$wysiwyg->setParameters($params);
return $wysiwyg->display();
} else {
throw new \InvalidArgumentException('Can not find wysiwyg service ' . $serviceId);
}
}
}
| true |
891675325700bd031ec7c0ce26271e32d5b66077 | PHP | oscarotero/psr7-unitesting | /src/Html/Count.php | UTF-8 | 628 | 2.625 | 3 | [
"MIT"
] | permissive | <?php
namespace Psr7Unitesting\Html;
use Symfony\Component\DomCrawler\Crawler;
use Psr7Unitesting\Utils\KeyValueConstraintTrait;
class Count extends AbstractConstraint
{
use KeyValueConstraintTrait;
public function toString()
{
return sprintf('has %d elements matching with the selector "%s"', $this->expected, $this->key);
}
protected function runMatches(Crawler $html)
{
return count($html->filter($this->key)) == $this->expected;
}
protected function additionalFailureDescription($html)
{
return sprintf('%d found', count($html->filter($this->key)));
}
}
| true |
3a7d72a2f249127d95fd263050bef9ac24ab0cf2 | PHP | garagepoort/BiblioMania | /app/service/filter/BookCountryFilter.php | UTF-8 | 1,304 | 2.6875 | 3 | [
"MIT"
] | permissive | <?php
use Bendani\PhpCommon\FilterService\Model\OptionsFilter;
use Bendani\PhpCommon\Utils\StringUtils;
class BookCountryFilter implements OptionsFilter
{
/** @var CountryService $countryService */
private $countryService;
/**
* BookCountryFilterHandler constructor.
*/
public function __construct()
{
$this->countryService = App::make('CountryService');
}
public function getFilterId()
{
return FilterType::BOOK_COUNTRY;
}
public function getType()
{
return "multiselect";
}
public function getField()
{
return "Land";
}
public function getOptions()
{
$options= array();
$noValueOption = array("key" => "Geen waarde", "value" => "");
array_push($options, $noValueOption);
foreach($this->countryService->getCountries() as $country){
if(!StringUtils::isEmpty($country->name)){
array_push($options, array("key"=>$country->name, "value"=>$country->id));
}else{
$noValueOption["value"] = $country->id;
}
}
return $options;
}
public function getSupportedOperators()
{
return null;
}
public function getGroup()
{
return "book";
}
} | true |
fff668612395c06665821963054fb87121f93cb3 | PHP | tatsuya-yoshikawa/bbs | /models/PostRepository.php | UTF-8 | 13,221 | 2.796875 | 3 | [] | no_license | <?php
class PostRepository
{
const MESSAGE_MAX_IMAGE_SIZE = '2MB';
protected $pdo;
public function __construct($pdo)
{
$this->pdo = $pdo;
}
public static function getColors()
{
return [
'red' => '赤',
'blue' => '青',
'yellow' => '黄',
'green' => '緑',
'black' => '黒',
];
}
/**
* 本文を調べる(部分一致)
*
* @return array
*/
public function postSearch($word)
{
$stmt = $this->pdo->prepare(implode(' ', [
"SELECT",
"*",
"FROM post",
"WHERE text",
"LIKE ?",
]));
// 実行
$stmt->bindValue(1, '%' . addcslashes($word, '\_%') . '%', PDO::PARAM_STR);
$stmt->execute();
// 投稿の取り出し
$post_results = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $post_results;
}
/**
* 検索のバリデート
*
*/
public function searchValidate($value)
{
$error = [];
// 名前のチェック
if (empty($value)) {
$error[] = '検索したい言葉(キーワード)が入力されていません。'."\n".'キーワードを入力し、再度「検索」ボタンを押してください。';
}
return $error;
}
/**
* 名前で投稿内容を検索(部分一致)
*
* @return array
*/
public function searchByName($name)
{
$stmt = $this->pdo->prepare(implode(' ', [
"SELECT",
"*",
"FROM post",
"WHERE name",
"LIKE ?",
]));
// 実行
$stmt->bindValue(1, '%' . addcslashes($name, '\_%') . '%', PDO::PARAM_STR);
$stmt->execute();
// 投稿の取り出し
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $results;
}
/**
* データベースに格納されているpostテーブルのレコードを配列で返す
*
* @return array
*/
public function find($limit = null,$offset = null)
{
if ($limit === null || $offset === null) {
$stmt = $this->pdo->prepare(implode(' ', [
'SELECT',
' * ',
'FROM post',
'ORDER BY `id` DESC',
]));
} else {
$stmt = $this->pdo->prepare(implode(' ', [
'SELECT',
' * ',
'FROM post',
'ORDER BY `id` DESC',
'LIMIT ? OFFSET ?',
]));
// //値をバインド
$stmt->bindValue(1, $limit, PDO::PARAM_INT);
$stmt->bindValue(2, $offset, PDO::PARAM_INT);
}
// 実行
$stmt->execute();
// 投稿の取り出し
$articles = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $articles;
}
/**
* 投稿の更新
*
*/
public function updatePost($values, $file)
{
$article = $this->findById($values['id']);
$article_image = ('../uploads');
// ファイルアップロード
if ($file['upfile']['error'] == UPLOAD_ERR_OK) {
$type = @exif_imagetype($file['upfile']['tmp_name']);
if ($type == IMAGETYPE_GIF) {
$extension = '.gif';
} elseif ($type == IMAGETYPE_JPEG) {
$extension = '.jpeg';
} elseif ($type == IMAGETYPE_PNG) {
$extension = '.png';
}
// 画像が存在する場合削除してからアップロード
if (!empty($article['fname'])) {
foreach (glob($article_image.'/'.$article['fname']) as $image) {
unlink($image);
}
$time = date('Ymd_His');
$sha1 = sha1_file($file['upfile']['tmp_name']);
// ファイル名の決定
$fname = sprintf('%s_%s%s', $time, $sha1, $extension);
$path = sprintf('../uploads/%s', $fname);
move_uploaded_file($file['upfile']['tmp_name'], $path);
} else { // 画像がない場合
$time = date('Ymd_His');
$sha1 = sha1_file($file['upfile']['tmp_name']);
// ファイル名の決定
$fname = sprintf('%s_%s%s', $time, $sha1, $extension);
$path = sprintf('../uploads/%s', $fname);
move_uploaded_file($file['upfile']['tmp_name'], $path);
}
} else { // UPLOAD_ERR_NO_FILE:
// 画像を削除する場合
if (!empty($values['delete'])) {
$fname = "";
unlink($article_image.'/'.$article['fname']);
// 画像を削除せずアップロードもしない場合
} else {
$fname = $article['fname'];
}
}
$stmt = $this->pdo->prepare(implode(' ', [
'UPDATE',
'post SET',
'name=?,text=?,color=?,fname=?',
'WHERE id = ?',
]));
// 更新
$stmt->execute([
$values['name'],
$values['text'],
$values['color'],
$fname,
$values['id'],
]);
}
/**
* データベースに格納されているpostテーブルのレコードをidで指定して取り出す
*
* @return string
*/
public function findById($id)
{
$stmt = $this->pdo->prepare(implode(' ', [
'SELECT',
'*',
'FROM post',
"WHERE id = ?",
]));
// 実行
$stmt->execute([$id]);
// 投稿の取り出し
$article = $stmt->fetch(PDO::FETCH_ASSOC);
return $article;
}
public function add($values,$file)
{
//アップロードファイル
if ($file['upfile']['error'] == UPLOAD_ERR_OK) {
$type = @exif_imagetype($file['upfile']['tmp_name']);
if ($type == IMAGETYPE_GIF) {
$extension = '.gif';
} elseif ($type == IMAGETYPE_JPEG) {
$extension = '.jpeg';
} elseif ($type == IMAGETYPE_PNG) {
$extension = '.png';
}
$time = date('Ymd_His');
$sha1 = sha1_file($file['upfile']['tmp_name']);
// ファイル名の決定
$fname = sprintf('%s_%s%s', $time, $sha1, $extension);
$path = sprintf('./uploads/%s', $fname);
move_uploaded_file($file['upfile']['tmp_name'], $path);
} else {
$fname = '';
}
if (!empty($values['user_id'])) {
// プリペアドステートメントを生成
$stmt = $this->pdo->prepare(implode(' ', [
'INSERT',
'INTO post(`name`,`text`,`time`,`color`,`fname`,`user_id`)',
'VALUES(?, ?, ?, ?, ?, ?)',
]));
//書き込みを実行
$stmt->execute([
$values['name'],
$values['text'],
date('Y-m-d H:i:s'),
$values['color'],
$fname,
$values['user_id'],
]);
} else {
// プリペアドステートメントを生成
$stmt = $this->pdo->prepare(implode(' ', [
'INSERT',
'INTO post(`name`,`text`,`time`,`color`,`password`,`fname`)',
'VALUES(?, ?, ?, ?, ?, ?)',
]));
//書き込みを実行
$stmt->execute([
$values['name'],
$values['text'],
date('Y-m-d H:i:s'),
$values['color'],
$values['password'],
$fname,
]);
}
}
/**
* 投稿の送信、編集時のチェック
*
* @return string
*/
public function validate($values, $file, $edit=false)
{
$error = [];
// 名前のチェック
if (empty($values['name'])) {
$error[] = '名前を入力してください';
} elseif (mb_strlen($values['name']) > 100) {
$error[] = '名前は100字以内で入力してください';
}
// テキストのチェック
if (empty($values['text'])) {
$error[] = '本文を入力してください';
} elseif (mb_strlen($values['text']) > 100) {
$error[] = '本文は100字以内で入力してください';
}
//色のチェック
if (empty($values['color'])) {
$error[] = '色の選択は必須です。';
} elseif (!array_key_exists($values['color'], self::getColors())) {
$error[] = '正しい値(色)を入力してください。';
}
// パスワードのチェック(投稿するときのみ)
if (!$edit) {
if (empty($values['user_id'])) {
if ($values['password']) {
if (mb_strlen($values['password']) > 0 && mb_strlen($values['password']) < 4) {
$error[] = 'パスワードは4文字以上で入力してください。';
} elseif (!preg_match("/^[a-zA-Z0-9]+$/", $values['password'])) { // パスワードが英数字のみか
$error[] = 'パスワードは英数字のみで入力してください。';
}
}
}
}
// ファイルアップロードチェック
if (!isset($file['upfile']['error']) || !is_int($file['upfile']['error'])) {
$error[] = 'パラメータが不正です。';
} elseif (!empty($values['delete']) && $file['upfile']['error'] === UPLOAD_ERR_OK ) {
$error[] = '画像の削除とアップロードは同時に行えません。';
} else {
switch ($file['upfile']['error']) {
case UPLOAD_ERR_INI_SIZE: // php.ini定義の最大サイズ超過
case UPLOAD_ERR_FORM_SIZE: // フォーム定義の最大サイズ超過 (設定した場合のみ)
$error[] = 'サイズオーバーです。' . self::MESSAGE_MAX_IMAGE_SIZE . 'まででお願いします。';
break;
case UPLOAD_ERR_NO_FILE: // ファイル未選択
break;
case UPLOAD_ERR_OK:
// $_FILSES['upfile']['mime']の値はブラウザ側で偽装可能なので、MIMEタイプを自前でチェックする
$type = @exif_imagetype($file['upfile']['tmp_name']);
if (!in_array($type, [IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG], true)) {
$error[] = '画像形式が未対応です。';
} else {
//TODO filesize check
$filesize = filesize($file['upfile']['tmp_name']);
if ($filesize > convertToByte(self::MESSAGE_MAX_IMAGE_SIZE)) {
$error[] = 'サイズオーバーです。' . self::MESSAGE_MAX_IMAGE_SIZE . 'まででお願いします。。。';
}
}
}
}
return $error;
}
/**
* 削除できない場合はエラーメッセージを配列で返す
* @return string
*/
public function validateDelete($id, $password)
{
$error = [];
$article = $this->findById($id);
if(!empty($password)) {
if (!($password == $article['password'])) {
$error[] = 'パスワードが違います。';
}
} else {
$error[] = 'パスワードを入力してください。';
}
return $error;
}
public function delete($id, $admin=false)
{
//画像の削除
$article = $this->findById($id);
if ($admin) {
if (!empty($article['fname'])) {
if (!unlink("../uploads/".$article['fname'])) {
throw new Exception('画像の削除に失敗しました (' . $article['fname'] . ')');
}
}
} else {
if (!empty($article['fname'])) {
if (!unlink("uploads/".$article['fname'])) {
throw new Exception('画像の削除に失敗しました (' . $article['fname'] . ')');
}
}
}
//削除
$stmt = $this->pdo->prepare(implode(' ', [
'DELETE',
'FROM post',
'WHERE id = ?',
]));
// 実行
$stmt->execute([$id]);
}
} | true |
32fc0c6b444ad59e998f42bb355ffecfd7b13dbf | PHP | PosUpIoT/LonguinusApp | /application/models/User_model.php | UTF-8 | 706 | 2.671875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
class User_model extends CI_Model {
public function __construct() {
parent::__construct();
}
public function get_users() {
$query = $this->db->query('SELECT * FROM users');
$users = $query->result_array();
return $users;
}
public function insert_user($data) {
$this->db->insert('users', $data);
}
public function login($email, $password) {
$data = array('email' => $email, 'password' => md5($password));
$query = $this->db->get_where('users', $data);
if($query->num_rows() > 0){
return TRUE;
}
return FALSE;
}
}
/* End of file User_model.php */
/* Location: ./application/models/User_model.php */ | true |
05e8d8bf932730bb657c8dd1a66b47eb76d9e4e3 | PHP | tzyluen/cms | /cms.server/crimes/Convict.inc | UTF-8 | 472 | 3.15625 | 3 | [] | no_license | <?php
class Convict {
private $id;
private $fname;
private $middle;
private $lname;
private $age;
private $address;
public function __construct($id, $fname, $middle, $lname, $age, $address) {
$this->id = $id;
$this->fname = $fname;
$this->middle = $middle;
$this->lname = $lname;
$this->age = $age;
$this->address= $address;
}
public function get($attr) {
return $this->$attr;
}
public function __toString() {
}
}
?>
| true |
b8bcb61155c0fc7bff2363d1b68aa0d69d23914d | PHP | whangdr3/uct | /uct/view.php | UTF-8 | 1,653 | 2.703125 | 3 | [] | no_license | <html>
<head>
<title>Edit Data</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
</head>
<body>
<div class="container pt-5">
<?php
include("config.php");
if($_SERVER["REQUEST_METHOD"] == "GET"){
$id = $_GET['id'];
$sql = "SELECT * FROM employee WHERE id = $id";
$stmt = sqlsrv_query( $conn, $sql);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
if( sqlsrv_fetch( $stmt ) === false) {
die( print_r( sqlsrv_errors(), true));
}
$fullname = sqlsrv_get_field( $stmt, 1);
$email = sqlsrv_get_field( $stmt, 2);
$post = sqlsrv_get_field( $stmt, 3);
}
?>
<h1 class="pb-5">View Post</h1>
<table class="table table-bordered">
<form action=<?php echo $_SERVER['PHP_SELF']; ?> method="POST">
<div class="form-group">
<label class="font-weight-bold">ID :</label>
<span class="font-weight-bold" style="font-size: 1em;"><?= $id; ?></span>
</div>
<div class="form-group">
<label class="font-weight-bold">Full Name :</label>
<span class="font-weight-bold" style="font-size: 1em;"><?= $fullname; ?></span>
</div>
<div class="form-group">
<label class="font-weight-bold">Email :</label>
<span class="font-weight-bold" style="font-size: 1em;"><?= $email; ?></span>
</div>
<div class="form-group">
<label class="font-weight-bold">Post :</label>
<span class="font-weight-bold" style="font-size: 1em;"><?= $post; ?></span>
</div>
</form>
</table>
</div>
</body>
</html>
| true |
0e8d26e3ba37aee9f42c9ce614f36c97529e1c74 | PHP | Wisembly/sfBalloon | /apps/frontend/lib/form/SimpleUserForm.class.php | UTF-8 | 766 | 2.65625 | 3 | [] | no_license | <?php
class SimpleUserForm extends sfGuardUserForm
{
public function configure()
{
parent::configure();
$this->useFields(array('first_name', 'last_name', 'email_address', 'password'));
$this->setWidget('password', new sfWidgetFormInputPassword(array(), array('autocomplete' => 'off')));
$this->setValidator('password', new sfValidatorString(array('required' => false)));
$this->widgetSchema->setHelp('password', 'Laissez vide si vous ne voulez pas changer de mot de passe');
$this->widgetSchema->setNameFormat('user[%s]');
}
public function updatePasswordColumn($value)
{
if(!empty($value)){
$value = md5($value);
}else{
$value = $this->getObject()->getPassword();
}
return $value;
}
} | true |
2d4657024f6e57db6f6b44bfdb14f2c8fe56ddca | PHP | roddy60/roddy60.github.io | /projects/a7.build-a-javascript-calculator/index.php | UTF-8 | 1,890 | 2.84375 | 3 | [] | no_license | <?php
/*
This program is used during development, as a wrapper for index.xhtml.
Its purpose is to defeat the browser's caching of certain CSS and
JavaScript files.
*/
const NO_CACHE_BUST_CLASS = 'no-cache-bust';
const XHTML_FILE = __DIR__ . '/index.xhtml';
libxml_use_internal_errors(TRUE);
$doc = new DomDocument;
if (!$doc->load(XHTML_FILE)) {
header('Content-Type: text/plain;charset=UTF-8');
echo 'Fatal error: ill-formed XML in file ', basename($XHTML_file), "\n";
} else {
change_URLs($doc, 'link', 'href');
change_URLs($doc, 'script', 'src');
header('Content-Type: application/xhtml+xml');
echo $doc->saveXml();
}
function cache_busting_disallowed(DomElement $element) {
for ($e = $element; $e instanceof DomElement; $e = $e->parentNode) {
if (element_disallows_cache_busting($e)) {
return TRUE;
}
}
return FALSE;
}
function change_URLs(DomDocument $doc, $element_name, $attribute_name) {
static $time;
if ($time === NULL) {
$time = sprintf('%.16f', microtime(TRUE));
}
foreach ($doc->getElementsByTagName($element_name) as $elem) {
if (eligible($elem, $attribute_name)) {
$attrib_val = $elem->getAttribute($attribute_name);
$separator_char = is_integer(strpos($attrib_val, '?'))? '&': '?';
$new_attrib_val = $attrib_val . $separator_char . $time;
$elem->setAttribute($attribute_name, $new_attrib_val);
}
}
}
function element_disallows_cache_busting(DomElement $element) {
$regex = '@(\A|\s)' . preg_quote(NO_CACHE_BUST_CLASS) . '(\s|\z)@';
return
$element->hasAttribute('class') &&
preg_match(
$regex,
$element->getAttribute('class')
) === 1;
}
function eligible(DomElement $element, $attribute_name) {
return
$element->hasAttribute($attribute_name) &&
$element->getAttribute($attribute_name) !== '' &&
!cache_busting_disallowed($element);
}
| true |
fae96b93626e241b338861058d730f48eed87892 | PHP | Ditmar/school | /application/libraries/captcha.php | UTF-8 | 2,041 | 2.71875 | 3 | [] | no_license | <?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/*
* this class is created by: mohammad tareq alam
* email: tareq.mist@gmail.com
* web:commitmentsoft.com
* blog: tareqalam.wordpress.com
*/
class Captcha {
var $CI = null;
function Captcha()
{
$this->CI =& get_instance();
$this->CI->load->library('session');
}
function captchaImg()
{
$RandomStr = md5(microtime());// md5 to generate the random string
$ResultStr = substr($RandomStr,0,5);//trim 5 digit
$NewImage =imagecreatefromjpeg(APPPATH."themes/img.jpg");//image create by existing image and as back ground
$LineColor = imagecolorallocate($NewImage,233,239,239);//line color
$TextColor = imagecolorallocate($NewImage, 255, 255, 255);//text color-white
imageline($NewImage,1,1,40,40,$LineColor);//create line 1 on image
imageline($NewImage,1,100,60,0,$LineColor);//create line 2 on image
imagestring($NewImage, 5, 20, 10, $ResultStr, $TextColor);// Draw a random string horizontally
$newdata = array(
'captchaKey' =>$ResultStr
);
$this->CI->session->set_userdata($newdata);
//$_SESSION['key'] = $ResultStr;// carry the data through session
header("Content-type: image/jpeg");// out out the image
imagejpeg($NewImage);//Output image to browser
}
function captchaText()
{
$RandomStr = md5(microtime());// md5 to generate the random string
$ResultStr = substr($RandomStr,0,5);//trim 5 digit
$newdata = array(
'captchaKey' =>$ResultStr
);
$this->CI->session->set_userdata($newdata);
return $ResultStr;
}
function validateCaptcha()
{
//$key=substr($_SESSION['key'],0,5);
$key = $this->CI->session->userdata('captchaKey');
$number = $_REQUEST['number'];
if($number!=$key){
$msg = '<center><font face="Verdana, Arial, Helvetica, sans-serif" color="#FF0000">
String not valid! Please try again!</font></center>';
return $msg;
}
else{ return 'success';}
}
} | true |
89f7acfb994fa7a9cbe85fd01d29646fa1a2624c | PHP | inabahtrg/KalturaServerCore | /api_v3/lib/types/KalturaWidget.php | UTF-8 | 2,442 | 2.609375 | 3 | [] | no_license | <?php
/**
* @package api
* @subpackage objects
*/
class KalturaWidget extends KalturaObject implements IFilterable
{
/**
* @var string
* @readonly
* @filter eq,in
*/
public $id;
/**
* @var string
* @filter eq
*/
public $sourceWidgetId;
/**
* @var string
* @readonly
* @filter eq
*/
public $rootWidgetId;
/**
* @var int
* @readonly
* @filter eq
*/
public $partnerId;
/**
* @var string
* @filter eq
*/
public $entryId;
/**
* @var int
* @filter eq
*/
public $uiConfId;
/**
* @var string
*/
private $customData;
/**
* @var KalturaWidgetSecurityType
*/
public $securityType;
/**
* @var int
*/
public $securityPolicy;
/**
* @var int
* @readonly
* @filter gte,lte,order
*/
public $createdAt;
/**
* @var int
* @readonly
* @filter gte,lte
*/
public $updatedAt;
/**
* Can be used to store various partner related data as a string
* @var string
* @filter like
*/
public $partnerData;
/**
* @var string
* @readonly
*/
public $widgetHTML;
/**
*
* Should enforce entitlement on feed entries
* @var bool
*/
public $enforceEntitlement;
/**
* Set privacy context for search entries that assiged to private and public categories within a category privacy context.
*
* @var string
* $filter eq
*/
public $privacyContext;
/**
*
* Addes the HTML5 script line to the widget's embed code
* @var bool
*/
public $addEmbedHtml5Support = false;
private static $map_between_objects = array
(
"id" , "sourceWidgetId" , "rootWidgetId" , "partnerId" , "entryId" , "uiConfId" , "widgetHTML" ,
"securityType" , "securityPolicy" , "createdAt" , "updatedAt" , "partnerData", "enforceEntitlement", "privacyContext", "addEmbedHtml5Support",
);
public function getMapBetweenObjects ( )
{
return array_merge ( parent::getMapBetweenObjects() , self::$map_between_objects );
}
public function fromWidget ( widget $entry )
{
parent::fromObject( $entry );
}
public function toWidget ()
{
$user = new widget();
$skip_props = array ( "widgetHTML" );
return parent::toObject( $user , $skip_props );
}
public function getExtraFilters()
{
return array();
}
public function getFilterDocs()
{
return array();
}
}
?> | true |
24248c4943e6c10616d143bf9606eb83dcd347f1 | PHP | voter101/renting-berlin | /src/phalcon-cli/models/Commands/MonitorCommand.php | UTF-8 | 2,007 | 2.796875 | 3 | [] | no_license | <?php
/**
* This file is part of the PHP Telegram Bot example-bot package.
* https://github.com/php-telegram-bot/example-bot/
*
* (c) PHP Telegram Bot Team
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* User "/echo" command
*
* Simply echo the input back to the user.
*/
namespace Longman\TelegramBot\Commands\UserCommands;
use Carbon\Carbon;
use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Entities\ServerResponse;
use Longman\TelegramBot\Exception\TelegramException;
class MonitorCommand extends UserCommand
{
/**
* @var string
*/
protected $name = 'monitor';
/**
* @var string
*/
protected $description = 'Your monitoring status';
/**
* @var string
*/
protected $usage = '/monitor';
/**
* @var string
*/
protected $version = '1.0.0';
/**
* Main command execution
*
* @return ServerResponse
* @throws TelegramException
*/
public function execute(): ServerResponse
{
$message = $this->getMessage();
$from = $message->getFrom();
$user_id = $from->getId();
$text = $message->getText(true);
$redis = new \Redis;
list($host,$port) = explode(':', getenv('REDIS_ADDRESS'));
$redis->pconnect($host, $port);
$url = $redis->get('rb.' . $user_id);
if (!$url) {
return $this->replyToChat('You have no current monitor. To set a monitor, write a search URL in this chat.' . PHP_EOL . 'Type /start for more info.');
} else {
$data = json_decode($url);
$lastCheck = Carbon::createFromTimeStamp($data->ts)->diffForHumans();
return $this->replyToChat('You are currently monitoring: ' . PHP_EOL . $data->url . PHP_EOL . PHP_EOL . 'Last publisehd AD: ' . $data->last. PHP_EOL . PHP_EOL . 'Last checked: ' . $lastCheck);
}
}
}
| true |
d53a77cec7493275ee6e2a196971efa8a71ed569 | PHP | fernetass/php | /gordo/enviar1.php | UTF-8 | 852 | 2.5625 | 3 | [] | no_license | <?php
session_start();
require_once 'funciones/validaciones.php';
$nombre=$_POST['nombre'];
$apellido=$_POST['apellido'];
$edad=$_POST['edad'];
$_SESSION['imp']=$_POST;
$errores=array();
if (!ctype_alpha($nombre) || (strlen($nombre)>10)|| $nombre=="")
{
$errores[]=true;
$_SESSION['error1']="el nombre debe ser solo caracteres y tener longitud max 10";
}
if (!ctype_alpha($apellido) || (strlen($apellido)>10) || $apellido=="")
{
$errores[]=true;
$_SESSION['error2']="el apellido debe ser solo caracteres y tener longitud max 10";
}
if(!is_numeric($edad) || $edad=="")
{
$errores[]=true;
$_SESSION['error3']="la edad debe ser numerica";
}
if(count($errores)>0)
{
header('location:registro1.php');
}
else
{
$_SESSION['exito']="El registro se ha logrado con éxito";
header('location:registro1.php');
}
?>
| true |
cb6a6b8bdfaa0bc55d821602d79a60e784f351f3 | PHP | alexyves/SiberianCMS | /lib/Siberian/Design.php | UTF-8 | 5,219 | 2.75 | 3 | [] | no_license | <?php
/**
* Class Siberian_Design
*
* @version 4.1.0
*
* Adding inheritance system in the design folders
*
*/
class Siberian_Design
{
public static $design_cache = array();
public static $design_codes = array();
public static $editions = array(
"sae" => array("sae", "local"),
"mae" => array("sae", "mae", "local"),
"pe" => array("sae", "mae", "pe", "local"),
"demo" => array("sae", "mae", "pe", "demo", "local"),
);
/** Various "Edition" Path's */
const LOCAL_PATH = "app/local/design/";
const SAE_PATH = "app/sae/design/";
const MAE_PATH = "app/mae/design/";
const PE_PATH = "app/pe/design/";
const DEMO_PATH = "app/demo/design/";
const CACHE_PATH = "var/cache/design.cache";
const CACHING = true;
public static function init() {
$basePathCache = Core_Model_Directory::getBasePathTo(self::CACHE_PATH);
/** Never cache in development */
if(self::CACHING && is_readable($basePathCache)) {
$cached = json_decode(file_get_contents($basePathCache), true);
if(!empty($cached)) {
self::$design_cache = $cached;
}
} else {
/** Registering depending on type */
switch(Siberian_Version::TYPE) {
default: case 'SAE':
self::registerDesignType(self::SAE_PATH);
break;
case 'MAE':
self::registerDesignType(self::SAE_PATH);
self::registerDesignType(self::MAE_PATH);
break;
case 'PE':
self::registerDesignType(self::SAE_PATH);
self::registerDesignType(self::MAE_PATH);
self::registerDesignType(self::PE_PATH);
break;
}
/** DEMO is a special case, it's a PE with additional modules */
//if(Siberian_Version::isDemo()) {
// self::registerDesignType(self::DEMO_PATH);
//}
/** Local always on top of everything (user defined) */
self::registerDesignType(self::LOCAL_PATH);
if(self::CACHING) {
file_put_contents($basePathCache, json_encode(self::$design_cache));
}
}
}
/** @system */
public static function clearCache() {
unlink(Core_Model_Directory::getBasePathTo(self::CACHE_PATH));
}
public static function registerDesignType($version)
{
$design_codes = glob("$version*", GLOB_ONLYDIR);
foreach ($design_codes as $design_code) {
/** Init the array if not. */
$base_code = basename($design_code);
if (!isset(self::$design_cache[$base_code])) {
self::$design_cache[$base_code] = array();
}
/** Looping trough files */
self::recursiveSearch($design_code, $base_code);
}
}
protected static function recursiveSearch($folder, $base_code) {
$links = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($folder, 4096),
RecursiveIteratorIterator::SELF_FIRST
);
foreach($links as $link) {
if(!$link->isDir()) {
$path = $link->getPathname();
$named_path = str_replace("$folder/", "", $path);
self::$design_cache[$base_code][$named_path] = $path;
}
}
}
public static function getPath($base_file, $type = null, $design_code = null, $key = false) {
$type = is_null($type) ? APPLICATION_TYPE : $type;
$design_code = is_null($design_code) ? DESIGN_CODE : $design_code;
/** Key contain only single slashes, removing duplicates helps to find the right ones. */
if($type == 'email') {
$base_file = preg_replace("#/+#", "/", sprintf("%s", $base_file));
} else {
$base_file = preg_replace("#/+#", "/", sprintf("%s/%s", $design_code, $base_file));
}
if(isset(self::$design_cache[$type]) && isset(self::$design_cache[$type][$base_file])) {
return "/".self::$design_cache[$type][$base_file];
}
return false;
}
public static function searchForFolder($folder, $type = null, $design_code = null) {
$found_files = array();
$type = is_null($type) ? APPLICATION_TYPE : $type;
$design_code = is_null($design_code) ? DESIGN_CODE : $design_code;
$files = self::getType($type);
$base_folder = preg_replace("#/+#", "/", sprintf("%s/%s", $design_code, $folder));
foreach($files as $key => $value) {
if(strpos($key, $base_folder) === 0) {
$found_files[$key] = $value;
}
}
return $found_files;
}
public static function getType($type) {
if(isset(self::$design_cache[$type])) {
return self::$design_cache[$type];
}
return false;
}
public static function getBasePath($base_file, $type = null, $design_code = null) {
return Core_Model_Directory::getBasePathTo(self::getPath($base_file, $type, $design_code));
}
}
| true |
81bb6dd020ebaefadda6ae34642c20271ba9367a | PHP | ranjan1703/HPEassignmentcode | /even.php | UTF-8 | 695 | 3.796875 | 4 | [] | no_license | <html>
<body>
<h3> To check given number is Odd or Even PHP</h3>
<form action="" method="post">
<label>Enter a number</label><input type="text" name="number" />
<input type="submit" />
</form>
</body>
</html>
<?php
if($_POST){
$number = $_POST['number'];
//check if the enter value is a number or throw an error
if (!(is_numeric($number) && is_int(0+$number))){
echo "<p style='color:red;'>Error: Please enter an Integer</p>";
die();
}
//divide the entered number by 2
//if the reminder is 0 then the number is even otherwise the number is odd
if(($number % 2) == 0){
echo "You entered an Even number";
}else{
echo "You entered an Odd number";
}
}
?>
| true |
b648dd3d410f7eae25cbade081ac4ead7fe119de | PHP | A-1198/building-database-applications-in-php-Coursera | /week5/crud/delete.php | UTF-8 | 1,355 | 2.921875 | 3 | [] | no_license | <?php
require_once "pdo.php";
session_start();
if (isset($_POST['delete']) && isset($_POST['user_id'])) {
$sql = "DELETE FROM users WHERE user_id = :id";
$statement = $pdo->prepare($sql);
$statement->execute(array(
":id" => $_POST["user_id"]
));
$_SESSION['success'] = "Record deleted";
header("Location: index.php");
return;
}
$statement = $pdo->prepare("SELECT name, user_id FROM users WHERE user_id = :id");
$statement->execute(array(":id" => $_GET['user_id']));
$row = $statement->fetch(PDO::FETCH_ASSOC);
while($row === false) {
$_SESSION['error'] = "Bad value for user id";
header("Location: index.php");
return;
}
?>
<!DOCTYPE html>
<html>
<head>
<?php include "header_content.php" ?>
</head>
<body>
<div class="container">
<p class="text-danger">Confirm: Deleting
<b><?php echo htmlentities($row['name']); ?></b>
</p>
<form method="POST">
<input type="hidden" name="user_id" value="<?php echo $row['user_id']; ?>" />
<input type="hidden" name="delete" value="delete" />
<button type="submit" class="btn btn-primary">Delete User</button>
<a href="index.php">Cancel </a>
</form>
</div>
</body>
</html> | true |
130bbb5e2c8bafeb91001d589b90939dbc1f0ec2 | PHP | sahibalejandro/dev-releases-bot | /app/Conversations/AddRepositoryConversation.php | UTF-8 | 2,514 | 2.546875 | 3 | [] | no_license | <?php
namespace App\Conversations;
use App\Repository;
use App\RepositoryTags;
use Mpociot\BotMan\Answer;
use Mpociot\BotMan\Conversation;
use App\Jobs\ReleaseNotification;
use App\Exceptions\RepositoryNotFound;
class AddRepositoryConversation extends Conversation
{
protected $additionalParameters = [
'parse_mode' => 'markdown',
'disable_notification' => true,
];
public function run()
{
$this->askRepositoryUrl();
}
public function askRepositoryUrl($question = null)
{
if (is_null($question)) {
$question = 'Please type the repository name, for example: *vendor/package*';
}
$this->ask($question, function (Answer $answer) {
// Get the CHAT ID to support group chats.
$chatId = $this->bot->getMessage()->getChannel();
$repositoryName = $answer->getText();
if (! Repository::isValidName($repositoryName)) {
$this->askRepositoryUrl('Invalid repository name, try again.');
return;
}
try {
$tags = new RepositoryTags($repositoryName);
} catch (RepositoryNotFound $e) {
$this->say("The repository *{$repositoryName}* does not exists.", $this->additionalParameters);
return;
}
$repository = Repository::byName($repositoryName);
$lastTagName = $tags->empty() ? null : $tags->latest()->name;
if ($repository) {
$repository->last_tag_name = $lastTagName;
$repository->save();
} else {
$repository = Repository::create([
'name' => $repositoryName,
'last_tag_name' => $lastTagName,
]);
}
if (! $repository->isWatchedBy($chatId)) {
$repository->subscribe($chatId);
$this->say("I'll keep you posted when *{$repositoryName}* is tagged.", $this->additionalParameters);
} else {
$this->say("You are already watching repository *{$repositoryName}*.", $this->additionalParameters);
}
if ($tags->empty()) {
$this->say("No tags published for *{$repositoryName}* until now.", $this->additionalParameters);
} else {
dispatch(new ReleaseNotification($repository, $tags->latest(), $chatId));
}
}, $this->additionalParameters);
}
} | true |
0c6732348f3d29192000e1b85496e0625872a1e2 | PHP | JulietaAtanasova/php-mvc | /Models/Picture.php | UTF-8 | 3,076 | 2.984375 | 3 | [] | no_license | <?php
namespace PhotoAlbum\Models;
use PhotoAlbum\Repositories\PictureRepository;
class Picture
{
/**
* @var int
*/
private $id;
/**
* @var string
*/
private $name;
/**
* @var string
*/
private $url;
/**
* @var string
*/
private $description;
/**
* @var \DateTime
*/
private $createdOn;
/**
* @var Album
*/
private $album;
/**
* @var PictureComment[]
*/
private $comments = [];
/**
* @var PictureVote[];
*/
private $votes = [];
function __construct($name, $url, $album, $description, $createdOn = null, $id = null)
{
$this->setAlbum($album);
$this->setDescription($description);
$this->setId($id);
$this->setName($name);
$this->setUrl($url);
$this->setCreatedOn($createdOn);
}
/**
* @param \PhotoAlbum\Models\Album $album
*/
public function setAlbum($album)
{
$this->album = $album;
}
/**
* @return \PhotoAlbum\Models\Album
*/
public function getAlbum()
{
return $this->album;
}
/**
* @param $createdOn
*/
public function setCreatedOn($createdOn)
{
$this->createdOn = date_create($createdOn);
}
/**
* @param \PhotoAlbum\Models\PictureComment[] $comments
*/
public function setComments($comments)
{
$this->comments = $comments;
}
/**
* @return \PhotoAlbum\Models\PictureComment[]
*/
public function getComments()
{
return $this->comments;
}
/**
* @param \PhotoAlbum\Models\PictureVote[] $votes
*/
public function setVotes($votes)
{
$this->votes = $votes;
}
/**
* @return \PhotoAlbum\Models\PictureVote[]
*/
public function getVotes()
{
return $this->votes;
}
/**
* @return \DateTime
*/
public function getCreatedOn()
{
return $this->createdOn;
}
/**
* @param string $description
*/
public function setDescription($description)
{
$this->description = $description;
}
/**
* @return string
*/
public function getDescription()
{
return $this->description;
}
/**
* @param int $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* @param string $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @param string $url
*/
public function setUrl($url)
{
$this->url = $url;
}
/**
* @return string
*/
public function getUrl()
{
return $this->url;
}
public function save()
{
return PictureRepository::create()->save($this);
}
} | true |
507e4f6d9f317604fa24aaf95b0522db7cc6ab55 | PHP | rizkyL/ca-sdk | /src/models/Representation.php | UTF-8 | 1,273 | 3.046875 | 3 | [] | no_license | <?php
class Representation {
private $primaryKey;
private $primary;
private $originalFilename;
private $versions = array();
private $annotations = array();
private $mimeType;
public function __construct($options = array()) {
$this->primaryKey = $options['representation_id'];
$this->originalFilename = $options['original_filename'];
$this->primary = $options['is_primary'];
$this->mimeType = $options['mime_type'];
}
public function getPrimaryKey() {
return $this->primaryKey;
}
public function isPrimary(){
return $this->primary;
}
public function getMimeType() {
return $this->mimeType;
}
public function addVersion($name, $url, $info) {
$this->versions[$name] = new RepresentationVersion($url, $info);
}
public function getVersion($name) {
return $this->versions[$name];
}
public function getOriginalFileName() {
return $this->originalFilename;
}
public function addAnnotation($id, $info) {
$this->annotations[$id] = $info;
}
public function getAnnotation($id) {
return $this->annotations[$id];
}
public function getAnnotations() {
return $this->annotations;
}
}
?>
| true |
2f1f3d748c13aa9bd9ba137b454f850bdb9c4f9d | PHP | lukasbachlechner/halla-store | /app/Controllers/ProductController.php | UTF-8 | 4,324 | 2.65625 | 3 | [] | no_license | <?php
namespace App\Controllers;
use App\Models\Product;
use Core\Config;
use Core\Router;
use Core\Session;
use Core\Validator;
use Core\View;
/**
* Class ProductController
* @package App\Controllers
*/
class ProductController
{
private ImageController $imageController;
public function __construct()
{
$this->imageController = new ImageController();
}
/**
* @param string $slug
*/
public function show(string $slug)
{
$product = Product::findBySlug($slug);
View::render('product-single', [
'product' => $product
]);
}
public function showAll()
{
$products = Product::all();
View::render('admin/products', [
'products' => $products
], 'admin');
}
public function createForm()
{
View::render('admin/product-create', [], 'admin');
}
/**
* @param int $id
*/
public function updateForm(int $id)
{
$product = Product::find($id);
View::render('admin/product-update', [
'product' => $product
], 'admin');
}
public function doCreate()
{
$errors = $this->validateAndGetErrors();
if (!empty($errors)) {
Session::set('errors', $errors);
Router::redirectTo("admin/produkte/add");
}
$product = new Product();
$product->name = $_POST['name'];
$product->description = $_POST['description'];
$product->price = $_POST['price'];
$product->quantity_available = $_POST['quantityAvailable'];
$product->quantity_sold = $_POST['quantitySold'];
$product->is_active = $_POST['isActive'];
$product->tax_rate = $_POST['taxRate'];
if ($product->save()) {
if ($this->imageController->uploadImages($product->id)) {
Session::set('success', ['Das Produkt wurde erfolgreich gespeichert.']);
Router::redirectTo("admin/produkte/edit/{$product->id}");
}
}
}
/**
* @param int $id
*/
public function doUpdate(int $id)
{
$errors = $this->validateAndGetErrors();
if (!empty($errors)) {
Session::set("errors", $errors);
Router::redirectTo('admin/produkte/add');
}
$product = Product::find($id);
$product->name = $_POST['name'];
$product->description = $_POST['description'];
$product->price = $_POST['price'];
$product->quantity_available = $_POST['quantityAvailable'];
$product->quantity_sold = $_POST['quantitySold'];
$product->is_active = $_POST['isActive'];
$product->tax_rate = $_POST['taxRate'];
if ($product->save()) {
if ($this->imageController->updateAndUploadImages($product->id)) {
Session::set('success', ['Das Produkt wurde erfolgreich gespeichert.']);
Router::redirectTo("admin/produkte/edit/{$product->id}");
}
}
}
/**
* @param int $productId
*/
public function doDelete(int $productId) {
// delete images
$product = Product::find($productId);
$imagesToDelete = '';
foreach ($product->getImages() as $image) {
$imagesToDelete .= $image->id . ';';
}
$product->disconnectAndDeleteImages($imagesToDelete);
// delete products
$product->delete();
Session::set('success', ['Das Produkt wurde erfolgreich gelöscht.']);
Router::redirectTo("admin/produkte");
}
private function validateAndGetErrors(): array
{
$validator = new Validator();
$validator->validate($_POST['name'], 'Produktname', true, 'textnum');
$validator->validate($_POST['description'], 'Produktbeschreibung', true, 'textnum');
$validator->validate($_POST['price'], 'Preis', true, 'float');
$validator->validate($_POST['quantityAvailable'], 'Verfügbare Einheiten', false, 'int');
$validator->validate($_POST['quantitySold'], 'Verkaufte Einheiten', false, 'int');
$validator->validate($_POST['isActive'], 'Sichtbarkeit', false, 'int');
$validator->validate($_POST['taxRate'], 'Steuersatz', false, 'int');
return $validator->getErrors();
}
} | true |
daaf73a1bc9abe2e41bd72706fb9c1643824d3e2 | PHP | red-robots/brackett-flagship | /index.php | UTF-8 | 5,328 | 2.515625 | 3 | [] | no_license | <?php
/**
* The main template file
*
*
*/
get_header(); ?>
<?php
// Query the Post type Slides
$querySlides = array(
'post_type' => 'slides',
'posts_per_page' => '-1',
'orderby' => 'menu_order',
'order' => 'ASC'
);
// The Query
$the_query = new WP_Query( $querySlides );
?>
<?php
// The Loop
if ( $the_query->have_posts() ) : ?>
<div class="flexslider">
<ul class="slides">
<?php while ( $the_query->have_posts() ) : ?>
<?php $the_query->the_post();
$image = get_field( 'slide' );
$url = $image['url'];
$title = $image['title'];
$alt = $image['alt'];
$caption = $image['caption'];
$size = 'slide';
$thumb = $image['sizes'][ $size ];
$width = $image['sizes'][ $size . '-width' ];
$height = $image['sizes'][ $size . '-height' ];
?>
<li>
<img
src="<?php echo $thumb; ?>"
alt="<?php echo $alt; ?>"
title="<?php echo $title; ?>"
width="<?php echo $width; ?>"
height="<?php echo $height; ?>"/>
</li>
<?php endwhile; ?>
</ul><!-- slides -->
</div><!-- .flexslider -->
<?php endif; // end loop ?>
<?php wp_reset_postdata(); ?>
<?php
/* FEATURED VIDEO */
$featVideoLink = get_field("featured_video_url",505);
if($featVideoLink) {
$parts = parse_url($featVideoLink);
if(isset($parts['query']) && $parts['query']) {
$query = $parts['query'];
$params = array_filter(explode("v=",$query));
$vidPlaceholder = get_stylesheet_directory_uri() . "/images/rectangle.png";
if($params) { $videoId = end($params); ?>
<div class="home-featured-video">
<div class="wrap">
<img src="<?php echo $vidPlaceholder ?>" alt="" aria-hidden="true" class="placeholder">
<iframe width="1050" height="637" src="https://www.youtube.com/embed/<?php echo $videoId; ?>?feature=oembed&loop=0&rel=0&modestbranding=0&controls=1" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen style="display:block;margin:0 auto;"></iframe>
</div>
</div>
<?php }
}
}
?>
<div class="main-home-content">
<div class="wrapper">
<div class="home-latest-news">
<h2>Latest News</h2>
<?php
$wp_query = new WP_Query();
$wp_query->query( array(
'post_type' => 'post',
'posts_per_page' => 3
) );
if ( $wp_query->have_posts() ) : ?>
<div class="home-latest-news-wrapper">
<?php while ( $wp_query->have_posts() ) : $wp_query->the_post(); ?>
<div class="news-item">
<a href="<?php the_permalink(); ?>">
<div class="date"><?php echo get_the_date( 'm.d.y' ); ?></div>
<?php the_excerpt( ); ?>
</a>
</div><!-- news item -->
<?php endwhile;?>
</div><!--.home-latest-news-wrapper-->
<?php endif; ?>
</div><!-- home latest news-->
<?php
// pull homepage
$post = get_post( 505 );
setup_postdata( $post );
$title = get_field( 'title' );
//$content = get_the_content();
$link = get_field( 'page_link' );
?>
<div class="home-summary clear-bottom">
<div class="home-summary-wrapper">
<h2><?php echo $title; ?></h2>
<div class="home-summary-content"><?php the_content(); ?></div><!-- home summary content -->
</div><!--.home-summary-wrapper-->
<?php if ( $link != '' ) { ?>
<div class="seemore"><a href="<?php echo $link; ?>">Meet Our Team</a></div><!-- seemore -->
<?php } ?>
</div><!-- home summary -->
<?php wp_reset_postdata();
wp_reset_query(); ?>
</div><!-- wrapper -->
</div><!-- main-home-content -->
<?php
// Let's get in homepage mode.
$post = get_post( 505 ); // My home "page" id = 505
setup_postdata( $post );
/*
Reverse Query on the Post Object Field
*/
$testimonials = get_posts( array(
'post_type' => 'testimonial',
'meta_query' => array(
array(
'key' => 'pages_to_show_testimonial', // name of custom field
'value' => '"' . get_the_ID() . '"', // matches exaclty "123",
'compare' => 'LIKE'
)
)
) );
// now get out of homepage mode now that we have our testimonials.
wp_reset_postdata();
if ( $testimonials ): ?>
<section class="the-testis">
<div class="wrapper">
<div class="testimonial testimonial-home">
<ul class="slides">
<?php foreach ( $testimonials as $testimonial ):
// get those id's for the fields
$ID = $testimonial->ID;
$job_title = get_field( 'job_title', $ID );
$company = get_field( 'company', $ID );
$testimonial = get_field( 'testimonial', $ID );
$title = get_the_title( $ID );
?>
<li>
<div class="the-testimonial"><?php echo $testimonial; ?></div>
<div class="testi-creds">
<div class="the-testimonial-name"><?php echo $title; ?></div>
<?php if ( $job_title != '' ) {
echo '<div class="the-testimonial-jt">, ' . $job_title . '</div>';
} ?>
<?php if ( $company != '' ) {
echo '<div class="the-testimonial-company">, ' . $company . '</div>';
} ?>
</div><!-- creds -->
</li>
<?php endforeach; ?>
</ul><!-- slides -->
</div><!-- .testimonial -->
</div><!-- wrapper -->
</section>
<?php endif;
wp_reset_postdata(); ?>
<?php get_footer(); ?> | true |
5b93b97813c91ff5f306ca37001f59b7bbd274e5 | PHP | strifejeyz/framework | /kernel/Route.php | UTF-8 | 1,282 | 3.234375 | 3 | [
"MIT"
] | permissive | <?php
use Kernel\Engine;
/**
* Class Route
*/
abstract class Route extends Engine
{
/**
* This method will get the route url
* get('route.name -> /foo/bar')
* Route::get('route.name.here')
* output: /foo/bar
*
* @param $route
* @return mixed
*/
public static function get($route)
{
$path = preg_replace('/\:(.*)/', '', self::$routes[$route]['url']);
$args = func_get_args();
if (count($args) > 1):
unset($args[0]);
foreach ($args as $arg):
$path .= $arg . "/";
endforeach;
$path = rtrim($path, '/');
endif;
return ($path);
}
/**
* Redirect to a specific route if
* it is valid or uses the given string
* as route.
*
* @param $route
* @var string $location
*/
public static function redirect($route)
{
return header("location: {$route}");
}
/**
* Refresh after the number of seconds of wait
* to a route given as second parameter
*
* @param $seconds
* @param $route
* return mixed
*/
public static function refresh($seconds, $route)
{
return header("refresh:{$seconds}; url='{$route}'");
}
}
| true |
b1d00aa01bc82ebf38e7aa9eac58f0d7ba6bef19 | PHP | NicktheGeek/genesis-style-select | /admin.php | UTF-8 | 1,964 | 2.515625 | 3 | [] | no_license | <?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
add_action( 'admin_menu', 'ntg_add_style_settings_box', 20 );
function ntg_add_style_settings_box() {
global $_genesis_admin_settings;
add_meta_box('genesis-theme-settings-style-select', __('Style Select', 'gsselect'), 'ntg_theme_settings_style_box', $_genesis_admin_settings->pagehook, 'main', 'default');
}
function ntg_theme_settings_style_box() {
// set the default selection (if empty)
$style = genesis_get_option('style_selection') ? genesis_get_option('style_selection') : 'style.css';
?>
<p><label><?php _e('Style Sheet', 'gsselect'); ?>:
<select name="<?php echo GENESIS_SETTINGS_FIELD; ?>[style_selection]">
<?php
foreach ( glob(CHILD_DIR . "/*.css") as $file ) {
$file = str_replace( CHILD_DIR . '/', '', $file );
if( ! genesis_style_check( $file, 'genesis' )){
continue;
}
?>
<option style="padding-right:10px;" value="<?php echo esc_attr( $file ); ?>" <?php selected($file, $style); ?>><?php echo esc_html( $file ); ?></option>
<?php } ?>
</select>
</label></p>
<p><span class="description">Please select your desired <b>Style Sheet</b> from the drop down list and save your settings.</span></p>
<p><span class="description"><b>Note:</b> Only Genesis style sheets in the Child theme directory will be included in the list.</span></p>
<?php
}
if( ! function_exists('genesis_style_check') ) {
// Checks if the style sheet is a Genesis style sheet
function genesis_style_check($fileText, $char_list) {
$fh = fopen(CHILD_DIR . '/' . $fileText, 'r');
$theData = fread($fh, 1000);
fclose($fh);
$search = strpos($theData, $char_list);
if($search === false){
return false;
}
return true;
}
}
| true |
cfb74efd4af5384081dea0a061686ac1f63d1c87 | PHP | jonathansc92/softblue | /PHP7/StringsFunctions/exercise03.php | UTF-8 | 282 | 3.671875 | 4 | [] | no_license | <?php
// Create a function look like the function strposwithout using it
function pos(string $string) {
$result = "";
for ($x = strlen($string) - 1; $x >= 0; $x--) {
$result .= substr($string, $x, 1);
}
return $result;
}
echo pos("Exemplo de string");
?> | true |
a4ff4597a8081b092bb17acf7365fc6e9899974a | PHP | phacility/phabricator | /src/applications/phurl/query/PhabricatorPhurlURLQuery.php | UTF-8 | 2,199 | 2.609375 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | <?php
final class PhabricatorPhurlURLQuery
extends PhabricatorCursorPagedPolicyAwareQuery {
private $ids;
private $phids;
private $names;
private $longURLs;
private $aliases;
private $authorPHIDs;
public function newResultObject() {
return new PhabricatorPhurlURL();
}
public function withIDs(array $ids) {
$this->ids = $ids;
return $this;
}
public function withPHIDs(array $phids) {
$this->phids = $phids;
return $this;
}
public function withNames(array $names) {
$this->names = $names;
return $this;
}
public function withNameNgrams($ngrams) {
return $this->withNgramsConstraint(
id(new PhabricatorPhurlURLNameNgrams()),
$ngrams);
}
public function withLongURLs(array $long_urls) {
$this->longURLs = $long_urls;
return $this;
}
public function withAliases(array $aliases) {
$this->aliases = $aliases;
return $this;
}
public function withAuthorPHIDs(array $author_phids) {
$this->authorPHIDs = $author_phids;
return $this;
}
protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) {
$where = parent::buildWhereClauseParts($conn);
if ($this->ids !== null) {
$where[] = qsprintf(
$conn,
'url.id IN (%Ld)',
$this->ids);
}
if ($this->phids !== null) {
$where[] = qsprintf(
$conn,
'url.phid IN (%Ls)',
$this->phids);
}
if ($this->authorPHIDs !== null) {
$where[] = qsprintf(
$conn,
'url.authorPHID IN (%Ls)',
$this->authorPHIDs);
}
if ($this->names !== null) {
$where[] = qsprintf(
$conn,
'url.name IN (%Ls)',
$this->names);
}
if ($this->longURLs !== null) {
$where[] = qsprintf(
$conn,
'url.longURL IN (%Ls)',
$this->longURLs);
}
if ($this->aliases !== null) {
$where[] = qsprintf(
$conn,
'url.alias IN (%Ls)',
$this->aliases);
}
return $where;
}
protected function getPrimaryTableAlias() {
return 'url';
}
public function getQueryApplicationClass() {
return 'PhabricatorPhurlApplication';
}
}
| true |
5196adda412a247dd4c09a5e95cbb133a907d90d | PHP | mohamednagy/Permissions-Handler | /src/Migrations/migrations.php | UTF-8 | 3,271 | 2.53125 | 3 | [
"MIT"
] | permissive | <?php
use Doctrine\Common\Inflector\Inflector;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUserPermissionsMigrations extends Migration
{
/**
* @var array
*/
private $tables;
/**
* __construct.
*
* @return void
*/
public function __construct()
{
$this->tables = config('permissionsHandler.tables');
}
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
if (! Schema::hasTable($this->tables['roles'])) {
Schema::create($this->tables['roles'], function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
if (! Schema::hasTable($this->tables['role_user'])) {
Schema::create($this->tables['role_user'], function (Blueprint $table) {
$foreignKeyName = Inflector::singularize($this->tables['roles']).'_id';
$table->integer($foreignKeyName)->unsigned()->index();
$table->foreign($foreignKeyName)->references('id')->on($this->tables['roles'])->onDelete('cascade');
$table->morphs('model');
$table->timestamps();
$table->primary([$foreignKeyName, 'model_id', 'model_type']);
});
}
if (! Schema::hasTable($this->tables['permissions'])) {
Schema::create($this->tables['permissions'], function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
if (! Schema::hasTable($this->tables['permission_role'])) {
Schema::create($this->tables['permission_role'], function (Blueprint $table) {
$permissionsForeignKeyName = Inflector::singularize($this->tables['permissions']).'_id';
$rolesForeignKeyName = Inflector::singularize($this->tables['roles']).'_id';
$table->integer($permissionsForeignKeyName)->unsigned()->index();
$table->foreign($permissionsForeignKeyName)->references('id')->on($this->tables['permissions'])->onDelete('cascade');
$table->integer($rolesForeignKeyName)->unsigned()->index();
$table->foreign($rolesForeignKeyName)->references('id')->on($this->tables['roles'])->onDelete('cascade');
$table->timestamps();
$table->primary([$permissionsForeignKeyName, $rolesForeignKeyName]);
});
}
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
if (Schema::hasTable($this->tables['role_user'])) {
Schema::drop($this->tables['role_user']);
}
if (Schema::hasTable($this->tables['permission_role'])) {
Schema::drop($this->tables['permission_role']);
}
if (Schema::hasTable($this->tables['roles'])) {
Schema::drop($this->tables['roles']);
}
if (Schema::hasTable($this->tables['permissions'])) {
Schema::drop($this->tables['permissions']);
}
}
}
| true |
9ff0b6f40a69cc5b67523c237e6c5265cafc2678 | PHP | ingenerator/form | /src/Renderer/FormElementRenderer.php | UTF-8 | 3,583 | 2.734375 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
/**
* @author Andrew Coulton <andrew@ingenerator.com>
* @licence proprietary
*/
namespace Ingenerator\Form\Renderer;
use Ingenerator\Form\Criteria\FieldCriteriaMatcher;
use Ingenerator\Form\Element\AbstractFormElement;
use Ingenerator\Form\Element\Field\AbstractFormField;
use Ingenerator\Form\Form;
use Ingenerator\Form\FormConfig;
class FormElementRenderer implements FormEditRenderer, FormDisplayRenderer
{
/**
* @var string
*/
protected $render_mode;
/**
* @var FormConfig
*/
protected $template_map;
private FormConfig $config;
/**
* @param \Ingenerator\Form\FormConfig $config
*/
public function __construct(FormConfig $config, $render_mode = 'edit')
{
$this->config = $config;
$this->render_mode = $render_mode;
}
/**
* @param string $value
* @param AbstractFormField $field
*
* @return string
*/
public function getHighlightClasses($value, AbstractFormField $field)
{
$matcher = new FieldCriteriaMatcher;
$classes = \array_keys(
\array_filter(
[
'answer-highlighted' => $matcher->matches($value, $field->highlight_if),
'answer-display-hidden' => $matcher->matches($value, $field->hide_display_if),
'answer-empty' => $matcher->matches($value, ['empty'])
]
)
);
return \implode(' ', $classes);
}
/**
* @param \Ingenerator\Form\Element\AbstractFormElement $element
*
* @return string
*/
public function render(AbstractFormElement $element)
{
if ( ! $template_file = $this->findTemplateForElement($element, $this->render_mode)) {
throw UndefinedTemplateException::forElement($element, $this->render_mode);
}
return $this->requireWithAnonymousScope($template_file, $element);
}
/**
* @param \Ingenerator\Form\Element\AbstractFormElement $element
* @param string $mode
*
* @return string
*/
protected function findTemplateForElement(AbstractFormElement $element, $mode)
{
if ($template_file = $this->config->getTemplateFile(\get_class($element), $mode)) {
return $template_file;
}
if ($element instanceof Form) {
return $this->config->getTemplateFile(Form::class, $mode);
}
return NULL;
}
/**
* @param string $template_file
* @param AbstractFormElement $element
*
* @return string
*/
protected function requireWithAnonymousScope($template_file, AbstractFormElement $element)
{
// Create a function with no scope except the variables it gets passed
$bound_capture = function (
AbstractFormElement $field,
FormElementRenderer $form_renderer,
$template_file
) {
require $template_file;
};
$anon_capture = $bound_capture->bindTo(NULL);
// Render the template
\ob_start();
try {
$anon_capture($element, $this, $template_file);
} finally {
$output = \ob_get_clean();
}
return $output;
}
/**
* @param \Ingenerator\Form\Element\Field\AbstractFormField $field
*
* @return string
*/
public function renderConstraintsAttributes(AbstractFormField $field)
{
return \HTML::attributes($field->constraints);
}
}
| true |
7463635f11afc94641234df49e8f0df2a46891d9 | PHP | trashtoy/PEACH2 | /src/Peach/DF/JsonCodec/StructuralChar.php | UTF-8 | 3,846 | 2.953125 | 3 | [
"MIT"
] | permissive | <?php
/*
* Copyright (c) 2015 @trashtoy
* https://github.com/trashtoy/
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* PHP class file.
* @auhtor trashtoy
* @since 2.1.0
* @ignore
*/
namespace Peach\DF\JsonCodec;
/**
* RFC 7159 で "six structural characters" として挙げられている以下の BNF ルールを解釈する
* Expression です.
*
* <pre>
* begin-array = ws %x5B ws ; [ left square bracket
*
* begin-object = ws %x7B ws ; { left curly bracket
*
* end-array = ws %x5D ws ; ] right square bracket
*
* end-object = ws %x7D ws ; } right curly bracket
*
* name-separator = ws %x3A ws ; : colon
*
* value-separator = ws %x2C ws ; , comma
* </pre>
*
* @ignore
*/
class StructuralChar implements Expression
{
/**
* 例えば array(",", "]") など
*
* @var array
*/
private $expected;
/**
* "[", "{", "]", "}", ":", "," のうちのどれかが入ります.
*
* @var string
*/
private $result;
/**
* 指定された文字を受理する StructuralChar インスタンスを構築します.
* @param array $expected 受理される文字のリスト
*/
public function __construct(array $expected)
{
$this->expected = $expected;
$this->result = null;
}
/**
* 現在の Context から空白および想定される文字を読み込みます.
* もしも想定外の文字を検知した場合は DecodeException をスローします.
*
* @param Context $context
*/
public function handle(Context $context)
{
$ws = WS::getInstance();
$ws->handle($context);
if (!$context->hasNext()) {
throw $context->createException("Unexpected end of JSON");
}
$this->handleChar($context);
$ws->handle($context);
}
/**
* 空白以外の文字を検知した際の処理です.
*
* @param Context $context
* @throws DecodeException 期待されている文字以外の文字を検知した場合
*/
private function handleChar(Context $context)
{
$chr = $context->current();
$expected = $this->expected;
if (in_array($chr, $expected, true)) {
$this->result = $chr;
$context->next();
return;
}
$quote = function ($chr) {
return "'{$chr}'";
};
$expectedList = implode(", ", array_map($quote, $expected));
throw $context->createException("'{$chr}' is not allowed (expected: {$expectedList})");
}
/**
* handle() の結果を返します.
*
* @return string
*/
public function getResult()
{
return $this->result;
}
}
| true |
7f95abbff12fd68277a1e50920fe814813addc8a | PHP | AlexanderAndreev94/test_project1.1 | /test/migrations/m170708_160928_create_categoryTree_table.php | UTF-8 | 918 | 2.5625 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
use yii\db\Migration;
/**
* Handles the creation of table `categoryTree`.
*/
class m170708_160928_create_categoryTree_table extends Migration
{
/**
* @inheritdoc
*/
public function up()
{
$this->createTable('categorytree', [
'id' => \yii\db\Schema::TYPE_INTEGER . 'NOT NULL AUTO_INCREMENT',
'name' => $this->string()->notNull(),
'status' => $this->string()->notNull(),
'tree'=> $this->integer()->notNull(),
'lft' => $this->integer()->notNull(),
'rgt' => $this->integer()->notNull(),
'depth' => $this->integer()->notNull(),
'position' => $this->integer()->notNull()->defaultValue(0),
]);
$this->addPrimaryKey('cat_id', 'categorytree', 'id');
}
/**
* @inheritdoc
*/
public function down()
{
$this->dropTable('categoryTree');
}
}
| true |
26290fdc3e073bebb8389599742ac86110fe6b80 | PHP | kkMatt/ProgrammingAssignments | /NFQ-Challenge/include.api.php | UTF-8 | 1,714 | 2.65625 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: KestutisIT
* Date: 2014/11/27
* Time: 2:29 AM
*/
// Read calls
$apiCommand = Flight::request()->query->command;
$apiData = Flight::request()->query->command;
// Set default output
$returnedData = "";
// DB: get new instance
$db = Flight::db();
// Depending on the call (command) received to api, load proper view
switch($apiCommand)
{
// List users
case "get_users":
$users = array();
$tmpUsers = array();
// DB: get all users in database
$users = $db->query("
SELECT user_id, user_name
FROM nfq_users
");
// Iterate over all users and add user group names & id's to user row
foreach($users as $user)
{
$userGroups = $db->query("
SELECT ug.group_id AS group_id, g.group_name AS group_name
FROM nfq_user_groups ug
LEFT JOIN nfq_groups g ON g.group_id=ug.group_id
WHERE ug.user_id='{$user['user_id']}'
");
$user['user_groups'] = $userGroups;
$tmpUsers[] = $user;
}
$users = $tmpUsers;
//print_r($users);
// Save view to variable
ob_start();
include("views/include.users.php");
$returnedData = ob_get_clean();
break;
// List groups
case "get_groups":
$groups = $db->query("
SELECT group_id, group_name
FROM nfq_groups
");
// Save view to variable
ob_start();
include("views/include.groups.php");
$returnedData = ob_get_clean();
break;
}
// Output - JSON
Flight::json(array(
"returnedData" => $returnedData
));
| true |
8c2a0c766eb8411d0d1c84765d273991861ca2ee | PHP | Umudo/slim-base | /App/Base/Task.php | UTF-8 | 1,364 | 2.609375 | 3 | [] | no_license | <?php
namespace App\Base;
use App\ConnectionManager\RedisManager;
use App\Helper\Container;
use App\Interfaces\Task as TaskInterface;
abstract class Task implements TaskInterface
{
private $rk;
private $rk_timeout;
/**
* @return bool
*/
abstract public function isActive() : bool;
/**
* @return bool
*/
abstract public function isLogEnabled() : bool;
abstract protected function run();
public function __construct()
{
$this->rk = 'task:update_check_time:class:' . get_class($this) . ':pid:' . getmypid();
$schedule = static::schedule();
$this->rk_timeout = strtotime($schedule['killWhenNotActiveFor'], 0);
}
protected function logger($action)
{
if (!$this->isLogEnabled()) {
return;
}
Container::getLogger()->addInfo('class:' . get_class($this) . ' pid:' . getmypid() . "\naction:" . $action);
}
protected function updateCheckTime()
{
try {
RedisManager::getInstance(Container::getContainer()->get('settings')['taskRunner']['redisInstanceName'])->setex($this->rk, $this->rk_timeout, time());
} catch (\Throwable $e) {
Container::getLogger()->addCritical($e);
}
}
public function start()
{
$this->updateCheckTime();
$this->run();
}
}
| true |
dc6381870712d3e41cfe51009217b09fa16f888e | PHP | dittto/router | /Route/Tests/RouteNodeArgumentsTest.php | UTF-8 | 1,521 | 2.703125 | 3 | [] | no_license | <?php
namespace Route\Tests;
use Route;
/**
* Class RouteNodeArgumentsTest
* Tests that RouteNodeArguments is working
*
* @package Route\Tests
*/
class RouteNodeArgumentsTest extends \PHPUnit_Framework_TestCase {
/**
* Tests the RouteNodeArguments() can be instantiated
*/
public function testInit() {
$node = new Route\RouteNodeArguments();
$this->assertTrue($node instanceof Route\RouteNodeArguments);
}
/**
* Tests the SetNode and GetNode methods
*/
public function testNode() {
// test the constructor
$childNode = $this->getMock('Route\RouteNode');
$childNode->different = 1;
$node = new Route\RouteNodeArguments($childNode);
$this->assertEquals($childNode, $node->GetNode());
// test the SetNode / GetNode pair
$otherNode = $this->getMock('Route\RouteNode');
$otherNode->different = 2;
$node->SetNode($otherNode);
$this->assertEquals($otherNode, $node->GetNode());
}
/**
* Tests the SetArguments and GetArguments methods
*/
public function testArgs() {
// test the constructor
$args = array(1 => 'one');
$node = new Route\RouteNodeArguments(null, $args);
$this->assertEquals($args, $node->GetArguments());
// test the SetArguments / GetArguments pair
$otherArgs = array(2 => 'two');
$node->SetArguments($otherArgs);
$this->assertEquals($otherArgs, $node->GetArguments());
}
}
| true |
d04604f252f68f01477ab9fe26a0bfe49002607e | PHP | manf11/belajar-web-simpan-data | /controllers/index.php | UTF-8 | 372 | 2.71875 | 3 | [] | no_license | <?php
require_once('database.php'); // disini kita ambil semua kodingan yang ada di database
// pertama siapin query nya dulu
$sql = "SELECT * FROM product";
$query = mysqli_query($connection, $sql);
$products = [];
while($product = mysqli_fetch_assoc($query)){
$products[] = $product;
}
require_once('views/index.php'); //ini panggil index.php yang ada di view
| true |
d592daa618692b88d492c7620fec9f57b9c64551 | PHP | NickoBrown/Web-Development | /Project/userlist.php | UTF-8 | 1,872 | 2.515625 | 3 | [] | no_license | <!--
Nicholas Brown
30032159
Activity 3
-->
<head>
<link rel="stylesheet" href="style.css">
</head>
<nav>
<h2>
<a href="topten.php">Top 10</a>
<a href="index.php">Movie Search</a>
</h2>
</nav>
<body>
<header>
<h1>User List</h1>
</header>
<table>
<tr>
<th>Title</th>
<th>Genre</th>
<th>Release Year</th>
<th>ID</th>
</tr>
<?php
include("connect.php");
$statement = $conn->prepare("SELECT * FROM `UserList`");
$statement->execute();
$user = $statement->fetchAll(PDO::FETCH_ASSOC);
for ($i = 0; true; $i++) {
echo "<td>" . $user[$i]['firstname'] . "</td>";
echo "<td>" . $user[$i]['lastname'] . "</td>";
echo "<td>" . $user[$i]['email'] . "</td>";
echo "<td>" . $user[$i]['id'] . "</td>";
$id = $user[$i]['id'];
if($id != null){
echo "<td>" .
"<form action=\"deluserscr.php\" method=\"post\">
<input value=\"$id\" type=\"hidden\" name=\"id\">
<input type=\"submit\" value=\"Delete User\">
</form> </td>";
}
else echo "<h2>No users found.</h2>";
echo "<tr>";
if ($user[$i + 1] == null) {
break;
}
}
?>
</table>
</body> | true |
225964dc30628f0b335e1c0680bccb0f210e1cea | PHP | EddyArellanes/chemicalquery | /application/controllers/classes/functions.php | UTF-8 | 1,565 | 2.796875 | 3 | [] | no_license | <?php
function crypt_pass($password, $digito = 9) {
$set_salt = '/1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
$salt = sprintf('$2x$%02d$', $digito);
for($i = 0; $i<22; $i++)
{
$salt .= $set_salt[mt_rand(0, 62)];
}
return crypt($password, $salt);
}
function encriptar($cadena, $clave = "una clave secreta")
{
$cifrado = MCRYPT_RIJNDAEL_256;
$modo = MCRYPT_MODE_ECB;
return mcrypt_encrypt($cifrado, $clave, $cadena, $modo,
mcrypt_create_iv(mcrypt_get_iv_size($cifrado, $modo), MCRYPT_RAND));
}
function desencriptar($cadena, $clave = "una clave secreta")
{
$cifrado = MCRYPT_RIJNDAEL_256;
$modo = MCRYPT_MODE_ECB;
return mcrypt_decrypt($cifrado, $clave, $cadena, $modo,
mcrypt_create_iv(mcrypt_get_iv_size($cifrado, $modo), MCRYPT_RAND));
}
function validarmail($mail)
{
$patron_mail = '/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/';
return preg_match($patron_mail, $mail, $coincidencias);
print_r($coincidencias);
}
function validartelefono($telefono)
{
$patron_tel = '^\d{8,12}$^';
return preg_match($patron_tel, $telefono, $coincidencias);
}
function test_input($data)
{
$data = trim($data);
$data = htmlspecialchars($data);
$data = filter_var($data, FILTER_SANITIZE_STRING);
return $data;
}
function test_input2($data)
{
$data = trim($data);
$data = htmlspecialchars($data);
return $data;
}
function test_input_mail($data)
{
$data = trim($data);
$data = htmlspecialchars($data);
$data = filter_var($data, FILTER_SANITIZE_EMAIL);
return $data;
}
?> | true |
cbf87310b3e1dedbbf31fa0331145f6979c53246 | PHP | webforge-labs/cms | /src/php/Webforge/Doctrine/Test/Entities/CompiledUser.php | UTF-8 | 1,531 | 2.796875 | 3 | [
"MIT"
] | permissive | <?php
namespace Webforge\Doctrine\Test\Entities;
use Doctrine\ORM\Mapping as ORM;
/**
* Compiled Entity for Webforge\Doctrine\Test\Entities\User
*
* To change table name or entity repository edit the Webforge\Doctrine\Test\Entities\User class.
* @ORM\MappedSuperclass
*/
abstract class CompiledUser
{
/**
* id
* @var integer
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue
*/
protected $id;
/**
* email
* @var string
* @ORM\Column(length=210)
*/
protected $email;
/**
* special
* @var string
* @ORM\Column(nullable=true)
*/
protected $special;
public function __construct($email)
{
$this->email = $email;
}
/**
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* @param integer $id
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* @return string
*/
public function getEmail()
{
return $this->email;
}
/**
* @param string $email
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* @return string
*/
public function getSpecial()
{
return $this->special;
}
/**
* @param string $special
*/
public function setSpecial($special = null)
{
$this->special = $special;
return $this;
}
}
| true |
89940225e797c9bab3e469ccb1abf2d2fac8a645 | PHP | birdshark/phalcon_multimodule_example | /app/common/models/RoleAdmin.php | UTF-8 | 1,835 | 2.734375 | 3 | [] | no_license | <?php
namespace Application\Common\Models;
class RoleAdmin extends ModelBase
{
/**
*
* @var integer
* @Primary
* @Column(column="admin_id", type="integer", length=10, nullable=false)
*/
public $admin_id;
/**
*
* @var integer
* @Primary
* @Column(column="role_id", type="integer", length=10, nullable=false)
*/
public $role_id;
/**
* Initialize method for model.
*/
public function initialize()
{
$this->setSchema("test");
$this->setSource("role_admin");
// $this->belongsTo('admin_id', 'Application\Common\Models\Admins', 'id', ['alias' => 'Admins']);
// $this->belongsTo('role_id', 'Application\Common\Models\Roles', 'id', ['alias' => 'Roles']);
}
/**
* Returns table name mapped in the model.
*
* @return string
*/
public function getSource()
{
return 'role_admin';
}
/**
* Allows to query a set of records that match the specified conditions
*
* @param mixed $parameters
* @return RoleAdmin[]|RoleAdmin|\Phalcon\Mvc\Model\ResultSetInterface
*/
public static function find($parameters = null)
{
return parent::find($parameters);
}
/**
* Allows to query the first record that match the specified conditions
*
* @param mixed $parameters
* @return RoleAdmin|\Phalcon\Mvc\Model\ResultInterface
*/
public static function findFirst($parameters = null)
{
return parent::findFirst($parameters);
}
public function getRole($admin_id){
$phql = "SELECT b.name,b.id FROM c:RoleAdmin a LEFT JOIN c:Roles b ON a.role_id = b.id WHERE admin_id = $admin_id";
$roles = $this->getModelsManager()->executeQuery($phql);
return $roles->toArray();
}
}
| true |
0fd0580e1757a8af3a3bd97a0eee8fe050299a87 | PHP | loveyu/Linger | /sys/core/lib/pcache.php | UTF-8 | 2,011 | 2.734375 | 3 | [] | no_license | <?php
namespace CLib;
c_lib()->load('interface/PCacheInterface');
/**
* 页面缓存类
* Class PCache
* @package CLib
*/
class PCache{
/**
* @var PCacheInterface
*/
private $drive;
/**
* @var bool 是否启用缓存的状态
*/
private $status;
/**
* @var int 设置的超时时间
*/
private $exp = 0;
/**
* 构造方法
* @param string $drive_name 驱动名称
* @param array $drive_config 驱动构造配置文件
* @throws \Exception 抛出驱动未找到的异常
*/
function __construct($drive_name = 'File', $drive_config = []){
if(hook()->apply("PCache_set", true)){
//只有当缓存启用时才调用页面缓存
$this->status = true;
if(empty($drive_name)){
$drive_name = "File";
}
c_lib()->load('pcache/' . $drive_name);
$drive_name = "CLib\\PCache\\" . $drive_name;
if(!class_exists($drive_name)){
throw new \Exception(___("Page Cache Drive Not Found"));
}
$this->drive = new $drive_name($drive_config);
hook()->add("Uri_load_begin", [
$this,
'hook_begin'
]);
hook()->add("Uri_load_end", [
$this,
'hook_end'
]);
} else{
$this->status = false;
}
}
/**
* 设置控制器的页面缓存。当存在缓存时该方法调用die()结束,并加载钩子
* @param float $min 缓存的时间
*/
public function set($min){
if(!$this->status){
return;
}
$this->exp = $min * 60;
$content = $this->drive->read(md5(URL_NOW), $this->exp);
if($content !== false){
echo $content;
if(ob_get_length()){
//刷新缓冲区
@ob_flush();
@flush();
@ob_end_flush();
}
hook()->apply("PCache_set_success", NULL);//缓存设置结束前钩子
exit;
}
}
/**
* 开始钩子
*/
public function hook_begin(){
if($this->status){
ob_start();
}
}
/**
* 结束钩子
*/
public function hook_end(){
if($this->status && $this->exp > 0){
$content = ob_get_contents();
$this->drive->write(md5(URL_NOW), $content, $this->exp);
}
}
} | true |
031fdd9f90b5fb42ad9c8184d3fea30f4663c8ee | PHP | hinaloe/tissue | /app/MetadataResolver/FantiaResolver.php | UTF-8 | 1,488 | 2.578125 | 3 | [
"MIT"
] | permissive | <?php
namespace App\MetadataResolver;
use Illuminate\Support\Facades\Log;
class FantiaResolver implements Resolver
{
public function resolve(string $url): Metadata
{
preg_match("~\d+~", $url, $match);
$postId = $match[0];
$client = new \GuzzleHttp\Client();
$res = $client->get($url);
if ($res->getStatusCode() === 200) {
$ogpResolver = new OGPResolver();
$metadata = $ogpResolver->parse($res->getBody());
$dom = new \DOMDocument();
@$dom->loadHTML(mb_convert_encoding($res->getBody(), 'HTML-ENTITIES', 'UTF-8'));
$xpath = new \DOMXPath($dom);
$node = $xpath->query("//meta[@property='twitter:image']")->item(0);
$ogpUrl = $node->getAttribute('content');
// 投稿に画像がない場合(ogp.jpgでない場合)のみ大きい画像に変換する
if ($ogpUrl != 'http://fantia.jp/images/ogp.jpg') {
preg_match("~https://fantia\.s3\.amazonaws\.com/uploads/post/file/{$postId}/ogp_(.*?)\.(jpg|png)~", $ogpUrl, $match);
$uuid = $match[1];
$extension = $match[2];
// 大きい画像に変換
$metadata->image = "https://c.fantia.jp/uploads/post/file/{$postId}/main_{$uuid}.{$extension}";
}
return $metadata;
} else {
throw new \RuntimeException("{$res->getStatusCode()}: $url");
}
}
}
| true |
d2677630d73a8b080c4f9395bfe8eb60746741c6 | PHP | 123lens/postnl-rest-api-client | /src/Messages/Requests/PostalcodeCheckRequest.php | UTF-8 | 2,917 | 2.8125 | 3 | [
"MIT"
] | permissive | <?php
namespace Budgetlens\PostNLApi\Messages\Requests;
/**
* Postalcode Check Request
*
* ### Example
* <code>
* $request = $client->checkout()->postalcodeCheck();
* $request->setPostalcode('1000AA')
* $request->setHouseNumber(1);
* $response = $request->send();
* $data = $response->getData();
* </code>
*
*/
use Budgetlens\PostNLApi\Messages\Requests\Contracts\MessageInterface;
use Budgetlens\PostNLApi\Messages\Requests\Contracts\RequestInterface;
use Budgetlens\PostNLApi\Messages\Responses\NearestLocationsResponse;
use Budgetlens\PostNLApi\Messages\Responses\PostalcodeCheckResponse;
class PostalcodeCheckRequest extends AbstractRequest implements RequestInterface, MessageInterface
{
/**
* Get Postalcode
* @return string|null
*/
public function getPostalCode(): ?string
{
return $this->getParameter('postal_code');
}
/**
* Set Postalcode
* @param string $postalcode
* @return NearestLocationsRequest
*/
public function setPostalCode(string $postalcode)
{
return $this->setParameter('postal_code', $postalcode);
}
/**
* Get House Number
* @return int|null
*/
public function getHouseNumber(): ?int
{
return $this->getParameter('house_number');
}
/**
* Set House Number
* @param int $houseNumber
*/
public function setHouseNumber(int $houseNumber)
{
$this->setParameter('house_number', $houseNumber);
}
/**
* Get HouseNumber Addition
* @return string|null
*/
public function getHouseNumberAddition(): ?string
{
return $this->getParameter('house_number_addition');
}
/**
* Set HouseNumber Addition
* @param string $addition
* @return NearestLocationsRequest
*/
public function setHouseNumberAddition(string $addition)
{
return $this->setParameter('house_number_addition', $addition);
}
/**
* Get Data
* @return array
*/
public function getData(): array
{
$this->validate(
'postal_code',
'house_number'
);
$data = [
'postalcode' => $this->getPostalCode(),
'housenumber' => $this->getHouseNumber(),
'housenumberaddition' => $this->getHouseNumberAddition()
];
return array_filter($data);
}
/**
* Send data
* @param array $data
* @return NearestLocationsResponse
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function sendData(array $data = [])
{
$response = $this->client->request(
'GET',
'/shipment/checkout/v1/postalcodecheck',
[
'query' => $data
]
);
return $this->response = new PostalcodeCheckResponse($this, $response->getBody()->json());
}
}
| true |
9546c59afc800565a5196b7d44036942bade6225 | PHP | alex687/SoftUni-Homeworks | /phpHomework/PHP Flow Control/PrimesInRange.php | UTF-8 | 927 | 3.75 | 4 | [] | no_license | <?php
function isPrime($number)
{
for ($i = 2; $i <= sqrt($number); $i++) {
if ($number % $i == 0) {
return false;
}
}
return true;
}
function checkPrimeRange($start, $end)
{
for ($i = $start; $i <= $end; $i++) {
if (isPrime($i)) {
echo "<strong>{$i}, </strong>";
} else {
echo $i.", ";
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Primes in range</title>
</head>
<body>
<form action="" method="post">
<label for="cars">Start</label>
<input type="number" name="start" id="start"/>
<label for="end">End</label>
<input type="number" name="end" id="end"/>
<input type="submit" value="Show Results"/>
</form>
<?php
if (isset($_POST['start']) && isset($_POST['end']) &&
is_numeric($_POST['start']) && is_numeric($_POST['end'])
) {
checkPrimeRange($_POST['start'], $_POST['end']);
}
?>
</body>
</html> | true |
2181395949fc02b99509a707c4452f3e0a1e8376 | PHP | MimaTomis/yii2-sitemap-generator | /src/SitemapGenerator/Component/SitemapGeneratorComponent.php | UTF-8 | 3,584 | 2.921875 | 3 | [] | no_license | <?php
namespace SitemapGenerator\Component;
use SitemapGenerator\Extractor\CompositeDataExtractor;
use SitemapGenerator\Extractor\DataExtractorInterface;
use SitemapGenerator\Factory\GeneratorFactoryInterface;
use SitemapGenerator\Factory\MultipleGeneratorFactory;
use SitemapGenerator\Factory\SimpleGeneratorFactory;
use yii\base\Component;
/**
* @property string $directoryToSaveSitemap
*/
class SitemapGeneratorComponent extends Component
{
/**
* Config for generator factory;
*
* @var string|array
*/
public $generatorFactory = SimpleGeneratorFactory::class;
/**
* Name of sitemap file
*
* @var string
*/
public $fileName = 'sitemap.xml';
/**
* Config for data extractor
*
* @var string|array
*/
public $extractor = [
'class' => CompositeDataExtractor::class,
'extractors' => []
];
/**
* Directory to save sitemap files
*
* @var string
*/
protected $directoryToSaveSitemap;
/**
* Initialize component
*/
public function init()
{
\Yii::$container->set(CompositeDataExtractor::class, function ($c, $params, $config) {
$compositeExtractor = new CompositeDataExtractor();
if (!empty($config['extractors'])) {
foreach ($config['extractors'] as $extractor) {
$extractor = $this->createExtractor($extractor);
$compositeExtractor->attachExtractor($extractor);
}
}
return $compositeExtractor;
});
\Yii::$container->set(MultipleGeneratorFactory::class, function($c, $params, $config) {
$writer = isset($config['writer']) ?
\Yii::createObject($config['writer']) :
null;
$factory = new MultipleGeneratorFactory($writer);
if (isset($config['urlToSitemapDirectory'])) {
$factory->setUrlToSitemapDirectory($config['urlToSitemapDirectory']);
}
if (isset($config['limitOfSitemapRecords'])) {
$factory->setLimitOfSitemapRecords($config['limitOfSitemapRecords']);
}
if (isset($config['lastModified'])) {
$factory->setLastModified(new \DateTime($config['lastModified']));
}
return $factory;
});
\Yii::$container->set(SimpleGeneratorFactory::class, function($c, $params, $config) {
$writer = isset($config['writer']) ?
\Yii::createObject($config['writer']) :
null;
return new SimpleGeneratorFactory($writer);
});
}
/**
* Generate sitemap and return path to file
*
* @return string
*/
public function generate()
{
$extractor = $this->createExtractor($this->extractor);
$factory = $this->createGeneratorFactory();
$generator = $factory->createGenerator($this->directoryToSaveSitemap);
return $generator->generate($this->fileName, $extractor);
}
/**
* Get directory to save sitemap. Default directory is yii2 "@webroot".
*
* @return string
*/
public function getDirectoryToSaveSitemap()
{
return $this->directoryToSaveSitemap ?: '@webroot';
}
/**
* Set directory to save sitemap
*
* @param string $directoryToSaveSitemap
*/
public function setDirectoryToSaveSitemap($directoryToSaveSitemap)
{
$this->directoryToSaveSitemap = $directoryToSaveSitemap;
}
/**
* Create generator factory from parameters;
*
* @return GeneratorFactoryInterface
*
* @throws \yii\base\InvalidConfigException
*/
protected function createGeneratorFactory()
{
return \Yii::createObject($this->generatorFactory);
}
/**
* Create instance of DataExtractorInterface subclass
*
* @param $extractor
*
* @return DataExtractorInterface
*
* @throws \yii\base\InvalidConfigException
*/
protected function createExtractor($extractor)
{
return \Yii::createObject($extractor);
}
} | true |
3eec0ca8d2b90e5289fb6fa69d56d14af44cee56 | PHP | mgufrone/google-charts | /tests/CalendarChartTest.php | UTF-8 | 1,287 | 2.609375 | 3 | [] | no_license | <?php
class CalendarChartTest extends WorkbenchTestCase
{
public function testBasic()
{
$options = ['xAxis'=>['title'=>'Hello World']];
$data = [
[ strtotime("2012-3-13"), 37032 ],
[ strtotime("2012-3-14"), 38024 ],
[ strtotime("2012-3-15"), 38024 ],
[ strtotime("2012-3-16"), 38108 ],
[ strtotime("2012-3-17"), 38229 ],
[ strtotime("2013-9-4"), 38177 ],
[ strtotime("2013-9-5"), 38705 ],
[ strtotime("2013-9-12"), 38210 ],
[ strtotime("2013-9-13"), 38029 ],
[ strtotime("2013-9-19"), 38823 ],
[ strtotime("2013-9-23"), 38345 ],
[ strtotime("2013-9-24"), 38436 ],
[ strtotime("2013-9-30"), 38447 ]
];
$columns = [
'Year',
'Expenses',
];
$chart = Calendar::
setOptions($options)
->setWidth(400)
->setHeight(300)
->addColumn('Date', 'date')
->addColumn('Expenses', 'number')
->setData($data)
;
$content = $chart->render();
$rendered_content = $content->render();
$this->assertEquals('calendar-chart', $chart->getPackage());
$this->assertEquals('google-charts::calendar-chart', $content->getName());
$this->assertRegExp('/visualization\\.Calendar/', $rendered_content);
$this->assertRegExp('/{packages:\["calendar"\]}/', $rendered_content);
$this->assertRegExp('/DataTable/', $rendered_content);
}
} | true |
958143f2f0a9a1e95371850d8e92cc03d60f8b3f | PHP | danielsalgadop/utils-1 | /src/Lib/Json/Conditionally/Json.php | UTF-8 | 1,248 | 2.71875 | 3 | [
"MIT"
] | permissive | <?php
namespace Stopsopa\UtilsBundle\Lib\Json\Conditionally;
use Stopsopa\UtilsBundle\Lib\AbstractApp;
use Stopsopa\UtilsBundle\Lib\Json\Pretty\Json as PrettyJson;
use Exception;
/**
* Warunkowy json.
*/
class Json
{
public static function encode($data, $options = 0, $depth = 512)
{
if ($data === false) {
return 'false';
}
if (AbstractApp::isDev()) {
$tmp = PrettyJson::encode(
$data,
$options = PrettyJson::JSON_PRETTY_PRINT | PrettyJson::JSON_FORCEUTF8 | PrettyJson::JSON_UNESCAPED_SLASHES | PrettyJson::JSON_UNESCAPED_UNICODE,
$depth
);
} else {
if (version_compare(PHP_VERSION, '5.4.0', '<')) {
$tmp = json_encode($data, $options);
}
else {
$tmp = json_encode($data, $options, $depth);
}
}
if ($tmp === false) {
throw new Exception('conditional: Nie powiodło się przekształcenie za pomocą json_encode'.print_r($data, true));
}
return $tmp;
}
public static function decode($json, $assoc = true, $depth = 512)
{
return json_decode($json, $assoc, $depth);
}
}
| true |
8e3f9fa1724867ea49010e873cf375b5a03f3399 | PHP | dcotta/code-books | /walace-php5-conceitos/Capitulo 21/class_HTML.inc | ISO-8859-1 | 8,375 | 2.828125 | 3 | [] | no_license | <?php
class HTML {
/* Atributos privativos */
private $html;
private $att;
private $text;
private $tipostag;
private $_idtipo;
private $_tagid;
private $_flgend;
/* Contrutor */
function __construct($tipo=0,$att=Array(),$end=FALSE) {
$this->html = Array();
$this->att = Array();
$this->_flgend = Array();
$this->_tagid = -1;
$this->_idtipo = 0;
$this->Addtipotag("HTML");
$this->Addtipotag("HEAD");
$this->Addtipotag("TITLE");
$this->Addtipotag("BODY");
$this->Addtipotag("TABLE");
$this->Addtipotag("TR");
$this->Addtipotag("TD");
$this->Addtipotag("A");
$this->Addtipotag("BR",FALSE);
$this->Addtipotag("FORM");
$this->Addtipotag("INPUT",FALSE);
$this->Addtipotag("SELECT");
$this->Addtipotag("OPTION");
$this->Addtipotag("TEXTAREA");
$this->Addtipotag("IMG",FALSE);
$this->AddTipotag("DIV");
$this->AddTipotag("SPAN");
$this->AddTipotag("BUTTON");
$this->AddTipotag("SCRIPT");
$this->AddTipotag("P");
if($tipo!=0) {
$this->AddTag($tipo,$att,$end);
}
}
/* mtodos privativos */
/* mtodos protegidos */
/* Mtodos pblicos */
public function Addtipotag($_desc_tipo,$_flgEnd=TRUE) {
$this->_idtipo++;
$this->tipostag[$this->_idtipo] = $_desc_tipo;
$this->tipostag[$_desc_tipo] = $_desc_tipo;
$this->_flgend[$this->_idtipo] = $_flgEnd;
$this->_flgend[$_desc_tipo] = $_flgEnd;
return $this->_idtipo;
}
public function AddTag($tipo,$att=Array(),$end=FALSE,$text="") {
$this->StartTag($tipo,$att,$end);
if($text!="") {
$this->AddText($this->_tagid,$text);
}
if($end) {
$this->EndTag($this->_tagid);
}
return $this->_tagid;
}
public function StartTag($tipo,$att=Array()) {
$this->_tagid++;
$this->html[$this->_tagid][0] = FALSE;
if($this->_flgend[$tipo]===FALSE) {
$this->html[$this->_tagid][0] = TRUE;
}
$this->html[$this->_tagid][1] = $this->tipostag[$tipo];
$this->html[$this->_tagid][2] = 0; // Start
$this->AddAtt($this->_tagid,$att);
return $this->_tagid;
}
public function AddAtt($id,$att=Array()) {
if(!is_array($att)) {
return FALSE;
}
elseif($this->html[$id][0]===NULL OR $this->html[$id][1]==NULL) {
return FALSE;
} else {
foreach($att as $key=>$vlr) {
$this->att[$id][$key] = $vlr;
}
}
}
public function AddText($id,$text="",$clear=FALSE) {
if($clear) {
$this->text[$id] = "";
}
$this->text[$id] .= $text;
}
public function EndTag($id) {
if($this->html[$id][0]===TRUE) {
return FALSE;
} elseif($this->html[$id][1]!=NULL) {
$this->html[$id][0] = TRUE;
$this->StartTag($this->html[$id][1]);
$this->html[$this->_tagid][0] = TRUE;
$this->html[$this->_tagid][2] = 1; // end
return TRUE;
} else {
return FALSE;
}
}
public function toHTML() {
if($this->_tagid==-1) {
return FALSE;
} else {
$htmltext = "";
foreach($this->html as $key=>$vlr) {
if($vlr[0]==FALSE) {
$htmltext = "<p>ERRO na Estrutura.. Falta fechar a tag.." .
$this->tipostag[$vlr[1]] . " (id #" . $key . ")</p>";
return $htmltext;
}
if($vlr[2]==0) {
// Start
$htmltext.= "<" . $vlr[1];
if(is_Array($this->att[$key])) {
foreach($this->att[$key] as $att=>$vlr) {
if($att=="_") {
$htmltext.= " " . $vlr;
} else {
$htmltext.= " " . $att . "=\"" . $vlr . "\"";
}
}
}
$htmltext.= ">";
if($this->text[$key]!="") {
$htmltext.= $this->text[$key];
}
}
if($vlr[2]==1) {
// End
if($this->_flgend[$vlr[1]]===TRUE) {
$htmltext.= "</" . $vlr[1] . ">";
}
if($vlr!="IMG") $htmltext.="\n";
}
}
return $htmltext;
}
return FALSE;
}
/* Fim dos mtodos pblicos */
}
/* gera uma tabela HTML (header+detalhes+footer) */
class TABELA Extends HTML {
/* atributos privativos */
private $_id_tabela = NULL;
private $_header = FALSE;
private $_footer = FALSE;
/* atributos protegidos */
protected $_num_cols = 0;
protected $_cor_fundo_header = "#d4d0c8";
protected $_cor_fundo_detalhe = "#ffffff";
protected $_cor_fonte_header = "#000000";
protected $_cor_fonte_detalhe = "#000000";
protected $_fonte = "Verdana";
protected $_extras = "";
/* Construtor */
function __construct($_gera_tabela=TRUE,$_width="100%") {
parent::__construct();
if($_gera_tabela) {
$this->AddTabela($_width);
}
}
/* mtodos privativos */
private function AddTRTD($_valores,$_tipo=0,$_colspan=FALSE) {
$_st = "font: {$this->_fonte};";
if($_tipo==0) {
// Header
$_st .= "color: {$this->_cor_fonte_header};";
$_st .= "background-color: {$this->_cor_fundo_header};";
} else {
// Detalhe
$_st .= "color: {$this->_cor_fonte_header_detalhe};";
$_st .= "background-color: {$this->_cor_fundo_detalhe};";
}
$_st .= $this->_extras; // complemento do estilo (css)
$_id = $this->AddTag("TR",Array("style"=>$_st));
if($_colspan===FALSE) {
foreach($_valores as $_vlr) {
$this->AddTag("TD",Array("style"=>$_st),TRUE,$_vlr);
}
} else {
$this->AddTag("TD",Array("style"=>$_st,"colspan"=>$this->_num_cols),TRUE,$_valores);
}
$this->EndTag($_id);
}
/* Fim dos mtodos privativos */
/* mtodos pblicos */
public function AddTabela($_width="100%") {
$this->_id_tabela = $this->AddTag("TABLE",
Array("border"=>0,
"cellspacing"=>0,
"cellpadding"=>2,
"align"=>"center",
"width"=>$_width,
"valign"=>"top")
);
}
public function setNumCols($_num) {
$this->_num_cols = $_num;
}
public function getNumCols() {
return $this->_num_cols;
}
public function setCorFundoHeader($_cor) {
$this->_cor_fundo_header = $_cor;
}
public function getCorFundoHeader() {
return $this->_cor_fundo_header;
}
public function setCorFundoDetalhe($_cor) {
$this->_cor_fundo_detalhe = $_cor;
}
public function getCorFundoDetalhe() {
return $this->_cor_fundo_detalhe;
}
public function setCorFonteHeader($_cor) {
$this->_cor_fonte_header = $_cor;
}
public function getCorFonteHeader() {
return $this->_cor_fonte_header;
}
public function setCorFonteDetalhe($_cor) {
$this->_cor_fonte_detalhe = $_cor;
}
public function getCorFonteDetalhe() {
return $this->_cor_fonte_detalhe;
}
public function setFonte($_fnt) {
$this->_fonte = $_fnt;
}
public function getFonte() {
return $this->_fonte;
}
public function setExtras($_extras) {
$this->_extras = $_extras;
}
public function getExtras() {
return $this->_extras;
}
public function Addheader($_head) {
/* _head = Array(Valores para o cabealho) */
if($this->_header===TRUE) {
return FALSE;
}
if($this->_num_cols==0) {
$this->setNumCols(sizeof($_head));
} elseif(sizeof($_head)!=$this->_num_cols) {
return FALSE;
}
$this->AddTRTD($_head);
return TRUE;
}
public function AddDetalhe($_detalhe) {
if($this->_num_cols==0) {
$this->setNumCols(sizeof($_detalhe));
} elseif($this->_num_cols!=sizeof($_detalhe)) {
return FALSE;
}
$this->AddTRTD($_detalhe,1);
return TRUE;
}
public function AddFooter($_footer,$_colspan=FALSE) {
if($this->_footer===TRUE) {
return FALSE;
}
if($this->_num_cols!=sizeof($_footer)&&$_colspan===FALSE) {
return FALSE;
}
$this->AddTRTD($_footer,0,$_colspan);
return TRUE;
}
public function close() {
if($this->_id_tabela===NULL) {
return FALSE;
}
$this->EndTag($this->_id_tabela);
return TRUE;
}
}
?> | true |
af149e2e161b00440e73ed84e97ebb7a7f4f7739 | PHP | roeltz/mt | /app/framework/data/core/Field.php | UTF-8 | 395 | 2.875 | 3 | [] | no_license | <?php
namespace data\core;
class Field {
public $name;
public $collection;
function __construct($name, Collection $collection) {
$this->name = $name;
$this->collection = $collection;
}
function __toString() {
$field = $this->name;
$collection = $this->collection->alias
? $this->collection->alias
: $this->collection->name;
return "{$collection}.{$field}";
}
}
| true |
bfa35600edc95410ef27cdf968e86ba277bad0d8 | PHP | AlexEvesDeveloper/hl-stuff | /hl-framework/rrp/RRP/Common/PropertyLetTypes.php | UTF-8 | 787 | 2.84375 | 3 | [] | no_license | <?php
namespace RRP\Common;
/**
* Class PropertyLetTypes
*
* @package RRP\Common
* @author April Portus <april.portus@barbon.com>
*/
class PropertyLetTypes
{
/**
* Get Reference Types
*
* @return array
*/
public static function getPropertyLetTypes()
{
return array(
'Let Only' => 'Let Only',
'Managed' => 'Managed',
'Rent Collect' => 'Rent Collect',
);
}
/**
* Returns true if landlord permission is required
*
* @param $propertyLetType
* @return bool
*/
public static function isLandlordPermissionRequired($propertyLetType)
{
if ($propertyLetType == 'Let Only') {
return true;
}
else {
return false;
}
}
}
| true |
39fb5d2254a04151584d7856d25aea7a7a44c961 | PHP | hiqdev/hipanel-module-finance | /src/forms/DomainTariffForm.php | UTF-8 | 4,348 | 2.53125 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
/**
* Finance module for HiPanel
*
* @link https://github.com/hiqdev/hipanel-module-finance
* @package hipanel-module-finance
* @license BSD-3-Clause
* @copyright Copyright (c) 2015-2019, HiQDev (http://hiqdev.com/)
*/
namespace hipanel\modules\finance\forms;
use hipanel\modules\finance\logic\IntegrityException;
use hipanel\modules\finance\models\DomainResource;
use hipanel\modules\finance\models\DomainService;
use yii\web\UnprocessableEntityHttpException;
class DomainTariffForm extends AbstractTariffForm
{
/**
* @var array Domain zones
* Key - zone name (com, net, ...)
* Value - zone id
* @see getZones
*/
protected $zones;
public function load($data, $formName = null)
{
$this->setAttributes($data[$this->formName()]);
$this->setResources($data[(new DomainResource())->formName()]);
$this->initTariff();
return true;
}
/**
* @return DomainService[]
*/
public function getServices()
{
return $this->createServices($this->tariff->resources);
}
/**
* @return DomainService[]
*/
public function getParentServices()
{
return $this->createServices($this->parentTariff->resources);
}
/**
* @param $resources
* @return DomainService[]
*/
protected function createServices($resources)
{
$result = [];
$resource = reset($resources);
foreach ($resource->getServiceTypes() as $type => $name) {
$service = new DomainService([
'name' => $name,
'type' => $type,
]);
foreach ($resources as $resource) {
if ($service->tryResourceAssignation($resource) && $service->isFulfilled()) {
$result[$type] = $service;
break;
}
}
}
return $result;
}
public function setResources($resources)
{
$result = [];
foreach ($resources as $resource) {
if ($resource instanceof DomainResource) {
$result[] = $resource;
continue;
}
$model = new DomainResource(['scenario' => $this->scenario]);
if ($model->load($resource, '') && $model->validate()) {
$result[] = $model;
} else {
throw new UnprocessableEntityHttpException('Failed to load resource model: ' . reset($model->getFirstErrors()));
}
}
$this->_resources = $result;
return $this;
}
public function getZoneResources($zone)
{
$id = $this->zones[$zone];
$result = [];
foreach ($this->tariff->resources as $resource) {
if (strcmp($resource->object_id, $id) === 0 && $resource->isTypeCorrect()) {
$result[$resource->type] = $resource;
}
}
if (empty($result)) {
return [];
}
$types = $resource->getTypes();
if (count($result) !== count($types)) {
throw new IntegrityException('Found ' . count($result) . ' resources for zone "' . $zone . '". Must be exactly ' . count($types));
}
// sorts $result by order of $resource->getTypes()
$result = array_merge($types, $result);
return $result;
}
public function getZoneParentResources($zone)
{
$id = $this->zones[$zone];
$result = [];
foreach ($this->parentTariff->resources as $resource) {
if (strcmp($resource->object_id, $id) === 0 && $resource->isTypeCorrect()) {
$result[$resource->type] = $resource;
}
}
if (empty($result)) {
return [];
}
$types = $resource->getTypes();
if (count($result) !== count($types)) {
throw new IntegrityException('Found ' . count($result) . ' resources for zone "' . $zone . '". Must be exactly ' . count($types));
}
// sorts $result by order of $resource->getTypes()
$result = array_merge($types, $result);
return $result;
}
public function getZones()
{
return $this->zones;
}
public function setZones($zones)
{
$this->zones = array_flip($zones);
}
}
| true |
336b109a7b20ae176be5fef9dd2a12a9b8ae6522 | PHP | sankarsanz/api | /db/db.php | UTF-8 | 9,113 | 3.09375 | 3 | [
"Apache-2.0"
] | permissive | <?php
class DB {
/**
* Method to connect mysql database and select database
* @return void
*/
function __construct() {
global $db;
$this->db_conn = mysql_connect(DB_HOST, DB_USER, DB_PASS);
if ($this->db_conn) {
if (!mysql_select_db(DB_NAME)) {
throw new Exception('Database (' . DB_NAME . ') does not exists!');
}
}
else {
throw new Exception('Could not connect to database with the provided credentials!');
}
$this->last_query = '';
}
/**
* Method to close mysql connection
* @return void
*/
function __destruct() {
mysql_close($this->db_conn);
}
function set_last_query($query) {
$this->last_query = $query;
}
function last_query() {
return $this->last_query;
}
/**
* Method to run mysql database query
* @return resource Query resource
*/
function query($query, $return_query = FALSE) {
/* if (defined('TIME_ZONE')) {
$target_time_zone = new DateTimeZone(TIME_ZONE);
$date_time = new DateTime('now', $target_time_zone);
mysql_query('SET time_zone = "' . $date_time->format('P') . '"');
} */
if ($return_query === TRUE) {
throw new Exception($query);
}
$result = mysql_query($query);
$this->set_last_query($query);
if (!empty(mysql_error($this->db_conn))) {
throw new Exception('Invalid query: ' . mysql_error($this->db_conn) . ' in "' . $query . '"');
}
return $result;
}
/**
* Method to get last inserted id
* @return int last inserted primary key
*/
function last_inserted_id() {
return mysql_insert_id($this->db_conn);
}
function get_columns($data) {
return implode(',', array_keys($data));
}
function get_column_values($data) {
$values_str = '';
$values = array_values($data);
foreach($values as $key => $value) {
$values_str .= ($key != 0) ? ', ' : '';
if (is_string($value)) {
$values_str .= '\'' . addcslashes(trim($value), "'") . '\'';
}
else if (is_numeric($value)) {
$values_str .= $value;
}
else {
$values_str .= '\'\'';
}
}
return $values_str;
}
function get_update_str($data) {
$update_str = '';
$i = 0;
foreach($data as $key => $value) {
$update_str .= ($i != 0) ? ', ' : '';
$update_str .= trim($key) . ' = ';
if (is_string($value)) {
$update_str .= '\'' . addcslashes(trim($value), "'") . '\'';
}
else if (is_numeric($value)) {
$update_str .= $value;
}
else {
$update_str .= '\'\'';
}
$i ++;
}
return $update_str;
}
function get_where_str($where) {
if (!is_array($where))
return $where;
$where = array_filter($where);
$where_str = '';
$i = 0;
foreach($where as $key => $value) {
$where_str .= ($i != 0) ? ' AND ' : '';
$where_str .= trim($key) . ' = ';
if (is_string($value)) {
$where_str .= '\'' . addcslashes(trim($value), "'") . '\'';
}
else if (is_numeric($value)) {
$where_str .= $value;
}
$i ++;
}
return $where_str;
}
/**
* Method to insert row into table
* $param1 $query string Mysql query
* @return int Affected rows
*/
function insert($tbl_name, $data) {
if (empty($data))
throw new Exception('Insert data should not be empty!');
else if (empty($tbl_name))
throw new Exception('Table name should not be empty!');
$columns = $this->get_columns($data);
$values = $this->get_column_values($data);
$query = 'INSERT INTO ' . $tbl_name . ' (' . $columns . ') VALUES (' . $values . ')';
$this->query($query);
return $this->last_inserted_id();
}
function insert_batch($tbl_name, $data) {
if (empty($data))
throw new Exception('Insert data should not be empty!');
else if (empty($tbl_name))
throw new Exception('Table name should not be empty!');
$columns = $this->get_columns($data);
$values = $this->get_column_values($data);
$query = 'INSERT INTO ' . $tbl_name . ' (' . $columns . ') VALUES (' . $values . '),(' . $values . ')';
$this->query($query);
return $this->last_inserted_id();
}
/**
* Method to insert row into table
* $param1 $query string Mysql query
* @return int Affected rows
*/
function update($tbl_name, $data, $where) {
if (empty($data))
throw new Exception('Update data should not be empty!');
else if (empty($tbl_name))
throw new Exception('Table name should not be empty!');
$update_str = $this->get_update_str($data);
$where_str = $this->get_where_str($where);
$query = 'UPDATE ' . $tbl_name . ' SET ' . $update_str . ' WHERE ' . $where_str;
$resource = $this->query($query);
return $this->affected_rows($resource);
}
/**
* Method to delete row from table
* $param1 $query string Mysql query
* @return int Affected rows
*/
function delete($query) {
$resource = $this->query($query);
return $this->affected_rows($resource);
}
/**
* Method to count rows in a resource
* $param1 $resource resource Mysql resource
* @return int Resource rows count
*/
function num_rows($resource) {
return mysql_num_rows($resource);
}
/**
* Method to get affected rows
* @return int Affected rows count
*/
function affected_rows() {
return mysql_affected_rows($this->db_conn);
}
/**
* Method to get all rows from resource
* $param1 $resource resource Mysql resource
* @return array object Associative array object of resource
*/
function fetch_object_array($resource) {
$result = array();
if ($this->num_rows($resource) > 0) {
while($row_obj = mysql_fetch_object($resource)) {
array_push($result, $row_obj);
}
}
return $result;
}
/**
* Method to get single row from resource
* $param1 $resource resource Mysql resource
* @return array Associative array of resource
*/
function fetch_object_row($resource) {
$result = array();
if ($this->num_rows($resource) > 0) {
$result = mysql_fetch_object($resource);
}
return $result;
}
/**
* Method to get all rows from resource
* $param1 $resource resource Mysql resource
* @return array Associative array of resource
*/
function fetch_assoc_array($resource) {
$result = array();
if ($this->num_rows($resource) > 0) {
while($row = mysql_fetch_assoc($resource)) {
array_push($result, $row);
}
}
return $result;
}
/**
* Method to get single row from resource
* $param1 $resource resource Mysql resource
* @return array
*/
function fetch_assoc_row($resource) {
$result = array();
if ($this->num_rows($resource) > 0) {
$result = mysql_fetch_assoc($resource);
}
return $result;
}
public function get_array_result($query) {
$resources = $this->query($query);
if ($this->num_rows($resources) > 0) :
$result = $this->fetch_assoc_array($resources);
else:
$result = array();
endif;
return $result;
}
public function get_results($query) {
$resources = $this->query($query);
if ($this->num_rows($resources) > 0) :
/**
* Success.
*/
$results['header'] = array(
'status' => 'S',
'message' => ucfirst( CMD ) . ' is executed successfully',
);
// Set Results
$results['data'] = $this->fetch_assoc_array($resources);
else:
/**
* Error
*/
$results['header'] = array(
'status' => 'N',
'message' => 'No records found.',
);
endif;
return $results;
}
function get($tbl_name, $args = array()) {
// Nothing...
return "This is my results";
}
}
?>
| true |
c89d67761d523461c90d90b56039009d0d872a2c | PHP | Keya53/Sec-Student-Management-System | /students.php | UTF-8 | 2,255 | 2.59375 | 3 | [] | no_license | <?php include "header.php"; ?>
<?php
$year = $_GET['year'];
?>
<h4>Sylhet Engineering College</h4>
<h5>Student information: <span class="key-color">
<?php
if ($year == 1)
echo "First Year";
else if ($year == 2)
echo "Second Year";
else if ($year == 3)
echo "Third Year";
else if ($year == 4)
echo "Final Year";
?></span>
</h5>
<div class="col-md-12">
<table class='table table-bordered table-responsive' id="data-table">
<thead>
<tr class="key-bg">
<th>SL NO</th>
<th>Roll</th>
<th>Student Name</th>
<th>Father Name</th>
<th>Address</th>
<th>Email</th>
<th>Mobile No</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php
$sql = "select * from student_admission WHERE year='" . $year . "'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
foreach ($result as $key => $row) {
?>
<tr>
<td> <?php echo $key + 1; ?></td>
<td> <?php echo $row["Roll"]; ?></td>
<td> <?php echo $row["student_name"]; ?></td>
<td> <?php echo $row["father_name"]; ?></td>
<td> <?php echo $row["address"]; ?></td>
<td> <?php echo $row["email"]; ?></td>
<td> <?php echo $row["mobile_no"]; ?></td>
<td><a class="btn btn-xs btn-primary" href="students_edit.php?id=<?php echo $row["id"]; ?>">Edit</a></td>
<td><a class="btn btn-xs btn-danger" href="students_delete.php?id=<?php echo $row["id"]; ?>">Delete</a></td>
</tr>
<?php
}
}
?>
</tbody>
</table>
</div>
<script type="text/Javascript">
$(document).ready(function () {
$('#data-table').DataTable();
});
</script>
<?php include "footer.php"; ?>
| true |
72f40921f601ac1cf810e73acd3d94722e450b5d | PHP | crouchingtigerhiddenadam/magdaldalan | /message/_send.php | UTF-8 | 1,276 | 2.625 | 3 | [] | no_license | <?php
require_once '../config.php';
if ( !isset( $_SESSION ) ) {
session_start();
}
$sender_user_id = $_SESSION[ 'user_id' ];
if ( $_SERVER[ 'REQUEST_METHOD' ] === 'POST' ) {
$content_value = htmlentities( $_POST[ 'content' ] );
if ( empty( $content_value ) ) {
$is_valid = false;
}
$recipient_user_id = htmlentities( $_GET[ 'r' ] );
if ( empty( $recipient_user_id )) {
$is_valid = false;
}
if ( !isset( $is_valid ) ) {
$db_connection = new mysqli( $db_server, $db_username, $db_password, $db_name );
$db_statement = $db_connection->prepare("
INSERT INTO message (
sender_user_id,
recipient_user_id,
content,
creation_datetime_utc )
VALUES (?, ?, ?, UTC_TIMESTAMP());
");
$db_statement->bind_param( 'iis', $sender_user_id, $recipient_user_id, $content_value );
$db_statement->execute();
$db_statement->close();
$db_connection->close();
}
}
?>
<section id="send">
<hr>
<form action="index.php?r=<?= $recipient_user_id ?>" class="send-form" method="post" onsubmit="send( event )">
<input autocomplete="off" class="send-content" id="content" name="content" type="text">
<button class="send-submit" type="submit">Send</button>
</form>
</section> | true |
fea5d0da8232ca12b06e19564e64123e3bd73293 | PHP | werd2000/CronosGit | /Modelos/PacientesModelo.php | UTF-8 | 2,657 | 2.828125 | 3 | [] | no_license | <?php
//require_once BASE_PATH . 'Modulos' . DS . 'Paciente' . DS . 'Modelos' . DS . 'paciente.php';
require_once BASE_PATH . 'Modulos' . DS . 'Paciente' . DS . 'Modelos' . DS . 'Paciente.php';
/**
* Clase Modelo Paciente que extiende de la clase Modelo
*/
class Modelos_pacientesModelo extends App_Modelo
{
private $_verEliminados = 0;
/**
* Clase constructora
*/
public function __construct()
{
parent::__construct();
}
/**
* Obtiene un array con los pacientes de una OS
* @return Resource
*/
public function getPacientesByOs($idOsocial)
{
$sql = 'SELECT osPaciente.*, pacientes.* FROM cronos_paciente_os as osPaciente,
cronos_pacientes as pacientes
WHERE osPaciente.idOSocial = ' . $idOsocial .
' AND osPaciente.idPaciente = pacientes.id ORDER BY pacientes.apellidos, pacientes.nombres';
$this->_db->setTipoDatos('Array');
$this->_db->query($sql);
return $this->_db->fetchall();
}
/**
* Obtiene los datos de un paciente
* @return Resource
*/
public function getPaciente($id)
{
$paciente = '';
$id = (int) $id;
$sql = "SELECT * FROM cronos_pacientes WHERE id = $id";
$this->_db->setTipoDatos('Array');
$this->_db->query($sql);
$retorno = $this->_db->fetchRow();
// echo '<pre>'; print_r($retorno);
if ($retorno!=false){
$paciente = new Paciente($retorno);
// echo '<pre>'; print_r($paciente);
}
return $paciente;
}
/**
* Obtiene algunos pacientes
* @return Resource
*/
public function getAlgunosPacientes($inicio, $fin, $orden, $filtro, $campos = array('*'))
{
// require_once BASE_PATH . 'Modulos' . DS . 'Paciente' . DS . 'Modelos' . DS . 'Paciente.php';
$this->_verEliminados = 0;
$sql = new Sql();
$sql->addCampos($campos);
$sql->addFuncion('Select');
$sql->addTable('cronos_pacientes AS pacientes');
$sql->addOrder($orden);
$sql->addWhere("pacientes.eliminado=$this->_verEliminados");
if ($filtro != '') {
$sql->addWhere($filtro);
}
if ($fin > 0) {
$sql->addLimit($inicio, $fin);
}
$this->_db->setTipoDatos('Array');
$this->_db->query($sql);
$lista = $this->_db->fetchall();
if(is_array($lista)){
foreach ($lista as $pac) {
$pacientes[] = new Paciente_Modelos_Paciente($pac);
}
}
return $pacientes;
}
}
| true |
82832b985bff5a675fbb550365a4a4e18ca83323 | PHP | kheniparth/SwiftMealOrderSystem | /items/ingredient.php | UTF-8 | 2,942 | 3.046875 | 3 | [] | no_license | <?php
session_start();
include_once '../dbconfig.php';
//get all ingredients from the database
function getAllIngredients(){
$result = [];
try{
//get global database connection
global $db_con;
//create and execute select query
$stmt = $db_con->prepare("SELECT * FROM Item_master WHERE Cust_id=:uid");
$stmt->execute(array(":uid"=>$_SESSION['user_session']));
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
//attach fetched data to result array
$result[] = $row;
}
//print JSON output of result array
echo json_encode($result);
}
catch(PDOException $e){
//print exception error message
echo $e->getMessage();
}
}
//add an ingredient in the database
function addIngredient(){
//check if ingredient name is set or not
if(isset($_POST['ingredientname'])){
$name = $_POST['ingredientname'];
}
//create item array for prepared statement
$item = array(":name" => $name, ":uid" => $_SESSION['user_session']);
try{
//get global database connection object
global $db_con;
//create and execute insert query
$stmt = $db_con->prepare("INSERT INTO Item_master (Item_name, Cust_id) VALUES (:name, :uid)");
if($stmt->execute($item)){
//print ok if query gets executed successfully
echo 'ok';
}
}
catch(PDOException $e){
//print exception error message
echo $e->getMessage();
}
}
//this function deletes an ingredient in the database
function deleteIngredient(){
//check if item id is set or not
if(isset($_POST['item_id'])){
$id = $_POST['item_id'];
}
//create item array for prepared statement
$item = array(":uid" => $_SESSION['user_session'], ":id"=>$id);
try{
//get global database connection object
global $db_con;
//create and execute delete query
$stmt = $db_con->prepare("DELETE FROM Item_master WHERE Item_id = :id AND Cust_id=:uid");
if($stmt->execute($item)){
//print ok if query gets executed
echo 'ok';
}
}
catch(PDOException $e){
//print exception error message
echo $e->getMessage();
}
}
//check session whether is set or not
if(!isset($_SESSION['user_session'])){
//navigate user to login page
header("Location: http:techmuzz.com/smos/login/index.php");
}else{
//check if function data is set or not
if(isset($_POST['function'])){
$function = $_POST['function'];
//call respective funtion from value of function variable
switch ($function) {
case 'getAllIngredients':
getAllIngredients();
break;
case 'addIngredient':
addIngredient();
break;
case 'deleteIngredient':
deleteIngredient();
break;
default:
printData();
break;
}
}
}
?>
| true |
51ecca0e8b24692ea35910a8c2a343de9d529c9b | PHP | alari/ring | /Apps/Ring/Ctr/Tpl/Admin/User.phps | UTF-8 | 2,776 | 2.5625 | 3 | [] | no_license | <?php
class R_Ctr_Tpl_Admin_User extends R_Ctr_Template {
/**
* Form with editable user fields
*
* @var O_Form_Handler
*/
public $form;
/**
* Current user
*
* @var R_Mdl_User
*/
public $user;
/**
* Query with available user roles
*
* @var O_Dao_Query
*/
public $roles;
public function displayContents()
{
if ($this->user) {
$isOur = $this->user->isOurUser();
$role = $this->user->role;
} else {
$isOur = -1;
$role = O_Acl_Role::getByName( "OpenId User" );
}
?>
<form method="POST">
<fieldset><legend>Основные параметры пользователя</legend>
<table>
<tr>
<td>OpenId:</td>
<td>
<?
if ($this->user)
echo $this->user->identity;
else {
?>
<input type="text" name="identity" value="" /><?
}
?></td>
</tr>
<?
if ($isOur) {
?>
<tr>
<td>Пароль:</td>
<td><input type="password" name="pwd" /></td>
</tr>
<?
if (!$this->user) {
?><tr>
<td colspan="2">Вводить только для наших пользователей. Автоматически
будет создан сайт.</td>
</tr>
<?
} else {
?>
<tr>
<td>Адрес сайта:</td>
<td><a href="<?=$this->user->url()?>"><?=$this->user->identity?></a><?
if ($this->user->site) {
?> (<a href="<?=$this->user->site->url( "Admin/Site" )?>">настройки</a>)<?
}
?></td>
</tr>
<?
}
?>
<?
}
?>
<tr>
<td>Роль:</td>
<td><select name="role">
<?
foreach ($this->roles as $r) {
?>
<option value="<?=$r->id?>"
<?=($r->id == $role->id ? ' selected="yes"' : "")?>><?=$r->name?></option>
<?
}
?>
</select></td>
</tr>
<tr>
<th colspan="2"><input type="submit" value="Сохранить" /></th>
</tr>
</table>
<?
if ($this->user) {
?><input type="hidden" name="id" value="<?=$this->user->id?>" /><input
type="hidden" name="action" value="edit" /><?
} else {
?>
<input type="hidden" name="action" value="create" />
<?
}
?>
</fieldset>
</form>
<?
if ($this->form) {
$this->form->render( $this->layout() );
}
if ($this->user) {
?>
<form method="post"
onsubmit="return (confirm('Требуется подтверждение. Вся связанная с пользователем информация будет удалена!') && prompt('Введите в поле 12354')==12354)">
<fieldset><legend>Удаление пользователя</legend>
<center><input type="submit" value="Удалить" /><input type="hidden"
name="action" value="delete" /><input type="hidden" name="id"
value="<?=$this->user->id?>" /></center>
</fieldset>
</form><?
}
}
} | true |
b866f484da0efc543154cd007d627f309d354527 | PHP | cwinchell2883/winchelldesign.com | /minimizer/user3/inc/func.form.php | UTF-8 | 2,696 | 2.953125 | 3 | [] | no_license | <?php
####
## Manufacturing Database
## (c) http://winchelldesign.com
## Developed By: Chris Winchell
##
##
## File: func.form.php
## Created: 9-17-2010
## Updated: --
####
function html_selectbox($name, $values, $selected=NULL, $attributes=array())
{
$attr_html = '';
if(is_array($attributes) && !empty($attributes))
{
foreach ($attributes as $k=>$v)
{
$attr_html .= ' '.$k.'="'.$v.'"';
}
}
$output = '<select name="'.$name.'" id="'.$name.'"'.$attr_html.'>'."\n";
if(is_array($values) && !empty($values))
{
foreach ($values as $key=>$value)
{
if(is_array($value))
{
$output .= '<optgroup label="'.$key.'">'."\n";
foreach ($value as $k=>$v)
{
$sel = $selected == $k ? ' selected="selected"' : '';
$output .= '<option value="'.$k.'"'.$sel.'>'.$v.'</option>'."\n";
}
$output .= '</optgroup>'."\n";
}
else
{
$sel = $selected == $key ? ' selected="selected"' : '';
$output .= '<option value="'.$key.'"'.$sel.'>'.$value.'</option>'."\n";
}
}
}
$output .= "</select>\n";
return $output;
}
function numlist_gen($name, $count, $limit)
{
$output = '<select name="'.$name.'" id="'.$name.'">\n"';
if($limit > $count || $limit == NULL)
{
$limit = $count;
}
$low = ($count-$limit);
while ($low <= ($count+$limit))
{
$output .= '<option value="'.$low.'">'.$low.'</option>'."\n";
++$low;
}
$output .= "</select>\n";
return $output;
}
function html_textbox($name, $size, $value=NULL, $attributes=array())
{
$attr_html = '';
if(is_array($attributes) && !empty($attributes))
{
foreach ($attributes as $k=>$v)
{
$attr_html .= ' '.$k.'="'.$v.'"';
}
}
if($size == NULL)
{
$size = 5;
}
$output = '<input name="'.$name.'" id="'.$name.'" type="text" size="'.$size.'" maxlength="'.$size.'" value="'.$value.'"'.$attr_html." />";
return $output;
}
function html_pickbox($name, $type, $value=NULL, $attributes=array())
{
$attr_html = '';
if(is_array($attributes) && !empty($attributes))
{
foreach ($attributes as $k=>$v)
{
$attr_html .= ' '.$k.'="'.$v.'"';
}
}
if($type == 'radio' || $type == 'checkbox' || $type == 'submit')
{
$output = '<input name="'.$name.'" id="'.$name.'" type="'.$type.'" value="'.$value.'"'.$attr_html." />";
if($value == NULL)
{
die('Pickbox Error');
}
}
else
{
die('Pickbox Type must be either checkbox or radio');
}
return $output;
}
?> | true |
dc7efe8cbd2ff852ef58999e3e8b563e38dd7961 | PHP | ikram220999/Boling-club-membership-system | /boling/q4b.php | UTF-8 | 399 | 3.421875 | 3 | [] | no_license | <?php
$text = " How can I cook rice in a clean round pot? ";
echo strlen ($text). "<br>";
$text = trim ($text);
echo $text ."<br>";
echo strtoupper ($text). "<br>";
echo strtolower ($text) . "<br>";
$text = str_replace ("can", "round", $text);
echo $text . "<br>";
echo substr ($text, 2, 6). "<br>";
var_dump (strpos ($text, "can"));
echo "<br>" ;
var_dump (strpos ($text, "could"));
?> | true |
08f94486332331ebbafa955503d0c2a68ea5be28 | PHP | inphinit/framework | /src/Inphinit/Dom/Document.php | UTF-8 | 13,947 | 2.75 | 3 | [
"MIT"
] | permissive | <?php
/*
* Inphinit
*
* Copyright (c) 2023 Guilherme Nascimento (brcontainer@yahoo.com.br)
*
* Released under the MIT license
*/
namespace Inphinit\Dom;
use Inphinit\Helper;
use Inphinit\Storage;
class Document extends \DOMDocument
{
private $xpath;
private $selector;
private $internalErr;
private $exceptionlevel = 3;
private $complete = false;
private $simple = false;
/**
* Used with `Document::reporting` method or in extended classes
*
* @var array
*/
protected $levels = array(\LIBXML_ERR_WARNING, \LIBXML_ERR_ERROR, \LIBXML_ERR_FATAL);
/** Used with `Document::save` method to save document in XML format */
const XML = 1;
/** Used with `Document::save` method to save document in HTML format */
const HTML = 2;
/** Used with `Document::save` method to convert and save document in JSON format */
const JSON = 3;
/** Used with `Document::toArray` method to convert document in a simple array */
const SIMPLE = 4;
/** Used with `Document::toArray` method to convert document in a minimal array */
const MINIMAL = 5;
/** Used with `Document::toArray` method to convert document in a array with all properties */
const COMPLETE = 6;
/**
* Create a Document instance
*
* @param string $version The version number of the document as part of the XML declaration
* @param string $encoding The encoding of the document as part of the XML declaration
* @return void
*/
public function __construct($version = '1.0', $encoding = 'UTF-8')
{
parent::__construct($version, $encoding);
}
/**
* Set level error for exception, set `LIBXML_ERR_NONE` (or `0` - zero) for disable exceptions.
* For disable only warnings use like this `$dom->reporting(LIBXML_ERR_FATAL, LIBXML_ERR_ERROR)`
*
* <ul>
* <li>0 - `LIBXML_ERR_NONE` - Disable errors</li>
* <li>1 - `LIBXML_ERR_WARNING` - Show warnings in DOM</li>
* <li>2 - `LIBXML_ERR_ERROR` - Show recoverable errors in DOM</li>
* <li>3 - `LIBXML_ERR_FATAL` - Show DOM fatal errors</li>
* </ul>
*
* @param int $args,...
* @return void
*/
public function reporting()
{
$this->levels = func_get_args();
}
/**
* Convert a array in node elements
*
* @param array|\Traversable $data
* @throws \Inphinit\Dom\DomException
* @return void
*/
public function fromArray(array $data)
{
if (empty($data)) {
throw new DomException('Array is empty', 2);
} elseif (count($data) > 1) {
throw new DomException('Root array accepts only a key', 2);
}
$root = key($data);
if (self::validTag($root) === false) {
throw new DomException('Invalid root <' . $root . '> tag', 2);
}
if ($this->documentElement) {
$this->removeChild($this->documentElement);
}
$this->enableRestoreInternal(true);
$this->generate($this, $data, 2);
$this->raise($this->exceptionlevel);
$this->enableRestoreInternal(false);
}
/**
* Convert DOM to JSON string
*
* @param bool $format
* @param int $options `JSON_HEX_QUOT`, `JSON_HEX_TAG`, `JSON_HEX_AMP`, `JSON_HEX_APOS`, `JSON_NUMERIC_CHECK`, `JSON_PRETTY_PRINT`, `JSON_UNESCAPED_SLASHES`, `JSON_FORCE_OBJECT`, `JSON_PRESERVE_ZERO_FRACTION`, `JSON_UNESCAPED_UNICODE`, `JSON_PARTIAL_OUTPUT_ON_ERROR`. The behaviour of these constants is described in http://php.net/manual/en/json.constants.php
*
* @return string
*/
public function toJson($format = Document::MINIMAL, $options = 0)
{
$this->exceptionlevel = 4;
$json = json_encode($this->toArray($format), $options);
$this->exceptionlevel = 3;
return $json;
}
/**
* Convert DOM to Array
*
* @param int $type
* @throws \Inphinit\Dom\DomException
* @return array
*/
public function toArray($type = Document::SIMPLE)
{
switch ($type) {
case Document::MINIMAL:
$this->simple = false;
$this->complete = false;
break;
case Document::SIMPLE:
$this->simple = true;
break;
case Document::COMPLETE:
$this->complete = true;
break;
default:
throw new DomException('Invalid type', 2);
}
return $this->getNodes($this->childNodes);
}
/**
* Magic method, return a well-formed XML string
*
* Example:
* <pre>
* <code>
* $xml = new Dom;
*
* $xml->fromArray(array(
* 'foo' => 'bar'
* ));
*
* echo $xml;
* </code>
* </pre>
*
* @return string
*/
public function __toString()
{
return $this->saveXML();
}
/**
* Save file to location
*
* @param string $path
* @param int $format Support XML, HTML, and JSON
* @throws \Inphinit\Dom\DomException
* @return void
*/
#[\ReturnTypeWillChange]
public function save($path, $format = Document::XML)
{
switch ($format) {
case Document::XML:
$format = 'saveXML';
break;
case Document::HTML:
$format = 'saveHTML';
break;
case Document::JSON:
$format = 'toJson';
break;
default:
throw new DomException('Invalid format', 2);
}
if (Storage::createFolder('tmp/dom')) {
$tmp = Storage::temp($this->$format(), 'tmp/dom');
} else {
$tmp = false;
}
if ($tmp === false) {
throw new DomException('Can\'t create tmp file', 2);
} elseif (copy($tmp, $path) === false) {
throw new DomException('Can\'t copy tmp file to ' . $path, 2);
} else {
unlink($tmp);
}
}
/**
* Get namespace attributes from root element or specific element
*
* @param \DOMElement $element
* @return void
*/
public function getNamespaces(\DOMElement $element = null)
{
if ($this->xpath === null) {
$this->xpath = new \DOMXPath($this);
}
if ($element === null) {
$nodes = $this->xpath->query('namespace::*');
$element = $this->documentElement;
} else {
$nodes = $this->xpath->query('namespace::*', $element);
}
$ns = array();
if ($nodes) {
foreach ($nodes as $node) {
$arr = $element->getAttribute($node->nodeName);
if ($arr) {
$ns[$node->nodeName] = $arr;
}
}
$nodes = null;
}
return $ns;
}
/**
* Load XML from a string
*
* @param string $source
* @param int $options
* @throws \Inphinit\Dom\DomException
* @return mixed
*/
public function loadXML($source, $options = 0)
{
return $this->resource('loadXML', $source, $options);
}
/**
* Load XML from a file
*
* @param string $filename
* @param int $options
* @throws \Inphinit\Dom\DomException
* @return mixed
*/
public function load($filename, $options = 0)
{
return $this->resource('load', $filename, $options);
}
/**
* Load HTML from a string
*
* @param string $source
* @param int $options
* @throws \Inphinit\Dom\DomException
* @return mixed
*/
public function loadHTML($source, $options = 0)
{
return $this->resource('loadHTML', $source, $options);
}
/**
* Load HTML from a file
*
* @param string $filename
* @param int $options
* @throws \Inphinit\Dom\DomException
* @return mixed
*/
public function loadHTMLFile($filename, $options = 0)
{
return $this->resource('loadHTMLFile', $filename, $options);
}
/**
* Use query-selector like CSS, jQuery, querySelectorAll
*
* @param string $selector
* @param \DOMNode $context
* @return \DOMNodeList
*/
public function query($selector, \DOMNode $context = null)
{
$this->enableRestoreInternal(true);
if ($this->selector === null) {
$this->selector = new Selector($this);
}
$nodes = $this->selector->get($selector, $context);
$level = $this->exceptionlevel;
$this->exceptionlevel = 3;
$this->raise($level);
$this->enableRestoreInternal(false);
return $nodes;
}
/**
* Use query-selector like CSS, jQuery, querySelector
*
* @param string $selector
* @param \DOMNode $context
* @return \DOMNode
*/
public function first($selector, \DOMNode $context = null)
{
$this->exceptionlevel = 4;
$nodes = $this->query($selector, $context);
$node = $nodes ? $nodes->item(0) : null;
$nodes = null;
return $node;
}
private function resource($function, $from, $options)
{
$this->enableRestoreInternal(true);
$resource = PHP_VERSION_ID >= 50400 ? parent::$function($from, $options) : parent::$function($from);
$this->raise(4);
$this->enableRestoreInternal(false);
return $resource;
}
private function enableRestoreInternal($enable)
{
\libxml_clear_errors();
if ($enable) {
$this->internalErr = \libxml_use_internal_errors(true);
} else {
\libxml_use_internal_errors($this->internalErr);
}
}
private function raise($debuglvl)
{
$err = \libxml_get_errors();
if (isset($err[0]->level) && in_array($err[0]->level, $this->levels, true)) {
throw new DomException(null, $debuglvl);
}
\libxml_clear_errors();
}
private function generate(\DOMNode $node, $data, $errorLevel)
{
if (is_array($data) === false) {
$node->textContent = $data;
return;
}
$nextLevel = $errorLevel + 1;
foreach ($data as $key => $value) {
if ($key === '@comments') {
continue;
} elseif ($key === '@contents') {
$this->generate($node, $value, $nextLevel);
} elseif ($key === '@attributes') {
self::setAttributes($node, $value);
} elseif (self::validTag($key)) {
if (Helper::seq($value)) {
foreach ($value as $subvalue) {
$this->generate($node, array($key => $subvalue), $nextLevel);
}
} elseif (is_array($value)) {
$this->generate($this->add($key, '', $node), $value, $nextLevel);
} else {
$this->add($key, $value, $node);
}
} else {
throw new DomException('Invalid tag: <' . $key . '>', $nextLevel);
}
}
}
private static function validTag($tagName)
{
return preg_match('#^([a-z_](\w+|)|[a-z_](\w+|):[a-z_](\w+|))$#i', $tagName) > 0;
}
private function add($name, $value, \DOMNode $node)
{
$newdom = $this->createElement($name, $value);
$node->appendChild($newdom);
return $newdom;
}
private static function setAttributes(\DOMNode $node, array &$attributes)
{
foreach ($attributes as $name => $value) {
$node->setAttribute($name, $value);
}
}
private function getNodes($nodes)
{
$items = array();
if ($nodes) {
foreach ($nodes as $node) {
if ($node->nodeType === \XML_ELEMENT_NODE && ($this->complete || $this->simple || ctype_alnum($node->nodeName))) {
$items[$node->nodeName][] = $this->nodeContents($node);
}
}
if (empty($items) === false) {
self::simplify($items);
}
}
return $items;
}
private function nodeContents(\DOMElement $node)
{
$extras = array( '@attributes' => array() );
if ($this->complete) {
foreach ($node->attributes as $attribute) {
$extras['@attributes'][$attribute->nodeName] = $attribute->nodeValue;
}
}
if ($this->complete && ($ns = $this->getNamespaces($node))) {
$extras['@attributes'] = $extras['@attributes'] + $ns;
}
if ($node->getElementsByTagName('*')->length) {
$r = $this->getNodes($node->childNodes) + (
empty($extras['@attributes']) ? array() : $extras
);
} elseif (empty($extras['@attributes'])) {
return $node->nodeValue;
} else {
$r = array($node->nodeValue) + $extras;
}
self::simplify($r);
return $r;
}
private static function simplify(&$items)
{
if (self::toContents($items)) {
foreach ($items as $name => &$item) {
if (is_array($item) === false || strpos($name, '@') !== false) {
continue;
}
if (count($item) === 1 && isset($item[0])) {
$item = $item[0];
} else {
self::toContents($item);
}
}
}
}
private static function toContents(&$item)
{
if (count($item) > 1 && isset($item[0]) && isset($item[1]) === false) {
$item['@contents'] = $item[0];
unset($item[0]);
return false;
}
return true;
}
}
| true |
b75e0794703b1a04292f67e52ac41f8046e79aaa | PHP | devcopas/session | /shoping-cart/cart.php | UTF-8 | 1,471 | 2.9375 | 3 | [] | no_license | <?php
session_start();
include 'connection.php';
$cart = isset($_SESSION['cart']) ? $_SESSION['cart'] : [];
$totalItem = 0;
foreach ($cart as $item) {
$totalItem += $item['quantity'];
}
?>
<html>
<head>
<title>Shopping Cart - Cart</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<nav class="main-menu">
<a href="list.php">list</a>
<a href="#" class="active">Cart (<?= $totalItem; ?>)</a>
</nav>
<div class="content">
<table>
<tr>
<th>Product</th>
<th>Price</th>
<th class="text-center">Qty</th>
<th class="text-right">Sub Total</th>
</tr>
<?php
$grandTotal = 0;
foreach ($cart as $row) :
$pdo = $db->prepare('SELECT * FROM product WHERE id = :product_id');
$data['product_id'] = $row['id'];
$pdo->execute($data);
$product = $pdo->fetch(PDO::FETCH_ASSOC);
$total = $product['price'] * $row['quantity'];
$grandTotal += $total;
?>
<tr>
<td><?= $product['title']; ?></td>
<td><?= number_format($product['price']); ?></td>
<td class="text-center"><?= $row['quantity']; ?></td>
<td class="text-right"><?= number_format($total); ?></td>
</tr>
<?php endforeach; ?>
<tr style="border-bottom: unset;">
<th colspan="3" class="text-right">Grand Total</th>
<td class="text-right"><?= number_format($grandTotal); ?></td>
</tr>
</table>
</div>
</div>
</body>
</html> | true |
7a263d58120ae6970e08f2ea4f78ba25a6618fdf | PHP | IssamSisbane/GestionfestivalcannesPHP | /Modele/MembreJuryManager.php | UTF-8 | 4,325 | 2.859375 | 3 | [] | no_license | <?php
class MembreJuryManager extends Model
{
/**
* Ajoute en base de données l'objet passé en paramètre
* @param MembreJury $MembreJury
*/
public function ajouterMembreJury(MembreJury $MembreJury)
{
$req = $this->getBdd()->prepare("INSERT INTO `membre_jury`(`id`, `nom`, `prenom`, `dateNaissance`, `serviceHebergement`, `id_jury`) VALUES (?,?,?,?,?,?)");
$req->execute(array($MembreJury->get_id(),
$MembreJury->get_nom(),
$MembreJury->get_prenom(),
$MembreJury->get_dateNaissance(),
$MembreJury->get_serviceHebergement(),
$MembreJury->get_id_jury(),
));
}
/**
* Modifie en base de données l'objet passé en paramètre
*/
public function modifierMembreJury(MembreJury $MembreJury)
{
$req = $this->getBdd()->prepare("UPDATE `membre_jury` SET `nom`=?,`prenom`=?,`dateNaissance`=?,`serviceHebergement`=?,`id_jury`=? WHERE id=?");
$req->execute(array($MembreJury->get_nom(),
$MembreJury->get_prenom(),
$MembreJury->get_dateNaissance(),
$MembreJury->get_serviceHebergement(),
$MembreJury->get_id_jury(),
$MembreJury->get_id()
));
}
/**
* Supprimer le Membre du jury designé par son id
* @param int $vipId
*/
public function supprimer($idVip)
{
return $this->delete('membre_jury',$idVip);
}
/**
* Renvoi l'id le plus grand de la table
* @return int id maximum
*/
public function recupereMaxId()
{
return $this->getGreaterId('membre_jury');
}
/**
* Renvoi un tableau qui contient tous les objets competitions
* @return array Objets Competition
*/
public function recupererToutesLesCompetitions()
{
return $this->getAll('competition','Competition');
}
/**
* Renvoi le libelle de la Competition en fonction de l'id du jury
* @param int $idJury
* @return string libelle
*/
public function recupererLibelleCompetition(int $idJury)
{
$req = $this->getBdd()->prepare("SELECT libelle FROM competition join jury on jury.id_competition = competition.id WHERE jury.id = ?");
$req->execute(array($idJury));
$result = $req->fetch();
return $result['libelle'];
}
/**
* Renvoi l'id du jury en fonction du nom de la competition
* @param string $LibelleCompetition
* @return int id
*/
public function recupererIdJury(string $LibelleCompetition)
{
$req = $this->getBdd()->prepare("SELECT jury.id as id FROM jury join competition on competition.id = jury.id_competition WHERE libelle = ?");
$req->execute(array($LibelleCompetition));
$result = $req->fetch();
var_dump($result);
return $result['id'];
}
/**
* Renvoi le nombre de membre d'un jury selon la competition
* @param string $LibelleCompetition
* @return int nb
*/
public function recupererNombreDeMembre(string $LibelleCompetition)
{
$req = $this->getBdd()->prepare("SELECT count(*) as nb from membre_jury
join jury on jury.id = membre_jury.id_jury
join competition on competition.id = jury.id_competition
where competition.libelle = ?");
$req->execute(array($LibelleCompetition));
$result = $req->fetch();
var_dump($result);
return $result['nb'];
}
/**
* Renvoi le nombre de membre maximum d'un jury selon la competition
* @param string $libelleCompetition
* @return int nb
*/
public function recupererNombreDeMembreMax(string $LibelleCompetition)
{
$req = $this->getBdd()->prepare("SELECT jury.nombre_membre as nb from jury JOIN competition on competition.id = jury.id_competition where competition.libelle = ?");
$req->execute(array($LibelleCompetition));
$result = $req->fetch();
var_dump($result);
return $result['nb'];
}
} | true |
2216ed82cf51a5e0aa5138814b8e078e67532ce8 | PHP | redakasbi/PFE | /etudiant.php | UTF-8 | 318 | 2.546875 | 3 | [] | no_license | <?php
echo"espace d'etudiant";
session_start();
// On appelle la session
// On affiche une phrase résumant les infos sur l'utilisateur courant
echo 'Pseudo : ',$_SESSION['Nom'],'<br />
Age : ',$_SESSION['Prenom'],'<br />
Sexe : ',$_SESSION['DateN'],'<br />
Ville : ',$_SESSION['Email'],'<br />';
?> | true |
382ad2aaaba4b3e910cc8a9bef4fa730495c94f2 | PHP | exesser/cms-bundle | /Api/V8_Custom/Service/EventDispatcher.php | UTF-8 | 2,944 | 2.640625 | 3 | [] | no_license | <?php
namespace ExEss\Bundle\CmsBundle\Api\V8_Custom\Service;
use Psr\Container\ContainerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* extend the symfony event dispatcher and add lazy initialization of event subscribers
*/
class EventDispatcher extends \Symfony\Component\EventDispatcher\EventDispatcher
{
protected ContainerInterface $container;
/**
* @var string[]
*/
protected array $lazySubscribers = [];
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
protected function initializeLazySubscribers(?string $eventName = null): void
{
if (!\count($this->lazySubscribers)) {
return;
}
$lazySubscribers = $this->lazySubscribers;
$this->lazySubscribers = [];
while (\count($lazySubscribers)) {
$service = \array_shift($lazySubscribers);
// if an event name was given, only add the subscribers that have events listening to this event
if (!$eventName
|| !\class_exists($service)
|| !$service instanceof EventSubscriberInterface
|| \array_key_exists($eventName, $service::getSubscribedEvents())
) {
$this->addSubscriber($this->container->get($service));
} else {
$this->lazySubscribers[] = $service;
}
}
}
public function addLazySubscriber(string $serviceName): void
{
$this->lazySubscribers[] = $serviceName;
}
/**
* @inheritdoc
*/
public function dispatch(object $event, ?string $eventName = null): object
{
$eventName = $eventName ?? \get_class($event);
$this->initializeLazySubscribers($eventName);
return parent::dispatch($event, $eventName);
}
/**
* @inheritdoc
*/
public function getListeners($eventName = null)
{
$this->initializeLazySubscribers($eventName);
return parent::getListeners($eventName);
}
/**
* @inheritdoc
*/
public function getListenerPriority($eventName, $listener)
{
$this->initializeLazySubscribers($eventName);
return parent::getListenerPriority($eventName, $listener);
}
/**
* @inheritdoc
*/
public function hasListeners($eventName = null)
{
$this->initializeLazySubscribers($eventName);
return parent::hasListeners($eventName);
}
/**
* @inheritdoc
*/
public function removeListener($eventName, $listener)
{
$this->initializeLazySubscribers($eventName);
parent::removeListener($eventName, $listener);
}
/**
* @inheritdoc
*/
public function removeSubscriber(EventSubscriberInterface $subscriber)
{
$this->initializeLazySubscribers();
parent::removeSubscriber($subscriber);
}
}
| true |
da71a12a54bb62ec206f2b8409e76db29ea81a3e | PHP | richtermarkbaay/MEDTrip | /src/HealthCareAbroad/SearchBundle/Services/SearchParameterBag.php | UTF-8 | 6,830 | 2.609375 | 3 | [
"MIT"
] | permissive | <?php
namespace HealthCareAbroad\SearchBundle\Services;
use Symfony\Component\HttpFoundation\ParameterBag;
//TODO: clean up
/**
* The behavior of this class differs from ParameterBag in that it
* only allows a defined group of parameter names to be set.
* This adds special processing and transformation of the passed in parameters.
*
* It will also disable several inherited functions.
*
*/
class SearchParameterBag extends ParameterBag
{
const SEARCH_TYPE_DESTINATIONS = 1;
const SEARCH_TYPE_TREATMENTS = 2;
const SEARCH_TYPE_COMBINATION = 3;
const FILTER_COUNTRY = 'country';
const FILTER_CITY = 'city';
const FILTER_SPECIALIZATION = 'specialization';
const FILTER_SUBSPECIALIZATION = 'subSpecialization';
const FILTER_TREATMENT = 'treatment';
/**
* Constructor.
*
* @param array $parameters An array of parameters
*
* @api
*/
public function __construct(array $parameters = array())
{
if (!empty($parameters)) {
$searchedTerm = null;
$treatment = null;
$destination = null;
$treatmentLabel = '';
$destinationLabel = '';
$filter = '';
// Allow only these keys
foreach ($parameters as $key => $value) {
if ('treatment' === $key) {
$treatment = $value;
} else if ('destination' === $key) {
$destination = $value;
} else if ('term' === $key) {
$searchedTerm = $value;
} else if ('treatmentLabel' === $key) {
$treatmentLabel = $parameters['treatmentLabel'];
} else if ('destinationLabel' === $key) {
$destinationLabel = $parameters['destinationLabel'];
} else if ('filter' === $key) {
$filter = $parameters['filter'];
} else {
throw new \Exception('Invalid parameter: ' . $key);
}
}
$this->parameters = $this->processParameters($treatment, $treatmentLabel, $destination, $destinationLabel, $searchedTerm, $filter);
}
}
private function processParameters($treatment, $treatmentLabel, $destination, $destinationLabel, $searchedTerm, $filter)
{
$context = '';
$countryId = 0;
$cityId = 0;
$treatmentType = '';
if (!empty($destination)) {
list($countryId, $cityId) = explode('-', $destination);
}
if (!is_numeric($cityId) && !is_numeric($countryId) && !is_numeric($treatment)) {
throw new \Exception('Invalid id');
}
if ($searchedTerm) {
//TODO: first condition is not enough
if ($treatmentLabel && $destinationLabel) {
$context = self::SEARCH_TYPE_COMBINATION;
} elseif ($treatmentLabel === $searchedTerm || ($countryId || $cityId)) {
$context = self::SEARCH_TYPE_TREATMENTS;
} elseif ($destinationLabel === $searchedTerm || ($treatment)) {
$context = self::SEARCH_TYPE_DESTINATIONS;
}
} else {
if ($countryId || $cityId) {
$context = $context | self::SEARCH_TYPE_DESTINATIONS;
}
if ($treatment) {
$context = $context | self::SEARCH_TYPE_TREATMENTS;
}
if (!$context) {
if ($treatmentLabel && $destinationLabel) {
$context = self::SEARCH_TYPE_COMBINATION;
} elseif ($treatmentLabel) {
$context = self::SEARCH_TYPE_TREATMENTS;
} elseif ($destinationLabel) {
$context = self::SEARCH_TYPE_DESTINATIONS;
}
}
}
return array(
'searchedTerm' => $searchedTerm,
'context' => $context,
'cityId' => $cityId,
'countryId' => $countryId,
'treatmentId' => $treatment,
'treatmentType' => $treatmentType,
'treatmentParameter' => $treatment,
'destinationParameter' => $destination,
'treatmentLabel' => $treatmentLabel,
'destinationLabel' => $destinationLabel,
'filter' => $filter
);
}
//TODO: not used
public function getDynamicRouteParams($doctrine = null)
{
$routeParams = array('countryId' => $this->parameters['countryId'], 'cityId' => $this->parameters['cityId']);
if ($this->parameters['context'] == self::SEARCH_TYPE_TREATMENTS || $this->parameters['context'] == self::SEARCH_TYPE_COMBINATION) {
if (is_null($doctrine)) {
throw new \Exception('Doctrine is required.');
}
$connection = $doctrine->getConnection();
// This should only return one row??? or we shouldn't be here if there are more than one type
$sql = "SELECT * FROM search_terms WHERE term_id = :termId GROUP BY type";
$stmt = $connection->prepare($sql);
$stmt->bindValue('termId', $this->parameters['treatmentId']);
$stmt->execute();
$result = $stmt->fetchAll(\PDO::FETCH_ASSOC);
$result = $result[0];
$routeParams = array_merge($routeParams, array(
'specializationId' => $result['specialization_id'],
'subSpecializationId' => $result['sub_specialization_id'],
'treatmentId' => $result['treatment_id']
));
}
return $routeParams;
}
////////////////////////////////////////////
// The following functions have been disabled
////////////////////////////////////////////
/**
* (non-PHPdoc)
* @see \Symfony\Component\HttpFoundation\ParameterBag::replace()
*/
public function replace(array $parameters = array())
{
throw new \Exception('Method disabled.');
}
/**
* (non-PHPdoc)
* @see \Symfony\Component\HttpFoundation\ParameterBag::add()
*/
public function add(array $parameters = array())
{
throw new \Exception('Method disabled.');
}
/**
* (non-PHPdoc)
* @see \Symfony\Component\HttpFoundation\ParameterBag::set()
*/
//TODO: temporarily enable this
// public function set($key, $value)
// {
// throw new \Exception('Method disabled.');
// }
/**
* (non-PHPdoc)
* @see \Symfony\Component\HttpFoundation\ParameterBag::remove()
*/
public function remove($key)
{
throw new \Exception('Method disabled.');
}
} | true |
2ff647e8ba28c6160bbb80302db59c49494a3678 | PHP | evgenyvmi/simple-blog-codeigniter | /application/controllers/blog.php | UTF-8 | 1,909 | 2.546875 | 3 | [
"MIT"
] | permissive | <?php
class Blog extends CI_Controller{
public function index()
{
$data['title'] = 'Posts';
$data['users'] = $this->user_model->get_users();
$data['posts'] = $this->blog_model->get_posts();
$this->load->view('templates/header');
$this->load->view('blog/index', $data);
$this->load->view('templates/footer');
}
public function show($slug= NULL)
{
$data['post'] = $this->blog_model->get_posts($slug);
$data['title'] = $data['post']['title'];
$this->load->view('templates/header');
$this->load->view('blog/show', $data);
$this->load->view('templates/footer');
}
public function create() {
// Check login
//if(!$this->session->userdata('logged_in')){
// redirect('users/login');
//}
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('text', 'Text', 'required');
$data['title'] = 'Create Post';
if($this->form_validation->run() === FAlSE){
$this->load->view('templates/header');
$this->load->view('blog/create', $data);
$this->load->view('templates/footer');
} else {
$this->blog_model->create_post();
$this->load->view('templates/header');
$this->load->view('blog/success');
$this->load->view('templates/footer');
}
}
public function delete($id){
$this->blog_model->delete_post($id);
redirect('blog');
}
public function edit($slug){
$data['post'] = $this->blog_model->get_posts($slug);
$data['title'] = 'Edit';
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('text', 'Text', 'required');
$this->load->view('templates/header');
$this->load->view('blog/edit', $data);
$this->load->view('templates/footer');
#$this->blog_model->edit_post($id);
#redirect('blog');
}
public function update(){
$this->blog_model->update_post();
redirect('blog');
}
}
| true |
a330a48f68b159798684d767e247153167aea767 | PHP | khavelka20/gamer_kin | /app/Services/YouTubeService.php | UTF-8 | 484 | 2.5625 | 3 | [] | no_license | <?php
namespace App\Services;
use Alaouy\Youtube\Youtube;
class YouTubeService {
private $key = 'AIzaSyDaN4NFxNxBGi011jwSWPmvTN89OUzBM-E';
public function findVideoByName($name) {
$youtube = new Youtube($this->key);
$results = $youtube->searchVideos($name . ' PC gameplay');
return $results[0];
}
public function getVideoInfo($videoId){
$youtube = new Youtube($this->key);
$results = $youtube->getVideoInfo($videoId);
return $results;
}
}
| true |
00367049679f79c82bb9aec4696639b771453bb0 | PHP | MikeLks57/foodtruck | /w/app/Model/IngredientsModel.php | UTF-8 | 1,379 | 2.84375 | 3 | [] | no_license | <?php
namespace Model;
use W\Model\Model;
use W\Model\ConnectionModel;
use PDO;
class IngredientsModel extends Model
{
public function getIngredientsByIdProduct($idProduct)
{
$pdo = ConnectionModel::getDbh();
$sql = 'SELECT ingredients.id as ingredientId, ingredients.name as ingredientName FROM ingredients INNER JOIN ingredients_product ON ingredients_product.id_ingredient = ingredients.id WHERE ingredients_product.id_product = :idProduct';
$ingredients = $pdo->prepare($sql);
$ingredients->bindParam(':idProduct', $idProduct, PDO::PARAM_INT);
$ingredients->execute();
return $ingredients->fetchAll();
}
public function ingredientExists($ingredientName)
{
$pdo = ConnectionModel::getDbh();
$sql = 'SELECT COUNT(name) AS nbName FROM ingredients WHERE name LIKE :ingredientName';
$stmt = $pdo->prepare($sql);
$ingredient = $ingredientName;
$stmt->bindParam(':ingredientName', $ingredient, PDO::PARAM_STR);
$stmt->execute();
$count = $stmt->fetch();
if($count['nbName'] > 0) {
return true;
}
}
public function getIngredientIdByName($ingredientName)
{
$pdo = ConnectionModel::getDbh();
$sql = 'SELECT id FROM ingredients WHERE name LIKE :ingredientName LIMIT 1';
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':ingredientName', $ingredientName, PDO::PARAM_STR);
$stmt->execute();
return $stmt->fetchColumn(0);
}
}
| true |
2cc0a9d8ead960df7109a0ed36af2bdd28d0a63a | PHP | ihsonnet/php-bootstrap-CRUD | /index.php | UTF-8 | 2,175 | 2.671875 | 3 | [] | no_license | <?php
require_once("header.php");
require_once("database.php");
if(isset($_POST['submit'])){
$name = isset($_POST["name"]) ? $_POST["name"] : "";
$email = isset($_POST["email"]) ? $_POST["email"] : "";
$subject = isset($_POST["subject"]) ? $_POST["subject"] : "";
$messege = isset($_POST["messege"]) ? $_POST["messege"] : "";
$query = "INSERT INTO alldata (name,email,subject,messege) VALUES('$name','$email','$subject','$messege')";
$sql = mysqli_query($con, $query);
if($sql){
$insert = "<div class='alert alert-success'>Data Insert Successful!</div>";
}else{
$insert = "<div class='alert alert-warning'>Something Wrong!</div>";
}
}
?>
<div class="container mt-5">
<div class="row">
<?php
if(isset($insert)){
echo $insert;
}
?>
</div>
<div class="row">
<a class="btn btn-primary mb-2" href="table.php">All Data</a>
</div>
<div class="row">
<form method="POST">
<div class="mb-2">
<label for="name">Name</label>
<input name="name" type="text" class="form-control" id="name">
</div>
<div class="mb-2">
<label for="email">Email</label>
<input name="email" type="email" class="form-control" id="email">
</div>
<div class="mb-2">
<label for="subject">Subject</label>
<input name="subject" type="text" class="form-control" id="subject">
</div>
<div class="mb-2">
<label for="messege">Messege</label>
<textarea name="messege" class="form-control" id="messege" cols="30" rows="10"></textarea>
</div>
<div class="mb-2 text-center">
<button name="submit" class="btn btn-outline-secondary">Submit</button>
</div>
</form>
</div>
</div>
<?php
require_once("footer.php");
?> | true |
47ca3cf133ed93717e8b6132031d7568263a8200 | PHP | ripasfilqadar/mppljadi | /cikoro2/application/models/userModel.php | UTF-8 | 797 | 2.5625 | 3 | [] | no_license | <?php
class Usermodel extends CI_Model
{
function Usermodel()
{
parent::__construct();
}
function check($username,$password)
{
try{
$sql = "select * from user where username='".$username."' and password=md5('".$password."')";
$query = $this->db->query($sql);
if($query->result()){
return 1;
}
else{
return false;
}
}
catch(Exception $e){
return false;
}
}
function changepassword($password,$password2)
{
try {
$sql="select * from user where password=md5('$password')";
$query=$this->db->query($sql);
if($query->result()){
$sql="update user set password=md5('$password2')";
$query=$this->db->query($sql);
return "berhasil";
}
else{
return "gagal";
}
}
catch (Exception $e) {
return "gagal";
}
}
} | true |
b45027d4822695662a87b3ad0074bf848840a11b | PHP | jameBruno/platform-client-sdk-php | /lib/Provider/Genesys.php | UTF-8 | 2,642 | 2.53125 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types=1);
namespace PureCloudPlatform\Client\V2\Provider;
use League\OAuth2\Client\Provider\AbstractProvider;
use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
use League\OAuth2\Client\Token\AccessToken;
use League\OAuth2\Client\Tool\BearerAuthorizationTrait;
use Psr\Http\Message\ResponseInterface;
class Genesys extends AbstractProvider
{
use BearerAuthorizationTrait;
const PATH_TOKEN = '/oauth/token';
const PATH_AUTHORIZATION = '/oauth/authorize';
const PATH_ME = '/api/v2/tokens/me';
const DEFAULT_LOGIN_BASE_URL = 'login.mypurecloud.com';
const DEFAULT_API_BASE_URL = 'api.mypurecloud.com';
/**
*
* @var TokenStorageInterface
*/
protected $baseUrl;
/**
*
* {@inheritdoc}
*
* @see \League\OAuth2\Client\Provider\AbstractProvider::getBaseAccessTokenUrl()
*/
public function getBaseAccessTokenUrl(array $params)
{
if(isset($params['baseUrl']))
$this->baseUrl = $params['baseUrl'];
else
$this->baseUrl = self::DEFAULT_LOGIN_BASE_URL;
return 'https://' . $this->baseUrl . self::PATH_TOKEN;
}
/**
*
* {@inheritdoc}
*
* @see \League\OAuth2\Client\Provider\AbstractProvider::getBaseAuthorizationUrl()
*/
public function getBaseAuthorizationUrl()
{
return 'https://' . $this->baseUrl . self::PATH_AUTHORIZATION;
}
/**
*
* {@inheritdoc}
*
* @see \League\OAuth2\Client\Provider\AbstractProvider::getDefaultScopes()
*/
protected function getDefaultScopes()
{
return [];
}
/**
*
* {@inheritdoc}
*
* @see \League\OAuth2\Client\Provider\AbstractProvider::checkResponse()
*/
protected function checkResponse(ResponseInterface $response, $data)
{
if (isset($data['error'])) {
$message = $data['error_description'] ?? $data['error'];
throw new IdentityProviderException($message, $response->getStatusCode(), $response);
}
}
/**
*
* {@inheritDoc}
* @see \League\OAuth2\Client\Provider\AbstractProvider::getResourceOwnerDetailsUrl()
*/
public function getResourceOwnerDetailsUrl(AccessToken $token)
{
return 'https://' . self::DEFAULT_API_BASE_URL . self::PATH_ME;
}
/**
*
* {@inheritdoc}
*
* @see \League\OAuth2\Client\Provider\AbstractProvider::createResourceOwner()
*/
protected function createResourceOwner(array $response, AccessToken $token)
{
return null;
}
} | true |
c64c9da16581b1b27f2bce376088e618e7d54976 | PHP | patrickthibaudeau/selfserve-kiosk | /classes/String.php | UTF-8 | 634 | 3 | 3 | [] | no_license | <?php
namespace kiosk;
/**
* Description of String
*
* @author patrick
*/
class LanguageStrings {
private $folder;
public function __construct($lang = 'en', $file = 'kiosk') {
global $CFG;
if (file_exists($CFG->rootFolder . '/lang/' . $lang . '/' . $file . '.php')) {
$this->folder = $CFG->rootFolder . '/lang/' . $lang . '/' . $file . '.php';
} else {
$this->folder = $CFG->rootFolder . '/lang/en/' . $file . '.php';
}
}
public function getString($name) {
$string = [];
include($this->folder);
return $string["$name"];
}
}
| true |
47d45bcaa55d1d10720e83f4fb0556d000eccfc4 | PHP | juniordrumsrmv/emporium | /module/Application/src/Entity/PromotionPrize.php | UTF-8 | 4,557 | 2.546875 | 3 | [] | no_license | <?php
namespace Application\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* PromotionPrize
*
* @ORM\Table(name="promotion_prize")
* @ORM\Entity
*/
class PromotionPrize
{
/**
* @var integer
*
* @ORM\Column(name="promotion_key", type="bigint", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="NONE")
*/
private $promotionKey;
/**
* @var integer
*
* @ORM\Column(name="store_key", type="bigint", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="NONE")
*/
private $storeKey;
/**
* @var integer
*
* @ORM\Column(name="store_group_key", type="smallint", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="NONE")
*/
private $storeGroupKey = '0';
/**
* @var integer
*
* @ORM\Column(name="initial_number", type="bigint", nullable=false)
*/
private $initialNumber;
/**
* @var integer
*
* @ORM\Column(name="increase", type="bigint", nullable=false)
*/
private $increase;
/**
* @var integer
*
* @ORM\Column(name="quantity", type="bigint", nullable=false)
*/
private $quantity;
/**
* @var string
*
* @ORM\Column(name="amount", type="decimal", precision=15, scale=3, nullable=false)
*/
private $amount;
/**
* @var boolean
*
* @ORM\Column(name="status", type="boolean", nullable=true)
*/
private $status;
/**
* Set promotionKey
*
* @param integer $promotionKey
*
* @return PromotionPrize
*/
public function setPromotionKey($promotionKey)
{
$this->promotionKey = $promotionKey;
return $this;
}
/**
* Get promotionKey
*
* @return integer
*/
public function getPromotionKey()
{
return $this->promotionKey;
}
/**
* Set storeKey
*
* @param integer $storeKey
*
* @return PromotionPrize
*/
public function setStoreKey($storeKey)
{
$this->storeKey = $storeKey;
return $this;
}
/**
* Get storeKey
*
* @return integer
*/
public function getStoreKey()
{
return $this->storeKey;
}
/**
* Set storeGroupKey
*
* @param integer $storeGroupKey
*
* @return PromotionPrize
*/
public function setStoreGroupKey($storeGroupKey)
{
$this->storeGroupKey = $storeGroupKey;
return $this;
}
/**
* Get storeGroupKey
*
* @return integer
*/
public function getStoreGroupKey()
{
return $this->storeGroupKey;
}
/**
* Set initialNumber
*
* @param integer $initialNumber
*
* @return PromotionPrize
*/
public function setInitialNumber($initialNumber)
{
$this->initialNumber = $initialNumber;
return $this;
}
/**
* Get initialNumber
*
* @return integer
*/
public function getInitialNumber()
{
return $this->initialNumber;
}
/**
* Set increase
*
* @param integer $increase
*
* @return PromotionPrize
*/
public function setIncrease($increase)
{
$this->increase = $increase;
return $this;
}
/**
* Get increase
*
* @return integer
*/
public function getIncrease()
{
return $this->increase;
}
/**
* Set quantity
*
* @param integer $quantity
*
* @return PromotionPrize
*/
public function setQuantity($quantity)
{
$this->quantity = $quantity;
return $this;
}
/**
* Get quantity
*
* @return integer
*/
public function getQuantity()
{
return $this->quantity;
}
/**
* Set amount
*
* @param string $amount
*
* @return PromotionPrize
*/
public function setAmount($amount)
{
$this->amount = $amount;
return $this;
}
/**
* Get amount
*
* @return string
*/
public function getAmount()
{
return $this->amount;
}
/**
* Set status
*
* @param boolean $status
*
* @return PromotionPrize
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* @return boolean
*/
public function getStatus()
{
return $this->status;
}
}
| true |
0e1fc8ca76aa54b6353031c3bb364da49fe04925 | PHP | Anupma-narang/Advantal | /lib/model/doctrine/base/BaseConcursoCategoria.class.php | UTF-8 | 3,189 | 2.515625 | 3 | [] | no_license | <?php
/**
* BaseConcursoCategoria
*
* This class has been auto-generated by the Doctrine ORM Framework
*
* @property string $name
* @property integer $concurso_tipo_id
* @property string $image
* @property integer $orden
* @property ConcursoTipo $ConcursoTipo
* @property Doctrine_Collection $Concurso
* @property Doctrine_Collection $ConcursoCp
*
* @method string getName() Returns the current record's "name" value
* @method integer getConcursoTipoId() Returns the current record's "concurso_tipo_id" value
* @method string getImage() Returns the current record's "image" value
* @method integer getOrden() Returns the current record's "orden" value
* @method ConcursoTipo getConcursoTipo() Returns the current record's "ConcursoTipo" value
* @method Doctrine_Collection getConcurso() Returns the current record's "Concurso" collection
* @method Doctrine_Collection getConcursoCp() Returns the current record's "ConcursoCp" collection
* @method ConcursoCategoria setName() Sets the current record's "name" value
* @method ConcursoCategoria setConcursoTipoId() Sets the current record's "concurso_tipo_id" value
* @method ConcursoCategoria setImage() Sets the current record's "image" value
* @method ConcursoCategoria setOrden() Sets the current record's "orden" value
* @method ConcursoCategoria setConcursoTipo() Sets the current record's "ConcursoTipo" value
* @method ConcursoCategoria setConcurso() Sets the current record's "Concurso" collection
* @method ConcursoCategoria setConcursoCp() Sets the current record's "ConcursoCp" collection
*
* @package symfony
* @subpackage model
* @author Your name here
* @version SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
*/
abstract class BaseConcursoCategoria extends sfDoctrineRecord
{
public function setTableDefinition()
{
$this->setTableName('concurso_categoria');
$this->hasColumn('name', 'string', 100, array(
'type' => 'string',
'notnull' => true,
'length' => 100,
));
$this->hasColumn('concurso_tipo_id', 'integer', null, array(
'type' => 'integer',
'notnull' => true,
));
$this->hasColumn('image', 'string', 255, array(
'type' => 'string',
'notnull' => false,
'length' => 255,
));
$this->hasColumn('orden', 'integer', null, array(
'type' => 'integer',
'notnull' => true,
));
}
public function setUp()
{
parent::setUp();
$this->hasOne('ConcursoTipo', array(
'local' => 'concurso_tipo_id',
'foreign' => 'id',
'onUpdate' => 'CASCADE'));
$this->hasMany('Concurso', array(
'local' => 'id',
'foreign' => 'concurso_categoria_id'));
$this->hasMany('ConcursoCp', array(
'local' => 'id',
'foreign' => 'concurso_categoria_id'));
}
} | true |
4aa8015db9485b1c097ccd952b5f0d5b8b7a54c9 | PHP | Jmiy/i-cache | /tests/Cases/CacheNullStoreTest.php | UTF-8 | 1,044 | 2.546875 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace HyperfTest\Cases;
use Illuminate\Cache\NullStore;
/**
* @internal
* @coversNothing
*/
class CacheNullStoreTest extends AbstractTestCase
{
public function testItemsCanNotBeCached()
{
$store = new NullStore();
$store->put('foo', 'bar', 10);
$this->assertNull($store->get('foo'));
}
public function testGetMultipleReturnsMultipleNulls()
{
$store = new NullStore();
$this->assertEquals([
'foo' => null,
'bar' => null,
], $store->many([
'foo',
'bar',
]));
}
public function testIncrementAndDecrementReturnFalse()
{
$store = new NullStore();
$this->assertFalse($store->increment('foo'));
$this->assertFalse($store->decrement('foo'));
}
}
| true |
373efe17b412478bc6926b2f942632b89d4fbcbc | PHP | perlnerd/symfony_journey | /src/AppBundle/Entity/JourneyRepository.php | UTF-8 | 1,563 | 2.59375 | 3 | [] | no_license | <?php
namespace AppBundle\Entity;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query\ResultSetMapping;
/**
* JourneyRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class JourneyRepository extends EntityRepository
{
/**
* runa query to get an overview report of user Events
* @return array query result
*/
public function fetchSummaryReportByDate($date)
{
$query = $this->getEntityManager()
->createQuery(
'select j.eventType, count(j.eventType) from AppBundle:Journey j WHERE j.eventTime LIKE :time group by j.eventType'
)
->setParameter('time', $date . '%');
return $query->getArrayResult();
}
/**
* Perform a query to fetch a user's journey by email address.
* @param string $email user's email address
* @return array query result
*/
public function fetchReportByEmail($email)
{
$rsm = new ResultSetMapping;
$rsm->addScalarResult('event_type', 'event_type');
$rsm->addScalarResult('event_time', 'event_time');
$query = $this->getEntityManager()
->createNativeQuery(
'select j.event_type as event_type, j.event_time as event_time from journey j LEFT JOIN user_auth u on u.id = j.user_id WHERE u.ua_email_address = :email ORDER by j.event_time ASC',
$rsm
)
->setParameter('email', $email);
return $query->getArrayResult();
}
}
| true |
4fbb3b62212569d7280c31403750cabe283eb7d9 | PHP | gintast/broedis | /baisus-array.php | UTF-8 | 1,147 | 2.953125 | 3 | [] | no_license | <?php
session_start();
$colors =
[
'red',
[
'red1',
'blue1',
'green1',
'yellow1'
],
'blue',
[ 'red2',
'blue2',
['red3', 'blue3', 'green3', 'yellow3'],
'yellow2'
],
'green',
'yellow'
];
// _d($colors);
$komoda = [];
foreach(range(1, 10) as $stalcius) {
if (rand(0, 3)) {
// darome nauja dezute
$dezute = [];
foreach(range(1, rand(4, 10)) as $skyrelis) {
$dezute[$skyrelis] = rand(1000000, 9999999);
}
$komoda[$stalcius] = $dezute;
}
else {
$komoda[$stalcius] = rand(1000000, 9999999);
}
}
// $_SESSION['m'] = $komoda;
$komoda = $_SESSION['m'];
_d($komoda);
_d($komoda[2], '$komoda[2]');
_d($komoda[6][4], '$komoda[6][4]');
_d($komoda[10][1], '$komoda[10][1]');
_d($komoda[4], '$komoda[ 4]');
foreach($komoda as $dezute) {
//ar dezute?
if (is_array($dezute)) {
foreach($dezute as $skaicius) {
// _d($skaicius);
}
}
else {
$skaicius = $dezute; // tai ne masyvas tai reiksme
// _d($skaicius);
}
}
| true |
764549938f4eb38c2bd9dd3968230f43d3cbce6a | PHP | sandeepchetikam/Angular-project | /Angular/connect-employee.php | UTF-8 | 1,341 | 2.671875 | 3 | [] | no_license | <?php
header("Access-Control-Allow-Origin: *");
$servername="localhost";
$username="root";
$password="sandeepchetikam";
$dbase="mydb";
$conn=mysqli_connect($servername,$username,$password,$dbase);
if (!$conn) {
echo "Connection Problem".mysqli_connect_error($conn);
}
// first only select what you want to use from the row
$sql= "SELECT`id`, `worklocation`, `firstname`, `lastname`, `gender`, `aadharno`, `panno`, `employeetype`, `dateofbirth`, `city`,`status`,`emailid`,`phoneno`,`department`,`title`,`jobdescription`,`startdate`,`employeeid`
FROM newdb WHERE status='Active'";
$result = mysqli_query($conn,$sql);
if(!$result){
// you only use `mysqli_connect_error` to get connection errors
// use mysqli_error($result) for normal query errors
echo "Query failed " . mysqli_error($result);
echo json_encode(array('error'=>'Query failed'));
exit;
}
$rowcount=mysqli_num_rows($result);
if ( mysqli_num_rows($result) > 0 ) {
while($row = mysqli_fetch_assoc($result)){
// now as you only have what you want in your assoc array
$rows[] = $row;
}
echo json_encode($rows);
} else {
// no data returned from query
// return something so the calling code knows what to do
echo json_encode(array('error'=>'No data in table'));
}
?> | true |
ddb911c55d3dc345a9079d005ba67da9a3e6c1b7 | PHP | mist-cloud/my_sample_projectA | /kihon/index2.php | UTF-8 | 140 | 2.65625 | 3 | [] | no_license | <?php
$a = [1,2,3];
echo "<pre>";
print_r($a);
echo "</pre>";
echo "<pre>";
var_dump($a);
echo "</pre>";
exit;
echo "表示されない";
?> | true |
f36b26cbe57d9c24a697b055cee5bc489721ae8d | PHP | Kostersson/github-security-checker | /src/AlertHandler/AlertHandler.php | UTF-8 | 1,576 | 2.953125 | 3 | [
"MIT"
] | permissive | <?php
namespace Kostersson\GithubSecurityChecker\AlertHandler;
use Kostersson\GithubSecurityChecker\Message\MessageInterface;
class AlertHandler implements AlertHandlerInterface
{
/**
* @var MessageInterface
*/
private $messageInterface;
/**
* @param MessageInterface $messageInterface
*/
public function __construct(MessageInterface $messageInterface)
{
$this->messageInterface = $messageInterface;
}
/**
* @param array $repository
* @param array $contributors
* @param array $alerts
*/
public function handleAlerts(array $repository, array $contributors, array $alerts)
{
if (count($alerts) === 0) {
return;
}
$str = '';
foreach ($contributors as $contributor) {
$str .= '<@'.$contributor['login'].'> ';
}
$str .= '\nRepository name: '.$repository['name']."\n";
$str .= "----------------------------------------------\n";
foreach ($alerts as $project => $alert) {
$str .= $project.' version: '.$alert['version'];
foreach ($alert['advisories'] as $file => $advisory) {
$str .= ' ('.$file.")\n";
foreach ($advisory as $title => $data) {
$str .= $title.': '.$data."\n";
}
}
$str .= "----------------------------------------------\n";
}
$str .= "#####################################################\n";
$this->messageInterface->sendAlertMessage($str);
}
}
| true |
02861808a530a0f8f0b8668352a8bd56e5a6fa1e | PHP | DavidPaca/Sistemaweb | /extras/buscador.php | UTF-8 | 1,067 | 2.546875 | 3 | [] | no_license | <!--require_once './inc/top.php';
$salida = "";
$query = "SELECT * FROM users WHERE username not LIKE '' ORDER BY id LIMIT 5";
if (isset($_POST['consulta'])) {
$q = mysqli_real_escape_string($con,$_POST['consulta']);
$query = "SELECT * FROM users WHERE id LIKE '%$q%' or first_name LIKE '%$q%' OR username LIKE '%$q%' or email LIKE '%$q%'";
}
$resultado = mysqli_query($con, $query);
if (mysqli_num_rows($resultado) > 0) {
$salida .= "<table border=1 class='tabla_datos'>
<thead>
<tr id='titulo'>
<td>ID</td>
<td>NOMBRE</td>
<td>USUARIO</td>
<td>EMAIL</td>
</tr>
</thead>
<tbody>";
while ($fila = mysqli_fetch_array($resultado)) {
$salida .= "<tr>
<td>" . $fila['id'] . "</td>
<td>" . $fila['first_name'] . "</td>
<td>" . $fila['username'] . "</td>
<td>" . $fila['email'] . "</td>
</tr>";
}
$salida .= "</tbody></table>";
} else {
$salida .= "NO hay datos en la tabla : C";
}
echo $salida;-->
| true |
72e19458ae66ad36c470e8676a88b9376e80dbbe | PHP | carolbarbosa101/Cidades_Digitais | /Model/ClassTipologiaPid.php | UTF-8 | 419 | 2.609375 | 3 | [] | no_license | <?php
class ClassTipologiaPid {
private $cod_pid, $cod_tipologia;
function getCod_pid() {
return $this->cod_pid;
}
function getCod_tipologia() {
return $this->cod_tipologia;
}
function setCod_pid($cod_pid) {
$this->cod_pid = $cod_pid;
}
function setCod_tipologia($cod_tipologia) {
$this->cod_tipologia = $cod_tipologia;
}
}
| true |
7a8a6fdd4b8f8e5f8b0120dad3b7f4ba92e28a04 | PHP | AnaHolgado/DWES | /CapituloVI/ej8.php | UTF-8 | 7,983 | 2.75 | 3 | [] | no_license | <?php
session_start();
if (!isset($_COOKIE["palabras"])){
$_SESSION['diccionario'] = array("gato" => "cat","perro" => "dog",
"raton" => "mouse","cerdo" => "pig","elefante" => "elephant",
"mofeta" => "skun","mapache" => "racoon","leon" => "lion",
"tigre" => "tiger","ballena" => "whale","delfin" => "dolphin",
"araña" => "spider","libelula" => "dragonfly","mariposa" => "butterfly",
"gusano" => "worm","conejo" => "rabbit","pez" => "fish",
"abeja" => "bee","tiburon" => "shark","camello" => "camel",);
$palabras = serialize($_SESSION['diccionario']);
setcookie("palabras", $palabras, time() + 3*24*3600);
header("Refresh:0");
} else {
$_SESSION['palabras'] = unserialize($_COOKIE["palabras"]);
}
if (isset($_POST["nuevo"])) {
$ingles = $_POST["ingles"];
$espanol = $_POST["espanol"];
$_SESSION['palabras'][$espanol] = $ingles;
$palabras = serialize($_SESSION['palabras']);
setcookie("palabras", $palabras, time() + 3*24*3600);
} else {
$palabras = $_COOKIE["palabras"];
$_SESSION['palabras'] = unserialize($palabras);
$diccionario = $_SESSION['palabras'];
}
?>
<!DOCTYPE html>
<!--Ejercicio 8. Realiza un programa que escoja al azar 5 palabras en inglés de
un mini-diccionario. El programa pedirá que el usuario teclee la traducción al
español de cada una de las palabras y comprobará si son correctas. Al final, el
programa deberá mostrar cuántas respuestas son válidas y cuántas erróneas. La
aplicación debe tener una opción para introducir los pares de palabras
(inglés - español) que se deben guardar en cookies; de esta forma, si de vez en
cuando se dan de alta nuevas palabras, la aplicación puede llegar a contar con
un número considerable de entradas en el mini-diccionario.
-->
<html>
<head>
<meta charset="UTF-8">
<meta name="keywords" content="Ejercicios PHP">
<meta name="author" content="Ana Holgado">
<title>Aprende PHP - Capitulo VI</title>
<link href="../css/style.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<header id = "header">
<h1>APRENDE PHP CON EJERCICIOS</h1>
<h2><a href= ../index.php>CAPITULO VI </a></h2>
</header>
<nav>
<ul>
<li><a href="ej7.php">Ejercicio 7</a></li>
<li><a href="ej10.php">Ejercicio 10</a></li>
<li><a href="ej13.php">Ejercicio 13</a></li>
<li><a href="ej16.php">Ejercicio 16</a></li>
<li><a href="ej20.php">Ejercicio 20</a></li>
<li><a href="ej23.php">Ejercicio 23</a></li>
<li><a href="ej28.php">Ejercicio 28</a></li>
</ul>
</nav>
<section>
<article>
<h3>Ejercicio 8</h3>
<p>Realiza un programa que escoja al azar 5 palabras en inglés de
un mini-diccionario. El programa pedirá que el usuario teclee la traducción al
español de cada una de las palabras y comprobará si son correctas. Al final, el
programa deberá mostrar cuántas respuestas son válidas y cuántas erróneas. La
aplicación debe tener una opción para introducir los pares de palabras
(inglés - español) que se deben guardar en cookies; de esta forma, si de vez en
cuando se dan de alta nuevas palabras, la aplicación puede llegar a contar con
un número considerable de entradas en el mini-diccionario.</p>
</article>
<article>
<h3>Ejercicio Resuelto</h3>
<p> Diccionario</p>
<p>
<?php
foreach ($diccionario as $clave => $valor) {
$palabrasDiccionario[] = $clave;
}
if(!isset($_REQUEST['enviar'])){
$_SESSION['indices']= array_rand($palabrasDiccionario, 5);
$indices = $_SESSION['indices'];
var_dump($_SESSION['indices']);
} else{
$palabra0 = strtolower($_GET['palabra0']);
$palabra1 = strtolower($_GET['palabra1']);
$palabra2 = strtolower($_GET['palabra2']);
$palabra3 = strtolower($_GET['palabra3']);
$palabra4 = strtolower($_GET['palabra4']);
}
?>
</p>
<br>
<?php
if (!isset($_GET['enviar']) || isset($_GET['volver'])){
?>
<form action="#" method="get">
<label> <?php echo $indices[0]; ?></label><input type="text" name ="palabra0"autofocus><br>
<label> <?php echo $indices[1]; ?></label><input type="text" name ="palabra1"><br>
<label> <?php echo $indices[2]; ?></label><input type="text" name ="palabra2"><br>
<label> <?php echo $indices[3]; ?></label><input type="text" name ="palabra3"><br>
<label> <?php echo $indices[4]; ?></label><input type="text" name ="palabra4"><br>
<br>
<input type="submit" name="enviar" value ="Enviar"><br>
</form>
<?php
}
?>
</article>
<article>
<h3>Resultado</h3>
<p>
<?php
if(isset($_REQUEST['enviar'])){
$indices = $_SESSION['indices'];
$aciertos = 0;
if($diccionario[$indices[0]] == $palabra0){
$aciertos++;
} else {
echo $indices[0]. " es ".$diccionario[$indices[0]]."<br>";
}
if($diccionario[$indices[1]] == $palabra1){
$aciertos++;
} else {
echo $indices[1]. " es ".$diccionario[$indices[1]]."<br>";
}
if($diccionario[$indices[2]] == $palabra2){
$aciertos++;
} else {
echo $indices[2]. " es ".$diccionario[$indices[2]]."<br>";
}
if($diccionario[$indices[3]] == $palabra3){
$aciertos++;
} else {
echo $indices[3]. " es ".$diccionario[$indices[3]]."<br>";
}
if($diccionario[$indices[4]] == $palabra4){
$aciertos++;
} else {
echo $indices[4]. " es ".$diccionario[$indices[4]]."<br>";
}
echo " Ha acertado ".$aciertos." preguntas.";
?>
<form action="#" method="post">
<label> Español </label><input type="text" name ="espanol"><br>
<label> Inglés</label><input type="text" name ="ingles"><br>
<br>
<input type="submit" name="nuevo" value ="Enviar"><br>
</form>
<form action="#" method="get">
<input type="submit" name="volver" value ="Volver"><br>
</form>
<?php
}
?>
</p>
</article>
</section>
<nav>
<a href="index.php" id="anterior">Anterior</a>
<a href="index.php" id="home">Home</a>
<a href="ej10.php" id="siguiente">Siguiente</a>
</nav>
<footer>
<p align="center" class="texto"> Página realizada por Ana Holgado Infante. <br>I.E.S. Campanillas. Desarrollo Web en Entorno Servidor.</p>
</footer>
</body>
</html>
| true |
dd5ee2a29c608dba18c45d36f4b70d88eaf37709 | PHP | darhmostafa/loginsystem | /loginsystem/home.php | UTF-8 | 1,419 | 2.5625 | 3 | [] | no_license | <?php
session_start();
if(empty($_SESSION['userdata']))
{
header('LOCATION:index.html');
} else
{
?>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<?php
echo '<h1>welcome to home page</h1>';
echo '<a href="logout.php">logout</a>';
$posts =
[
['title' => 'Post One' , 'post' => 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nihil'],
['title' => 'Post two' , 'post' => 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nihil'],
['title' => 'Post three', 'post' => 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nihil'],
['title' => 'Post fout' , 'post' => 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nihil'],
['title' => 'Post five' , 'post' => 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nihil']
];
echo "<div class='all'>";
for($i = 0; $i <= count($posts) - 1;$i++)
{
$pst = $posts[$i];
echo "<div class='posts'>";
echo "<h1>" . $pst["title"] . "</h1>";
echo '<div>';
echo "<h3>" . $pst["post"] . '<a href="javascript:showMore()" id="link">Read More ...</a>' ."</h3>";
echo '</div>';
echo "</div>";
}
echo "</div>";
}
?>
<script src="javascrpit.js"></script>
</body>
</html>
| true |
7ea264371b131ef5aaca1d5f2992e12e28a2d747 | PHP | nemundo/framework | /src/App/ModelDesigner/Com/Form/DefaultProjectForm.php | UTF-8 | 1,146 | 2.53125 | 3 | [
"MIT"
] | permissive | <?php
namespace Nemundo\App\ModelDesigner\Com\Form;
use Nemundo\Admin\Com\Form\AbstractAdminForm;
use Nemundo\Admin\Com\ListBox\AdminListBox;
use Nemundo\App\ModelDesigner\Com\ListBox\ProjectListBox;
use Nemundo\App\ModelDesigner\ModelDesignerConfig;
use Nemundo\App\ModelDesigner\Project\DefaultProject;
class DefaultProjectForm extends AbstractAdminForm
{
/**
* @var ProjectListBox
*/
private $project;
public function getContent()
{
$this->project = new AdminListBox($this);
$this->project->label = 'Default Project';
foreach ((new ModelDesignerConfig())->getProjectCollection()->getProjectList() as $project) {
$this->project->addItem($project->getClassName(), $project->project . ' (' . $project->namespace . ')');
}
$project = (new DefaultProject())->getDefaultProject();
if ($project !== null) {
$this->project->value = $project->getClassName();
}
return parent::getContent();
}
protected function onSubmit()
{
(new DefaultProject())->setDefaultProject($this->project->getValue());
}
} | true |
c71ed0b37483a51583b6879830ffd8b32136376c | PHP | peace098beat/Tweetbox | /php/Speache.php | UTF-8 | 910 | 3.3125 | 3 | [] | no_license | <?php
/*
* Speache.php
*
* (2016/06/04) Tomoyuki Nohara
*
*/
/*************************************************************************/
/* フォーム処理*/
/*************************************************************************/
function get_speaches( )
{
// ファイルの内容を配列に取り込みます。
// この例ではHTTPを通してURL上のHTMLソースを取得します。
$lines = file('php/Speache.txt');
return $lines;
}
/*************************************************************************/
/* 使い方 */
/*
// ファイルの内容を配列に取り込みます。
$lines = file('Speache.txt');
// 配列をループしてHTMLをHTMLソースとして表示し、行番号もつけます。
foreach ($lines as $line_num => $line) {
echo htmlspecialchars($line) . "<br/>\n";
}
*/
/*************************************************************************/
?> | true |
f3eb8db6c1399c421e94db2cc86f4b6ebe4e196c | PHP | icirlin/Football-Management-App | /database-manager.php | UTF-8 | 786 | 2.734375 | 3 | [] | no_license | <?php
$servername = "127.0.0.1";
$username = "icirlin";
$password = "";
$dbname = "FootballPlayers";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . $conn->connect_error);
}
$result = mysqli_query($conn, "SHOW TABLE STATUS");
if (!$result){
die("Query Failed");
}
echo mysqli_num_rows($result) or "ERROR";
$result_array = mysqli_fetch_array($result);
echo "\n";
var_dump($result_array);
//foreach ($result_array as $key => $field){
// echo $key . " : " . $field . "\n";
//}
#mysql_select_db($dbname) or die(mysql_error());
#print "Connected successfully\n";
#$query = "SHOW TABLES";
#$result = mysql_query($conn, "SHOW TABLE STATUS") or die("Query fail: " . mysqli_error($conn));
?> | true |
7022dbd007b3c501781f3285251cf001c8686eaf | PHP | n-suzuki-actself/actself_problem7 | /src/Controller/ReviewsController.php | UTF-8 | 7,357 | 2.59375 | 3 | [] | no_license | <?php
namespace App\Controller;
//use Cake\ORM\TableRegistry;
class ReviewsController extends AppController{
public $name = 'Reviews';
public $autoRender = false;
/**口コミ助
* 口コミ一覧画面
*/
public function __construct(\Cake\Network\Request $request = null, \Cake\Network\Response $response = null, $name = null, $eventManager = null, $components = null) {
parent::__construct($request, $response, $name, $eventManager, $components);
session_start();
//var_dump($_SESSION['login']);
if(! isset($_SESSION['login'])){
// ログインされてない
// リダイレクト ログイン画面へ
return $this->redirect(['controller' => 'Logins', 'action' => 'login']);
}// セッションの値もチェック
elseif($_SESSION['login'] !== true){
return $this->redirect(['controller' => 'Logins', 'action' => 'login']);
}
}
public function review($id){
$rows = $this->Reviews->findByBook_id($id)
->order(['created' => 'DESC']);
//['order' => ['created' =>'DESC']]);
$this->set('rows' , $rows);
//$this->set('entity' , $this->Reviews->newEntity());
$this->Render('/Reviews/review');
}
// public function review($id){
// //$books = TableRegistry::get('Books');
// // 口コミ一覧に書籍のタイトルを表示したい
// $rows = $books->getRecord($id);
// $title = $rows['title'];
// $data =[
// 'id' => $id,
// 'title' => $title
//
// ];
//
// $this->set('data' , $data);
// $this->Render('/Reviews/review');
// // 口コミ一覧を表示する
// $reviews = TableRegistry::get('Reviews');
// $list = $reviews->getList($id);
// $this->set('list' , $list);
// $this->Render('/Reviews/review');
//
// }
public function deletereview($id , $book_id){
// Tableクラスを呼び出して、削除処理
$reviews = TableRegistry::get('Reviews');
$reviews->delRecord($id);
// 口コミの5段階評価の平均点を計算を委託
$this->_average($book_id);
// その後、review()へリダイレクト
$this->redirect(['action' => 'review', $book_id]);
}
public function addreview($id){
//GETか?
if($this->request->is('get')){
// GETである
// CSRF対策 ワンタイムトークン発行
// セッションに記録
$str = sha1(time());
$_SESSION['one_time_token'] = $str;
$this->set('str' , $str);
// 新規登録画面を表示
$books = TableRegistry::get('Books');
// 口コミ登録する書籍のタイトルを表示したい
$rows = $books->getRecord($id);
$title = $rows['title'];
$data =[
'id' => $id,
'title' => $title
];
$this->set('data' , $data);
$this->Render('/Reviews/add_review');
}// ワンタイムトークンが一致するか
elseif($_SESSION['one_time_token'] != $this->request->data('one_time_token')) {
echo '危険なアクセス';
}
else{
// GET以外である
// Tableクラスを呼び出して、登録処理
$reviews = TableRegistry::get('Reviews');
$header = $this->request->data('header');
$nickname = $this->request->data('nickname');
$body = $this->request->data('body');
$star_count = $this->request->data('star_count');
$book_id = $this->request->data('book_id');
$reviews->addRecord($header , $nickname , $body , $star_count , $book_id);
// 口コミの5段階評価の平均点を計算を委託
$this->_average($book_id);
// その後、review()へリダイレクト
return $this->redirect(['action' => 'review', $book_id]);
}
}
public function updatereview($id){
// GETか?
if($this->request->is('get')){
// GETである
// CSRF対策 ワンタイムトークン発行
// セッションに記録
$str = sha1(time());
$_SESSION['one_time_token'] = $str;
$this->set('str' , $str);
// 更新画面を表示
$books = TableRegistry::get('Books');
// 口コミ更新する書籍のタイトルを表示したい
$rows = $books->getRecord($id);
$title = $rows['title'];
$data =[
'id' => $id,
'title' => $title
];
$this->set('data' , $data);
$this->Render('/Reviews/update_review');
}// ワンタイムトークンが一致するか
elseif($_SESSION['one_time_token'] != $this->request->data('one_time_token')) {
echo '危険なアクセス';
}
else{
// GET以外である
// Tableクラスを呼び出して、登録処理
$reviews = TableRegistry::get('Reviews');
$id = $this->request->data('id');
$header = $this->request->data('header');
$nickname = $this->request->data('nickname');
$body = $this->request->data('body');
$star_count = $this->request->data('star_count');
$book_id = $this->request->data('book_id');
$reviews->updateRecord($id , $header , $nickname , $body , $star_count , $book_id);
// 口コミの5段階評価の平均点を計算を委託
$this->_average($book_id);
// その後、review()へリダイレクト
return $this->redirect(['action' => 'review', $book_id]);
}
}
private function _average($book_id){
$reviews = TableRegistry::get('Reviews');
// 口コミの5段階評価の平均点を計算する
$rows = $reviews->getList($book_id);
$record_count = 0;
$total= 0;
// 書籍に紐づく口コミのレコード合計数と口コミ評価合計数を計算する
foreach($rows as $data):
$record_count++;
$total = $total+$data['star_count'];
endforeach;
$average = round($total/$record_count , 2);
// 平均点をbooksテーブル@average_scoreカラムに更新する
$books = TableRegistry::get('Books');
$books->updateAverage($book_id , $average);
}
}
| true |
fe6daaa15e44be4efbe9ee425be6f3838cd4ec74 | PHP | sosaavedra/securecoding | /tools for whitebox/phpteam18/models/SecurePin.php | UTF-8 | 1,043 | 3.15625 | 3 | [] | no_license | <?php
class SecurePinModel{
public $userId =-1;
public $securePin =-1;
public function parseSecurePin($securePin){
if(isset($securePin->SecurePin))
$this->securePin = $securePin->SecurePin;
if(isset($securePin->UserID))
$this->userId = $securePin->UserID;
}
}
class SecurePin extends Model{
function __construct($db) {
parent::__construct($db);
}
public function getPinForUser($userId){
$sql = "SELECT ". SECUREPIN_USERID .", ". SECUREPIN_PIN ." from ". SECUREPIN ." WHERE UserID = :userId";
$query = $this->db->prepare($sql);
$query->execute(array(':userId' => $userId));
$pins = $query->fetchAll();
$pin = $pins[0];
$securePinModel = new SecurePinModel();
$securePinModel->parseSecurePin($pin);
return $securePinModel;
}
public function addSecurePin($userId, $securePin)
{
$sql = "INSERT into ". SECUREPIN ."(". SECUREPIN_USERID .",". SECUREPIN_PIN .") VALUES(:userid, :pin)";
$query = $this->db->prepare($sql);
$query->execute(array('userid'=> $userId, 'pin'=>$securePin));
}
}
?>
| true |
0975b12c34353b9a5c456e76b1d1b2ad8e8a8854 | PHP | JeroenSteen/ksmvc | /app/classes/xss.php | UTF-8 | 215 | 2.71875 | 3 | [] | no_license | <?php
class XSS{
//https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet
public function XSS(){
}
public static function escape($input){
return htmlentities($input);
}
} | true |
fd80d99967a427451f5480c172692b1ab33e321a | PHP | rvfe/cadastro | /src/Controller/Pessoas.php | UTF-8 | 3,611 | 2.515625 | 3 | [] | no_license | <?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use App\Entity\Pessoa;
/**
* @Route("/pessoa", name="pessoa_")
*/
class Pessoas extends AbstractController
{
/**
* @Route("/", name="index", methods={"GET"})
*/
public function index(): Response
{
$cadastrados = $this->getDoctrine()->getRepository(Pessoa::class)->findAll();
return $this->json([
'Usuários cadastrados:' => $cadastrados
]);
}
/**
* @Route("/{pessoaId}", name="show", methods={"GET"})
*/
public function show($pessoaId)
{
$pessoa = $this->getDoctrine()->getRepository(Pessoa::class)->find($pessoaId);
$nome = $this->getDoctrine()->getRepository(Pessoa::class)->find($pessoaId)->getNome($pessoaId);
return $this->json([
'Dados de '.$nome.':' => $pessoa
]);
}
/**
* @Route("/", name="create", methods={"POST"})
*/
public function create(Request $request)
{
$data = $request->request->all();
$cadastro = new Pessoa();
$cadastro->setNome($data['nome']);
$cadastro->setTelefone($data['telefone']);
$cadastro->setEndereco($data['endereco']);
$cadastro->setIdade($data['idade']);
$cadastro->setCriadoEm(new \DateTime('now'));
$cadastro->setAtualizadoEm(new \DateTime('now'));
$doctrine = $this->getDoctrine()->getManager();
$doctrine->persist($cadastro);
$doctrine->flush();
return $this->json([
$data['nome'] .' foi adicionado(a)'. ' com sucesso!'
]);
}
/**
* @Route("/{pessoaId}", name="update",methods={"PUT","PATCH"})
*/
public function update($pessoaId, Request $request)
{
$data = $request->request->all();
$doctrine = $this->getDoctrine();
$cadastro = $doctrine->getRepository(Pessoa::Class)->find($pessoaId);
$id = $cadastro->getId($pessoaId);
if($request->request->has ('nome'))
$cadastro->setNome($data['nome']);
if($request->request->has ('telefone'))
$cadastro->setTelefone($data['telefone']);
if($request->request->has ('endereco'))
$cadastro->setEndereco($data['endereco']);
if($request->request->has ('idade'))
$cadastro->setIdade($data['idade']);
$cadastro->setAtualizadoEm(new \DateTime('now'));
$manager = $doctrine->getManager();
$manager->flush();
return $this->json([
'O cadastro de ' .$data['nome']. ' (ID:'.$id.') foi atualizado com sucesso!'
]);
}
/**
* @Route("/{pessoaId}", name="delete", methods={"DELETE"})
*/
public function delete($pessoaId)
{
$cadastro = $this->getDoctrine()->getRepository(Pessoa::class)->find($pessoaId);
$nome = $this->getDoctrine()->getRepository(Pessoa::class)->find($pessoaId)->getNome($pessoaId);
$id = $this->getDoctrine()->getRepository(Pessoa::class)->find($pessoaId)->getId($pessoaId);
$manager = $this->getDoctrine()->getManager();
$manager->remove($cadastro);
$manager->flush();
return $this->json([
'O cadastro de '.$nome.' (ID: '.$id.') foi removido com sucesso'
]);
}
}
| true |
5ca229b6c4991d4a6e286255ec0569bde516ae85 | PHP | netis-pl/yii2-fsm | /components/StateActionInterface.php | UTF-8 | 3,723 | 2.765625 | 3 | [] | no_license | <?php
namespace netis\fsm\components;
/**
* Description here...
*
* @author Michał Motyczko <michal@motyczko.pl>
*/
interface StateActionInterface
{
/**
* Return target state
*
* @return integer
*/
public function getTargetState();
/**
* Loads the model specified by $id and prepares some data structures.
*
* @param \netis\crud\db\ActiveRecord|IStateful $model
*
* @return array contains values, in order: $stateChange(array), $sourceState(mixed), $format(string|array)
* @internal param string $targetState
*/
public function getTransition($model);
/**
* May render extra views for special cases and checks permissions.
*
* @fixme consider some way of disable auth check because this method is used by BulkStateAction which passes dummy model as $model parameter
*
* @param \netis\crud\db\ActiveRecord $model
* @param array $stateChange
* @param mixed $sourceState
* @param boolean $confirmed
*
* @return array|bool
* @internal param string $targetState
*/
public function checkTransition($model, $stateChange, $sourceState, $confirmed = true);
/**
* Perform last checks and the actual state transition.
*
* @param \yii\db\ActiveRecord|IStateful $model
* @param array $stateChange
* @param mixed $sourceState
* @param boolean $confirmed
*
* @return bool true if state transition has been performed
* @internal param string $targetState
*/
public function performTransition($model, $stateChange, $sourceState, $confirmed = true);
/**
* Called before executing performTransition.
* @param \yii\db\ActiveRecord $model
* @return bool
*/
public function beforeTransition($model);
/**
* Called after successful {@link performTransition()} execution.
* @param \yii\db\ActiveRecord $model
*/
public function afterTransition($model);
/**
* @param \yii\db\ActiveRecord|IStateful $model
* @param array $stateChange
* @param string $sourceState
* @param string $targetState
*/
public function setSuccessFlash($model, $stateChange, $sourceState, $targetState);
/**
* Creates url params for a route to specific state transition.
* @param StateTransition $state
* @param \yii\db\ActiveRecord $model
* @param string $targetState
* @param string $id
* @param boolean $contextMenu the url going to be used in a context menu
* @return array url params to be used with a route
*/
public function getUrlParams($state, $model, $targetState, $id, $contextMenu = false);
/**
* Builds an array containing all possible status changes and result of validating every transition.
* @param \netis\crud\db\ActiveRecord|IStateful $model
* @return array
*/
public function prepareStates($model);
/**
* Builds a menu item used in the context menu.
*
* @param string $actionId target action id
* @param array $transitions obtained by getGroupedByTarget()
* @param mixed $model target model
* @param mixed $sourceState current value of the state attribute
* @param callable $checkAccess should have the following signature: function ($action, $model)
* @param bool $useDropDownMenu should this method create drop down menu or buttons
*
* @return array
*/
public function getContextMenuItem($actionId, $transitions, $model, $sourceState, $checkAccess, $useDropDownMenu = true);
} | true |
314db724011ffd89439606ff56e8ccad7a4ee416 | PHP | jyoti2911/twitter_search_block | /modules/twitter_search_block/src/Plugin/Block/TwitterAPIClass.php | UTF-8 | 1,474 | 2.578125 | 3 | [] | no_license | <?php
/**
* @file
* Contains \Drupal\twitter_search_block\Plugin\Block\TwitterAPIClass.
*/
namespace Drupal\twitter_search_block\Plugin\Block;
class TwitterAPIClass {
/**
* function to get the embedded timeline of tweets with given search query value and count
*/
public function twitter_api($hash_value_one, $settings, $count,$result_type) {
$output = '';
/** URL for REST request, see: https://dev.twitter.com/docs/api/1.1/ * */
$url = 'https://api.twitter.com/1.1/search/tweets.json';
$requestMethod = 'GET';
$getfield = '?q=' . $hash_value_one . '&count=' . $count . '&result_type='.$result_type;
$twitter = new TwitterAPIExchange($settings);
$api_response = $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
$response = json_decode($api_response);
foreach ($response->statuses as $tweetinn) {
$tweet_id = $tweetinn->id_str;
$url = 'https://api.twitter.com/1.1/statuses/oembed.json'; //twitter Rest Api to get the embedded tweet
$requestMethod = 'GET';
$getfield = '?id=' . $tweet_id . '&hide_media=true&maxwidth=260&hide_thread=true';
$twitter1 = new TwitterAPIExchange($settings);
$api_response1 = $twitter1->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
$response1 = json_decode($api_response1);
$output .= $response1->html;
}
return $output;
}
}
| true |
85340d709d51b1fb46a5b286c75df2cc30f51745 | PHP | UnbreakableEdu/todos | /funcoes/ex11.php | UTF-8 | 246 | 3.734375 | 4 | [] | no_license | <?php
function polCm($pol){
$cm=$pol*2.54;
return $cm;
}
print "Digite um número em polegadas: ";
$pol = (float) fgets(STDIN);
$cm = polCm($pol);
print $pol." polegadas equivale a ".$cm." centímetros "; | true |
04a1aaec4ef54082b7c2bdfa8e8d23636ad8dc35 | PHP | orzy/p3 | /src/Session.php | UTF-8 | 5,048 | 2.8125 | 3 | [
"MIT"
] | permissive | <?php
/**
* P3_Session
*
* require
* * P3_Abstract
*
* @version 3.0.6
* @see https://github.com/orzy/p3
* @license The MIT license (http://www.opensource.org/licenses/mit-license.php)
*/
class P3_Session extends P3_Abstract {
const TYPE_SYS = 'system_session';
const TYPE_APP = 'app_session';
const FORM_TOKEN = 'form_token';
const HASH_ALGO = 'sha512';
private $_seed = '';
/**
* コンストラクタ
* @param string $seed (Optional) hash生成で使う文字列
* @param array $setting (Optional) 初期設定
*/
public function __construct($seed = '', array $setting = array()) {
$this->_seed = $seed;
if (!session_id()) {
$setting = array_merge(array(
'name' => 'sid',
'gc_maxlifetime' => 60 * 60 * 24 * 3,
'cookie_httponly' => true,
'use_only_cookies' => true,
'entropy_file' => '/dev/urandom',
'entropy_length' => 32,
'hash_function' => true,
'hash_bits_per_character' => 5,
), $setting);
foreach ($setting as $key => $value) {
ini_set("session.$key", $value);
}
session_start();
}
if (!isset($_SESSION[self::TYPE_SYS])) {
$_SESSION[self::TYPE_SYS] = array();
$_SESSION[self::TYPE_APP] = array();
}
}
/**
* セッションに値をセットする
* @param string $key
* @param mixed $value
* @param string $type (Optional)
*/
public function set($key, $value, $type = self::TYPE_APP) {
$_SESSION[$type][$key] = $value;
}
/**
* セッションの値を削除する
* @param string $key
* @param string $type (Optional)
*/
public function remove($key, $type = self::TYPE_APP) {
unset($_SESSION[$type][$key]);
}
/**
* セッションの値を取得する
* @param string $key
* @param boolean $unset (Optional) 値を削除するかどうか
* @param string $type (Optional)
* @return mixed
*/
public function get($key, $unset = false, $type = self::TYPE_APP) {
$value = $this->_arrayValue($key, $_SESSION[$type]);
if ($unset) {
unset($_SESSION[$type][$key]);
}
return $value;
}
/**
* セッションの値を全て破棄する
* @return 処理結果
*/
public function end() {
$_SESSION = array();
return session_destroy();
}
/**
* 1度しか使わないセッション値をセット/取得する
* @param string $key
* @return mixed
*/
public function flash($value = null) {
if (is_null($value)) {
return $this->get('flash', true, self::TYPE_SYS);
} else {
$this->set('flash', $value, self::TYPE_SYS);
}
}
/**
* フォームのCSRF・二重送信防止用のワンタイムトークンを取得/チェックする
* @param boolean $init true:取得, false:チェック
* @return mixed 取得時はstring、チェック時はboolean
*/
public function token($init) {
if ($init) {
$token = session_id() . microtime();
$this->set('token', $token, self::TYPE_SYS);
return $token;
} else {
$token = $this->get('token', true, self::TYPE_SYS);
return ($this->_arrayValue(self::FORM_TOKEN, $_POST) === $token);
}
}
/**
* ログイン
* @param string $hash saltとhash化したパスワード
* @param string $password パスワード
* @param mixed $data (Optional) ログイン情報としてセッションに保存する値
* @return boolean パスワードが正しいかどうか
*/
public function login($hash, $password, $data = true) {
list($salt) = explode(':', $hash);
if (!$salt) {
throw new UnexpectedValueException("saltがありません $hash");
}
if ($this->hash($password, $salt) !== $hash) {
return false;
}
// ログイン成功の場合
session_regenerate_id(true);
$this->set('login', $data, self::TYPE_SYS);
$redirectUrl = $this->get('check', true, self::TYPE_SYS);
if ($redirectUrl) {
$http = new P3_Http();
$http->redirect($redirectUrl);
} else {
return true;
}
}
/**
* ログイン済みかチェックする
* 未ログインの場合、ログインページへリダイレクトしてexitする
* @param string $loginUrl ログインページのURL
*/
public function check($loginUrl) {
if ($this->get('login', false, self::TYPE_SYS)) { // ログイン済みか
return;
} else if (!$_POST) { // GETの場合はログイン後にこのURLにリダイレクトさせる
$this->set('check', $_SERVER['REQUEST_URI'], self::TYPE_SYS);
}
$http = new P3_Http();
$http->redirect($loginUrl);
}
/**
* ログアウトする
*/
public function logout() {
$this->remove('login', self::TYPE_SYS);
}
/**
* パスワードとsaltからhashを生成する
* @param string $password パスワード
* @param string $salt (Optional) salt
* @return string saltとhash
*/
public function hash($password, $salt = '') {
if (!$this->_seed) {
throw new UnexpectedValueException('seedがありません');
}
if (!$salt) {
$salt = microtime();
}
return "$salt:" . hash_hmac(self::HASH_ALGO, "$password*$salt", $this->_seed);
}
}
| true |
95e52f6bf4703c42628069fc9190b3a48e761706 | PHP | productsupcom/guzzle-examples | /src/Command/AbstractCommand.php | UTF-8 | 3,199 | 2.75 | 3 | [] | no_license | <?php
namespace Productsup\Command;
use \Exception;
use \Symfony\Component\Console\Command\Command;
use \Symfony\Component\Console\Input\InputArgument;
use \Symfony\Component\Console\Input\InputInterface;
use \Symfony\Component\Console\Input\InputOption;
use \Symfony\Component\Console\Logger\ConsoleLogger;
use \Symfony\Component\Console\Output\OutputInterface;
/**
* Pup abstract command.
*/
abstract class AbstractCommand extends Command
{
/**
* Productsup logger.
*
* @var \Productsup\Logger
*/
protected $logger;
/**
* Main configuration for all Pup binaries. Defines the minimal required
* options: site and process.
*
* @return void
*/
protected function configure()
{
$this
->addOption('site', null, InputOption::VALUE_REQUIRED, 'Site ID')
->addOption('process', null, InputOption::VALUE_REQUIRED, 'Process ID', uniqid())
;
}
/**
* Main initialize for all Pup Binaries. Sets up logger to multiple channels
* and sets main options a properties.
*
* @param InputInterface $input
* @param OutputInterface $output
*
* @return void
*/
public function initialize(InputInterface $input, OutputInterface $output)
{
$siteId = $input->getOption('site');
$process = $input->getOption('process');
putenv('PRODUCTSUP_PID='.$process);
$logInfo = new \Productsup\LogInfo();
$logInfo->name = '';
$logInfo->site = $siteId;
$logInfo->process = $process;
$redisConfig = \System\Config::getSection('redis::notification');
$redisConfig['channel'] = sprintf(
'%s_%s.log',
$siteId,
substr(md5($siteId."a"), 0, 15).substr(md5($siteId."b"), 5, 5)
);
$this->logger = new \Productsup\Logger(
array(
'Shell' => new \Productsup\Handler\SymfonyConsoleHandler(\Psr\Log\LogLevel::DEBUG, 0, $output),
'Redis' => new \Productsup\Handler\RedisHandler($redisConfig, 'notice', 0),
'Gelf' => new \Productsup\Handler\GelfHandler(),
),
$logInfo
);
}
/**
* Creates directory for specified file path and optionally touches file.
*
* @param string $filePath File path to ensure
* @param boolean $touchFile Touch the file
*
* @return void
*
* @throws Exception If directory could not be created or file could not be
* touched
*/
protected function ensureFileIsWriteable($filePath, $touchFile = false)
{
$fileDir = dirname($filePath);
if (!is_dir($fileDir)) {
if (!mkdir($fileDir, 0777, true)) {
throw new Exception(sprintf(
"Could not create directory '%s' for file '%s'.",
$fileDir,
basename($filePath)
));
}
}
if ($touchFile) {
if (!touch($filePath)) {
throw new Exception(sprintf("Could not create file '%s'.", $filePath), 1);
}
}
return;
}
}
| true |
b337d8a3714832c5dc1f5ab9ddd060ffab7e77f3 | PHP | sgh1986915/php-oop-mvc-unbeatablecar | /checkoutfolder/module/motorvehiclecompare/controller/ajaxcomparevehiclescount.controller.class.php | UTF-8 | 1,696 | 2.71875 | 3 | [] | no_license | <?php
class InvModuleAjaxcomparevehiclescountController extends InvPublicController
{
public function __construct($obj_db , $obj_session , $view_template , $path_info){
$this->view_title = 'Compare Motor Vehicles';
parent::__construct($obj_db , $obj_session , $view_template , $path_info);
$this->obj_motorvehiclestockdb = InvModuleMotorvehiclestockFunctions::getMotorVehicleDB($this->obj_db);
}
protected function setInputValues()
{
$this->setInputValue('add');
$this->setInputValue('remove');
}
public function doController()
{
$this->getOrCreateCompare();
if($this->obj_compare = $this->obj_motorvehiclestockdb->getFileModel('motorvehiclecompare')){
if($this->obj_session->getValue('compare_id') && $this->obj_compare->open($this->obj_session->getValue('compare_id'))){
echo count($this->obj_compare->getItems());
exit;
}
}
echo 0;
exit;
}
/**
* Get a compare list for this session, or create one.
*/
public function getOrCreateCompare()
{
if($this->obj_compare = $this->obj_motorvehiclestockdb->getFileModel('motorvehiclecompare')){
if($this->obj_session->getValue('compare_id') && $this->obj_compare->open($this->obj_session->getValue('compare_id')))
{
// Compare list id session already exists and has loaded.
return true;
}
else
{
// Compare list id does not exist in session. Create a new compare session.
if($this->obj_compare->create())
{
if($this->obj_compare->save())
{
$this->obj_session->setValue('compare_id' , $this->obj_compare->id);
return true;
}
}
}
}
error_log('Error getting motorvehiclecompare data');
return false;
}
}
?> | true |
ac58815c27ebfc85b863357aa8326d3013579bcf | PHP | Toruse/Syo-framework | /includes/syo/filter/int.php | UTF-8 | 800 | 3.078125 | 3 | [] | no_license | <?php
/**
* Класс преобразовывает строку в число
*/
class Syo_Filter_Int extends Syo_Filter_Abstract
{
/**
* Конструктор.
* @param array $param
*/
public function __construct($param='')
{
//Устанавливаем имя фильтра
$this->_name='int';
//Устанавливаем параметры для фильтра
if (is_array($param))
{
$this->_param=$param;
}
}
/**
* Выполняем фильтрацию.
* @param variant $value - данная переменная пройдёт фильтрацию
* @return variant
*/
public function isFilter($value)
{
return intval($value);
}
}
?> | true |
2d7c75ef3d059bed087208808f61b900f4274e91 | PHP | dreamcampaigns/managesend-php | /src/DataClass/Subscriber/Subscriber.php | UTF-8 | 3,184 | 2.703125 | 3 | [
"MIT"
] | permissive | <?php
/*
* This file is part of the Managesend package.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Managesend\DataClass\Subscriber;
use Managesend\Hydrator\AbstractHydrator;
/**
* Class BaseSubscriber
* @package Managesend\DataClass\Subscriber
*/
class Subscriber extends AbstractHydrator
{
/** @var string */
protected $email;
/** @var string */
protected $mobile;
/** @var string */
protected $company;
/** @var string */
protected $firstName;
/** @var string */
protected $lastName;
/** @var string */
protected $address;
/** @var string */
protected $city;
/** @var string */
protected $state;
/** @var string */
protected $postalCode;
/** @var string */
protected $country;
/** @var string */
protected $status;
/** @var string */
protected $smsStatus;
/** @var array */
protected $customFields;
/** @var string */
protected $joinDate;
/**
* @return string
*/
public function getEmail()
{
return $this->email;
}
/**
* @return string
*/
public function getMobile()
{
return $this->mobile;
}
/**
* @return string
*/
public function getCompany()
{
return $this->company;
}
/**
* @return string
*/
public function getFirstName()
{
return $this->firstName;
}
/**
* @return string
*/
public function getLastName()
{
return $this->lastName;
}
/**
* @return string
*/
public function getAddress()
{
return $this->address;
}
/**
* @return string
*/
public function getCity()
{
return $this->city;
}
/**
* @return string
*/
public function getState()
{
return $this->state;
}
/**
* @return string
*/
public function getPostalCode()
{
return $this->postalCode;
}
/**
* @return string
*/
public function getCountry()
{
return $this->country;
}
/**
* @return string
*/
public function getStatus()
{
return $this->status;
}
/**
* @return string
*/
public function getSmsStatus()
{
return $this->smsStatus;
}
/**
* @return array
*/
public function getCustomFields()
{
return $this->customFields;
}
/**
* @param string $customField
*
* @return bool
*/
public function hasCustomField($customField)
{
return \array_key_exists($customField,$this->customFields);
}
/**
* @param string $customField
*
* @return mixed|null
*/
public function getCustomFieldValue($customField)
{
if($this->hasCustomField($customField)){
return $this->customFields[$customField];
}
return NULL;
}
/**
* @return string
*/
public function getJoinDate()
{
return $this->joinDate;
}
} | true |
5bd2469b2a3be361dfd045e14a30185bcd69ac06 | PHP | chadedge/php-bluehornet | /src/MethodResponses/TransactionalListTemplate.php | UTF-8 | 4,332 | 2.65625 | 3 | [] | no_license | <?php
namespace Dawehner\Bluehornet\MethodResponses;
class TransactionalListTemplate extends ResponseBase
{
/**
* {@inheritdoc}
*/
protected $methodName = 'transactional.listTemplates';
/**
* @var int
*/
protected $templateId;
/**
* @var string
*/
protected $fromDescription;
/**
* @var string
*/
protected $fromEmail;
/**
* @var string
*/
protected $replyEmail;
/**
* @var string
*/
protected $subject;
/**
* @var string
*/
protected $messageNotes;
/**
* @var string
*/
protected $billCodes;
/**
* @var string
*/
protected $templateData;
/**
* @var string
*/
protected $html;
/**
* @var string
*/
protected $plain;
/**
* @var string
*/
protected $binding;
/**
* @return int
*/
public function getTemplateId()
{
return $this->templateId;
}
/**
* @param int $templateId
* @return $this
*/
public function setTemplateId($templateId)
{
$this->templateId = $templateId;
return $this;
}
/**
* @return string
*/
public function getFromDescription()
{
return $this->fromDescription;
}
/**
* @param string $fromDescription
* @return $this
*/
public function setFromDescription($fromDescription)
{
$this->fromDescription = $fromDescription;
return $this;
}
/**
* @return string
*/
public function getFromEmail()
{
return $this->fromEmail;
}
/**
* @param string $fromEmail
* @return $this
*/
public function setFromEmail($fromEmail)
{
$this->fromEmail = $fromEmail;
return $this;
}
/**
* @return string
*/
public function getReplyEmail()
{
return $this->replyEmail;
}
/**
* @param string $replyEmail
* @return $this
*/
public function setReplyEmail($replyEmail)
{
$this->replyEmail = $replyEmail;
return $this;
}
/**
* @return string
*/
public function getSubject()
{
return $this->subject;
}
/**
* @param string $subject
* @return $this
*/
public function setSubject($subject)
{
$this->subject = $subject;
return $this;
}
/**
* @return string
*/
public function getMessageNotes()
{
return $this->messageNotes;
}
/**
* @param string $messageNotes
* @return $this
*/
public function setMessageNotes($messageNotes)
{
$this->messageNotes = $messageNotes;
return $this;
}
/**
* @return string
*/
public function getBillCodes()
{
return $this->billCodes;
}
/**
* @param string $billCodes
* @return $this
*/
public function setBillCodes($billCodes)
{
$this->billCodes = $billCodes;
return $this;
}
/**
* @return string
*/
public function getTemplateData()
{
return $this->templateData;
}
/**
* @param string $templateData
* @return $this
*/
public function setTemplateData($templateData)
{
$this->templateData = $templateData;
return $this;
}
/**
* @return string
*/
public function getHtml()
{
return $this->templateData['html'];
}
/**
* @param string $html
* @return $this
*/
public function setHtml($html)
{
$this->templateData['html'] = $html;
return $this;
}
/**
* @return string
*/
public function getPlain()
{
return $this->templateData['plain'];
}
/**
* @param string $plain
* @return $this
*/
public function setPlain($plain)
{
$this->templateData['plain'] = $plain;
return $this;
}
/**
* @return string
*/
public function getBinding()
{
return $this->binding;
}
/**
* @param string $binding
* @return $this
*/
public function setBinding($binding)
{
$this->binding = $binding;
return $this;
}
}
| true |
f9fb646cadf48e8b940c4b1a0c4e9ff6409ff9a6 | PHP | ffgalvao/laravel-task | /app/Services/EntityList.php | UTF-8 | 1,307 | 2.765625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Services;
use App\Models\Company;
use App\Models\Employee;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection;
class EntityList
{
/**
* @param bool $inArrayKeyValue
*
* @return array|Collection
*/
static public function companyList(bool $inArrayKeyValue = false)
{
if ($inArrayKeyValue) {
$companies = Company::select('slug', 'name')
->orderBy('name')
->pluck('name', 'slug')
->toArray();
} else {
$companies = Company::orderBy('name')->get();
}
return $companies;
}
/**
* @param string $companyId
* @param bool $withPagination
* @param int $paginationLength
*
* @return Employee|LengthAwarePaginator|Builder
*/
static public function companyEmployeesList(string $companyId, bool $withPagination = false, int $paginationLength = 10)
{
$employees = Employee::whereCompanyId($companyId)
->orderBy('first_name')
->orderBy('last_name');
if($withPagination){
$employees = $employees->paginate($paginationLength);
}
return $employees;
}
} | true |