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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
63428f126a06942672e6dbc9fc25828c3ae8a543 | PHP | ammannbe/php-tmpfile | /src/TmpFile/File.php | UTF-8 | 2,056 | 3.296875 | 3 | [
"MIT"
] | permissive | <?php
namespace TmpFile;
use TmpFile\Contracts\FileContract;
/**
* Create Temporary Files
*/
class File extends FS implements FileContract
{
/**
* Create new instance
*
* @param string|null $name Folder name
* @param string|null $path Temporary path
* @return void
*/
public function __construct(string $name = null, string $path = null)
{
if (!$name) {
$name = time();
}
$path = $path ?? sys_get_temp_dir();
$command = "mktemp -p {$path} {$name}.XXXXXX";
$this->path = trim(`{$command} 2>/dev/null`);
if (!$this->exists()) {
throw new \Exception("Could not create file '{$name}' in {$path}");
}
}
/**
* Destroy object and delete it from the filesystem
*
* @return void
*/
public function __destruct()
{
@unlink($this->path);
}
/**
* Check if file exists
*
* @return bool
*/
public function exists(): bool
{
return is_file($this->path);
}
/**
* Get the file content
*
* @return string
*/
public function read(): string
{
if ($this->exists()) {
return file_get_contents($this->path) ?: '';
}
return '';
}
/**
* Write content to the file
*
* This method overwrites existing content in the file
*
* @see file_put_contents()
* @param string|array<string>|resource $data Content to write
* @param bool $overwrite Overwrite instead of append
* @return bool
*/
public function write($data, bool $overwrite = true): bool
{
if (is_array($data)) {
// "\n" must be in double quotation marks to create a correct line wrap
$data = implode("\n", $data);
}
$flags = $overwrite ? 0 : FILE_APPEND;
if ($this->exists() && file_put_contents($this->path, $data, $flags) !== false) {
return true;
}
return false;
}
}
| true |
4b20c8d26b59084da75da211cd9459f183f2c149 | PHP | mvodanovic/WebFW | /cms/dblayer/tables/usertype.class.php | UTF-8 | 873 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
namespace WebFW\CMS\DBLayer\Tables;
use WebFW\Database\Table;
use WebFW\Database\TableColumns\IntegerColumn;
use WebFW\Database\TableColumns\VarcharColumn;
use WebFW\Database\TableColumns\BooleanColumn;
use WebFW\Database\TableConstraints\PrimaryKey;
use WebFW\Database\TableConstraints\Unique;
class UserType extends Table
{
protected function init()
{
$this->setName('cms_user_type');
$this->addColumn(IntegerColumn::spawn($this, 'user_type_id', false)->setDefaultValue(null, true));
$this->addColumn(VarcharColumn::spawn($this, 'caption', false, 100));
$this->addColumn(BooleanColumn::spawn($this, 'is_root', false));
$this->addConstraint(PrimaryKey::spawn($this)->addColumn($this->getColumn('user_type_id')));
$this->addConstraint(Unique::spawn($this)->addColumn($this->getColumn('caption')));
}
}
| true |
56e85c54e60689e74823f41fbd743d5e810c519a | PHP | ammarshaikh9613/AkashSirInternship | /Internship_day2/switch.php | UTF-8 | 556 | 3.328125 | 3 | [] | no_license | <?php
$var='e';
switch($var)
{
case 'A':
echo "$var is Vowel";
break;
case 'E':
echo "$var is Vowel";
break;
case 'I':
echo "$var is Vowel";
break;
case 'O':
echo "$var is Vowel";
break;
case 'U':
echo "$var is Vowel";
break;
default:
echo "$var its consonant";
}
?> | true |
b58e02fe8047f58855cc0e6a4ded80bf6c356dc3 | PHP | aleksru/emart | /app/Models/Traits/HasSavesRelations.php | UTF-8 | 5,969 | 2.953125 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Models\Traits;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
/**
* Trait HasSavesRelations
* Автоматическое сохранение всех отношений для модели.
*
* @package App\Models\Traits
*/
trait HasSavesRelations
{
/**
* Возвращает отношения, которые следует автоматически сохранять.
*
* @return array
*/
public function getSavesRelations()
{
return $this->savesRelations ?? [];
}
/**
* Подключает трейт.
*/
public static function bootHasSavesRelations()
{
/**
* Для удобства использования, можно держать данные для отношений
* в атрибутах модели. На событии сохранения мы вытаскиваем их из
* атрибутов и проставляем в отношения, для предотвращения ошибок записи
* в базу из-за несуществующих атрибутов.
*/
static::saving(function (Model $model) {
foreach ($model->getSavesRelations() as $relations) {
$model->setRelationsFromAttributes($model, (array) $relations);
}
});
/**
* Автоматически сохраняем все данные отношений.
* Сохраняем только те данные, которые являются обычным массивом.
* Если это Eloquent коллекция, тогда мы ничего не трогаем.
*/
static::saved(function (Model $model) {
foreach ($model->getSavesRelations() as $type => $relations) {
$model->saveRelations($model, (array) $relations, $type);
}
});
}
/**
* Устанавливает данные из атрибутов в отношения для
* последующего сохранения.
*
* @param Model $model
* @param array $relations
*/
protected function setRelationsFromAttributes(Model $model, array $relations)
{
foreach ($relations as $relation) {
// Вытаскиваем данные из атрибутов
// Данные могут быть как массивом, так и обычной коллекцией (только не Eloquent)
$value = $model->getAttributeValue($relation);
$value = $value instanceof Collection ? $value->toArray() : $value;
// Убираем данные из атрибутов для предотвращения ошибок
unset($model[$relation]);
// Если значение не пустое, тогда устанавливаем его в данные отношений.
// Впоследствии эти данные будут использоваться в событии saved.
if (!is_null($value)) {
$model->setRelation($relation, $value);
}
}
}
/**
* Сохраняет выбранные отношения.
*
* @param Model $model
* @param array $relations
* @param $type
*/
protected function saveRelations(Model $model, array $relations, $type)
{
foreach ($relations as $relation) {
// Получаем данные из отношений, если они там есть.
if ($model->relationLoaded($relation)) {
$data = $model->getRelation($relation);
// Если данные в отношениях есть, то сохраняем их и
// устанавливаем новые записанные данные в виде коллекции
if (is_array($data)) {
switch (mb_strtoLower($type)) {
case 'many-to-many':
$this->saveManyToManyRelation($model, $relation, $data);
break;
case 'has-many':
$this->saveHasManyRelation($model, $relation, $data);
break;
case 'has-one':
$this->saveHasOneRelation($model, $relation, $data);
break;
default:
break;
}
}
}
}
}
/**
* Сохраняет и устанавливает ManyToMany отношения.
*
* @param Model $model
* @param string $relation
* @param array $data
*/
protected function saveManyToManyRelation(Model $model, string $relation, array $data)
{
$synced = $model->$relation()->sync(collect($data)->pluck('id'));
$model->setRelation($relation, $synced['updated']);
}
/**
* Сохраняет и устанавливает HasMany отношения.
*
* @param Model $model
* @param string $relation
* @param array $data
*/
protected function saveHasManyRelation(Model $model, string $relation, array $data)
{
$model->$relation()->delete();
$model->setRelation($relation, $model->$relation()->createMany($data));
}
/**
* Сохраняет и устанавливает HasOne отношения.
*
* @param Model $model
* @param string $relation
* @param array $data
*/
protected function saveHasOneRelation(Model $model, string $relation, array $data)
{
$model->$relation()->delete();
$model->setRelation($relation, $model->$relation()->create($data));
}
} | true |
38f9b16c87a5cfe6df713144c49b28ace902113a | PHP | abouba1997/Blog | /pages/connexion.php | UTF-8 | 3,633 | 2.578125 | 3 | [] | no_license | <?php
require '../db/connexion_db.php';
$checked = false;
$errors = array();
if(isset($_POST['pseudo']) AND isset($_POST['password'])) {
if(!empty($_POST['pseudo']) && !empty($_POST['password'])) {
if(preg_match("/^[a-zA-Z-]*$/", strip_tags(html_entity_decode($_POST['pseudo'])))) {
$pseudo = strip_tags(html_entity_decode($_POST['pseudo']));
$sql = "SELECT id, password FROM members WHERE pseudo = :pseudo";
$req = $db->prepare($sql);
$req->execute(array('pseudo' => $pseudo));
$result = $req->fetch();
if($result) {
$password = strip_tags(html_entity_decode($_POST['password']));
$isPasswordCorrect = password_verify(strip_tags(html_entity_decode($_POST['password'])), $result['password']);
$checked = $_POST['connexion_auto'];
if($isPasswordCorrect) {
session_start();
$_SESSION['id'] = $result['id'];
if($checked == true) {
setcookie('pseudo', $pseudo, time() + (86400 * 30), null, null, false, true);
setcookie('password', $password, time() + (86400 * 30), null, null, false, true);
}
header("Location: ../index.php");
} else {
array_push($errors, "Mauvais identifiant ou mot de passe.");
}
} else {
array_push($errors, "Mauvais identifiant ou mot de passe.");
}
} else {
array_push($errors, 'Pseudo incorrect.');
}
}else {
array_push($errors, 'Pseudo incorrect', 'Mot de passe incorrect');
}
}
require '../part/header.php';
?>
<div class="connexion">
<div class="connexion-dev">
<div class="errors">
<ul>
<?php foreach($errors as $error): ?>
<li><?= $error; ?></li>
<?php endforeach; ?>
</ul>
</div>
<form method="post">
<div class="row">
<div class="col-25">
<label for="pseudo">Pseudo: </label>
</div>
<div class="col-75">
<input type="text" name="pseudo" id="pseudo">
</div>
</div>
<div class="row">
<div class="col-25">
<label for="password">Mot de passe: </label>
</div>
<div class="col-75">
<input type="password" name="password" id="password">
</div>
</div>
<div class="row">
<div class="col-25">
<label for="connexion_auto">Connexion automatique : </label>
</div>
<div class="col-75">
<input type="checkbox" name="connexion_auto" id="connexion_auto">
</div>
</div>
<div class="row">
<div class="row-submit">
<input type="submit" value="Connecter">
</div>
</div>
</form>
</div>
</div>
<?php require '../part/footer.php'; ?> | true |
7621bc4410cb78293c4daf28ec6f76830e0509ca | PHP | fourotthomas/webflix | /scripts/insert-actor.php | UTF-8 | 1,743 | 2.890625 | 3 | [] | no_license | <?php
// J'inclus la connexion à la base de données
require __DIR__.'/../config/database.php';
$actors = [
['Pacino', 'Al', '1940-04-25'],
['Brando', 'Marlon', '1924-04-03'],
['de Niro', 'Robert', '1943-08-17'],
['Willis', 'Bruce', '1955-03-19'],
['Liotta', 'Ray', '1954-12-18'],
['Snipes', 'Wesley', '1962-07-31'],
['Stalone', 'Sylvester', '1946-07-06'],
['Norton', 'Edward', '1969-08-18'],
['Spacey', 'Kevin', '1959-07-26'],
['Kilmer', 'Val', '1959-12-31'],
// Simulation d'une injection SQL
['Milou', "Tintin'); INSERT INTO actor (name, firstname, birthday) VALUES ('HACKED', 'HACKED', '1991-11-18');", '1999-12-25'],
];
$db->query('SET FOREIGN_KEY_CHECKS = 0');
$db->query('TRUNCATE actor');
$db->query('SET FOREIGN_KEY_CHECKS = 1');
foreach ($actors as $actor) {
// $db->query("INSERT INTO actor (name, birthday, firstname) VALUES ('$actor[0]', '$actor[2]', '$actor[1]')");
echo "INSERT INTO actor (name, birthday, firstname) VALUES ('$actor[0]', '$actor[2]', '$actor[1]')";
// echo '<br />'.PHP_EOL;
// On peut écrire une requête préparée pour se protéger des injections SQL. Les injections SQL ne sont possibles que
// s'il y a dans la requête une concaténation avec des entrées utilisateurs ($_GET, $_POST).
// Dans une requête préparée, on a des paramètres qui ressemblent à :colonne
$query = $db->prepare("INSERT INTO actor (name, firstname, birthday) VALUES (:name, :firstname, :birthday)");
// On renseigne chaque paramètre de la requête
$query->bindValue(':name', $actor[0]);
$query->bindValue(':firstname', $actor[1]);
$query->bindValue(':birthday', $actor[2]);
// On exécute la requête
$query->execute();
} | true |
106cf700f45b5a294c8081a37daa7195b24911e1 | PHP | nathan78370/Login | /login.php | UTF-8 | 903 | 2.828125 | 3 | [] | no_license | <?php
if (isset($_POST['submit']))
{
$username = $_POST['username'];
$pass = $_POST['pass'];
$db = new PDO('mysql:host=localhost;dbname=loginsystem','root','');
foreach($db->query('SELECT * from user') as $row) {
print_r($row);
}
$dbh = null;
} catch (PDOException $e) {
print "Erreur !: " . $e->getMessage() . "<br/>";
die();
$sql = "SELECT * FROM user where username = '$username' ";
$result = $db->prepare($sql);
$result->execute();
if($result->rowCount() > 0)
{
}
else
{
$pass = password_hash($pass, PASSWORD_DEFAULT);
$sql = "INSERT INTO user (username, password) VALUES ('$username','$pass')";
$req = $db->prepare($sql);
$req->execute();
echo "Enregistrement effectué";
echo('<br />');
echo $username;
echo('<br />');
echo $pass;
}
}
?> | true |
e941c21fb59fc2999b8f0c9bbe906e0390efe631 | PHP | PetyaKatsarova/softuni_php_sql | /15.Encapsulation_inheritance/ShoppingSpree/Person.php | UTF-8 | 2,750 | 3.6875 | 4 | [] | no_license | <?php
class Person{
/** @var string */
private $name;
/** @var float*/
private $money;
/** @var Product[] | array*/
private $products;
public function __construct(string $name, float $money)
{
$this->setName($name);
$this->setMoney($money);
$this->products = [];
}
private function setName($name):void{
if(empty($name)){
throw new Exception("name cannot be empty.");
}
$this->name = $name;
}
public function getName():string{
return $this->name;
}
private function setMoney(float $money){
if($money<0){
throw new Exception('Money cannot be negative.');
}
$this->money = $money;
}
public function getMoney():float{
return $this->money;
}
// setter for products
public function addProduct(Product $product):void{
$this->products[] = $product;
}
public function getProducts(){
return $this->products;
}
private function cantAffordProduct(Product $product):bool{
return $product->getCost() > $this->getMoney();
}
public function buyProduct(Product $product){
if($this->cantAffordProduct($product)){
throw new Exception(message: "{$this->getName()} can't affort {$product->getName()}<br/>");
// !!!!!!!!!!!!!! when i use try-catch in the class instance and $ex->getMessage()will give me this message!!!!!!!!!!!!!!!!!!!!
}else{
$this->setMoney($this->getMoney() - $product->getCost());
// $this->products[] = $product;
$this->addProduct($product);
echo "{$this->getName()} bought {$product->getName()}<br/>";
}
}
public function __toString()
{
return count($this->getProducts()) === 0 ?
$this->getName() . " - Nothing bought<br/>" :
$this->getName() . ' - ' .implode(',',
array_map(function(Product $product){
return $product->getName();
},
$this->getProducts())) . "<br/>";
// another solution
if(count($this->getProducts()) === 0){
return $this->getName() . " - Nothing bought<br/>";
}
return $this->getName() . ' - ' .implode(',',
array_map(function(Product $product){
return $product->getName();
},
$this->getProducts())) . "<br/>";
// another solution
// foreach($this->getProducts() as $product){
// $output .= $product->getName() . ',';
// }
// return substr($output,0,strrpos($output, ',')) . "<br/>";
}
}
| true |
16ff447038765f9a1fcf437a19edd9b3491a20aa | PHP | KaijiS/EC_exercise_Phalcon | /api/app/library/CheckImage.php | UTF-8 | 882 | 2.84375 | 3 | [] | no_license | <?php
use Phalcon\Mvc\User\Component;
class CheckImage extends Component
{
function getMimeType($raw_data){
/*
データのMIME情報を返す
*/
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_buffer($finfo, $raw_data);
finfo_close($finfo);
return $mime;
}
function checkMimeType($mime){
/*
画像データのMIMEタイプのチェックを行う
画像用のMIMEではない場合はエラーを出す
*/
switch($mime){
case 'image/gif':
break;
case 'image/jpeg':
break;
case 'image/bmp':
break;
case 'image/png':
break;
default:
throw new RuntimeException('画像形式が誤っています');
}
}
} | true |
006f47e5bf840a80de9e2d968c41557d2abb14be | PHP | pedromazala/docer-holding-challenge | /src/Logger/StdoutLogger.php | UTF-8 | 150 | 2.9375 | 3 | [] | no_license | <?php
namespace Language\Logger;
class StdoutLogger implements Logger
{
public function print(string $line)
{
echo $line;
}
}
| true |
9cbd5e7140538a265d015d0d696cad09f294ac6b | PHP | gurkiratThind/Asian-Swords | /exercises/exe6-6/tools.php | UTF-8 | 1,555 | 3.234375 | 3 | [] | no_license | <?php
/**
* prevent loading of tools.php directly
* must go through index.php first.
*/
if (!isset($index_loaded)) {
die('Direct acces to this file is forbidden');
}
/**
* this file contain utility functions.
*/
/**
* Display any one dimensional array.
*/
function array_display($array_name)
{
$r = '';
$r .= '<style> table,td,th{border: solid 2px black;}</style>';
$r .= '<table>';
$r .= '<tr>';
$r .= '<th>Index/Key</th>';
$r .= '<th>Value</th>';
$r .= '</tr>';
foreach ($array_name as $index => $value) {
$r .= '<tr>';
$r .= '<td> '.$index.' </td>';
if ($index == 'price') {
$r .= '<td> $'.$value.' </td>';
$r .= '</tr>';
} else {
$r .= '<td>'.$value.' </td>';
$r .= '</tr>';
}
}
$r .= '</table>';
return $r;
}
/**
* Multi-Dimensional Array Display Function.
*/
function multiple_arrayDisplay($multiple_array)
{
$r = '';
$r .= '<style> td,th{border: solid 2px black;}</style>';
$r .= '<table>';
$r .= '<tr>';
foreach ($multiple_array[0] as $key => $value) {
$r .= '<th>'.$key.'</th>';
}
$r .= '</tr>';
foreach ($multiple_array as $key => $value) {
$r .= '<tr>';
foreach ($value as $key1 => $value1) {
if ($key1 == 'price') {
$r .= '<td> $'.$value1.' </td>';
} else {
$r .= '<td>'.$value1.' </td>';
}
}
$r .= '</tr>';
}
$r .= '</table>';
return $r;
}
| true |
9e5a8c3561764cec6dced5ba75f88f277fdeb33c | PHP | thdan109/admin-webshop | /thongke.php | UTF-8 | 3,370 | 2.640625 | 3 | [] | no_license | <?php
include("../home/moduls/connection.php");
if (isset($_GET['month'])){
$month=$_GET['month'];
}else{
$month= date('m');
}
$sel = "SELECT * FROM `thongke` WHERE MONTH(ngaydat) =$month ";
$rs = $connect->query($sel);
$chart = "SELECT sanphamdadat , sum(`soluong`) as tongsl, sum(`giasp`)*sum(`soluong`) as gia FROM `thongke` WHERE MONTH(ngaydat) = $month GROUp BY sanphamdadat";
$rs1 = $connect ->query($chart);
$sel1 = "SELECT sanphamdadat , sum(`soluong`) as tongsl, `giasp`*sum(`soluong`) as gia FROM `thongke` WHERE MONTH(ngaydat) = $month GROUp BY sanphamdadat";
$rs2 = $connect->query($sel1);
$chartall = "SELECT sum(`soluong`) as tongsl,sum(giasp*soluong) as gia, MONTH(ngaydat) as thang FROM `thongke` GROUp BY MONTH(ngaydat)";
$rs_all = $connect ->query($chartall);
$dataPoints = array();
$sum=0;
$summ=0;
while ($row1 = $rs -> fetch_assoc()){
$sum = $row1['giasp']*$row1['soluong'];
$summ += $sum;
}
while ($row = $rs_all -> fetch_assoc()){
array_push($dataPoints,array('label' => 'Tháng '.$row['thang'], 'y'=>$row['gia']));
}
?>
<!DOCTYPE HTML>
<html>
<head>
<script>
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
theme: "light2", // "light1", "light2", "dark1", "dark2"
title: {
text: ""
},
axisY: {
title: "Biểu đồ mua bán sản phẩm",
includeZero: false
},
data: [{
type: "column",
dataPoints: <?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
}]
});
chart.render();
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<table class="banghienthi" style="margin: auto; width: 800px">
<tr>
<th colspan=3>
<select onchange="thongke()" name="" id="month" style="width: 400px; ">
<?php
for ($i=1;$i<13;$i++){
?>
<option
<?php
if ($month==$i){
?>
selected = "selected";
<?php
}
?>
value="<?php echo $i;?>" > Tháng <?php echo $i;?>
</option>
<?php
}
?>
</select>
</th>
</tr>
<tr>
<th>Tên sản phẩm</th>
<th>Số lượng</th>
<th>Tổng tiền</th>
</tr>
<?php
while ($rows = $rs2 ->fetch_assoc()){
echo "<tr>";
echo "<td>".$rows['sanphamdadat']."</td>";
echo "<td>".$rows['tongsl']."</td>";
echo "<td>".$rows['gia']."</td>";
echo "</tr>";
$spthongke=$rows['sanphamdadat'];
$tongsl_thongke= $rows['tongsl'];
$gia_thongke = $rows['gia'];
}
echo "Tổng doanh thu: ".number_format($summ);
?>
</table>
</body>
</html>
<script>
function thongke(){
var months = document.getElementById('month');
var select1 = months.options[months.selectedIndex].value;
window.location.href = 'indexad.php?view=thongke&month='+select1;
}
</script> | true |
eee361286e3d0cbf7674b2514606c71064ef0c8b | PHP | egaraev/PHP | /Service_PHP_script/www/admin/lib/other.inc | WINDOWS-1252 | 7,471 | 2.859375 | 3 | [] | no_license | <?php
function d($var)
{
print '<pre style="background: #000; color: #0f0; border: 1px solid #0f0; font: 12px Courier-New;">';
$ret = print_r($var, true);
$ret = str_replace('=>', '<font color="#ffffff">=></font>', $ret);
#$ret = preg_replace('#Array\n\((.*)\n\)#ms', '<div style="border: 1px solid #0f0;">\\0</div>', $ret);
print $ret;
print '</pre>';
}
/**
* Prepare a variable to use in date base
* Deleting dangerous symbols
*
* @param string $variable
**/
function danger_var($variable)
{
if (get_magic_quotes_gpc())
{
return $variable;
}
// array
if (is_array($variable))
{
foreach($variable as $var)
{
$var = addslashes($var);
}
}
// variable
else
{
$variable = addslashes($variable);
}
return $variable;
}
function get_real_ip()
{
global $HTTP_ENV_VARS, $HTTP_SERVER_VARS, $REMOTE_ADDR;
if( getenv('HTTP_X_FORWARDED_FOR') != '' )
{
$client_ip = ( !empty($HTTP_SERVER_VARS['REMOTE_ADDR']) ) ? $HTTP_SERVER_VARS['REMOTE_ADDR'] : ( ( !empty($HTTP_ENV_VARS['REMOTE_ADDR']) ) ? $HTTP_ENV_VARS['REMOTE_ADDR'] : $REMOTE_ADDR );
$entries = explode(',', getenv('HTTP_X_FORWARDED_FOR'));
reset($entries);
while (list(, $entry) = each($entries))
{
$entry = trim($entry);
#if ( preg_match("/^([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)/", $entry, $ip_list) )
#{
# $private_ip = array('/^0\./', '/^127\.0\.0\.1/', '/^192\.168\..*/', '/^172\.((1[6-9])|(2[0-9])|(3[0-1]))\..*/', '/^10\..*/', '/^224\..*/', '/^240\..*/');
# $found_ip = preg_replace($private_ip, $client_ip, $ip_list[1]);
# if ($client_ip != $found_ip)
# {
# $client_ip = $found_ip;
# break;
# }
#}
}
}
else
{
$client_ip = ( !empty($HTTP_SERVER_VARS['REMOTE_ADDR']) ) ? $HTTP_SERVER_VARS['REMOTE_ADDR'] : ( ( !empty($HTTP_ENV_VARS['REMOTE_ADDR']) ) ? $HTTP_ENV_VARS['REMOTE_ADDR'] : $REMOTE_ADDR );
}
return $client_ip;
}
function redirect($url)
{
if(headers_sent())
{
print "<meta http-equiv=\"refresh\" content=\"0;url=".$url."\">";
}
else
{
header('Location: '.$url);
}
}
// IN: 127.0.0.1
// OUT: 7f000001
function encode_ip($dotquad_ip)
{
$ip_sep = explode('.', $dotquad_ip);
return sprintf('%02x%02x%02x%02x', $ip_sep[0], $ip_sep[1], $ip_sep[2], $ip_sep[3]);
}
// IN: 7f000001
// OUT: 127.0.0.1
function decode_ip($encoded_ip)
{
$ip_sep[0] = substr($encoded_ip, 0, 2);
$ip_sep[1] = substr($encoded_ip, 2, 2);
$ip_sep[2] = substr($encoded_ip, 4, 2);
$ip_sep[3] = substr($encoded_ip, 6, 2);
return hexdec($ip_sep[0]).'.'.hexdec($ip_sep[1]).'.'.hexdec($ip_sep[2]).'.'.hexdec($ip_sep[3]);
}
function is_empty($str)
{
if (trim($str) == '') return true;
else return false;
}
/**
* , safe_mode
*
* @author baxi
*
* @param string $patchname
* @param oct $mode
* @param array $ftp
*/
function makedir($patchname, $mode = 0777, $ftp = array())
{
if (!ini_get('safe_mode'))
{
mkdir($patchname, $mode);
}
else if (sizeof($ftp) == 3) // server, login, password
{
if ($conn_id = ftp_connect($ftp['server']))
{
if (ftp_login($conn_id, $ftp['login'], $ftp['password']))
{
$patch = explode('/', $patchname);
for ($i=0; $i<sizeof($patch); $i++)
{
if (!$patch[$i]) continue;
if (!@ftp_chdir($conn_id, $patch[$i]))
{
if (ftp_mkdir($conn_id, $patch[$i]))
{
ftp_site($conn_id, 'CHMOD '.decoct($mode).' '.$patch[$i]);
ftp_chdir($conn_id, $patch[$i]);
} else {return -4;} // ERROR: Directory create error
}
}
} else {return -3;} // ERROR: Login error
} else {return -2;} // ERROR: Can't connect
} else {return -1;} // ERROR: Require array (server => '', login => '', password => '')
return true;
}
//transliterating
function translit($string, $allow_slashes = 0)
{
$slash = "";
if ($allow_slashes) $slash = "\/";
static $LettersFrom = "";
static $LettersTo = "abvgdeziklmnoprstufyejxe";
static $Consonant = "";
static $Vowel = "";
static $BiLetters = array(
"" => "zh", ""=>"ts", "" => "ch",
"" => "sh", "" => "sch", "" => "ju", "" => "ja",
);
$string = preg_replace("/[_\s\.,?!\[\](){}]+/", "_", $string);
$string = preg_replace("/-{2,}/", "--", $string);
$string = preg_replace("/_-+_/", "--", $string);
$string = preg_replace("/[_\-]+$/", "", $string);
$string = strtolower( $string );
//here we replace /
$string = preg_replace("/(|)([".$Vowel."])/", "j\\2", $string);
$string = preg_replace("/(|)/", "", $string);
//transliterating
$string = strtr($string, $LettersFrom, $LettersTo );
$string = strtr($string, $BiLetters );
$string = preg_replace("/j{2,}/", "j", $string);
$string = preg_replace("/[^".$slash."0-9a-z_\-]+/", "", $string);
return $string;
}
function log_write($action, $info)
{
global $user_id;
switch($action)
{
case 'add_post':
case 'del_post':
case 'edit_post':
}
mysql_query("INSERT INTO `log` (
`log_id` ,
`log_user` ,
`log_time` ,
`log_action` ,
`log_info` )
VALUES (
'',
'".$user_id."',
'".time()."',
'".$action."',
'".$info."')");
}
function db_get_columns($table_name)
{
$res = mysql_query('SELECT * FROM '.$table_name.' LIMIT 0,1');
$res = mysql_query('SHOW FIELDS FROM '.$table_name);
while($x = mysql_fetch_assoc($res))
{
$type = $x['Type'];
if(false === strstr($type, '('))
{
$type .= '()';
}
preg_match('/(.*)\((.*)\)/', $type, $info);
d($info);
$ret[$x['Field']] = array(
'type' => $info[1],
'size' => ($info[2] ? $info[2] : 0),
'values' => ($info[1] == 'enum' ? explode(',', $info[2]) : '')
);
}
d($ret);
/*
$i = 0;
while ($i < mysql_num_fields($res))
{
$meta = mysql_fetch_field($res, $i);
#d($meta);
// If there is column and column name IS NOT "item_id"
if ($meta && $meta->name != 'item_id')
{
$ret[$meta->name] = $meta->type;
}
$i++;
}
*/
// If there is at least one column
if (isset($ret))
{
return $ret;
}
}
function time_local()
{
if (defined('TIME_ZONE'))
{
return time() + TIME_ZONE * 3600;
}
else
{
return time();
}
}
function print_sql($string)
{
$string = preg_replace('#[0-9]+#i', "<font color=#ff0000>\\0</font>", $string);
$string = preg_replace('#[a-zA-Z]+\.#i', "<font color=#0000f0><b>\\0</b></font>", $string);
$string = preg_replace('#(select|update|delete|insert|from|where|order|limit)#i', "\n<font color=#ff6600>\\0</font>\n\t", $string);
$string = preg_replace('#( AS )#i', "<font color=#808000><b>\\0</b></font>", $string);
$string = preg_replace('#( AND | OR )#i', "\n\t<font color=#008000><b>\\0</b></font>", $string);
$string = preg_replace('#\'(.*)\'#i', "<font color=#0000f0>\\0</font>", $string);
print "<pre style='background: #eee; border: 1px black solid; margin: 20px; padding: 5px;'>".$string."</pre>";
}
function pgt_microtime() {
global $microtime, $foother_info;
list($usec, $sec) = explode(" ", microtime());
if ($microtime > 0)
{
$now = ((float)$usec + (float)$sec);
return round($now - $microtime, 3);
}
else
{
$microtime = ((float)$usec + (float)$sec);
}
}
/**
* Validate email address
*
* @param string $email
* @return bool
*/
function is_email ($email)
{
// Hase '@'
if ($domain = strstr($email, '@'))
{
// Hase '.'
if (strstr($domain, '.'))
{
return true;
}
}
return false;
}
?> | true |
c405ad81fbcce0611e6da5318cf488a3aa46c801 | PHP | oxkhar/payslips | /src/Application/ModifyTaxRateAction.php | UTF-8 | 724 | 2.859375 | 3 | [] | no_license | <?php declare(strict_types=1);
namespace Payslip\Application;
use Payslip\Domain\PayslipRepository;
class ModifyTaxRateAction
{
/**
* @var PayslipRepository
*/
private $payslipRepository;
public function __construct(PayslipRepository $payslipRepository)
{
$this->payslipRepository = $payslipRepository;
}
public function action(string $month, string $year, float $taxRate): ActionResponse
{
$response = [];
$payslips = $this->payslipRepository->findByMonthAndYear($month, $year);
foreach ($payslips as $payslip) {
$response[] = $payslip->modifyTaxRate($taxRate);
}
return PayslipResponse::fromList($response);
}
}
| true |
7373b91788ac2e47850b2e7604fb1848c6b1c5a1 | PHP | robbenmu/csscaffold | /system/core/Exception.php | UTF-8 | 798 | 3.140625 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
/**
* Creates a generic exception.
*/
class Scaffold_Exception extends Exception
{
# Header
protected $header = FALSE;
# Scaffold error code
protected $code = 42;
/**
* Set exception message.
*
* @param string i18n language key for the message
* @param array addition line parameters
*/
public function __construct($message)
{
# Sets $this->message the proper way
parent::__construct($message);
}
/**
* Magic method for converting an object to a string.
*
* @return string i18n message
*/
public function __toString()
{
return (string) $this->message;
}
/**
* Sends an Internal Server Error header.
*
* @return void
*/
public function sendHeaders()
{
// Send the 500 header
header('HTTP/1.1 500 Internal Server Error');
}
} | true |
d1eb55f83776ac007b11140f6f222dfb18bee3b7 | PHP | concretecms/community_badges | /src/PortlandLabs/CommunityBadges/API/V1/CommunityBadges.php | UTF-8 | 3,953 | 2.609375 | 3 | [] | no_license | <?php
/**
* @project: Community Badges
*
* @copyright (C) 2021 Portland Labs (https://www.portlandlabs.com)
* @author Fabian Bitter (fabian@bitter.de)
*/
namespace PortlandLabs\CommunityBadges\API\V1;
use Concrete\Core\Application\EditResponse;
use Concrete\Core\Error\ErrorList\ErrorList;
use Concrete\Core\Http\Request;
use Concrete\Core\Http\Service\Json;
use Concrete\Core\User\User;
use League\Fractal\Resource\Collection;
use PortlandLabs\CommunityBadges\AwardService;
use PortlandLabs\CommunityBadges\Exceptions\GrantBadgeNotFound;
use PortlandLabs\CommunityBadges\Exceptions\InvalidSelfAssignment;
use PortlandLabs\CommunityBadges\Exceptions\MailTransportError;
use PortlandLabs\CommunityBadges\Exceptions\NoAuthorization;
use PortlandLabs\CommunityBadges\Exceptions\NoUserSelected;
use Symfony\Component\HttpFoundation\JsonResponse;
class CommunityBadges
{
protected $awardService;
protected $request;
public function __construct(
AwardService $awardService,
Request $request
)
{
$this->awardService = $awardService;
$this->request = $request;
}
public function getList()
{
$achievements = $this->awardService->getAllAchievements();
return new JsonResponse($achievements);
}
public function giveAward()
{
$editResponse = new EditResponse();
$errorList = new ErrorList();
if (!$this->request->request->has("grantedAwardId") || $this->request->request->getInt("grantedAwardId") === 0) {
$errorList->add(t("Missing granted award id."));
} else if (!$this->request->request->has("user") || $this->request->request->getInt("user") === 0) {
$errorList->add(t("You need to select a valid user."));
} else {
$grantAwardId = $this->request->request->getInt("grantedAwardId", 0);
$userId = $this->request->request->getInt("user", 0);
$user = User::getByUserID($userId);
try {
$grantedAward = $this->awardService->getGrantAwardById((int)$grantAwardId);
$this->awardService->giveGrantedAward($grantedAward, $user);
$editResponse->setMessage(t("Award successfully given to the user %s.", $user->getUserName()));
} catch (GrantBadgeNotFound $e) {
$errorList->add(t("You need to select a valid grant award."));
} catch (MailTransportError $e) {
$errorList->add(t("There was an error while sending the mail notification."));
} catch (NoUserSelected $e) {
$errorList->add(t("You need to select a user."));
} catch (NoAuthorization $e) {
$errorList->add(t("You can't give away an granted award that you don't own by yourself."));
} catch (InvalidSelfAssignment $e) {
$errorList->add(t("You can't award yourself."));
}
}
$editResponse->setError($errorList);
return new JsonResponse($editResponse);
}
public function dismissGrantAward()
{
$editResponse = new EditResponse();
$errorList = new ErrorList();
if (!$this->request->request->has("grantedAwardId") || $this->request->request->getInt("grantedAwardId") === 0) {
$errorList->add(t("Missing granted award id."));
} else {
$grantAwardId = $this->request->request->getInt("grantedAwardId", 0);
try {
$grantedAward = $this->awardService->getGrantAwardById((int)$grantAwardId);
$this->awardService->dismissGrantedAward($grantedAward);
} catch (GrantBadgeNotFound $e) {
$errorList->add(t("You need to select a valid grant award."));
}
$editResponse->setMessage(t("Award successfully dismissed."));
}
$editResponse->setError($errorList);
return new JsonResponse($editResponse);
}
} | true |
1dd976b12ba2deb09dc4ab702eac98d45eec5b26 | PHP | wifidu/LeetCode | /回朔/组合总和.php | UTF-8 | 1,111 | 3.4375 | 3 | [] | no_license | <?php
Class Solution{
public function combinationSum(array $candidates, int $target)
{
$res = [];
$len = count($candidates);
sort($candidates);
$this->dfs($candidates, $len, $target, 0, [], $res);
return $res;
}
/**
* @param candidates 数组输入
* @param len 输入数组的长度,冗余变量
* @param residue 剩余数值
* @param begin 本轮搜索的起点下标
* @param path 从根结点到任意结点的路径
* @param res 结果集变量
*/
private function dfs(array $candidates, int $len, int $residue, int $begin, array $path, array $res)
{
if ($residue == 0) {
array_push($res, $path);
return ;
}
for ($i = $begin; $i < $len; $i ++) {
if ($residue - $candidates[$i] < 0) {
break;
}
array_push($path, $candidates[$i]);
$this->dfs($candidates, $len, $residue - $candidates[$i], $i, $path, $res);
array_pop($path);
}
}
}
?>
| true |
ea238d27380a86e1a716d443e15cd5af86fd657b | PHP | R11baka/Omdb | /src/Api/ApiFactory.php | UTF-8 | 372 | 2.71875 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types=1);
namespace Omdb\Api;
use Omdb\Api\HttpClient\CurlClient;
class ApiFactory
{
private string $apiKey;
public function __construct(string $apiKey)
{
$this->apiKey = $apiKey;
}
public function make(): ApiInterface
{
$client = new CurlClient();
return new Api($client, $this->apiKey);
}
}
| true |
494cbe96f68bf46a7234552ed19fe38e2a978278 | PHP | rendyss/sstestimonials_v2 | /sstestimonials-v2/includes/class-sstestimonials-v2-widget.php | UTF-8 | 2,055 | 2.71875 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: ASUS
* Date: 2/11/2019
* Time: 2:52 AM
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( ! class_exists( 'SSTestimonialsV2_Widget' ) ) {
class SSTestimonialsV2_Widget extends WP_Widget {
protected $pluginName;
protected $widgetName;
public function __construct( $pluginName ) {
$this->pluginName = $pluginName;
$this->widgetName = $this->pluginName . "_widget";
$widget_options = array(
'classname' => $this->widgetName,
'description' => 'This is a super simple widget to display random testimonials',
);
parent::__construct( $this->widgetName, 'Random Testimonial', $widget_options );
}
public function widget( $args, $instance ) {
$title = apply_filters( 'widget_title', $instance['title'] );
echo $args['before_widget'] . $args['before_title'] . $title . $args['after_title'];
$ssTestimonialsIO = new SSTestimonialsV2_IO();
$ssTestimonialsTemplate = new SSTestimonialsV2_Template( plugin_dir_path( dirname( __FILE__ ) ) . 'templates' );
$random_testi = $ssTestimonialsIO->get_random();
if ( $random_testi ) {
echo $ssTestimonialsTemplate->render( 'sstestimonials-v2-front-layout', array(
'name' => $random_testi['name'],
'text' => $random_testi['text'],
'time' => $random_testi['time']
) );
} else {
echo "<i>Data not found</i>";
}
echo $args['after_widget'];
}
public function form( $instance ) {
$title = ! empty( $instance['title'] ) ? $instance['title'] : ''; ?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>">Title:</label>
<input type="text" id="<?php echo $this->get_field_id( 'title' ); ?>"
name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo esc_attr( $title ); ?>"/>
</p><?php
}
public function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance['title'] = strip_tags( $new_instance['title'] );
return $instance;
}
}
} | true |
078d1d4dec7a01e0da3ba658423d23b146e4bcf6 | PHP | Boutanche/MCMP_Tests | /Poubelle/post_log.php | UTF-8 | 2,260 | 2.546875 | 3 | [] | no_license | <?php
/*
if(!empty($_POST)) {
if (isset($_POST['formulaire'])) {
if ($_POST['formulaire'] == 'log') {
if(isset($_POST['login']) AND isset($_POST['password'])) {
if (!empty($_POST['login']) and !empty($_POST['password'])) {
//TODO: Securité :
$req_log = $bdd->prepare('SELECT IdAdherent, Nom, Prenom, Organisateur, Password, Login FROM adherent WHERE Login = :log');
$req_log->execute(array(
'log' => $_POST['login'],
));
$resultat_login = $req_log->fetch();
if(!$resultat_login) {
$message_log = "Mauvais identifiant";
$page = 'accueil';
sleep(1);
}
else {
//Comparaison du pass
$isPasswordCorrect = password_verify($_POST['password'], $resultat_login['Password']);
if ($isPasswordCorrect) {
//$hashed_password = My_Crypt($_POST["password"]);
//if ($_POST['password'] == $resultat_login['Password']){
$nom = $resultat_login['Nom'];
$prenom = $resultat_login['Prenom'];
$_SESSION['id_adherent'] = $resultat_login['IdAdherent'];
$_SESSION['nom'] = $nom;
$_SESSION['prenom'] = $prenom;
$user_level = 1;
if ($resultat_login['Organisateur'] == 1) {
$user_level = 2;
}
$_SESSION['user_level'] = $user_level;
$message_log = "Bravo " . $prenom . " " . $nom . " vous êtes connecté!";
$page = $homepage;
} else {
$message_log = "Identifiant ou mot de passe invalide";
$page = 'accueil';
sleep(1);
}
}
}
}
}
}
}
*/ | true |
9939a1b341f8a70aebbc9813c987338e2cb7aeb5 | PHP | lipemascarenhas/PHP_practices | /PHP/Aulas_PHP/Basic_PHP/aula19/01manuseando_array.php | UTF-8 | 561 | 3.890625 | 4 | [] | no_license | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vetores e Matrizes</title>
</head>
<body>
<pre>
<?php
$v = array("A", "J", "M", "X", "K");
print "<p>-print_r: </p>";
print_r($v);
print "<p>-var_dump: </p>";
var_dump($v);
print "<p>-count:</p>";
$tot = count($v);
print "<p>O vetor tem $tot elementos</p>";
$v[] = "O";
print "<p>-Vetor V depois de acrescentarmos uma string à array</p>";
print_r($v);
?>
</pre>
</body>
</html>
| true |
f726ade1dcf8ec8b7aedd3651b203a89996a4d17 | PHP | justmiles94/Phase5_TeamAnger | /PHP/login.php | UTF-8 | 352 | 2.515625 | 3 | [] | no_license | <?php
/*
CONNECT-DB.PHP
Allows PHP to connect to your database
*/
include('connectStarTrekDB.php');
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "select * from users where username='".$username."' and password='".$password."'";
if ($connection->query($sql)->num_rows > 0) {
echo "true";
} else {
echo "false";
}
?> | true |
8f30684f9a86cdf0c3b2087d4a63feffb413d4a7 | PHP | bracey-coder/Codeigniter-shop-cms | /application/helpers/youtube_video_helper.php | UTF-8 | 1,275 | 2.8125 | 3 | [] | no_license | <?php if (!defined('BASEPATH')) exit('No direct script access allowed');
// Create youtube video link for representing a video
function show_youtube($video_link)
{
if (!empty($video_link)) {
return 'http://www.youtube.com/v/' . _get_youtube_id_from_url($video_link);
}
}
// Get youtuve video id from url
function _get_youtube_id_from_url($url)
{
$pattern =
'%^# Match any youtube URL
(?:https?://)? # Optional scheme. Either http or https
(?:www\.)? # Optional www subdomain
(?: # Group host alternatives
youtu\.be/ # Either youtu.be,
| youtube\.com # or youtube.com
(?: # Group path alternatives
/embed/ # Either /embed/
| /v/ # or /v/
| /watch\?v= # or /watch\?v=
) # End path alternatives.
) # End host alternatives.
([\w-]{10,12}) # Allow 10-12 for 11 char youtube id.
$%x'
;
$result = preg_match($pattern, $url, $matches);
if (false !== $result) {
return $matches[1];
}
return false;
}
?> | true |
154a63a84a64736d559f4352b1568e23df32394b | PHP | rectorphp/rector | /rules/TypeDeclaration/NodeAnalyzer/CallTypesResolver.php | UTF-8 | 4,815 | 2.5625 | 3 | [
"MIT"
] | permissive | <?php
declare (strict_types=1);
namespace Rector\TypeDeclaration\NodeAnalyzer;
use PhpParser\Node\Arg;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Expr\StaticCall;
use PHPStan\Reflection\ReflectionProvider;
use PHPStan\Type\MixedType;
use PHPStan\Type\NullType;
use PHPStan\Type\ObjectType;
use PHPStan\Type\ThisType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeWithClassName;
use PHPStan\Type\UnionType;
use Rector\NodeCollector\ValueObject\ArrayCallable;
use Rector\NodeTypeResolver\NodeTypeResolver;
use Rector\NodeTypeResolver\PHPStan\Type\TypeFactory;
final class CallTypesResolver
{
/**
* @readonly
* @var \Rector\NodeTypeResolver\NodeTypeResolver
*/
private $nodeTypeResolver;
/**
* @readonly
* @var \Rector\NodeTypeResolver\PHPStan\Type\TypeFactory
*/
private $typeFactory;
/**
* @readonly
* @var \PHPStan\Reflection\ReflectionProvider
*/
private $reflectionProvider;
public function __construct(NodeTypeResolver $nodeTypeResolver, TypeFactory $typeFactory, ReflectionProvider $reflectionProvider)
{
$this->nodeTypeResolver = $nodeTypeResolver;
$this->typeFactory = $typeFactory;
$this->reflectionProvider = $reflectionProvider;
}
/**
* @param MethodCall[]|StaticCall[]|ArrayCallable[] $calls
* @return array<int, Type>
*/
public function resolveStrictTypesFromCalls(array $calls) : array
{
$staticTypesByArgumentPosition = [];
foreach ($calls as $call) {
if (!$call instanceof StaticCall && !$call instanceof MethodCall) {
continue;
}
foreach ($call->args as $position => $arg) {
if (!$arg instanceof Arg) {
continue;
}
if ($arg->unpack) {
continue;
}
$staticTypesByArgumentPosition[$position][] = $this->resolveStrictArgValueType($arg);
}
}
// unite to single type
return $this->unionToSingleType($staticTypesByArgumentPosition);
}
private function resolveStrictArgValueType(Arg $arg) : Type
{
$argValueType = $this->nodeTypeResolver->getNativeType($arg->value);
// "self" in another object is not correct, this make it independent
$argValueType = $this->correctSelfType($argValueType);
if (!$argValueType instanceof ObjectType) {
return $argValueType;
}
// fix false positive generic type on string
if (!$this->reflectionProvider->hasClass($argValueType->getClassName())) {
return new MixedType();
}
return $argValueType;
}
private function correctSelfType(Type $argValueType) : Type
{
if ($argValueType instanceof ThisType) {
return new ObjectType($argValueType->getClassName());
}
return $argValueType;
}
/**
* @param array<int, Type[]> $staticTypesByArgumentPosition
* @return array<int, Type>
*/
private function unionToSingleType(array $staticTypesByArgumentPosition) : array
{
$staticTypeByArgumentPosition = [];
foreach ($staticTypesByArgumentPosition as $position => $staticTypes) {
$unionedType = $this->typeFactory->createMixedPassedOrUnionType($staticTypes);
// narrow parents to most child type
$staticTypeByArgumentPosition[$position] = $this->narrowParentObjectTreeToSingleObjectChildType($unionedType);
}
if (\count($staticTypeByArgumentPosition) !== 1) {
return $staticTypeByArgumentPosition;
}
if (!$staticTypeByArgumentPosition[0] instanceof NullType) {
return $staticTypeByArgumentPosition;
}
return [new MixedType()];
}
private function narrowParentObjectTreeToSingleObjectChildType(Type $type) : Type
{
if (!$type instanceof UnionType) {
return $type;
}
if (!$this->isTypeWithClassNameOnly($type)) {
return $type;
}
/** @var TypeWithClassName $firstUnionedType */
$firstUnionedType = $type->getTypes()[0];
foreach ($type->getTypes() as $unionedType) {
if (!$unionedType instanceof TypeWithClassName) {
return $type;
}
if ($unionedType->isSuperTypeOf($firstUnionedType)->yes()) {
return $type;
}
}
return $firstUnionedType;
}
private function isTypeWithClassNameOnly(UnionType $unionType) : bool
{
foreach ($unionType->getTypes() as $unionedType) {
if (!$unionedType instanceof TypeWithClassName) {
return \false;
}
}
return \true;
}
}
| true |
af778fb467211fa4a7324d877f8bd0c373dc4242 | PHP | mcred/phpred | /src/cli/CLI.php | UTF-8 | 696 | 3.46875 | 3 | [] | no_license | <?php
namespace PHPRed\CLI;
abstract class CLI
{
private $stdout;
private $stderr;
private $stdin;
public function __construct($stdout = STDOUT, $stderr = STDERR, $stdin = STDIN)
{
$this->stdout = $stdout;
$this->stderr = $stderr;
$this->stdin = $stdin;
}
protected function shutDown()
{
fclose($this->stdout);
fclose($this->stderr);
fclose($this->stdin);
}
protected function output(string $statement)
{
fwrite($this->stdout, $statement . "\n");
}
protected function prompt(string $question)
{
$this->output($question);
return trim(fgets($this->stdin));
}
}
| true |
6dcd4114cc3522719e95b36c8a9343d4abd1e8b5 | PHP | NHK-13/ProjetBlog | /src/Entity/MotsCles.php | UTF-8 | 1,851 | 2.703125 | 3 | [] | no_license | <?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass="App\Repository\MotsClesRepository")
*/
class MotsCles
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
*/
private $motcle;
/**
* @ORM\Column(type="string", length=255)
*/
private $slug;
/**
* @ORM\ManyToMany(targetEntity="App\Entity\Articles", mappedBy="motcles")
*/
private $articles;
public function __construct()
{
$this->articles = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getMotcle(): ?string
{
return $this->motcle;
}
public function setMotcle(string $motcle): self
{
$this->motcle = $motcle;
return $this;
}
public function getSlug(): ?string
{
return $this->slug;
}
public function setSlug(string $slug): self
{
$this->slug = $slug;
return $this;
}
/**
* @return Collection|Articles[]
*/
public function getArticles(): Collection
{
return $this->articles;
}
public function addArticle(Articles $article): self
{
if (!$this->articles->contains($article)) {
$this->articles[] = $article;
$article->addMotcle($this);
}
return $this;
}
public function removeArticle(Articles $article): self
{
if ($this->articles->contains($article)) {
$this->articles->removeElement($article);
$article->removeMotcle($this);
}
return $this;
}
}
| true |
6fa81496592f122b5b91341eabffb1f39a2d6510 | PHP | qfz9527/ulog | /src/Formatter/DefaultFormatter.php | UTF-8 | 2,013 | 2.671875 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: nicholas
* Date: 16-4-20
* Time: 下午8:15
*/
namespace AGarage\ULog\Formatter;
use AGarage\ULog\LogEntity;
use AGarage\ULog\ULog;
class DefaultFormatter implements FormatterInterface
{
public function format(LogEntity $log)
{
$level = strtoupper($log->getLevel());
$milli = $log->getTime() % 1000;
$time = date('Y-m-d H:m:s', $log->getTime() / 1000);
$content = str_replace("\n", '{\n}', $log->getMessage());
return "$time.$milli - $level - {$log->getService()} @ {$log->getHost()} - $content";
}
public function __construct(array $formatterConfig)
{
}
/**
* @param $str
* @return LogEntity
*/
public function deformat($str)
{
$log = new LogEntity();
$pos = strpos($str, '.');
$timeStr = substr($str, 0, $pos);
$time = strtotime($timeStr);
$str = substr($str, $pos + 1);
$pos = strpos($str, ' - ');
$milliStr = substr($str, 0, $pos);
$time = $time * 1000 + intval($milliStr);
$log->setTime($time);
$str = substr($str, $pos + 3);
$pos = strpos($str, ' - ');
$levelStr = substr($str, 0, $pos);
$log->setLevel(strtolower($levelStr));
$str = substr($str, $pos + 3);
$pos = strpos($str, ' @ ');
$service = substr($str, 0, $pos);
$log->setService($service);
$str = substr($str, $pos + 3);
$pos = strpos($str, ' - ');
$host = substr($str, 0, $pos);
$log->setHost($host);
$str = substr($str, $pos + 3);
$content = str_replace('{\n}', "\n", $str);
$log->setMessage($content);
return $log;
}
public function stringifyException(\Exception $ex)
{
$str = "Exception: ".get_class($ex)."\nCode: {$ex->getCode()}\nFile: {$ex->getFile()}\nLine: {$ex->getLine()}\nMessage: {$ex->getMessage()}\nTrace: {$ex->getTraceAsString()}";
return $str;
}
} | true |
cd13e555d781e0bef4ae866106575b3982984174 | PHP | caonUlisses/Sicoob | /src/Retorno/CNAB240/LineAbstract.php | UTF-8 | 1,250 | 2.875 | 3 | [] | no_license | <?php
namespace Sicoob\Retorno\CNAB240;
use Sicoob\Helpers\Helper;
use Sicoob\Retorno\Fields\Field;
abstract class LineAbstract
{
public $line;
public $fields = [];
public $configs = [];
public function __construct($line = null)
{
if ($line)
$this->fill($line);
}
public function fill($line)
{
$this->line = $line;
foreach ($this->configs as $configName => $config) {
$field = new Field();
$field->type = $config['type'];
$field->start = $config['start'];
$field->end = $config['end'];
$field->length = $config['length'];
$field->values = isset($config['values']) ? $config['values'] : null;
$field->name = $configName;
$field->value = Helper::cutInterval($line, $config['start'], $config['end']);
if (isset($config['helper'])) {
$helper = $config['helper'];
$field->value = Helper::$helper($field->value);
}
$field->render();
if ($field->type == 'money') {
$field->value = (float) $field->value;
}
$this->fields[$configName] = $field;
}
}
} | true |
11c75e1b0dc8a847b13d013e709d2e56299dcc3e | PHP | ilovepdf/ilovepdf-php | /src/Sign/Receivers/ReceiverAbstract.php | UTF-8 | 1,901 | 3.09375 | 3 | [] | no_license | <?php
namespace Ilovepdf\Sign\Receivers;
abstract class ReceiverAbstract
{
public $name;
public $email;
protected $type;
public $access_code;
public function __construct(string $name, string $email)
{
$this->setName($name);
$this->setEmail($email);
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @param mixed $name
* @return Signer
*/
public function setName($name): ReceiverAbstract
{
$this->name = $name;
return $this;
}
/**
* @return mixed
*/
public function getEmail(): string
{
return $this->email;
}
/**
* @param mixed $email
* @return Signer
*/
public function setEmail($email): ReceiverAbstract
{
$this->email = $email;
return $this;
}
/**
* @return string
*/
public function getType(): string
{
return $this->type;
}
/**
* @param string $type
* @return Signer
*/
protected function setType(string $type): ReceiverAbstract
{
$this->type = $type;
return $this;
}
/**
* @return mixed
*/
public function getAccessCode()
{
return $this->access_code;
}
/**
* @param mixed $access_code
* @return ReceiverAbstract
*/
public function setAccessCode($access_code): ReceiverAbstract
{
$this->access_code = $access_code;
return $this;
}
public function __toArray()
{
return [
'name' => $this->getName(),
'email' => $this->getEmail(),
'type' => $this->getType(),
'access_code' => $this->getAccessCode()
];
}
} | true |
645feb5020a7fa96ca6664d3e58a553dfaf5b54b | PHP | BITVoxy/CryptoMegaPot | /lotto.php | UTF-8 | 319 | 3.515625 | 4 | [] | no_license | <?php
class Lotto {
static public function draw($min, $max, $limit) {
$balls = range($min, $max);
shuffle($balls);
array_splice($balls, $limit);
return $balls;
}
}
// Lotto
//print_r( Lotto::draw(1,49,6) );
// Euro
//print_r( Lotto::draw(1,50,5) );
//print_r( Lotto::draw(1,11,2) );
?>
| true |
4327da52a0f4843c8c3f77cb4bbb218c680b71f4 | PHP | yheisonlanza2002/secion-entrada | /perfil.php | UTF-8 | 1,517 | 2.75 | 3 | [] | no_license | <?php
include 'conect.php';
session_start();
if (isset($_SESSION['nombre'])) {
$nombre=$_SESSION['nombre'];
}else{
$nombre="";
}
if ($nombre=="") {
echo "<script>window.location='index.php'</script>";
}else{
echo "usuario : $nombre";
}
try {
$sql="SELECT * FROM usuario";
$resultado = $base->prepare($sql);
$resultado->execute(array());
while ($consulta = $resultado->fetch(PDO::FETCH_ASSOC)) {
?>
<table>
<tr>
<td>Cedula</td>
<td><?php echo $consulta['cedula_u'];?></td>
</tr>
<tr>
<td>Nombre</td>
<td></td>
</tr>
<tr>
<td>Apellido</td>
<td></td>
</tr>
<tr>
<td>Telefono</td>
<td></td>
</tr>
<tr>
<td>Direccion</td>
<td></td>
</tr>
<tr>
<td>Email</td>
<td></td>
</tr>
<tr>
<td>Sexo</td>
<td></td>
</tr>
</table>
<?php
}
} catch (\Throwable $th) {
//throw $th;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>cerrar</title>
</head>
<body>
<a href="cerrar.php">cerrar seccion</a>
</body>
</html> | true |
4d9e9c55ce63f23eb4fd2c6c346f92f588396966 | PHP | fl3xice/tuscam | /src/Bot/Types/Chat.php | UTF-8 | 1,657 | 2.90625 | 3 | [] | no_license | <?php
namespace bot\Types;
class Chat
{
public $id;
public $type;
public $title;
public $username;
public $first_name;
public $last_name;
public $photo;
public $bio;
public $description;
public $invite_link;
private $pinned_message;
private $permissions;
public $slow_mode_delay;
public $sticker_set_name;
public $can_set_sticker_set;
public $linked_chat_id;
private $location;
public function __construct($chat)
{
$this->id = $chat->id;
$this->type = $chat->type;
$this->title = $chat->title;
$this->username = $chat->username;
$this->first_name = $chat->first_name;
$this->last_name = $chat->last_name;
$this->photo = $chat->photo;
$this->bio = $chat->bio;
$this->description = $chat->description;
$this->invite_link = $chat->invite_link;
$this->pinned_message = $chat->pinned_message;
$this->permissions = $chat->permissions;
$this->slow_mode_delay = $chat->slow_mode_delay;
$this->sticker_set_name = $chat->sticker_set_name;
$this->can_set_sticker_set = $chat->can_set_sticker_set;
$this->linked_chat_id = $chat->linked_chat_id;
$this->location = $chat->location;
}
/**
* @return mixed
*/
public function getPinnedMessage()
{
return $this->pinned_message;
}
/**
* @return mixed
*/
public function getPermissions()
{
return $this->permissions;
}
/**
* @return mixed
*/
public function getLocation()
{
return $this->location;
}
} | true |
644e7aa5c1726653a5ed5ceacff6e12a2dc8acb7 | PHP | luiheid/OSS_Final_Project | /todo.php | UTF-8 | 1,706 | 2.640625 | 3 | [] | no_license | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>todo</title>
</head>
<body>
<h1>TODO</h1>
<?php
$conn=mysqli_connect("localhost","2ill","cuby1103","list");
if(!$conn){
echo 'db에 연결하지 못 했습니다'.mysqli_connect_error();
}
$sql = "SELECT * FROM achieve WHERE category='todo'";
$result = mysqli_query($conn,$sql);
echo "UNCOMPLETED LIST";
echo "<table width='800'><tr style='background-color:lightgrey'><th>TITLE</th><th width='160'>CREATE-DATE</th></tr>";
while($row = mysqli_fetch_array($result)){
if($row['achieve']==0)
echo "<tr><td><a href=\"view_todo.php?num={$row['num']}\">{$row["title"]}</a> </td><td> {$row["create_date"]} </td></tr>";
}
echo "</table>";
echo "<br><br><br>";
echo "COMPLETED LIST";
mysqli_close($conn);
$conn=mysqli_connect("localhost","2ill","cuby1103","list");
$sql = "SELECT * FROM achieve WHERE category='todo'";
$result = mysqli_query($conn,$sql);
echo "<table width='960'><tr style='background-color:lightgrey'><th>TITLE</th><th width='160'>CREATE-DATE</th><th width='160'>COMPLETE-DATE</th></tr>";
while($row = mysqli_fetch_array($result)){
if($row['achieve']==1)
echo "<tr><td><a href=\"view_todo_com.php?num={$row['num']}\">{$row["title"]}</a> </td><td> {$row["create_date"]} </td><td> {$row["complete_date"]} </td></tr>";
}
echo "</table>";
mysqli_close($conn);
?>
<br>
<a href = "write_todo.php">add new</a>
<a href = "index.html">Home</a>
</body>
</html>
| true |
9f5bf53da094705cad9a1c1300cddd46b239519e | PHP | basuregami/Design-pattern | /2. Repository/src/app/Repository/Implementation/BaseRepository.php | UTF-8 | 2,458 | 2.84375 | 3 | [] | no_license | <?php
namespace App\Repository\Implementation;
use App\Database\Connection;
use App\Repository\Contracts\BaseRepositoryInterface;
abstract class BaseRepository
{
/**
* @Author: Basu Regami
* @Date: 2020-05-19 22:28:07
* @Desc: connection object
* @var object
*/
protected $connection;
/**
* @Author: Basu Regami
* @Date: 2020-05-19 22:28:09
* @Desc: Database object
* @var object
*/
protected $db;
/**
* @Author: Basu Regami
* @Date: 2020-05-19 22:28:21
* @Desc: Namespace of the model
* @var Object
*/
protected $model;
public function __construct()
{
$this->connection = Connection::getInstance();
$this->db = $this->connection->getConnection();
}
public function findById($id, $columns = array('*'))
{
$sql = "SELECT * FROM {$this->model->table} WHERE id = $id";
$this->connection->prepareStatement($sql);
$this->connection->execute();
$result = $this->connection->getResult();
foreach ($row = $result->fetch_assoc() as $key => $value)
{
// $this->model->$key = $value;
// print_r($this->model->$key = 'test');
$this->model->$key = $value;
}
return $this->model;
}
public function getAll()
{
$sql = "SELECT * FROM {$this->model->table}";
$this->connection->prepareStatement($sql);
$this->connection->execute();
$result = $this->connection->getResult();
$response = [];
foreach ($row = $result->fetch_assoc() as $key => $value)
{
// $this->model->$key = $value;
// print_r($this->model->$key = 'test');
$this->model->$key = $value;
array_push($response, $this->model);
}
return $response;
}
public function findBy($attribute, $value)
{
$this->connection->bind('SSS', 'ram','sam','hari', 'gita');
$sql = "SELECT * FROM {$this->model->table} WHERE {$attribute} = {$value}" ;
$this->connection->prepareStatement($sql);
$this->connection->execute();
$result = $this->connection->getResult();
print_r($result);
die;
foreach ($row = $result->fetch_assoc() as $key => $value)
{
$this->model->$key = $value;
}
return $response;
}
} | true |
ebe96044eb3343d9b25cbd504b7031e195830717 | PHP | vettich/vettich.sp3 | /lib/db/ormbase.php | UTF-8 | 895 | 2.609375 | 3 | [
"MIT"
] | permissive | <?php
namespace vettich\sp3\db;
use Bitrix\Main\Entity;
class OrmBase extends Entity\DataManager
{
public static function createTable()
{
try {
$entity = self::getEntity();
$connection = $entity->getConnection();
if (!$connection->isTableExists($entity->getDBTableName())) {
$sql = $entity->compileDbTableStructureDump();
$connection->query($sql[0]);
return $connection->isTableExists($entity->getDBTableName());
}
return true;
} catch (\Exception $e) {
}
return false;
}
public static function dropTable()
{
try {
$entity = self::getEntity();
$connection = $entity->getConnection();
if ($connection->isTableExists($entity->getDBTableName())) {
$connection->dropTable($entity->getDBTableName());
return !$connection->isTableExists($entity->getDBTableName());
}
return true;
} catch (\Exception $e) {
}
return false;
}
}
| true |
a676fcf9ad7bc053c1348b590292eb1c7d55eb16 | PHP | hungneox/ramen-messenger | /src/Console/AbstractCommand.php | UTF-8 | 497 | 2.578125 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | <?php
namespace Neox\Ramen\Messenger\Console;
use GuzzleHttp\ClientInterface;
use Illuminate\Console\Command;
use GuzzleHttp\Client;
abstract class AbstractCommand extends Command
{
/**
* @var Client
*/
protected $httpClient;
/**
* AbstractCommand constructor.
*
* @param ClientInterface $httpClient
*/
public function __construct(ClientInterface $httpClient)
{
parent::__construct();
$this->httpClient = $httpClient;
}
}
| true |
4c2ce65ca74d7d00dff8322e381b05d07b906e0b | PHP | kordero/worklist | /db/migrations/20171113094255_create_journal_files_table.php | UTF-8 | 609 | 2.546875 | 3 | [] | no_license | <?php
use Phinx\Migration\AbstractMigration;
use Phinx\Db\Adapter\MysqlAdapter;
class CreateJournalFilesTable extends AbstractMigration
{
public function up() {
$this->table('journal_files', ['engine' => "InnoDB"])
->addColumn('ext', 'string', ['null' => false, 'limit' => 8])
->addColumn('uploaded_time', 'timestamp', ['null' => false, 'default' => 'CURRENT_TIMESTAMP', 'update' => 'CURRENT_TIMESTAMP'])
->addColumn('data', 'blob', ['null' => false, 'limit' => MysqlAdapter::BLOB_MEDIUM])
->save();
}
public function down() {
$this->dropTable('journal_files');
}
}
| true |
fe788a4e442b2a4f0da720cf15bf68ddd8a60e83 | PHP | Rpalaces/cst366final | /DBConnection.php | UTF-8 | 308 | 2.53125 | 3 | [] | no_license | <?php
function getDataBaseconnection($opt){
$host='localhost';
$dbname=$opt;
$username='rpalaces';
$password='';
$dbConn = new PDO("mysql:host=$host;dbname=$dbname",$username,$password);
$dbConn -> setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
return $dbConn;
}
?> | true |
e6274e961431ef0027b815a76888ae3b2375a92f | PHP | TonyBostonTB/icingaweb2-module-director | /application/forms/IcingaTimePeriodForm.php | UTF-8 | 1,876 | 2.546875 | 3 | [] | no_license | <?php
namespace Icinga\Module\Director\Forms;
use Icinga\Module\Director\Web\Form\DirectorObjectForm;
class IcingaTimePeriodForm extends DirectorObjectForm
{
public function setup()
{
$isTemplate = isset($_POST['object_type']) && $_POST['object_type'] === 'template';
$this->addElement('select', 'object_type', array(
'label' => $this->translate('Object type'),
'description' => $this->translate('Whether this should be a template'),
'class' => 'autosubmit',
'multiOptions' => $this->optionalEnum(array(
'object' => $this->translate('Timeperiod object'),
'template' => $this->translate('Timeperiod template'),
))
));
if ($isTemplate) {
$this->addElement('text', 'object_name', array(
'label' => $this->translate('Timeperiod template name'),
'required' => true,
'description' => $this->translate('Name for the Icinga timperiod template you are going to create')
));
} else {
$this->addElement('text', 'object_name', array(
'label' => $this->translate('Timeperiod'),
'required' => true,
'description' => $this->translate('Name for the Icinga timeperiod you are going to create')
));
}
$this->addElement('text', 'display_name', array(
'label' => $this->translate('Display Name'),
'description' => $this->translate('the display name')
));
$this->addElement('text', 'update_method', array(
'label' => $this->translate('Update Method'),
'description' => $this->translate('the update method'),
));
$this->addImportsElement();
$this->setButtons();
}
}
| true |
62c4467088b73e51e4f13f2df83ea3a1c7be20fb | PHP | yasmineYE/PHP-Honey-Pot | /creation.php | UTF-8 | 1,003 | 2.71875 | 3 | [] | no_license | <?php
session_start();
if(empty($_POST['login']) || empty($_POST['password']) || empty($_POST['sd_password'])){
echo 'Empty fields';
}else{
$login = strip_tags(trim($_POST['login']));
$password = filter_var($_POST['password'],FILTER_SANITIZE_STRING);
$sd_password = filter_var($_POST['sd_password'],FILTER_SANITIZE_STRING);
if(!empty($login)){
$conn = require_once('config/mysql_connect.php');
$test_req = $conn->query("SELECT * FROM users WHERE login='".$login."'");
if(!$test_req){
echo die("Error : ".mysqli_error($conn));
}else{
if($password == $sd_password){
$creation_req = $conn->query("INSERT INTO users(login,password) VALUES ('".$login."','".$password."')");
if($creation_req){
echo 'Registred';
$_SESSION['new_user'] = $password;
}else{
die(mysqli_error($conn));
}
}else{
echo 'Wrong password match. Please try again';
}
}
}else{
echo 'Login invalid';
}
}
| true |
308e8ddcda225302aa45f70222fad27af29ce8f3 | PHP | 1of0/php-serializer | /test/RecursionTest.php | UTF-8 | 4,290 | 2.5625 | 3 | [
"MIT"
] | permissive | <?php
/**
* Copyright (c) 2016 Bernardo van der Wal
* MIT License
*
* Refer to the LICENSE file for the full copyright notice.
*/
namespace OneOfZero\Json\Test;
use OneOfZero\Json\Configuration;
use OneOfZero\Json\Enums\OnMaxDepth;
use OneOfZero\Json\Enums\OnRecursion;
use OneOfZero\Json\Exceptions\NotSupportedException;
use OneOfZero\Json\Exceptions\RecursionException;
use OneOfZero\Json\Serializer;
use OneOfZero\Json\Test\FixtureClasses\RecursiveReferableClass;
use OneOfZero\Json\Test\FixtureClasses\SimpleClass;
use stdClass;
class RecursionTest extends AbstractTest
{
public function testRecursionExpectException()
{
$this->setExpectedExceptionRegExp(RecursionException::class, '/.*Infinite.*/');
$config = new Configuration();
$config->defaultRecursionHandlingStrategy = OnRecursion::THROW_EXCEPTION;
$input = new SimpleClass(null, null, null);
$input->foo = $input;
$serializer = new Serializer($config);
$serializer->serialize($input);
}
public function testRecursionExpectReference()
{
$config = new Configuration();
$config->defaultRecursionHandlingStrategy = OnRecursion::CREATE_REFERENCE;
$input = new RecursiveReferableClass(123);
$input->foo = new SimpleClass($input, 'bar', 'baz');
$expectedOutput = json_encode([
'@type' => RecursiveReferableClass::class,
'foo' => [
'@type' => SimpleClass::class,
'foo' => [
'@type' => RecursiveReferableClass::class,
'id' => 123,
],
'bar' => 'bar',
'baz' => 'baz',
],
'id' => 123,
]);
$serializer = new Serializer($config);
$json = $serializer->serialize($input);
$this->assertEquals($expectedOutput, $json);
}
public function testRecursionExpectNull()
{
$config = new Configuration();
$config->defaultRecursionHandlingStrategy = OnRecursion::SET_NULL;
$input = new SimpleClass(null, null, null);
$input->foo = $input;
$serializer = new Serializer($config);
$json = $serializer->serialize($input);
$this->assertEquals('null', $json);
}
public function testRecursionExpectMaxDepthException()
{
$this->setExpectedExceptionRegExp(RecursionException::class, '/.*depth.*/');
$config = new Configuration();
$config->maxDepth = 5;
$config->defaultRecursionHandlingStrategy = OnRecursion::CONTINUE_MAPPING;
$input = new SimpleClass(null, null, null);
$input->foo = $input;
$serializer = new Serializer($config);
$serializer->serialize($input);
}
public function testRecursionExpectMaxDepthSetNull()
{
$config = new Configuration();
$config->maxDepth = 5;
$config->defaultRecursionHandlingStrategy = OnRecursion::CONTINUE_MAPPING;
$config->defaultMaxDepthHandlingStrategy = OnMaxDepth::SET_NULL;
$input = new SimpleClass(null, 'bar', 'baz');
$input->foo = $input;
$serializer = new Serializer($config);
$json = $serializer->serialize($input);
$deserialized = json_decode($json);
$counter = 1;
$child = $deserialized;
while (property_exists($child, 'foo'))
{
$counter++;
$child = $child->foo;
}
$this->assertEquals($config->maxDepth, $counter);
}
public function testInvalidRecursionStrategy()
{
$this->setExpectedException(NotSupportedException::class);
$config = new Configuration();
$config->defaultRecursionHandlingStrategy = 1337;
$input = new SimpleClass(null, 'bar', 'baz');
$input->foo = $input;
$serializer = new Serializer($config);
$serializer->serialize($input);
}
public function testInvalidMaxDepthStrategy()
{
$this->setExpectedException(NotSupportedException::class);
$config = new Configuration();
$config->defaultRecursionHandlingStrategy = OnRecursion::CONTINUE_MAPPING;
$config->defaultMaxDepthHandlingStrategy = 1337;
$input = new SimpleClass(null, 'bar', 'baz');
$input->foo = $input;
$serializer = new Serializer($config);
$serializer->serialize($input);
}
public function testRecursiveStdClass()
{
$this->setExpectedExceptionRegExp(RecursionException::class, '/.*Infinite.*/');
$config = new Configuration();
$config->defaultRecursionHandlingStrategy = OnRecursion::THROW_EXCEPTION;
$input = new stdClass();
$input->foo = $input;
$serializer = new Serializer($config);
$serializer->serialize($input);
}
}
| true |
95817a50c76a2d82a99eba7fcd8e9cecfe68c980 | PHP | marcofiset/fun-lang | /spec/Fun/TokenDefinitionTest.php | UTF-8 | 884 | 2.5625 | 3 | [] | no_license | <?php
use Fun\Lexing\Tokens\TokenDefinition;
use Fun\Lexing\Tokens\TokenType;
class TokenDefinitionTest extends PHPUnit_Framework_TestCase
{
private $tokenDefinition;
public function setUp()
{
$this->tokenDefinition = new TokenDefinition('/\d+/', TokenType::Number);
}
public function testMatchReturnsTokenObjectIfMatchedInput()
{
$token = $this->tokenDefinition->match('123');
$this->assertInstanceOf('Fun\Lexing\Tokens\Token', $token);
$this->assertEquals('123', $token->getValue());
$this->assertEquals(TokenType::Number, $token->getType());
}
public function testNoMatchReturnsNull()
{
$this->assertNull($this->tokenDefinition->match('abc'));
}
public function testMatchReturnsNullIfOffsetNotZero()
{
$this->assertNull($this->tokenDefinition->match('abc123'));
}
} | true |
8d92a7631648aeee80e6a657711ebebc3e5c895c | PHP | vasilyevd/socio | /protected/commands/MmfileGeneratePreviewCommand.php | UTF-8 | 1,189 | 2.765625 | 3 | [] | no_license | <?php
/**
* Finish uploaded files previews manipulations.
*/
class MmfileGeneratePreviewCommand extends CConsoleCommand
{
public function run($args)
{
$models = Mmfile::model()->findAllByAttributes(array('preview' => false));
foreach ($models as $m) {
// Create previews by file extension.
$fileExtension = strtolower(pathinfo($m->name, PATHINFO_EXTENSION));
switch ($fileExtension) {
case 'doc':
case 'docx':
case 'odt':
case 'ppt':
case 'xls':
case 'xlsx':
Mmfile::createDocPreview($m->getUploadPath('name'));
break;
case 'pdf':
Mmfile::createPdfPreview($m->getUploadPath('name'));
break;
case 'jpeg':
case 'jpg':
case 'gif':
case 'png':
Mmfile::createImgPreview($m->getUploadPath('name'));
break;
}
// Set file preview status.
$m->preview = true;
$m->save();
}
}
}
| true |
91f0b96a01490aaee7eec0109419fb99eaf2feb3 | PHP | ChouaibMONCEF/SkyFly | /Controller/userscontroller.php | UTF-8 | 1,787 | 2.5625 | 3 | [] | no_license | <?php
class UsersController {
public function auth(){
if(isset($_POST['submit'])){
$data['email'] = $_POST['email'];
$result = user::login($data);
if($result->email === $_POST['email'] && password_verify($_POST['pswrd'], $result->pswrd) ){
$_SESSION['logged'] = true ;
$_SESSION['fullname'] = $result->fullname ;
$_SESSION['id'] = $result->id ;
Session::set('success', 'Logged in Successfully');
Redirect::to('home');
}
else{
Session::set('error', 'Email or password is incorrect ');
Redirect::to('login');
}
}
}
public function getId(){
if(isset($_POST['id'])){
$data = array(
'id' => $_POST['id']
);
$user = user::getId($data);
return $user;
}
}
public function register(){
if(isset($_POST['submit'])){
$options = [
'cost' => 12
];
$password = password_hash($_POST['pswrd'], PASSWORD_BCRYPT);
$data = array(
'fullname' => $_POST['fullname'],
'email' => $_POST['email'],
'pswrd' => $password,
'passportid' => $_POST['passportid'],
'birthdate' => $_POST['birthdate']
);
$result = user::createUser($data);
if($result === 'ok'){
Session::set('success', 'Registered Successfully');
Redirect::to('login');
}else{
echo $result;
}
}
}
static public function logout(){
session_destroy();
}
}
?> | true |
50f284a85c586a22623cc70c9c32f18b575a2def | PHP | FlyingMagikarp/sbbplus | /View/View_RouteOverview.php | UTF-8 | 2,748 | 2.625 | 3 | [] | no_license | <?php
require '../Controller.php';
include '../res/head.php';
include 'Nav.php';
class View_RouteOverview
{
public $controller;
public function __construct(){
$this->controller = new Controller();
}
public function getRoutes(){
return $this->controller->getRoutes();
}
public function deleteRoute($id){
$this->controller->deleteRoute($id);
}
}
$self = new View_RouteOverview();
$routeData = $self->getRoutes();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(isset($_POST['delete'])) {
if ($_POST['delete'] == 'true') {
$self->deleteRoute($_POST['id']);
}
}
header("Location: View_RouteOverview.php");
exit();
}
?>
<html>
<head>
<title>SBB Plus</title>
</head>
<body>
<div>
<?php echo getNavbar(); ?>
</div>
<div class="container-fluid">
<div class="col-md-12 col-sm-12">
<br>
<div><a class="btn btn-dark" href="View_RouteNew.php" role="button">Linie erfassen</a></div>
<br>
<table class="table">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">Name</th>
<th scope="col">Bearbeiten</th>
<th></th>
</tr>
</thead>
<tbody>
<?php if(sizeof($routeData) > 0): ?>
<?php for($i=0;$i < sizeof($routeData);$i++): ?>
<tr>
<td><?php echo $routeData[$i]->id; ?></td>
<td><?php echo $routeData[$i]->name; ?></td>
<td>
<form name="editRoute" action="View_RouteEdit.php" method="post">
<input name="id" value="<?php echo $routeData[$i]->id ?>" hidden><input name="edit" value="true" hidden><button type="submit" class="btn btn-sm btn-white"><img class="glyph" src="/sbbplus/Res/Glyph/svg/si-glyph-pencil.svg"></button>
</form>
</td>
<td>
<form name="deleteRoute" action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> method="post">
<input name="id" value="<?php echo $routeData[$i]->id ?>" hidden><input name="delete" value="true" hidden><button type="submit" class="btn btn-sm btn-white" onclick="return confirm('Are you sure?');"><img class="glyph" src="/sbbplus/Res/Glyph/svg/si-glyph-trash.svg"></button>
</form>
</td>
</tr>
<?php endfor; ?>
<?php endif; ?>
</tbody>
</table>
</div>
</div>
<?php include '../res/js.php'; ?>
</body>
</html> | true |
425afadb6562d402eacfbcd04cb1ee40efd5be3a | PHP | semishin/ariol | /modules/ariol/classes/CM/Form/Plugin/ORM/Multiselect.php | UTF-8 | 1,755 | 2.53125 | 3 | [] | no_license | <?php defined('SYSPATH') or die('No direct script access.');
/**
* @version SVN: $Id:$
*/
class CM_Form_Plugin_ORM_Multiselect extends CM_Form_Plugin_ORM_Abstract
{
private $_field_name = NULL;
private $_value_model = NULL;
private $_parent_field = NULL;
public function __construct($field_name, ORM $value_model, $parent_field)
{
$this->_field_name = $field_name;
$this->_value_model = clone $value_model;
$this->_parent_field = $parent_field;
}
protected function get_db_values()
{
return $this->get_model()->{$this->_field_name}->order_by('index')->find_all();
}
public function construct_form(CM_Form_Abstract $form, $param)
{
$this->set_model($param);
$values = array();
foreach ($this->get_db_values() as $db_value)
{
$values[$db_value->index] = $db_value->value;
}
$form->get_field($this->_field_name)->set_raw_value($values);
}
public function populate(CM_Form_Abstract $form)
{
}
public function after_submit(CM_Form_Abstract $form)
{
$values = unserialize($form->get_field($this->_field_name)->get_value()->get_raw());
foreach ($this->get_db_values() as $db_value)
{
if ( ! isset($values[$db_value->index]))
{
$db_value->delete();
}
else if (is_null($values[$db_value->index]))
{
unset($values[$db_value->index]);
$db_value->delete();
}
else
{
$db_value->value = $values[$db_value->index];
$db_value->save();
unset($values[$db_value->index]);
}
}
foreach ($values as $index => $value)
{
if (is_null($value)) continue;
$db_value = clone $this->_value_model;
$db_value->index = $index;
$db_value->value = $value;
$db_value->{$this->_parent_field} = $this->get_model();
$db_value->save();
}
}
} | true |
33371e5c80edee9c752f9cb1e9f8faf2803c7a88 | PHP | hd4y2t/sipaten-kecamatansimpangkatis | /website/application/models/Mberita.php | UTF-8 | 3,451 | 2.53125 | 3 | [] | no_license | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Mberita extends CI_Model {
public function __construct()
{
parent::__construct();
//Do your magic here
$this->slug_kat = '';
}
public function get_all($limit = 20, $offset = 0, $type = 'result')
{
if($this->input->get('kategori') != '')
$this->db->where('kategori', $this->input->get('kategori'));
if($this->input->get('query') != '')
$this->db->like('title', $this->input->get('query'))
->or_like('short_descriptions', $this->input->get('query'))
->or_like('descriptions', $this->input->get('query'))
->or_like('uploaded', $this->input->get('query'))
->or_like('kategori', $this->input->get('query'));
$this->db->join('kategori', 'berita.kategori = kategori.id_kat', 'left');
$this->db->where(array('status' => 'show' ));
$this->db->order_by('id', 'DESC');
if($type == 'result')
{
return $this->db->get('berita', $limit, $offset)->result();
} else {
return $this->db->get('berita')->num_rows();
}
}
public function get_all_kat($slug_kat = '')
{
$this->db->where(array('kategori' => $slug_kat , 'status' => 'show' ));
$this->db->order_by('id', 'DESC');
return $this->db->get('berita')->result();
}
public function get_all_tags($slug_kat = '')
{
$this->db->where(array('status' => 'show' ));
$this->db->like('tags', $slug_kat);
$this->db->order_by('id', 'DESC');
return $this->db->get('berita')->result();
}
public function berita_slide()
{
$this->db->where(array('slider' => 'yes' ,'status' => 'show' ));
$this->db->order_by('id', 'DESC');
return $this->db->get('berita')->result();
}
public function berita_list()
{
$this->db->where(array('slider' => 'no' ,'status' => 'show' ));
$this->db->order_by('id', 'DESC');
$this->db->limit(4);
return $this->db->get('berita')->result();
}
public function berita_populer()
{
$this->db->where(array('status' => 'show'));
$this->db->order_by('hits', 'DESC');
$this->db->limit(3);
return $this->db->get('berita')->result();
}
public function get_detail($slug= '')
{
$array = array('slug' => $slug);
$this->db->where($array);
$equipid = $this->db->get('berita');
return $equipid->row();
}
public function uphit($param)
{
$hit = $this->get_detail($param);
$plus = $hit->hits + 1;
$object = array('hits' => $plus );
$this->db->update('berita', $object, array('slug' => $param));
}
public function get_kategori()
{
$this->db->select('id_kat,nama,slug_kat');
$this->db->order_by('id_kat', 'desc');
return $this->db->get('kategori')->result();
}
public function get_tags()
{
$this->db->select('id,nama,slug');
$this->db->order_by('id', 'desc');
return $this->db->get('tags')->result();
}
public function get_tag_where($slug)
{
$this->db->select('id,nama,slug');
$potong = explode(',', $slug);
foreach ($potong as $key => $value) {
$this->db->or_where('id', $value);
}
$this->db->order_by('id', 'desc');
return $this->db->get('tags')->result();
}
public function get_komentar($param)
{
$this->db->select('nama,komentar,dates,');
$array = array('id_berita' => $param , 'status' => 'show');
$this->db->where($array);
$this->db->order_by('id', 'asc');
return $this->db->get('komentar_berita')->result();
}
} | true |
f2b7ec0c513a028f1644fb6d8d0bf30c8540ceb6 | PHP | Huisch/Huisch | /src/TelegramCommands/StartCommand.php | UTF-8 | 2,085 | 2.796875 | 3 | [
"MIT"
] | permissive | <?php
namespace App\TelegramCommands;
use App\Entity\House;
use App\Entity\Resident;
use App\Exception\InternalHuischException;
use Doctrine\ORM\EntityManagerInterface;
use Longman\TelegramBot\Commands\SystemCommand;
use Longman\TelegramBot\Entities\ServerResponse;
use Longman\TelegramBot\Entities\Update;
use Longman\TelegramBot\Exception\TelegramException;
use Longman\TelegramBot\Request;
use Longman\TelegramBot\Telegram;
/**
* Start command
*/
class StartCommand extends SystemCommand implements HuischCommandInterface {
protected $name = 'start';
protected $description = 'Start command';
protected $usage = '/start';
protected $version = '1.1.0';
protected $show_in_help = true;
private $em;
public function __construct(Telegram $telegram, Update $update = null, EntityManagerInterface $em = null) {
$this->em = $em;
parent::__construct($telegram, $update);
}
/**
* Command execute method
*
* @return ServerResponse
* @throws TelegramException
* @throws InternalHuischException
*/
public function execute() {
$message = $this->getMessage();
$chat = $message->getChat();
$user = $message->getFrom();
if ($chat->isGroupChat()) {
$house = $this->em->getRepository(House::class)->findByChat($chat);
$this->em->getRepository(Resident::class)->findByHouseAndUser($house, $user);
return $house->sendMessage("{$house->getName()} heeft nu {$house->getResidents()->count()} {$house->getResidentsPlural('bewoner', 'bewoners')}: {$house->getResidentsString()}.");
} else {
$resident = $this->em->getRepository(Resident::class)->findByUser($user);
if (!$resident) {
return Request::sendMessage([
'chat_id' => $chat->getId(),
'text' => "Welkom! Voeg me toe aan een groep en typ /start in de groep om me te gebruiken."
]);
} else {
return $resident->sendMessage("Je bent nu actief in {$resident->getHouse()->getName()}.");
}
}
}
/**
* Show in help when current environment is group or not.
* @param bool $group
* @return bool
*/
public function showWhen(bool $group) {
return true;
}
}
| true |
19cb842c2a4f17da1ee300567173a677694ed666 | PHP | RyanCadby/normalbear | /wp-content/themes/normalbear/classes/widgets.php | UTF-8 | 11,539 | 2.625 | 3 | [] | no_license | <?php
/** WIDGETS.PHP
* // ----- Version: 1.0
* // ----- Released: 4.5.2020
* // ----- Description: declare theme sidebar and widget areas
**/
function sbc_widgets_init() {
register_sidebar( array(
'name' => 'Left Column',
'id' => 'left-col',
'before_widget' => '<div class="left-col widget">',
'after_widget' => '</div>',
'before_title' => '<h4 class="head widget-head">',
'after_title' => '</h4>',
) );
register_sidebar( array(
'name' => 'Center Column',
'id' => 'center-col',
'before_widget' => '<div class="center-col widget">',
'after_widget' => '</div>',
'before_title' => '<h4 class="head widget-head">',
'after_title' => '</h4>',
) );
register_sidebar( array(
'name' => 'Right Column',
'id' => 'right-col',
'before_widget' => '<div class="right-col widget">',
'after_widget' => '</div>',
'before_title' => '<h4 class="head widget-head">',
'after_title' => '</h4>',
) );
register_sidebar( array(
'name' => 'Service Sidebar',
'id' => 'service-sidebar',
'before_widget' => '<div class="sidebar service-sidebar">',
'after_widget' => '</div>',
'before_title' => '<h4 class="head service-widget-head">',
'after_title' => '</h4>',
) );
}
add_action( 'widgets_init', 'sbc_widgets_init' );
// create custom connect widget that uses ACF fields in theme options
function sbc_connect_widget() {
class connect_widget extends WP_Widget {
function __construct() {
parent::__construct(
// Base ID of your widget
'connect_widget',
// Widget name will appear in UI
__('Connect', 'connect_widget_domain'),
// Widget description
array( 'description' => __( 'Insert your connect links with this widget', 'connect_widget_domain' ), )
);
}
// Creating widget output
public function widget( $args, $instance ) {
$title = apply_filters( 'widget_title', $instance['title'] );
// echo Title if Title
echo $args['before_widget'];
echo '<div class="connect-widget">';
if ( ! empty( $title ) ):
echo $args['before_title'] . $title . $args['after_title'];
endif;
// echo social links if social links available in theme options
if( have_rows('_about', 'option') ):
while( have_rows('_about', 'option') ): the_row();
if( have_rows('connect_media') ):
// echo 'Follow Us: ';
while( have_rows('connect_media') ): the_row();
$link = get_sub_field('link');
$platform = get_sub_field('platform');
$icon = '<a href="' . $link . '">' .
'<i class="' . $platform . '"></i>' .
'</a>';
echo $icon;
endwhile;
endif;
endwhile;
endif;
// This is where you run the code and display the output
// echo __( 'Hello, World!', 'connect_widget_domain' );
echo $args['after_widget'];
echo '</div>';
}
// Widget Backend
public function form( $instance ) {
if ( isset( $instance[ 'title' ] ) ) {
$title = $instance[ 'title' ];
}
else {
$title = __( 'New title', 'connect_widget_domain' );
}
// Widget admin form
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" />
</p>
<?php
}
// Updating widget replacing old instances with new
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
return $instance;
}
} // close class
// Register the widget
register_widget( 'connect_widget' );
}
add_action( 'widgets_init', 'sbc_connect_widget' );
// create custom connect widget that uses ACF fields in theme options
function sbc_sub_service_menu() {
class sub_service_menu extends WP_Widget {
function __construct() {
parent::__construct(
// Base ID of your widget
'sub_service_menu',
// Widget name will appear in UI
__('Sub Service Menu', 'sub_service_widget_domain'),
// Widget description
array( 'description' => __( 'Add menu items for other sub service under the same parent', 'sub_service_widget_domain' ), )
);
}
// Creating widget output
public function widget( $args, $instance ) {
echo '<div class="sidebar sub-service-menu">';
global $post;
$parent = get_post_ancestors($post->ID);
$id = ($parent) ? $parent[count($parent)-1]: $post->ID;
$parent_title = get_the_title($id);
$child_list = wp_list_pages( array(
'child_of' => $id,
'title_li' => '',
));
echo '</div>';
}
// Widget Backend
public function form( $instance ) {
}
// Updating widget replacing old instances with new
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
return $instance;
}
} // close class
// Register the widget
register_widget( 'sub_service_menu' );
}
add_action( 'widgets_init', 'sbc_sub_service_menu' );
// create custom connect widget that uses ACF fields in theme options
function sbc_contact_info() {
class contact_info extends WP_Widget {
function __construct() {
parent::__construct(
// Base ID of your widget
'contact_info',
// Widget name will appear in UI
__('Contact Info', 'contact_widget_domain'),
// Widget description
array( 'description' => __( 'Add to show email, phone, location', 'contact_widget_domain' ), )
);
}
// Creating widget output
public function widget( $args, $instance ) {
$title = apply_filters( 'widget_title', $instance['title'] );
$text = apply_filters( 'widget_title', $instance['text'] );
// echo sidebar section container
echo '<div class="sidebar about-sidebar">';
//check for title
if ( ! empty( $title ) ):
echo $args['before_title'] . $title . $args['after_title'];
endif;
// check for text
if ( ! empty( $text ) ):
echo '<p class="about-text">' . $text . '</p>';
endif;
echo '<div class="sidebar contact-info">';
// echo social links if social links available in theme options
if( have_rows('_about', 'option') ):
while( have_rows('_about', 'option') ): the_row();
$about = get_field('_about', 'option');
$phone = $about['phone_num'];
$email = $about['email'];
$address_1 = $about['address_line_1'];
$address_2 = $about['address_line_2'];
$city = $about['city'];
$state = $about['state'];
$zip = $about['zip']; ?>
<?php if($phone): ?>
<div class="phone-cont">
<a class="phone" href="tel:<?php echo $phone; ?>"><i class="fas fa-mobile-alt"></i> <span><?php echo $phone ?></span></a>
</div>
<?php endif; ?>
<div class="email-cont">
<a class="email" href="mailto:<?php echo $email; ?>"><i class="fas fa-envelope"></i> <span><?php echo $email; ?></span></a>
</div>
<div class="address-cont">
<a class="address" href="https://www.google.com/maps/place/<?php echo $address_1 . '+' . $city . '+' . $state . '+' . $zip;?>">
<i class="fas fa-map-marker-alt"></i>
<div class="address-item-cont">
<p class="address-item address1"><?php echo $address_1; ?></p>
<?php if($address_2): ?>
<p class="address-item address2"><?php echo $address_2; ?></p>
<?php endif; ?>
<p class="address-item address3"><?php echo $city . ', ' . $state . ' ' . $zip?></p>
</div>
</a>
</div>
<?php endwhile;
endif;
echo '</div> </div>';
}
// Widget Backend
public function form( $instance ) {
if ( isset( $instance[ 'title' ] ) ) {
$title = $instance[ 'title' ];
}
else {
$title = __( 'New title', 'connect_widget_domain' );
}
if ( isset( $instance[ 'text' ] ) ) {
$text = $instance[ 'text' ];
}
else {
$text = __( 'New text', 'connect_widget_domain' );
}
// Widget admin form
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" />
<label for="<?php echo $this->get_field_id( 'text' ); ?>"><?php _e( 'Description:' ); ?></label>
<input class="widefat" rows="5" id="<?php echo $this->get_field_id( 'text' ); ?>" name="<?php echo $this->get_field_name( 'text' ); ?>" type="text" value="<?php echo esc_attr( $text ); ?>"/>
</p>
<?php
}
// Updating widget replacing old instances with new
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
$instance['text'] = ( ! empty( $new_instance['text'] ) ) ? strip_tags( $new_instance['text'] ) : '';
return $instance;
}
} // close class
// Register the widget
register_widget( 'contact_info' );
}
add_action( 'widgets_init', 'sbc_contact_info' );
| true |
fdba4381f33d32f4ee6814411b4eef4478751a3d | PHP | furqansiddiqui/e2e-encrypted-relay-client-php | /src/Server/E2ERelayNode.php | UTF-8 | 4,570 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types=1);
namespace FurqanSiddiqui\E2ESecureRelay\Server;
use FurqanSiddiqui\E2ESecureRelay\AbstractE2ERelayNode;
use FurqanSiddiqui\E2ESecureRelay\Exception\CipherException;
use FurqanSiddiqui\E2ESecureRelay\Exception\RelayCurlException;
use FurqanSiddiqui\E2ESecureRelay\RelayCurlRequest;
use FurqanSiddiqui\E2ESecureRelay\RelayCurlResponse;
/**
* Class E2ERelayNode
* @package FurqanSiddiqui\E2ESecureRelay\Server
*/
class E2ERelayNode extends AbstractE2ERelayNode
{
/** @var array|string[] */
public readonly array $ipWhitelist;
/**
* @param string $sharedSecret
* @param string $ipWhitelist
*/
public function __construct(string $sharedSecret, string $ipWhitelist)
{
parent::__construct($sharedSecret);
$this->ipWhitelist = array_values(array_filter(explode(",", trim($ipWhitelist)), function ($ip) {
if (filter_var(trim($ip), FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
return $ip;
}
return null;
}));
}
/**
* @param \FurqanSiddiqui\E2ESecureRelay\RelayCurlRequest $req
* @return \FurqanSiddiqui\E2ESecureRelay\RelayCurlResponse
* @throws \FurqanSiddiqui\E2ESecureRelay\Exception\RelayCurlException
*/
private function relayCurlRequest(RelayCurlRequest $req): RelayCurlResponse
{
$req->method = strtolower($req->method);
if (!in_array($req->method, ["get", "post", "put", "delete", "options"])) {
throw new RelayCurlException('Invalid HTTP method', 1001);
}
$ch = curl_init();
if (!$req->url || !curl_setopt($ch, CURLOPT_URL, $req->url)) {
throw new RelayCurlException('Invalid destination URL', 1002);
}
if ($req->httpVersion) {
curl_setopt($ch, CURLOPT_HTTP_VERSION, $req->httpVersion);
}
if ($req->useSSL) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $req->sslVerifyPeer);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, $req->sslVerifyHost ? 2 : 0);
if ($req->sslVerifyPeer || $req->sslVerifyHost) {
curl_setopt($ch, CURLOPT_CAPATH, dirname(__DIR__) . DIRECTORY_SEPARATOR . "ssl" . DIRECTORY_SEPARATOR);
}
}
if ($req->method === "get") {
curl_setopt($ch, CURLOPT_HTTPGET, 1);
} else {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($req->method));
curl_setopt($ch, CURLOPT_POSTFIELDS, $req->body);
}
if ($req->headers) {
curl_setopt($ch, CURLOPT_HTTPHEADER, array_filter($req->headers, function ($v, $k) {
return $k . ": " . $v;
}, ARRAY_FILTER_USE_BOTH));
}
curl_setopt($ch, CURLOPT_USERAGENT, $req->userAgent ?? $this->defaultUserAgent);
if ($req->timeOut > 0) {
curl_setopt($ch, CURLOPT_TIMEOUT, $req->timeOut);
}
if ($req->connectTimeout > 0) {
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $req->connectTimeout);
}
return new RelayCurlResponse($ch);
}
/**
* @return never
*/
final public function listen(): never
{
if ($this->ipWhitelist && !in_array($_SERVER["REMOTE_ADDR"], $this->ipWhitelist)) {
http_response_code(403);
exit();
}
if ($_SERVER["REQUEST_METHOD"] === "GET") {
http_response_code(204);
exit();
}
try {
$request = $this->decrypt(base64_decode(file_get_contents("php://input")));
} catch (CipherException $e) {
http_response_code(451);
exit($e->getMessage());
}
if (strtolower($request->method) === "handshake") {
http_response_code(202);
exit();
}
try {
$response = $this->relayCurlRequest($request);
} catch (RelayCurlException $e) {
if ($e->curlHandle) {
http_response_code(453);
exit(curl_errno($e->curlHandle) . "\t" . curl_error($e->curlHandle));
}
http_response_code(452);
exit($e->getCode() . "\t" . $e->getMessage());
}
try {
$encrypted = $this->encrypt($response);
} catch (CipherException $e) {
http_response_code(454);
exit($e->getMessage());
}
http_response_code(250);
header("E2E-Response-Status-Code: " . $response->statusCode);
exit(base64_encode($encrypted));
}
}
| true |
b1c81786e8571b9182262dde0909c0375d6cd0cb | PHP | RC2K7/CSE405 | /Assignments/Login/index.php | UTF-8 | 496 | 2.609375 | 3 | [] | no_license | <?php
session_start();
if(isset($_SESSION['username'])) {
header("Location: ./clickme.php");
exit();
}
?>
<!DOCTYPE html>
<html>
<body>
<form action="login.php" method="post">
Username: <input type="text" value="alice" name="username" size="36" />
Password: <input type="password" value="1234" name="password" size="36" />
<input type="submit" value="Login" />
</form>
</body>
</html> | true |
bd2b2214e574fb7bfdef83282d83c0a1d77ea975 | PHP | cash2one/WorkCode_Bakup | /newbee_api/protected/commands/PrepareCommand.php | UTF-8 | 1,917 | 2.75 | 3 | [] | no_license | <?php
/**
* 预处理相关
* @author zhoujianjun
*
*/
class PrepareCommand extends CConsoleCommand
{
public function init()
{
set_time_limit(0);
}
/**
* php yiic.php prepare filterlife
* 首先清除表里container_filterlife_today中的数据
* 然后将cleaner_status表里净化器滤芯寿命小于15%的净化器的id记录在表container_filterlife_today中
* 凌晨执行
*/
public function actionFilterlife()
{
// 清除表container_filterlife_today中的数据(昨天滤芯寿命小于15%的净化器的id)
$sql = "truncate table container_filterlife_today";
Yii::app()->db->createCommand($sql)->execute();
// 查找符合条件的滤芯的id
$sql = "SELECT count(id) AS total FROM cleaner_status";
$total = Yii::app()->db->createCommand($sql)->queryScalar();
if ($total>0)
{
// 100条记录每次
$n = 100;
$j = ceil($total/100);
for ($i=0; $i<$j; $i++)
{
$sql = "SELECT id,filter_surplus_life,type from cleaner_status LIMIT ".$i*$n.",".$n;
$result = Yii::app()->db->createCommand($sql)->queryAll();
if (!empty($result))
{
foreach ($result as $value)
{
$life = json_decode($value['filter_surplus_life'], true);
if (!empty($life))
{
$defaultLife = CleanerStatus::getDefaultLife($value['type']);
$i = 1;
$exist = false;
foreach ($life as $id => $surplus)
{
if ($value['type'] == CleanerStatus::TYPE_BIG_WITH)
$id = $i;
if (round($surplus/$defaultLife[$id],2) < 0.15)
{
// 少于15%, 只要有一个满足条件 就记录
$exist = true;
break;
}
$i++;
}
if ($exist)
{
$sql = "insert into container_filterlife_today values('{$value['id']}')";
Yii::app()->db->createCommand($sql)->execute();
}
}
}
}
}
}
}
} | true |
9244030a9668279ce7484d11c271f4ac23db3416 | PHP | atiqteamwork/restaurant | /database/seeds/CategoryDataSeeder.php | UTF-8 | 750 | 2.609375 | 3 | [] | no_license | <?php
use App\MenuCategory;
use Illuminate\Database\Seeder;
class CategoryDataSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$category1 = new MenuCategory();
$category2 = new MenuCategory();
$category3 = new MenuCategory();
$category4 = new MenuCategory();
$category1->category_title = "Fast Food";
$category1->save();
$category2->category_title = "Extra Value Meals";
$category2->save();
$category3->category_title = "Sandwiches";
$category3->status = "Inactive";
$category3->save();
$category4->category_title = "Happy Meal";
$category4->save();
}
}
| true |
f7e104a51508d59dcfc7d246fbc9d0df9b845d9c | PHP | yaroslavlutz/corporate.laravel.loc | /database/migrations/2018_02_05_203344_create_table_menus.php | UTF-8 | 1,728 | 2.703125 | 3 | [
"MIT"
] | permissive | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTableMenus extends Migration
{
/** Run the migrations.
* @return void
*/
public function up()
{
Schema::create('menus', function (Blueprint $table) { //Можно сразу к создаваемым ячейкам применять какие-то default-значения: $table->text('text')->default('some text..');
//$table->engine = 'InnoDB'; //можно явно указать какой движок будет использоваться для табл.если не указывать, то использунтся движок,выбранный для БД вцелом
$table->increments('id'); //это значит поле `id` INT AUTO_INCREMENT PPIMARY KEY
$table->integer('parent_menu_id'); //это ID родительского пункта меню,если пункт меню вложенный,т.к.предпологается древовидность меню(двууровневое Меню)
$table->string('title',50); //varchar длинной 50 символов //заголовок пункта меню
$table->string('url_path',255); //varchar длинной 255 символов //Это URL для пункта меню
$table->timestamps(); //для записи времени создания или изменения соответствующей записи в БД
});
}
/** Reverse the migrations.
* @return void
*/
public function down()
{
Schema::dropIfExists('menus');
}
}
| true |
7be429bd36e6b05321843361b25a8390a3117701 | PHP | CristianLavao/planetmusicv2.0 | /phplogin.php | ISO-8859-2 | 2,716 | 2.734375 | 3 | [] | no_license | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" charset="utf-8" />
<title>Documento sin título</title>
</head>
<body>
<?php
class Login
{
public function iniciosesion($Usuario, $Contrasena)
{
include('conexion.php');
session_start();
$usuario=$_POST["Usuario"];
$contrasena=$_POST["Contrasena"];
//hhhhhhhhhhhhhhhhhhhhhhhhhhhh
$sql = "SELECT * FROM Usuarios WHERE nombre_de_usuario='$usuario'";
if(!$result = $db->query($sql)){
die('Hay un error corriendo en la consulta o datos no encontrados!!! [' . $db->error . ']');
}
while($row = $result->fetch_assoc()){
$uusername=stripslashes($row["nombre_de_usuario"]);
$ccontrasena=stripslashes($row["contrasena"]);
$rroles_id_rol=stripslashes($row["roles_id_rol"]);
//-----traer texto del id del rol -------
$sql2 = "SELECT * FROM Roles WHERE id_rol='$rroles_id_rol'";
if(!$result2 = $db->query($sql2)){
die('Hay un error corriendo en la consulta o datos no encontrados!!! [' . $db->error . ']');
}
while($row2 = $result2->fetch_assoc()){
$iidrol=stripslashes($row2["id_rol"]);
$ddescripcion=stripslashes($row2["descripcion"]);
echo "";
}
//-----traer texto del id del rol -------
}
//$usuariocorrecto="alejo";
//$contrasenacorrecta="123";
//Esta es la consulta de la DB (Select * from jsdfjsdhfkj WHERE usuario="'$usuario'")
//hhhhhhhhhhhhhhhhhhhhhhhhhhhh
//echo "esta es una pgina confidencial";
if (($usuario==$uusername) && ($contrasena == $ccontrasena))
{
echo "todo admin. Supongamos que aqui hay un reporte confidencial";
$_SESSION['login']="1";
$_SESSION['Usuario']=$usuario;
if ($ddescripcion=="Administrador")
{
$_SESSION['rol']=$ddescripcion;
header ('Location: index_admin.php');
}
}
if (($usuario==$uusername) && ($contrasena == $ccontrasena))
{
echo "todo ok. Supongamos que aqui hay un reporte confidencial";
$_SESSION['login']="1";
$_SESSION['Usuario']=$usuario;
if ($ddescripcion=="Usuario")
{
$_SESSION['rol']=$ddescripcion;
header ('Location: index_usuario.php');
}
}
if (($usuario!=$uusername) || ($contrasena != $ccontrasena))
{
echo "
<script language='JavaScript'>
var n = 'contrase\u00f1a';
alert('Nombre de usuario y '+n+' incorrectos vuelve a intentar');
</script>
";
header('Refresh:0, URL=inicio_sesion3.php');
//crear variable de sesion
//header ("Location: index.php");
}
}
}
$nuevo=new Login();
$nuevo-> iniciosesion($_POST['Usuario'], $_POST['Contrasena']);
?>
</body>
</html>
| true |
47e154ba866560a3ab04fa5ebbd026d72853c321 | PHP | rdeanar/SCSync | /get.php | UTF-8 | 12,618 | 2.640625 | 3 | [] | no_license | <?php
/**
* get.php path_to_save
*
*/
date_default_timezone_set('Europe/Moscow');
ini_set('memory_limit', '256M');
include "config.php";
include "db.php";
include "php-soundcloud/Services/Soundcloud.php";
class scsync
{
public $save_path = '/store/';
public $save_local = true;
const db_links = DB_LINK;
const db_auth = DB_AUTH;
public $db;
public $already_downloaded = array();
public $sc; // API object
public $count = 50;
public static $current_download_operation = 'downloading content';
public $stat = array(0, 0, 0);
static function log($msg, $replace = false)
{
if ($replace) {
echo "\r" . $msg . "";
} else {
echo "\n" . wordwrap($msg, 80) . "";
}
}
/**
* Pre progress bar
*/
static function ppb()
{
self::log('_');
}
/**
* Auth
*/
public function __construct()
{
$auth = $this->getAuth();
// create client object and set access token
$this->sc = new Services_Soundcloud(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);
$this->sc->setCurlOptions(array(
CURLOPT_PROGRESSFUNCTION => array(get_class($this), 'progressCallback'),
CURLOPT_NOPROGRESS => false,
CURLOPT_RETURNTRANSFER => true,
));
if ($auth['expires_in'] > time()) { // сессия еще валидна
self::log('Use saved session.');
$this->sc->setAccessToken($auth['access_token']);
} else {
// обновляем сессию
self::log('Session expired. Trying to refresh session.');
try {
self::$current_download_operation = 'Refreshing session';
self::ppb();
$token = $this->sc->accessTokenRefresh($auth['refresh_token']);
$token['expires_in'] += time();
$db = new db(self::db_auth);
$db->saveAuth(serialize($token));
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
self::log('Refreshing session failed.');
die();
}
}
self::log('Authorization successful.');
$this->already_downloaded = $this->getLinksArray();
}
/**
* Print statistic
*/
public function __destruct()
{
self::log(str_repeat('-', 80));
self::log($this->stat[0] . ' downloaded, ' . $this->stat[1] . ' skipped, ' . $this->stat[2] . ' failed');
self::log('');
}
/**
* Set path to download tracks
* @param $local
* @param $path
*/
public function setSavePath($local, $path)
{
$this->save_local = $local;
$this->save_path = $path;
}
/**
* Set download limit
* @param $count
*/
public function setCount($count)
{
$this->count = $count;
}
/**
* Download all tracks from own stream object
* @param $stream
*/
public function processStream($stream)
{
$i = 0;
$j = 0;
$count = min($this->count, count($stream->collection));
foreach ($stream->collection as $item) {
if ($i >= $count) continue;
if ($this->trackDownload($item->origin)) $j++;
$i++;
self::log($i . ' / ' . $count . ' tracks processed. ' . ceil(($i) * 100 / $count) . '%, ' . $j . ' downloaded, ' . ($i - $j) . ' skipped');
}
}
/**
* Download all tracks from array of track objects
* @param $tracks
*/
public function processTracksArray($tracks)
{
$i = 0;
$j = 0;
$count = min($this->count, count($tracks));
foreach ($tracks as $track) {
if ($i >= $count) continue;
if ($this->trackDownload($track)) $j++;
$i++;
self::log($i . ' / ' . $count . ' tracks processed. ' . ceil(($i) * 100 / $count) . '%, ' . $j . ' downloaded, ' . ($i - $j) . ' skipped');
}
}
/**
* Download one track from track object
* @param $track
* @return bool
*/
public function trackDownload($track)
{
if ($track->kind != 'track') return false;
self::log(str_repeat('-', 80)); // -----------------------------
self::log('Track "' . $track->title . '"');
if (in_array($track->id, $this->already_downloaded)) {
self::log('Already downloaded. Continue...');
$this->stat[1]++; // skipped
self::log(str_repeat('-', 80)); // -----------------------------
return false;
}
$downloaded_file = null;
$download = false;
$low = false;
try {
$low = false;
self::$current_download_operation = 'Trying to download full track';
self::ppb();
$downloaded_file = $this->sc->download($track->id);
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
//self::log($e->getMessage());
self::log('Unable to download full track.');
}
if (is_null($downloaded_file)) {
self::log('Downloading stream version');
$track_url = $track->stream_url . '?client_id=' . CLIENT_ID;
//$downloaded_file = file_get_contents($track_url);
self::$current_download_operation = 'Downloading stream';
self::ppb();
$downloaded_file = $this->downloadFileByUrl($track_url);
$low = true;
}
if (!is_null($downloaded_file)) {
if ($this->save_local == true) {
$path = dirname(__FILE__) . $this->save_path;
if (!file_exists($path)) mkdir($path);
} else {
$path = $this->save_path;
}
$new_name = '';
if ($track->created_at != null) {
$new_name .= date('Y-m-d', strtotime($track->created_at));
}
$new_name .= '-';
$new_name .= str_replace(' ', '_', $track->user->username);
$new_name .= '-';
$new_name .= str_replace(' ', '_', $track->title);
if ($low) {
$new_name .= '-';
$new_name .= '128';
}
$new_name .= '.mp3';
$download = file_put_contents($path . $new_name, $downloaded_file);
if ($download) {
$this->addLink($track->id);
self::log('Successfully downloaded as "' . $new_name . '"!');
$this->stat[0]++; // downloaded
}
} else {
self::log('Unable to download ' . ($low ? '(low)' : '(high)') . ' "' . $track->title . '" ');
$this->stat[2]++; // failed
}
self::log(str_repeat('-', 80)); // -----------------------------
return $download ? true : false;
}
/**
* Download file by url (for downloading stream version of track)
* @param $url
* @return mixed
*/
public function downloadFileByUrl($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, array(get_class($this), 'progressCallback'));
curl_setopt($ch, CURLOPT_NOPROGRESS, false);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
/**
* Progress bar handler
* @param $download_size
* @param $downloaded
* @param $upload_size
* @param $uploaded
*/
public function progressCallback($download_size, $downloaded, $upload_size, $uploaded)
{
if ($download_size > 0) {
$progress = (round($downloaded / $download_size * 1000) / 10);
$progress_int = round($progress);
// [*******----------][43%]
$pr_long = 40;
$pr_complete = round($pr_long * $progress_int / 100);
$pr_string = "[" . str_repeat('*', $pr_complete) . str_repeat('-', ($pr_long - $pr_complete)) . "][" . $progress_int . "%] " . scsync::$current_download_operation;
// scsync::log( scsync::$current_download_operation . ', precent:' .$progress. " from " . $download_size, true);
scsync::log($pr_string, true);
} else {
scsync::log(scsync::$current_download_operation, true);
}
}
/**
* Add track id in history log
* @param $link
*/
public function addLink($link)
{
$db = new db(self::db_links);
$db->addLink($link);
}
/**
* Get list of all track ids from history log
* @return array
*/
public function getLinksArray()
{
$db = new db(self::db_links);
return $db->getLinksArray();
}
/**
* Get auth from db
* @return mixed
*/
public function getAuth()
{
$db = new db(self::db_auth);
return unserialize($db->getAuth());
}
/**
* Download tracks from own stream
*/
public function ownStream()
{
try {
self::log('Own stream');
self::$current_download_operation = 'Getting own stream';
self::ppb();
$stream = json_decode($this->sc->get('me/activities/tracks/affiliated'));
$this->processStream($stream);
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
self::log('Unknown error with message ' . $e->getMessage());
}
}
/**
* Resolve content by url
* @param $url
* @return mixed
*/
public function resolve($url)
{
try {
self::$current_download_operation = 'Resolve content type by link';
self::ppb();
return json_decode($this->sc->get('resolve', array('url' => $url), array(CURLOPT_FOLLOWLOCATION => true)));
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
self::log('Resolve failed.');
}
}
/**
* Download user's tracks
* @param $id
*/
public function getUserTracks($id)
{
try {
self::log('User #' . $id);
self::$current_download_operation = 'Getting user\'s tracks';
self::ppb();
$stream = json_decode($this->sc->get('users/' . $id . '/tracks'));
$this->processTracksArray($stream);
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
self::log('Unknown error with message ' . $e->getMessage());
}
}
/**
* Download group's tracks
* @param $id
*/
public function getGroupTracks($id)
{
try {
self::log('Group #' . $id);
self::$current_download_operation = 'Getting group\'s tracks';
self::ppb();
$stream = json_decode($this->sc->get('groups/' . $id . '/tracks'));
$this->processTracksArray($stream);
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
self::log('Unknown error with message ' . $e->getMessage());
}
}
}
$app = new scsync();
if (isset($argv[1])) {
$app->setSavePath(false, $argv[1]);
}
if (isset($argv[3])) {
$app->setCount($argv[3]);
}
if (isset($argv[2])) {
if ($argv[2] == 'STREAM') {
$app->ownStream();
} else {
$resolve = $app->resolve($argv[2]);
$id = $resolve->id;
switch ($resolve->kind) {
case 'track':
$app->trackDownload($resolve);
break;
case 'user':
$app->getUserTracks($id);
break;
case 'playlist':
$app->processTracksArray($resolve->tracks);
break;
case 'group':
$app->getGroupTracks($id);
break;
default:
scsync::log('Unknown kind: ' . $resolve->kind . ', id: ' . $id);
}
}
}
//print_r($argv);
//die('DIE');
/*
/me/activities gives you user's recent activities
/me/activities/all is the same as the one above (Recent activities) /me/activities/tracks/affiliated is the recent tracks from users the logged-in user follows (the stream)
/me/activities/tracks/exclusive is recent exclusively shared tracks
/me/activities/all/own is recent activities on the logged-in users tracks
*/
?>
| true |
7ed1a341abe3f0c682c00757eb94f9154f05e15f | PHP | Bruno17/MIGX | /core/components/migx/model/migx/migx.class.php | UTF-8 | 128,401 | 2.59375 | 3 | [] | no_license | <?php
/**
* migx
*
* @author Bruno Perner
*
*
* @package migx
*/
/**
* @package migx
* @subpackage migx
*/
class Migx {
/**
* @access public
* @var modX A reference to the modX object.
*/
public $modx = null;
/**
* @access public
* @var array A collection of properties to adjust MIGX behaviour.
*/
public $config = array();
/**
* @access public
* @var source, the source of this MIGX-TV
*/
public $source = false;
/**
* @access public
* @var working_context, the working context
*/
public $working_context = null;
/**
* The MIGX Constructor.
*
* This method is used to create a new MIGX object.
*
* @param modX &$modx A reference to the modX object.
* @param array $config A collection of properties that modify MIGX
* behaviour.
* @return MIGX A unique MIGX instance.
*/
function __construct(modX & $modx, array $config = array()) {
$this->modx = &$modx;
$packageName = 'migx';
$packagepath = $this->findPackagePath($packageName);
$modelpath = $packagepath . 'model/';
$prefix = null;
$this->modx->addPackage($packageName, $modelpath, $prefix);
/* allows you to set paths in different environments
* this allows for easier SVN management of files
*/
$corePath = $this->modx->getOption('migx.core_path', null, $modx->getOption('core_path') . 'components/migx/');
$assetsPath = $this->modx->getOption('migx.assets_path', null, $modx->getOption('assets_path') . 'components/migx/');
$assetsUrl = $this->modx->getOption('migx.assets_url', null, $modx->getOption('assets_url') . 'components/migx/');
$defaultconfig['debugUser'] = '';
$defaultconfig['corePath'] = $corePath;
$defaultconfig['modelPath'] = $corePath . 'model/';
$defaultconfig['processorsPath'] = $corePath . 'processors/';
$defaultconfig['templatesPath'] = $corePath . 'templates/';
$defaultconfig['controllersPath'] = $corePath . 'controllers/';
$defaultconfig['chunksPath'] = $corePath . 'elements/chunks/';
$defaultconfig['snippetsPath'] = $corePath . 'elements/snippets/';
$defaultconfig['auto_create_tables'] = true;
$defaultconfig['baseUrl'] = $assetsUrl;
$defaultconfig['cssUrl'] = $assetsUrl . 'css/';
$defaultconfig['jsUrl'] = $assetsUrl . 'js/';
$defaultconfig['jsPath'] = $assetsPath . 'js/';
$defaultconfig['connectorUrl'] = $assetsUrl . 'connector.php';
$defaultconfig['request'] = $_REQUEST;
$this->config = array_merge($defaultconfig, $config);
/* load debugging settings */
if ($this->modx->getOption('debug', $this->config, false)) {
error_reporting(E_ALL);
ini_set('display_errors', true);
$this->modx->setLogTarget('HTML');
$this->modx->setLogLevel(modX::LOG_LEVEL_ERROR);
$debugUser = $this->config['debugUser'] == '' ? $this->modx->user->get('username') : 'anonymous';
$user = $this->modx->getObject('modUser', array('username' => $debugUser));
if ($user == null) {
$this->modx->user->set('id', $this->modx->getOption('debugUserId', $this->config, 1));
$this->modx->user->set('username', $debugUser);
} else {
$this->modx->user = $user;
}
}
}
public function findPackagePath($packageName) {
$modx = &$this->modx;
$lc_packageName = strtolower($packageName);
return $modx->getOption( $lc_packageName . '.core_path',null,$modx->getOption('core_path').'components/' . $lc_packageName . '/');
}
public function getXpdoInstanceAndAddPackage($scriptProperties) {
$modx = &$this->modx;
$prefix = isset($scriptProperties['prefix']) ? $scriptProperties['prefix'] : '';
$usecustomprefix = $modx->getOption('useCustomPrefix', $scriptProperties, '');
$usecustomprefix = empty($usecustomprefix) ? $modx->getOption('usecustomprefix', $scriptProperties, '') : $usecustomprefix;
$usecustomprefix = empty($usecustomprefix) ? $modx->getOption('use_custom_prefix', $scriptProperties, '') : $usecustomprefix;
if (empty($prefix)) {
$prefix = !empty($usecustomprefix) ? $prefix : null;
}
$packageName = $modx->getOption('packageName', $scriptProperties, '');
if (!empty($packageName)) {
$packagepath = $this->findPackagePath($packageName);
$modelpath = $packagepath . 'model/';
$xpdo_name = $packageName . '_xpdo';
if (isset($this->modx->$xpdo_name)) {
//create xpdo-instance for that package only once
$xpdo = &$this->modx->$xpdo_name;
} elseif (file_exists($packagepath . 'config/config.inc.php')) {
include ($packagepath . 'config/config.inc.php');
if (is_null($prefix) && isset($table_prefix)) {
$prefix = $table_prefix;
}
$charset = '';
if (!empty($database_connection_charset)) {
$charset = ';charset=' . $database_connection_charset;
}
$dsn = $database_type . ':host=' . $database_server . ';dbname=' . $dbase . $charset;
$xpdo = new xPDO($dsn, $database_user, $database_password);
//echo $o=($xpdo->connect()) ? 'Connected' : 'Not Connected';
$this->modx->$xpdo_name = &$xpdo;
} else {
$xpdo = &$this->modx;
}
if (is_dir($modelpath)) {
$xpdo->addPackage($packageName, $modelpath, $prefix);
}
} else {
$xpdo = &$this->modx;
}
return $xpdo;
}
public function prepareQuery(&$xpdo, $scriptProperties) {
$modx = &$this->modx;
$limit = $modx->getOption('limit', $scriptProperties, '0');
$offset = $modx->getOption('offset', $scriptProperties, 0);
$totalVar = $modx->getOption('totalVar', $scriptProperties, 'total');
$where = $modx->getOption('where', $scriptProperties, array());
//$where = !empty($where) && !is_array($where) ? $modx->fromJSON($where) : $where;
$queries = $modx->getOption('queries', $scriptProperties, array());
$queries = !empty($queries) && !is_array($queries) ? $modx->fromJSON($queries) : $queries;
$sortConfig = $modx->getOption('sortConfig', $scriptProperties, array());
$sortConfig = !empty($sortConfig) && !is_array($sortConfig) ? $modx->fromJSON($sortConfig) : $sortConfig;
$joins = $modx->getOption('joins', $scriptProperties, array());
$joins = !empty($joins) && !is_array($joins) ? $modx->fromJSON($joins) : $joins;
$having = $modx->getOption('having', $scriptProperties, '');
$selectfields = $modx->getOption('selectfields', $scriptProperties, '');
$selectfields = !empty($selectfields) ? explode(',', $selectfields) : null;
$specialfields = $modx->getOption('specialfields', $scriptProperties, '');
$classname = $scriptProperties['classname'];
$groupby = $modx->getOption('groupby', $scriptProperties, '');
$debug = isset($scriptProperties['debug']) ? $scriptProperties['debug'] : false;
$c = $xpdo->newQuery($classname);
$c->select($xpdo->getSelectColumns($classname, $c->getAlias(), '', $selectfields));
if (!empty($specialfields)) {
$c->select($specialfields);
}
if (is_array($joins) && count($joins) > 0) {
$this->prepareJoins($classname, $joins, $c);
}
if (!empty($where)) {
if (is_string($where) && ($where[0] == '{' || $where[0] == '[')) {
$where = json_decode($where, true);
}
if (is_array($where)) {
foreach ($where as $key => $value) {
if (strstr($key, 'MONTH') || strstr($key, 'YEAR') || strstr($key, 'DATE')) {
$c->where($key . " = " . $value, xPDOQuery::SQL_AND);
unset($where[$key]);
}
}
} else {
$where = array($where);
}
$c->where($where);
}
if (!empty($queries)) {
foreach ($queries as $key => $query) {
$c->where($query, $key);
}
}
if (!empty($having)) {
$c->having($having);
}
if (!empty($groupby)) {
$c->groupby($groupby);
}
//set "total" placeholder for getPage
$total = $xpdo->getCount($classname, $c);
$modx->setPlaceholder($totalVar, $total);
if (is_array($sortConfig)) {
foreach ($sortConfig as $sort) {
$sortby = $sort['sortby'];
$sortdir = isset($sort['sortdir']) ? $sort['sortdir'] : 'ASC';
$c->sortby($sortby, $sortdir);
}
}
//&limit, &offset
if (!empty($limit)) {
$c->limit($limit, $offset);
}
$c->prepare();
if ($debug) {
echo $c->toSql();
}
return $c;
}
public function getCollection($c) {
$rows = array();
$this->modx->exec('SET SQL_BIG_SELECTS = 1');
if ($c->stmt->execute()) {
if (!$rows = $c->stmt->fetchAll(PDO::FETCH_ASSOC)) {
$rows = array();
}
}
return $rows;
}
public function checkGrouping($fields, $groupingField, $key, &$oldgroupvalue, &$group_keys, $output, $level = 0) {
if (!empty($groupingField)) {
$newgroupvalue = isset($fields[$groupingField]) ? $fields[$groupingField] : '';
$gr_level = empty($level) ? '' : $level;
/*
print_r($oldgroupvalue);
echo 'old:' . $oldgroupvalue[$level];
echo ' ';
echo 'new:' . $newgroupvalue;
echo ' ';
echo $gr_level;
echo ' ';
echo $level . ' - ';
*/
if (!isset($group_keys[$level])){
$group_keys[$level] = array();
$group_keys[$level][$key] = $key;
}
if (isset($oldgroupvalue[$level]) && $oldgroupvalue[$level] == $newgroupvalue) {
//still the same group
if ($fields['_last']) {
//last item at all
$group_keys[$level][] = $key;
$group_count = count($group_keys[$level]);
$group_idx = 1;
foreach ($group_keys[$level] as $group_key) {
$output[$group_key]['_groupcount' . $gr_level] = $group_count;
$output[$group_key]['_groupidx' . $gr_level] = $group_idx;
$output[$group_key]['_groupfirst' . $gr_level] = $group_idx == 1 ? true : '';
$output[$group_key]['_grouplast' . $gr_level] = $group_idx == $group_count ? true : '';
$group_idx++;
}
}
} elseif (isset($group_keys[$level])) {
//new group has started
$group_count = count($group_keys[$level]);
$group_idx = 1;
foreach ($group_keys[$level] as $group_key) {
$output[$group_key]['_groupcount' . $gr_level] = $group_count;
$output[$group_key]['_groupidx' . $gr_level] = $group_idx;
$output[$group_key]['_groupfirst' . $gr_level] = $group_idx == 1 ? true : '';
$output[$group_key]['_grouplast' . $gr_level] = $group_idx == $group_count ? true : '';
$group_idx++;
}
if ($fields['_last']) {
$output[$key]['_groupcount' . $gr_level] = 1;
$output[$key]['_groupidx' . $gr_level] = 1;
$output[$key]['_groupfirst' . $gr_level] = true;
$output[$key]['_grouplast' . $gr_level] = true;
}
$oldgroupvalue[$level] = $newgroupvalue;
$group_keys[$level] = array();
}
$group_keys[$level][] = $key;
if (!isset($oldgroupvalue[$level])){
$oldgroupvalue[$level] = $newgroupvalue;
}
}
return $output;
}
public function renderOutput($rows, $scriptProperties) {
$modx = &$this->modx;
$tpl = $modx->getOption('tpl', $scriptProperties, '');
$wrapperTpl = $modx->getOption('wrapperTpl', $scriptProperties, '');
$emptyTpl = $modx->getOption('emptyTpl', $scriptProperties, '');
$tplFirst = $modx->getOption('tplFirst', $scriptProperties, '');
$tplLast = $modx->getOption('tplLast', $scriptProperties, '');
$groupingField = $modx->getOption('groupingField', $scriptProperties, '');
$groupingField = $modx->getOption('groupingFields', $scriptProperties, $groupingField);
$prepareSnippet = $modx->getOption('prepareSnippet', $scriptProperties, '');
$totalVar = $modx->getOption('totalVar', $scriptProperties, 'total');
$total = $modx->getPlaceholder($totalVar);
$toSeparatePlaceholders = $modx->getOption('toSeparatePlaceholders', $scriptProperties, false);
$toPlaceholder = $modx->getOption('toPlaceholder', $scriptProperties, false);
$toPlaceholders = $modx->getOption('toPlaceholders', $scriptProperties, false);
$outputSeparator = $modx->getOption('outputSeparator', $scriptProperties, '');
//$placeholdersKeyField = $modx->getOption('placeholdersKeyField', $scriptProperties, 'MIGX_id');
$placeholdersKeyField = $modx->getOption('placeholdersKeyField', $scriptProperties, 'id');
$toJsonPlaceholder = $modx->getOption('toJsonPlaceholder', $scriptProperties, false);
$toJson = $modx->getOption('toJson', $scriptProperties, false);
$jsonPrettyPrint = $modx->getOption('jsonPrettyPrint', $scriptProperties, false);
$processedToJson = !empty($toJson) ? true : false;
$processedToJson = $modx->getOption('processedFieldsToJson', $scriptProperties, $processedToJson);
$createChunk = $modx->getOption('createChunk', $scriptProperties, false);
$addfields = $modx->getOption('addfields', $scriptProperties, '');
$addfields = !empty($addfields) ? explode(',', $addfields) : null;
$count = count($rows);
$properties = array();
foreach ($scriptProperties as $property => $value) {
$properties['property.' . $property] = $value;
}
$properties['_count'] = $count;
$properties['_total'] = $total;
$idx = $modx->getOption('idx', $scriptProperties, 0);
$output = array();
$template = array();
$groupoutput = array();
$group_indexes = array();
$groups = array();
$oldgroupvalue = array();
$group_keys = array();
$jsonOptions = $jsonPrettyPrint ? JSON_PRETTY_PRINT : null;
if ($count > 0) {
foreach ($rows as $key => $fields) {
if (!empty($addfields)) {
foreach ($addfields as $addfield) {
$addfield = explode(':', $addfield);
$addname = $addfield[0];
$adddefault = isset($addfield[1]) ? $addfield[1] : '';
$fields[$addname] = $adddefault;
}
}
if (($toJson || $toJsonPlaceholder) && !$processedToJson) {
$output[] = $fields;
} else {
$fields['_alt'] = $idx % 2;
$idx++;
$fields['_first'] = $idx == 1 ? true : '';
$fields['_last'] = $idx == $count ? true : '';
$fields['idx'] = $fields['_idx'] = $idx;
$fields = array_merge($fields, $properties);
if (!empty($prepareSnippet)) {
$result = $modx->runSnippet($prepareSnippet, array('fields' => &$fields));
}
$output[] = $fields;
//check grouping
$groupingFields = explode(',', $groupingField);
foreach ($groupingFields as $level => $gr_field) {
$output = $this->checkGrouping($fields, $gr_field, $key, $oldgroupvalue, $group_keys, $output, $level);
}
}
}
if ($toJson || $toJsonPlaceholder) {
} else {
$rows = $output;
$output = array();
$i = 0;
foreach ($rows as $fields) {
if ($i == 0 && $createChunk) {
if ($chunk = $modx->getObject('modChunk', array('name' => $createChunk))) {
} else {
$ph_prefix = !empty($toPlaceholders) ? $toPlaceholders . '.' : '';
$chunk = $modx->newObject('modChunk');
$chunk->set('name', $createChunk);
$chunk_content = array();
foreach ($fields as $field => $value) {
$chunk_content[] = '[[+' . $ph_prefix . $field . ']]';
}
$chunk->set('content', implode("\n", $chunk_content));
$chunk->save();
}
}
if ($toPlaceholders) {
//works only for one row - output the fields to placeholders
if ($toPlaceholders == 'print_r') {
return '<pre>' . print_r($fields, 1) . '</pre>';
}
$modx->toPlaceholders($fields, $toPlaceholders);
return '';
}
$rowtpl = '';
$idx = isset($fields['idx']) ? $fields['idx'] : 0;
//get changing tpls from field
if (substr($tpl, 0, 7) == "@FIELD:") {
$tplField = substr($tpl, 7);
$rowtpl = $fields[$tplField];
}
if ($fields['_first'] && !empty($tplFirst)) {
$rowtpl = $tplFirst;
}
if ($fields['_last'] && empty($rowtpl) && !empty($tplLast)) {
$rowtpl = $tplLast;
}
$tplidx = 'tpl_' . $idx;
if (empty($rowtpl) && !empty($scriptProperties[$tplidx])) {
$rowtpl = $scriptProperties[$tplidx];
}
if ($idx > 1 && empty($rowtpl)) {
$divisors = $this->getDivisors($idx);
if (!empty($divisors)) {
foreach ($divisors as $divisor) {
$tplnth = 'tpl_n' . $divisor;
if (!empty($scriptProperties[$tplnth])) {
$rowtpl = $scriptProperties[$tplnth];
if (!empty($rowtpl)) {
break;
}
}
}
}
}
//get changing tpls by running a snippet to determine the current tpl
if (substr($tpl, 0, 9) == "@SNIPPET:") {
$snippet = substr($tpl, 9);
$rowtpl = $modx->runSnippet($snippet, $fields);
}
if (!empty($rowtpl)) {
$template = $this->getTemplate($tpl, $template);
$fields['_tpl'] = $template[$tpl];
} else {
$rowtpl = $tpl;
}
$template = $this->getTemplate($rowtpl, $template);
if ($template[$rowtpl]) {
$chunk = $modx->newObject('modChunk');
$chunk->setCacheable(false);
$chunk->setContent($template[$rowtpl]);
if (!empty($placeholdersKeyField) && isset($fields[$placeholdersKeyField])) {
$output[$fields[$placeholdersKeyField]] = $chunk->process($fields);
} else {
$output[] = $chunk->process($fields);
}
} else {
if (!empty($placeholdersKeyField)) {
$output[$fields[$placeholdersKeyField]] = '<pre>' . print_r($fields, 1) . '</pre>';
} else {
$output[] = '<pre>' . print_r($fields, 1) . '</pre>';
}
}
$i++;
}
}
}
if ($toJsonPlaceholder) {
$modx->setPlaceholder($toJsonPlaceholder, json_encode($output));
return '';
}
if ($toJson) {
return json_encode($output,$jsonOptions);
}
if (!empty($toSeparatePlaceholders)) {
$modx->toPlaceholders($output, $toSeparatePlaceholders);
return '';
}
if (is_array($output)) {
$o = implode($outputSeparator, $output);
} else {
$o = $output;
}
if (!empty($o) && !empty($wrapperTpl)) {
$template = $this->getTemplate($wrapperTpl);
if ($template[$wrapperTpl]) {
$chunk = $modx->newObject('modChunk');
$chunk->setCacheable(false);
$chunk->setContent($template[$wrapperTpl]);
$properties['output'] = $o;
$o = $chunk->process($properties);
}
}
if (empty($o) && !empty($emptyTpl)) {
$template = $this->getTemplate($emptyTpl);
if ($template[$emptyTpl]) {
$chunk = $modx->newObject('modChunk');
$chunk->setCacheable(false);
$chunk->setContent($template[$emptyTpl]);
$o = $chunk->process($properties);
}
}
if (!empty($toPlaceholder)) {
$modx->setPlaceholder($toPlaceholder, $o);
return '';
}
return $o;
}
function findProcessor($processorspath, $filename, &$filenames) {
$result = $this->findCustomFile($processorspath, $filename, $filenames);
if (!$result){
$filename = strtolower($filename);
$result = $this->findCustomFile($processorspath, $filename, $filenames);
}
return $result;
}
function findGrid($processorspath, $filename, &$filenames) {
return $this->findCustomFile($processorspath, $filename, $filenames, 'grids');
}
function findCustomFile($defaultpath, $filename, &$filenames, $type = 'processors') {
$config = $this->customconfigs;
$packageName = $this->modx->getOption('packageName', $config);
$packageName = explode(',', $packageName);
$packageName = $packageName[0];
$task = $this->getTask();
if (!empty($packageName)) {
$packagepath = $this->findPackagePath($packageName);
switch ($type) {
case 'processors':
$path = $packagepath . 'processors/mgr/';
if (!empty($task)) {
$filepath = $path . $task . '/' . $filename;
$filenames[] = $filepath;
if (file_exists($filepath)) {
return $filepath;
}
}
$filepath = $path . 'default/' . $filename;
$filenames[] = $filepath;
if (file_exists($filepath)) {
return $filepath;
}
break;
case 'grids':
$path = $packagepath . 'migxtemplates/mgr/grids/';
$filepath = $path . '/' . $filename;
$filenames[] = $filepath;
if (file_exists($filepath)) {
return $filepath;
}
break;
}
}
switch ($type) {
case 'processors':
if (!empty($task)) {
$filepath = $defaultpath . $task . '/' . $filename;
$filenames[] = $filepath;
$found = false;
if (file_exists($filepath)) {
return $filepath;
}
}
$filepath = $defaultpath . 'default/' . $filename;
$filenames[] = $filepath;
if (file_exists($filepath)) {
return $filepath;
}
break;
case 'grids':
default:
$filepath = $defaultpath . $filename;
$filenames[] = $filepath;
if (file_exists($filepath)) {
return $filepath;
}
break;
}
return false;
}
function checkMultipleForms($formtabs, &$controller, &$allfields, &$record) {
$multiple_formtabs = $this->modx->getOption('multiple_formtabs', $this->customconfigs, '');
$multiple_formtabs_label = $this->modx->getOption('multiple_formtabs_label', $this->customconfigs, 'Formname');
$multiple_formtabs_field = $this->modx->getOption('multiple_formtabs_field', $this->customconfigs, 'MIGX_formname');
$controller->setPlaceholder('multiple_formtabs_label', $multiple_formtabs_label);
if (!empty($multiple_formtabs)) {
if (isset($_REQUEST['loadaction']) && $_REQUEST['loadaction'] == 'switchForm') {
$data = $this->modx->fromJson($this->modx->getOption('record_json', $_REQUEST, ''));
if (is_array($data) && isset($data[$multiple_formtabs_field])) {
$record = array_merge($record, $data);
}
}
$mf_configs = explode('||', $multiple_formtabs);
$classname = 'migxConfig';
$c = $this->modx->newQuery($classname);
$c->select($this->modx->getSelectColumns($classname, $c->getAlias()));
$c->where(array('id:IN' => $mf_configs));
$c->sortby('FIELD(' . $classname . '.id, ' . implode(',', $mf_configs) . ')');
$formnames = array();
if ($collection = $this->modx->getCollection($classname, $c)) {
$idx = 0;
$formtabs = false;
$firstformtabs = array();
foreach ($collection as $object) {
$ext = $object->get('extended');
$text = $this->modx->getOption('multiple_formtabs_optionstext', $ext, '');
$value = $this->modx->getOption('multiple_formtabs_optionsvalue', $ext, '');
$formname = array();
$formname['value'] = !empty($value) ? $value : $object->get('name');
$formname['text'] = !empty($text) ? $text : $object->get('name');
$formname['selected'] = 0;
if ($idx == 0) {
$firstformtabs = $this->modx->fromJson($object->get('formtabs'));
}
if (isset($record[$multiple_formtabs_field]) && $record[$multiple_formtabs_field] == $formname['value']) {
$formname['selected'] = 1;
$formtabs = $this->modx->fromJson($object->get('formtabs'));
}
$formnames[] = $formname;
$idx++;
/*
foreach ($form['formtabs'] as $tab) {
$tabs[$form['formname']][] = $tab;
}
*/
}
$formtabs = $formtabs ? $formtabs : $firstformtabs;
$config = $this->customconfigs;
$hooksnippets = $this->modx->fromJson($this->modx->getOption('hooksnippets', $config, ''));
if (is_array($hooksnippets)) {
$hooksnippet = $this->modx->getOption('getformnames', $hooksnippets, '');
if (!empty($hooksnippet)) {
$snippetProperties = array();
$snippetProperties['formnames'] = &$formnames;
$result = $this->modx->runSnippet($hooksnippet, $snippetProperties);
}
}
$controller->setPlaceholder('formnames', $formnames);
$field = array();
$field['field'] = $multiple_formtabs_field;
$field['tv_id'] = 'Formname';
$allfields[] = $field;
}
}
return $formtabs;
}
function loadConfigs($grid = true, $other = true, $properties = array(), $sender = '') {
$winbuttons = array();
$gridactionbuttons = array();
$gridcolumnbuttons = array();
$gridcontextmenus = array();
$gridfunctions = array();
$winfunctions = array();
$renderer = array();
$editors = array();
$gridfilters = array();
$configs = array('migx_default');
//$configs = array();
if (isset($properties['configs']) && !empty($properties['configs'])) {
$configs = explode(',', $properties['configs']);
} elseif (isset($this->config['configs']) && !empty($this->config['configs'])) {
$configs = explode(',', $this->config['configs']);
}
$tempParams = $this->modx->getOption('tempParams', $properties, '');
if (!empty($configs)) {
//$configs = (isset($this->config['configs'])) ? explode(',', $this->config['configs']) : array();
//$configs = array_merge( array ('master'), $configs);
if ($grid) {
$configFile = $this->config['corePath'] . 'configs/grid/grid.config.inc.php'; // [ file ]
if (file_exists($configFile)) {
include ($configFile);
}
//custom collection of grid-functions...... - deprecated
$configFile = $this->config['corePath'] . 'configs/grid/grid.custom.config.inc.php'; // [ file ]
if (file_exists($configFile)) {
include ($configFile);
}
}
//get migxconfig-specific grid-configs
$req_configs = $this->modx->getOption('configs', $_REQUEST, '');
$preloadGridConfigs = false;
if ($sender == 'mgr/fields' && ($req_configs == 'migxcolumns' || $req_configs == 'migxdbfilters')) {
$preloadGridConfigs = true;
$configs_id = $this->modx->getOption('co_id', $_REQUEST, '');
$this->configsObject = $this->modx->getObject('migxConfig', $configs_id);
}
if ($sender == 'migxconfigs/fields') {
$preloadGridConfigs = true;
}
if ($preloadGridConfigs && is_Object($this->configsObject)) {
$config = $this->configsObject->get('name');
$configFile = $this->config['corePath'] . 'configs/grid/grid.' . $config . '.config.inc.php'; // [ file ]
if (file_exists($configFile)) {
include ($configFile);
}
//package-specific
$extended = $this->configsObject->get('extended');
$packageName = $this->modx->getOption('packageName', $extended, '');
if (!empty($packageName)) {
$packageName = explode(',', $packageName);
$packageName = $packageName[0];
$packagepath = $this->findPackagePath($packageName);
$configFile = $packagepath . 'migxconfigs/grid/grid.' . $config . '.config.inc.php'; // [ file ]
if (file_exists($configFile)) {
include ($configFile);
}
$configFile = $packagepath . 'migxconfigs/grid/grid.config.inc.php'; // [ file ]
if (file_exists($configFile)) {
include ($configFile);
}
}
}
if ($tempParams == 'importcsv') {
$configs[] = 'importcsv';
}
if ($tempParams == 'exportcsv') {
$configs[] = 'exportcsv';
}
foreach ($configs as $config) {
$parts = explode(':', $config);
$cfObject = false;
if (isset($parts[1])) {
$config = $parts[0];
$packageName = $parts[1];
} elseif ($cfObject = $this->modx->getObject('migxConfig', array('name' => $config, 'deleted' => '0'))) {
$extended = $cfObject->get('extended');
$packageName = $this->modx->getOption('packageName', $extended, '');
}
if (isset($packageName)) {
$packageName = explode(',', $packageName);
$packageName = $packageName[0];
$packagepath = $this->findPackagePath($packageName);
$configpath = $packagepath . 'migxconfigs/';
}
if ($grid) {
//first try to find custom-grid-configurations (buttons,context-menus,functions)
$configFile = $this->config['corePath'] . 'configs/grid/grid.' . $config . '.config.inc.php'; // [ file ]
if (file_exists($configFile)) {
include ($configFile);
}
if (!empty($packageName)) {
$configFile = $configpath . 'grid/grid.' . $config . '.config.inc.php'; // [ file ]
if (file_exists($configFile)) {
include ($configFile);
}
$configFile = $configpath . 'grid/grid.config.inc.php'; // [ file ]
if (file_exists($configFile)) {
include ($configFile);
}
}
}
if ($other) {
//second try to find config-object
if (isset($configpath) && !$cfObject && file_exists($configpath . $config . '.config.js')) {
$filecontent = @file_get_contents($configpath . $config . '.config.js');
$objectarray = $this->importconfig($this->modx->fromJson($filecontent));
$this->prepareConfigsArray($objectarray, $gridactionbuttons, $gridcontextmenus, $gridcolumnbuttons, $winbuttons);
}
if ($cfObject) {
$objectarray = $cfObject->toArray();
$this->prepareConfigsArray($objectarray, $gridactionbuttons, $gridcontextmenus, $gridcolumnbuttons, $winbuttons);
}
//and from MIGX config folder
$configFile = $this->config['corePath'] . 'configs/' . $config . '.config.js'; // [ file ]
if (file_exists($configFile)) {
$filecontent = @file_get_contents($configFile);
$objectarray = $this->importconfig($this->modx->fromJson($filecontent));
if (isset($objectarray['name']) && ($objectarray['name'] == 'importcsv' || $objectarray['name'] == 'exportcsv')){
if (isset($this->customconfigs['win_id'])){
$objectarray['extended']['win_id'] = $this->customconfigs['win_id'];
}
}
$this->prepareConfigsArray($objectarray, $gridactionbuttons, $gridcontextmenus, $gridcolumnbuttons, $winbuttons);
}
if (!isset($objectarray) || !is_array($objectarray)){
//get some default configs, if not allready done
$objectarray = array();
$this->prepareConfigsArray($objectarray, $gridactionbuttons, $gridcontextmenus, $gridcolumnbuttons, $winbuttons);
}
//third add configs from file, if exists
$configFile = $this->config['corePath'] . 'configs/' . $config . '.config.inc.php'; // [ file ]
if (file_exists($configFile)) {
include ($configFile);
}
if (isset($configpath) && !empty($packageName)) {
$configFile = $configpath . $config . '.config.inc.php'; // [ file ]
if (file_exists($configFile)) {
include ($configFile);
}
}
}
//print_r($this->customconfigs['tabs']) ;
}
}
if (isset($this->customconfigs['filters']) && is_array($this->customconfigs['filters']) && count($this->customconfigs['filters']) > 0) {
foreach ($this->customconfigs['filters'] as $filter) {
if (isset($gridfilters[$filter['type']]) && is_array($gridfilters[$filter['type']])) {
$this->customconfigs['gridfilters'][$filter['name']] = array_merge($filter, $gridfilters[$filter['type']]);
}
}
}
$this->customconfigs['gridactionbuttons'] = $gridactionbuttons;
$this->customconfigs['gridcontextmenus'] = $gridcontextmenus;
$this->customconfigs['gridcolumnbuttons'] = $gridcolumnbuttons;
$this->customconfigs['gridfunctions'] = array_merge($gridfunctions, $renderer, $editors);
$this->customconfigs['winfunctions'] = $winfunctions;
$this->customconfigs['windowbuttons'] = $winbuttons;
//$defaulttask = empty($this->customconfigs['join_alias']) ? 'default' : 'default_join';
$defaulttask = 'default';
$this->customconfigs['task'] = empty($this->customconfigs['task']) ? $defaulttask : $this->customconfigs['task'];
}
public function prepareConfigsArray($objectarray, &$gridactionbuttons, &$gridcontextmenus, &$gridcolumnbuttons, &$winbuttons) {
if (isset($objectarray['extended']) && is_array($objectarray['extended'])) {
foreach ($objectarray['extended'] as $key => $value) {
if (!empty($value)) {
$this->customconfigs[$key] = $value;
}
}
}
unset($objectarray['extended']);
if (isset($this->customconfigs)) {
$this->customconfigs = is_array($this->customconfigs) ? array_merge($this->customconfigs, $objectarray) : $objectarray;
$this->customconfigs['tabs'] = isset($objectarray['formtabs']) ? $this->modx->fromJson($objectarray['formtabs']) : array();
$this->customconfigs['filters'] = isset($objectarray['filters']) ? $this->modx->fromJson($objectarray['filters']) : array();
//$this->customconfigs['tabs'] = stripslashes($cfObject->get('formtabs'));
//$this->customconfigs['columns'] = $this->modx->fromJson(stripslashes($cfObject->get('columns')));
$this->customconfigs['columns'] = isset($objectarray['columns']) ? $this->modx->fromJson($objectarray['columns']) : array();
}
$menus = isset($objectarray['contextmenus']) ? $objectarray['contextmenus'] : '';
if (!empty($menus)) {
$menus = explode('||', $menus);
foreach ($menus as $menu) {
$gridcontextmenus[$menu]['active'] = 1;
}
}
$columnbuttons = isset($objectarray['columnbuttons']) ? $objectarray['columnbuttons'] : '';
if (!empty($columnbuttons)) {
$columnbuttons = explode('||', $columnbuttons);
foreach ($columnbuttons as $button) {
if (isset($gridcontextmenus[$button])) {
$gridcolumnbuttons[$button] = $gridcontextmenus[$button];
$gridcolumnbuttons[$button]['active'] = 1;
}
}
}
$actionbuttons = isset($objectarray['actionbuttons']) ? $objectarray['actionbuttons'] : '';
if (!empty($actionbuttons)) {
$actionbuttons = explode('||', $actionbuttons);
foreach ($actionbuttons as $button) {
$gridactionbuttons[$button]['active'] = 1;
}
}
$winbuttonslist = null;
if (isset($this->customconfigs['winbuttonslist'])) {
$winbuttonslist = $this->customconfigs['winbuttonslist'];
if (!empty($winbuttonslist)) {
$winbuttonslist = explode('||', $winbuttonslist);
foreach ($winbuttonslist as $button) {
$winbuttons[$button]['active'] = 1;
}
}
}
if (!is_array($winbuttonslist)){
foreach ($winbuttons as $key =>$button){
if (isset($button['default']) && !empty($button['default'])){
$winbuttons[$key]['active'] = 1;
}
}
}
}
function loadPackageManager() {
include_once ($this->config['modelPath'] . 'migx/migxpackagemanager.class.php');
return new MigxPackageManager($this->modx);
}
public function getTask() {
return isset($this->customconfigs['task']) ? $this->customconfigs['task'] : '';
}
public function getTabs() {
return isset($this->customconfigs['tabs']) ? $this->customconfigs['tabs'] : '';
}
public function getColumns() {
return isset($this->customconfigs['columns']) ? $this->customconfigs['columns'] : '';
}
public function getGrid() {
return !empty($this->customconfigs['grid']) ? $this->customconfigs['grid'] : 'default';
}
public function prepareCmpTabs($properties, &$controller, &$tv) {
$cmptabs = (isset($this->config['cmptabs'])) ? explode('||', $this->config['cmptabs']) : array();
$cmptabsout = array();
$grids = '';
$updatewindows = '';
$iframewindows = '';
$customHandlers = array();
$maincaption = "_('migx.management')";
if (count($cmptabs) > 0) {
foreach ($cmptabs as $tab_idx => $tab) {
$this->customconfigs = array();
$this->config['configs'] = $tab;
$properties['tv_id'] = $tab_idx + 1;
$this->prepareGrid($properties, $controller, $tv);
$tabcaption = empty($this->customconfigs['cmptabcaption']) ? 'undefined' : $this->customconfigs['cmptabcaption'];
$tabdescription = empty($this->customconfigs['cmptabdescription']) ? 'undefined' : $this->customconfigs['cmptabdescription'];
$maincaption = empty($this->customconfigs['cmpmaincaption']) ? $maincaption : "'" . $this->replaceLang($this->customconfigs['cmpmaincaption']) . "'";
$controller->setPlaceholder('config', $this->config);
$controller->setPlaceholder('cmptabcaption', $tabcaption);
$controller->setPlaceholder('cmptabdescription', $tabdescription);
$cmptabfile = $this->config['templatesPath'] . 'mgr/cmptab.tpl';
if (!empty($this->customconfigs['cmptabcontroller'])) {
$controllerfile = $this->config['controllersPath'] . 'custom/' . $this->customconfigs['cmptabcontroller'] . '.php';
if (file_exists($controllerfile)) {
$tabTemplate = '';
include ($controllerfile);
if (!empty($tabTemplate) && file_exists($tabTemplate)) {
$cmptabfile = $tabTemplate;
}
}
}
$cmptabsout[] = $this->replaceLang($controller->fetchTemplate($cmptabfile));
$grid = $this->getGrid();
$filenames = array();
$defaultpath = $this->config['templatesPath'] . '/mgr/grids/';
$filename = $grid . '.grid.tpl';
if ($gridfile = $this->findGrid($defaultpath, $filename, $filenames)) {
$grids .= $this->replaceLang($controller->fetchTemplate($gridfile));
}
//$gridfile = $this->config['templatesPath'] . '/mgr/grids/' . $grid . '.grid.tpl';
//$windowfile = $this->config['templatesPath'] . 'mgr/updatewindow.tpl';
//$updatewindows .= $this->replaceLang($controller->fetchTemplate($windowfile));
$filenames = array();
$defaultpath = $this->config['templatesPath'] . 'mgr/';
$filename = 'updatewindow.tpl';
if ($gridfile = $this->findGrid($defaultpath, $filename, $filenames)) {
$updatewindows .= $this->replaceLang($controller->fetchTemplate($gridfile));
}
$filenames = array();
$filename = 'iframewindow.tpl';
if ($windowfile = $this->findGrid($defaultpath, $filename, $filenames)) {
$iframewindows .= $this->replaceLang($controller->fetchTemplate($windowfile));
}
}
}
if (count($customHandlers) > 0) {
$customHandlers = implode(',', $customHandlers);
$controller->setPlaceholder('customHandlers', $customHandlers);
}
$controller->setPlaceholder('maincaption', $maincaption);
$controller->setPlaceholder('grids', $grids);
$controller->setPlaceholder('updatewindows', $updatewindows);
$controller->setPlaceholder('iframewindows', $iframewindows);
$controller->setPlaceholder('cmptabs', implode(',', $cmptabsout));
return $controller->fetchTemplate($this->config['templatesPath'] . 'mgr/gridpanel.tpl');
}
public function loadLang($prefix = 'migx') {
$lang = $this->modx->lexicon->fetch($prefix);
if (is_array($lang)) {
$this->migxlang = isset($this->migxlang) && is_array($this->migxlang) ? array_merge($this->migxlang, $lang) : $lang;
//$this->migxi18n = array();
foreach ($lang as $key => $value) {
$this->addLangValue($key, $value);
}
}
}
public function addLangValue($key, $value) {
//$key = str_replace('migx.', 'migx_', $key);
//$this->migxi18n[$key] = $value;
$this->langSearch[$key] = '[[%' . $key . ']]';
$this->langReplace[$key] = $value;
}
public function replaceLang($value, $debug = false) {
if ($debug) {
echo str_replace($this->langSearch, $this->langReplace, $value);
}
if (isset($this->langSearch) && isset($this->langReplace)) {
$value = str_replace($this->langSearch, $this->langReplace, $value);
}
return $value;
}
public function prepareGrid($properties, &$controller, &$tv, $columns = array()) {
$this->loadConfigs(false);
//$lang = $this->modx->lexicon->fetch();
$resource = is_object($this->modx->resource) ? $this->modx->resource->toArray() : array();
$resource['id'] = $this->config['resource_id'] = $this->modx->getOption('id', $resource, '');
$this->config['connected_object_id'] = $this->modx->getOption('object_id', $_REQUEST, '');
$this->config['req_configs'] = $this->modx->getOption('configs', $_REQUEST, '');
if (isset($this->customconfigs['media_source_id'])) {
$this->config['media_source_id'] = $this->customconfigs['media_source_id'];
} else {
$this->config['media_source_id'] = is_object($this->source) ? $this->source->id : $this->getDefaultSource('id');
}
if (is_object($tv)) {
$win_id = $tv->get('id');
$tv_type = $tv->get('type');
} else {
$tv_type = '';
$win_id = 'migxdb';
$tv = $this->modx->newObject('modTemplateVar');
$controller->setPlaceholder('tv', $tv);
}
$this->customconfigs['win_id'] = !empty($this->customconfigs['win_id']) ? $this->customconfigs['win_id'] : $win_id;
$tv_id = $tv->get('id');
$tv_id = empty($tv_id) && isset($properties['tv_id']) ? $properties['tv_id'] : $tv_id;
$this->config['tv_id'] = $tv_id;
$search = array();
$replace = array();
foreach ($this->config as $key => $value) {
if (!is_array($value)) {
$replace['config_' . $key] = $value;
$search['config_' . $key] = '[[+config.' . $key . ']]';
}
}
foreach ($this->customconfigs as $key => $value) {
if (!is_array($value)) {
$replace['config_' . $key] = $value;
$search['config_' . $key] = '[[+config.' . $key . ']]';
}
}
$this->migxlang['migx.add'] = isset($this->migxlang['migx.add']) ? $this->migxlang['migx.add'] : 'Add Item';
$l['migx.add'] = !empty($this->customconfigs['migx_add']) ? $this->customconfigs['migx_add'] : $this->migxlang['migx.add'];
$l['migx.add'] = str_replace("'", "\'", $l['migx.add']);
$this->addLangValue('migx.add', $l['migx.add']);
$this->loadConfigs();
$handlers = array();
if (isset($this->customconfigs['extrahandlers'])) {
$extrahandlers = explode('||', $this->customconfigs['extrahandlers']);
foreach ($extrahandlers as $handler) {
$handlers[] = $handler;
}
}
//winbuttons
$winbuttons = '';
if (isset($this->customconfigs['windowbuttons'])) {
if (is_array($this->customconfigs['windowbuttons']) && count($this->customconfigs['windowbuttons']) > 0) {
$buttons_a = array();
foreach ($this->customconfigs['windowbuttons'] as $button) {
if (!empty($button['active'])) {
unset($button['active']);
if (isset($button['handler'])) {
$handlerarr = explode(',', $button['handler']);
foreach ($handlerarr as $handler) {
if (!in_array($handler, $handlers)) {
$handlers[] = $handler;
}
}
}
$buttons_a[] = str_replace('"', '', json_encode($button));
}
}
if (count($buttons_a) > 0) {
$winbuttons = ',buttons:[' . implode(',', $buttons_a) . ']';
}
}
}
$this->customconfigs['winbuttons'] = $winbuttons;
$buttons = array();
if (count($this->customconfigs['gridactionbuttons']) > 0) {
foreach ($this->customconfigs['gridactionbuttons'] as $button) {
if (!empty($button['active'])) {
unset($button['active']);
if (isset($button['handler'])) {
$handlerarr = explode(',', $button['handler']);
$button['handler'] = $handlerarr[0]; //can have only one handler, use the first one
//load one or multiple handlers
foreach ($handlerarr as $handler) {
if (!in_array($handler, $handlers)) {
$handlers[] = $handler;
}
}
}
if (isset($button['menu']) && is_array($button['menu'])) {
foreach ($button['menu'] as $menu) {
if (!in_array($menu['handler'], $handlers)) {
$handlers[] = $menu['handler'];
}
}
}
//$button['text'] = $this->replaceLang($button['text']);
$standalone = $this->modx->getOption('standalone', $button, '');
if (!empty($standalone)) {
$gridbuttons[] = str_replace('"', '', json_encode($button));
} else {
$buttons[] = str_replace('"', '', json_encode($button));
}
}
}
}
$filters = array();
$filterDefaults = array();
if (isset($this->customconfigs['gridfilters']) && count($this->customconfigs['gridfilters']) > 0) {
foreach ($this->customconfigs['gridfilters'] as $filter) {
if (isset($filter['comboparent']) && !empty($filter['comboparent'])) {
$combochilds[$filter['comboparent']][$filter['name']] = $filter['name'];
}
}
foreach ($this->customconfigs['gridfilters'] as $filter) {
$filter['emptytext'] = empty($filter['emptytext']) ? 'migx.search' : $filter['emptytext'];
$filter['emptytext'] = str_replace(array('[[%', ']]'), '', $this->replaceLang('[[%' . $filter['emptytext'] . ']]'));
$filter['combochilds'] = '[]';
if (isset($combochilds[$filter['name']])) {
$filter['combochilds'] = json_encode(array_values($combochilds[$filter['name']]));
//print_r($filter);
}
foreach ($filter as $key => $value) {
if (!is_array($value)) {
$replace[$key] = $value;
$search[$key] = '[[+' . $key . ']]';
}
}
$filtername = $filter['handler'] . '_' . $filter['name'];
if (isset($this->customconfigs['gridfunctions'][$filter['handler']])) {
$this->customconfigs['gridfunctions'][$filtername] = str_replace($search, $replace, $this->customconfigs['gridfunctions'][$filter['handler']]);
}
$filters[] = str_replace($search, $replace, $filter['code']);
if (!in_array($filtername, $handlers)) {
$handlers[] = $filtername;
}
$default = array();
$default['name'] = $filter['name'];
$default['default'] = isset($filter['default']) ? $filter['default'] : '';
if (isset($_REQUEST['filter_' . $filter['name']])) {
$default['default'] = $this->modx->sanitizeString($_REQUEST['filter_' . $filter['name']]);
}
$filterDefaults[] = $default;
}
}
$this->customconfigs['tbar'] = '';
$tbaritems = array();
$tbaractions = array();
if (isset($gridbuttons) && count($gridbuttons) > 0) {
$gridbuttons = implode(',', $gridbuttons);
$tbaractions[] = $gridbuttons;
}
if (isset($buttons) && count($buttons) > 0) {
$gridactionbuttons = implode(',', $buttons);
$perRow = $this->modx->getOption('actionbuttonsperrow', $this->customconfigs, '4');
$tbaractions[] = "
{
xtype: 'buttongroup',
title: '[[%migx.actions]]',
columns: {$perRow},
defaults: {
scale: 'large'
},
items: [{$gridactionbuttons}]
}
";
}
if (count($tbaractions) > 0) {
$tbaritems[] = implode(',', $tbaractions);
}
$tbarfilters = array();
if (count($filters) > 0) {
$gridfilters = implode(',', $filters);
$perRow = $this->modx->getOption('filtersperrow', $this->customconfigs, '4');
$tbarfilters[] = "
{
xtype: 'buttongroup',
title: '[[%migx.filters]]',
columns: {$perRow},
defaults: {
scale: 'large'
},
items: [{$gridfilters}]
}
";
}
if (count($tbarfilters) > 0) {
$tbaritems[] = implode(',', $tbarfilters);
}
if (count($tbaritems) > 0) {
$this->customconfigs['tbar'] = implode(',', $tbaritems);
}
$menues = '';
if (count($this->customconfigs['gridcontextmenus']) > 0) {
foreach ($this->customconfigs['gridcontextmenus'] as $menue) {
if (!empty($menue['active'])) {
unset($menue['active']);
if (!empty($menue['handler'])) {
$handlerarr = explode(',', $menue['handler']);
foreach ($handlerarr as $handler) {
if (!in_array($handler, $handlers)) {
$handlers[] = $handler;
}
}
}
//$menues .= $this->replaceLang($menue['code']);
$menues .= $menue['code'];
}
}
}
if ($tv_type == 'migx' && empty($menues)) {
//default context-menues for migx
$menues = "
m.push({
text: '[[%migx.edit]]'
,handler: this.migx_update
});
m.push({
text: '[[%migx.duplicate]]'
,handler: this.migx_duplicate
});
m.push('-');
m.push({
text: '[[%migx.remove]]'
,handler: this.migx_remove
});
m.push('-');
m.push({
text: '[[%migx.move_to_top]]'
,handler: this.moveToTop
});
m.push({
text: '[[%migx.move_to_bottom]]'
,handler: this.moveToBottom
});
";
}
$this->customconfigs['gridcontextmenus'] = $menues;
$columnbuttons = '';
if (count($this->customconfigs['gridcolumnbuttons']) > 0) {
foreach ($this->customconfigs['gridcolumnbuttons'] as $button) {
if (!empty($button['active'])) {
unset($button['active']);
if (!empty($button['handler'])) {
$handlerarr = explode(',', $button['handler']);
foreach ($handlerarr as $handler) {
if (!in_array($handler, $handlers)) {
$handlers[] = $handler;
}
}
}
//$menues .= $this->replaceLang($menue['code']);
$columnbuttons .= $button['code'];
}
}
}
$this->customconfigs['gridcolumnbuttons'] = $columnbuttons;
$gridfunctions = array();
$default_formtabs = '[{"caption":"Default", "fields": [{"field":"title","caption":"Title"}]}]';
$default_columns = '[{"header": "Title", "width": "160", "sortable": "true", "dataIndex": "title"}]';
$formtabs = $this->getTabs();
if (empty($formtabs)) {
// get them from input-properties
$formtabs = $this->modx->fromJSON($this->modx->getOption('formtabs', $properties, $default_formtabs));
$formtabs = empty($properties['formtabs']) ? $this->modx->fromJSON($default_formtabs) : $formtabs;
}
//$this->migx->debug('resource',$resource);
//multiple different Forms
// Note: use same field-names and inputTVs in all forms
$inputTvs = $this->extractFieldsFromTabs($formtabs);
/* get base path based on either TV param or filemanager_path */
//$this->modx->getService('fileHandler', 'modFileHandler', '', array('context' => $this->modx->context->get('key')));
/* pasted from processors.element.tv.renders.mgr.input*/
/* get working context */
$wctx = isset($_GET['wctx']) && !empty($_GET['wctx']) ? $this->modx->sanitizeString($_GET['wctx']) : '';
if (!empty($wctx)) {
$workingContext = $this->modx->getContext($wctx);
if (!$workingContext) {
return $this->modx->error->failure($this->modx->lexicon('permission_denied'));
}
$wctx = $workingContext->get('key');
} else {
$wctx = $this->modx->context->get('key');
}
$this->working_context = $wctx;
if (is_object($tv)) {
$this->source = $tv->getSource($this->working_context, false);
}
/* pasted end*/
//$base_path = $modx->getOption('base_path', null, MODX_BASE_PATH);
//$base_url = $modx->getOption('base_url', null, MODX_BASE_URL);
//$columns = $this->modx->fromJSON($this->modx->getOption('columns', $properties, $default_columns));
//$columns = empty($properties['columns']) ? $this->modx->fromJSON($default_columns) : $columns;
$columns = empty($columns) ? $this->getColumns() : $columns;
$item = array();
$pathconfigs = array();
$cols = array();
$fields = array();
$colidx = 0;
if (is_array($columns) && count($columns) > 0) {
foreach ($columns as $key => $column) {
$field = array();
if (isset($column['type'])) {
$field['type'] = $column['type'];
}
$field['name'] = $column['dataIndex'];
$field['mapping'] = $column['dataIndex'];
$fields[] = $field;
$column['show_in_grid'] = isset($column['show_in_grid']) ? (int)$column['show_in_grid'] : 1;
$fieldconfig = $this->modx->getOption($field['name'], $inputTvs, '');
if (!empty($column['show_in_grid'])) {
$col = array();
$col['dataIndex'] = $column['dataIndex'];
$col['header'] = htmlentities($this->replaceLang($column['header']), ENT_QUOTES, $this->modx->getOption('modx_charset'));
$col['sortable'] = isset($column['sortable']) && $column['sortable'] == 'true' ? true : false;
if (isset($column['width']) && !empty($column['width'])) {
$col['width'] = (int)$column['width'];
}
if (isset($column['renderer']) && !empty($column['renderer'])) {
$col['renderer'] = $column['renderer'];
$handlers[] = $column['renderer'];
}
if (isset($column['editor']) && !empty($column['editor'])) {
$col['editor'] = $column['editor'];
$handlers[] = $column['editor'];
}
$cols[] = $col;
$pathconfigs[$colidx] = isset($inputTvs[$field['name']]) ? $this->prepareSourceForGrid($inputTvs[$field['name']]) : array();
$colidx++;
}
$default = isset($fieldconfig['default']) ? (string )$fieldconfig['default'] : '';
$item[$field['name']] = isset($column['default']) ? $column['default'] : $default;
}
}
$newitem[] = $item;
$gf = '';
$wf = '';
if (count($handlers) > 0) {
$gridfunctions = array();
$winfunctions = array();
$collectedhandlers = array();
foreach ($handlers as $handler) {
if (!in_array($handler, $collectedhandlers) && isset($this->customconfigs['gridfunctions'][$handler])) {
$gridfunction = $this->customconfigs['gridfunctions'][$handler];
if (!empty($gridfunction)) {
$collectedhandlers[] = $handler;
$gridfunctions[] = $gridfunction;
}
}
if (!in_array($handler, $collectedhandlers) && isset($this->customconfigs['winfunctions'][$handler])) {
$winfunction = $this->customconfigs['winfunctions'][$handler];
if (!empty($winfunction)) {
$collectedhandlers[] = $handler;
$winfunctions[] = $winfunction;
}
}
}
if (count($gridfunctions) > 0) {
$gf = ',' . str_replace($search, $replace, implode(',', $gridfunctions));
$gf = str_replace('[[+newitem]]', json_encode($newitem), $gf);
}
if (count($winfunctions) > 0) {
$wf = ',' . str_replace($search, $replace, implode(',', $winfunctions));
}
}
$this->customconfigs['gridfunctions'] = $gf;
$this->customconfigs['winfunctions'] = $wf;
//print_r(array_keys($this->customconfigs));
//$controller->setPlaceholder('i18n', $this->migxi18n);
$tv_caption = $tv->get('caption');
$tv_name = $tv->get('name');
$default_win_title = !empty($tv_name) ? $tv_name : 'MIGX';
$default_win_title = !empty($tv_caption) ? $tv_caption : $default_win_title;
$controller->setPlaceholder('filterDefaults', json_encode($filterDefaults));
$controller->setPlaceholder('tv_id', $tv_id);
$controller->setPlaceholder('migx_lang', json_encode($this->migxlang));
$controller->setPlaceholder('properties', $properties);
$controller->setPlaceholder('resource', $resource);
$controller->setPlaceholder('configs', $this->modx->getOption('configs', $this->config, ''));
$controller->setPlaceholder('reqConfigs', $this->modx->getOption('configs', $_REQUEST, ''));
$controller->setPlaceholder('object_id', $this->modx->getOption('object_id', $_REQUEST, ''));
$controller->setPlaceholder('reqTempParams', $this->modx->getOption('tempParams', $_REQUEST, ''));
$controller->setPlaceholder('connected_object_id', $this->modx->getOption('object_id', $_REQUEST, ''));
$controller->setPlaceholder('window_id', $this->modx->getOption('window_id', $_REQUEST, ''));
$controller->setPlaceholder('pathconfigs', json_encode($pathconfigs));
$controller->setPlaceholder('columns', json_encode($cols));
$controller->setPlaceholder('fields', json_encode($fields));
$controller->setPlaceholder('newitem', json_encode($newitem));
$controller->setPlaceholder('base_url', $this->modx->getOption('base_url'));
$controller->setPlaceholder('myctx', $wctx);
$controller->setPlaceholder('auth', $_SESSION["modx.{$this->modx->context->get('key')}.user.token"]);
$controller->setPlaceholder('customconfigs', $this->customconfigs);
$controller->setPlaceholder('win_id', $this->customconfigs['win_id']);
$controller->setPlaceholder('update_win_title', !empty($this->customconfigs['update_win_title']) ? $this->customconfigs['update_win_title'] : $default_win_title);
}
function getColumnRenderOptions($col = '*', $indexfield = 'idx', $format = 'json', $getdefaultclickaction = false) {
$columns = $this->getColumns();
$columnrenderoptions = array();
$optionscolumns = array();
if (is_array($columns)) {
foreach ($columns as $column) {
$defaultclickaction = '';
$renderer = $this->modx->getOption('renderer', $column, '');
$renderoptions = $this->modx->getOption('renderoptions', $column, '');
$renderchunktpl = $this->modx->getOption('renderchunktpl', $column, '');
$options = $this->modx->fromJson($renderoptions);
if ($getdefaultclickaction && !empty($column['clickaction'])) {
$option = array();
$defaultclickaction = $column['clickaction'];
$option['clickaction'] = $column['clickaction'];
$option['selectorconfig'] = $this->modx->getOption('selectorconfig', $column, '');
$defaultselectorconfig = $option['selectorconfig'];
$columnrenderoptions[$column['dataIndex']]['default_clickaction'] = $option;
}
if (is_array($options) && count($options) > 0) {
foreach ($options as $key => $option) {
$option['idx'] = $key;
$option['_renderer'] = $renderer;
$option['clickaction'] = empty($option['clickaction']) && !empty($defaultclickaction) ? $defaultclickaction : $option['clickaction'];
$option['selectorconfig'] = $this->modx->getOption('selectorconfig', $column, '');
$option['selectorconfig'] = empty($option['selectorconfig']) && !empty($defaultselectorconfig) ? $defaultselectorconfig : $option['selectorconfig'];
if (isset($option['use_as_fallback']) && !empty($option['use_as_fallback'])) {
$option['value'] = 'use_as_fallback';
}
$option[$indexfield] = isset($option[$indexfield]) ? $option[$indexfield] : 0;
$columnrenderoptions[$column['dataIndex']][$option[$indexfield]] = $format == 'json' ? json_encode($option) : $option;
}
} elseif (!empty($renderer) && $renderer == 'this.renderChunk') {
$option['idx'] = 0;
$option['_renderer'] = $renderer;
$option['_renderchunktpl'] = $renderchunktpl;
$option[$indexfield] = isset($option[$indexfield]) ? $option[$indexfield] : 0;
$columnrenderoptions[$column['dataIndex']][$option[$indexfield]] = $format == 'json' ? json_encode($option) : $option;
}
}
}
return $col == '*' ? $columnrenderoptions : $columnrenderoptions[$col];
}
function renderChunk($tpl, $properties = array(), $getChunk = true, $printIfemty = true) {
$value = $this->parseChunk($tpl, $properties, $getChunk, $printIfemty);
$this->modx->getParser();
/*parse all non-cacheable tags and remove unprocessed tags, if you want to parse only cacheable tags set param 3 as false*/
$this->modx->parser->processElementTags('', $value, true, true, '[[', ']]', array());
return $value;
}
function checkRenderOptions($rows) {
$columnrenderoptions = $this->getColumnRenderOptions('*', 'value', 'array');
//print_r($columnrenderoptions);
$outputrows = is_array($rows) ? $rows : array();
if (is_array($rows) && count($columnrenderoptions) > 0) {
$outputrows = array();
foreach ($rows as $row) {
foreach ($columnrenderoptions as $column => $options) {
$value = $this->modx->getOption($column, $row, '');
$row[$column . '_ro'] = isset($options[$value]) ? json_encode($options[$value]) : '';
if (empty($row[$column . '_ro']) && isset($options['use_as_fallback'])) {
$row[$column . '_ro'] = json_encode($options['use_as_fallback']);
}
foreach ($options as $option) {
if ($option['_renderer'] == 'this.renderChunk') {
$row['_this.value'] = $value;
$properties = $row;
$properties['_request'] = $_REQUEST;
$properties['_media_source_id'] = $this->config['media_source_id'];
$renderchunktpl = $this->modx->getOption('_renderchunktpl', $option, '');
if (!empty($renderchunktpl)) {
$row[$column] = $this->renderChunk($renderchunktpl, $properties, false);
} else {
$row[$column] = $this->renderChunk($option['name'], $properties);
}
}
break;
}
}
$outputrows[] = $row;
}
}
return $outputrows;
}
function prepareSourceForGrid($inputTv) {
if (!empty($inputTv['inputTV']) && $tv = $this->modx->getObject('modTemplateVar', array('name' => $inputTv['inputTV']))) {
} else {
$tv = $this->modx->newObject('modTemplateVar');
}
$mediasource = $this->getFieldSource($inputTv, $tv);
return '&source=' . $mediasource->get('id');
}
function getFieldSource($field, &$tv) {
//source from config
$sourcefrom = isset($field['sourceFrom']) && !empty($field['sourceFrom']) ? $field['sourceFrom'] : 'config';
if ($sourcefrom == 'config' && isset($field['sources'])) {
if (is_array($field['sources'])) {
foreach ($field['sources'] as $context => $sourceid) {
$sources[$context] = $sourceid;
}
} else {
$fsources = $this->modx->fromJson($field['sources']);
if (is_array($fsources)) {
foreach ($fsources as $source) {
if (isset($source['context']) && isset($source['sourceid'])) {
$sources[$source['context']] = $source['sourceid'];
}
}
}
}
}
if (isset($sources[$this->working_context]) && !empty($sources[$this->working_context])) {
//try using field-specific mediasource from config
if ($mediasource = $this->modx->getObject('sources.modMediaSource', $sources[$this->working_context])) {
return $mediasource;
}
}
if ($this->source && $sourcefrom == 'migx') {
//use global MIGX-mediasource for all TVs
$tv->setSource($this->source);
$mediasource = $this->source;
} else {
//useTV-specific mediasource
$mediasource = $tv->getSource($this->working_context, false);
}
//try to get the context-default-media-source
if (!$mediasource) {
$mediasource = $this->getDefaultSource();
}
return $mediasource;
}
function getDefaultSource($return = 'object') {
$defaultSourceId = null;
if ($contextSetting = $this->modx->getObject('modContextSetting', array('key' => 'default_media_source', 'context_key' => $this->working_context))) {
$defaultSourceId = $contextSetting->get('value');
}
$mediasource = modMediaSource::getDefaultSource($this->modx, $defaultSourceId);
return $return == 'object' ? $mediasource : $mediasource->get($return);
}
function generateTvTab($tvnames) {
$tvnames = !empty($tvnames) ? explode(',', $tvnames) : array();
$fields = array();
foreach ($tvnames as $tvname) {
$field['field'] = $tvname;
$field['inputTV'] = $tvname;
$fields[] = $field;
}
return $fields;
}
function checkForConnectedResource($resource_id = false, &$config = []) {
if ($resource_id) {
$check_resid = $this->modx->getOption('check_resid', $config);
if ($check_resid == '@TV' && $resource = $this->modx->getObject('modResource', $resource_id)) {
if ($check = $resource->getTvValue($config['check_resid_TV'])) {
$check_resid = $check;
}
}
if (!empty($check_resid)) {
//$c->where("CONCAT('||',resource_ids,'||') LIKE '%||{$resource_id}||%'", xPDOQuery::SQL_AND);
return true;
}
}
return false;
}
function createForm(&$tabs, &$record, &$allfields, &$categories, $scriptProperties) {
$fieldid = 0;
$config = $this->customconfigs;
$hooksnippets = $this->modx->fromJson($this->modx->getOption('hooksnippets', $config, ''));
if (is_array($hooksnippets)) {
$hooksnippet_beforecreateform = $this->modx->getOption('beforecreateform', $hooksnippets, '');
if (!empty($hooksnippet_beforecreateform)) {
$snippetProperties = array();
$snippetProperties['tabs'] = &$tabs;
$snippetProperties['record'] = &$record;
$snippetProperties['scriptProperties'] = &$scriptProperties;
$result = $this->modx->runSnippet($hooksnippet_beforecreateform, $snippetProperties);
}
}
$input_prefix = $this->modx->getOption('input_prefix', $scriptProperties, '');
$input_prefix = !empty($input_prefix) ? $input_prefix . '_' : '';
$rte = isset($scriptProperties['which_editor']) ? $scriptProperties['which_editor'] : $this->modx->getOption('which_editor', '', $this->modx->_userConfig);
if (!is_array($tabs)) {
return array('error' => 'There seems to be an error in the formtabs-config');
}
foreach ($tabs as $tabid => $tab) {
$layouts = array();
$layoutcolumns = array();
$tvs = array();
$fields = $this->modx->getOption('fields', $tab, array());
$fields = is_array($fields) ? $fields : $this->modx->fromJson($fields);
if (is_array($fields) && count($fields) > 0) {
foreach ($fields as &$field) {
if (isset($field['restrictive_condition'])) {
$props = $record;
$rc = $this->renderChunk($field['restrictive_condition'], $props, false, false);
if (!empty($rc)) {
continue;
}
}
$fieldname = $this->modx->getOption('field', $field, '');
$useDefaultIfEmpty = $this->modx->getOption('useDefaultIfEmpty', $field, 0);
$fieldid++;
/*generate unique tvid, must be numeric*/
/*todo: find a better solution*/
$field['tv_id'] = $input_prefix . $scriptProperties['tv_id'] . '_' . $fieldid;
$params = array();
$tv = false;
if (isset($field['inputTV']) && $tv = $this->modx->getObject('modTemplateVar', array('name' => $field['inputTV']))) {
$params = $tv->get('input_properties');
$params['inputTVid'] = $tv->get('id');
}
if (!empty($field['inputTVtype'])) {
$tv = $this->modx->newObject('modTemplateVar');
$tv->set('type', $field['inputTVtype']);
}
if (!$tv) {
$tv = $this->modx->newObject('modTemplateVar');
$tv->set('type', 'text');
}
$o_type = $tv->get('type');
if ($tv->get('type') == 'richtext') {
$tv->set('type', 'migx' . str_replace(' ', '_', strtolower($rte)));
}
//we change the phptype, that way we can use any id, not only integers (issues on windows-systems with big integers!)
$tv->_fieldMeta['id']['phptype'] = 'string';
/*
$tv->set('id','skdjflskjd');
echo 'id:'. $tv->get('id');
$tv->_fieldMeta['id']['phptype'] = 'string';
echo($tv->_fieldMeta['id']['phptype']);
$tv->set('id','skdjflskjd');
echo 'id:'. $tv->get('id');
*/
if (!empty($field['inputOptionValues'])) {
$tv->set('elements', $field['inputOptionValues']);
}
if (!empty($field['default'])) {
$tv->set('default_text', $tv->processBindings($field['default']));
}
if (isset($field['display'])) {
$tv->set('display', $field['display']);
}
if (!empty($field['configs'])) {
$props = $record;
$cfg_parsed = $this->renderChunk($field['configs'], $props, false, false);
$cfg = json_decode($cfg_parsed, 1);
if (is_array($cfg)) {
$params = array_merge($params, $cfg);
} else {
$params['configs'] = $cfg_parsed;
}
}
/*insert actual value from requested record, convert arrays to ||-delimeted string */
$fieldvalue = '';
if (isset($record[$fieldname])) {
$fieldvalue = $record[$fieldname];
if (is_array($fieldvalue)) {
$fieldvalue = is_array($fieldvalue[0]) ? json_encode($fieldvalue) : implode('||', $fieldvalue);
}
}
$tv->set('value', $fieldvalue);
if (!empty($field['caption'])) {
$field['caption'] = htmlentities($this->replaceLang($field['caption']), ENT_QUOTES, $this->modx->getOption('modx_charset'));
$tv->set('caption', $field['caption']);
}
$desc = '';
if (!empty($field['description'])) {
$desc = $field['description'];
$field['description'] = is_string($desc) ? htmlentities($this->replaceLang($desc), ENT_QUOTES, $this->modx->getOption('modx_charset')) : '';
$tv->set('description', $field['description']);
}
$allfield = array();
$allfield['field'] = $fieldname;
$allfield['tv_id'] = $field['tv_id'];
$allfield['array_tv_id'] = $field['tv_id'] . '[]';
$allfields[] = $allfield;
$field['array_tv_id'] = $field['tv_id'] . '[]';
$mediasource = $this->getFieldSource($field, $tv);
$tv->setSource($mediasource);
$tv->set('id', $field['tv_id']);
/*
$default = $tv->processBindings($tv->get('default_text'), $resourceId);
if (strpos($tv->get('default_text'), '@INHERIT') > -1 && (strcmp($default, $tv->get('value')) == 0 || $tv->get('value') == null)) {
$tv->set('inherited', true);
}
*/
$isnew = $this->modx->getOption('isnew', $scriptProperties, 0);
$isduplicate = $this->modx->getOption('isduplicate', $scriptProperties, 0);
$existingvalue = $tv->get('value');
if (!empty($useDefaultIfEmpty)) {
//old behaviour minus use now default values for checkboxes, if new record
if ($tv->get('value') == null) {
$v = $tv->get('default_text');
if ($tv->get('type') == 'checkbox' && $tv->get('value') == '') {
if (!empty($isnew) && empty($isduplicate)) {
$v = $tv->get('default_text');
} else {
$v = '';
}
}
$tv->set('value', $v);
}
} else {
//set default value, only on new records
if (empty($existingvalue) && !empty($isnew) && empty($isduplicate)) {
$v = $tv->get('default_text');
$tv->set('value', $v);
}
}
$this->modx->smarty->assign('tv', $tv);
/* move this part into a plugin onMediaSourceGetProperties and create a mediaSource - property 'autoCreateFolder'
* may be performancewise its better todo that here?
if (!empty($properties['basePath'])) {
if ($properties['autoResourceFolders'] == 'true') {
$params['basePath'] = $basePath . $scriptProperties['resource_id'] . '/';
$targetDir = $params['basePath'];
$cacheManager = $this->modx->getCacheManager();
// if directory doesnt exist, create it
if (!file_exists($targetDir) || !is_dir($targetDir)) {
if (!$cacheManager->writeTree($targetDir)) {
$this->modx->log(modX::LOG_LEVEL_ERROR, '[MIGX] Could not create directory: ' . $targetDir);
return $this->modx->error->failure('Could not create directory: ' . $targetDir);
}
}
// make sure directory is readable/writable
if (!is_readable($targetDir) || !is_writable($targetDir)) {
$this->modx->log(xPDO::LOG_LEVEL_ERROR, '[MIGX] Could not write to directory: ' . $targetDir);
return $this->modx->error->failure('Could not write to directory: ' . $targetDir);
}
} else {
$params['basePath'] = $basePath;
}
}
*/
if (!isset($params['allowBlank']))
$params['allowBlank'] = 1;
$value = $tv->get('value');
if ($value === null) {
$value = $tv->get('default_text');
}
$this->modx->smarty->assign('params', $params);
/* find the correct renderer for the TV, if not one, render a textbox */
$inputRenderPaths = $tv->getRenderDirectories('OnTVInputRenderList', 'input');
if ($o_type == 'richtext') {
$fallback = true;
foreach ($inputRenderPaths as $path) {
$renderFile = $path . $tv->get('type') . '.class.php';
if (file_exists($renderFile)) {
$fallback = false;
break;
}
}
if ($fallback) {
$tv->set('type', 'textarea');
}
}
$inputForm = $tv->getRender($params, $value, $inputRenderPaths, 'input', null, $tv->get('type'));
/*
//extract scripts from content
$pattern = '#<script(.*?)</script>#is';
preg_match_all($pattern, $inputForm, $matches);
foreach ($matches[0] as $jsvalue) {
$js .= $jsvalue;
}
$inputForm = preg_replace($pattern, '', $inputForm);
*/
if (isset($field['description_is_code']) && !empty($field['description_is_code'])) {
$props = $record;
unset($field['description']);
$tv_array = $tv->toArray();
unset($tv_array['description']);
// don't parse the value - set special placeholder, replace it later
$tv_array['value'] = '[+[+value]]';
$tempvalue = $tv->get('value');
$props['record_json'] = json_encode($props);
$props['tv_json'] = json_encode($tv_array);
$props['field_json'] = json_encode($field);
// don't parse the rendered formElement - set special placeholder, replace it later
$props['tv_formElement'] = '[+[+tv_formElement]]';
$tv->set('formElement', str_replace(array('[+[+value]]', '[+[+tv_formElement]]'), array($tempvalue, $inputForm), $this->renderChunk($desc, $props, false, false)));
$tv->set('type', 'description_is_code');
} else {
if (empty($inputForm))
continue;
$tv->set('formElement', $inputForm);
}
//$tvs[] = $tv;
$layout_id = isset($field['MIGXlayoutid']) ? $field['MIGXlayoutid'] : 0;
$column_id = isset($field['MIGXcolumnid']) ? $field['MIGXcolumnid'] : 0;
$column_width = $this->modx->getOption('MIGXcolumnwidth', $field, '');
$column_minwidth = $this->modx->getOption('MIGXcolumnminwidth', $field, '');
if (empty($column_width)) {
$column_width = '100%';
}
$column_minwidth = empty($column_minwidth) ? '0' : $column_minwidth;
$layouts[$layout_id]['caption'] = $this->modx->getOption('MIGXlayoutcaption', $field, '');
$layouts[$layout_id]['style'] = $this->modx->getOption('MIGXlayoutstyle', $field, '');
$layouts[$layout_id]['columns'][$column_id]['tvs'][] = $tv;
$layouts[$layout_id]['columns'][$column_id]['width'] = $column_width;
$layouts[$layout_id]['columns'][$column_id]['minwidth'] = $column_minwidth;
$layouts[$layout_id]['columns'][$column_id]['style'] = $this->modx->getOption('MIGXcolumnstyle', $field, '');
$layouts[$layout_id]['columns'][$column_id]['caption'] = $this->modx->getOption('MIGXcolumncaption', $field, '');
}
}
//echo '<pre>' . print_r($layouts,1) . '</pre>';
//$layoutcolumn = array();
//$layoutcolumn['tvs'] = $tvs;
//$layoutcolumns[] = $layoutcolumn;
//$layout = array();
//$layout['columns'] = $layoutcolumns;
//$layouts[] = $layout;
$cat = array();
$cat['category'] = $this->modx->getOption('caption', $tab, 'undefined');
$cat['print_before_tabs'] = isset($tab['print_before_tabs']) && !empty($tab['print_before_tabs']) ? true : false;
$cat['id'] = $tabid;
$cat['layouts'] = $layouts;
//$cat['tvs'] = $tvs;
$categories[] = $cat;
}
}
function extractFieldsFromTabs($formtabs, $onlyTvTypes = false) {
//multiple different Forms
// Note: use same field-names and inputTVs in all forms
if (is_array($formtabs) && isset($formtabs[0]['formtabs'])) {
$forms = $formtabs;
$formtabs = array();
foreach ($forms as $form) {
foreach ($form['formtabs'] as $tab) {
$tab['formname'] = $form['formname'];
$formtabs[] = $tab;
}
}
}
$inputTvs = array();
if (is_array($formtabs)) {
foreach ($formtabs as $tabidx => $tab) {
$formname = isset($tab['formname']) && !empty($tab['formname']) ? $tab['formname'] . '_' : '';
if (isset($tab['fields'])) {
$fields = is_array($tab['fields']) ? $tab['fields'] : $this->modx->fromJson($tab['fields']);
if (is_array($fields)) {
foreach ($fields as $field) {
//$fieldkey = $formname.$field['field'];
if (isset($field['inputTV']) && !empty($field['inputTV'])) {
$inputTvs[$field['field']] = $field;
//for different inputTvs, for example with different mediasources, in multiple forms, currently not used for the grid
$inputTvs[$formname . $field['field']] = $field;
} elseif (isset($field['inputTVtype']) && !empty($field['inputTVtype'])) {
$inputTvs[$field['field']] = $field;
$inputTvs[$formname . $field['field']] = $field;
} elseif (!$onlyTvTypes) {
$inputTvs[$field['field']] = $field;
$inputTvs[$formname . $field['field']] = $field;
}
}
}
}
}
}
return $inputTvs;
}
function extractInputTvs($formtabs) {
return $this->extractFieldsFromTabs($formtabs, true);
}
function parseChunk($tpl, $fields = array(), $getChunk = true, $printIfemty = true) {
$output = '';
if ($getChunk) {
if ($chunk = $this->modx->getObject('modChunk', array('name' => $tpl), true)) {
$tpl = $chunk->getContent();
} elseif (file_exists($tpl)) {
$tpl = file_get_contents($tpl);
} elseif (file_exists($this->modx->getOption('base_path') . $tpl)) {
$tpl = file_get_contents($this->modx->getOption('base_path') . $tpl);
} else {
$tpl = false;
}
}
if ($tpl) {
$chunk = $this->modx->newObject('modChunk');
$chunk->setCacheable(false);
$chunk->setContent($tpl);
$output = $chunk->process($fields);
} elseif ($printIfemty) {
$output = '<pre>' . print_r($fields, 1) . '</pre>';
}
return $output;
}
function sortTV($sort, &$c, $dir = 'ASC', $sortbyTVType = '') {
$c->leftJoin('modTemplateVar', 'tvDefault', array("tvDefault.name" => $sort));
$c->leftJoin('modTemplateVarResource', 'tvSort', array("tvSort.contentid = modResource.id", "tvSort.tmplvarid = tvDefault.id"));
if (empty($sortbyTVType))
$sortbyTVType = 'string';
if ($this->modx->getOption('dbtype') === 'mysql') {
switch ($sortbyTVType) {
case 'integer':
$c->select("CAST(IFNULL(tvSort.value, tvDefault.default_text) AS SIGNED INTEGER) AS sortTV");
break;
case 'decimal':
$c->select("CAST(IFNULL(tvSort.value, tvDefault.default_text) AS DECIMAL) AS sortTV");
break;
case 'datetime':
$c->select("CAST(IFNULL(tvSort.value, tvDefault.default_text) AS DATETIME) AS sortTV");
break;
case 'string':
default:
$c->select("IFNULL(tvSort.value, tvDefault.default_text) AS sortTV");
break;
}
}
$c->sortby("sortTV", $dir);
return true;
}
function tvFilters($tvFilters = '', &$criteria = null) {
//tvFilter::categories=inArray=[[+category]]
$tvFilters = !empty($tvFilters) ? explode('||', $tvFilters) : array();
if (!empty($tvFilters)) {
$tmplVarTbl = $this->modx->getTableName('modTemplateVar');
$tmplVarResourceTbl = $this->modx->getTableName('modTemplateVarResource');
$conditions = array();
$operators = array(
'<=>' => '<=>',
'===' => '=',
'!==' => '!=',
'<>' => '<>',
'==' => 'LIKE',
'!=' => 'NOT LIKE',
'<<' => '<',
'<=' => '<=',
'=<' => '=<',
'>>' => '>',
'>=' => '>=',
'=>' => '=>',
'=inArray=' => '=inArray=');
foreach ($tvFilters as $fGroup => $tvFilter) {
$filterGroup = array();
$filters = explode(',', $tvFilter);
$multiple = count($filters) > 0;
foreach ($filters as $filter) {
$operator = '==';
$sqlOperator = 'LIKE';
foreach ($operators as $op => $opSymbol) {
if (strpos($filter, $op, 1) !== false) {
$operator = $op;
$sqlOperator = $opSymbol;
break;
}
}
$tvValueField = 'tvr.value';
$tvDefaultField = 'tv.default_text';
$f = explode($operator, $filter);
if (count($f) == 2) {
$tvName = $this->modx->quote($f[0]);
if (is_numeric($f[1]) && !in_array($sqlOperator, array('LIKE', 'NOT LIKE'))) {
$tvValue = $f[1];
if ($f[1] == (integer)$f[1]) {
$tvValueField = "CAST({$tvValueField} AS SIGNED INTEGER)";
$tvDefaultField = "CAST({$tvDefaultField} AS SIGNED INTEGER)";
} else {
$tvValueField = "CAST({$tvValueField} AS DECIMAL)";
$tvDefaultField = "CAST({$tvDefaultField} AS DECIMAL)";
}
} elseif ($sqlOperator == '=inArray=') {
$sqlOperator = 'LIKE';
$tvValueField = "CONCAT('||',{$tvValueField},'||')";
$tvDefaultField = "CONCAT('||',{$tvDefaultField},'||')";
$tvValue = $this->modx->quote('%||' . $f[1] . '||%');
} else {
$tvValue = $this->modx->quote($f[1]);
}
if ($multiple) {
$filterGroup[] = "(EXISTS (SELECT 1 FROM {$tmplVarResourceTbl} tvr JOIN {$tmplVarTbl} tv ON {$tvValueField} {$sqlOperator} {$tvValue} AND tv.name = {$tvName} AND tv.id = tvr.tmplvarid WHERE tvr.contentid = modResource.id) " . "OR EXISTS (SELECT 1 FROM {$tmplVarTbl} tv WHERE tv.name = {$tvName} AND {$tvDefaultField} {$sqlOperator} {$tvValue} AND tv.id NOT IN (SELECT tmplvarid FROM {$tmplVarResourceTbl} WHERE contentid = modResource.id)) " . ")";
} else {
$filterGroup = "(EXISTS (SELECT 1 FROM {$tmplVarResourceTbl} tvr JOIN {$tmplVarTbl} tv ON {$tvValueField} {$sqlOperator} {$tvValue} AND tv.name = {$tvName} AND tv.id = tvr.tmplvarid WHERE tvr.contentid = modResource.id) " . "OR EXISTS (SELECT 1 FROM {$tmplVarTbl} tv WHERE tv.name = {$tvName} AND {$tvDefaultField} {$sqlOperator} {$tvValue} AND tv.id NOT IN (SELECT tmplvarid FROM {$tmplVarResourceTbl} WHERE contentid = modResource.id)) " . ")";
}
} elseif (count($f) == 1) {
$tvValue = $this->modx->quote($f[0]);
if ($multiple) {
$filterGroup[] = "EXISTS (SELECT 1 FROM {$tmplVarResourceTbl} tvr JOIN {$tmplVarTbl} tv ON {$tvValueField} {$sqlOperator} {$tvValue} AND tv.id = tvr.tmplvarid WHERE tvr.contentid = modResource.id)";
} else {
$filterGroup = "EXISTS (SELECT 1 FROM {$tmplVarResourceTbl} tvr JOIN {$tmplVarTbl} tv ON {$tvValueField} {$sqlOperator} {$tvValue} AND tv.id = tvr.tmplvarid WHERE tvr.contentid = modResource.id)";
}
}
}
$conditions[] = $filterGroup;
}
if (!empty($conditions)) {
$firstGroup = true;
foreach ($conditions as $cGroup => $c) {
if (is_array($c)) {
$first = true;
foreach ($c as $cond) {
if ($first && !$firstGroup) {
$criteria->condition($criteria->query['where'][0][1], $cond, xPDOQuery::SQL_OR, null, $cGroup);
} else {
$criteria->condition($criteria->query['where'][0][1], $cond, xPDOQuery::SQL_AND, null, $cGroup);
}
$first = false;
}
} else {
$criteria->condition($criteria->query['where'][0][1], $c, $firstGroup ? xPDOQuery::SQL_AND : xPDOQuery::SQL_OR, null, $cGroup);
}
$firstGroup = false;
}
}
return true;
}
}
public function debug($key, $value, $reset = false) {
$debug[$key] = $value;
$chunk = $this->modx->getObject('modChunk', array('name' => 'debug'));
$oldContent = $reset ? '' : $chunk->getContent();
$chunk->setContent($oldContent . print_r($debug, 1));
$chunk->save();
}
function filterItems($where, $items) {
$tempitems = array();
foreach ($items as $item) {
$include = true;
foreach ($where as $key => $operand) {
$key = explode(':', $key);
$field = $key[0];
$then = $include;
$else = false;
$subject = $item[$field];
$operator = isset($key[1]) ? $key[1] : '=';
$params = isset($key[2]) ? $key[2] : '';
$operator = strtolower($operator);
switch ($operator) {
case '!=':
case 'neq':
case 'not':
case 'isnot':
case 'isnt':
case 'unequal':
case 'notequal':
$output = (($subject != $operand) ? $then : (isset($else) ? $else : ''));
break;
case '<':
case 'lt':
case 'less':
case 'lessthan':
$output = (($subject < $operand) ? $then : (isset($else) ? $else : ''));
break;
case '>':
case 'gt':
case 'greater':
case 'greaterthan':
$output = (($subject > $operand) ? $then : (isset($else) ? $else : ''));
break;
case '<=':
case 'lte':
case 'lessthanequals':
case 'lessthanorequalto':
$output = (($subject <= $operand) ? $then : (isset($else) ? $else : ''));
break;
case '>=':
case 'gte':
case 'greaterthanequals':
case 'greaterthanequalto':
$output = (($subject >= $operand) ? $then : (isset($else) ? $else : ''));
break;
case 'isempty':
case 'empty':
$output = empty($subject) ? $then : (isset($else) ? $else : '');
break;
case '!empty':
case 'notempty':
case 'isnotempty':
$output = !empty($subject) && $subject != '' ? $then : (isset($else) ? $else : '');
break;
case 'isnull':
case 'null':
$output = $subject == null || strtolower($subject) == 'null' ? $then : (isset($else) ? $else : '');
break;
case 'inarray':
case 'in_array':
case 'ia':
case 'in':
$operand = is_array($operand) ? $operand : explode(',', $operand);
$output = in_array($subject, $operand) ? $then : (isset($else) ? $else : '');
break;
case 'find':
case 'find_in_set':
$subject = is_array($subject) ? $subject : explode(',', $subject);
$output = in_array($operand, $subject) ? $then : (isset($else) ? $else : '');
break;
case 'find_pd':
case 'find_in_pipesdelimited_set':
$subject = explode('||', $subject);
$output = in_array($operand, $subject) ? $then : (isset($else) ? $else : '');
break;
case 'contains':
$output = strpos($subject, $operand) !== false ? $then : (isset($else) ? $else : '');
break;
case 'snippet':
$result = $this->modx->runSnippet($params, array('subject' => $subject, 'operand' => $operand));
$output = !empty($result) ? $then : (isset($else) ? $else : '');
break;
case '==':
case '=':
case 'eq':
case 'is':
case 'equal':
case 'equals':
case 'equalto':
default:
$output = (($subject == $operand) ? $then : (isset($else) ? $else : ''));
break;
}
$include = $output ? $output : false;
}
if ($include) {
$tempitems[] = $item;
}
}
return $tempitems;
}
/**
* Sort DB result
*
* @param array $data Result of sql query as associative array
*
* @param array $options Sortoptions as array
*
*
* <code>
*
* // You can sort data by several columns e.g.
* $data = array();
* for ($i = 1; $i <= 10; $i++) {
* $data[] = array( 'id' => $i,
* 'first_name' => sprintf('first_name_%s', rand(1, 9)),
* 'last_name' => sprintf('last_name_%s', rand(1, 9)),
* 'date' => date('Y-m-d', rand(0, time()))
* );
* }
*
* $options = array(array('sortby'=>'date','sortdir'=>'DESC','sortmode'=>'numeric'));
* $data = sortDbResult($data, $options);
* printf('<pre>%s</pre>', print_r($data, true));
*
* $options = array(array('sortby'=>'last_name','sortdir'=>'ASC','sortmode'=>'string'),array('sortby'=>'first_name','sortdir'=>'ASC','sortmode'=>'string'));
* $data = sortDbResult($data, $options);
* printf('<pre>%s</pre>', print_r($data, true));
*
* </code>
*
* @return array $data - Sorted data
*/
function sortDbResult($_data, $options = array()) {
$sortmodes = array();
$sortmodes['numeric'] = SORT_NUMERIC;
$sortmodes['string'] = SORT_STRING;
$sortmodes['regular'] = SORT_REGULAR;
$sortdirs = array();
$sortdirs['ASC'] = SORT_ASC;
$sortdirs['DESC'] = SORT_DESC;
$_rules = array();
if (count($options) > 0) {
foreach ($options as $option) {
$rule['name'] = isset($option['sortby']) ? (string )$option['sortby'] : '';
if (empty($rule['name']) || (is_array(current($_data)) && !in_array($rule['name'], array_keys(current($_data))))) {
continue;
}
$rule['order'] = isset($option['sortdir']) && isset($sortdirs[$option['sortdir']]) ? $sortdirs[$option['sortdir']] : $sortdirs['ASC'];
$rule['mode'] = isset($option['sortmode']) && isset($sortmodes[$option['sortmode']]) ? $sortmodes[$option['sortmode']] : $sortmodes['regular'];
$_rules[] = $rule;
}
}
$_cols = array();
foreach ($_data as $_k => $_row) {
foreach ($_rules as $_rule) {
if (!isset($_cols[$_rule['name']])) {
$_cols[$_rule['name']] = array();
$_params[] = &$_cols[$_rule['name']];
$_params[] = $_rule['order'];
$_params[] = $_rule['mode'];
}
$_cols[$_rule['name']][$_k] = $_row[$_rule['name']];
}
}
$_params[] = &$_data;
call_user_func_array('array_multisort', $_params);
return $_data;
}
public function prepareJoins($classname, $joins, &$c) {
$selectcolumns = array();
if (is_array($joins)) {
foreach ($joins as $join) {
$jalias = $this->modx->getOption('alias', $join, '');
$type = $this->modx->getOption('type', $join, 'left');
$joinclass = $this->modx->getOption('classname', $join, '');
$selectfields = $this->modx->getOption('selectfields', $join, '');
$on = $this->modx->getOption('on', $join, null);
if (!empty($jalias)) {
if (empty($joinclass) && $fkMeta = $c->xpdo->getFKDefinition($classname, $jalias)) {
$joinclass = $fkMeta['class'];
}
if (!empty($joinclass)) {
/*
if ($joinFkMeta = $modx->getFKDefinition($joinclass, 'Resource')){
$localkey = $joinFkMeta['local'];
}
*/
$selectfields = !empty($selectfields) ? explode(',', $selectfields) : null;
switch ($type) {
case 'left':
$c->leftjoin($joinclass, $jalias, $on);
break;
case 'right':
$c->rightjoin($joinclass, $jalias, $on);
break;
case 'inner':
$c->innerjoin($joinclass, $jalias, $on);
break;
default:
$c->leftjoin($joinclass, $jalias, $on);
break;
}
if ($object = $c->xpdo->newObject($joinclass)) {
$columns = $object->toArray($jalias . '_');
$selectcolumns = array_merge($selectcolumns, $columns);
$c->select($c->xpdo->getSelectColumns($joinclass, $jalias, $jalias . '_', $selectfields));
}
}
}
}
}
return $selectcolumns;
}
public function addRelatedLinkIds(&$object, &$record, $config) {
$modx = &$this->modx;
$xpdo = &$object->xpdo;
$link_classname = $modx->getOption('link_classname', $config, '');
$link_alias = $modx->getOption('link_alias', $config, '');
$postfield = $modx->getOption('postfield', $config, '');
$id_field = $modx->getOption('id_field', $config, '');
$link_field = $modx->getOption('link_field', $config, '');
$ids = array();
if ($collection = $object->getMany($link_alias)) {
foreach ($collection as $link_object) {
$ids[] = $link_object->get($link_field);
//print_r($object->toArray());
}
}
$record[$postfield] = implode('||', $ids);
}
public function handleRelatedLinks(&$object, $postvalues, $config = array()) {
$modx = &$this->modx;
$xpdo = &$object->xpdo;
$link_classname = $modx->getOption('link_classname', $config, '');
$link_alias = $modx->getOption('link_alias', $config, '');
$postfield = $modx->getOption('postfield', $config, '');
$id_field = $modx->getOption('id_field', $config, '');
$link_field = $modx->getOption('link_field', $config, '');
$attributes = explode('||', $modx->getOption($postfield, $postvalues, ''));
$old_attributes = array();
if ($attr_collection = $object->getMany($link_alias)) {
foreach ($attr_collection as $attr_o) {
$old_attributes[$attr_o->get($link_field)] = $attr_o;
}
}
foreach ($attributes as $attribute) {
if (!empty($attribute)) {
if (isset($old_attributes[$attribute])) {
unset($old_attributes[$attribute]);
} else {
$attr_o = $xpdo->newObject($link_classname);
$attr_o->set($link_field, $attribute);
$attr_o->set($id_field, $object->get('id'));
$attr_o->save();
}
}
}
foreach ($old_attributes as $attr_o) {
$attr_o->remove();
}
}
public function handleRelatedLinksFromMIGX(&$object, $postvalues, $config) {
$modx = &$this->modx;
$xpdo = &$object->xpdo;
$link_classname = $modx->getOption('link_classname', $config, '');
$link_alias = $modx->getOption('link_alias', $config, '');
$postfield = $modx->getOption('postfield', $config, '');
$id_field = $modx->getOption('id_field', $config, '');
$link_field = $modx->getOption('link_field', $config, '');
$pos_field = $modx->getOption('pos_field', $config, 'pos');
$resave_object = $modx->getOption('resave_object', $config, 0);
$extrafields = explode(',', $modx->getOption('extrafields', $config, ''));
$products = $modx->fromJson($modx->getOption($postfield, $postvalues, ''));
$old_products = array();
if ($product_collection = $object->getMany($link_alias)) {
foreach ($product_collection as $product_o) {
$old_products[$product_o->get('id')] = $product_o;
}
}
$pos = 1;
$new_products = array();
foreach ($products as $product) {
$product_id = $modx->getOption($link_field, $product, '');
$migx_id = $modx->getOption('MIGX_id', $product, '');
$id = $modx->getOption('id', $product, 'new');
if (!empty($product_id)) {
if (isset($old_products[$id])) {
$product_o = $old_products[$id];
unset($old_products[$id]);
} else {
$product_o = $xpdo->newObject($link_classname);
}
$product_o->set($pos_field, $pos);
foreach ($extrafields as $extrafield) {
$value = $modx->getOption($extrafield, $product, '');
$product_o->set($extrafield, $value);
}
$product_o->set($link_field, $product_id);
$product_o->set($id_field, $object->get('id'));
$product_o->save();
$new_product = $product_o->toArray();
$new_product['MIGX_id'] = $migx_id;
$new_products[] = $new_product;
$pos++;
}
}
//save cleaned json
$object->set($postfield, json_encode($new_products));
if (!empty($resave_object)) {
$object->save();
}
foreach ($old_products as $product_o) {
$product_o->remove();
}
}
public function handleTranslations(&$object, $postvalues, $config) {
$modx = &$this->modx;
$xpdo = &$object->xpdo;
$link_classname = $modx->getOption('link_classname', $config, '');
$link_alias = $modx->getOption('link_alias', $config, 'Translations');
$postfield = $modx->getOption('postfield', $config, '');
$id_field = $modx->getOption('id_field', $config, '');
$link_field = $modx->getOption('link_field', $config, 'iso_code');
$languages = $modx->getOption('languages', $config, array());
$old_translations = array();
if ($trans_collection = $object->getMany($link_alias)) {
foreach ($trans_collection as $trans_o) {
$old_translations[$trans_o->get($link_field)] = $trans_o;
}
}
foreach ($languages as $language) {
$iso_code = $modx->getOption($link_field, $language, '');
if (!empty($iso_code)) {
if (isset($old_translations[$iso_code])) {
$trans_o = $old_translations[$iso_code];
unset($old_translations[$iso_code]);
} else {
$trans_o = $xpdo->newObject($link_classname);
$trans_o->set($link_field, $iso_code);
$trans_o->set($id_field, $object->get('id'));
}
foreach ($postvalues as $field => $value) {
$fieldparts = explode('_', $field);
$fieldparts = array_reverse($fieldparts);
if ($fieldparts[0] == $iso_code) {
$fieldname = str_replace('_' . $iso_code, '', $field);
$trans_o->set($fieldname, $value);
}
}
$trans_o->save();
}
}
foreach ($old_translations as $trans_o) {
$trans_o->remove();
}
}
public function handleOrderPositions(&$xpdo, $config, $scriptProperties) {
$modx = &$this->modx;
$classname = $config['classname'];
$checkdeleted = isset($config['gridactionbuttons']['toggletrash']['active']) && !empty($config['gridactionbuttons']['toggletrash']['active']) ? true : false;
$newpos_id = $modx->getOption('new_pos_id', $scriptProperties, 0);
$col = $modx->getOption('col', $scriptProperties, '');
$object_id = $modx->getOption('object_id', $scriptProperties, 0);
$showtrash = $modx->getOption('showtrash', $scriptProperties, '');
$resource_id = $modx->getOption('co_id', $scriptProperties, is_object($modx->resource) ? $modx->resource->get('id') : false);
$col = explode(':', $col);
if (!empty($newpos_id) && !empty($object_id) && count($col) > 1) {
$workingobject = $xpdo->getObject($classname, $object_id);
$posfield = $col[0];
$position = $col[1];
$joinalias = isset($config['join_alias']) ? $config['join_alias'] : '';
if (!empty($joinalias)) {
if ($fkMeta = $xpdo->getFKDefinition($classname, $joinalias)) {
$joinclass = $fkMeta['class'];
$joinfield = $fkMeta[$fkMeta['owner']];
} else {
$joinalias = '';
}
}
//$parent = $workingobject->get('parent');
$c = $xpdo->newQuery($classname);
//$c->where(array('deleted'=>0 , 'parent'=>$parent));
$c->select($xpdo->getSelectColumns($classname, $classname));
if (!empty($joinalias)) {
/*
if ($joinFkMeta = $modx->getFKDefinition($joinclass, 'Resource')){
$localkey = $joinFkMeta['local'];
}
*/
$c->leftjoin($joinclass, $joinalias);
$c->select($xpdo->getSelectColumns($joinclass, $joinalias, 'Joined_'));
}
if ($this->checkForConnectedResource($resource_id, $config)) {
if (!empty($joinalias)) {
$c->where(array($joinalias . '.' . $joinfield => $resource_id));
} else {
$c->where(array($classname . '.resource_id' => $resource_id));
}
}
if ($checkdeleted) {
if (!empty($showtrash)) {
$c->where(array($classname . '.deleted' => '1'));
} else {
$c->where(array($classname . '.deleted' => '0'));
}
}
$c->sortby($posfield);
//$c->sortby('name');
if ($collection = $xpdo->getCollection($classname, $c)) {
$curpos = 1;
foreach ($collection as $object) {
$id = $object->get('id');
if ($id == $newpos_id && $position == 'before') {
$workingobject->set($posfield, $curpos);
$workingobject->save();
$curpos++;
}
if ($id != $object_id) {
$object->set($posfield, $curpos);
$object->save();
$curpos++;
}
if ($id == $newpos_id && $position == 'after') {
$workingobject->set($posfield, $curpos);
$workingobject->save();
$curpos++;
}
}
}
}
}
public function getTemplate($rowtpl, $template = array()) {
if (!isset($template[$rowtpl])) {
if (substr($rowtpl, 0, 6) == "@FILE:") {
$template[$rowtpl] = file_get_contents($this->modx->config['base_path'] . substr($rowtpl, 6));
} elseif (substr($rowtpl, 0, 6) == "@CODE:") {
$template[$rowtpl] = str_replace(array('{{', '}}'), array('[[', ']]'), substr($rowtpl, 6));
} elseif ($chunk = $this->modx->getObject('modChunk', array('name' => $rowtpl), true)) {
$template[$rowtpl] = $chunk->getContent();
} else {
$template[$rowtpl] = false;
}
}
return $template;
}
public function addConnectorParams($properties, $unset = '') {
global $modx;
$properties['connectorUrl'] = $this->config['connectorUrl'];
$params = array();
$unset = explode(',', $unset);
$req = $_REQUEST;
foreach ($unset as $param) {
unset($req[$param]);
}
foreach ($req as $key => $value) {
$params[] = $key . '=' . $value;
}
$properties['urlparams'] = implode('&', $params);
return $properties;
}
public function getDivisors($integer) {
$divisors = array();
for ($i = $integer; $i > 1; $i--) {
if (($integer % $i) === 0) {
$divisors[] = $i;
}
}
return $divisors;
}
public function is_modx3(){
$result = false;
$versionData = [];
if (method_exists($this->modx,'getVersionData')){
$versionData = $this->modx->getVersionData();
}
if (isset($versionData['version']) && (int) $versionData['version'] >= 3){
$result = true;
}
return $result;
}
function importconfig($array) {
$excludekeys_ifarray = array(
'getlistwhere',
'hooksnippets',
'joins',
'configs');
$array = $this->recursive_encode($array, $excludekeys_ifarray);
return $array;
}
function recursive_encode($array, $excludekeys_ifarray = array()) {
if (is_array($array)) {
foreach ($array as $key => $value) {
if (!is_int($key) && is_array($value) && in_array($key, $excludekeys_ifarray)) {
$array[$key] = !empty($value) ? json_encode($value) : $value;
//$array[$key] = $this->recursive_encode($value, $excludekeys);
} else {
$array[$key] = $this->recursive_encode($value, $excludekeys_ifarray);
}
}
if (!$this->is_assoc($array)) {
$array = json_encode($array);
}
}
return $array;
}
function is_assoc($array) {
return (bool)count(array_filter(array_keys($array), 'is_string'));
}
function recursive_decode($array) {
foreach ($array as $key => $value) {
if (is_string($value) && $decoded = json_decode($value, true)) {
$array[$key] = $this->recursive_decode($decoded);
} else {
$array[$key] = $this->recursive_decode($value);
}
}
return $array;
}
/**
* Indents a flat JSON string to make it more human-readable.
* Source: http://recursive-design.com/blog/2008/03/11/format-json-with-php/
*
* @param string $json The original JSON string to process.
*
* @return string Indented version of the original JSON string.
*/
function indent($json) {
$result = '';
$pos = 0;
$strLen = strlen($json);
$indentStr = ' ';
$newLine = "\n";
$prevChar = '';
$outOfQuotes = true;
for ($i = 0; $i <= $strLen; $i++) {
// Grab the next character in the string.
$char = substr($json, $i, 1);
// Are we inside a quoted string?
if ($char == '"' && $prevChar != '\\') {
$outOfQuotes = !$outOfQuotes;
// If this character is the end of an element,
// output a new line and indent the next line.
} else
if (($char == '}' || $char == ']') && $outOfQuotes) {
$result .= $newLine;
$pos--;
for ($j = 0; $j < $pos; $j++) {
$result .= $indentStr;
}
}
// Add the character to the result string.
$result .= $char;
// If the last character was the beginning of an element,
// output a new line and indent the next line.
if (($char == ',' || $char == '{' || $char == '[') && $outOfQuotes) {
$result .= $newLine;
if ($char == '{' || $char == '[') {
$pos++;
}
for ($j = 0; $j < $pos; $j++) {
$result .= $indentStr;
}
}
$prevChar = $char;
}
return $result;
}
}
| true |
14cd0efb591c78ffc9d9b191796e1a16ff703c4e | PHP | josegranado/BlogProgramacionll | /models/Categorie.php | UTF-8 | 2,040 | 3.078125 | 3 | [] | no_license | <?php
require_once(dirname(dirname(__FILE__)).'/database.php');
class Categorie
{
public static function all($conn)
{
try
{
$categories = $conn->prepare("SELECT * FROM categorias");
$categories->execute();
$results = $categories->fetchAll();
return $results;
}
catch( PDOException $e)
{
die('Connection Failed: ' . $e->getMessage());
}
}
public static function create($categorie, $conn)
{
try
{
$created = $conn->prepare("INSERT INTO categorias (nombre, description) VALUES (:nombre, :description )");
$created->bindParam(':nombre', $categorie['nombre']);
$created->bindParam(':description', $categorie['description']);
return $created->execute();
}
catch( PDOException $e)
{
die('Connection Failed: ' . $e->getMessage());
}
}
public static function find($id, $conn)
{
try
{
$records = $conn->prepare('SELECT * FROM categorias WHERE id = :id');
$records->bindParam(':id', $id);
$records->execute();
$results = $records->fetch(PDO::FETCH_ASSOC);
return $results;
}
catch(PDOException $e)
{
die('Connection FAiled: '. $e->getMessage());
}
}
public static function update($categorie, $id, $conn)
{
try
{
$updated = $conn->prepare('UPDATE categorias SET
nombre = :nombre,
description = :description
WHERE id = :id
');
$updated->bindParam(':id', $id);
$updated->bindParam(':nombre', $categorie['nombre']);
$updated->bindParam(':description', $categorie['description']);
return $updated->execute();
}
catch( PDOEXception $e)
{
die('Connection FAiled: '. $e->getMessage());
}
}
public static function delete($id, $conn)
{
try
{
$deleted = $conn->prepare('DELETE FROM categorias WHERE id = :id');
$deleted->bindParam(':id', $id);
return $deleted->execute();
}
catch(PDOException $e)
{
die('Connection failed'. $e->getMessage());
}
}
} | true |
a27f4abc80845f1f26cf6b9ca269777eaca8ede3 | PHP | samroy92/CST336-Final | /week2/assignment2.php | UTF-8 | 3,040 | 3.484375 | 3 | [] | no_license | <!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" href="assignment2.css" type="text/css">
<title>Week 2 - Assignment</title>
</head>
<body>
<div id="mainwrapper">
<h1>Week 2 - Assignment</h1>
<h3><center>Prime numbers pattern recognition</center></h3>
<div id="subdiv-main">
<h5>Try to find a pattern as to why prime numbers end in certain digits. Is there a coorelation? If we calculated infinite primes would they end with the same frequency of digits? Each box of color represents a prime number, and each color represents the same last digit. Take a look: </h5>
<?php
$prime = 1;
$one = 0;
$two = 0;
$three = 0;
$four = 0;
$five = 0;
$six = 0;
$seven = 0;
$eight = 0;
$nine = 0;
$cols = 60;
echo "<small>";
echo "<table border=\"0\">";
for ($i = 0; $i < 150; $i++)
{
echo "<tr>";
for ($j = 0; $j < $cols; $j++)
{
$nextprime = gmp_nextprime($prime);
$primearray = str_split(gmp_strval($prime));
$primedigits = strlen(gmp_strval($prime));
$num = $primearray[$primedigits - 1];
switch($num)
{
case 1:
echo "<td class='one'>";
$one+=1;
echo gmp_strval($prime);
echo "</td>";
break;
case 2:
echo "<td>";
$two+=1;
echo gmp_strval($prime);
echo "</td>";
break;
case 3:
echo "<td class='three'>";
$three+=1;
echo gmp_strval($prime);
echo "</td>";
break;
case 4:
echo "<td>";
$four+=1;
echo gmp_strval($prime);
echo ", ";
echo "</td>";
break;
case 5:
echo "<td>";
$five+=1;
echo gmp_strval($prime);
echo "</td>";
break;
case 6:
echo "<td>";
$six+=1;
echo gmp_strval($prime);
echo "</td>";
break;
case 7:
echo "<td class='seven'>";
$seven+=1;
echo gmp_strval($prime);
echo "</td>";
break;
case 8:
echo "<td>";
$eight+=1;
echo gmp_strval($prime);
echo "</td>";
break;
case 9:
echo "<td class='nine'>";
$nine+=1;
echo gmp_strval($prime);
echo "</td>";
break;
default:
echo "</td>";
break;
}
$prime = $nextprime;
}
echo "</tr>";
}
echo "</table>";
echo "</small>";
echo "</div>";
echo "<div id=\"subdiv-alt\">";
echo "<p>";
echo "$one primes ended in 1.";
echo "<br>";
echo "$two primes ended in 2.";
echo "<br>";
echo "$three primes ended in 3.";
echo "<br>";
echo "$four primes ended in 4.";
echo "<br>";
echo "$five primes ended in 5.";
echo "<br>";
echo "$six primes ended in 6.";
echo "<br>";
echo "$seven primes ended in 7.";
echo "<br>";
echo "$eight primes ended in 8.";
echo "<br>";
echo "$nine primes ended in 9.";
echo "</div>";
?>
</div>
</body>
</html> | true |
6fbc89a7d93a556293633fa335d1aa045f02199c | PHP | demaciageelun/weqin | /后端/models/OrderCommentsTemplates.php | UTF-8 | 1,577 | 2.625 | 3 | [] | no_license | <?php
namespace app\models;
use Yii;
/**
* This is the model class for table "{{%order_comments_templates}}".
*
* @property int $id
* @property int $mall_id
* @property int $mch_id
* @property int $type 模板类型:1.好评|2.中评|3.差评
* @property string $title 标题
* @property string $content 内容
* @property string $created_at
* @property string $updated_at
* @property string $deleted_at
* @property int $is_delete
*/
class OrderCommentsTemplates extends ModelActiveRecord
{
/**
* {@inheritdoc}
*/
public static function tableName()
{
return '{{%order_comments_templates}}';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['mall_id', 'created_at', 'updated_at', 'deleted_at'], 'required'],
[['mall_id', 'mch_id', 'type', 'is_delete'], 'integer'],
[['created_at', 'updated_at', 'deleted_at'], 'safe'],
[['title'], 'string', 'max' => 65],
[['content'], 'string', 'max' => 255],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'mall_id' => 'Mall ID',
'mch_id' => 'Mch ID',
'type' => '模板类型:1.好评|2.中评|3.差评',
'title' => '标题',
'content' => '内容',
'created_at' => 'Created At',
'updated_at' => 'Updated At',
'deleted_at' => 'Deleted At',
'is_delete' => 'Is Delete',
];
}
}
| true |
e30a29005adef48d0aa0af25bea018d881101c9f | PHP | udamuri/lado | /frontend/models/NodeForm.php | UTF-8 | 3,039 | 2.515625 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
namespace frontend\models;
use Yii;
use yii\base\Model;
use yii\data\Pagination;
use frontend\models\TablePost;
use frontend\models\TableCategory;
use app\components\Constants;
/**
* Page form
*/
class NodeForm extends Model
{
public $slug = '';
public function checkSlug()
{
$arrPage = [];
$urlAlias = TablePost::findOne(['post_url_alias'=>$this->slug]);
if($urlAlias AND count($urlAlias) > 0) {
$arrPage = [
'id' => $urlAlias['post_id'],
'title' => $urlAlias['post_title'],
'type' => 'page',
'alias' => $urlAlias['post_url_alias'],
'date' => $urlAlias['post_date'],
'modified' => $urlAlias['post_modified'],
'excerpt' => $urlAlias['post_excerpt'],
'data' => $urlAlias['post_content']
];
return $arrPage;
} else {
$urlAlias = TableCategory::findOne(['category_name'=>$this->slug]);
if($urlAlias AND count($urlAlias) > 0) {
$arrPage = [
'id' => $urlAlias['category_id'],
'title' => $urlAlias['category_name'],
'type' => 'post',
'alias' => $urlAlias['category_name'],
'date' => $urlAlias['category_date'],
'modified' => $urlAlias['category_date'],
'excerpt' => '',
'data' => $this->post($urlAlias['category_id'])
];
return $arrPage;
}
return false;
}
return false;
}
private function post($_cid = 0, $_search = '')
{
$search = $_search;
$query = (new \yii\db\Query())
->select([
'tp.post_id',
'tp.post_category_id',
'tp.post_title',
'tp.post_url_alias',
'tp.post_excerpt',
'tp.post_date',
'tp.post_modified',
'tp.post_status',
'tp.user_id',
'tc.category_name'
])
->from('tbl_post tp')
->leftJoin('tbl_category tc', 'tc.category_id = tp.post_category_id')
->where(['post_type'=>1])
->andWhere(['post_category_id'=>$_cid]);
if($search !== '') {
$query->andWhere('lower(post_title) LIKE "%'.$search.'%" ');
}
$countQuery = clone $query;
$pageSize = 5;
$pages = new Pagination([
'totalCount' => $countQuery->count(),
'pageSize'=>$pageSize
]);
$models = $query->offset($pages->offset)
->limit($pages->limit)
->orderBy(['post_id'=>SORT_DESC])
->all();
return [
'models' => $models,
'pages' => $pages,
'offset' =>$pages->offset,
'page' =>$pages->page,
'search' =>$search,
];
}
} | true |
2becb1b889af52b739ec3a405793b750ce9d0be9 | PHP | deljdlx/phi-html | /source/class/Element/Select.php | UTF-8 | 495 | 2.75 | 3 | [
"MIT"
] | permissive | <?php
namespace Phi\HTML\Element;
use Phi\HTML\Element;
class Select extends Element
{
/**
* @var Option[]
*/
private $options = array();
public function __construct()
{
parent::__construct('select', false);
}
public function addOption(Option $option)
{
$this->options[] = $option;
return $this;
}
public function render()
{
$this->children = $this->options;
return parent::render();
}
} | true |
5161772f671ebb1af949dcb6768b87d8c0e56d13 | PHP | PurpleBooth/git-lint-validators | /src/PurpleBooth/GitLintValidators/ValidatorFactoryImplementation.php | UTF-8 | 1,603 | 2.640625 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types=1);
/*
* Copyright (C) 2016 Billie Thompson
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace PurpleBooth\GitLintValidators;
use PurpleBooth\GitLintValidators\Validator\CapitalizeTheSubjectLineValidator;
use PurpleBooth\GitLintValidators\Validator\DoNotEndTheSubjectLineWithAPeriodValidator;
use PurpleBooth\GitLintValidators\Validator\LimitTheBodyWrapLengthTo72CharactersValidator;
use PurpleBooth\GitLintValidators\Validator\LimitTheTitleLengthTo69CharactersValidator;
use PurpleBooth\GitLintValidators\Validator\SeparateSubjectFromBodyWithABlankLineValidator;
use PurpleBooth\GitLintValidators\Validator\SoftLimitTheTitleLengthTo50CharactersValidator;
/**
* Build a ready ValidateMessage.
*/
class ValidatorFactoryImplementation implements ValidatorFactory
{
/**
* Get a message validator set-up with all the validators.
*
* @return ValidateMessage
*/
public function getMessageValidator(): ValidateMessage
{
$messageValidator = new ValidateMessageImplementation(
[
new CapitalizeTheSubjectLineValidator(),
new DoNotEndTheSubjectLineWithAPeriodValidator(),
new LimitTheBodyWrapLengthTo72CharactersValidator(),
new LimitTheTitleLengthTo69CharactersValidator(),
new SeparateSubjectFromBodyWithABlankLineValidator(),
new SoftLimitTheTitleLengthTo50CharactersValidator(),
]
);
return $messageValidator;
}
}
| true |
064dc0cabbc0efd4e61a5842e39e49b78769c98a | PHP | jose199827/CursoPDO | /Leccion_Abstracion/classPersona.php | UTF-8 | 410 | 3.390625 | 3 | [] | no_license | <?php
abstract class Persona
{
public $intDpi;
public $strNombre;
public $intEdad;
function __construct(int $dpi, string $nombre, int $edad)
{
$this->intDpi = $dpi;
$this->strNombre = $nombre;
$this->intEdad = $edad;
}
//Metodos
abstract public function getDatosPersonale();
abstract public function setMensaje(string $mensaje);
abstract public function getMensaje(): string;
}
| true |
7088704ecf3157d70e7539db52f03d735f30f2c4 | PHP | BramBleys/MMC | /application/models/Rit_model.php | UTF-8 | 8,867 | 2.953125 | 3 | [
"MIT"
] | permissive | <?php
/**
* @class Rit_model
* @brief Model-klasse voor de ritten van de vrijwilliger
*
* Model-klasse die alle methodes bevat om te interageren met de database-tabel rit
*/
class Rit_model extends CI_Model {
/**
* Constructor
*/
function __construct() {
parent::__construct();
}
/**
* Retourneert het rit-record met id = $id
* @param $id De id van het record waar we informatie over nodig hebben
* @return Een object van het rit-record
*/
function get($id) {
$this->db->where('id', $id);
$query = $this->db->get('rit');
$rit = $query->row();
return $rit;
}
function getAll() {
$this->db->order_by('vertrekTijdstip');
$query = $this->db->get('rit');
return $query->result();
}
/**
* Retourneert een array met alle ritten in voor de gebruiker met gebruikerId = $gebruikerId
* @param $gebruikerId De id van de gebruiker waar we informatie over nodig hebben
* @return Een array met alle ritten
*/
function getAllRitten($gebruikerId) {
$this->db->where('gebruikerIdVrijwilliger', $gebruikerId);
$query = $this->db->get('rit');
return $query->result();
}
/**
* Retourneert het rit-record met ritIdHeenrit = $id
* @param $id De id van de rit waar we de terugrit van willen vinden
* @return Een object van het rit-record
*/
function getByHeenRit($id) {
$this->db->where('ritIdHeenrit', $id);
$query = $this->db->get('rit');
$rit = $query->row();
return $rit;
}
/**
* Retourneert een object van rit-records (aangevuld met gebruiker- en adresgegevens)
* met gebruikerIdMinderMobiele = $gebruikerId en vertrekTijdstip > nu
* @param $gebruikerId De id van de gebruiker waar de ritten van willen hebben
* @see Gebruiker_model::getGebruiker()
* @see Adres_model::getAdres()
* @return Een object van rit-records (aangevuld met gebruiker- en adresgegevens)
*/
function getAllByDatumWithGebruikerEnAdresWhereGebruikerEnDatum($gebruikerId) {
$nu = date('Y-m-d H:i:s');
$this->db->order_by('vertrekTijdstip');
$this->db->where('gebruikerIdMinderMobiele', $gebruikerId);
$this->db->where('vertrekTijdstip >', $nu);
$query = $this->db->get('rit');
$ritten = $query->result();
foreach ($ritten as $rit) {
$this->load->model('Gebruiker_model');
$rit->chauffeur = $this->Gebruiker_model->getGebruiker($rit->gebruikerIdVrijwilliger);
$this->load->model('Adres_model');
$rit->vertrekAdres = $this->Adres_model->getAdres($rit->adresIdVertrek);
$rit->bestemmingAdres = $this->Adres_model->getAdres($rit->adresIdBestemming);
}
return $ritten;
}
/**
* Retourneert een object van rit-records (aangevuld met gebruiker- en adresgegevens)
* met gebruikerIdMinderMobiele = $gebruikerId en vertrekTijdstip > nu
* @param $gebruikerId De id van de gebruiker waar de ritten van willen hebben
* @see Gebruiker_model::getGebruiker()
* @see Adres_model::getAdres()
* @return Een object van rit-records (aangevuld met gebruiker- en adresgegevens)
*/
function getAllByDatumWithGebruikerEnAdresWhereGebruikerEnDatumOuder($gebruikerId) {
// geef gebruiker-object met opgegeven $id met de geplande ritten
$nu = date('Y-m-d H:i:s');
$this->db->order_by('vertrekTijdstip');
$this->db->where('gebruikerIdMinderMobiele', $gebruikerId);
$this->db->where('vertrekTijdstip <', $nu);
$query = $this->db->get('rit');
$ritten = $query->result();
foreach ($ritten as $rit) {
$this->load->model('Gebruiker_model');
$rit->chauffeur = $this->Gebruiker_model->getGebruiker($rit->gebruikerIdVrijwilliger);
$this->load->model('Adres_model');
$rit->vertrekAdres = $this->Adres_model->getAdres($rit->adresIdVertrek);
$rit->bestemmingAdres = $this->Adres_model->getAdres($rit->adresIdBestemming);
}
return $ritten;
}
/**
* Retourneert een object van rit-records
* met gebruikerIdMinderMobiele = $gebruikerId en vertrekDatum in de week van $datum
* @param $gebruikerId De id van de gebruiker waar de ritten van willen hebben
* @param $datum De datum in de week waar de ritten in willen vinden
* @return Een object van rit-records
*/
function getWhereDatum($gebruikerId, $datum) {
$date = strtotime($datum);
$weekDag = date('w', $date);
if ($weekDag != 1) {
$startdate = strtotime("last monday", $date);
$enddate = strtotime("monday", $date);
} else {
$startdate = strtotime("today", $date);
$enddate = strtotime("next monday", $date);
}
$startdate = date('Y-m-d H:i:s', $startdate);
$enddate = date('Y-m-d H:i:s', $enddate);
$this->db->order_by('vertrekTijdstip');
$this->db->where('gebruikerIdMinderMobiele', $gebruikerId);
$this->db->where('vertrekTijdstip >', $startdate);
$this->db->where('vertrekTijdstip <', $enddate);
$this->db->where('ritIdHeenrit', NULL);
$query = $this->db->get('rit');
$ritten = $query->result();
return $ritten;
}
function getAllByDatumWithGebruikerEnAdres() {
$this->db->order_by('vertrekTijdstip');
$query = $this->db->get('rit');
$ritten = $query->result();
foreach ($ritten as $rit) {
$this->load->model('Gebruiker_model');
$rit->minderMobiele = $this->Gebruiker_model->getGebruiker($rit->gebruikerIdMinderMobiele);
$rit->chauffeur = $this->Gebruiker_model->getGebruiker($rit->gebruikerIdVrijwilliger);
$this->load->model('Coach_model');
$coach = $this->Coach_model->getCoachWhereMinderMobiele($rit->minderMobiele->id);
if(!$coach) {
$rit->coach = null;
} else {
$coachId = $coach->gebruikerIdCoach;
$rit->coach = $this->Gebruiker_model->getGebruiker($coachId);
}
$this->load->model('Adres_model');
$rit->vertrekAdres = $this->Adres_model->getAdres($rit->adresIdVertrek);
$rit->bestemmingAdres = $this->Adres_model->getAdres($rit->adresIdBestemming);
}
return $ritten;
}
function getRitWithGebruikerEnAdres($ritId) {
$this->db->where('id', $ritId);
$query = $this->db->get('rit');
$rit = $query->row();
$this->load->model('Gebruiker_model');
$rit->minderMobiele = $this->Gebruiker_model->getGebruiker($rit->gebruikerIdMinderMobiele);
$rit->chauffeur = $this->Gebruiker_model->getGebruiker($rit->gebruikerIdVrijwilliger);
$this->load->model('Coach_model');
$coach = $this->Coach_model->getCoachWhereMinderMobiele($rit->minderMobiele->id);
$coachId = $coach->gebruikerIdCoach;
$rit->coach = $this->Gebruiker_model->getGebruiker($coachId);
$this->load->model('Adres_model');
$rit->vertrekAdres = $this->Adres_model->getAdres($rit->adresIdVertrek);
$rit->bestemmingAdres = $this->Adres_model->getAdres($rit->adresIdBestemming);
return $rit;
}
/**
* Maakt een nieuw rit-record aan met record = $rit, retourneert de id van het toegevoegde record
* @param $rit Het rit object dat we willen toevoegen aan de database
* @return De id van het toegevoegde record
*/
function insert($rit) {
$this->db->insert('rit', $rit);
return $this->db->insert_id();
}
function update($rit) {
$this->db->where('id', $rit->id);
$this->db->update('rit', $rit);
}
/**
* Verwijderd een rit-record met id = $id
* @param $id De id van het rit-record dat we willen verwijderen
*/
function delete($id) {
$this->db->where('id', $id);
$this->db->delete('rit');
}
} | true |
66f1d4f4086c8252a304a14a9d256f3dc9823ee6 | PHP | hlohaus/production | /.gitlab-ci/tools/src/Service/TaggingService.php | UTF-8 | 6,909 | 2.5625 | 3 | [
"MIT"
] | permissive | <?php declare(strict_types=1);
namespace Shopware\CI\Service;
use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;
use Shopware\CI\Service\Exception\TaggingException;
use Shopware\CI\Service\ProcessBuilder as Builder;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Process\Exception\ProcessFailedException;
class TaggingService
{
/**
* @var array
*/
private $config;
/**
* @var Client
*/
private $gitlabApiClient;
/**
* @var bool
*/
private $sign;
/**
* @var OutputInterface
*/
private $stdout;
public function __construct(array $config, Client $gitlabApiClient, OutputInterface $stdout, bool $sign = false)
{
$this->config = $config;
$this->gitlabApiClient = $gitlabApiClient;
$this->sign = $sign;
$this->stdout = $stdout;
}
public function createTag(string $tag, string $repoPath, string $message, bool $force = false): void
{
if ($force) {
try {
$this->deleteTag($tag, $repoPath);
} catch (ProcessFailedException $e) {
// ignore failure
}
}
$sign = $this->sign ? '--sign' : '--no-sign';
self::inRepo($repoPath)
->with('tag', $tag)
->with('message', $message)
->with('sign', $sign)
->run('git tag {{ $tag }} -a -m {{ $message }} {{ $sign }}')
->throw();
}
public function pushTag(string $tag, string $repoPath, string $remoteName, ?string $remoteUrl = null, ?string $localRef = null): void
{
$params = array_merge($this->config, [
'tag' => $tag,
'remoteName' => $remoteName,
'remoteUrl' => $remoteUrl,
'localRef' => $localRef ?? 'refs/tags/' . $tag,
'remoteRef' => 'refs/tags/' . $tag,
]);
if ($remoteUrl !== null) {
self::inRepo($repoPath)
->with($params)
->run(
'
git remote remove {{ $remoteName }} || true;
git remote add {{ $remoteName }} {{ $remoteUrl }}'
);
}
self::inRepo($repoPath)
->with($params)
->output($this->stdout)
->run('git push {{ $remoteName }} {{ $localRef }}:{{ $remoteRef }}')
->throw();
}
public function deleteTag(string $tag, string $repoPath): void
{
$builder = new Builder();
$builder->in($repoPath)
->with('tag', $tag)
->output($this->stdout)
->run('git tag -d {{ $tag }}')
->throw();
}
public function fetchTagPush(string $tag, string $commitRef, string $remoteName = 'upstream', ?string $repoPath = null, ?string $remoteUrl = null, ?string $message = null): void
{
if ($remoteUrl !== null && filter_var($remoteUrl, \FILTER_VALIDATE_URL) === false) {
throw new TaggingException($tag, $repoPath ?? '', 'remoteUrl is not a valid url');
}
$isTmp = false;
if ($repoPath === null) {
$repoPath = sys_get_temp_dir() . '/repo_' . bin2hex(random_bytes(16));
$isTmp = true;
}
(new Builder())
->with('repoPath', $repoPath)
->run('mkdir -p {{ $repoPath }}');
if (!file_exists($repoPath)) {
throw new TaggingException($tag, $repoPath, 'Repository path not found');
}
try {
$this->cloneOrFetch($commitRef, $repoPath, $remoteName, $remoteUrl);
$message = $message ?? 'Release ' . $tag;
$this->createTag($tag, $repoPath, $message, true);
$this->pushTag($tag, $repoPath, $remoteName, $remoteUrl);
} finally {
if ($isTmp) {
(new Builder())
->with('dir', $repoPath)
->run('rm -Rf {{ $dir }}');
}
}
}
public function cloneOrFetch(string $commitRef, string $repoPath, string $remoteName, ?string $remoteUrl = null, bool $bare = true): void
{
$params = array_merge($this->config, [
'remoteUrl' => $remoteUrl,
'remoteName' => $remoteName,
'commitRef' => $commitRef,
]);
if ($bare) {
self::inRepo($repoPath)
->with($params)
->run('git init --bare .')
->throw();
} else {
self::inRepo($repoPath)
->with($params)
->run('git init .')
->throw();
}
if ($remoteUrl !== null) {
self::inRepo($repoPath)
->with($params)
->run('git remote add {{ $remoteName }} {{ $remoteUrl }}');
}
self::inRepo($repoPath)
->output($this->stdout)
->with($params)
->run('git fetch --depth=1 {{ $remoteName }} {{ $commitRef }}')
->throw();
self::inRepo($repoPath)
->run('git reset --soft FETCH_HEAD')
->throw();
if (!$bare) {
self::inRepo($repoPath)
->run('git checkout HEAD')
->throw();
}
}
public function createReleaseBranch(string $repository, string $tag, string $gitRemoteUrl): void
{
$repository = escapeshellarg($repository);
$commitMsg = escapeshellarg('Release ' . $tag);
$escapedTag = escapeshellarg($tag);
$gitRemoteUrl = escapeshellarg($gitRemoteUrl);
$sign = $this->sign ? '--gpg-sign' : '--no-gpg-sign';
$signTag = $this->sign ? '--sign' : '--no-sign';
$shellCode = <<<CODE
set -e
git -C $repository add PLATFORM_COMMIT_SHA composer.json composer.lock
git -C $repository commit -m $commitMsg $sign
git -C $repository tag $escapedTag -a -m $commitMsg $signTag
git -C $repository remote add release $gitRemoteUrl
git -C $repository push release --tags
CODE;
system($shellCode, $returnCode);
if ($returnCode !== 0) {
throw new \RuntimeException('Failed to create release branch');
}
}
public function openMergeRequest(string $projectId, string $sourceBranch, string $targetBranch, string $title): void
{
$requestOptions = [
RequestOptions::JSON => [
'id' => $projectId,
'source_branch' => $sourceBranch,
'target_branch' => $targetBranch,
'title' => $title,
],
];
$this->gitlabApiClient->request('POST', 'projects/' . $projectId . '/merge_requests', $requestOptions);
}
private static function inRepo(string $repoPath): Builder
{
return (new Builder())->in($repoPath);
}
}
| true |
b5fcead09ab2146384620756dba5f6a72213696e | PHP | stagerightlabs/Laravel-Migration-Wrangler | /src/Commands/MigrationsExporter.php | UTF-8 | 2,873 | 3.09375 | 3 | [] | no_license | <?php
namespace SRLabs\MigrationWrangler\Commands;
use Illuminate\Support\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Console\ConfirmableTrait;
class MigrationsExporter extends Command
{
/**
* Prompt the user to confirm this action if they are in a prodiction env
*/
use ConfirmableTrait;
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'migrations:export
{--database= : The database connection to use.}
{--filepath= : The destination for the json file.}
{--pretty : Write the json with a readable structure.}
{--force : Force the operation to run when in production.}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Export the migrations table to a json file';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
// Ask the user for confirmation if we are in a production environment
if (! $this->confirmToProceed()) {
return;
}
// Establish the json encoding options
$pretty = $this->option('pretty');
$jsonOptions = 0;
if ($pretty) {
$jsonOptions = $jsonOptions | JSON_PRETTY_PRINT;
}
// Which database connection shall we use?
$database = $this->option('database') ?? config('database.default');
// Ensure that the specified connection exists
if (!config('database.connections.' . $database)) {
$this->error("You have specified an invalid connection: \"{$database}\"");
return 1;
}
// Ensure that the specified database has a migrations table
if (! Schema::setConnection(DB::connection($database))->hasTable('migrations')) {
$this->error("The \"{$database}\" database does not have a migrations table.");
return 1;
}
// Fetch the migrations table data
$migrations = DB::table('migrations')->get();
// Generate the filename for the new file
$now = Carbon::now()->format('Ymd');
$filename = "{$database}_migrations_{$now}.json";
// Establish the export path
$filepath = ($this->option('filepath') ?? database_path()) . '/' . $filename;
// Write the json to the file
$file = fopen($filepath, 'w');
fwrite($file, json_encode($migrations, $jsonOptions));
fclose($file);
// All set!
$this->info("Exported \"{$database}\" migrations to {$filename}");
}
}
| true |
314cc1293181e446f590366a544b2bd115c57f03 | PHP | Catfeeds/CLW | /app/Repositories/BuildingFeaturesRepository.php | UTF-8 | 1,326 | 2.78125 | 3 | [] | no_license | <?php
namespace App\Repositories;
use App\Models\BuildingFeature;
use Illuminate\Database\Eloquent\Model;
class BuildingFeaturesRepository extends Model
{
/**
* 说明: 获取楼盘特色列表
*
* @return \Illuminate\Database\Eloquent\Collection|static[]
* @author 刘坤涛
*/
public function buildingFeatureList()
{
return BuildingFeature::all();
}
/**
* 说明: 添加楼盘特色
*
* @param $request
* @return mixed
* @author 刘坤涛
*/
public function addBuildingFeature($request)
{
return BuildingFeature::create([
'name' => $request->name,
'weight' => $request->weight,
'pic' => $request->pic,
'pc_pic' => $request->pc_pic
]);
}
/**
* 说明: 修改楼盘特色
*
* @param $request
* @param $buildingFeatures
* @return bool
* @author 刘坤涛
*/
public function updateBuildingFeature($request, $buildingFeatures)
{
$buildingFeatures->name = $request->name;
$buildingFeatures->weight = $request->weight;
$buildingFeatures->pic = $request->pic;
$buildingFeatures->pc_pic = $request->pc_pic;
if (!$buildingFeatures->save()) return false;
return true;
}
} | true |
22754617ee0edc2d696cbaa4e6c2dbc7855100e1 | PHP | alimansoori/base-api | /app/Lib/Editors/Adapter/Editor.php | UTF-8 | 2,996 | 2.546875 | 3 | [] | no_license | <?php
namespace Lib\Editors\Adapter;
use Lib\Assets\Inline;
use Lib\Assets\Resource;
use Lib\Editors\Adapter;
use Lib\Editors\Ajax\AjaxCreate;
use Lib\Editors\Ajax\AjaxEdit;
use Lib\Editors\Ajax\AjaxRemove;
abstract class Editor extends Adapter
{
public function __construct(string $name, $hierarchy = false)
{
parent::__construct($name);
if ($hierarchy)
{
$this->ajaxCreate = new AjaxCreate($this, true);
$this->ajaxEdit = new AjaxEdit($this, true);
$this->ajaxRemove = new AjaxRemove($this, true);
}
}
public function render(): string
{
$this->beforeRender();
return '';
}
public function processAssets()
{
$this->assetsManager->addInlineJsTop("var ". $this->getName(). ";");
if($this->assetsManager->getCss() instanceof \Phalcon\Assets\Collection)
{
/** @var Resource $css */
foreach($this->assetsManager->getCss()->getResources() as $css)
$this->getTable()->assetsManager->addCss($css->getPath(), $css->getLocal(), $css->getFilter(), $css->getAttributes());
/** @var Inline $css */
foreach($this->assetsManager->getCss()->getCodes() as $css)
$this->getTable()->assetsManager->addInlineCss($css->getContent(), $css->getFilter(), $css->getAttributes());
}
if($this->assetsManager->getJs() instanceof \Phalcon\Assets\Collection)
{
/** @var Resource $js */
foreach($this->assetsManager->getJs()->getResources() as $js)
$this->getTable()->assetsManager->addJs($js->getPath(), $js->getLocal(), $js->getFilter(), $js->getAttributes());
/** @var Inline $js */
foreach($this->assetsManager->getJs()->getCodes() as $js)
$this->getTable()->assetsManager->addInlineJs($js->getContent(), $js->getFilter(), $js->getAttributes());
}
/** @var Inline $content */
foreach($this->assetsManager->getInlineJsTop() as $content)
$this->getTable()->assetsManager->addInlineJsTop($content->getContent());
$editor = "{$this->getName()} = new $.fn.dataTable.Editor( ";
$editor .= json_encode($this->options);
// process options to json encode
$editor .= " );";
$this->getTable()->assetsManager->addInlineJsMain($editor);
/** @var Inline $content */
foreach($this->assetsManager->getInlineJsMain() as $content)
$this->getTable()->assetsManager->addInlineJsMain($content->getContent());
/** @var Inline $content */
foreach($this->assetsManager->getInlineJsBottom() as $content)
$this->getTable()->assetsManager->addInlineJsBottom($content->getContent());
$this->getTable()->assetsManager->addCss('dt/css/style.dataTable.css');
}
public function beforeRender(): void
{
// TODO: Implement beforeRender() method.
}
} | true |
05cc4e9b55adfb1398471ccdc7302103e8f644f5 | PHP | varshiniyadavalli/PESTICIDE-PROMULGATOR | /pest/star.php | UTF-8 | 6,540 | 2.734375 | 3 | [] | no_license | <html>
<head>
<link rel="stylesheet" type="text/css" href="rating_style.css">
<script type="text/javascript">
function change(id)
{
var cname=document.getElementById(id).className;
var ab=document.getElementById(id+"_hidden").value;
document.getElementById(cname+"rating").innerHTML=ab;
for(var i=ab;i>=1;i--)
{
document.getElementById(cname+i).src="star2.png";
}
var id=parseInt(ab)+1;
for(var j=id;j<=5;j++)
{
document.getElementById(cname+j).src="star1.png";
}
}
</script>
</head>
<body>
<h1>Star Rating System Using PHP and JavaScript</h1>
<?php
/*$host="localhost";
$username="root";
$password="";
$databasename="snist";*/
$connect=mysqli_connect("localhost","root","","snist");
//$db=mysqli_select_db($databasename);
$select_rating=mysql_query("select php,asp,jsp from rating");
$total=mysql_num_rows($select_rating);
while($row=mysql_fetch_array($select_rating))
{
$phpar[]=$php;
$aspar[]=$asp;
$jspar[]=$jsp;
}
$total_php_rating=(array_sum($phpar)/$total);
$total_asp_rating=(array_sum($aspar)/$total);
$total_jsp_rating=(array_sum($jspar)/$total);
?>
<form method="post" action="insert_rating.php">
<p id="total_votes">Total Votes:<?php echo $total;?></p>
<div class="div">
<p>PHP (<?php echo $total_php_rating;?>)</p>
<input type="hidden" id="php1_hidden" value="1">
<img src="images/star1.png" onmouseover="change(this.id);" id="php1" class="php">
<input type="hidden" id="php2_hidden" value="2">
<img src="images/star1.png" onmouseover="change(this.id);" id="php2" class="php">
<input type="hidden" id="php3_hidden" value="3">
<img src="images/star1.png" onmouseover="change(this.id);" id="php3" class="php">
<input type="hidden" id="php4_hidden" value="4">
<img src="images/star1.png" onmouseover="change(this.id);" id="php4" class="php">
<input type="hidden" id="php5_hidden" value="5">
<img src="images/star1.png" onmouseover="change(this.id);" id="php5" class="php">
</div>
<div class="div">
<p>ASP (<?php echo $total_asp_rating;?>)</p>
<input type="hidden" id="asp1_hidden" value="1">
<img src="images/star1.png" onmouseover="change(this.id);" id="asp1" class="asp">
<input type="hidden" id="asp2_hidden" value="2">
<img src="images/star1.png" onmouseover="change(this.id);" id="asp2" class="asp">
<input type="hidden" id="asp3_hidden" value="3">
<img src="images/star1.png" onmouseover="change(this.id);" id="asp3" class="asp">
<input type="hidden" id="asp4_hidden" value="4">
<img src="images/star1.png" onmouseover="change(this.id);" id="asp4" class="asp">
<input type="hidden" id="asp5_hidden" value="5">
<img src="images/star1.png" onmouseover="change(this.id);" id="asp5" class="asp">
</div>
<div class="div">
<p>JSP (<?php echo $total_jsp_rating;?>)</p>
<input type="hidden" id="jsp1_hidden" value="1">
<img src="images/star1.png" onmouseover="change(this.id);" id="jsp1" class="jsp">
<input type="hidden" id="jsp2_hidden" value="2">
<img src="images/star1.png" onmouseover="change(this.id);" id="jsp2" class="jsp">
<input type="hidden" id="jsp3_hidden" value="3">
<img src="images/star1.png" onmouseover="change(this.id);" id="jsp3" class="jsp">
<input type="hidden" id="jsp4_hidden" value="4">
<img src="images/star1.png" onmouseover="change(this.id);" id="jsp4" class="jsp">
<input type="hidden" id="jsp5_hidden" value="5">
<img src="images/star1.png" onmouseover="change(this.id);" id="jsp5" class="jsp">
</div>
<input type="hidden" name="phprating" id="phprating" value="0">
<input type="hidden" name="asprating" id="asprating" value="0">
<input type="hidden" name="jsprating" id="jsprating" value="0">
<input type="submit" value="Submit" name="submit_rating">
</form>
</body>
</html>
In this step we made 3 div element to rate three programming language PHP,ASP,JSP and put the star image in them whenever the user wants to give ratings user has to put the mouse over the star and we call a change function which get the star id and change the star image to coloured means.You may also like live voting system using Ajax and PHP.
In javascript change(id) function we get the id of star which the user put the mouse over that and then we make 2 for loops one is to blink all the previous star including him and second one is to blank all the next star excluding him.
And after that we use connect to the database and get Total votes and there rating by getting total ratings per language and then divide then divide each rating with total votes.You can also view our create captcha system using PHP tutorial to add captcha on rating system.
Step 3.Make a PHP file to store the ratings for Star Rating System
We make a PHP file named insert_rating.php
<?php
if(isset($_POST['submit_rating']))
{
$host="localhost";
$username="root";
$password="";
$databasename="sample";
$connect=mysql_connect($host,$username,$password);
$db=mysql_select_db($databasename);
$php_rating=$_POST['phprating'];
$asp_rating=$_POST['asprating'];
$jsp_rating=$_POST['jsprating'];
$insert=mysql_query("insert into rating values('','$php_rating','$asp_rating','jsp_rating')");
}
?>
In this step we get the value and store them to database.You can do validation to make your code more secure or you can view our How to do validation before and after submitting the form tutorial.
Step 4.Make a CSS file and define styling for Star Rating System
We make a CSS file and save it with name rating_style.css.
body
{
background-color:#0B4C5F;
font-family:helvetica;
text-align:center;
}
h1
{
margin-top:20px;
font-size:40px;
color:#E6E6E6;
}
#total_votes
{
font-size:30px;
color:#FE2E2E;
font-weight:bold;
}
.div
{
border:1px solid #E6E6E6;
clear:both;
margin-top:20px;
height:100px;
width:400px;
padding:10px;
margin-left:300px;
border-radius:3px;
}
.div p
{
margin:0px;
font-size:20px;
text-align:left;
color:#E6E6E6;
}
img
{
margin-top:10px;
width:50px;
height:50px;
float:left;
}
input[type="submit"]
{
border:none;
background:none;
background-color:#585858;
width:100px;
height:50px;
color:white;
border-radius:3px;
font-size:17px;
margin-top:20px;
} | true |
20d4261bd87e6b324a68c1f5827c0e89722e6e87 | PHP | 1-8192/resume_registry_php | /view.php | UTF-8 | 2,831 | 3.03125 | 3 | [] | no_license | <?php
session_start();
require_once "pdo.php";
//logging logic
if (!isset($_SESSION["name"])) {
die("ACCESS DENIED");
}
//Getting data for user to edit from db
$stmt = $pdo->prepare("SELECT * FROM Profile WHERE profile_id = :id");
$stmt->execute(array(":id" => $_GET['profile_id']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
//making sure we're getting back an answer
if ($row === false) {
$_SESSION['error'] = "Bad value for profile id";
header("Location: index.php");
return;
} else {
$first_name = htmlentities($row['first_name']);
$last_name = htmlentities($row['last_name']);
$email = htmlentities($row['email']);
$headline = htmlentities($row['headline']);
$summary = htmlentities($row['summary']);
$profile_id = htmlentities($row['profile_id']);
}
$stmt = $pdo->prepare("SELECT * FROM Position WHERE profile_id = :id");
$stmt->execute(array(":id" => $_GET['profile_id']));
$count = 0;
$position_row = [];
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$position_row[$count] = $row;
$count++;
}
$stmt = $pdo->prepare("SELECT year, name FROM Education JOIN Institution ON Education.institution_id = Institution.institution_id WHERE profile_id = :prof ORDER BY rank");
$stmt->execute(array(":prof" => $_GET['profile_id']));
$education_row = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<?php require_once "head.php" ?>
<body>
<div class="container">
<h1>Profile information</h1>
<p>First Name: <?php echo $first_name ?></p>
<p>Last Name: <?php echo $last_name ?></p>
<p>Email: <?php echo $email ?></p>
<p>Headline: <?php echo $headline ?></p>
<p>Summary: <?php echo $summary ?></p>
<?php
if (count($position_row) > 0) {
echo('<p>Positions:</p><ul>');
for($i=0; $i<count($position_row); $i++) {
$year = htmlentities($position_row[$i]['year']);
$desc = htmlentities($position_row[$i]['description']);
echo('<li>'.$year .': ' .$desc .'</li>');
}
}
if (count($education_row) > 0) {
echo('<p>Education:</p><ul>');
for($i=0; $i<count($education_row); $i++) {
$year = htmlentities($education_row[$i]['year']);
$name = htmlentities($education_row[$i]['name']);
echo('<li>'.$year.': ' .$name .'</li>');
}
}
?>
<a href="index.php">Done</a>
</div>
</body>
</html> | true |
fe1d353bc114626350b1cf1964391d3388fe8002 | PHP | sellerlabs/nucleus | /src/SellerLabs/Nucleus/View/Composite/IconButton.php | UTF-8 | 1,813 | 2.921875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | <?php
/**
* Copyright 2015, Eduardo Trujillo
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* This file is part of the Nucleus package
*/
namespace SellerLabs\Nucleus\View\Composite;
use SellerLabs\Nucleus\Support\Html;
use SellerLabs\Nucleus\View\Common\Button;
use SellerLabs\Nucleus\View\Common\Italic;
use SellerLabs\Nucleus\View\Interfaces\RenderableInterface;
use SellerLabs\Nucleus\View\Interfaces\SafeHtmlProducerInterface;
use SellerLabs\Nucleus\View\SafeHtmlWrapper;
/**
* Class IconButton.
*
* @author Eduardo Trujillo <ed@sellerlabs.com>
* @package SellerLabs\Nucleus\View\Composite
*/
class IconButton implements RenderableInterface, SafeHtmlProducerInterface
{
/**
* @var array
*/
protected $attributes;
/**
* @var RenderableInterface|RenderableInterface[]|string|string[]
*/
protected $content;
/**
* @var string
*/
protected $icon;
/**
* @param string $icon
* @param string|RenderableInterface|string[]|RenderableInterface[] $content
* @param array $attributes
*/
public function __construct($icon, $content = '', $attributes = [])
{
$this->icon = $icon;
$this->content = $content;
$this->attributes = $attributes;
}
/**
* Render the object into a string.
*
* @return mixed
*/
public function render()
{
return (new Button($this->attributes, [
new Italic(['class' => 'icon ' . $this->icon]),
$this->content,
]))->render();
}
/**
* Get a safe HTML version of the contents of this object.
*
* @return SafeHtmlWrapper
*/
public function getSafeHtml()
{
return Html::safe($this->render());
}
}
| true |
9966539f98d161187da03e1ed9e26972fbfeaba5 | PHP | Christophe1/php-project | /list_contacts.php | UTF-8 | 1,386 | 2.75 | 3 | [] | no_license |
<?php
require('dbConnect.php');
//use the variables we created in volleyLogin.php
session_start();
$username = $_SESSION['username'] . "<br>";
$user_id = $_SESSION['user_id'];
echo $username;
echo $user_id;
//-we want to show contact_ids in the contacts table that have the $user_id above.
//select everything from user
$sql = "SELECT * FROM user WHERE username = '$username'";
//get the result of the above
$result = mysqli_query($con,$sql);
//get every other record in the same row
$row = mysqli_fetch_assoc($result);
//make the user_id record in that row a variable
$user_id = $row["user_id"];
$username = $row["username"];
echo "user id is " . $user_id . "<br>";
echo "user name is " . $username . "<br>";
//session_start();
$_SESSION['user_id']= $user_id;
$_SESSION['username'] = $username;
//$sql2 = "SELECT * FROM review WHERE user_id = '$user_id'";
$sql2 = "SELECT * FROM contacts WHERE user_id = '$user_id'";
$result2 = mysqli_query($con,$sql2);
//if no contacts for the user_id
if (mysqli_num_rows($result)==0) {
echo "No Contacts";
}
//if username is in the db
if (mysqli_num_rows($result) > 0) {
//if username has reviews in the db
while($rows = mysqli_fetch_assoc($result2)) {
$contact_id=$rows['contact_id'];
echo "contact is " . $contact_id . "<br>";
?> | true |
1c35274355cdf8dcac301110e4fe81bd02ee54d0 | PHP | twin1080/payment.loc | /commands/HelloController.php | UTF-8 | 2,157 | 2.90625 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace app\commands;
use Yii;
use yii\console\Controller;
/**
* This command echoes the first argument that you have entered.
*
* This command is provided as an example for you to learn how to create console commands.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class HelloController extends Controller
{
/**
* This command echoes what you have entered as the message.
* @param string $message the message to be echoed.
*/
public function actionIndex($message = 'hello world')
{
echo $message . "\n";
}
public function actionInit()
{
$auth = Yii::$app->authManager;
// добавляем разрешение "createPost"
$adminPermission = $auth->createPermission('adminPermission');
$adminPermission->description = 'admin permissions';
$auth->add($adminPermission);
// добавляем разрешение "updatePost"
$customerPermission = $auth->createPermission('customerPermission');
$customerPermission->description = 'customer permissions';
$auth->add($customerPermission);
// добавляем роль "customer" и даём роли разрешение "createPost"
$customer = $auth->createRole('customer');
$auth->add($customer);
$auth->addChild($customer, $customerPermission);
// добавляем роль "admin" и даём роли разрешение "updatePost"
// а также все разрешения роли "author"
$admin = $auth->createRole('admin');
$auth->add($admin);
$auth->addChild($admin, $adminPermission);
//$auth->addChild($admin, $author);
// Назначение ролей пользователям. 1 и 2 это IDs возвращаемые IdentityInterface::getId()
// обычно реализуемый в модели User.
$auth->assign($customer, 103);
$auth->assign($admin, 100);
}
}
| true |
82ccef685a19b01d67519c097e2782d4f8527a00 | PHP | Webdien123/RFID_Release | /resources/views/To_Mau_Ket_Qua.php | UTF-8 | 1,483 | 2.96875 | 3 | [
"MIT"
] | permissive | <?php
function stripUnicode($str){
$ThaiThe = $str;
if(!$ThaiThe) return null;
$unicode = array(
'a'=>'á|à|ả|ã|ạ|ă|ắ|ặ|ằ|ẳ|ẵ|â|ấ|ầ|ẩ|ẫ|ậ',
'd'=>'đ',
'e'=>'é|è|ẻ|ẽ|ẹ|ê|ế|ề|ể|ễ|ệ',
'i'=>'í|ì|ỉ|ĩ|ị',
'o'=>'ó|ò|ỏ|õ|ọ|ô|ố|ồ|ổ|ỗ|ộ|ơ|ớ|ờ|ở|ỡ|ợ',
'u'=>'ú|ù|ủ|ũ|ụ|ư|ứ|ừ|ử|ữ|ự',
'y'=>'ý|ỳ|ỷ|ỹ|ỵ',
);
foreach($unicode as $nonUnicode=>$uni) $ThaiThe = preg_replace("/($uni)/i", $nonUnicode, $ThaiThe);
return $ThaiThe;
}
function utf8_substr_replace($original, $replacement, $position, $length)
{
$startString = mb_substr($original, 0, $position, "UTF-8");
$endString = mb_substr($original, $position + $length, mb_strlen($original), "UTF-8");
$out = $startString . $replacement . $endString;
return $out;
}
function Doi_Mau($str, $TuKhoa)
{
$TK = "";
$Chuoi = "";
$TK = stripUnicode($TuKhoa);
$Chuoi = stripUnicode($str);
$index = stripos($Chuoi, $TK);
if ($index || strtolower($Chuoi[0]) == strtolower($TK[0])){
$length = strlen($TK);
$Chuoi = utf8_substr_replace($str, $TK, $index , $length);
$sub1 = mb_substr($str, $index, $length, "UTF-8");
$KQ = str_replace($TK ,"<span class='bg-danger'>$sub1</span>", $Chuoi);
return $KQ;
}
else
return $str;
}
?> | true |
36a7ee036d9240d4a4e7d2248d5d1e03e3221de8 | PHP | Abdallah-SE/Electronic_store_app | /app/controllers/supplierscontroller.php | UTF-8 | 3,898 | 2.578125 | 3 | [] | no_license | <?php
namespace PHPMVC\Controllers;
use PHPMVC\Models\SupplierModel;
use PHPMVC\LIB\InputFilter;
use PHPMVC\LIB\Helper;
use PHPMVC\lib\Messenger;
class SuppliersController extends AbstractController {
private $_createRules = [
'Name' => 'req|alphanum|between(5,40)',
'PhoneNumber' => 'req|alphanum|max(15)',
'Email' => 'req|vEmail',
'Address' => 'req|alphanum|max(50)'
];
use InputFilter;
use Helper;
public function defaultAction(){
$this->language->load('template.common');
$this->language->load('suppliers.default');
$this->_data['suppliers'] = SupplierModel::getAll();
return $this->_view();
}
public function createAction(){
$this->language->load('template.common');
$this->language->load('suppliers.create');
$this->language->load('suppliers.labels');
$this->language->load('validation.errors');
$this->language->load('suppliers.messages');
if(isset($_POST['submit']) && $this->isValidInput($this->_createRules, $_POST)){
$user_obj = new SupplierModel();
$user_obj->Name = $this->filterStr($_POST['Name']);
$user_obj->PhoneNumber = $this->filterStr($_POST['PhoneNumber']);
$user_obj->Email = $this->filterStr($_POST['Email']);
$user_obj->Address = $this->filterStr($_POST['Address']);
if($user_obj->save()){
$this->messeger->add($this->language->get('message_create_success'));
$this->redirect('/suppliers');
} else {
$this->messeger->add($this->language->get('message_create_failed'), Messenger::ERROR_MESSEEGE);
}
}
return $this->_view();
}
public function editAction(){
$this->language->load('template.common');
$this->language->load('suppliers.edit');
$this->language->load('suppliers.labels');
$this->language->load('validation.errors');
$this->language->load('suppliers.messages');
// get the id of selected user to edit
$id = $this->filterInt($this->_params[0]);
$user = SupplierModel::getByPK($id);
// wrong supplier
if($user === FALSE){
$this->redirect('/suppliers');
}
// send supplier data that have been editing
$this->_data['supplier'] = $user;
if(isset($_POST['submit']) && $this->isValidInput($this->_createRules, $_POST)){
$user->Name = $this->filterStr($_POST['Name']);
$user->PhoneNumber = $this->filterStr($_POST['PhoneNumber']);
$user->Email = $this->filterStr($_POST['Email']);
$user->Address = $this->filterStr($_POST['Address']);
// check if the editing be done
if($user->save()){
$this->messeger->add($this->language->get('message_create_success'));
$this->redirect('/suppliers');
} else {
$this->messeger->add($this->language->get('message_create_failed'), Messenger::ERROR_MESSEEGE);
}
}
return $this->_view();
}
public function deleteAction(){
// get the id of selected user to edit
$id = $this->filterInt($this->_params[0]);
$supplier = SupplierModel::getByPK($id);
if($supplier === FALSE){
$this->redirect('/suppliers');
}
$this->language->load('suppliers.messages');
if($supplier ->delete()){
$this->messeger->add($this->language->get('message_delete_success'));
$this->redirect('/suppliers');
}else {
$this->messeger->add($this->language->get('message_delete_failed'), Messenger::ERROR_MESSEEGE);
$this->redirect('/suppliers');
}
}
}
| true |
c5f0480c7ad21799967ea0511114584a4afa68e4 | PHP | mega6382/skeleton | /tests/unit/Template/BaseTest.php | UTF-8 | 1,026 | 2.734375 | 3 | [] | no_license | <?php
class Template extends A_Template_Base {
public function getForTesting($name)
{
return $this->$name;
}
public function render()
{
}
}
class TemplateTest extends UnitTestCase {
function setUp() {
}
function TearDown() {
}
function testTemplateNoConstructArgs() {
$Template = new Template();
$this->assertEqual($Template->getForTesting('filename'), '');
$this->assertEqual($Template->getForTesting('data'), array());
}
function testTemplateConstructArgs() {
$args = array('bar'=>7);
$Template = new Template('foo', $args);
// check if filename and data set
$this->assertEqual($Template->getForTesting('filename'), 'foo');
$this->assertEqual($Template->getForTesting('data'), $args);
$this->assertEqual($Template->get('bar'), 7);
// manually set data to see change
$this->assertEqual($Template->setFilename('baz')->getForTesting('filename'), 'baz');
$this->assertEqual($Template->set('bar', 9)->get('bar'), 9);
}
}
| true |
99cc7865098d490b145e2dd4c3f0e44ad8abcb41 | PHP | massira/SymfonyFormation-DIP | /src/Services/NewsletterManager.php | UTF-8 | 718 | 3.078125 | 3 | [] | no_license | <?php
namespace DIP\Formation\Services;
/**
* Class NewsletterManager
*
* @package DIP\Formation\Services
*/
class NewsletterManager
{
/** @var Mailer */
private $mailer;
/** @var string */
private $name;
/**
* @param Mailer $mailer
*/
public function __construct(Mailer $mailer)
{
$this->mailer = $mailer;
}
/**
* Send newsletter
*/
public function sendNews()
{
print 'Newsletter is sent';
}
/**
* @param string $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
} | true |
6b2efc7c6c22ebd327134f38770b0a7e0db8249d | PHP | isabella232/SimpleApiBundle | /Response/ItemResponse.php | UTF-8 | 510 | 2.875 | 3 | [
"MIT"
] | permissive | <?php
namespace Betsol\Bundle\SimpleApiBundle\Response;
class ItemResponse extends Response
{
/** @var array */
protected $item;
/**
* @param array $item
*/
public function __construct(array $item = [])
{
$this->item = $item;
}
/**
* @return array
*/
public function getItem()
{
return $this->item;
}
/**
* @param array $item
*/
public function setItem(array $item)
{
$this->item = $item;
}
} | true |
6d5572152ca22f6a040e51a2d2e4133966b58dfd | PHP | openstate/HNS.dev | /bo/formgen/formgen/trunk/elements/datetimeElement.class.php | UTF-8 | 5,969 | 2.75 | 3 | [] | no_license | <?php
class datetimeElement extends InputElement {
protected $name = '';
protected $value = array(
'Day' => null, 'Month' => null, 'Year' => null,
'Hour' => null, 'Minute' => null, 'Second' => null
);
protected $opts = array(
'start_year' => '+0',
'end_year' => '+4',
'reverse_years' => 'false',
'fields' => 'DMY',
'year_empty' => null,
'month_empty' => null,
'day_empty' => null,
'minute_interval' => 1,
'second_interval' => 1,
);
protected $childValues;
public function __construct() {
parent::__construct();
$this->childValues = array(
'day' => new SimpleInputValue($this, 'day', $this->value['Day'], array(array($this, 'getJSSubValue'), 'Day')),
'month' => new SimpleInputValue($this, 'month', $this->value['Month'], array(array($this, 'getJSSubValue'), 'Month')),
'year' => new SimpleInputValue($this, 'year', $this->value['Year'], array(array($this, 'getJSSubValue'), 'Year')),
'hour' => new SimpleInputValue($this, 'hour', $this->value['Hour'], array(array($this, 'getJSSubValue'), 'Hour')),
'minute' => new SimpleInputValue($this, 'minute', $this->value['Minute'], array(array($this, 'getJSSubValue'), 'Minute')),
'second' => new SimpleInputValue($this, 'second', $this->value['Second'], array(array($this, 'getJSSubValue'), 'Second'))
);
}
public function getHtml(HtmlContext $context) {
parent::getHtml($context);
$bool = array(false => 'false', true => 'true');
$result = $this->applyTemplate('datetime.html',
array_merge(
$this->opts,
array(
'name' => $this->state['name'],
'value' => sprintf(
'%d-%d-%d %d:%d:%d',
$this->value['Year'], $this->value['Month'], $this->value['Day'],
$this->value['Hour'], $this->value['Minute'], $this->value['Second']
),
'display_days' => $bool[strpos($this->opts['fields'], 'D') !== false],
'display_months' => $bool[strpos($this->opts['fields'], 'M') !== false],
'display_years' => $bool[strpos($this->opts['fields'], 'Y') !== false],
'display_hours' => $bool[strpos($this->opts['fields'], 'h') !== false],
'display_minutes' => $bool[strpos($this->opts['fields'], 'm') !== false],
'display_seconds' => $bool[strpos($this->opts['fields'], 's') !== false],
'year_empty' => $this->opts['year_empty'] === null ? 'null' : '\''.$this->opts['year_empty'].'\'',
'month_empty' => $this->opts['month_empty'] === null ? 'null' : '\''.$this->opts['month_empty'].'\'',
'day_empty' => $this->opts['day_empty'] === null ? 'null' : '\''.$this->opts['day_empty'].'\'',
'sm_year_empty' => $this->opts['year_empty'] === null ? '' : 'year_empty=\''. $this->opts['year_empty'].'\'',
'sm_month_empty' => $this->opts['month_empty'] === null ? '' : 'month_empty=\''.$this->opts['month_empty'].'\'',
'sm_day_empty' => $this->opts['day_empty'] === null ? '' : 'day_empty=\''. $this->opts['day_empty'].'\'',
)
),
$context);
return $result;
}
public function parse(DOMElement $node, $parser, ParseContext $context) {
parent::parse($node, $parser, $context);
foreach ($this->opts as $key => &$value) {
if ($node->hasAttribute($key))
$value = $node->getAttribute($key);
}
$this->source = $node->getAttribute('values');
}
public function getEvent($name) {
return array(
'add' => 'function(eventname, handler) { bindDateEvent(this, \''.addslashes($name).'\', eventname, handler) }.bind(form)',
'name' => 'change'
);
}
public function getConditions() {
$result = parent::getConditions();
$result[] = array(
'extraJS' => 'initCalendar(form, \''.addslashes($this->state['name']).'\');'
);
return $result;
}
public function getAllValues() {
$result = parent::getAllValues();
$result[$this->name]['full'] = $this->getValue();
return $result;
}
public function getChildValues() {
$children = array();
foreach (array(
'D' => 'day',
'M' => 'month',
'Y' => 'year',
'h' => 'hour',
'm' => 'minute',
's' => 'second'
) as $field => $name) {
if (strpos($this->opts['fields'], $field) !== false)
$children[$name] = $this->childValues[$name];
}
return $children;
}
public function getValue() {
$date = sprintf('%04d-%02d-%02d', $this->value['Year'], $this->value['Month'], $this->value['Day']);
$time = sprintf('%02d:%02d:%02d', $this->value['Hour'], $this->value['Minute'], $this->value['Second']);
$showDate = preg_match('/[DMY]/', $this->opts['fields']);
$showTime = preg_match('/[hms]/', $this->opts['fields']);
if ($showDate && $showTime)
return $date.' '.$time;
else if ($showDate)
return $date;
else
return $time;
}
public function setFromData($data, $raw = false) {
if (isset($data[$this->name])) {
if (!is_array($data[$this->name]) && $raw) {
$dateMatch = '(?P<year>\d{2,4})?-(?P<month>\d{1,2})?-(?P<day>\d{1,2})?';
$timeMatch = '(?P<hour>\d{1,2})?:((?P<minute>\d{1,2})?(:((?P<second>\d{1,2})(\.[0-9]+))?)?)?';
if (!preg_match('/^'.$dateMatch.'$/', $data[$this->name], $matches) &&
!preg_match('/^'.$timeMatch.'$/', $data[$this->name], $matches) &&
!preg_match('/^'.$dateMatch.' '.$timeMatch.'$/', $data[$this->name], $matches))
return;
$data = $matches;
} else
$data = $data[$this->name];
// Element-wise initing
foreach ($data as $key => $value)
$this->value[ucfirst($key)] = $value;
}
}
public function isGiven() {
return (bool)$this->value;
}
public function getJSValue() {
return 'getDateValue(form, \''.addslashes($this->state['name']).'\')';
}
public function getJSSubValue($subElem) {
return 'form[\''.addslashes($this->state['name'].'['.ucfirst($subElem->getName()).']').'\'].value';
}
}
?> | true |
219d913b5d0479c7d596323a4ac239e807c999d7 | PHP | p4lv/diag | /src/Controller/Api.php | UTF-8 | 1,506 | 2.625 | 3 | [
"MIT"
] | permissive | <?php
namespace Diag\Controller;
use Diag\DataMapper;
use Diag\DiagResponse;
use Diag\LogReader;
use Diag\Record;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
class Api
{
private $logReader;
private $dataMapper;
public function __construct(DataMapper $dataMapper, LogReader $logReader)
{
$this->logReader = $logReader;
$this->dataMapper = $dataMapper;
}
private $container;
public function setContainer(\Psr\Container\ContainerInterface $container)
{
$this->container = $container;
}
public function getList(Request $request): JsonResponse
{
$data = $this->logReader->getLast($request->get('limit', 10));
$response = new JsonResponse($data);
return $response;
}
public function postRecords(Request $request): JsonResponse
{
$this->dataMapper->store($request->request->all());
$response = new JsonResponse(['status' => 'ok']);
return $response;
}
public function postRecord(Request $request): JsonResponse
{
$record = new Record($request->request->all());
$this->dataMapper->store($record);
$response = new JsonResponse($record->toArray());
return $response;
}
public function getRecord(Request $request): JsonResponse
{
$id = $request->get('id');
$response = new DiagResponse($this->logReader->get($id));
return $response;
}
}
| true |
ca8e76a2d9efd3eb0db83c86a10a66bc3914ae36 | PHP | wpillar/fourum | /fourum/controllers/admin/ForumsController.php | UTF-8 | 2,231 | 2.53125 | 3 | [] | no_license | <?php
namespace Fourum\Controllers\Admin;
use Fourum\Controllers\AdminController;
use Fourum\Models\Forum\Type;
use Fourum\Models\Forum;
use Fourum\Tree\Node;
use Fourum\Tree\NodeRepositoryInterface;
use Fourum\Storage\Forum\ForumRepositoryInterface;
use Fourum\Storage\Setting\Manager;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
class ForumsController extends AdminController
{
/**
* @var ForumRepositoryInterface
*/
private $forumRepository;
/**
* @var NodeRepositoryInterface
*/
private $nodeRepository;
/**
* @param Manager $manager
* @param ForumRepositoryInterface $forumRepository
*/
public function __construct(
Manager $manager,
ForumRepositoryInterface $forumRepository,
NodeRepositoryInterface $nodeRepository
) {
parent::__construct($manager);
$this->forumRepository = $forumRepository;
$this->nodeRepository = $nodeRepository;
}
/**
* @return View
*/
public function index()
{
$data['tree'] = $this->tree;
return View::make('forums.index', $data);
}
/**
* @return View
*/
public function add()
{
$data['tree'] = $this->tree;
$data['types'] = Type::all();
return View::make('forums.add', $data);
}
/**
* @return \Illuminate\Http\RedirectResponse
*/
public function save()
{
$title = Input::get('title');
$type = Input::get('type');
$parent = Input::get('parent');
$forum = new Forum();
$forum->title = $title;
$forum->type = $type;
$forum->save();
if ($parent !== "null") {
$parent = $this->forumRepository->get($parent);
$parentNode = $parent->getNode();
$forumNode = $this->nodeRepository->create(array('forum_id' => $forum->id));
$forumNode->makeChildOf($parentNode);
} else {
$forumNode = $this->nodeRepository->create(array('forum_id' => $forum->id));
$forumNode->makeChildOf($this->tree);
}
return Redirect::to('admin/forums');
}
}
| true |
00d312a00182440c0f007e27f332aec01152818d | PHP | kenichiromiya/webwritecms | /template.php | UTF-8 | 551 | 2.578125 | 3 | [] | no_license | <?php
class Template
{
function getcontents($template,$data = array())
{
global $_LANG;
extract($data);
$cwd = getcwd();
chdir("views");
ob_start();
//include_once("functions.php");
include($template);
$contents = ob_get_contents();
ob_end_clean();
chdir($cwd);
return $contents;
}
function display($template,$data = array())
{
global $_LANG;
extract($data);
$cwd = getcwd();
chdir("views");
//include_once("functions.php");
include($template);
chdir($cwd);
}
}
?>
| true |
af8b8e431e49928823822891c8d0a4d3677e6690 | PHP | sanaeefar-saeed/blackJack | /src/Britejack/Card.php | UTF-8 | 477 | 3.1875 | 3 | [] | no_license | <?php namespace Briteskies\Britejack;
class Card
{
public $key;
public $value;
public $suite;
/**
* Card constructor.
*
* This method initialize the cards and assign them to properties
*
* @param $key
* @param $value
* @param $suite
*
* @return void
*/
public function __construct($key, $value, $suite)
{
$this->key = $key;
$this->value = $value;
$this->suite = $suite;
}
} | true |
db7e7cd6aff918f1bb8f873925d14d567f85d380 | PHP | tzabcd/yiiSpace | /protected/modules/oauth/vendors/oauth2-server-php/src/OAuth2/Response/Error.php | UTF-8 | 1,315 | 2.8125 | 3 | [
"MIT"
] | permissive | <?php
/**
*
*/
class OAuth2_Response_Error extends OAuth2_Response
{
public function __construct($statusCode, $error, $errorDescription, $errorUri = null)
{
$parameters = array(
'error' => $error,
'error_description' => $errorDescription,
);
if (!is_null($errorUri)) {
if (strlen($errorUri) > 0 && $errorUri[0] == '#') {
// we are referencing an oauth bookmark (for brevity)
$errorUri = 'http://tools.ietf.org/html/rfc6749' . $errorUri;
}
$parameters['error_uri'] = $errorUri;
}
$httpHeaders = array(
'Cache-Control' => 'no-store'
);
parent::__construct($parameters, $statusCode, $httpHeaders);
if (!$this->isClientError() && !$this->isServerError()) {
throw new InvalidArgumentException(sprintf('The HTTP status code is not an error ("%s" given).', $statusCode));
}
}
public function getError()
{
return $this->parameters['error'];
}
public function getErrorDescription()
{
return $this->parameters['error_description'];
}
public function getErrorUri()
{
return $this->parameters['error_uri'];
}
}
| true |
73ae8cb3054bb1771ae44c4b9fea334f72892d6f | PHP | keviinmiichael/notefix | /public/clases/validadorUsuario.php | UTF-8 | 1,313 | 2.90625 | 3 | [] | no_license | <?php
require_once("validador.php");
require_once("repositorio.php");
class ValidadorUsuario extends Validador {
public function validar(Array $datos, Repositorio $repo) {
$repoUsuarios = $repo->getRepositorioUsuarios();
$erroresRegister = [];
if (empty(trim($datos["name"]))){
$erroresRegister["name"] = "Completa tu nombre";
}
if (empty(trim($datos["lastname"]))){
$erroresRegister["lastname"] = "Completa tu apellido";
}
if (empty(trim($datos["tel"]))){
$erroresRegister["tel"] = "Completa tu telefono";
}
if (empty(trim($datos["email"]))){
$erroresRegister["email"] = "Por favor ingrese mail";
}elseif (!filter_var($datos["email"], FILTER_VALIDATE_EMAIL)){
$erroresRegister["email"] = "Por favor ingrese un mail correcto";
}elseif ($repoUsuarios->existeElMail($datos["email"])){
$erroresRegister["email"] = "El email ya esta registrado";
}
if (empty(trim($datos["pass1"]))){
$erroresRegister["pass"] = "El password es obligatorio!";
}
if (empty(trim($datos["pass2"]))){
$erroresRegister["pass"] = "El password es obligatorio!";
}
if ($datos["pass1"] !== $datos["pass2"]){
$erroresRegister["pass"] = "Las contraseñas no coinciden";
}
return $erroresRegister;
}
}
| true |
3509d0c74fc0659099e39c27c1d0025ba5919e5c | PHP | OkayCMS/Okay_Lite | /view/View.php | UTF-8 | 23,073 | 2.640625 | 3 | [] | no_license | <?php
require_once('api/Okay.php');
class View extends Okay {
/* Смысл класса в доступности следующих переменных в любом View */
public $currency;
public $currencies;
public $user;
public $group;
public $page;
public $language;
public $lang_link;
public $js_version;
public $css_version;
public $current_url;
/* Класс View похож на синглтон, храним статически его инстанс */
private static $view_instance;
public function __construct() {
// После переключения на язык по умолчанию, если не вызвать set_lang_id() до создания экземпляра класса settings,
// то мультиязычные настройки первый раз приходят на предыдущем языке.
if (empty($_GET['lang_label']) && empty($_GET['lang_id'])) {
$first_language = $this->languages->get_first_language();
$this->languages->set_lang_id($first_language->id);
}
$admin_theme = $this->settings->admin_theme;
$admin_theme_managers = $this->settings->admin_theme_managers;
if (!empty($_SESSION['admin']) && !empty($admin_theme) && $this->settings->theme != $this->settings->admin_theme) {
if (empty($admin_theme_managers) || in_array($_SESSION['admin'], $this->settings->admin_theme_managers)) {
$this->settings->theme = $this->settings->admin_theme;
}
}
parent::__construct();
if ($prg_seo_hide = $this->request->post("prg_seo_hide")) {
header("Location: ".$prg_seo_hide);
exit;
}
if (!defined('IS_CLIENT')) {
define('IS_CLIENT', true);
}
// Если инстанс класса уже существует - просто используем уже существующие переменные
if(self::$view_instance) {
$this->currency = &self::$view_instance->currency;
$this->currencies = &self::$view_instance->currencies;
$this->user = &self::$view_instance->user;
$this->group = &self::$view_instance->group;
$this->page = &self::$view_instance->page;
$this->language = &self::$view_instance->language;
$this->lang_link = &self::$view_instance->lang_link;
$this->js_version = &self::$view_instance->js_version;
$this->css_version = &self::$view_instance->css_version;
$this->current_url = &self::$view_instance->current_url;
} else {
// Сохраняем свой инстанс в статической переменной,
// чтобы в следующий раз использовать его
self::$view_instance = $this;
/*Устанавливаем версию js и css*/
if ($this->settings->theme == $this->settings->admin_theme) {
$this->js_version = time();
$this->css_version = time();
}
if (empty($this->js_version)) {
$this->js_version = $this->settings->js_version;
}
if (empty($this->css_version)) {
$this->css_version = $this->settings->css_version;
}
$this->design->assign('js_version', $this->js_version);
$this->design->assign('css_version',$this->css_version);
// Язык
$languages = $this->languages->get_languages();
$lang_link = '';
if (!empty($languages)) {
if($_GET['lang_label']) {
$this->language = $this->languages->get_language($this->languages->lang_id());
if ($this->language->enabled == 0) {
header('HTTP/1.1 503 Service Temporarily Unavailable');
header('Status: 503 Service Temporarily Unavailable');
header('Retry-After: 300');
}
if(!is_object($this->language)) {
$_GET['page_url'] = '404';
$_GET['module'] = 'PageView';
$this->language = $this->languages->get_first_language();
} else {
$lang_link = $this->language->label . '/';
}
} else {
$this->language = $this->languages->get_first_language();
$this->languages->set_lang_id($this->language->id);
}
$first_lang = $this->languages->get_first_language();
$ruri = $_SERVER['REQUEST_URI'];
if (strlen($this->config->subfolder) > 1) {
$pos = strpos($_SERVER['REQUEST_URI'], $this->config->subfolder);
if ($pos === 1 || $pos === 0) {
$sf = $this->config->subfolder;
$ruri = preg_replace("~$sf~", '', $ruri);
}
}
$ruri = explode('/', $ruri);
$as = $first_lang->id != $this->languages->lang_id() ? 2 : 1;
if(is_array($ruri) && $first_lang->id == $this->languages->lang_id() && $ruri[1] == $first_lang->label) {
header("HTTP/1.1 301 Moved Permanently");
header('Location: '.$this->config->root_url.'/'.implode('/',array_slice($ruri, 2)));
exit();
}
foreach($languages as $l) {
// основному языку не нужна метка
if($first_lang->id != $l->id) {
$l->url = $l->label . ($ruri?'/'.implode('/',array_slice($ruri, $as)):'');
} else {
$l->url = ($ruri ? implode('/',array_slice($ruri, $as)) : '');
}
$l->url = $this->config->root_url.'/'.$l->url;
}
if(!$this->language->enabled && $this->language->id != $first_lang->id) {
header('HTTP/1.0 503 Service Temporarily Unavailable');
header('Status: 503 Service Temporarily Unavailable');
header('Retry-After: 86400');//86400 seconds - 1day
}
}
$this->design->assign('lang_link', $lang_link);
$this->lang_link = $lang_link;
// Все валюты
$this->currencies = $this->money->get_currencies(array('enabled'=>1));
// Выбор текущей валюты
if($currency_id = $this->request->get('currency_id', 'integer')) {
$_SESSION['currency_id'] = $currency_id;
header("Location: ".$this->request->url(array('currency_id'=>null)));
}
// Берем валюту из сессии
if(isset($_SESSION['currency_id'])) {
$this->currency = $this->money->get_currency($_SESSION['currency_id']);
}
// Или первую из списка
else {
$this->currency = reset($this->currencies);
}
// Пользователь, если залогинен
if(isset($_SESSION['user_id'])) {
$u = $this->users->get_user(intval($_SESSION['user_id']));
if($u) {
$this->user = $u;
$this->group = $this->users->get_group($this->user->group_id);
}
}
// Текущая страница (если есть)
$subdir = substr(dirname(dirname(__FILE__)), strlen($_SERVER['DOCUMENT_ROOT']));
$page_url = trim(substr($_SERVER['REQUEST_URI'], strlen($subdir)),"/");
if(strpos($page_url, '?') !== false) {
$page_url = substr($page_url, 0, strpos($page_url, '?'));
}
if(!empty($languages) && !empty($first_lang)) {
$strlen = $first_lang->id == $this->language->id ? "" : $first_lang->label;
$page_url = trim(substr($page_url, strlen($strlen)),"/");
}
// Сохраним урл, он может понадобиться в других view
$this->current_url = $page_url;
if (!empty($_GET['page_url']) && in_array($_GET['page_url'], array('all-products', 'discounted', 'bestsellers'))) {
$page_url = $_GET['page_url'];
}
$this->design->assign('language', $this->language);
$this->design->assign('languages', $languages);
$this->translations->debug = (bool)$this->config->debug_translation;
$this->design->assign('lang', $this->translations->get_translations(array('lang'=>$this->language->label)));
$this->page = $this->pages->get_page((string)$page_url);
$this->design->assign('page', $this->page);
// Передаем в дизайн то, что может понадобиться в нем
$this->design->assign('currencies', $this->currencies);
$this->design->assign('currency', $this->currency);
$this->design->assign('user', $this->user);
$this->design->assign('group', $this->group);
$this->design->assign('config', $this->config);
$this->design->assign('settings', $this->settings);
// Настраиваем плагины для смарти
/*Распаковка переменной под админом*/
$this->design->smarty->registerPlugin('modifier', 'printa', array($this, 'printa'));
/*Выборка записей*/
$this->design->smarty->registerPlugin("function", "get_posts", array($this, 'get_posts_plugin'));
/*Выборка брендов*/
$this->design->smarty->registerPlugin("function", "get_brands", array($this, 'get_brands_plugin'));
/*Выборка просмотренных товаров*/
$this->design->smarty->registerPlugin("function", "get_browsed_products", array($this, 'get_browsed_products'));
/*Выборка товаров с пометкой "хит продаж"*/
$this->design->smarty->registerPlugin("function", "get_featured_products", array($this, 'get_featured_products_plugin'));
/*Выборка новых товаров*/
$this->design->smarty->registerPlugin("function", "get_new_products", array($this, 'get_new_products_plugin'));
/*Выборка акционных товаров*/
$this->design->smarty->registerPlugin("function", "get_discounted_products", array($this, 'get_discounted_products_plugin'));
/*Выборка категорий*/
$this->design->smarty->registerPlugin("function", "get_categories", array($this, 'get_categories_plugin'));
/*Выборка групп баннеров*/
$this->design->smarty->registerPlugin("function", "get_banner", array($this, 'get_banner_plugin'));
/*Иницализация капчи*/
$this->design->smarty->registerPlugin("function", "get_captcha", array($this, 'get_captcha_plugin'));
}
}
function fetch() {
return false;
}
public function get_captcha_plugin($params, &$smarty) {
if(isset($params['var'])) {
$number = 0;
unset($_SESSION[$params['var']]);
$total = rand(10,50);
$secret = rand(1,10);
$result[] = $total - $secret;
$result[] = $total;
$_SESSION[$params['var']] = $secret;
$smarty->assign($params['var'], $result);
} else {
return false;
}
}
public function get_categories_plugin($params, &$smarty) {
if(!empty($params['var'])) {
$smarty->assign($params['var'], $this->categories->get_categories($params));
}
}
public function get_posts_plugin($params, &$smarty) {
if(!isset($params['visible'])) {
$params['visible'] = 1;
}
if(!empty($params['var'])) {
$smarty->assign($params['var'], $this->blog->get_posts($params));
}
}
public function get_brands_plugin($params, &$smarty) {
if(!isset($params['visible'])) {
$params['visible'] = 1;
}
if(!empty($params['var'])) {
$smarty->assign($params['var'], $this->brands->get_brands($params));
}
}
public function get_browsed_products($params, &$smarty) {
if(!empty($_COOKIE['browsed_products']) && !empty($params['var'])) {
$browsed_products_ids = explode(',', $_COOKIE['browsed_products']);
$browsed_products_ids = array_reverse($browsed_products_ids);
if(isset($params['limit'])) {
$browsed_products_ids = array_slice($browsed_products_ids, 0, $params['limit']);
}
$products = array();
$images_ids = array();
foreach($this->products->get_products(array('id'=>$browsed_products_ids, 'visible'=>1)) as $p) {
$products[$p->id] = $p;
$images_ids[] = $p->main_image_id;
}
if (!empty($products)) {
// Выбираем варианты товаров
$variants = $this->variants->get_variants(array('product_id'=>$browsed_products_ids));
// Для каждого варианта
foreach($variants as $variant) {
if ($products[$variant->product_id]) {
$products[$variant->product_id]->variants[] = $variant;
}
}
if (!empty($images_ids)) {
$images = $this->products->get_images(array('id'=>$images_ids));
foreach ($images as $image) {
if (isset($products[$image->product_id])) {
$products[$image->product_id]->image = $image;
}
}
}
foreach ($browsed_products_ids as $id) {
if (isset($products[$id])) {
if (isset($products[$id]->variants[0])) {
$products[$id]->variant = $products[$id]->variants[0];
}
$result[] = $products[$id];
}
}
}
$smarty->assign($params['var'], $result);
}
}
public function get_featured_products_plugin($params, &$smarty) {
if(!isset($params['visible'])) {
$params['visible'] = 1;
}
$params['in_stock'] = 1;
$params['featured'] = 1;
if(!empty($params['var'])) {
$images_ids = array();
foreach($this->products->get_products($params) as $p) {
$products[$p->id] = $p;
$images_ids[] = $p->main_image_id;
}
if(!empty($products)) {
// id выбраных товаров
$products_ids = array_keys($products);
// Выбираем варианты товаров
$variants = $this->variants->get_variants(array('product_id'=>$products_ids));
// Для каждого варианта
foreach($variants as $variant) {
// добавляем вариант в соответствующий товар
$products[$variant->product_id]->variants[] = $variant;
}
// Выбираем изображения товаров
if (!empty($images_ids)) {
$images = $this->products->get_images(array('id'=>$images_ids));
foreach ($images as $image) {
if (isset($products[$image->product_id])) {
$products[$image->product_id]->image = $image;
}
}
}
foreach($products as $product) {
if(isset($product->variants[0])) {
$product->variant = $product->variants[0];
}
}
}
$smarty->assign($params['var'], $products);
}
}
public function get_new_products_plugin($params, &$smarty) {
if(!isset($params['visible'])) {
$params['visible'] = 1;
}
if(!isset($params['sort'])) {
$params['sort'] = 'created';
}
$params['in_stock'] = 1;
if(!empty($params['var'])) {
$images_ids = array();
foreach($this->products->get_products($params) as $p) {
$products[$p->id] = $p;
$images_ids[] = $p->main_image_id;
}
if(!empty($products)) {
// id выбраных товаров
$products_ids = array_keys($products);
// Выбираем варианты товаров
$variants = $this->variants->get_variants(array('product_id'=>$products_ids));
// Для каждого варианта
foreach($variants as $variant) {
// добавляем вариант в соответствующий товар
$products[$variant->product_id]->variants[] = $variant;
}
// Выбираем изображения товаров
if (!empty($images_ids)) {
$images = $this->products->get_images(array('id'=>$images_ids));
foreach ($images as $image) {
if (isset($products[$image->product_id])) {
$products[$image->product_id]->image = $image;
}
}
}
foreach($products as $product) {
if(isset($product->variants[0])) {
$product->variant = $product->variants[0];
}
}
}
$smarty->assign($params['var'], $products);
}
}
public function get_discounted_products_plugin($params, &$smarty) {
if(!isset($params['visible'])) {
$params['visible'] = 1;
}
$params['in_stock'] = 1;
$params['discounted'] = 1;
if(!empty($params['var'])) {
$images_ids = array();
foreach($this->products->get_products($params) as $p) {
$products[$p->id] = $p;
$images_ids[] = $p->main_image_id;
}
if(!empty($products)) {
// id выбраных товаров
$products_ids = array_keys($products);
// Выбираем варианты товаров
$variants = $this->variants->get_variants(array('product_id'=>$products_ids));
// Для каждого варианта
foreach($variants as $variant) {
// добавляем вариант в соответствующий товар
$products[$variant->product_id]->variants[] = $variant;
}
// Выбираем изображения товаров
if (!empty($images_ids)) {
$images = $this->products->get_images(array('id'=>$images_ids));
foreach ($images as $image) {
if (isset($products[$image->product_id])) {
$products[$image->product_id]->image = $image;
}
}
}
foreach($products as $product) {
if(isset($product->variants[0])) {
$product->variant = $product->variants[0];
}
}
}
$smarty->assign($params['var'], $products);
}
}
public function printa($var) {
if ($_SESSION['admin']) {
print_r($var);
}
}
public function get_banner_plugin($params, &$smarty){
if(!isset($params['group']) || empty($params['group'])) {
return false;
}
@$category = $this->design->smarty->getTemplateVars('category');
@$brand = $this->design->smarty->getTemplateVars('brand');
@$page = $this->design->smarty->getTemplateVars('page');
$show_filter_array = array('categories'=>$category->id,'brands'=>$brand->id,'pages'=>$page->id);
$banner = $this->banners->get_banner($params['group'], true, $show_filter_array);
if(!empty($banner)) {
if($items = $this->banners->get_banners_images(array('banner_id'=>$banner->id, 'visible'=>1))) {
$banner->items = $items;
}
$smarty->assign($params['var'], $banner);
}
}
public function setHeaderLastModify($lastModify) {
$lastModify=empty($lastModify)?date("Y-m-d H:i:s"):$lastModify;
$tmpDate=date_parse($lastModify);
@$LastModified_unix=mktime( $tmpDate['hour'], $tmpDate['minute'], $tmpDate['second '], $tmpDate['month'],$tmpDate['day'],$tmpDate['year'] );
//Проверка модификации страницы
$LastModified = gmdate("D, d M Y H:i:s \G\M\T", $LastModified_unix);
$IfModifiedSince = false;
if (isset($_ENV['HTTP_IF_MODIFIED_SINCE'])) {
$IfModifiedSince = strtotime(substr($_ENV['HTTP_IF_MODIFIED_SINCE'], 5));
}
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
$IfModifiedSince = strtotime(substr($_SERVER['HTTP_IF_MODIFIED_SINCE'], 5));
}
if ($IfModifiedSince && $IfModifiedSince >= $LastModified_unix) {
header($_SERVER['SERVER_PROTOCOL'] . ' 304 Not Modified');
exit;
}
//echo $lastModify." (View.php)<br />";
header('Last-Modified: '. $LastModified);
}
}
| true |
49ea7fb37fc15c1b0571094fcacce98165b3b0dc | PHP | d3besel1s/TicTacToe | /classes/Database.php | UTF-8 | 1,468 | 3.234375 | 3 | [
"MIT"
] | permissive | <?php
require('../config.php');
class Database
{
/**
* Query to create the table
*/
const DB_TABLE_INFO = [
'turns' => 'CREATE TABLE Turns
(
id INT NOT NULL AUTO_INCREMENT,
GameId varchar(255),
BoardStatus varchar(255),
LastMove int(11),
Player int(11),
GameStatus varchar(255),
PRIMARY KEY (id)
)',
];
/**
* @var PDO
*/
public $connection;
/**
* Database constructor
*/
public function __construct()
{
try {
$this->connection = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME, DB_USER, DB_PASSWORD);
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->checkIfTablesExist();
} catch (PDOException $e) {
echo "Database failed: ".$e->getMessage();
}
}
/**
* Creates table if it does not exist in database
*/
public function checkIfTablesExist()
{
foreach (self::DB_TABLE_INFO as $tableName => $createSql) {
try {
$result = $this->connection->query('SELECT 1 FROM turns LIMIT 1');
} catch (Exception $e) {
$result = false;
}
if ($result === false) {
$this->connection->exec($createSql);
}
}
}
}
?>
| true |
8569eafa372517e24e42ea565110a9851dfb4f18 | PHP | CodeOp/elobbyist_distribution | /modules/elobbyist/views/handlers/elobbyist_views_handler_linked_name.inc | UTF-8 | 3,238 | 2.8125 | 3 | [] | no_license | <?php
/**
* @file
* Contains the linked name field handler.
*/
/**
* Field handler to provide simple renderer that allows linking to a record.
* Definition terms:
* - link_to_record default: Should this field have the checkbox "link to record" enabled by default.
* - url: url with '%' as the view->base_field place holder
*
* @ingroup views_field_handlers
*/
class elobbyist_views_handler_linked_name extends views_handler_field {
function init(&$view, &$options) {
parent::init($view, $options);
$table = '';
if (isset($options['table']) && !empty($options['table'])) {
$table = $options['table'];
}
else {
$table = $view->base_table;
}
if (entity_access('update', $table)) {
return;
}
elseif (entity_access('view', $table)) {
if (isset($this->definition['readonly url'])) {
$this->definition['url'] = $this->definition['readonly url'];
}
else
{
unset($this->definition['url']);
}
}
else {
unset($this->definition['url']);
}
}
function option_definition() {
$options = parent::option_definition();
$options['link_to_record'] = array('default' => isset($this->definition['link_to_record default']) ? $this->definition['link_to_record default'] : FALSE, 'bool' => TRUE);
return $options;
}
/**
* Provide link to node option
*/
function options_form(&$form, &$form_state) {
$form['link_to_record'] = array(
'#title' => t('Link this field to the record edit form'),
'#description' => t("Enable to override this field's links."),
'#type' => 'checkbox',
'#default_value' => !empty($this->options['link_to_record']),
);
parent::options_form($form, $form_state);
}
/**
* Render whatever the data is as a link to the record.
*
* Data should be made XSS safe prior to calling this function.
*/
function render_link($data, $values) {
if (!empty($this->options['link_to_record'])) {
$fieldval = NULL;
if (isset($this->definition['id field']) && isset($this->view->field[$this->definition['id field']])) {
$deffieldname = $this->view->field[$this->definition['id field']]->field_alias;
$fieldname = NULL;
if (!empty($this->table_alias )) {
$fieldname = $this->table_alias . '_' . $this->definition['id field'];
if (!isset($values->$fieldname)) {
$fieldname = $deffieldname;
}
}
else
{
$fieldname = $deffieldname;
}
$fieldval = $values->$fieldname;
}
else {
$fieldval = $this->view->field[$this->view->base_field]->original_value;
}
if (!empty($data) && !empty($fieldval) && isset($this->definition['url'])) {
$this->options['alter']['make_link'] = TRUE;
$this->options['alter']['path'] = str_replace('%', $fieldval,
$this->definition['url']);
}
else {
$this->options['alter']['make_link'] = FALSE;
}
}
return $data;
}
function render($values) {
$value = $this->get_value($values);
return $this->render_link($this->sanitize_value($value), $values);
}
}
| true |
5f9bd88fe1239b8158e5e809d203d36b5f537d9f | PHP | GLOCTARRR/Practicum | /php/1_3/function.php | UTF-8 | 895 | 3.25 | 3 | [] | no_license | <?php
$elements = Array();
$elements_number = 0;
function createArray(){
global $elements_number, $elements;
$elements_number = $_POST['number'];
if($elements_number > 0){
for($i = 0; $i < $elements_number; $i++){
$elements[$i] = mt_rand(1, 100);
}
}
}
function displayElements(){
global $elements;
foreach($elements as $value)
echo $value." ";
}
function evenElements(){
global $elements_number, $elements;
$result = 1;
for($i = 0; $i < $elements_number; $i++){
if($i%2==0 && $elements[$i]>0){
$result *= $elements[$i];
}
}
echo $elements_number!=0 ? $result : "";
}
function oddElements(){
global $elements_number, $elements;
$result = 1;
for($i = 0; $i < $elements_number; $i++){
if($i%2!=0 && $elements[$i]>0){
$result *= $elements[$i];
}
}
echo $elements_number!=0 ? $result : "";
}
?> | true |
42062e35f28ebafbd6f79b3e3c10158d7cf8ec81 | PHP | Jhon12M/SoftContaPlus | /admon/auditoriaDetalles.php | UTF-8 | 1,436 | 2.578125 | 3 | [
"Apache-2.0"
] | permissive | <?php
/*
DETALLES DE LA BITACORA DE AUDITORIA
Presenta las acciones que se han realizado durante una sesión de un usuario en el sistema de información.
Viene de auditoria.php y recibe como parámetros:
$sesion: numero de la sesión en la variable $sesion pasada por get.
Autor: Galo Fabián Muñoz Espín
Fecha de creación: 02-2011
Ultima modificación:
*/
if (!session_is_registered('Usuario'))
{
?>
<script language="Javascript">
window.alert('Acceso no autorizado');
window.location='index.php';
</script>
<?php
}
?>
<table>
<h3>SUCESOS DE LA SESIÓN</h3>
<table border="1">
<tr><TD>Código</TD><TD>Fecha y Hora</TD><TD>Usuario</TD><TD>Suceso</TD><TD>Novedad</TD><TD>Información anterior</TD></tr>
<?php
include('funciones/conexion.inc.php');
foreach($_GET as $variable => $valor) ${$variable}=$valor;
$cadenaSQL="select codigo,fechahora, usuario, (case when (suceso='3') then 'Inserción' else ((case when (suceso='4') then 'Modificación' else ((case when (suceso='5') then 'Eliminación' else 'Consulta' end)) end)) end), detalle, registroanterior from admon_bitacoraauditoria where sesion='$sesion' and suceso in ('3','4','5','6') order by fechahora desc";
$consulta=pg_query($conexion,$cadenaSQL);
for ($i=0;$i<pg_num_rows($consulta);$i++)
{
echo '<tr>';
for ($j=0;$j<pg_num_fields($consulta);$j++) echo '<td>' . pg_result($consulta,$i,$j) . '</td>';
echo '</tr>';
}
pg_close($conexion);
?>
</table>
</center> | true |
15c6979851a88c4e53d56cf391e59e8be33be732 | PHP | hulume/joydong | /app/Stario/Wesite/WeMenu.php | UTF-8 | 624 | 2.546875 | 3 | [] | no_license | <?php
namespace Star\Wesite;
use Illuminate\Database\Eloquent\Model;
class WeMenu extends Model {
protected $table = 'wesite';
protected $guarded = ['id'];
protected $casts = ['link' => 'array'];
// 获取所有的图文消息集合
// public function pages() {
// return $this->hasMany('Star\Wechat\WePage', 'wx_menu_id');
// }
// 主导航菜单
public function scopeMain($query) {
return $query->where('type', 1);
}
// 引导菜单
public function scopeGuide($query) {
return $query->where('type', 2);
}
// 主题菜单
public function scopeTheme($query) {
return $query->where('type', 3);
}
}
| true |
d3dd947a78d2232983814ddbfb23ad46fb886760 | PHP | mariusolariu/Dynamic-Web-Apps | /week_3/section_8/e1.php | UTF-8 | 1,044 | 3.765625 | 4 | [] | no_license | <!DOCTYPE html>
<html>
<head>
<meta charset = “utf-8”>
<title> Dynamic Web Apps </title>
<script>
</script>
</head>
<body>
<?php
class Calculator{
private static $total = 0;
public function add($x){
Calculator::$total += $x;
return Calculator::$total;
}
public function substract($x){
Calculator::$total -= $x;
return Calculator::$total;
}
public function multiply($x){
Calculator::$total *= $x;
return Calculator::$total;
}
public function divide($x){
if ($x != 0){
Calculator::$total /= $x;
}else{
echo "Can't divide by 0 <br>";
}
return Calculator::$total;
}
}
$calc = new Calculator();
echo "Total: " . $calc->add(4) . "<br>";
echo "Total: " . $calc->add(12) . "<br>";
echo "Total: " . $calc->add(8) . "<br>";
echo "Total: " . $calc->substract(16) . "<br>";
echo "Total: " . $calc->multiply(4) . "<br>";
echo "Total: " . $calc->divide(8) . "<br>";
?>
</body>
</html>
| true |
dd642abd86afbf2945eef026aa3aa9f5e0d191be | PHP | wangle201210/laravel | /app/User.php | UTF-8 | 1,937 | 2.71875 | 3 | [] | no_license | <?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laratrust\Traits\LaratrustUserTrait;
use Tymon\JWTAuth\Contracts\JWTSubject as AuthenticatableUserContract;
class User extends Authenticatable implements AuthenticatableUserContract {
use LaratrustUserTrait, Notifiable, FilterAndSorting;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* @return mixed
*/
public function getJWTIdentifier() {
return $this->getKey(); // Eloquent model method
}
/**
* @return array
*/
public function getJWTCustomClaims() {
return [
'exp' => time() + 60 * 60 * 3,
'user' => [
'id' => $this->id,
],
];
}
/**
* This scope allows to retrive the users with a specific role.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $role
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeWhereRoleIs($query, $role = '') {
return $query->whereHas('roles', function ($roleQuery) use ($role) {
$roleQuery->where('name', $role);
});
}
/**
* This scope allows to retrive the users with some role.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $role
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeWhereRoleIn($query, $role = []) {
return $query->whereHas('roles', function ($roleQuery) use ($role) {
$roleQuery->whereIn('name', $role);
});
}
}
| true |
69d5ce1082d51ca745caf840a3c031d81bc8c804 | PHP | silvamfilipe/video-player | /src/Domain/VideoPlayer.php | UTF-8 | 242 | 2.8125 | 3 | [] | no_license | <?php
namespace App\Domain;
interface VideoPlayer
{
/**
* Creates the necessary HTML to render the provided video
*
* @param Video $video
* @return string
*/
public function render(Video $video): string;
}
| true |
5ddb1f8836c1bacb998bab37950c32b1b20f5aae | PHP | rufhausen/bands | /database/seeds/GenresTableSeeder.php | UTF-8 | 545 | 2.765625 | 3 | [
"MIT"
] | permissive | <?php
use Illuminate\Database\Seeder;
class GenresTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$csv = \File::get(resource_path('assets/genres.csv'));
$genresArray = explode(PHP_EOL, $csv);
asort($genresArray);
foreach ($genresArray as $key => $value) {
if (!empty($value)) {
App\Genre::create([
'name' => $value,
]);
}
}
}
}
| true |
488d1fabfb0214ca6373fdb38cfe85c90b75d860 | PHP | t2421/backend | /php/dao/migrations/20181124155023_AddUser.php | UTF-8 | 670 | 2.734375 | 3 | [] | no_license | <?php
use Phpmig\Migration\Migration;
class AddUser extends Migration
{
/**
* Do the migration
*/
public function up()
{
$now =
$sql = 'CREATE TABLE user_list (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)';
$container = $this->getContainer();
$container['db']->query($sql);
}
/**
* Undo the migration
*/
public function down()
{
$sql = "DROP TABLE user_list;";
$container = $this->getContainer();
$container['db']->query($sql);
}
}
| true |
c545e8adfa98ca3299aeb0a37c0ac36998e5a39b | PHP | FlavioHualpa/MySQL-PHP | /query_detalle.php | UTF-8 | 598 | 2.65625 | 3 | [] | no_license | <?php
require 'connect.php';
if ($db) {
$cons = $db->prepare('SELECT
(SELECT title
FROM series
WHERE id = :id
) AS nombre,
(SELECT COUNT(id)
FROM seasons
WHERE serie_id = :id
) AS temporadas,
(SELECT COUNT(episodes.id)
FROM episodes
INNER JOIN seasons ON episodes.season_id = seasons.id
WHERE seasons.serie_id = :id
) AS episodios'
);
$id = $_GET['serie_id'] ?? 0;
$cons->bindValue(':id', $id);
$cons->execute();
}
| true |
488df4c13b8c4c5090497c96af242c4b6bec234e | PHP | thecrazybob/laravel-whmcs | /src/WHMCS.php | UTF-8 | 459 | 2.78125 | 3 | [
"MIT"
] | permissive | <?php
namespace WHMCS;
class WHMCS extends WhmcsCore {
/**
* Instantiate a new instance
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Generic function to call WHMCS API
*
* @param string $action
* @param array $data
* @return array
*/
public function callAPI($request)
{
return $this->submitRequest($request);
}
} | true |
d185970ed7a0864c8f1f5b4b20b1dfa6502487ec | PHP | raman10101/buzzerout_server | /Utils/UtilsQuery.php | UTF-8 | 2,207 | 3.109375 | 3 | [] | no_license | <?php
class UtilsQuery
{
private $conn;
function __construct()
{
require_once './../Config/Connect.php';
$db = new Connect();
$this->conn = $db->connect();
}
public function lowerCase($text)
{
$response = array();
$response['error'] = false;
$response['old_username'] = $text;
$response['new_username'] = strtolower($text);
return $response;
}
public function noSpecialChar($text)
{
$response = array();
if (!ctype_alnum($text)) {
$response['error'] = true;
$response['message'] = "username contain special character";
} else {
$response['error'] = false;
$response['message'] = "username does not contain special character";
}
return strtolower($text);
}
public function passwordLenght($text)
{
$response = array();
if (strlen($text) < 11) {
$response['error'] = true;
$response['message'] = "password lenght is small";
} else {
$response['error'] = false;
$response['message'] = "strong password ";
}
return $response;
}
public function passwordEncrypt($text)
{
$response = array();
$response['error'] = false;
$response['message'] = "password encrypted";
$ciphering = "AES-128-CTR";
// Use OpenSSl Encryption method
$iv_length = openssl_cipher_iv_length($ciphering);
$options = 0;
// Non-NULL Initialization Vector for encryption
$encryption_iv = '1234567891011121';
// Store the encryption key
$encryption_key = "password";
// Use openssl_encrypt() function to encrypt the data
$response['encrypt_password'] = openssl_encrypt(
$text,
$ciphering,
$encryption_key,
$options,
$encryption_iv
);
return $response;
}
public function passwordDecrypt($text)
{
$response = array();
$response['error'] = false;
$response['message'] = "password decrypt";
// Non-NULL Initialization Vector for decryption
$decryption_iv = '1234567891011121';
$ciphering = "AES-128-CTR";
// Store the decryption key
$decryption_key = "password";
$options = 0;
// Use openssl_decrypt() function to decrypt the data
$response['decrypted_password'] = openssl_decrypt(
$text,
$ciphering,
$decryption_key,
$options,
$decryption_iv
);
return $response;
}
}
| true |