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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
dd3068eb10f83ad024d634432c07aa268924d4b2 | PHP | seedgabo/baum | /src/NestedSet/Concerns/WorksWithSoftDeletes.php | UTF-8 | 2,399 | 2.65625 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | <?php
namespace Baum\NestedSet\Concerns;
use Illuminate\Database\Eloquent\SoftDeletingScope;
trait WorksWithSoftDeletes
{
/**
* Returns wether soft delete functionality is enabled on the current model
* instance or not.
*
* @return boolean
*/
public function hasSoftDeletes()
{
// To determine if there's a global soft delete scope defined we must
// first determine if there are any, to workaround a non-existent key error.
$globalScopes = $this->getGlobalScopes();
if (count($globalScopes) === 0) {
return false;
}
// Now that we're sure that the calling class has some kind of global scope
// we check for the SoftDeletingScope existance
return static::hasGlobalScope(new SoftDeletingScope);
}
/**
* "Makes room" for the the current node between its siblings.
*
* @return void
*/
public function shiftSiblingsForRestore()
{
if (!$this->hasSoftDeletes()) {
return;
}
if (is_null($this->getRight()) || is_null($this->getLeft())) {
return;
}
$this->getConnection()->transaction(function () {
$lftCol = $this->getLeftColumnName();
$rgtCol = $this->getRightColumnName();
$lft = $this->getLeft();
$rgt = $this->getRight();
$diff = $rgt - $lft + 1;
$this->newQuery()->where($lftCol, '>=', $lft)->increment($lftCol, $diff);
$this->newQuery()->where($rgtCol, '>=', $lft)->increment($rgtCol, $diff);
});
}
/**
* Restores all of the current node's descendants.
*
* @return void
*/
public function restoreDescendants()
{
if (!$this->hasSoftDeletes()) {
return;
}
if (is_null($this->getRight()) || is_null($this->getLeft())) {
return;
}
$this->getConnection()->transaction(function () {
$this->newQuery()
->withTrashed()
->where($this->getLeftColumnName(), '>', $this->getLeft())
->where($this->getRightColumnName(), '<', $this->getRight())
->update([
$this->getDeletedAtColumn() => null,
$this->getUpdatedAtColumn() => $this->{$this->getUpdatedAtColumn()}
]);
});
}
}
| true |
d3f630edb88c7d7e331511f2efd53804e9839743 | PHP | ace7jae/hunianlengkap | /application/views/Administrator/DataRumah/tabel_kota_report.php | UTF-8 | 2,031 | 2.875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | <?php
// Tentukan path yang tepat ke mPDF
$nama_dokumen='cetak-report-keberangkatan'; //Beri nama file PDF hasil.
define('_MPDF_PATH','./assets/mpdf/'); // Tentukan folder dimana anda menyimpan folder mpdf
include(_MPDF_PATH . "mpdf.php"); // Arahkan ke file mpdf.php didalam folder mpdf
$mpdf=new mPDF('utf-8', 'A4', 10.5, 'arial'); // Membuat file mpdf baru
//Memulai proses untuk menyimpan variabel php dan html
ob_start();
?>
<style>
table{margin: auto;display: table;
border-collapse: separate;
border-spacing: 2px;
border-color: gray;}
td,th{padding: 5px;text-align: center; width: 150px}
h1{text-align: center}
th{background-color: #00BFFF; padding: 10px;color: #fff}
</style>
<h1>LAPORAN DATA KEBERANGKATAN</h1>
<table border="1">
<tr>
<th>Id Berangkat</th>
<th>Bus</th>
<th>Tujuan</th>
<th>Tanggal Keberangkatan</th>
<th>Jam Keberangkatan</th>
<th>Rute Awal</th>
<th>Rute Tujuan</th>
<th>Harga</th>
</tr>
<?php
foreach ($data_keberangkatan->result() as $dt) {
echo "
<tr>
<td>$dt->id_keberangkatan</td>
<td>$dt->bus</td>
<td>$dt->tujuan</td>
<td>$dt->tanggal_keberangkatan</td>
<td>$dt->jam_keberangkatan</td>
<td>$dt->rute_awal</td>
<td>$dt->rute_tujuan</td>
<td>$dt->harga</td>
</tr>
";
}
?>
</table>
<!-- /.container-fluid -->
<?php
//penulisan output selesai, sekarang menutup mpdf dan generate kedalam format pdf
$html = ob_get_contents(); //Proses untuk mengambil hasil dari OB..
ob_end_clean();
//Disini dimulai proses convert UTF-8, kalau ingin ISO-8859-1 cukup dengan mengganti $mpdf->WriteHTML($html);
$mpdf->WriteHTML(utf8_encode($html));
$mpdf->Output($nama_dokumen.".pdf" ,'I');
exit;
?>S | true |
545681332706c2f72a0daad6088867ec8258a298 | PHP | sumeetgopi/startcar | /app/Utility.php | UTF-8 | 327 | 2.53125 | 3 | [
"MIT"
] | permissive | <?php
namespace App;
trait Utility
{
public function store($inputs = [], $id = null, $multiple = false)
{
if($id) { $this->find($id)->update($inputs); return $id; }
else {
if($multiple) { $this->insert($inputs); }
else { return $this->create($inputs)->id; }
}
}
} | true |
71724c3909b35d5e5ba47f65a8500312a87154f0 | PHP | gruevy/project5 | /admin/deleteAdmin.php | UTF-8 | 3,045 | 2.703125 | 3 | [
"Unlicense"
] | permissive | <!-- Page by: Jazmin Belmonte -->
<?php
require "config.php";
require "common.php";
if (isset($_GET['user_id'])) {
//echo $_GET['id'];
try {
$connection = new PDO($dsn, $username, $password, $options);
$id = $_GET['user_id'];
$sql = "DELETE FROM users WHERE user_id = :user_id";
$statement = $connection->prepare($sql);
$statement->bindValue(':user_id', $id);
$statement->execute();
echo "Record deleted.";
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
}
try {
$connection = new PDO($dsn, $username, $password, $options);
$sql = "SELECT * FROM users";
$statement = $connection->prepare($sql);
$statement->execute();
$result = $statement->fetchAll();
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
?>
<?php include "templates/header.php"?>
<!-- php if(userType = admin)
manageAccountButton
manageUsersButton
manageContent -->
<br>
<br>
<div class="AD">
<div class="tabs is-centered">
<ul>
<li class="is-active"><a href="#">Manage Admin Account</a></li>
<li><a href="manageUsers.php">Manage Users</a></li>
<li><a href="manageContent.php">Manage Content</a></li>
</ul>
</div>
<div class="columns">
<div class="column">
<!-- First column -->
<ul class="has-text-centered">
<li><a href="readAdmin.php">Find Other Admin Accounts</a></li>
<li><a href="updateAdmin.php">Update Admin Account</a></li>
<li class="selected"><a href="deleteAdmin.php">Delete Admin Account</a></li>
</ul>
</div>
<div class="column" id="secondC">
<!-- Second column -->
<p class="is-size-5 has-text-centered has-text-grey">Delete Admin Accounts</p>
<table class="table is-bordered is-striped is-narrow is-hoverable is-fullwidth">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Role</th>
<th>Location</th>
<th>Date Created</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
<?php foreach ($result as $row) { ?>
<tr>
<td><?php echo escape($row["user_id"]); ?></td>
<td><?php echo escape($row["user_firstname"]); ?></td>
<td><?php echo escape($row["user_lastname"]); ?></td>
<td><?php echo escape($row["user_role"]); ?></td>
<td><?php echo escape($row["location"]); ?></td>
<td><?php echo escape($row["user_created"]); ?></td>
<td><a href="delete.php?user_id=<?php echo escape($row["user_id"]);?>">Delete</a></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>
<?php include "templates/footer.php"?> | true |
27d7a8689e22695337a24a0b8474a6d9970e46d8 | PHP | NorbertElephant/Exercice_03W | /exo_php_procedural/exo_liste_des_courses/exo_liste_des_courses.php | UTF-8 | 2,490 | 3.1875 | 3 | [] | no_license | <?php
session_start();
/**
* aarray_search
*
* @param [type] $needle
* @param [type] $haystack
* @return void
*/
function aarray_search($needle, $haystack){
foreach ($haystack as $key => $value) {
if( $value['art']== $needle){
return $key;
}
}
return false;
}
// système de d'ajout de produits sans doublons
if(isset($_POST['article'],$_POST['quantity'],$_POST['add'])) {
if(is_numeric($_POST['quantity'])) {
if (isset($_SESSION['cart']) && ($key = aarray_search($_POST['article'],$_SESSION['cart']) !== false)) { // fonction de recherche sur un tableau associé
if($_SESSION['cart'][$key]['qty']+ $_POST['quantity'] <= 0 ){
// Si le calcul est égal à 0 ou moins suppression de l'article
unset($_SESSION['cart'][$key]);
}else {
$_SESSION['cart'][$key]['qty'] += $_POST['quantity'];
}
} else {
$_SESSION['cart'][] = array(
"art" => $_POST['article'],
"qty" => $_POST['quantity']
);
}
}else {
echo 'Mauvaise saisie ! Veuillez indiquer une quantité numérique';
}
}
// Système de suppresion de produits
if (isset($_SESSION['cart'],$_POST['del']) && count($_POST)>0 ){
foreach ($_POST as $keyCart => $checked) {
unset($_SESSION['cart'][$keyCart]);
}
}
?>
<form method='POST'>
<input name="article" placeholder="Saisissez un produit" type ='text' >
<input name="quantity" placeholder="Saisissez une quantité" type ='text' >
<input name ='add' type='submit' >
</form>
<?php
if(!empty($_SESSION['cart'])){
?>
<form method='POST'>
<table border ="1">
<thead>
<tr>
<th> Article </th>
<th> Quantity </th>
</tr>
</thead>
<tfoot>
<tr>
<td colspan='3'> <input name="del" type="submit" value="Supprimer"/> </td>
</tfoot>
<tbody>
<?php
foreach ($_SESSION['cart'] as $key => $article) {
echo '<tr><td>' .$article['art'] . ' </td><td> ' . $article['qty'] . '</td><td> <input name="'.$key.'" type="checkbox" </td></tr>' ;
}
?>
</tbody>
</table>
</form>
<?php
}
| true |
83b40920996dd16547c3f70922c5b5b77b54e2fa | PHP | charilab/geoapi | /ov_tobefixed.php | UTF-8 | 1,626 | 2.578125 | 3 | [] | no_license | <?php
function build_query_convenience($desc) {
$invalid_convenience_names = array(
'セブンイレブン', '7', '[Ss]even', 'セブン・イレブン',
'[Ll]awson', 'LAWSON',
'[Ff]amily',
'Mini Stop', 'MINI STOP', '[Mm]ini[Ss]top', 'Mini-Stop',
'[Cc]ircle',
'[Ss]unkus', 'Thankusu', 'SUNKUS',
'ローソン100', 'ローソンショップ100',
'ThreeF',
'[Ss]eico',
'Daily',
'Coco'
);
$q="";
foreach($invalid_convenience_names as $name) {
if ($desc) {
$q = sprintf("%snode(%s)[shop=convenience]['name'~'^%s'];out meta;\n", $q, $desc, $name);
} else {
$q = sprintf("%snode[shop=convenience]['name'~'^%s'];\n", $q, $name);
}
}
return $q;
}
function get_nodes($kind, $desc) {
switch($kind) {
case "convenience":
$query = build_query_convenience($desc);
$nodes = call_overpass($query);
break;
case "signals":
$query = sprintf("node(%s)[highway=traffic_signals]['name'!~'.']['noname'!~'.'];out meta;", $desc);
$nodes = call_overpass($query);
break;
case "toilets":
$query = sprintf("node(%s)[amenity=toilets]['wheelchair'!~'.'];out meta;", $desc);
$nodes = call_overpass($query);
break;
default:
$nodes = null;
}
return $nodes;
}
function get_ways($kind, $desc) {
switch($kind) {
case "bike":
$ways = null;
break;
case "nobike":
$ways = null;
break;
default:
$ways = null;
}
return $ways;
}
?>
| true |
dbc33603edf670a635f8e33a98a85635dd16623f | PHP | kL3x/GluecksradBot | /lib/functions.php | UTF-8 | 3,912 | 2.875 | 3 | [] | no_license | <?php
function rmkdir($path, $chmod = '777') {
$exp = explode("/", $path);
$way = '';
foreach ($exp as $n) {
$way .= $n.'/';
if (!file_exists($way))
mkdir($way, $chmod);
}
}
function iif($expression, $true, $false='') {
return ($expression ? $true : $false);
}
function formatdate($timeformat, $timestamp, $replacetoday=0) {
global $config;
$summertime = date("I", $timestamp)*3600;
$timestamp += 3600*intval(1)+$summertime;
if ($replacetoday == 1) {
if (gmdate("Ymd", $timestamp) == gmdate("Ymd", time()+3600*intval(1)+$summertime)) {
return 'Heute';
} elseif (gmdate("Ymd", $timestamp) == gmdate("Ymd",time()-86400+3600*intval(1)+$summertime)) {
return 'Gestern';
}
}
return gmdate($timeformat, $timestamp);
}
function formatnumber($number) {
if ($number == (int)$number) $i = 0;
else $i = 2;
return number_format($number,$i,',','.');
}
function formatsize($size) {
if ($size >= 1073741824) { return round(($size / 1073741824), 2)." GB"; }
elseif ($size >= 1048576) { return round(($size / 1048576), 2)." MB"; }
elseif ($size >= 1024) { return round(($size / 1024), 2)." KB"; }
else { return $size." Byte"; }
}
function in_string($needle, $haystack, $insensitive = 0) {
if ($insensitive) {
return (false !== stristr($haystack, $needle)) ? true : false;
} else {
return (false !== strpos($haystack, $needle)) ? true : false;
}
}
function read_recursiv($path) {
$result = array();
$handle = opendir($path);
if ($handle) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$name = $path . "/" . $file;
if ($name == "./images") continue;
if ($name == "./logs") continue;
if (preg_match("/[A-Za-z0-9]+\.js/isU", $name)) continue;
if (preg_match("/[A-Za-z0-9]+\.css/isU", $name)) continue;
if (preg_match("/[A-Za-z0-9]+\.sql/isU", $name)) continue;
if (is_dir($name)) {
$ar = read_recursiv($name);
foreach ($ar as $value) {
$result[] = $value;
}
} else {
$result[] = $name;
}
}
}
}
closedir($handle);
return $result;
}
function inarray(&$array, $needle) {
foreach ($array as $key => $value) {
if ($value == $needle || $key == $needle)
return true;
else
if(is_array($value))
inarray($value,$needle);
else
return false;
}
}
function getdifftime($time) {
$difftime = (time() - $time);
$weeks = floor($difftime / (7*(24*3600)) );
$difftime = $difftime - ($weeks * (7*(24*3600)));
$days = floor($difftime / (24*3600));
$difftime = $difftime - ($days * (24*3600));
$hours = floor($difftime / (3600));
$difftime = $difftime - ($hours * (3600));
$minutes = floor($difftime /(60));
$difftime = $difftime - ($minutes * 60);
$seconds = $difftime;
if (!eregi("[0-9]{2}", $seconds)) $seconds = '0'.$seconds;
if (!eregi("[0-9]{2}", $minutes)) $minutes = '0'.$minutes;
if (!eregi("[0-9]{2}", $hours)) $hours = '0'.$hours;
if ($weeks == 1) $weeks = $weeks .' Woche';
elseif ($weeks == 0) $weeks = '';
else $weeks = $weeks .' Wochen';
if ($days == 1) $days = $days .' Tag';
elseif ($days == 0) $days = '';
else $days = $days .' Tage';
if ($hours == 1) $hours = $hours .' Stunde';
elseif ($hours == 0) $hours = '';
else $hours = $hours .' Stunden';
if ($minutes == 1) $minutes = $minutes .' Minute';
elseif ($minutes == 0) $minutes = '';
else $minutes = $minutes .' Minuten';
if ($seconds == 1) $seconds = $seconds .' Sekunde';
else $seconds = $seconds .' Sekunden';
return $weeks.' '.$days.' '.$hours.' '.$minutes.' '.$seconds;
}
?> | true |
9b363a2b4e68741d42e12091625f3ee76e343d82 | PHP | montycheese/RecDawgs | /src/html/php/doEnterMatchScore.php | UTF-8 | 1,346 | 2.6875 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: montanawong
* Date: 4/23/16
* Time: 17:22
*/
session_start();
require_once("autoload.php");
use edu\uga\cs\recdawgs\logic\impl\LogicLayerImpl as LogicLayerImpl;
$logicLayer = new LogicLayerImpl();
//check to make sure none of the data is null or empty
foreach($_POST as $inputData){
if($inputData == "" or $inputData == null){
$errorMsg = urlencode("Missing form field");
header("Location: ../index.php?status={$errorMsg}");
exit();
}
}
try {
$match = $logicLayer->findMatch(null, $_POST['matchId'])->current();
$teamCaptain = $logicLayer->findStudent(null, $_SESSION['userId'])->current();
//assuming only the team captains can enter scores
$persistenceId = $logicLayer->enterMatchScore(
$teamCaptain,
$match,
intval(trim($_POST['homeTeamScore'])),
intval(trim($_POST['awayTeamScore'])));
$successMsg = urlencode("Scores input successfully!");
header("Location: ../index.php?status={$successMsg}");
echo $persistenceId;
}
catch(\edu\uga\cs\recdawgs\RDException $rde){
$errorMsg = urlencode($rde->string);
header("Location: ../index.php?status={$errorMsg}");
}
catch(Exception $e){
$errorMsg = urlencode("Unexpected error");
header("Location: ../index.php?status={$errorMsg}");
}
exit(); | true |
8e70a2c343de7fa636c66464e523533e9ce873ec | PHP | ecodevsolution/spk | /backend/models/TblPenggajian.php | UTF-8 | 903 | 2.515625 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
namespace backend\models;
use Yii;
/**
* This is the model class for table "tbl_penggajian".
*
* @property integer $idgaji
* @property string $idabsensi
* @property double $total_gaji
* @property string $tgl_gaji
*/
class TblPenggajian extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'tbl_penggajian';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['total_gaji'], 'number'],
[['tgl_gaji'], 'safe'],
[['idabsensi'], 'string', 'max' => 8],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'idgaji' => 'Idgaji',
'idabsensi' => 'Idabsensi',
'total_gaji' => 'Total Gaji',
'tgl_gaji' => 'Tgl Gaji',
];
}
}
| true |
48076fa51c32f113dabc5f02ccd934b214ab5a96 | PHP | MckeyHong/mk_gps | /app/Helpers/Website.php | UTF-8 | 2,078 | 2.71875 | 3 | [] | no_license | <?php
/* 系統常用函數 */
namespace App\Helpers;
use Validator;
use Config;
use Auth;
class Website
{
/**
* 取得導頁資料
* @param array $aParam
* @param string $sDefaultUrl
* @return string
*/
public static function getRedirect(array $aParam = array(), $sDefaultUrl = '')
{
if (count(Validator::make($aParam, array('_redirect' => 'required|url'))->errors()->all()) == 0) {
return $aParam['_redirect'];
} else {
return $sDefaultUrl;
}
}
/**
* 處理列表Get參數
* @param array $aParam
* @return array
*/
public static function handleGet(array $aParam = array())
{
$aGet = $aWhere = array();
$aError = Validator::make($aParam['get'], $aParam['format'])->messages();
foreach ($aParam['format'] as $sKey => $sVal) {
$aGet[$sKey] = ($aError->has($sKey)) ? '' : $aParam['get'][$sKey];
if ($sKey == 'c') {
$aWhere[$aParam['replace'][$sKey]] = $aGet[$sKey] != '' ? array($aGet[$sKey]) : $aParam['city'];
} else {
$aWhere[$aParam['replace'][$sKey]] = $aGet[$sKey];
}
}
$aWhere['per_page'] = Config::get('website.per_page');
return ['get' => $aGet, 'where' => $aWhere];
}
/**
* 取得資料要儲存的共同資訊(Ex.時間、人員)
* @param string $sType
* @return array
*/
public static function getSaveInfo($sType = '')
{
$sTime = time();
switch ($sType) {
case 'edit':
return [
'modify_date' => $sTime,
'modify_user' => Auth::user()->_id
];
break;
default:
return [
'create_date' => $sTime,
'create_user' => Auth::user()->_id,
'modify_date' => $sTime,
'modify_user' => Auth::user()->_id
];
break;
}
}
}
| true |
ffc81cecb843800d6f9667fe14e766ce910b7357 | PHP | pnikunj353/test | /api.php | UTF-8 | 1,775 | 2.515625 | 3 | [] | no_license | <?php
include('connection.php');
$jsonString = file_get_contents('php://input');
$jsonObj = json_decode($jsonString, true);
$data = $jsonObj;
if($data["mode"] == "login")
{
$name=$data['user_name'];
$pass=$data['password'];
$result = mysqli_query($mysqli,"SELECT user_id,user_name FROM pro1 where user_name='$name' and password='$pass'");
$arrResponse = array();
while($row = mysqli_fetch_assoc($result))
{
$arrResponse[] = $row;
}
if (!empty($arrResponse))
{
$response = array(
"status" => 1,
"message" => "Success",
"response" => $arrResponse
);
}
else
{
$response = array(
"status" => 0,
"message" => "No Data found",
"response" => $arrResponse
);
}
}
elseif($data["mode"] == "getprofile")
{
$id=$data['user_id'];
$result = mysqli_query($mysqli,"SELECT * FROM pro1 where user_id=$id");
$arrResponse = array();
while($row = mysqli_fetch_assoc($result))
{
$arrResponse[] = $row;
}
if (!empty($arrResponse))
{
$response = array(
"status" => 1,
"message" => "Success",
"response" => $arrResponse
);
}
else
{
$response = array(
"status" => 0,
"message" => "No Data found",
"response" => $arrResponse
);
}
}
else
{
$response = array(
"status" => 0,
"message" => "Invalid Mode",
"response" => ''
);
}
echo json_encode($response);
?>
| true |
f6e08d2b9d29c689fbc094fc5c6b3812b84199e2 | PHP | capons/clout-cron | /application/models/_network.php | UTF-8 | 1,187 | 2.546875 | 3 | [] | no_license | <?php
/**
* This class processes network business logic.
*
* @author Al Zziwa <al@clout.com>
* @version 1.3.2
* @copyright Clout
* @created 05/12/2015
*/
class _network extends CI_Model
{
# add user to the referrer network
function add_user_to_referrer_network($userId, $referrerId, $level)
{
log_message('info', '_score/add_user_to_referrer_network:: [1] ');
log_message('info', '_score/add_user_to_referrer_network:: [2] user_id:'.$userId.', referrer_id:'.$referrerId.', level: '.$level);
# add direct network
if($level == 'level_1') $result = $this->_query_reader->run('add_cached_direct_network_data', array('user_id'=>$userId, 'referrer_id'=>$referrerId));
# add other levels of the network
else {
$levelParts = explode('_',$level);
$result = $this->_query_reader->run('add_cached_other_network_data', array(
'user_id'=>$userId, 'referrer_id'=>$referrerId, 'this_network_level'=>$level,
'higher_network_level'=>'level_'.(array_pop($levelParts) - 1)
));
}
log_message('info', '_score/add_user_to_referrer_network:: [3] result: '.($result? 'SUCCESS': 'NONE'));
return array('result'=>($result? 'success': 'fail'));
}
}
?> | true |
648eccdef4e69b0b6bb450d461720d95db15a545 | PHP | Odilio/wdo-analytics-API | /examples/get-basic-data-about-opened-gap-market.php | UTF-8 | 1,177 | 2.953125 | 3 | [
"MIT"
] | permissive | <?php
/**
* Recubera dados basicos de dias com uma % maxima ou minimo de GAP de abertura de mercado
*
* File: get-basic-data-about-opened-gap-market.php
*
* @var \WDOAPI\WDOAPI $wdo Carrega a classe da API
* @var date<yyyy-mm-dd> $startDate Data que comeca de contar os candles
* @var date<yyyy-mm-dd> $endDate Data que termina de contar os candles
* @var string<min|max> $type Minimo|maximo de % no GAP de abertura do mercado
* @var float $osc OSC minima em relaxao ao GAP de abertura
* @var array $sgdbArrCandles Recupero os candles ja processados entre um intervalo de data
* @var array $retorno Recupera dos dados basicos de Niveis de OSC no proprio candle
*/
// Autoload dos arquivos de dependencia
include('../src/WDOAPI/autoload.php');
$wdo = new \WDOAPI\WDOAPI();
$startDate = '2017-08-01';
$endDate = '2017-12-01';
$osc = '0.2'; // 0.2% de oscilacao por exemplo
$type = "min";
$sgdbArrCandles = $wdo->listIntradayData( $startDate, $endDate );
$retorno = $wdo->checkBasicDataAboutGapAberturaOsc( $sgdbArrCandles, $osc, $type );
echo '<pre>';
print_r( $retorno );
echo '</pre>';
?> | true |
dc7929f8d91706cc9a41097f085e79b6a5ae1d8e | PHP | GuiemB/PHP-OOD | /OOD_5/student.php | UTF-8 | 381 | 3.125 | 3 | [] | no_license | <?php
class Student extends Person
{
private $studyField;
public function getstudyField()
{
return $this->studyField;
}
public function setStudyField($studyField)
{
$this->studyField=$studyField;
}
public function print()//overriding print method from parent class Person
{
parent::print();//calling print method from parent class Person
echo $this->studyField.'<br>';
}
}
?>
| true |
f2dab33548cf2b655dccc7a0d0e52627ddc012e2 | PHP | Daikichibana/colegioFinalDAW | /app/Http/Controllers/AulaController.php | UTF-8 | 1,312 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Aula;
use DB;
class AulaController extends Controller
{
public function index(Request $request){
$buscar= $request->buscar;
$buscar2= $request->buscar2;
if($buscar==''||$buscar2==''){
$Aula=Aula::all();
}
else{
$Aula=Aula::select('*')->whereBetween('capacidad',[$buscar, $buscar2])->get();
}
return $Aula;
}
public function store(Request $request){
$Aula = new Aula;
$Aula->descripcion=$request->descripcion;
$Aula->capacidad=$request->capacidad;
$Aula->save();
}
public function update(Request $request){
$Aula = Aula::findOrFail($request->id);
$Aula->descripcion=$request->descripcion;
$Aula->capacidad=$request->capacidad;
$Aula->save();
}
public function delete(Request $request){
$Aula = Aula::findOrFail($request->id);
$Aula->delete();
}
public function buscarAulaPorId(Request $request){
$buscar= $request->buscar;
if($buscar==''){
$Aula=Aula::all();
}
else{
$Aula=Aula::where('id','=', $buscar)
->get();}
return $Aula;
}
}
| true |
f87c30d1598ede414c86867494c2825369f2dd29 | PHP | alexperegrina/symfony-skeleton-full | /src/Auth/src/Application/Command/SetName/SetNameHandler.php | UTF-8 | 789 | 2.734375 | 3 | [] | no_license | <?php
declare(strict_types=1);
namespace Auth\Application\Command\SetName;
use AlexPeregrina\ValueObject\Domain\Identity\Uuid;
use AlexPeregrina\ValueObject\Domain\String\StringVO;
use AlexPeregrina\ValueObject\Domain\User\Name;
use Core\Domain\Messenger\Handler\CommandHandler;
class SetNameHandler implements CommandHandler
{
public function __construct(private SetNameService $service)
{}
public function __invoke(SetNameCommand $command): void
{
$name = new Name(
new StringVO($command->firstName()),
$command->middleName() ? new StringVO($command->middleName()) : null,
$command->lastName() ? new StringVO($command->lastName()) : null
);
$this->service->execute(new Uuid($command->id()), $name);
}
} | true |
a81783c4cb614ccb1ef6fcf9ba8f38f99d8e5fc6 | PHP | AaronJan/Housekeeper | /src/Housekeeper/Abilities/Cache/Statically/CacheAdapter.php | UTF-8 | 3,260 | 2.5625 | 3 | [
"Apache-2.0"
] | permissive | <?php
namespace Housekeeper\Abilities\Cache\Statically;
use Housekeeper\Contracts\Repository as RepositoryContract;
use Housekeeper\Contracts\Action as ActionContract;
use Illuminate\Contracts\Redis\Database as RedisContract;
use Housekeeper\Support\SmartHasher;
use Housekeeper\Abilities\Cache\Contracts\CacheAdapter as CacheAdapterContract;
/**
* Class CacheAdapter
*
* @package Housekeeper\Abilities\Cache\Statically
*/
class CacheAdapter implements CacheAdapterContract
{
/**
* @var \Illuminate\Contracts\Redis\Database|\Illuminate\Redis\Database
*/
protected $redis;
/**
* @var \Housekeeper\Contracts\Repository
*/
protected $repository;
/**
* @var string
*/
protected $prefix;
/**
* @var string
*/
protected $cacheKey;
/**
* CacheManager constructor.
*
* @param \Housekeeper\Contracts\Repository $repository
* @param \Illuminate\Contracts\Redis\Database $redis
* @param $configs
*/
public function __construct(RepositoryContract $repository,
RedisContract $redis,
array $configs)
{
$this->repository = $repository;
$this->redis = $redis;
$this->prefix = $configs['prefix'];
}
/**
* @return \Illuminate\Contracts\Redis\Database|\Illuminate\Redis\Database
*/
protected function getRedis()
{
return $this->redis;
}
/**
* @return \Housekeeper\Contracts\Repository
*/
protected function getRepository()
{
return $this->repository;
}
/**
* @param \Housekeeper\Contracts\Action $action
* @param $value
*/
public function setCacheForAction(ActionContract $action, $value)
{
$this->getRedis()->hset(
$this->cacheKey(),
$this->getCacheFieldForAction($action),
serialize($value)
);
}
/**
* @param \Housekeeper\Contracts\Action $action
* @return mixed|null
*/
public function getCacheForAction(ActionContract $action)
{
$cachedValue = $this->getRedis()->hget(
$this->cacheKey(),
$this->getCacheFieldForAction($action)
);
return is_null($cachedValue) ? null : unserialize($cachedValue);
}
/**
*
*/
public function flush()
{
$this->getRedis()->del($this->cacheKey());
}
/**
* @param \Housekeeper\Contracts\Action $action
* @return string
*/
protected function getCacheFieldForAction(ActionContract $action)
{
$id = md5(
SmartHasher::hash($this->getRepository()->getCurrentPlan()) .
$action->getMethodName() .
SmartHasher::hash($action->getArguments())
);
return $id;
}
/**
* @return string
*/
protected function cacheKey()
{
if ( ! $this->cacheKey) {
$this->cacheKey = $this->prefix .
str_replace(
'\\', '#',
get_class($this->getRepository())
);
}
return $this->cacheKey;
}
} | true |
4fa3d8a617fef7ea18a724844a231d237b41a168 | PHP | saltisgood/website | /lib/HTMLOutput.php | UTF-8 | 5,792 | 2.5625 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: Nick Stephen
* Date: 23/09/14
* Time: 2:34 PM
*/
include_once 'Content.php';
include_once 'Menus.php';
function strStartsWith($haystack, $needle)
{
$length = strlen($needle);
return (substr($haystack, 0, $length) === $needle);
}
function strEndsWith($haystack, $needle)
{
$length = strlen($needle);
if ($length == 0) {
return true;
}
return (substr($haystack, -$length) === $needle);
}
class HTML implements Output
{
const TITLE_SUF = ' - NickStephen.com';
public $content;
public $relPath = './';
public $thisPath = '';
public $canonicalLink;
function __construct()
{
$this->content = new Content();
}
public function write()
{
$this->writeHeader();
$this->writeBody();
}
public function writeHeader()
{
echo '<!DOCTYPE html><head>
<meta charset="UTF-8" />
<title>', $this->content->title;
if (!is_null($this->content->subtitle))
{
echo ' · ', $this->content->subtitle;
}
echo HTML::TITLE_SUF, '</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />';
if (!is_null($this->canonicalLink))
{
echo '<link rel="canonical" href="', $this->canonicalLink, '" />';
}
echo '
<link href="http://fonts.googleapis.com/css?family=Roboto:400,400italic,700,500" rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="/styles.css" />
<style> @media (min-width: 601px) { html { background: url(\'/img/back', rand(1,5), '.jpg\') no-repeat center center fixed; background-size: cover; } }</style>
<noscript><style> .scrpt { display: none; } .noscrpt { display: inline; } </style></noscript>',
"<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-46464874-1', 'auto');
ga('send', 'pageview');
</script>
</head>";
}
public function writeBody()
{
echo '<body>';
$this->content->write();
// Now the main dessert is finished, add the toppings.
if (strcmp($this->thisPath, './') == 0)
{
writeHeader(false, false);
}
else
{
writeHeader(strEndsWith($this->thisPath, 'index.php'));
}
$sideMenu = new SideMenu($this->relPath);
if (function_exists('setupMenu'))
{
setupMenu($sideMenu);
}
/* $path = explode('/', $this->thisPath);
$count = count($path);
if ($count >= 2 && strcmp($path[1], 'software') === 0)
{
$sideMenu->software->active = true;
if ($count >= 3 && strcmp($path[2], 'android') === 0)
{
if ($count >= 3 && strcmp($path[2], 'oaa') === 0)
{
$sideMenu->software->subItems[0]->active = true;
if ($count >= 4)
{
if (strcmp($path[3], 'index.php') === 0)
{
$sideMenu->software->subItems[0]->subItems[0]->active = true;
} else if (strcmp($path[3], 'download.php') === 0)
{
$sideMenu->software->subItems[0]->subItems[1]->active = true;
} else if (strcmp($path[3], 'help.php') === 0)
{
$sideMenu->software->subItems[0]->subItems[2]->active = true;
} else if (strcmp($path[3], 'source.php') === 0)
{
$sideMenu->software->subItems[0]->subItems[3]->active = true;
}
}
}
else if ($count >= 3 && strcmp($path[2], 'snap') === 0)
{
$sideMenu->software->subItems[1]->active = true;
if ($count >= 4)
{
if (strcmp($path[3], 'index.php') === 0)
{
$sideMenu->software->subItems[1]->subItems[0]->active = true;
} else if (strcmp($path[3], 'download.php') === 0)
{
$sideMenu->software->subItems[1]->subItems[1]->active = true;
} else if (strcmp($path[3], 'help.php') === 0)
{
$sideMenu->software->subItems[1]->subItems[2]->active = true;
} else if (strcmp($path[3], 'source.php') === 0)
{
$sideMenu->software->subItems[1]->subItems[3]->active = true;
}
}
}
}
}
else if ($count == 2 && strcmp($path[1], 'contact.php') === 0)
{
$sideMenu->contact->active = true;
}
else if ($count == 3 && strcmp($path[1], 'blog') === 0 && strcmp($path[2], 'index.php') === 0)
{
$sideMenu->blog->active = true;
} */
writeSideMenu($sideMenu);
writeFooter($sideMenu, $this->content->title);
echo '<div id="bg"></div><script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" defer></script>
<script type="text/javascript" src="/scripts.js" defer></script></body>';
}
} | true |
693259d863a88165a30c02bd036ccc5ecb8da68d | PHP | Starbugstone/ADListing | /dumpGroupe.php | UTF-8 | 4,150 | 2.640625 | 3 | [] | no_license | <?php
header("X-UA-Compatible: IE=Edge");
if(!isset($_SESSION))
{
session_start();
}
include 'php/config.php';
include 'php/functions.php';
// connect
$ldapconn = ldap_connect($ldapserver) or die("Could not connect to LDAP server.");
if($ldapconn) {
// Adding options
ldap_set_option ($ldapconn, LDAP_OPT_REFERRALS, 0);
ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
// binding to ldap server
$ldapbind = ldap_bind($ldapconn, $ldapuser, $ldappass) or die ("Error trying to bind: ".ldap_error($ldapconn));
// verify binding
if ($ldapbind) {
//recupere variable passé dans URL
//on fait un choix de filtre en fonction de ceux qu'on passe comme paramettre. Le resultat est toujours un seul utilisateurs car ces données doivent etre uniques dans AD
if (isset($_GET['dn'])){
$dn=$_GET['dn'];
$dn=escapeLdapFilter($dn);
$filter = "(&(objectCategory=group)(distinguishedname=$dn))";
}elseif (isset($_GET['id'])){
$id=$_GET['id'];
//filter on ID
$filter = "(&(objectCategory=group)(sAMAccountName=$id))";
}elseif (isset($_GET['dispName'])){
$dispName = $_GET['dispName'];
$filter = "(&(objectCategory=group)(displayname=$dispName))";
}
else{
echo("<h1>erreur de filtre</h1>");
}
//Getting results
$result = ldap_search($ldapconn,$ldaptree, $filter) or die ("Error in search query: ".ldap_error($ldapconn));
$data = ldap_get_entries($ldapconn, $result);
if (!isset($data[0])){
//bug in IE with utf-8 encoding
$filter = utf8_encode($filter);
$result = ldap_search($ldapconn,$ldaptree, $filter) or die ("Error in search query: ".ldap_error($ldapconn));
$data = ldap_get_entries($ldapconn, $result);
//echo $filter;
}
//grab all our required info
//1st pannel
$samaccountname = $data[0]['samaccountname'][0];
$cn = getOr($data[0]['cn'][0],$samaccountname);
$fullDn = $data[0]['dn'];
//$mail = getOr($data[0]['mail'][0],"Aucun mail");
if (isset($data[0]['mail'][0])){
$mail = $data[0]['mail'][0]."<a href=\"mailto:".$data[0]['mail'][0]."\"><i class='fa fa-envelope-o secIcon' aria-hidden='true' title='Envoyer Mail'></i></a>";
}else{
$mail = "Aucun mail";
}
if(isset($data[0]['managedby'][0])){
$managedby = "<a href=\"detailCompte.php?dn=".$data[0]['managedby'][0]."\">".explodeCN($data[0]['managedby'][0])."</a>";
}
else{
$managedby ="Pas de Gestionnaire";
}
$description = getOr($data[0]["description"][0], "Pas de description");
//2nd pannel
if (isset($data[0]['member'])){
$members = $data[0]['member'];
array_shift($members); //get rid of dead line
$memberCount = "( ".$data[0]['member']['count']." )";
//asort($members); //alphanum sorting
natcasesort($members);
$memberNoError = TRUE;
}
else{
$members = "Aucun Membre";
$memberCount = "";
$memberNoError = FALSE;
}
} else {
echo "LDAP bind failed...";
}
}
?>
<!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">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="font-awesome-4.6.3/css/font-awesome.min.css">
<title>Compte - <?php echo($cn); ?></title>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<?php include 'favicon.php'; ?>
<link href="css/ripple.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<link href="css/print.css" rel="stylesheet">
</head>
<body>
<?php
echo '<h1>Dump all data</h1><pre>';
print_r($data);
echo '</pre>';
?>
</body>
</html>
| true |
788b730a815049e176334563c0ab19a9c625112f | PHP | dxwalter/digital-earners | /service/objects/investment.php | UTF-8 | 16,662 | 2.921875 | 3 | [] | no_license | <?php
include_once 'BaseFunction.php';
class Investment extends BaseFunction{
public $id;
public $userId;
public $capital;
public $roi;
public $binaryDate = 0;
public $dateOfUpload;
public $timeOfUpload;
/**
* The profile picture here stands for proof of payment.
* Because of the imageProcessor library that collects
* an object of a class a paramenter, I had to set the proof of
* payment to profile picture which is the same in the customer class.
*/
public $profilePicture;
public $receiptStatus;
public $roiPaymentStatus;
private $dbConnection;
private $tableName = 'investment';
public function __construct($dbObject)
{
$this -> dbConnection = $dbObject;
}
public function createInvestment()
{
$queryString = "INSERT INTO ".$this -> tableName." (id, userid, capital, roi, upload_date, upload_time, binary_date, proof_of_payment, receipt_status, roi_payment_status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$query = $this -> dbConnection -> prepare($queryString);
$query -> execute([
"",
$this -> userId,
$this -> capital,
$this -> roi,
$this -> dateOfUpload,
$this -> timeOfUpload,
$this -> binaryDate,
$this -> profilePicture,
$this -> receiptStatus,
$this -> roiPaymentStatus
]);
return $query -> rowCount();
}
public function getPaymentDate()
{
$sixteenDays = 17 * 86400;
$currentTime = [
"hour" => date('H'),
"min" => date("i")
];
$currenthour = $currentTime["hour"];
$currentMinute = $currentTime["min"];
if ($currentMinute > 0) {
$currentMinute = $currentMinute + (60 - $currentMinute);
} else {
$currentMinute = 0;
}
if ($currentMinute == 60) {
$currenthour = $currenthour + 1;
}
if ($currenthour > 0) {
$currenthour = (23 - $currenthour) + 1;
} else {
$currenthour = 0;
}
// convert current hour to seconds
$currenthourToSecond = (60 * $currenthour) * 60;
// Payday
$payday = strtotime('now') + $sixteenDays + $currenthourToSecond;
// return $payday;
$dateToPay = explode(" ", date("l j m Y H i s A", $payday));
$yearTopay = $dateToPay[3];
$monthTopay = $dateToPay[1];
$dayToPay = $dateToPay[2];
$mainPayDay = mktime(0, 0, 0, $dayToPay, $monthTopay, $yearTopay);
return $mainPayDay;
// Take note of this script, it's what you'll use in knowing whren to pay
// $dateTopay = date_create(date('d-m-Y', $payday));
// echo date_format($dateTopay, "l j F, Y H:i:s");
// $dateToPay = print_r(explode(" ", date("l j F Y H i s A", $payday)));
// print_r($dateToPay);
// die();
}
public function calculatepaydayremainin()
{
# code...
//
// $now = strtotime('now');
// $countdayUnix = $payday - $now;
// echo floor($countdayUnix / 86400);
}
public function confirmInvestment()
{
$query = $this -> dbConnection -> prepare("
UPDATE ".$this -> tableName."
SET binary_date = :binaryDate, receipt_status = :confirmReceipt WHERE id = :id AND userid = :userId LIMIT 1
");
$confirmReceipt = 1;
$query -> bindParam(":binaryDate", $this -> binaryDate);
$query -> bindParam(":confirmReceipt", $confirmReceipt);
$query -> bindParam(":id", $this -> id);
$query -> bindParam(":userId", $this -> userId);
$query -> execute();
return $query -> rowCount();
}
public function getInvestmentDetails($investmentId)
{
$query = $this -> dbConnection -> prepare(
"SELECT * FROM ".$this -> tableName." WHERE id = :id LIMIT 1"
);
$query -> bindParam(":id", $investmentId);
$query -> execute();
if ($query -> rowCount()) {
$row = $query -> fetch(PDO::FETCH_ASSOC);
return $row;
} else {
return false;
}
}
public function paymentCashout()
{
$paymentStatus = 1;
$query = $this -> dbConnection -> prepare(
"UPDATE ".$this -> tableName."
SET
roi_payment_status = :paymentStatus
WHERE
userid = :userId AND id = :id
LIMIT 1
"
);
$query -> bindParam(":paymentStatus", $paymentStatus);
$query -> bindParam(":userId", $this -> userId);
$query -> bindParam(":id", $this -> id);
$query -> execute();
return $query -> rowCount();
}
public function getUncategorisedHistory($count)
{
if ($count == "all") {
$limit = "";
} else {
$limit = "LIMIT ".$count."";
}
$one = 1;
$query = $this -> dbConnection -> prepare("
SELECT * FROM ".$this -> tableName."
WHERE userid = :userId AND receipt_status = :receiptStatus ORDER BY id DESC ".$limit."
");
$query -> bindParam(":userId", $this -> userId);
$query -> bindParam(":receiptStatus", $one);
$query -> execute();
return $query;
}
public function getRunningHistory()
{
// This method is to get all the
// investment that is still running
// the criteria will be when roi_payment_status field
// is equal to zero
$zero = 0;
$one = 1;
$query = $this -> dbConnection -> prepare("
SELECT * FROM ".$this -> tableName."
WHERE
userid = :userId AND roi_payment_status = :zero AND receipt_status = :receiptStatus
ORDER BY id DESC
");
$query -> bindParam(":userId", $this -> userId);
$query -> bindParam(":zero", $zero);
$query -> bindParam(":receiptStatus", $one);
$query -> execute();
return $query;
}
public function getCompletedHistory()
{
// This method is to get all the
// investment that is still running
// the criteria will be when roi_payment_status field
// is equal to zero
$one = 1;
$query = $this -> dbConnection -> prepare("
SELECT * FROM ".$this -> tableName."
WHERE
userid = :userId AND roi_payment_status = :one
ORDER BY id DESC
");
$query -> bindParam(":userId", $this -> userId);
$query -> bindParam(":one", $one);
$query -> execute();
return $query;
}
public function latestRunningInvestment()
{
$zero = 0;
$query = $this -> dbConnection -> prepare(
"
SELECT capital, roi, id FROM ".$this -> tableName."
WHERE
userid = :userId AND roi_payment_status = :zero
ORDER BY id DESC LIMIT 1
"
);
$query -> bindParam(":userId", $this -> userId);
$query -> bindParam(":zero", $zero);
$query -> execute();
return $query;
}
public function totalRoiToBePaid()
{
$receiptStatus = 1;
$roiPaymentStatus = 0;
$query = $this -> dbConnection -> prepare(
"
SELECT SUM(roi) FROM ".$this -> tableName."
WHERE receipt_status = :receiptStatus AND roi_payment_status = :roiPaymentStatus"
);
$query -> bindParam(":receiptStatus", $receiptStatus);
$query -> bindParam(":roiPaymentStatus", $roiPaymentStatus);
$query -> execute();
return $query;
}
public function totalRoiEarned()
{
$receiptStatus = 1;
$roiPaymentStatus = 1;
$query = $this -> dbConnection -> prepare(
"
SELECT SUM(roi) FROM ".$this -> tableName."
WHERE
userid = :userId
AND
receipt_status = :receiptStatus
AND
roi_payment_status = :roiPaymentStatus
"
);
$query -> bindParam(":userId", $this -> userId);
$query -> bindParam(":receiptStatus", $receiptStatus);
$query -> bindParam(":roiPaymentStatus", $roiPaymentStatus);
$query -> execute();
return $query;
}
public function totalInvestmentCapital()
{
$query = $this -> dbConnection -> prepare(
"SELECT SUM(capital) FROM ".$this -> tableName.""
);
$query -> execute();
return $query;
}
public function totalUserInvestmentCapital($investorId)
{
$receiptStatus = 1;
$query = $this -> dbConnection -> prepare(
"
SELECT SUM(capital) FROM ".$this -> tableName."
WHERE userid = :userId AND receipt_status = :receiptStatus
"
);
$query -> bindParam(":receiptStatus", $receiptStatus);
$query -> bindParam(":userId", $investorId);
$query -> execute();
return $query;
}
public function totalActiveInvestment()
{
$receiptStatus = 1;
$roiPaymentStatus = 0;
$query = $this -> dbConnection -> prepare(
"SELECT SUM(capital) FROM ".$this -> tableName." WHERE receipt_status = :receiptStatus AND roi_payment_status = :roiPaymentStatus"
);
$query -> bindParam(":receiptStatus", $receiptStatus);
$query -> bindParam(":roiPaymentStatus", $roiPaymentStatus);
$query -> execute();
return $query;
}
public function totalUnconfirmedInvestments()
{
$zero = 0;
$query = $this -> dbConnection -> prepare("
SELECT COUNT(id) as count FROM ".$this -> tableName."
WHERE
receipt_status = :receiptStatus
");
$query -> bindParam(":receiptStatus", $zero);
$query -> execute();
return $query;
}
public function deleteInvestment()
{
$query = $this -> dbConnection -> prepare("
DELETE FROM ".$this -> tableName."
WHERE
id = :investmentId AND userid = :investorId
LIMIT 1
");
$query -> bindParam(":investmentId", $this -> id);
$query -> bindParam(":investorId", $this -> userId);
$query -> execute();
return $query -> rowCount();
}
public function getListOfPayableInvestors($today)
{
$binaryDate = $today;
$roiStatus = 0;
$invReceiptStat = 1;
$query = $this -> dbConnection -> prepare(
"
SELECT
customer.fullname, customer.profile_picture, investment.*
FROM
investment
INNER JOIN
customer
ON
investment.userid = customer.userid
WHERE
investment.binary_date <= :binaryDate AND `roi_payment_status` = :roiStatus AND investment.receipt_status = :invReceiptStat
ORDER BY
investment.id ASC
"
);
$query -> bindParam(":binaryDate", $binaryDate);
$query -> bindParam(":roiStatus", $roiStatus);
$query -> bindParam(":invReceiptStat", $invReceiptStat);
$query -> execute();
return $query;
}
public function getUnconfirmedInvestments($countType)
{
$zero = 0;
if ($countType == "all") {
$queryString = "
SELECT
customer.fullname, customer.profile_picture, investment.*
FROM
investment
INNER JOIN
customer
ON
investment.userid = customer.userid
WHERE
investment.receipt_status = :zero
ORDER BY
investment.id ASC
";
} else{
$queryString = "
SELECT
customer.fullname, customer.profile_picture, investment.*
FROM
investment
INNER JOIN
customer
ON
investment.userid = customer.userid
WHERE
investment.receipt_status = :zero
ORDER BY
investment.id ASC
LIMIT
$countType
";
}
$query = $this -> dbConnection -> prepare($queryString);
$query -> bindParam(':zero', $zero);
$query -> execute();
return $query;
}
public function getTotalNumberOfNewInvestments()
{
$totalUnconfirmedInvestments = $this -> totalUnconfirmedInvestments();
$unconfirmedRow = $totalUnconfirmedInvestments->fetch(PDO::FETCH_ASSOC);
$summedUnconfirmedInvestment = $unconfirmedRow["count"];
return $summedUnconfirmedInvestment;
}
public function getInvestmentListing($investmentDate)
{
$receiptStatus = 1;
$query = $this -> dbConnection -> prepare("
SELECT
customer.fullname, customer.profile_picture, investment.*
FROM
".$this -> tableName."
INNER JOIN
customer
ON
investment.userid = customer.userid
WHERE
investment.upload_date = :dateOfUpload AND receipt_status = :receiptStatus
ORDER by investment.id DESC
");
$query -> bindParam(":dateOfUpload", $investmentDate);
$query -> bindParam(":receiptStatus", $receiptStatus);
$query -> execute();
return $query;
}
public function getPayoutInvestmentListing($payoutDate)
{
$query = $this -> dbConnection -> prepare("
SELECT
customer.fullname, customer.profile_picture, investment.*
FROM
".$this -> tableName."
INNER JOIN
customer
ON
investment.userid = customer.userid
WHERE
investment.binary_date = :dateOfpayment
ORDER by investment.id DESC
");
$query -> bindParam(":dateOfpayment", $payoutDate);
$query -> execute();
return $query;
}
}
| true |
4c83ec57951cbe6ab15292ab0a4f255793aa0cea | PHP | anaya66/mvccode | /tests/UserTest.php | UTF-8 | 3,569 | 2.53125 | 3 | [] | no_license | <?php
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Tests\TestCase;
use App\User;
class UserTest extends TestCase
{
/**
* A basic test example.
*
* @return void
*/
public function test_user_can_signup()
{
DB::table('users')->delete(1000000);
DB::table('users')->insert(['id'=>1000000,
'name' => 'ananya1',
'email' => 'ananya6@gmail.com',
'password' => bcrypt('ananya1')
]);
$User= DB::table('users')->where('email','ananya6@gmail.com')->get();
if(isset($User) && count($User)) {
$this->assertTrue(true);
}
}
public function test_user_can_login()
{
DB::table('users')->delete(1000000);
DB::table('users')->insert(['id'=>1000000,
'name' => 'ananya1',
'email' => 'ananya6@gmail.com',
'password' => bcrypt('ananya1')
]);
$credential = [
'email' => 'user@ad.com',
'password' => 'incorrectpass',
];
$response = $this->post('login',$credential);
$response->assertSessionHasErrors();
}
public function test_admin_can_login()
{
DB::table('users')->delete(1000001);
DB::table('users')->insert(['id'=>1000001,
'name' => 'admin2',
'email' => 'admin2@gmail.com',
'password' => bcrypt('admin')
]);
DB::table('roles')->delete(1);
DB::table('roles')->insert([
'name' => 'admin',
'id'=>1
]);
DB::table('role_user')-> where('user_id',1000001)->limit(1)->delete();
DB::table('role_user')->insert([
'user_id' => 1000001,
'role_id'=>1
]);
$credential = [
'email' => 'user@ad.com',
'password' => 'incorrectpass'
];
$response = $this->post('login',$credential);
$response->assertSessionHasErrors();
}
public function test_admin_can_create_category()
{
DB::table('categories')->delete(1000001);
$category= DB::table('categories')->insert(['id'=>1000001,
'name' => 'testcategory',
'status' => '1',
]);
if(isset($category)){
$this->assertTrue(true);
}
}
public function test_admin_can_create_subjects()
{
DB::table('subjects')->delete(1000001);
$subject= DB::table('subjects')->insert(['id'=>1000001,
'name' => 'test',
'status' => '1',
'category_id'=> 1000001,
'duration'=>40,
]);
if(isset($subject)){
$this->assertTrue(true);
}
}
/**public function admin_can_create_questions()
{
DB::table('questions')->delete(1000001);
$question= DB::table('questions')->insert(['id'=>1000001,
'subject_id' => 1000001,
'option_1'=>'1',
'option_2'=>'2',
'option_3'=>'3',
'option_4'=>'4',
'answer'=>2,
]);
if(isset($question)){
$this->assertTrue(true);
}
}
/* public function admin_can_create_questions()
{
DB::table('questions')->delete(1000001);
$question= DB::table('questions')->insert(['id'=>1000001,
'subject_id' => 1000001,
'option_1'=>'1',
'option_2'=>'2',
'option_3'=>'3',
'option_4'=>'4',
'answer'=>2,
'update_at'=>'2021-09-21 00:00:00',
]);
if(isset($question)){
$this->assertTrue(true);
}
}
*/
}
| true |
aa7b95314e5e7e9a0af37766d3852af30473fe07 | PHP | Awsme/TM-RU | /marathon14/Application.php | UTF-8 | 2,240 | 2.6875 | 3 | [] | no_license | <?php
/**
* Created by JetBrains PhpStorm.
* @author vandamm
* Date: 15.05.12
* Time: 19:19
*/
class Moto_Application
{
protected $routePrefix;
protected $prefix;
protected $fromEmail = 'ru@templatemonster.com';
protected $fromName = 'Почтовый робот ТМ Russia';
public function __construct()
{
//$this->prefix = $prefix = Database::instance()->table_prefix();;
$this->prefix = "";
}
/**
* Route the request
* @return bool
*/
public function route()
{
try
{
if (preg_match('#/' . $this->routePrefix . '/(\w+)/#', $_SERVER['REQUEST_URI'], $matches)
&& method_exists($this, $matches[1]))
{
$result = call_user_func(array($this, $matches[1]));
if (!empty($result))
{
return json_encode($result);
}
}
}
catch (Exception $e)
{
$this->redirect();
}
return false;
}
/**
* Redirect in case of errors
*/
protected function redirect()
{
header('Location: /ru/' . $this->routePrefix . '/');
exit;
}
public function setSenderInfo($info = array())
{
$this->fromEmail = isset($info['fromEmail']) ? $info['fromEmail'] : $this->fromEmail;
$this->fromName = isset($info['fromName']) ? $info['fromName'] : $this->fromName;
}
/**
* Send actual email
* @param $email
* @param $subject
* @param $text
* @return array
*/
protected function sendEmail($email, $subject, $text, $tr = null)
{
$mail = new Zend_Mail('UTF-8');
$mail->setFrom($this->fromEmail, $this->fromName);
$mail->addTo($email);
$mail->setSubject($subject);
$mail->setBodyHtml($text);
if (strpos($_SERVER['HTTP_HOST'], '.fmt'))
{
$tr = new Zend_Mail_Transport_Smtp('192.168.5.23');
}
// $tr = new Zend_Mail_Transport_Sendmail();
//$tr = new Zend_Mail_Transport_Smtp();
try
{
$mail->send($tr);
return array('success' => true);
}
catch (Exception $e)
{
return array('error' => $e->getMessage());
}
}
protected function isValidMail( $mail = '' )
{
return $mail && filter_var($mail, FILTER_VALIDATE_EMAIL);
}
protected function motoLog(Exception $e)
{
$path = CURRENT_THEME_DIR . '/motolog.txt';
file_put_contents($path, date("Y-m-d H:i:s") . ' ' . $e->getMessage() . "\n\n", FILE_APPEND);
}
}
| true |
97ba73fd8deeace86a586f376eb3b9790a1f29ad | PHP | dbsengineering/GSB | /controleurs/c_enregistreDonn.php | UTF-8 | 2,745 | 2.890625 | 3 | [] | no_license | <?php
/**
* c_enregistreDonn.php
*/
/**
* Controleur qui enregistre, modifie, et rembourse les frais
* Suivant le numéro qui est passé en paramètre, une procédure intervient.
* En plus, une fonction qui retourne les tarifs.
*
* PHP version 5.5.12
*
* @category Controleurs
* @package Controleurs
* @author Cavron Jérémy
* @copyright 2014-2015 CAVRON Jérémy
* @version v 1.0
*/
require_once('../include/class.pdogsb.inc.php');
if(isset($_POST['postNumFunc'])){
$numFunction = $_POST['postNumFunc'];
switch ($numFunction){
case "0":
valider();
break;
case "1":
rembourser();
break;
case "2":
modifier();
break;
}
}
/**
* Procédure de validation.
*
* @package controleurs
*/
function valider(){
if(isset($_POST['postId']) && isset($_POST['postJustif']) &&
isset($_POST['postMois'])){
$idVis = $_POST['postId'];
$nbJustif = $_POST['postJustif'];
$annMois = $_POST['postMois'];
PdoGsb::getPdoGsb()->majNbJustificatifs($idVis, $annMois, $nbJustif);
//Mise à jour de l'état, du montant de la fiche de frais
PdoGsb::getPdoGsb()->majEtatFicheFraisJustMont($idVis, $annMois, 'VA');
$montant = PdoGsb::getPdoGsb()->getLesInfosFicheFrais($idVis, $annMois);
echo ($montant[3]);
}
}
/**
* Procédure de remboursement.
*
* @package controleurs
*/
function rembourser() {
if(isset($_POST['postId']) && isset($_POST['postMois'])){
$idVis = $_POST['postId'];
$annMois = $_POST['postMois'];
PdoGsb::getPdoGsb()->majEtatFicheFrais($idVis, $annMois, 'RB');
}
}
/**
* Procédure de modification frais Forfait et le nombre de justificatifs.
*
* @package controleurs
*/
function modifier(){
if(isset($_POST['postId']) && isset($_POST['postMois']) &&
isset($_POST['postTabFrais']) && isset($_POST['postJustif'])){
$listeRecup = json_decode($_POST['postTabFrais']);
$rep = $listeRecup[0];
$nuit = $listeRecup[1];
$km = $listeRecup[3];
$etp = $listeRecup[2];
$idVis = $_POST['postId'];
$nbJustif = $_POST['postJustif'];
$annMois = $_POST['postMois'];
$listeFrais = array('REP' => $rep,'NUI' => $nuit,'KM' => $km,'ETP' => $etp);
//Mise à jour du nombre de justificatifs
PdoGsb::getPdoGsb()->majNbJustificatifs($idVis, $annMois, $nbJustif);
//On envoie seulement les frais Forfait
//Mise à jour des forfait
PdoGsb::getPdoGsb()->majFraisForfait($idVis, $annMois, $listeFrais);
}
}
?> | true |
179071a8873abbe17f9c1d27120adaff305d69a1 | PHP | mylow/lucalight | /sidebar.php | UTF-8 | 637 | 2.625 | 3 | [] | no_license | <?php
if(is_page()) {
if($post->post_parent){// check if page is parent...
echo '<h3>'.get_the_title($post->post_parent).'</h3>';
echo '<ul>';
wp_list_pages(array('title_li' => '', 'child_of' => $post->post_parent,)); //... list current page
echo '</ul>';
} else { // if page does not have a parent...
echo '<h3>'.get_the_title($post->ID).'</h3>';
echo '<ul>';
wp_list_pages(array('title_li' => '', 'child_of' => $post->ID,));// ... do this
echo '</ul>';
}
?> | true |
8f22480379b6a65cd97ccb97fcda0688e5aa5718 | PHP | C0mkid/IronBot | /includes/functions_configs.php | UTF-8 | 821 | 2.640625 | 3 | [] | no_license | <?php
class configs
{
// @TODO: Rewrite configs class
public function loadConfig($name)
{
global $config, $phpEx, $root_path;
include($root_path . 'includes/configs/config_' . $name . '.' . $phpEx);
// merge values with arrays together
foreach ($config[$name] as $setting => $value)
{
if (array_key_exists($setting, $config['global']) && is_array($config['global'][$setting]))
{
if (!is_array($value))
{
$array = array($value);
}
else
{
$array = $value;
}
$server[$setting] = array_merge($config['global'][$setting], $array);
}
}
$config = array_merge($config['global'], $config[$name], $config);
}
public function loadConfigs()
{
foreach (func_get_args() as $arg)
{
$this->loadConfig($arg);
}
}
} | true |
3126817eaf1c3b1a8f85e0119d87a486e00b23f6 | PHP | esyede/hexazor | /system/Libraries/Hash/Hash.php | UTF-8 | 1,589 | 3.015625 | 3 | [
"MIT"
] | permissive | <?php
namespace System\Libraries\Hash;
defined('DS') or exit('No direct script access allowed.');
use Exception;
class Hash
{
/**
* Buat hash password.
*
* @param string $value
* @param array $options
*
* @return string
*/
public function make($value, array $options = [])
{
// skip deprecation warning di PHP 7.0.0+
// ref: https://www.php.net/manual/en/function.password-hash.php
unset($options['salt']);
if (!isset($options['cost'])) {
$options['cost'] = PASSWORD_BCRYPT_DEFAULT_COST;
}
$hashed = password_hash($value, PASSWORD_DEFAULT, $options);
if (!is_string($hashed)) {
throw new Exception('Malformatted password hash result.');
}
return $hashed;
}
/**
* Cocokkan string password dengan hash-nya.
*
* @param string $value
* @param string $hashed
*
* @return bool
*/
public function check($value, $hashed)
{
return password_verify($value, $hashed);
}
/**
* Cek kekuatan hash berdasarkan cost yang diberikan.
*
* @param string $hashed
* @param array $options
*
* @return bool
*/
public function needsRehash($hashed, array $options = [])
{
// skip deprecation warning di PHP 7.0.0+
unset($options['salt']);
if (!isset($options['cost'])) {
$options['cost'] = PASSWORD_BCRYPT_DEFAULT_COST;
}
return password_needs_rehash($hashed, PASSWORD_DEFAULT, $options);
}
}
| true |
753cc47c7dfec31b33a15bc9b19fa7c8093165c8 | PHP | technodelight/bytes-in-human | /src/BytesInHuman.php | UTF-8 | 990 | 3.25 | 3 | [
"MIT"
] | permissive | <?php
namespace Technodelight\BytesInHuman;
class BytesInHuman
{
const BASE = 1024;
private $bytes = 0;
public static function fromBytes($bytes)
{
$instance = new self;
$instance->bytes = (int) $bytes;
return $instance;
}
public function asString()
{
switch (true) {
case $this->bytes >= self::BASE && $this->bytes < pow(self::BASE, 2):
return sprintf('%.2fK', $this->bytes / self::BASE);
case $this->bytes >= pow(self::BASE, 2) && $this->bytes < pow(self::BASE, 3):
return sprintf('%.2fM', $this->bytes / pow(self::BASE, 2));
case $this->bytes >= pow(self::BASE, 3):
return sprintf('%.2fG', $this->bytes / pow(self::BASE, 3));
default:
return sprintf('%dB', $this->bytes);
}
}
public function __toString()
{
return $this->asString();
}
protected function __construct() {}
}
| true |
d60c2dfb61bd96ed0ed4f6c0440051df347da791 | PHP | Kaoxlaw/phpExercicesSeptember | /vtc/models/models.php | UTF-8 | 1,038 | 3.125 | 3 | [] | no_license | <?php
class Models
{
public static function getConnection()
{
try {
$bdd = new PDO(
'mysql:host=localhost;dbname=vtc',
"afpaphp",
"afpaphp"
);
} catch (PDOException $e) {
print "Erreur";
}
return $bdd;
}
public function findById($id, $table)
{
$bdd = $this->getConnection();
$sql = $bdd->prepare(" SELECT * FROM $table WHERE id_" . $table . " = " . $id);
$sql->execute();
$result = $sql->fetchAll(PDO::FETCH_CLASS, $table);
return $result;
}
public function display($table)
{
$bdd = $this->getConnection();
$sql = $bdd->prepare(" SELECT * FROM $table ");
$sql->execute();
$result = $sql->fetchAll(PDO::FETCH_CLASS, $table);
return $result;
}
public function deleteById($id, $table)
{
$bdd = $this->getConnection();
$sql = $bdd->prepare(" DELETE FROM $table WHERE id_" . $table . " = " . $id);
if (!$sql->execute()) {
die("Not WOrking Bro!");
}
header("Location: index.php");
}
}
| true |
1bff3542cef50259d0efb2a1de730382ba02a1a5 | PHP | besrabasant/tailwind-issue | /web/app/plugins/github-updater/src/GitHub_Updater/API/Language_Pack_API.php | UTF-8 | 3,982 | 2.75 | 3 | [
"GPL-2.0-or-later",
"MIT",
"GPL-2.0-only"
] | permissive | <?php
/**
* GitHub Updater
*
* @author Andy Fragen
* @license GPL-2.0+
* @link https://github.com/afragen/github-updater
* @package github-updater
*/
namespace Fragen\GitHub_Updater\API;
use Fragen\GitHub_Updater\API;
use Fragen\GitHub_Updater\Traits\GHU_Trait;
/**
* Class Language_Pack_API
*/
class Language_Pack_API extends API {
use GHU_Trait;
/**
* Holds loose class method name.
*
* @var null
*/
public static $method = 'translation';
/**
* Constructor.
*
* @param \stdClass $type
*/
public function __construct( $type ) {
parent::__construct();
$this->type = $type;
$this->response = $this->get_repo_cache();
}
/**
* Get/process Language Packs.
*
* @param array $headers Array of headers of Language Pack.
*
* @return bool When invalid response.
*/
public function get_language_pack( $headers ) {
$response = ! empty( $this->response['languages'] ) ? $this->response['languages'] : false;
$type = explode( '_', $this->type->type );
if ( ! $response ) {
$response = $this->get_language_pack_json( $type[0], $headers, $response );
if ( $response ) {
foreach ( $response as $locale ) {
$package = $this->process_language_pack_package( $type[0], $locale, $headers );
$response->{$locale->language}->package = $package;
$response->{$locale->language}->type = $type[1];
$response->{$locale->language}->version = $this->type->local_version;
}
$this->set_repo_cache( 'languages', $response );
} else {
return false;
}
}
$this->type->language_packs = $response;
return true;
}
/**
* Get language-pack.json from appropriate host.
*
* @param string $type ( github|bitbucket|gitlab ).
* @param array $headers
* @param mixed $response API response.
*
* @return array|bool|mixed
*/
private function get_language_pack_json( $type, $headers, $response ) {
switch ( $type ) {
case 'github':
$response = $this->api( '/repos/' . $headers['owner'] . '/' . $headers['repo'] . '/contents/language-pack.json' );
$contents = base64_decode( $response->content );
$response = json_decode( $contents );
break;
case 'bitbucket':
$response = $this->api( '/1.0/repositories/' . $headers['owner'] . '/' . $headers['repo'] . '/src/master/language-pack.json' );
$response = json_decode( $response->data );
break;
case 'gitlab':
$id = urlencode( $headers['owner'] . '/' . $headers['repo'] );
$response = $this->api( '/projects/' . $id . '/repository/files/language-pack.json' );
$contents = base64_decode( $response->content );
$response = json_decode( $contents );
break;
case 'gitea':
$response = $this->api( '/repos/' . $headers['owner'] . '/' . $headers['repo'] . '/raw/master/language-pack.json' );
$contents = base64_decode( $response->content );
$response = json_decode( $contents );
break;
}
if ( $this->validate_response( $response ) ) {
return false;
}
return $response;
}
/**
* Process $package for update transient.
*
* @param string $type ( github|bitbucket|gitlab ).
* @param string $locale
* @param array $headers
*
* @return array|null|string
*/
private function process_language_pack_package( $type, $locale, $headers ) {
$package = null;
switch ( $type ) {
case 'github':
$package = [ 'https://github.com', $headers['owner'], $headers['repo'], 'blob/master' ];
$package = implode( '/', $package ) . $locale->package;
$package = add_query_arg( [ 'raw' => 'true' ], $package );
break;
case 'bitbucket':
$package = [ 'https://bitbucket.org', $headers['owner'], $headers['repo'], 'raw/master' ];
$package = implode( '/', $package ) . $locale->package;
break;
case 'gitlab':
$package = [ 'https://gitlab.com', $headers['owner'], $headers['repo'], 'raw/master' ];
$package = implode( '/', $package ) . $locale->package;
break;
}
return $package;
}
}
| true |
ba4bb3d55996ae973e250fe815e3588475c1fb30 | PHP | MatviyRoman/php-class | /microtime.php | UTF-8 | 419 | 2.953125 | 3 | [] | no_license | <?php
$string1 = str_repeat('x', 100);
$string2 = str_repeat('y', 100);
$string3 = str_repeat('z', 100);
$mark = microtime(true);
for ($i = 0; $i < 2000; $i++) {
ob_start();
for ($j = 0; $j < 2000; $j++) {
print $string1 . $string2 . $string3;
}
ob_get_clean();
}
print '<a href="https://paiza.io/projects/daUsTK6Nj2YLU1pN8UD10w?language=php">play code</a>';
echo microtime(true) - $mark; | true |
9db998acd5325b4e0fa324fc310f843baa1ff181 | PHP | Dencina1996/Forohub | /app/Models/ReportThread.php | UTF-8 | 1,032 | 2.5625 | 3 | [] | no_license | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
use Auth;
class ReportThread extends Model {
use HasFactory;
protected $table = 'threads_reports';
protected $fillable = [
'created_at',
'updated_at',
'user_id',
'thread_id',
'report_type',
'description',
'solved'
];
public function threads() {
return $this->belongsTo(Thread::class, 'thread_id');
}
public function author() {
return $this->belongsTo(User::class, 'user_id');
}
public static function createThreadReport($thread_id, $report_type, $description) {
ReportThread::create([
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
'user_id' => Auth::user()->id,
'thread_id' => $thread_id,
'report_type' => $report_type,
'description' => $description,
'solved' => 0
]);
}
}
| true |
1d6bbf3a3764f3f425b131cbf985e60a86d06243 | PHP | peterwu19881230/Microbial_phenotype_data_mining | /NicholsAnnotationsForOMP/JWstrainSearchAndReplace1.php | UTF-8 | 6,466 | 2.59375 | 3 | [] | no_license | <?php
/*
Correct strain names by search and replace. (1. title change: JWXXXX-number -> JWXXXX 2. Strain info table: strain name: JWXXXX-number ->JWXXXX, synonyms: JWXXXX-number -> JWXXXX)
(!) After correcting the pages, they no longer appear in the category page (). I think there will be a way to fix that so I still ran this code
(!)This page has been corrected before running the script (added: coli): OMP ST:1173 ! Escherichia K-12 JW5596-1
(!)There were 2 pages for JW5249: JW5249 and JW5249-1. I deleted JW5249-1 and keep JW5249. Also I added JW5249-1 as a synonym in the JW5249 page
Test by: php JWstrainSearchAndReplace.php -w /Library/WebServer/Documents/omp/sandy/
The test website's URL: https://microbialphenotypes.org/sandy/index.php/Main_Page
All the existing JW pages: https://microbialphenotypes.org/sandy/index.php/Category:OMP_ST:800_!_Escherichia_coli_K-12_BW25113_derivatives
*/
$params = getopt( "w:" );
set_IP($params['w']);
$maintClass = "NicholsMaint";
class NicholsMaint extends Maintenance {
public function __construct() {
parent::__construct();
$this->parse_parameters();
}
public function execute() {
#once I have the paper I am looking for, I search by allele, which in this case is also the strain name
$dbw = wfGetDB( DB_SLAVE );
$result = $dbw->select(
array('page'),
'*',
array("page_title REGEXP 'Escherichia_coli_K-12_JW[0-9]{4}-'"), #There exists redirects like JW 5335-1 , JW659-5. I don't want to find them.
__METHOD__,
array()
);
$num=0;
foreach($result as $x) { #If no pages are found, this foreach() is not run. I don't know why
#Uses the pages found and creates a title object and finds the tables on the strain pages that were previously created using the pombe_knockout_insert.php code
$title = Title::newFromText($x->page_title);
echo $title."\n";
$old_page = new WikiPageTE($title);
$oldtable = $old_page->getTable("Strain_info_table");
if(!isset($oldtable[0])){ echo "->This page has been redirected\n"; continue;} #I don't want the re-directed empty page be processed. Otherwise it will cause Fatal Error
if(strpos($title, "yraP(del)::FRT-cat-FRT") !== false){ #These are the weird pages I don't understand and want to escape. Ref: https://stackoverflow.com/questions/4366730/how-do-i-check-if-a-string-contains-a-specific-word
echo $title,"\n -> is not what I want and will be neglected"."\n";
continue;
}
echo " ->This page contains dash and number and should be replaced"."\n";
$num++;
//Edit and replace the title
#Check if the page has been redirected (if so the strain info table should be empty)
$newtitle=preg_replace('/-[0-9]{1}$/',"",$title); echo "Correction: ".$newtitle."\n"; #-[0-9]{1}$ needs to be surrounded by /. Ref: https://phpenthusiast.com/blog/php-regular-expressions
$t = Title::newFromText($newtitle);
#Change the page title
$context = new RequestContext();
$movepage = $old_page->move($t, $context);
//Verify that the updated title is in the database (there will be 2 titles, the additional one which has the old title is there for redirection):
# login to SQL and search for that page:
# login on Tetramer
# mysql -u peterwu => enter password
# use omp_sandy_wikidb
# SELECT * FROM page WHERE page_title LIKE '%ST:983_!%';
$wikiPage = new WikiPageTE($t); # WikiPageTE is a class defined in WikiPageTE.php
$newtable = $wikiPage->getTable("Strain_info_table");
//Remove the -number in the Strain Name box in the Strain Info Table
$box = $newtable[0];
# I don't think this is that useful: https://github.tamu.edu/HuLab/wiki-maintenance/blob/master/wiki_editors/SearchReplace.php
# Will this be the solution?: https://github.tamu.edu/HuLab/wiki-maintenance/blob/master/wiki_editors/EditTablesByTemplate.php
$strainInfo=$box->rows[0]->row_data_original;
list($strainName,$synonyms,$TaxonInfo,$Genotype,$StrainRef,$StrainAvail,$ancestry,$annotatedPheno)=explode("||",$strainInfo);
$newStrainName=preg_replace('/-[0-9]{1}$/',"",$strainName);
preg_match('/JW[0-9]{4}-[0-9]{1}$/',$title,$matches); #search for a pattern and store it into the variable $matches
$oldStrainName=$matches[0];
$newSynonyms=$oldStrainName;
$box->delete_row(0); #Note: if I delete the row and try to revert it using the webpage, I have to edit the table and save it, otherwise the reverted data will not be put back into the SQL
#I verified with Sandy that doing this is fine. No need for additional acts to delete things in the SQL
# 0 inside delete_row is the row index (in the strain info table the 1st column (not counting the name column) is considered the 1st row)
$box->insert_row(
$newStrainName."||".
$newSynonyms."||".
$TaxonInfo."||".
$Genotype."||".
$StrainRef."||".
$StrainAvail."||".
$ancestry."||".
$annotatedPheno
);
$wikiPage->touch();
#if($num==1)break; #This line is used to test the code: $num==1: only 1 page will be corrected
}
echo $num." of page(s) has/have been processed"."\n";
}
private function parse_parameters(){
$this->addOption( "people", "say hello to this", $required = false, $withArg = true, $shortName = 'l' );
}
}
require_once( RUN_MAINTENANCE_IF_MAIN );
function set_IP($path){
global $IP;
if ( isset($path) && is_file("$path/maintenance/Maintenance.php") ){
$IP = $path;
require_once( $IP . "/maintenance/Maintenance.php" );
return $path;
} else {
die ("need -w <path-to-wiki-directory>");
}
} | true |
e1d1a9ba9e734213819b94483413a2d9956642ad | PHP | toriworks/IPGroup | /download.php | UTF-8 | 1,469 | 2.515625 | 3 | [] | no_license | <?php
//function mb_basename($path) { return end(explode('/',$path)); }
function utf2euc($str) { return iconv("UTF-8","cp949//IGNORE", $str); }
function is_ie() { return isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false; }
//
//// 파라미터 수신
$filename = $_REQUEST['filename'];
$ofilename = $_REQUEST['ofilename'];
$category = $_REQUEST['category'];
//
//// 다운로드 받을 경로 설정
//$directory = '';
if($category == 'CI') {
$directory = './uploaded/introduction/';
}
//
//// 파일명 조합
$filename = trim($filename);
$filepath = $directory.$filename;
$filesize = filesize($filepath);
//
//// IE 처리
if( is_ie() ) $ofilename = utf2euc($ofilename);
//
//// 헤더 설정
//header("Pragma: public");
//header("Expires: 0");
//header("Content-Type: application/octet-stream");
//header("Content-Disposition: attachment; filename=\"$ofilename\"");
//header("Content-Transfer-Encoding: binary");
//header("Content-Length: $filesize");
//
//// 파일 읽기
//readfile($filepath);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($ofilename));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: '.$filesize);
ob_clean();
flush();
readfile($filepath);
exit;
?>
| true |
fdd91c48bd0a17470c68534d15c7bee3cd458cfe | PHP | vesicd8/quickfood | /database/seeders/UnitSeeder.php | UTF-8 | 433 | 2.75 | 3 | [] | no_license | <?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class UnitSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$units = ['mg', 'g', 'kg', 'ml', 'l'];
foreach ($units as $unit){
DB::table('units')->insert([
'unit' => $unit
]);
}
}
}
| true |
4dfad10f2590d3fa4286dfeba7f2d98bb1794b57 | PHP | Zextia/staff-management | /classes/class.mysql_db.php | UTF-8 | 2,836 | 3 | 3 | [
"Apache-2.0"
] | permissive | <?php
class mysql_db extends database {
public $resource;
public $num_rows = null;
public $valid_resource = false;
function __construct() {
mysql_connect(HOSTNAME, USERNAME, PASSWORD);
mysql_select_db(DATABASE);
return $this;
}
function select($table = '', $conditions = '') {
$return = array();
if (trim($table) != '') {
if (trim($conditions) == '') {
$conditions = ' 1 = 1';
}
$sql = "SELECT * FROM $table WHERE $conditions;";
$this->query($sql);
if ($this->valid_resource && ($this->num_rows > 0)) {
return true;
} else {
return false;
}
} else {
return false;
}
return $return;
}
function query($sql = '', $type = 'select') {
if (trim($sql) != '') {
$this->resource = mysql_query($sql);
if (!$this->resource) {
return false;
}
if ($type == 'insert') {
return $this->resource;
} else {
$this->set_number_of_results();
}
} else {
return false;
}
}
function update() {
}
function delete($id = 0) {
if ($id && is_numeric($id)) {
}
}
function insert($table = '', $data = array()) {
if (trim($table) == '' || !is_array($data) || count($data) == 0) {
return false;
}
$sql = $this->create_insert_sql($table, $data);
$this->query($sql, 'insert');
return $this->valid_resource;
}
function get_results() {
if ($this->num_rows == 1) {
return $this->get_one_result();
}
$result = array();
while ($row = $this->get_one_result()) {
$result[] = $row;
}
return $result;
}
private function get_one_result() {
return mysql_fetch_array($this->resource);
}
function get_number_of_results() {
return $this->num_rows;
}
function get_db_instance() {
return $this;
}
function set_number_of_results() {
$this->num_rows = mysql_num_rows($this->resource);
}
private function create_insert_sql($table = '', $data = array()) {
$sql = "INSERT INTO `$table` (";
$columns = '';
$values = '';
$i = 0;
foreach ($data as $k => $v) {
if ($i == 0) {
$columns .= "`$k`";
$values .= "'$v'";
} else {
$columns .= ", `$k`";
$values .= ", '$v'";
}
$i++;
}
$sql .= "$columns) VALUES ($values) ;";
return $sql;
}
}
| true |
e80f928f9fa4f47c7158fccef4e65de0d02ec4af | PHP | eicesoft/lark | /src/Pool/ObjectPool.php | UTF-8 | 5,716 | 2.84375 | 3 | [
"MIT"
] | permissive | <?php
namespace Lark\Pool;
use Co\Channel;
use Lark\Core\Config;
use Lark\Core\TSingleton;
use Lark\Event\EventManager;
use Lark\Event\Local\PoolEvent;
/**
* Class ObjectPool
* @package Lark\Pool
* @author kelezyb
*/
class ObjectPool
{
use TSingleton;
/**
* 最大活跃数
* @var int
*/
public $maxActive = 100;
/**
* 最多可空闲数
* @var int
*/
public $maxIdle = 10;
/**
* 拨号器
* @var DialerInterface
*/
protected $dialer;
/**
* 连接队列
* @var Channel
*/
protected $queue;
/**
* 活跃连接集合
* @var array
*/
protected $actives = [];
/**
* AbstractObjectPool constructor.
* @param array $config
* @throws \PhpDocReader\AnnotationException
* @throws \ReflectionException
*/
public function __construct()
{
$pool_config = Config::get(get_called_class(), 'pool');
if ($pool_config) {
$this->maxActive = $pool_config['maxActive'] ?? 100;
$this->maxIdle = $pool_config['maxIdle'] ?? 10;
}
if (class_exists('Channel')) {
$this->queue = new Channel($this->maxIdle);
} else {
$this->queue = new class {
public function stats()
{
return ['queue_num' => 0];
}
public function push($obj)
{
return true;
}
};
}
}
/**
* 创建连接
* @return object
*/
protected function createConnection()
{
$closure = function () {
$connection = $this->dialer->dial();
$connection->pool = $this;
return $connection;
};
$id = spl_object_hash($closure);
$this->actives[$id] = '';
try {
$connection = call_user_func($closure);
} finally {
unset($this->actives[$id]);
}
return $connection;
}
/**
* 借用连接
* @return object
*/
public function borrow()
{
if ($this->getIdleNumber() > 0 || $this->getTotalNumber() >= $this->maxActive) {
// 队列有连接,从队列取
// 达到最大连接数,从队列取
$type = 'borrow';
$connection = $this->pop();
} else {
// 创建连接
$type = 'create';
$connection = $this->createConnection();
}
//触发事件
EventManager::Instance()->trigger(new PoolEvent($type, $this));
// 登记, 队列中出来的也需要登记,因为有可能是 discard 中创建的新连接
$id = spl_object_hash($connection);
$this->actives[$id] = ''; // 不可保存外部连接的引用,否则导致外部连接不析构
// 返回
return $connection;
}
/**
* 归还连接
* @param $connection
* @return bool
*/
public function return(object $connection)
{
$id = spl_object_hash($connection);
// 判断是否已释放
if (!isset($this->actives[$id])) {
return false;
}
EventManager::Instance()->trigger(new PoolEvent('return', $this));
// 移除登记
unset($this->actives[$id]); // 注意:必须是先减 actives,否则会 maxActive - maxIdle <= 1 时会阻塞
// 入列
return $this->push($connection);
}
/**
* 丢弃连接
* @param $connection
* @return bool
*/
public function discard(object $connection)
{
$id = spl_object_hash($connection);
// 判断是否已丢弃
if (!isset($this->actives[$id])) {
return false;
}
EventManager::Instance()->trigger(new PoolEvent('discard', $this));
// 移除登记
unset($this->actives[$id]); // 注意:必须是先减 actives,否则会 maxActive - maxIdle <= 1 时会阻塞
// 入列一个新连接替代丢弃的连接
$result = $this->push($this->createConnection());
// 返回
return $result;
}
/**
* 获取连接池的统计信息
* @return array
*/
public function stats()
{
return [
'total' => $this->getTotalNumber(),
'idle' => $this->getIdleNumber(),
'active' => $this->getActiveNumber(),
];
}
/**
* 放入连接
* @param $connection
* @return bool
*/
protected function push($connection)
{
// 解决对象在协程外部析构导致的: Swoole\Error: API must be called in the coroutine
if (class_exists('Coroutine')) {
if (\Swoole\Coroutine::getCid() == -1) {
return false;
}
}
if ($this->getIdleNumber() < $this->maxIdle) {
return $this->queue->push($connection);
}
return false;
}
/**
* 弹出连接
* @return mixed
*/
protected function pop()
{
return $this->queue->pop();
}
/**
* 获取队列中的连接数
* @return int
*/
protected function getIdleNumber()
{
$count = $this->queue->stats()['queue_num'];
return $count < 0 ? 0 : $count;
}
/**
* 获取活跃的连接数
* @return int
*/
protected function getActiveNumber()
{
return count($this->actives);
}
/**
* 获取当前总连接数
* @return int
*/
protected function getTotalNumber()
{
return $this->getIdleNumber() + $this->getActiveNumber();
}
} | true |
5bfd200e89f3ee9aba8effb0c44b6fd3b591e6a4 | PHP | poojakarthik/my-work | /lib/classes/logic/collection/event/Logic_Collection_Event_Action.php | UTF-8 | 2,253 | 2.53125 | 3 | [] | no_license | <?php
/**
* Description of Collection_Logic_Event_Action
*
* @author JanVanDerBreggen
*/
class Logic_Collection_Event_Action extends Logic_Collection_Event
{
protected $oDO;
public function __construct($mDefinition)
{
if ($mDefinition instanceof Logic_Collection_Event_Instance)
{
$this->oCollectionEventInstance = $mDefinition;
$this->oParentDO = Collection_Event::getForId($mDefinition->collection_event_id);
$this->oDO = Collection_Event_Action::getForCollectionEventId($this->oParentDO->id);
}
else if (is_numeric($mDefinition))
{
$this->oParentDO = Collection_Event::getForId($mDefinition);
$this->oDO = Collection_Event_Action::getForCollectionEventId($this->oParentDO->id);
}
else
{
throw new Exception ('Bad definition of Logic_Collection_Event_Action, possibly a configuration error');
}
}
protected function _invoke($aParameters = null)
{
// Normalise things
$intAccountId = $this->getAccount()->id;
$strExtraDetails = trim($aParameters['extra_details']);
$strExtraDetails = ($strExtraDetails == "")? NULL : $strExtraDetails;
// Retrieve the Action Type
$actionType = Action_Type::getForId($this->action_type_id);
// Check that each $intAccountId, $intServiceId and $intContactId can be associated with actions of type $actionType, and NULLify them if they can't
$arrAllowableActionAssociationTypes = $actionType->getAllowableActionAssociationTypes();
if (!array_key_exists(ACTION_ASSOCIATION_TYPE_ACCOUNT, $arrAllowableActionAssociationTypes))
{
throw new Logic_Collection_Exception("Incorrect Action Type: Account is not an allowable association type. Configuration Error");
}
$intEmployeeId = Flex::getUserId()!== NULL ? Flex::getUserId() : Employee::SYSTEM_EMPLOYEE_ID;
$oAction = Action::createAction($actionType, $strExtraDetails, $intAccountId,null, null, $intEmployeeId, $intEmployeeId);
}
public static function complete($aEventInstances)
{
foreach ($aEventInstances as $oInstance)
{
$oInstance->complete();
}
}
public function __get($sField)
{
switch ($sField)
{
case 'name':
case 'collection_event_type_id':
return $this->oParentDO->$sField;
default:
return $this->oDO->$sField;
}
}
}
?>
| true |
27c3fa7eb2393d1b95a6e83311903537b34d2575 | PHP | vlakarados/ReRouter | /src/RouteCollector.php | UTF-8 | 1,340 | 2.625 | 3 | [
"MIT"
] | permissive | <?php
namespace ReRouter;
class RouteCollector extends \FastRoute\RouteCollector
{
public function addRoute($httpMethod, $route, $handler) {
if ($httpMethod == 'REST') {
// Make REST methods available
// TODO: find a better way to do this witout duplicates with an appended slash character
parent::addRoute('GET', $route[0], array($handler, 'index'));
parent::addRoute('GET', $route[0].'/', array($handler, 'index'));
parent::addRoute('POST', $route[0].'', array($handler, 'create'));
parent::addRoute('POST', $route[0].'/', array($handler, 'create'));
parent::addRoute('GET', $route[0].'/'.$route[1], array($handler, 'show'));
parent::addRoute('GET', $route[0].'/'.$route[1].'/', array($handler, 'show'));
parent::addRoute('PUT', $route[0].'/'.$route[1], array($handler, 'edit'));
parent::addRoute('PUT', $route[0].'/'.$route[1].'/', array($handler, 'edit'));
parent::addRoute('PATCH', $route[0].'/'.$route[1], array($handler, 'edit'));
parent::addRoute('PATCH', $route[0].'/'.$route[1].'/', array($handler, 'edit'));
parent::addRoute('DELETE', $route[0].'/'.$route[1], array($handler, 'delete'));
parent::addRoute('DELETE', $route[0].'/'.$route[1].'/', array($handler, 'delete'));
return;
}
parent::addRoute($httpMethod, $route, $handler);
}
}
| true |
525c58cb817658156d7dce3500b38d271b3661b2 | PHP | Gregoraz/movie-rental | /admin/receipt.php | UTF-8 | 1,919 | 2.515625 | 3 | [] | no_license | <?php
require('../connection.php');
session_start();
if(isset($_SESSION["logged"])) {
if(isset($_GET["orderID"])) {
$sql = '
SELECT orders.orderID, customer.firstname AS cfirstname, customer.lastname AS clastname, customer.email AS cemail, customer.address AS caddress, employee.firstname AS efirstname, employee.lastname AS elastname, employee.email AS eemail, movie.name AS moviename, movie.priceperday, movie.rentedtill, orders.orderdate, orders.rentDuration, orders.price FROM orders
INNER JOIN customer ON orders.customerID = customer.customerID
INNER JOIN employee ON orders.employeeID = employee.employeeID
INNER JOIN movie ON orders.movieID = movie.movieID
WHERE orders.orderID = '.$_GET["orderID"].'
;';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
echo '
Receipt<br><br>
Order ID: '.$row["orderID"].' <br><br>
Rented movie: '.$row["moviename"].' <br><br>
Customer<br>Firstname: '.$row["cfirstname"].' <br>
Lastname: '.$row["clastname"].' <br>
Email: '.$row["cemail"].' <br>
Address: '.$row["caddress"].' <br><br>
Employee<br>
Firstname: '.$row["efirstname"].' <br>
Lastname: '.$row["elastname"].' <br>
Email: '.$row["eemail"].' <br><br>
Order date: '.$row["orderdate"].' <br>
Rent duration: '.$row["rentDuration"].' days<br>
Return date: '.$row["rentedtill"].' <br>
Price per one day: £'.$row["priceperday"].' <br>
Price at all: £'.$row["price"].' <br><br>
Please ensure that you will return the movie on the time!
';
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
else echo "GET has been not sent.";
}
else header("Location: index.php");
?> | true |
5d4caaeff2a98a8399f474834e7d753afa986f34 | PHP | shpizel/encounters | /src/Mamba/EncountersBundle/Controller/VariablesController.php | UTF-8 | 1,787 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
namespace Mamba\EncountersBundle\Controller;
use Mamba\EncountersBundle\Controller\ApplicationController;
use Symfony\Component\HttpFoundation\Response;
use Core\MambaBundle\API\Mamba;
use Mamba\EncountersBundle\EncountersBundle;
/**
* VariablesController
*
* @package EncountersBundle
*/
class VariablesController extends ApplicationController {
protected
/**
* JSON Result
*
* @var array
*/
$json = array(
'status' => 0,
'message' => '',
'data' => array(
),
)
;
/**
* Sets variables
*
* @return \Symfony\Component\HttpFoundation\Response
*/
public function setVariableAction() {
if ($webUserId = $this->getSession()->get(Mamba::SESSION_USER_ID_KEY)) {
$key = (string) $this->getRequest()->request->get('key');
$data = (string) $this->getRequest()->request->get('data');
$Variables = $this->getVariablesHelper();
if ($Variables->isExternal($key)) {
try {
if (!$this->getVariablesHelper()->set($webUserId, $key, $data)) {
list($this->json['status'], $this->json['message']) = array(2, "Could not set variable");
}
} catch (\Exception $e) {
list($this->json['status'], $this->json['message']) = array(2, $e->getMessage());
}
} else {
list($this->json['status'], $this->json['message']) = array(2, "Invalid key");
}
} else {
list($this->json['status'], $this->json['message']) = array(1, "Invalid session");
}
return $this->JSONResponse($this->json);
}
} | true |
12b921ccf9daa095098e45cd4bd52f62326f6fbf | PHP | durino13/simple-cms | /database/migrations/2016_10_02_204813_soft_deletions.php | UTF-8 | 1,269 | 2.640625 | 3 | [] | no_license | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class SoftDeletions extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
// Create deleted_at field in these tables
$tables = [
'd_article',
'users',
'c_category'
];
foreach ($tables as $tabName) {
Schema::table($tabName, function ($table) {
$table->softDeletes();
});
}
// Drop 'trash' column in these tables
$dropTrashTables = [
'c_category',
'd_article'
];
foreach ($dropTrashTables as $tabName) {
Schema::table($tabName, function ($table) {
$table->dropColumn('trash');
});
}
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
$tables = [
'd_article',
'users',
'c_category'
];
foreach ($tables as $tabName) {
Schema::table($tabName, function ($table) {
$table->dropColumn('deleted_at');
});
}
}
}
| true |
93d2c445f40fab95e178d5fb420a5992fcfa6d25 | PHP | misoks/iTAPS-That | /newAccount.php | UTF-8 | 3,088 | 2.8125 | 3 | [] | no_license | <?php
session_start();
$page_title = "Create an Account";
include_once('header.php');
if ( isset($_POST['username']) && isset($_POST['password'])
&& ($_POST['specialization'] != -1) && ($_POST['year'] != -1)){
$u = mysql_real_escape_string($_POST['username']);
$p = mysql_real_escape_string($_POST['password']);
$s = mysql_real_escape_string($_POST['specialization']);
$s2 = mysql_real_escape_string($_POST['second_specialization']);
$y = mysql_real_escape_string($_POST['year']);
if($s2 == -1){
$s2 = "None";
}
$sql = "INSERT INTO Student (username, password, specialization, second_spec, year)
VALUES('$u', '$p', '$s', '$s2', '$y')";
$result = mysql_query($sql);
if ( $result === FALSE ) {
movePage('newAccount.php', "Sorry, that username has already been taken.", 'error');
unset($_SESSION['userid']);
include_once('footer.php');
} else {
$sql = "SELECT s.user_id, s.specialization, s.second_spec FROM Student s
WHERE username = '$u' AND password='$p'";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
if(htmlentities($row[0]) == 1){
$_SESSION['admin'] = true;
movePage('admin.php');
}
else{
$_SESSION['userid'] = htmlentities($row[0]);
$_SESSION['specialization'] = htmlentities($row[1]);
$_SESSION['second_specialization'] = htmlentities($row[2]);
movePage('manual.php');
}
movePage('manual.php', "Account creation succeeded!", 'success');
include_once('footer.php');
}
return;
}
else if(isset($_POST['username']) && isset($_POST['password'])
&& (($_POST['specialization'] == -1) || ($_POST['year'] == -1))){
movePage('newAccount.php', "Please complete all the required fields.", 'error');
unset($_SESSION['userid']);
}
?>
<h1>Create an Account</h1>
<form method="post">
<p>Username:
<input type="text" name="username"></p>
<p>Password:
<input type="password" name="password"></p>
<p>Specialization:
<select name="specialization">
<option value=-1>Select</option>
<?php
$sql3 = "SELECT DISTINCT r.specialization FROM Requirements r WHERE r.specialization != 'MSI' ";
$result = mysql_query($sql3);
while($row = mysql_fetch_row($result)){
echo "<option value=".htmlentities($row[0]).">".htmlentities($row[0])."</option>";
}
echo "</select>";
?>
<p/>
<p>(Optional) Second Specialization:
<select name="second_specialization">
<option value=-1>Select</option>
<?php
$sql3 = "SELECT DISTINCT r.specialization FROM Requirements r WHERE r.specialization != 'MSI' ";
$result = mysql_query($sql3);
while($row = mysql_fetch_row($result)){
echo "<option value=".htmlentities($row[0]).">".htmlentities($row[0])."</option>";
}
echo "</select>";
?>
<p/>
<p>Year of Graduation:
<select name="year">
<option value=-1>Select</option>
<?php
$current_year = intval(date('Y'));
for($i = ($current_year - 1); $i < ($current_year + 6); $i = $i + 1){
echo "<option value=".$i.">".$i."</option>";
}
echo "</select>";
?>
<p/>
<input type="submit" value="Submit"/>
</form>
<?php include_once('footer.php'); ?> | true |
c1af01f124c9c878a6cb2291f4bc68915588bacb | PHP | nurisakbar/Simple-School-Class-System | /app/Http/Controllers/StudentController.php | UTF-8 | 4,846 | 2.515625 | 3 | [] | no_license | <?php
namespace App\Http\Controllers;
use App\Models\Student;
use Illuminate\Http\Request;
use App\Http\Requests\StudentCreate;
use App\Models\StudentClass;
use App\Models\TestScores;
use Auth;
use App\Models\Schedule;
use Illuminate\Support\Facades\Hash;
class StudentController extends Controller
{
public $religion;
public $education;
public $workKind;
public function __construct()
{
$this->middleware('auth', ['except'=>['dashboard','update']]);
$this->religion = ['Islam','Kristen','Budha','Konghuchu'];
$this->education = ['SD','SMP','SMA','S1','S2','S3'];
$this->workKind = ['Karyawan Swasta','Lain nya'];
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$data['students'] = Student::all();
return view('student.index', $data);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$data['religions'] = $this->religion;
$data['educations'] = $this->education;
$data['workKinds'] = $this->workKind;
$data['class'] = StudentClass::pluck('name', 'id');
return view('student.create', $data);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(StudentCreate $request)
{
$input = $request->all();
$input['password'] = Hash::make($request->password);
if ($request->hasFile('photo')) {
$file = $request->file('photo');
$nama_file = str_replace(' ', '_', $file->getClientOriginalName());
$file->move('student_photo', $nama_file);
$input['photo'] = $nama_file;
}
Student::create($input);
return redirect('student')->with('message', 'A Student has been created successfull!');
}
/**
* Display the specified resource.
*
* @param \App\Models\Student $student
* @return \Illuminate\Http\Response
*/
public function show(Student $student)
{
$data['student'] = $student;
return view('student.detail', $data);
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\Student $student
* @return \Illuminate\Http\Response
*/
public function edit(Student $student)
{
$data['religions'] = $this->religion;
$data['educations'] = $this->religion;
$data['workKinds'] = $this->workKind;
$data['class'] = StudentClass::pluck('name', 'id');
$data['student'] = $student;
return view('student.edit', $data);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\Student $student
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Student $student)
{
$student = $student;
$input = $request->all();
if ($request->password != null) {
$input['password'] = Hash::make($request->password);
} else {
$input['password'] = $student->password;
}
if ($request->has('photo')) {
$file = $request->file('photo');
$nama_file = str_replace(' ', '_', $file->getClientOriginalName());
$file->move('student_photo', $nama_file);
$input['photo'] = $nama_file;
}
$student->update($input);
if ($request->has('redirect')) {
return redirect('student-dashboard')->with('message', 'Upload Photo Berhasil');
}
return redirect('student')->with('message', 'A Student With Name '.$student->name.' Has Updated');
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Student $student
* @return \Illuminate\Http\Response
*/
public function destroy(Student $student)
{
$student = $student;
$student->delete();
return redirect('student')->with('message', 'Student With Name '.$student->name.' Has Deleted');
}
public function dashboard()
{
$data['tab'] = $_GET['tab']??'jadwal';
$student = Auth::guard('student')->user();
$data['student'] = $student;
$data['schedules'] = Schedule::with('course', 'teacher')->where('schedules.student_class_id', $student->student_class_id)->get();
$data['scores'] = TestScores::where('student_id', $student->student_id)->get();
return view('student.dashboard', $data);
}
}
| true |
f3c6a9c9dc4c7f21ce2e96d981b74b221e9db3e4 | PHP | auliarampit/avam | /2.php | UTF-8 | 501 | 3.03125 | 3 | [] | no_license | <?php
function ValidasiUsername($user){
$lowercase = preg_match("/^[a-z]*$/", $user);
if ($lowercase && strlen($user)==8) {
echo "true <br/>";
}else{
echo "false <br/>";
}
}
function ValidasiPassword($pass){
$bebas = preg_match("/^[a-z || A-Z || 0-9 || @_.=,|+()*&^%$#!'\/-]*$/", $pass);
if ($bebas && strlen($pass)==8) {
echo "true <br/>";
}else{
echo "false <br/>";
}
}
ValidasiUsername("auliarah");
ValidasiPassword("auliaR_A")
?> | true |
0e53e8bf1f907d7c9cc56878fc3ce193f630f9df | PHP | FarhanLhant/salmanfarhan | /uts/login(complete).php | UTF-8 | 7,731 | 3.09375 | 3 | [] | no_license | <?php
// Initialize the session
session_start();
/* Check if the user is already logged in, if yes then redirect him to welcome page
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){
header("location: welcome.php");
exit;
}*/
// Include config file
include 'config.php';
// Define variables and initialize with empty values
$username = $password = "";
$username_err = $password_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Check if username is empty
if(empty(trim($_POST["username"]))){
$username_err = "Please enter username.";
} else{
$username = trim($_POST["username"]);
}
// Check if password is empty
if(empty(trim($_POST["password"]))){
$password_err = "Please enter your password.";
} else{
$password = trim($_POST["password"]);
}
// Validate credentials
if(empty($username_err) && empty($password_err)){
// Prepare a select statement
$sql = "SELECT idUser, username, password FROM user WHERE username = ?";
/* tes koneksi
$stmt = mysqli_prepare($link, $sql);
if ($stmt === FALSE) {
die($mysqli->error);
}
$stmt->execute();
*/
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_username);
// Set parameters
$param_username = $username;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Store result
mysqli_stmt_store_result($stmt);
// Check if username exists, if yes then verify password
if(mysqli_stmt_num_rows($stmt) == 1){
// Bind result variables
mysqli_stmt_bind_result($stmt, $idUser, $username, $hashed_password);
if(mysqli_stmt_fetch($stmt)){
if($password == $hashed_password){
// Password is correct, so start a new session
session_start();
// Store data in session variables
$_SESSION["loggedin"] = true;
$_SESSION["id"] = $id;
$_SESSION["username"] = $username;
// Redirect user to welcome page
header("location: profile.php");
} else{
// Display an error message if password is not valid
$password_err = "The password you entered was not valid.";
}
}
} else{
// Display an error message if username doesn't exist
$username_err = "No account found with that username.";
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
// Close statement
mysqli_stmt_close($stmt);
}
}
// Close connection
mysqli_close($link);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Vietgram | Login</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="description" content="Vietgram, like Instagram but with Pho" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<main id="login">
<div class="login__column">
<img src="images/phoneImage.png" class="login__phone" />
</div>
<div class="login__column">
<div class="login__box">
<img src="images/loginLogo.png" class="login__logo" />
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="login__form <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>">
<label>Username</label>
<input type="text" name="username" class="form-control" value="<?php echo $username; ?>" required>
<span class="help-block"><?php echo "<div style=\"color: red;\">" . $username_err ."</div>"; ?></span>
</div>
<div class="login__form <?php echo (!empty($password_err)) ? 'has-error' : '' ?>" >
<label>Password</label>
<input type="password" name="password" class="form-control" required>
<span class="help-block"><?php echo "<div style=\"color: red;\">" . $password_err ."</div>"; ?></span>
</div>
<div class="login__form">
<input type="submit" class="btn btn-primary" value="Login">
</div>
</form>
<span class="login__divider">or</span>
<a href="#" class="login__link">
<i class="fa fa-money"></i>
Log in with Facebook
</a>
<a href="#" class="login__link login__link--small">Forgot password</a>
</div>
<div class="login__box">
<span>Don't have an account?</span> <a href="#">Sign up</a>
</div>
<div class="login__box--transparent">
<span>Get the app.</span>
<div class="login__appstores">
<img src="images/ios.png" class="login__appstore" alt="Apple appstore logo" title="Apple appstore logo" />
<img src="images/android.png" class="login__appstore" alt="Android appstore logo" title="Android appstore logo" />
</div>
</div>
</div>
</main>
<footer class="footer">
<div class="footer__column">
<nav class="footer__nav">
<ul class="footer__list">
<li class="footer__list-item"><a href="#" class="footer__link">About Us</a></li>
<li class="footer__list-item"><a href="#" class="footer__link">Support</a></li>
<li class="footer__list-item"><a href="#" class="footer__link">Blog</a></li>
<li class="footer__list-item"><a href="#" class="footer__link">Press</a></li>
<li class="footer__list-item"><a href="#" class="footer__link">Api</a></li>
<li class="footer__list-item"><a href="#" class="footer__link">Jobs</a></li>
<li class="footer__list-item"><a href="#" class="footer__link">Privacy</a></li>
<li class="footer__list-item"><a href="#" class="footer__link">Terms</a></li>
<li class="footer__list-item"><a href="#" class="footer__link">Directory</a></li>
<li class="footer__list-item"><a href="#" class="footer__link">Language</a></li>
</ul>
</nav>
</div>
<div class="footer__column">
<span class="footer__copyright">© 2017 Vietgram</span>
</div>
</footer>
</body>
</html> | true |
10cbf9cfb30618963296fb210e15a1b9122e3da7 | PHP | canaconruda/Kinsta-site | /themes/freshio/inc/template-functions.php | UTF-8 | 30,732 | 2.53125 | 3 | [] | no_license | <?php
if (!function_exists('freshio_display_comments')) {
/**
* Freshio display comments
*
* @since 1.0.0
*/
function freshio_display_comments()
{
// If comments are open or we have at least one comment, load up the comment template.
if (comments_open() || 0 !== intval(get_comments_number())) :
comments_template();
endif;
}
}
if (!function_exists('freshio_comment')) {
/**
* Freshio comment template
*
* @param array $comment the comment array.
* @param array $args the comment args.
* @param int $depth the comment depth.
*
* @since 1.0.0
*/
function freshio_comment($comment, $args, $depth)
{
if ('div' === $args['style']) {
$tag = 'div';
$add_below = 'comment';
} else {
$tag = 'li';
$add_below = 'div-comment';
}
?>
<<?php echo esc_attr($tag) . ' '; ?><?php comment_class(empty($args['has_children']) ? '' : 'parent'); ?> id="comment-<?php comment_ID(); ?>">
<div class="comment-body">
<div class="comment-meta commentmetadata">
<div class="comment-author vcard">
<?php echo get_avatar($comment, 128); ?>
<?php printf('<cite class="fn">%s</cite>', get_comment_author_link()); ?>
</div>
<?php if ('0' === $comment->comment_approved) : ?>
<em class="comment-awaiting-moderation"><?php esc_attr_e('Your comment is awaiting moderation.', 'freshio'); ?></em>
<br/>
<?php endif; ?>
<a href="<?php echo esc_url(htmlspecialchars(get_comment_link($comment->comment_ID))); ?>"
class="comment-date">
<?php echo '<time datetime="' . get_comment_date('c') . '">' . get_comment_date() . '</time>'; ?>
</a>
</div>
<?php if ('div' !== $args['style']) : ?>
<div id="div-comment-<?php comment_ID(); ?>" class="comment-content">
<?php endif; ?>
<div class="comment-text">
<?php comment_text(); ?>
</div>
<div class="reply">
<?php
comment_reply_link(
array_merge(
$args, array(
'add_below' => $add_below,
'depth' => $depth,
'max_depth' => $args['max_depth'],
)
)
);
?>
<?php edit_comment_link(esc_html__('Edit', 'freshio'), ' ', ''); ?>
</div>
</div>
<?php if ('div' !== $args['style']) : ?>
</div>
<?php endif; ?>
<?php
}
}
if (!function_exists('freshio_footer_widgets')) {
/**
* Display the footer widget regions.
*
* @return void
* @since 1.0.0
*/
function freshio_footer_widgets()
{
$rows = intval(apply_filters('freshio_footer_widget_rows', 1));
$regions = intval(apply_filters('freshio_footer_widget_columns', 5));
for ($row = 1; $row <= $rows; $row++) :
// Defines the number of active columns in this footer row.
for ($region = $regions; 0 < $region; $region--) {
if (is_active_sidebar('footer-' . esc_attr($region + $regions * ($row - 1)))) {
$columns = $region;
break;
}
}
if (isset($columns)) :
?>
<div class="col-full">
<div
class=<?php echo '"footer-widgets row-' . esc_attr($row) . ' col-' . esc_attr($columns) . ' fix"'; ?>>
<?php
for ($column = 1; $column <= $columns; $column++) :
$footer_n = $column + $regions * ($row - 1);
if (is_active_sidebar('footer-' . esc_attr($footer_n))) :
?>
<div class="block footer-widget-<?php echo esc_attr($column); ?>">
<?php dynamic_sidebar('footer-' . esc_attr($footer_n)); ?>
</div>
<?php
endif;
endfor;
?>
</div><!-- .footer-widgets.row-<?php echo esc_attr($row); ?> -->
</div>
<?php
unset($columns);
endif;
endfor;
}
}
if (!function_exists('freshio_credit')) {
/**
* Display the theme credit
*
* @return void
* @since 1.0.0
*/
function freshio_credit()
{
?>
<div class="site-info">
<?php echo apply_filters('freshio_copyright_text', $content = esc_html__('Coppyright', 'freshio') . ' © ' . date('Y') . ' ' . '<a class="site-url" href="' . site_url() . '">' . get_bloginfo('name') . '</a>' . esc_html__('. All Rights Reserved.', 'freshio')); ?>
</div><!-- .site-info -->
<?php
}
}
if (!function_exists('freshio_social')) {
function freshio_social()
{
$social_list = freshio_get_theme_option('social_text', []);
if (empty($social_list)) {
return;
}
?>
<div class="freshio-social">
<ul>
<?php
foreach ($social_list as $social_item) {
?>
<li><a href="<?php echo esc_url($social_item); ?>"></a></li>
<?php
}
?>
</ul>
</div>
<?php
}
}
if (!function_exists('freshio_site_welcome')) {
/**
* Site branding wrapper and display
*
* @return void
* @since 1.0.0
*/
function freshio_site_welcome()
{
?>
<div class="site-welcome">
<?php
echo freshio_get_theme_option('welcome-message');
?>
</div>
<?php
}
}
if (!function_exists('freshio_site_branding')) {
/**
* Site branding wrapper and display
*
* @return void
* @since 1.0.0
*/
function freshio_site_branding()
{
?>
<div class="site-branding">
<?php echo freshio_site_title_or_logo(); ?>
</div>
<?php
}
}
if (!function_exists('freshio_site_title_or_logo')) {
/**
* Display the site title or logo
*
* @param bool $echo Echo the string or return it.
*
* @return string
* @since 2.1.0
*/
function freshio_site_title_or_logo()
{
$logo = freshio_get_theme_option('site_mode') == 'light' ? freshio_get_theme_option('logo_light', ['url' => '']) : freshio_get_theme_option('logo_dark', ['url' => '']);
$logo_light = freshio_get_theme_option('logo_light', ['url' => '']);
$logo_dark = freshio_get_theme_option('logo_dark', ['url' => '']);
if ($logo['url']) {
$logo = sprintf(
'<a href="%1$s" class="custom-logo-link" rel="home"><img src="%2$s" class="logo-light" alt="Logo"/><img src="%3$s" class="logo-dark" alt="Logo"/></a>',
esc_url(home_url('/')),
esc_url($logo_light['url']),
esc_url($logo_dark['url'])
);;
$html = is_home() ? '<h1 class="logo">' . $logo . '</h1>' : $logo;
} else {
$tag = is_home() ? 'h1' : 'div';
$html = '<' . esc_attr($tag) . ' class="beta site-title"><a href="' . esc_url(home_url('/')) . '" rel="home">' . esc_html(get_bloginfo('name')) . '</a></' . esc_attr($tag) . '>';
if ('' !== get_bloginfo('description')) {
$html .= '<p class="site-description">' . esc_html(get_bloginfo('description', 'display')) . '</p>';
}
}
return $html;
}
}
if (!function_exists('freshio_primary_navigation')) {
/**
* Display Primary Navigation
*
* @return void
* @since 1.0.0
*/
function freshio_primary_navigation()
{
?>
<nav class="main-navigation" role="navigation"
aria-label="<?php esc_html_e('Primary Navigation', 'freshio'); ?>">
<?php
$args = apply_filters('freshio_nav_menu_args', [
'fallback_cb' => '__return_empty_string',
'theme_location' => 'primary',
'container_class' => 'primary-navigation',
]);
wp_nav_menu($args);
?>
</nav>
<?php
}
}
if (!function_exists('freshio_mobile_navigation')) {
/**
* Display Handheld Navigation
*
* @return void
* @since 1.0.0
*/
function freshio_mobile_navigation()
{
?>
<nav class="mobile-navigation" aria-label="<?php esc_html_e('Mobile Navigation', 'freshio'); ?>">
<?php
$args = apply_filters('freshio_nav_menu_args', [
'fallback_cb' => '__return_empty_string',
'theme_location' => 'handheld',
'container_class' => 'handheld-navigation',
]);
wp_nav_menu($args);
?>
</nav>
<?php
}
}
if (!function_exists('freshio_vertical_navigation')) {
/**
* Display Vertical Navigation
*
* @return void
* @since 1.0.0
*/
function freshio_vertical_navigation()
{
if (isset(get_nav_menu_locations()['vertical'])) {
$string = get_term(get_nav_menu_locations()['vertical'], 'nav_menu')->name;
?>
<nav class="vertical-navigation" aria-label="<?php esc_html_e('Vertiacl Navigation', 'freshio'); ?>">
<div class="vertical-navigation-header">
<i class="freshio-icon-bars"></i>
<span class="vertical-navigation-title"><?php echo esc_html($string); ?></span>
</div>
<?php
$args = apply_filters('freshio_nav_menu_args', [
'fallback_cb' => '__return_empty_string',
'theme_location' => 'vertical',
'container_class' => 'vertical-menu',
]);
wp_nav_menu($args);
?>
</nav>
<?php
}
}
}
if (!function_exists('freshio_homepage_header')) {
/**
* Display the page header without the featured image
*
* @since 1.0.0
*/
function freshio_homepage_header()
{
edit_post_link(esc_html__('Edit this section', 'freshio'), '', '', '', 'button freshio-hero__button-edit');
?>
<header class="entry-header">
<?php
the_title('<h1 class="entry-title">', '</h1>');
?>
</header><!-- .entry-header -->
<?php
}
}
if (!function_exists('freshio_page_header')) {
/**
* Display the page header
*
* @since 1.0.0
*/
function freshio_page_header()
{
if (freshio_is_woocommerce_activated() || freshio_is_bcn_nav_activated() || is_page()) {
return;
}
if (is_front_page() && is_page_template('template-fullwidth.php')) {
return;
}
?>
<header class="entry-header">
<?php
freshio_post_thumbnail('full');
the_title('<h1 class="entry-title">', '</h1>');
?>
</header><!-- .entry-header -->
<?php
}
}
if (!function_exists('freshio_page_content')) {
/**
* Display the post content
*
* @since 1.0.0
*/
function freshio_page_content()
{
?>
<div class="entry-content">
<?php the_content(); ?>
<?php
wp_link_pages(
array(
'before' => '<div class="page-links">' . esc_html__('Pages:', 'freshio'),
'after' => '</div>',
)
);
?>
</div><!-- .entry-content -->
<?php
}
}
if (!function_exists('freshio_breadcrumb_header')) {
/**
* Display the breadcrumb header with a link to the single post
*
* @since 1.0.0
*/
function freshio_get_breadcrumb_header()
{
ob_start();
if (is_page() || is_single()) {
the_title('<h1 class="breadcrumb-heading">', '</h1>');
} elseif (is_archive()) {
if (freshio_is_woocommerce_activated()) {
echo '<h1 class="breadcrumb-heading"> ' . woocommerce_page_title(false) . '</h1>';
} else {
the_archive_title('<h1 class="breadcrumb-heading">', '</h1>');
}
}
return ob_get_clean();
}
}
if (!function_exists('freshio_post_header')) {
/**
* Display the post header with a link to the single post
*
* @since 1.0.0
*/
function freshio_post_header()
{
?>
<header class="entry-header">
<?php
/**
* Functions hooked in to freshio_post_header_before action.
*/
do_action('freshio_post_header_before');
?>
<div class="entry-meta">
<?php
freshio_post_meta();
?>
</div>
<?php
if (!is_single()) {
the_title(sprintf('<h2 class="alpha entry-title"><a href="%s" rel="bookmark">', esc_url(get_permalink())), '</a></h2>');
}
?>
<?php
do_action('freshio_post_header_after');
?>
</header><!-- .entry-header -->
<?php
}
}
if (!function_exists('freshio_post_content')) {
/**
* Display the post content with a link to the single post
*
* @since 1.0.0
*/
function freshio_post_content()
{
?>
<div class="entry-content">
<?php
/**
* Functions hooked in to freshio_post_content_before action.
*
*/
do_action('freshio_post_content_before');
the_content(
sprintf(
/* translators: %s: post title */
__('Read More %s', 'freshio'),
'<span class="screen-reader-text">' . get_the_title() . '</span>'
)
);
/**
* Functions hooked in to freshio_post_content_after action.
*
*/
do_action('freshio_post_content_after');
wp_link_pages(
array(
'before' => '<div class="page-links">' . esc_html__('Pages:', 'freshio'),
'after' => '</div>',
)
);
?>
</div><!-- .entry-content -->
<?php
}
}
if (!function_exists('freshio_post_meta')) {
/**
* Display the post meta
*
* @since 1.0.0
*/
function freshio_post_meta()
{
if ('post' !== get_post_type()) {
return;
}
// Posted on.
$time_string = '<time class="entry-date published updated" datetime="%1$s">%2$s</time>';
if (get_the_time('U') !== get_the_modified_time('U')) {
$time_string = '<time class="entry-date published" datetime="%1$s">%2$s</time><time class="updated" datetime="%3$s">%4$s</time>';
}
$time_string = sprintf(
$time_string,
esc_attr(get_the_date('c')),
esc_html(get_the_date()),
esc_attr(get_the_modified_date('c')),
esc_html(get_the_modified_date())
);
$posted_on = '<span class="posted-on">' . sprintf('<a href="%1$s" rel="bookmark">%2$s</a>', esc_url(get_permalink()), $time_string) . '</span>';
// Author.
$author = sprintf(
'<span class="post-author"><span>%1$s<a href="%2$s" class="url fn" rel="author">%3$s</a></span></span>',
esc_html__('by ', 'freshio'),
esc_url(get_author_posts_url(get_the_author_meta('ID'))),
esc_html(get_the_author())
);
$comments = '<span class="total-comments"><span>' . get_comments_number() . '</span></span>';
echo wp_kses(
sprintf('%1$s %2$s %3$s', $posted_on, $author, $comments), array(
'span' => array(
'class' => array(),
),
'a' => array(
'href' => array(),
'title' => array(),
'rel' => array(),
),
'time' => array(
'datetime' => array(),
'class' => array(),
),
)
);
}
}
if (!function_exists('freshio_edit_post_link')) {
/**
* Display the edit link
*
* @since 2.5.0
*/
function freshio_edit_post_link()
{
edit_post_link(
sprintf(
wp_kses(
/* translators: %s: Name of current post. Only visible to screen readers */
__('Edit <span class="screen-reader-text">%s</span>', 'freshio'),
array(
'span' => array(
'class' => array(),
),
)
),
get_the_title()
),
'<div class="edit-link">',
'</div>'
);
}
}
if (!function_exists('freshio_categories_link')) {
/**
* Prints HTML with meta information for the current cateogries
*/
function freshio_categories_link()
{
// Get Categories for posts.
$categories_list = get_the_category_list(' ');
if ('post' === get_post_type() && $categories_list) {
// Make sure there's more than one category before displaying.
echo '<span class="categories-link"><span class="screen-reader-text">' . esc_html__('Categories', 'freshio') . '</span>' . $categories_list . '</span>';
}
}
}
if (!function_exists('freshio_post_taxonomy')) {
/**
* Display the post taxonomies
*
* @since 2.4.0
*/
function freshio_post_taxonomy()
{
/* translators: used between list items, there is a space after the comma */
$categories_list = get_the_category_list(__(', ', 'freshio'));
/* translators: used between list items, there is a space after the comma */
$tags_list = get_the_tag_list('');
?>
<aside class="entry-taxonomy">
<?php if ($tags_list) : ?>
<div class="tags-links">
<strong><?php echo esc_html(_n('Tag:', 'Tags:', count(get_the_tags()), 'freshio')); ?></strong>
<?php printf('%s', $tags_list); ?>
</div>
<?php endif; ?>
</aside>
<?php
}
}
if (!function_exists('freshio_paging_nav')) {
/**
* Display navigation to next/previous set of posts when applicable.
*/
function freshio_paging_nav()
{
global $wp_query;
$args = array(
'type' => 'list',
'next_text' => _x('Next', 'Next post', 'freshio'),
'prev_text' => _x('Previous', 'Previous post', 'freshio'),
);
the_posts_pagination($args);
}
}
if (!function_exists('freshio_post_nav')) {
/**
* Display navigation to next/previous post when applicable.
*/
function freshio_post_nav()
{
$prev_post = get_previous_post();
$next_post = get_next_post();
$args = array(
'next_text' => get_the_post_thumbnail($next_post->ID, array(110, 110)) . '<span class="nav-content"><span class="reader-text">' . esc_html__('NEXT', 'freshio') . ' </span>%title' . '</span> ',
'prev_text' => get_the_post_thumbnail($prev_post->ID, array(110, 110)) . '<span class="nav-content"><span class="reader-text">' . esc_html__('PREV', 'freshio') . ' </span>%title' . '</span> ',
);
the_post_navigation($args);
}
}
if (!function_exists('freshio_posted_on')) {
/**
* Prints HTML with meta information for the current post-date/time and author.
*
* @deprecated 2.4.0
*/
function freshio_posted_on()
{
_deprecated_function('freshio_posted_on', '2.4.0');
}
}
if (!function_exists('freshio_homepage_content')) {
/**
* Display homepage content
* Hooked into the `homepage` action in the homepage template
*
* @return void
* @since 1.0.0
*/
function freshio_homepage_content()
{
while (have_posts()) {
the_post();
get_template_part('content', 'homepage');
} // end of the loop.
}
}
if (!function_exists('freshio_social_icons')) {
/**
* Display social icons
* If the subscribe and connect plugin is active, display the icons.
*
* @link http://wordpress.org/plugins/subscribe-and-connect/
* @since 1.0.0
*/
function freshio_social_icons()
{
if (class_exists('Subscribe_And_Connect')) {
echo '<div class="subscribe-and-connect-connect">';
subscribe_and_connect_connect();
echo '</div>';
}
}
}
if (!function_exists('freshio_get_sidebar')) {
/**
* Display freshio sidebar
*
* @uses get_sidebar()
* @since 1.0.0
*/
function freshio_get_sidebar()
{
get_sidebar();
}
}
if (!function_exists('freshio_post_header_single')) {
function freshio_post_header_single($size = 'post-thumbnail')
{
freshio_categories_link();
the_title('<h1 class="entry-title">', '</h1>');
?>
<div class="entry-header">
<div class="entry-meta">
<?php
freshio_post_meta();
?>
</div>
</div>
<?php
}
}
if (!function_exists('freshio_post_thumbnail')) {
/**
* Display post thumbnail
*
* @param string $size the post thumbnail size.
*
* @uses has_post_thumbnail()
* @uses the_post_thumbnail
* @var $size thumbnail size. thumbnail|medium|large|full|$custom
* @since 1.5.0
*/
function freshio_post_thumbnail($size = 'post-thumbnail')
{
echo '<div class="post-thumbnail">';
if (has_post_thumbnail()) {
the_post_thumbnail($size ? $size : 'post-thumbnail');
}
if (!is_single()) {
freshio_categories_link();
}
echo '</div>';
}
}
if (!function_exists('freshio_primary_navigation_wrapper')) {
/**
* The primary navigation wrapper
*/
function freshio_primary_navigation_wrapper()
{
echo '<div class="freshio-primary-navigation"><div class="col-full">';
}
}
if (!function_exists('freshio_primary_navigation_wrapper_close')) {
/**
* The primary navigation wrapper close
*/
function freshio_primary_navigation_wrapper_close()
{
echo '</div></div>';
}
}
if (!function_exists('freshio_header_container')) {
/**
* The header container
*/
function freshio_header_container()
{
echo '<div class="col-full">';
}
}
if (!function_exists('freshio_header_container_close')) {
/**
* The header container close
*/
function freshio_header_container_close()
{
echo '</div>';
}
}
if (!function_exists('freshio_breadcrumb')) {
function freshio_breadcrumb()
{
if (!is_page_template('template-homepage.php')) {
get_template_part('template-parts/breadcrumb');
}
}
}
if (!function_exists('freshio_header_custom_link')) {
function freshio_header_custom_link()
{
echo freshio_get_theme_option('custom-link', '');
}
}
if (!function_exists('freshio_header_contact_info')) {
function freshio_header_contact_info()
{
echo freshio_get_theme_option('contact-info', '');
}
}
if (!function_exists('freshio_header_account')) {
function freshio_header_account()
{
if (!freshio_get_theme_option('show-header-account', true)) {
return;
}
if (freshio_is_woocommerce_activated()) {
$account_link = get_permalink(get_option('woocommerce_myaccount_page_id'));
} else {
$account_link = wp_login_url();
}
?>
<div class="site-header-account">
<a href="<?php echo esc_html($account_link); ?>"><i class="freshio-icon-user"></i></a>
<div class="account-dropdown">
</div>
</div>
<?php
}
}
if (!function_exists('freshio_template_account_dropdown')) {
function freshio_template_account_dropdown()
{
if (!freshio_get_theme_option('show-header-account', true)) {
return;
}
?>
<div class="account-wrap" style="display: none;">
<div class="account-inner <?php if (is_user_logged_in()): echo "dashboard"; endif; ?>">
<?php if (!is_user_logged_in()) {
freshio_form_login();
} else {
freshio_account_dropdown();
}
?>
</div>
</div>
<?php
}
}
if (!function_exists('freshio_form_login')) {
function freshio_form_login()
{
if (freshio_is_woocommerce_activated()) {
$account_link = get_permalink(get_option('woocommerce_myaccount_page_id'));
} else {
$account_link = wp_registration_url();
}
?>
<div class="login-form-head">
<span class="login-form-title"><?php esc_attr_e('Sign in', 'freshio') ?></span>
<span class="pull-right">
<a class="register-link" href="<?php echo esc_url($account_link); ?>"
title="<?php esc_attr_e('Register', 'freshio'); ?>"><?php esc_attr_e('Create an Account', 'freshio'); ?></a>
</span>
</div>
<form class="freshio-login-form-ajax" data-toggle="validator">
<p>
<label><?php esc_attr_e('Username or email', 'freshio'); ?> <span class="required">*</span></label>
<input name="username" type="text" required placeholder="<?php esc_attr_e('Username', 'freshio') ?>">
</p>
<p>
<label><?php esc_attr_e('Password', 'freshio'); ?> <span class="required">*</span></label>
<input name="password" type="password" required
placeholder="<?php esc_attr_e('Password', 'freshio') ?>">
</p>
<button type="submit" data-button-action
class="btn btn-primary btn-block w-100 mt-1"><?php esc_html_e('Login', 'freshio') ?></button>
<input type="hidden" name="action" value="freshio_login">
<?php wp_nonce_field('ajax-freshio-login-nonce', 'security-login'); ?>
</form>
<div class="login-form-bottom">
<a href="<?php echo wp_lostpassword_url(get_permalink()); ?>" class="lostpass-link"
title="<?php esc_attr_e('Lost your password?', 'freshio'); ?>"><?php esc_attr_e('Lost your password?', 'freshio'); ?></a>
</div>
<?php
}
}
if (!function_exists('freshio_account_dropdown')) {
function freshio_account_dropdown()
{ ?>
<?php if (has_nav_menu('my-account')) : ?>
<nav class="social-navigation" role="navigation" aria-label="<?php esc_attr_e('Dashboard', 'freshio'); ?>">
<?php
wp_nav_menu(array(
'theme_location' => 'my-account',
'menu_class' => 'account-links-menu',
'depth' => 1,
));
?>
</nav><!-- .social-navigation -->
<?php else: ?>
<ul class="account-dashboard">
<?php if (freshio_is_woocommerce_activated()): ?>
<li>
<a href="<?php echo esc_url(wc_get_page_permalink('myaccount')); ?>"
title="<?php esc_html_e('Dashboard', 'freshio'); ?>"><?php esc_html_e('Dashboard', 'freshio'); ?></a>
</li>
<li>
<a href="<?php echo esc_url(wc_get_account_endpoint_url('orders')); ?>"
title="<?php esc_html_e('Orders', 'freshio'); ?>"><?php esc_html_e('Orders', 'freshio'); ?></a>
</li>
<li>
<a href="<?php echo esc_url(wc_get_account_endpoint_url('downloads')); ?>"
title="<?php esc_html_e('Downloads', 'freshio'); ?>"><?php esc_html_e('Downloads', 'freshio'); ?></a>
</li>
<li>
<a href="<?php echo esc_url(wc_get_account_endpoint_url('edit-address')); ?>"
title="<?php esc_html_e('Edit Address', 'freshio'); ?>"><?php esc_html_e('Edit Address', 'freshio'); ?></a>
</li>
<li>
<a href="<?php echo esc_url(wc_get_account_endpoint_url('edit-account')); ?>"
title="<?php esc_html_e('Account Details', 'freshio'); ?>"><?php esc_html_e('Account Details', 'freshio'); ?></a>
</li>
<?php else: ?>
<li>
<a href="<?php echo esc_url(get_dashboard_url(get_current_user_id())); ?>"
title="<?php esc_html_e('Dashboard', 'freshio'); ?>"><?php esc_html_e('Dashboard', 'freshio'); ?></a>
</li>
<?php endif; ?>
<li>
<a title="<?php esc_html_e('Log out', 'freshio'); ?>" class="tips"
href="<?php echo esc_url(wp_logout_url(home_url())); ?>"><?php esc_html_e('Logout', 'freshio'); ?></a>
</li>
</ul>
<?php endif;
}
}
if (!function_exists('freshio_header_search_popup')) {
function freshio_header_search_popup()
{
?>
<div class="site-search-popup">
<div class="site-search-popup-wrap">
<a href="#" class="site-search-popup-close"><i class="freshio-icon-times-circle"></i></a>
<?php
if (freshio_is_woocommerce_activated()) {
freshio_product_search();
} else {
?>
<div class="site-search">
<?php get_search_form(); ?>
</div>
<?php
}
?>
</div>
</div>
<?php
}
}
if (!function_exists('freshio_header_search_button')) {
function freshio_header_search_button()
{
if (!freshio_get_theme_option('show-header-search', true)) {
return;
}
add_action('wp_footer', 'freshio_header_search_popup', 1);
wp_enqueue_script('freshio-search-popup');
?>
<div class="site-header-search">
<a href="#" class="button-search-popup"><i class="freshio-icon-search"></i></a>
</div>
<?php
}
}
if (!function_exists('freshio_header_sticky')) {
function freshio_header_sticky()
{
get_template_part('template-parts/header', 'sticky');
}
}
if (!function_exists('freshio_mobile_nav')) {
function freshio_mobile_nav()
{
if (isset(get_nav_menu_locations()['handheld'])) {
?>
<div class="freshio-mobile-nav">
<a href="#" class="mobile-nav-close"><i class="freshio-icon-times"></i></a>
<?php
freshio_language_switcher_mobile();
freshio_mobile_navigation();
freshio_social();
?>
</div>
<div class="freshio-overlay"></div>
<?php
}
}
}
if (!function_exists('freshio_mobile_nav_button')) {
function freshio_mobile_nav_button(){
if (isset(get_nav_menu_locations()['handheld'])) {
wp_enqueue_script('freshio-nav-mobile');
?>
<a href="#" class="menu-mobile-nav-button">
<span
class="toggle-text screen-reader-text"><?php echo esc_attr(apply_filters('freshio_menu_toggle_text', esc_html__('Menu', 'freshio'))); ?></span>
<i class="freshio-icon-bars"></i>
</a>
<?php
}
}
}
if (!function_exists('freshio_language_switcher')) {
function freshio_language_switcher()
{
$languages = apply_filters('wpml_active_languages', []);
if (!freshio_is_wpml_activated() || count($languages) <= 0) {
return;
}
?>
<div class="freshio-language-switcher">
<ul class="menu">
<li class="item">
<span>
<img width="18" height="12"
src="<?php echo esc_url($languages[ICL_LANGUAGE_CODE]['country_flag_url']) ?>"
alt="<?php esc_attr($languages[ICL_LANGUAGE_CODE]['default_locale']) ?>">
<?php
echo esc_html($languages[ICL_LANGUAGE_CODE]['translated_name']);
?>
</span>
<ul class="sub-item">
<?php
foreach ($languages as $key => $language) {
if (ICL_LANGUAGE_CODE === $key) {
continue;
}
?>
<li>
<a href="<?php echo esc_url($language['url']) ?>">
<img width="18" height="12"
src="<?php echo esc_url($language['country_flag_url']) ?>"
alt="<?php esc_attr($language['default_locale']) ?>">
<?php echo esc_html($language['translated_name']); ?>
</a>
</li>
<?php
}
?>
</ul>
</li>
</ul>
</div>
<?php
}
}
if (!function_exists('freshio_language_switcher_mobile')) {
function freshio_language_switcher_mobile()
{
$languages = apply_filters('wpml_active_languages', []);
if (!freshio_is_wpml_activated() || count($languages) <= 0) {
return;
}
?>
<div class="freshio-language-switcher-mobile">
<span>
<img width="18" height="12"
src="<?php echo esc_url($languages[ICL_LANGUAGE_CODE]['country_flag_url']) ?>"
alt="<?php esc_attr($languages[ICL_LANGUAGE_CODE]['default_locale']) ?>">
</span>
<?php
foreach ($languages as $key => $language) {
if (ICL_LANGUAGE_CODE === $key) {
continue;
}
?>
<a href="<?php echo esc_url($language['url']) ?>">
<img width="18" height="12" src="<?php echo esc_url($language['country_flag_url']) ?>"
alt="<?php esc_attr($language['default_locale']) ?>">
</a>
<?php
}
?>
</div>
<?php
}
}
if (!function_exists('freshio_footer_default')) {
function freshio_footer_default()
{
// freshio_footer_widgets();
get_template_part('template-parts/copyright');
}
}
if (!function_exists('freshio_pingback_header')) {
/**
* Add a pingback url auto-discovery header for single posts, pages, or attachments.
*/
function freshio_pingback_header()
{
if (is_singular() && pings_open()) {
echo '<link rel="pingback" href="', esc_url(get_bloginfo('pingback_url')), '">';
}
}
}
if (!function_exists('freshio_social_share')) {
function freshio_social_share()
{
get_template_part('template-parts/socials');
}
}
if (!function_exists('modify_read_more_link')) {
function modify_read_more_link()
{
return '<p class="more-link-wrap"><a class="more-link" href="' . get_permalink() . '"><span>' . esc_html__('Read More', 'freshio') . '<i class="freshio-icon-angle-double-right"></i></span></a></p>';
}
}
add_filter('the_content_more_link', 'modify_read_more_link');
if (!function_exists('freshio_update_comment_fields')) {
function freshio_update_comment_fields($fields)
{
$commenter = wp_get_current_commenter();
$req = get_option('require_name_email');
$aria_req = $req ? "aria-required='true'" : '';
$fields['author']
= '<p class="comment-form-author">
<input id="author" name="author" type="text" placeholder="' . esc_attr__("Your Name *", "freshio") . '" value="' . esc_attr($commenter['comment_author']) .
'" size="30" ' . $aria_req . ' />
</p>';
$fields['email']
= '<p class="comment-form-email">
<input id="email" name="email" type="email" placeholder="' . esc_attr__("Email Address *", "freshio") . '" value="' . esc_attr($commenter['comment_author_email']) .
'" size="30" ' . $aria_req . ' />
</p>';
$fields['url']
= '<p class="comment-form-url">
<input id="url" name="url" type="url" placeholder="' . esc_attr__("Your Website", "freshio") . '" value="' . esc_attr($commenter['comment_author_url']) .
'" size="30" />
</p>';
return $fields;
}
}
add_filter('comment_form_default_fields', 'freshio_update_comment_fields');
| true |
7fcd3fc89cf9f646eeccaeb401b3720b2a1cf846 | PHP | ledo4ek/NewST | /protected/helpers/CStringHelper.php | UTF-8 | 1,001 | 3.0625 | 3 | [] | no_license | <?php
class CStringHelper
{
// Это не универсальный вариант, так что лучше через Yii::t
public static function getCase($text, $count)
{
if (strlen($count) > 2)
$count = substr($count, strlen($count) - 2);
if ($count > 30)
$count = 20 + substr($count, strlen($count) - 1);
switch (true)
{
case $count == 0:
$end = 'иев';
break;
case $count == 1:
$end = 'ий';
break;
case $count <= 4:
$end = 'ия';
break;
case $count <= 20:
$end = 'иев';
break;
case $count == 21:
$end = 'ий';
break;
case $count <= 24:
$end = 'ия';
break;
case $count <= 30:
$end = 'иев';
}
return $text . $end;
}
public static function trimContent($text)
{
$text_elements = explode('.', $text);
if (count($text_elements) > 5)
{
$text_elements = array_slice($text_elements, 0, 5);
$text = implode('.', $text_elements) . '';
}
return $text;
}
}
| true |
8bec84cf89b9417ba1aa9018eeb6a6eeead77a22 | PHP | petebacondarwin/sapphire | /email/Email.php | UTF-8 | 22,081 | 2.6875 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
/**
* @package sapphire
* @subpackage email
*/
if(isset($_SERVER['SERVER_NAME'])) {
/**
* X-Mailer header value on emails sent
*/
define('X_MAILER', 'SilverStripe Mailer - version 2006.06.21 (Sent from "'.$_SERVER['SERVER_NAME'].'")');
} else {
/**
* @ignore
*/
define('X_MAILER', 'SilverStripe Mailer - version 2006.06.21');
}
// Note: The constant 'BOUNCE_EMAIL' should be defined as a valid email address for where bounces should be returned to.
/**
* Class to support sending emails.
* @package sapphire
* @subpackage email
*/
class Email extends ViewableData {
/**
* @param string $from Email-Address
*/
protected $from;
/**
* @param string $to Email-Address. Use comma-separation to pass multiple email-addresses.
*/
protected $to;
/**
* @param string $subject Subject of the email
*/
protected $subject;
/**
* @param string $body HTML content of the email.
* Passed straight into {@link $ss_template} as $Body variable.
*/
protected $body;
/**
* @param string $plaintext_body Optional string for plaintext emails.
* If not set, defaults to converting the HTML-body with {@link Convert::xml2raw()}.
*/
protected $plaintext_body;
/**
* @param string $cc
*/
protected $cc;
/**
* @param string $bcc
*/
protected $bcc;
/**
* @param Mailer $mailer Instance of a {@link Mailer} class.
*/
protected static $mailer;
/**
* This can be used to provide a mailer class other than the default, e.g. for testing.
*
* @param Mailer $mailer
*/
static function set_mailer(Mailer $mailer) {
self::$mailer = $mailer;
}
/**
* Get the mailer.
*
* @return Mailer
*/
static function mailer() {
if(!self::$mailer) self::$mailer = new Mailer();
return self::$mailer;
}
/**
* @param array $customHeaders A map of header-name -> header-value
*/
protected $customHeaders = array();
/**
* @param array $attachements Internal, use {@link attachFileFromString()} or {@link attachFile()}
*/
protected $attachments = array();
/**
* @param boolean $
*/
protected $parseVariables_done = false;
/**
* @param string $ss_template The name of the used template (without *.ss extension)
*/
protected $ss_template = "GenericEmail";
/**
* @param array $template_data Additional data available in a template.
* Used in the same way than {@link ViewableData->customize()}.
*/
protected $template_data = null;
/**
* @param string $bounceHandlerURL
*/
protected $bounceHandlerURL = null;
/**
* @param sring $admin_email_address The default administrator email address.
* This will be set in the config on a site-by-site basis
*/
static $admin_email_address = '';
/**
* @param string $send_all_emails_to Email-Address
*/
protected static $send_all_emails_to = null;
/**
* @param string $bcc_all_emails_to Email-Address
*/
protected static $bcc_all_emails_to = null;
/**
* @param string $cc_all_emails_to Email-Address
*/
protected static $cc_all_emails_to = null;
/**
* Create a new email.
*/
public function __construct($from = null, $to = null, $subject = null, $body = null, $bounceHandlerURL = null, $cc = null, $bcc = null) {
if($from != null) $this->from = $from;
if($to != null) $this->to = $to;
if($subject != null) $this->subject = $subject;
if($body != null) $this->body = $body;
if($cc != null) $this->cc = $cc;
if($bcc != null) $this->bcc = $bcc;
if($bounceHandlerURL != null) $this->setBounceHandlerURL($bounceHandlerURL);
parent::__construct();
}
public function attachFileFromString($data, $filename, $mimetype = null) {
$this->attachments[] = array(
'contents' => $data,
'filename' => $filename,
'mimetype' => $mimetype,
);
}
public function setBounceHandlerURL( $bounceHandlerURL ) {
if($bounceHandlerURL) {
$this->bounceHandlerURL = $bounceHandlerURL;
} else {
$this->bounceHandlerURL = $_SERVER['HTTP_HOST'] . Director::baseURL() . 'Email_BounceHandler';
}
}
public function attachFile($filename, $attachedFilename = null, $mimetype = null) {
if(!$attachedFilename) $attachedFilename = basename($filename);
$absoluteFileName = Director::getAbsFile($filename);
if(file_exists($absoluteFileName)) {
$this->attachFileFromString(file_get_contents($absoluteFileName), $attachedFilename, $mimetype);
} else {
user_error("Could not attach '$absoluteFileName' to email. File does not exist.", E_USER_NOTICE);
}
}
public function Subject() {
return $this->subject;
}
public function Body() {
return $this->body;
}
public function To() {
return $this->to;
}
public function From() {
return $this->from;
}
public function Cc() {
return $this->cc;
}
public function Bcc() {
return $this->bcc;
}
public function setSubject($val) {
$this->subject = $val;
}
public function setBody($val) {
$this->body = $val;
}
public function setTo($val) {
$this->to = $val;
}
public function setFrom($val) {
$this->from = $val;
}
public function setCc($val) {
$this->cc = $val;
}
public function setBcc($val) {
$this->bcc = $val;
}
/**
* Set the "Reply-To" header with an email address.
* @param string $email The email address of the "Reply-To" header
*/
public function replyTo($email) {
$this->addCustomHeader('Reply-To', $email);
}
/**
* Add a custom header to this value.
* Useful for implementing all those cool features that we didn't think of.
*
* @param string $headerName
* @param string $headerValue
*/
public function addCustomHeader($headerName, $headerValue) {
if($headerName == 'Cc') $this->cc = $headerValue;
else if($headerName == 'Bcc') $this->bcc = $headerValue;
else {
if(isset($this->customHeaders[$headerName])) $this->customHeaders[$headerName] .= ", " . $headerValue;
else $this->customHeaders[$headerName] = $headerValue;
}
}
public function BaseURL() {
return Director::absoluteBaseURL();
}
/**
* Debugging help
*/
public function debug() {
$this->parseVariables();
return "<h2>Email template $this->class</h2>\n" .
"<p><b>From:</b> $this->from\n" .
"<b>To:</b> $this->to\n" .
"<b>Cc:</b> $this->cc\n" .
"<b>Bcc:</b> $this->bcc\n" .
"<b>Subject:</b> $this->subject</p>" .
$this->body;
}
/**
* Set template name (without *.ss extension).
*
* @param string $template
*/
public function setTemplate($template) {
$this->ss_template = $template;
}
/**
* @return string
*/
public function getTemplate() {
return $this->ss_template;
}
protected function templateData() {
if($this->template_data) {
return $this->template_data->customise(array(
"To" => $this->to,
"Cc" => $this->cc,
"Bcc" => $this->bcc,
"From" => $this->from,
"Subject" => $this->subject,
"Body" => $this->body,
"BaseURL" => $this->BaseURL(),
"IsEmail" => true,
));
} else {
return $this;
}
}
/**
* Used by {@link SSViewer} templates to detect if we're rendering an email template rather than a page template
*/
public function IsEmail() {
return true;
}
/**
* Populate this email template with values.
* This may be called many times.
*/
function populateTemplate($data) {
if($this->template_data) {
$this->template_data = $this->template_data->customise($data);
} else {
if(is_array($data)) $data = new ArrayData($data);
$this->template_data = $this->customise($data);
}
$this->parseVariables_done = false;
}
/**
* Load all the template variables into the internal variables, including
* the template into body. Called before send() or debugSend()
* $isPlain=true will cause the template to be ignored, otherwise the GenericEmail template will be used
* and it won't be plain email :)
*/
protected function parseVariables($isPlain = false) {
SSViewer::set_source_file_comments(false);
if(!$this->parseVariables_done) {
$this->parseVariables_done = true;
// Parse $ variables in the base parameters
$data = $this->templateData();
// Process a .SS template file
$fullBody = $this->body;
if($this->ss_template && !$isPlain) {
// Requery data so that updated versions of To, From, Subject, etc are included
$data = $this->templateData();
$template = new SSViewer($this->ss_template);
if($template->exists()) {
$fullBody = $template->process($data);
}
}
// Rewrite relative URLs
$this->body = HTTP::absoluteURLs($fullBody);
}
}
/**
* @desc Validates the email address. Returns true of false
*/
static function validEmailAddress($address) {
return ereg('^([a-zA-Z0-9_+\.\-]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$', $address);
}
/**
* Send the email in plaintext.
*
* @see send() for sending emails with HTML content.
* @uses Mailer->sendPlain()
*
* @param string $messageID Optional message ID so the message can be identified in bounces etc.
* @return bool Success of the sending operation from an MTA perspective.
* Doesn't actually give any indication if the mail has been delivered to the recipient properly)
*/
function sendPlain($messageID = null) {
Requirements::clear();
$this->parseVariables(true);
if(empty($this->from)) $this->from = Email::getAdminEmail();
$this->setBounceHandlerURL($this->bounceHandlerURL);
$headers = $this->customHeaders;
$headers['X-SilverStripeBounceURL'] = $this->bounceHandlerURL;
if($messageID) $headers['X-SilverStripeMessageID'] = project() . '.' . $messageID;
if(project()) $headers['X-SilverStripeSite'] = project();
$to = $this->to;
$subject = $this->subject;
if(self::$send_all_emails_to) {
$subject .= " [addressed to $to";
$to = self::$send_all_emails_to;
if($this->cc) $subject .= ", cc to $this->cc";
if($this->bcc) $subject .= ", bcc to $this->bcc";
$subject .= ']';
} else {
if($this->cc) $headers['Cc'] = $this->cc;
if($this->bcc) $headers['Bcc'] = $this->bcc;
}
if(self::$cc_all_emails_to) {
if(!empty($headers['Cc']) && trim($headers['Cc'])) {
$headers['Cc'] .= ', ' . self::$cc_all_emails_to;
} else {
$headers['Cc'] = self::$cc_all_emails_to;
}
}
if(self::$bcc_all_emails_to) {
if(!empty($headers['Bcc']) && trim($headers['Bcc'])) {
$headers['Bcc'] .= ', ' . self::$bcc_all_emails_to;
} else {
$headers['Bcc'] = self::$bcc_all_emails_to;
}
}
Requirements::restore();
return self::mailer()->sendPlain($to, $this->from, $subject, $this->body, $this->attachments, $headers);
}
/**
* Send an email with HTML content.
*
* @see sendPlain() for sending plaintext emails only.
* @uses Mailer->sendHTML()
*
* @param string $messageID Optional message ID so the message can be identified in bounces etc.
* @return bool Success of the sending operation from an MTA perspective.
* Doesn't actually give any indication if the mail has been delivered to the recipient properly)
*/
public function send($messageID = null) {
Requirements::clear();
$this->parseVariables();
if(empty($this->from)) $this->from = Email::getAdminEmail();
$this->setBounceHandlerURL( $this->bounceHandlerURL );
$headers = $this->customHeaders;
$headers['X-SilverStripeBounceURL'] = $this->bounceHandlerURL;
if($messageID) $headers['X-SilverStripeMessageID'] = project() . '.' . $messageID;
if(project()) $headers['X-SilverStripeSite'] = project();
$to = $this->to;
$subject = $this->subject;
if(self::$send_all_emails_to) {
$subject .= " [addressed to $to";
$to = self::$send_all_emails_to;
if($this->cc) $subject .= ", cc to $this->cc";
if($this->bcc) $subject .= ", bcc to $this->bcc";
$subject .= ']';
unset($headers['Cc']);
unset($headers['Bcc']);
} else {
if($this->cc) $headers['Cc'] = $this->cc;
if($this->bcc) $headers['Bcc'] = $this->bcc;
}
if(self::$cc_all_emails_to) {
if(!empty($headers['Cc']) && trim($headers['Cc'])) {
$headers['Cc'] .= ', ' . self::$cc_all_emails_to;
} else {
$headers['Cc'] = self::$cc_all_emails_to;
}
}
if(self::$bcc_all_emails_to) {
if(!empty($headers['Bcc']) && trim($headers['Bcc'])) {
$headers['Bcc'] .= ', ' . self::$bcc_all_emails_to;
} else {
$headers['Bcc'] = self::$bcc_all_emails_to;
}
}
Requirements::restore();
return self::mailer()->sendHTML($to, $this->from, $subject, $this->body, $this->attachments, $headers, $this->plaintext_body);
}
/**
* Used as a default sender address in the {@link Email} class
* unless overwritten. Also shown to users on live environments
* as a contact address on system error pages.
*
* Used by {@link Email->send()}, {@link Email->sendPlain()}, {@link Debug->friendlyError()}.
*
* @param string $newEmail
*/
public static function setAdminEmail($newEmail) {
self::$admin_email_address = $newEmail;
}
/**
* @return string
*/
public static function getAdminEmail() {
return self::$admin_email_address;
}
/**
* Send every email generated by the Email class to the given address.
* It will also add " [addressed to (email), cc to (email), bcc to (email)]" to the end of the subject line
* This can be used when testing, by putting a command like this in your _config.php file
*
* if(!Director::isLive()) Email::send_all_emails_to("someone@example.com")
*/
public static function send_all_emails_to($emailAddress) {
self::$send_all_emails_to = $emailAddress;
}
/**
* CC every email generated by the Email class to the given address.
* It won't affect the original delivery in the same way that send_all_emails_to does. It just adds a CC header
* with the given email address. Note that you can only call this once - subsequent calls will overwrite the configuration
* variable.
*
* This can be used when you have a system that relies heavily on email and you want someone to be checking all correspondence.
*
* if(Director::isLive()) Email::cc_all_emails_to("supportperson@example.com")
*/
public static function cc_all_emails_to($emailAddress) {
self::$cc_all_emails_to = $emailAddress;
}
/**
* BCC every email generated by the Email class to the given address.
* It won't affect the original delivery in the same way that send_all_emails_to does. It just adds a BCC header
* with the given email address. Note that you can only call this once - subsequent calls will overwrite the configuration
* variable.
*
* This can be used when you have a system that relies heavily on email and you want someone to be checking all correspondence.
*
* if(Director::isLive()) Email::cc_all_emails_to("supportperson@example.com")
*/
public static function bcc_all_emails_to($emailAddress) {
self::$bcc_all_emails_to = $emailAddress;
}
/**
* Checks for RFC822-valid email format.
*
* @param string $str
* @return boolean
*
* @copyright Cal Henderson <cal@iamcal.com>
* This code is licensed under a Creative Commons Attribution-ShareAlike 2.5 License
* http://creativecommons.org/licenses/by-sa/2.5/
*/
function is_valid_address($email){
$qtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]';
$dtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]';
$atom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c'.
'\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+';
$quoted_pair = '\\x5c[\\x00-\\x7f]';
$domain_literal = "\\x5b($dtext|$quoted_pair)*\\x5d";
$quoted_string = "\\x22($qtext|$quoted_pair)*\\x22";
$domain_ref = $atom;
$sub_domain = "($domain_ref|$domain_literal)";
$word = "($atom|$quoted_string)";
$domain = "$sub_domain(\\x2e$sub_domain)*";
$local_part = "$word(\\x2e$word)*";
$addr_spec = "$local_part\\x40$domain";
return preg_match("!^$addr_spec$!", $email) ? 1 : 0;
}
/**
* Encode an email-address to protect it from spambots.
* At the moment only simple string substitutions,
* which are not 100% safe from email harvesting.
*
* @todo Integrate javascript-based solution
*
* @param string $email Email-address
* @param string $method Method for obfuscating/encoding the address
* - 'direction': Reverse the text and then use CSS to put the text direction back to normal
* - 'visible': Simple string substitution ('@' to '[at]', '.' to '[dot], '-' to [dash])
* - 'hex': Hexadecimal URL-Encoding - useful for mailto: links
* @return string
*/
public static function obfuscate($email, $method = 'visible') {
switch($method) {
case 'direction' :
Requirements::customCSS(
'span.codedirection { unicode-bidi: bidi-override; direction: rtl; }',
'codedirectionCSS'
);
return '<span class="codedirection">' . strrev($email) . '</span>';
case 'visible' :
$obfuscated = array('@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] ');
return strtr($email, $obfuscated);
case 'hex' :
$encoded = '';
for ($x=0; $x < strlen($email); $x++) $encoded .= '&#x' . bin2hex($email{$x}).';';
return $encoded;
default:
user_error('Email::obfuscate(): Unknown obfuscation method', E_USER_NOTICE);
return $email;
}
}
}
/**
* Base class that email bounce handlers extend
* @package sapphire
* @subpackage email
*/
class Email_BounceHandler extends Controller {
static $allowed_actions = array(
'index'
);
function init() {
BasicAuth::protect_entire_site(false);
parent::init();
}
function index() {
$subclasses = ClassInfo::subclassesFor( $this->class );
unset($subclasses[$this->class]);
if( $subclasses ) {
$subclass = array_pop( $subclasses );
$task = new $subclass();
$task->index();
return;
}
// Check if access key exists
if( !isset($_REQUEST['Key']) ) {
echo 'Error: Access validation failed. No "Key" specified.';
return;
}
// Check against access key defined in sapphire/_config.php
if( $_REQUEST['Key'] != EMAIL_BOUNCEHANDLER_KEY) {
echo 'Error: Access validation failed. Invalid "Key" specified.';
return;
}
if( !$_REQUEST['Email'] ) {
echo "No email address";
return;
}
$this->recordBounce( $_REQUEST['Email'], $_REQUEST['Date'], $_REQUEST['Time'], $_REQUEST['Message'] );
}
private function recordBounce( $email, $date = null, $time = null, $error = null ) {
if(ereg('<(.*)>', $email, $parts)) $email = $parts[1];
$SQL_email = Convert::raw2sql($email);
$SQL_bounceTime = Convert::raw2sql("$date $time");
$duplicateBounce = DataObject::get_one("Email_BounceRecord", "\"BounceEmail\" = '$SQL_email' AND (\"BounceTime\"+INTERVAL 1 MINUTE) > '$SQL_bounceTime'");
if(!$duplicateBounce) {
$record = new Email_BounceRecord();
$member = DataObject::get_one( 'Member', "\"Email\"='$SQL_email'" );
if( $member ) {
$record->MemberID = $member->ID;
// If the SilverStripeMessageID (taken from the X-SilverStripeMessageID header embedded in the email) is sent,
// then log this bounce in a Newsletter_SentRecipient record so it will show up on the 'Sent Status Report' tab of the Newsletter
if( isset($_REQUEST['SilverStripeMessageID'])) {
// Note: was sent out with: $project . '.' . $messageID;
$message_id_parts = explode('.', $_REQUEST['SilverStripeMessageID']);
// Note: was encoded with: base64_encode( $newsletter->ID . '_' . date( 'd-m-Y H:i:s' ) );
$newsletter_id_date_parts = explode ('_', base64_decode($message_id_parts[1]) );
// Escape just in case
$SQL_memberID = Convert::raw2sql($member->ID);
$SQL_newsletterID = Convert::raw2sql($newsletter_id_date_parts[0]);
// Log the bounce
$oldNewsletterSentRecipient = DataObject::get_one("Newsletter_SentRecipient", "\"MemberID\" = '$SQL_memberID' AND \"ParentID\" = '$SQL_newsletterID' AND \"Email\" = '$SQL_email'");
// Update the Newsletter_SentRecipient record if it exists
if($oldNewsletterSentRecipient) {
$oldNewsletterSentRecipient->Result = 'Bounced';
$oldNewsletterSentRecipient->write();
} else {
// For some reason it didn't exist, create a new record
$newNewsletterSentRecipient = new Newsletter_SentRecipient();
$newNewsletterSentRecipient->Email = $SQL_email;
$newNewsletterSentRecipient->MemberID = $member->ID;
$newNewsletterSentRecipient->Result = 'Bounced';
$newNewsletterSentRecipient->ParentID = $newsletter_id_date_parts[0];
$newNewsletterSentRecipient->write();
}
// Now we are going to Blacklist this member so that email will not be sent to them in the future.
// Note: Sending can be re-enabled by going to 'Mailing List' 'Bounced' tab and unchecking the box under 'Blacklisted'
$member->setBlacklistedEmail(TRUE);
echo '<p><b>Member: '.$member->FirstName.' '.$member->Surname.' <'.$member->Email.'> was added to the Email Blacklist!</b></p>';
}
}
if( !$date )
$date = date( 'd-m-Y' );
/*else
$date = date( 'd-m-Y', strtotime( $date ) );*/
if( !$time )
$time = date( 'H:i:s' );
/*else
$time = date( 'H:i:s', strtotime( $time ) );*/
$record->BounceEmail = $email;
$record->BounceTime = $date . ' ' . $time;
$record->BounceMessage = $error;
$record->write();
echo "Handled bounced email to address: $email";
} else {
echo 'Sorry, this bounce report has already been logged, not logging this duplicate bounce.';
}
}
}
/**
* Database record for recording a bounced email
* @package sapphire
* @subpackage email
*/
class Email_BounceRecord extends DataObject {
static $db = array(
'BounceEmail' => 'Varchar',
'BounceTime' => 'SS_Datetime',
'BounceMessage' => 'Varchar'
);
static $has_one = array(
'Member' => 'Member'
);
static $has_many = array();
static $many_many = array();
static $defaults = array();
static $singular_name = 'Email Bounce Record';
/**
* a record of Email_BounceRecord can't be created manually. Instead, it should be
* created though system.
*/
public function canCreate($member = null) {
return false;
}
}
?>
| true |
898900bca44dae82d179be67a12944835ad9a589 | PHP | dexcell/CE | /classes/kohana/ce.php | UTF-8 | 813 | 2.796875 | 3 | [] | no_license | <?php defined('SYSPATH') or die('No direct access allowed.');
abstract class Kohana_CE {
// CE instances
protected static $_instance;
protected $_config = array();
/**
* Singleton pattern
*
* @return CE
*/
public static function instance()
{
if ( ! isset(CE::$_instance))
{
// Load the configuration for this type
$config = Kohana::$config->load('ce');
if ( ! $type = $config->get('driver'))
{
$type = 'google';
}
// Set the class name
$class = 'CE_'.ucfirst($type);
// Create a new instance
CE::$_instance = new $class($config);
}
return CE::$_instance;
}
public function __construct($config)
{
$this->_config = $config;
}
abstract public function convert($amount, $from, $to);
} | true |
b7302c6badc29096603f58ef7b24087d54e3f92c | PHP | symfony/symfony | /src/Symfony/Component/Scheduler/Trigger/JitterTrigger.php | UTF-8 | 1,023 | 2.609375 | 3 | [
"MIT"
] | permissive | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Scheduler\Trigger;
/**
* @author Kevin Bond <kevinbond@gmail.com>
*/
final class JitterTrigger extends AbstractDecoratedTrigger
{
/**
* @param positive-int $maxSeconds
*/
public function __construct(private readonly TriggerInterface $trigger, private readonly int $maxSeconds = 60)
{
parent::__construct($trigger);
}
public function __toString(): string
{
return sprintf('%s with 0-%d second jitter', $this->trigger, $this->maxSeconds);
}
public function getNextRunDate(\DateTimeImmutable $run): ?\DateTimeImmutable
{
if (!$nextRun = $this->trigger->getNextRunDate($run)) {
return null;
}
return $nextRun->add(new \DateInterval(sprintf('PT%sS', random_int(0, $this->maxSeconds))));
}
}
| true |
6e611720584183cc456e1ad2ac4c4c6476a95d15 | PHP | jadob/jadob | /src/Jadob/Bridge/Twig/Extension/PathExtension.php | UTF-8 | 2,226 | 2.765625 | 3 | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | <?php
declare(strict_types=1);
namespace Jadob\Bridge\Twig\Extension;
use Jadob\Router\Exception\RouteNotFoundException;
use Jadob\Router\Router;
use function ltrim;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
/**
*
* @author pizzaminded <mikolajczajkowsky@gmail.com>
* @license MIT
*/
class PathExtension extends AbstractExtension
{
/**
* @var Router
*/
private Router $router;
/**
* PathExtension constructor.
*
* @param Router $router
*/
public function __construct(Router $router)
{
$this->router = $router;
}
/**
* @return TwigFunction[]
*/
public function getFunctions(): array
{
return [
new TwigFunction('path', [$this, 'path'], ['is_safe' => ['html']]),
new TwigFunction('url', [$this, 'url'], ['is_safe' => ['html']]),
new TwigFunction('asset_url', [$this, 'assetUrl'], ['is_safe' => ['html']])
];
}
/**
* @param string $path
* @param array $params
* @return string
* @throws RouteNotFoundException
*/
public function path(string $path, array $params = []): string
{
return $this->router->generateRoute($path, $params);
}
/**
* @param string $path
* @param array $params
* @return string
* @throws RouteNotFoundException
*/
public function url(string $path, array $params = []): string
{
return $this->router->generateRoute($path, $params, true);
}
/**
* Generates an absolute URL to given asset in project public root.
* @param string $path
* @return string
*/
public function assetUrl(string $path): string
{
$context = $this->router->getContext();
$protocol = 'http';
if ($context->isSecure()) {
$protocol = 'https';
}
$port = null;
if (
!($context->isSecure() && $context->getPort() === 443)
&& !(!$context->isSecure() && $context->getPort() === 80)
) {
$port = $context->getPort();
}
return $protocol . '://' . $context->getHost() . ($port !== null ? ':' . $port : null) . '/' . ltrim($path, '/');
}
} | true |
a8aad16bb877f3e43d8e77fd29455b683b11e87f | PHP | sunkararohith008/Dream-Destination-Tourism-Website | /Transport/rideshare-backend/login.php | UTF-8 | 1,986 | 2.828125 | 3 | [] | no_license | <?php
//Check to see if there is no session yet
if (session_status() == PHP_SESSION_NONE) {
//Start the session since there is no session
session_start();
}
// get the data from the form
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
$user_password = filter_input(INPUT_POST, 'password');
//Clearing our the messages from the session if they already exist
unset($_SESSION['email_message']);
unset($_SESSION['password_message']);
unset($_SESSION['login_mesaage']);
//Validate email
if ( $email === FALSE ) {
$_SESSION['email_message'] = 'Please provide a valid email address.';
}
//validate password
if ( $user_password === FALSE || strlen($user_password) < 6 ) {
$_SESSION['password_message'] = 'Please provide a password at least 6 characters long.';
}
// if an error message exists, go to the index page
if (isset($_SESSION['password_message']) ||
isset($_SESSION['email_message']) ) {
$_SESSION['email'] = $email;
//We could use include('index.php'); or header('Location: ./index.php'); here
header('Location: ./dlogin.php');
exit();
} else {
require_once('database.php');
require_once('db_admin.php');
//Here is where we need to validate the user and set the session
if(is_valid_admin_login($email, $user_password)){
//Login is Successful
$_SESSION[is_valid_admin] = true;
header('Location: ./index.php');
}else{
//Login Not sucessful
if(email_exists($email)){
$_SESSION['login_mesaage'] = "password incorrect. Please try again.";
}else{
$_SESSION['login_mesaage'] = "Username does not exist. Please try again.";
}
header('Location: ./dlogin.php');
exit();
}
}
?>
| true |
98ef2189c4bbbdd3f8deb88ca0d75af663313605 | PHP | lorenzen-tonna-services-ltd/verivox-php-lib | /src/request/BenchmarkRequest.php | UTF-8 | 2,041 | 2.71875 | 3 | [] | no_license | <?php
namespace Verivox\Request;
class BenchmarkRequest implements Request
{
/**
* @var int
*/
private $zipCode;
/**
* @var string
*/
private $requestType;
/**
* @var string
*/
private $duration;
/**
* @var string
*/
private $locationId;
/**
* @var int
*/
private $annualTotal;
/**
* @var float
*/
private $heatingPower;
/**
* @var string
*/
private $profile = 'h0';
public function getHeaders()
{
return [
'Accept: application/vnd.verivox.' . $this->requestType . 'Benchmarks-v1+xml'
];
}
public function getXML()
{
return null;
}
public function setZipCode($zipCode)
{
$this->zipCode = $zipCode;
}
public function setRequestType($requestType)
{
$this->requestType = $requestType;
}
public function setLocationId($locationId)
{
$this->locationId = $locationId;
}
public function setAnnualTotal($annualTotal)
{
$this->annualTotal = $annualTotal;
}
public function setHeatingPower($heatingPower)
{
$this->heatingPower = $heatingPower;
}
public function setProfile($profile)
{
$this->profile = $profile;
}
public function getRequestUrl($partnerId, $campaignId)
{
$url = 'https://www.verivox.de/servicehook/benchmarks/' . $this->requestType . '/profiles/' . $this->profile . '/locations/' . $this->zipCode . '/';
if (!empty($this->locationId)) {
$url .= $this->locationId . '/';
}
$url .= '?partnerId=' . $partnerId . '&campaignId=' . $campaignId;
if (!empty($this->annualTotal)) {
$url .= '&usage=' . $this->annualTotal;
}
if (!empty($this->heatingPower)) {
$url .= '&heatingPower=' . $this->heatingPower;
}
return $url;
}
public function getResultSet($xml)
{
return $xml;
}
} | true |
6800a6fc3d6cb8512a42debee773cc56fcaf07eb | PHP | Peppernwine/aig-site | /app/resource/MandatoryFieldValidation.php | UTF-8 | 999 | 3 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: arthirajeev
* Date: 6/19/2018
* Time: 8:13 AM
*/
class MandatoryFieldException extends ServerException
{
private $missingFields ;
public function __construct($missingFields)
{
$this->missingFields = $missingFields;
parent::__construct("Missing required Fields - ".implode(', ', $this->missingFields));
}
}
class MandatoryFieldValidation
{
private $fields;
private $values;
public function validate() {
$missingFields = [];
foreach($this->fields as $fieldName=>$displayLabel) {
if (!array_key_exists($fieldName,$this->values) || empty($this->values[$fieldName]))
$missingFields[] = $displayLabel;
}
if (!empty($missingFields))
throw new MandatoryFieldException($missingFields);
}
public function __construct($fields,$values) {
$this->fields = $fields;
$this->values = $values;
}
}
| true |
4c3ccd7b5dd10a68ad7ab4c302e06a24b666a911 | PHP | navarrogabriel/concursos_docentes | /app/Http/Controllers/RequisitoController.php | UTF-8 | 3,630 | 2.546875 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers;
use App\DataTables\RequisitoDataTable;
use App\Http\Requests;
use App\Http\Requests\CreateRequisitoRequest;
use App\Http\Requests\UpdateRequisitoRequest;
use App\Repositories\RequisitoRepository;
use Flash;
use App\Http\Controllers\AppBaseController;
use Response;
class RequisitoController extends AppBaseController
{
/** @var RequisitoRepository */
private $requisitoRepository;
public function __construct(RequisitoRepository $requisitoRepo)
{
$this->requisitoRepository = $requisitoRepo;
}
/**
* Display a listing of the Requisito.
*
* @param RequisitoDataTable $requisitoDataTable
* @return Response
*/
public function index(RequisitoDataTable $requisitoDataTable)
{
return $requisitoDataTable->render('requisitos.index');
}
/**
* Show the form for creating a new Requisito.
*
* @return Response
*/
public function create()
{
return view('requisitos.create');
}
/**
* Store a newly created Requisito in storage.
*
* @param CreateRequisitoRequest $request
*
* @return Response
*/
public function store(CreateRequisitoRequest $request)
{
$input = $request->all();
$requisito = $this->requisitoRepository->create($input);
Flash::success('Requisito saved successfully.');
return redirect(route('requisitos.index'));
}
/**
* Display the specified Requisito.
*
* @param int $id
*
* @return Response
*/
public function show($id)
{
$requisito = $this->requisitoRepository->findWithoutFail($id);
if (empty($requisito)) {
Flash::error('Requisito not found');
return redirect(route('requisitos.index'));
}
return view('requisitos.show')->with('requisito', $requisito);
}
/**
* Show the form for editing the specified Requisito.
*
* @param int $id
*
* @return Response
*/
public function edit($id)
{
$requisito = $this->requisitoRepository->findWithoutFail($id);
if (empty($requisito)) {
Flash::error('Requisito not found');
return redirect(route('requisitos.index'));
}
return view('requisitos.edit')->with('requisito', $requisito);
}
/**
* Update the specified Requisito in storage.
*
* @param int $id
* @param UpdateRequisitoRequest $request
*
* @return Response
*/
public function update($id, UpdateRequisitoRequest $request)
{
$requisito = $this->requisitoRepository->findWithoutFail($id);
if (empty($requisito)) {
Flash::error('Requisito not found');
return redirect(route('requisitos.index'));
}
$requisito = $this->requisitoRepository->update($request->all(), $id);
Flash::success('Requisito updated successfully.');
return redirect(route('requisitos.index'));
}
/**
* Remove the specified Requisito from storage.
*
* @param int $id
*
* @return Response
*/
public function destroy($id)
{
$requisito = $this->requisitoRepository->findWithoutFail($id);
if (empty($requisito)) {
Flash::error('Requisito not found');
return redirect(route('requisitos.index'));
}
$this->requisitoRepository->delete($id);
Flash::success('Requisito deleted successfully.');
return redirect(route('requisitos.index'));
}
}
| true |
ba02b7584b94bf37dee1930da6e9540aa7126d69 | PHP | zball/CloudPOS | /src/CloudPOS/Bundle/StoreBundle/Manager/CartManager.php | UTF-8 | 2,958 | 2.671875 | 3 | [] | no_license | <?php
namespace CloudPOS\Bundle\StoreBundle\Manager;
use CloudPOS\Bundle\StoreBundle\Entity\Cart;
use CloudPOS\Bundle\StoreBundle\Entity\CartItem;
use CloudPOS\Bundle\StoreBundle\Entity\Manageable;
use Symfony\Component\HttpFoundation\Request;
/**
* Class CartManager
* @package CloudPOS\Bundle\StoreBundle\Manager
*/
class CartManager extends BaseManager{
/**
* @var
*/
private $cart;
/**
* @param Cart $cart
*
* @return CartManager
*/
public function setCart(Cart $cart )
{
$this->cart = $cart;
return $this;
}
/**
* @return mixed
*/
public function getCart()
{
return $this->cart;
}
/**
* @param Request $request
* @param Manageable $manageable
*/
public function update(Request $request, Manageable $manageable)
{
// TODO: Implement update() method.
}
/**
* @param Request $request
* @return Cart
*/
public function create(Request $request )
{
$cart = new Cart;
return $this->isValid($cart) ? $cart : $this->getErrors();
}
/**
* @param CartItem $cartItem
*
* @return CartManager
*/
public function addItem(CartItem $cartItem )
{
if($duplicate = $this->findDuplicateProduct($cartItem->getProduct())){
$duplicate->setQuantity($duplicate->getQuantity() + $cartItem->getQuantity());
}else{
$this->cart->addCartItem( $cartItem );
}
$this->updateCartTotal();
return $this;
}
/**
* @param $product
* @return bool
*/
public function findDuplicateProduct($product)
{
foreach($this->getCart()->getCartItems() as $ci){
if($product == $ci->getProduct())
return $ci;
}
return false;
}
/**
* @param CartItem $cartItem
* @return CartManager
*/
public function removeItem(CartItem $cartItem )
{
$duplicate = $this->findDuplicateProduct($cartItem->getProduct());
$this->cart->removeCartItem($duplicate);
$this->delete($duplicate);
$this->updateCartTotal();
return $this;
}
/**
*
*/
public function updateCartTotal()
{
$cartTotal = 0;
foreach($this->cart->getCartItems() as $ci){
$cartTotal += ($ci->getQuantity() * $ci->getUnitPrice());
}
$this->cart->setCartTotal($cartTotal);
}
/**
*
*/
public function emptyCart()
{
$cartItems = $this->cart->getCartItems();
foreach( $cartItems as $cartItem ){
$this->removeItem( $cartItem );
}
}
public function saveCart()
{
parent::save($this->cart);
return $this;
}
}
| true |
4f461573ad56995faca5d52a9c9b24a8dc29cb07 | PHP | CaoJiayuan/laravel-api | /src/CaoJiayuan/LaravelApi/WebSocket/ServerCommand.php | UTF-8 | 2,291 | 2.75 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: cjy
* Date: 2018/3/2
* Time: 下午5:10
*/
namespace CaoJiayuan\LaravelApi\WebSocket;
use CaoJiayuan\LaravelApi\WebSocket\Events\WebSocketClosed;
use CaoJiayuan\LaravelApi\WebSocket\Events\WebSocketConnected;
use CaoJiayuan\LaravelApi\WebSocket\Events\WebSocketMessage;
use CaoJiayuan\LaravelApi\WebSocket\Events\WorkerStarted;
use Illuminate\Console\Command;
use Workerman\Worker;
class ServerCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'api-util:ws {cmd=restart : Command to send} {--port=3000 : Listen port} {--count=4 : Work process} {--daemon=1 : Daemon mode}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'A websocket server using workerman';
protected $worker;
public function handle()
{
$port = $this->option('port') ?: 3000;
$count = $this->option('count') ?: 4;
$cmd = $this->argument('cmd') ?: 'restart';
$d = $this->option('daemon') ?: 0;
global $argv;
$argv[1] = $cmd;
if ($d) {
$argv[2] = '-d';
} else {
$argv[2] = '';
}
$context = [];
$ssl = $this->getSSL();
if (!empty($ssl)) {
$context['ssl'] = $ssl;
}
$this->worker = new Worker("websocket://0.0.0.0:{$port}", $context);
if (!empty($ssl)) {
$this->worker->transport = 'ssl';
}
$this->worker->count = $count;
$this->worker->onConnect = [$this, 'onConnect'];
$this->worker->onMessage = [$this, 'onMessage'];
$this->worker->onClose = [$this, 'onClose'];
event(new WorkerStarted($this->worker));
Worker::runAll();
}
public function onConnect($connection)
{
event(new WebSocketConnected($this->worker, $connection));
}
public function onMessage($connection, $data)
{
event(new WebSocketMessage($this->worker, $connection, $data));
}
public function onClose($connection)
{
event(new WebSocketClosed($this->worker, $connection));
}
protected function getSSL()
{
return [];
}
}
| true |
b5ed7fa45cb8dd6a5ccc4948920892e34fc3e468 | PHP | vbuck/rootd-wordpress-core | /Rootd/core/Rootd/Element/Form/Abstract.php | UTF-8 | 874 | 2.625 | 3 | [] | no_license | <?php
class Rootd_Element_Form_Abstract extends Rootd_Element_Abstract
{
protected $_attributes = array();
protected $_isTypeSet = false;
public function _construct()
{
$this->setTagName('input');
}
protected function _beforeRender()
{
if ($this->getType()) {
$this->setAttribute('type', $this->getType());
}
return parent::_beforeRender();
}
public function getAllowedAttributes()
{
return array('id', 'name', 'type', 'class', 'value', 'placeholder', 'disabled', 'readonly', 'style', 'onchange', 'onclick', 'onfocus', 'onblur');
}
public function setType($type)
{
if (!$this->_isTypeSet) {
$this->setData('type', $type);
$this->_isTypeSet = true;
}
return $this;
}
} | true |
e0b91b2f0e8b884a688af096e4c1955fff3d1e67 | PHP | Gustavo210/Cine | /projeto_cinema/control/api.php | UTF-8 | 6,201 | 2.515625 | 3 | [] | no_license | <?php
require_once("config.php");
session_start();
header('Content-Type: application/json');
$response_data = array(
"status" => false,
"error" => "",
"data" => null
);
switch($_GET["method"]){
case "getFilmes": {
try{
$search = $_GET['search'];
$search = '%' . $search . '%';
$sql = "SELECT * FROM filme where Nome LIKE :search ORDER BY idFilme DESC LIMIT 3";
$stmt = $PDO->prepare($sql);
$stmt->bindParam( ':search', $search);
$result = $stmt->execute();
$rows = $stmt->fetchAll();
$response_data["status"] = true;
$response_data["data"] = $rows;
} catch (PDOException $e){
$response_data["status"] = false;
$response_data["error"] = 'Erro:' . $e->getMessage();
}
break;
}
case "getLogin":{
try{
$email = $_GET["email"];
$senha = $_GET["senha"];
$sql = "SELECT * FROM usuarios where email = :e and senha = :s";
$stmt = $PDO->prepare($sql);
$stmt->bindParam( ':e', $email);
$stmt->bindParam( ':s', $senha);
$result = $stmt->execute();
if($stmt->rowCount() >= 1){
$response_data["status"] = true;
$rows = $stmt->fetchAll();
$_SESSION["isLogged"] = true;
$_SESSION["userId"] = $rows[0]["idUser"];
$_SESSION["userName"] = $rows[0]["nome"];
$response_data["data"] = $rows[0];
} else {
$response_data["status"] = false;
}
} catch (PDOException $e){
$response_data["status"] = false;
$response_data["error"] = 'Erro:' . $e->getMessage();
}
break;
}
case "addLogin":{
try{
$nome = $_GET["nome"];
$email = $_GET["email"];
$senha = $_GET["senha"];
$sql = "INSERT INTO usuarios (nome,email,senha) VALUES (:n,:e,:s)";
$stmt = $PDO->prepare($sql);
$stmt->bindParam( ':n', $nome);
$stmt->bindParam( ':e', $email);
$stmt->bindParam( ':s', $senha);
$result = $stmt->execute();
if($stmt->rowCount() >= 1){
$response_data["status"] = true;
$_SESSION["isLogged"] = true;
$_SESSION["userId"] = $PDO->lastInsertId();
$_SESSION["userName"] = $nome;
} else {
$response_data["status"] = false;
}
} catch (PDOException $e){
$response_data["status"] = false;
$response_data["error"] = 'Erro:' . $e->getMessage();
}
break;
}
case "addCompra":{
try{
$ingressoTotal = $_GET["ingressoTotal"];
$combosTotal = $_GET["combosTotal"];
$compraTotal = $_GET["compraTotal"];
$idCliente = $_GET["idCliente"];
$boleto = $_GET["boleto"];
$horario = $_GET["horario"];
$id_filme = $_GET["id_filme"];
$dia = $_GET["dia"];
$assentos = $_GET["assentos"];
$sql = "INSERT INTO compras (idCliente,
ingressoTotal,
combosTotal,
compraTotal,
boleto,
data_compra,
dia,
horario,
assentos,
id_filme
) VALUES (
:idCliente,
:ingressoTotal,
:combosTotal,
:compraTotal,
:boleto,
now(),
:dia,
:horario,
:assentos,
:id_filme)";
$stmt = $PDO->prepare($sql);
$stmt->bindParam( ':idCliente', $idCliente);
$stmt->bindParam( ':ingressoTotal', $ingressoTotal);
$stmt->bindParam( ':combosTotal', $combosTotal);
$stmt->bindParam( ':compraTotal', $compraTotal);
$stmt->bindParam( ':boleto', $boleto);
$stmt->bindParam( ':horario', $horario);
$stmt->bindParam( ':dia', $dia);
$stmt->bindParam( ':assentos', $assentos);
$stmt->bindParam( ':id_filme', $id_filme);
$result = $stmt->execute();
if($stmt->rowCount() >= 1){
$response_data["status"] = true;
} else {
$response_data["status"] = false;
}
} catch (PDOException $e){
$response_data["status"] = false;
$response_data["error"] = 'Erro:' . $e->getMessage();
}
break;
}
case "getLogout": {
session_destroy();
$response_data["status"] = true;
break;
}
case "getHorario":{
try{
$idFilme = $_GET["id_filme"];
$dia = $_GET["dia"];
$sql = "SELECT {$dia} FROM sessoes where id_filme = :idFilme";
$stmt = $PDO->prepare($sql);
$stmt->bindParam( ':idFilme', $idFilme);
$result = $stmt->execute();
if($stmt->rowCount() >= 1){
$response_data["status"] = true;
$rows = $stmt->fetch();
$response_data["data"] = $rows[0];
} else {
$response_data["status"] = false;
}
} catch (PDOException $e){
$response_data["status"] = false;
$response_data["error"] = 'Erro:' . $e->getMessage();
}
break;
}
default: {
break;
}
}
echo json_encode($response_data);
?> | true |
fc548a5031297cec35b286ba8558133d16bc7e87 | PHP | Sergei2014/hospital | /yii/frontend/views/display/csz1.php | UTF-8 | 14,184 | 2.53125 | 3 | [] | no_license | <?php
use common\models\Schedule;
echo '<pre>';
//print_r($doctors);
echo '</pre>';
if(isset($_GET['dat'])){
$data = $_GET['dat'];
}else{
$data = date('d-m-Y');
}
$test = strtotime("$data");
$week_number = date("W", $test);
$year = date('Y');
for($day=1; $day<=6; $day++)
{
if($day == 1){
$datapn = date('Y-m-d', strtotime($year."W".$week_number.$day));
}
if($day == 2){
$datavt = date('Y-m-d', strtotime($year."W".$week_number.$day));
}
if($day == 3){
$datasr = date('Y-m-d', strtotime($year."W".$week_number.$day));
}
if($day == 4){
$datact = date('Y-m-d', strtotime($year."W".$week_number.$day));
}
if($day == 5){
$datapt = date('Y-m-d', strtotime($year."W".$week_number.$day));
}
if($day == 6){
$datacb = date('Y-m-d', strtotime($year."W".$week_number.$day));
}
}
?>
<div class="head">
<div class="otd-l">№1 отбасылық денсаулық орталығы <br>Центр семейного здоровья №1</div>
<div class="otd-r">№1 отбасылық денсаулық орталығы <br>Центр семейного здоровья №1</div>
<div class="title">РАСПИСАНИЕ РАБОТЫ ВРАЧЕЙ</div>
</div><div class="tblwrap">
<table class="parent">
<tbody>
<tr>
<td>
<table class="child">
<tbody>
<tr>
<th>ФИО специалиста</th>
<th>Участок</th>
<th><div class="date">Пн</div></th><th><div class="date">Вт</div></th><th><div class="date">Ср</div></th><th><div class="date">Чт</div></th><th><div class="date">Пт</div></th><th><div class="date">Сб</div></th></th>
</tr>
<?php $i=1; ?>
<?php foreach ($doctors as $value) {?>
<?php if($i % 2 == 1) { ?>
<tr>
<td class="doc"><div class="docname"> <?= $value['surname'] .' '. $value['name'] .' '. $value['patronymic'] ?><br><span style="font-size: 12px;"><?= $value['profession_name'] ?></span></div><div class="docspec"></div></td>
<td class="docspec"></td>
<?php $schedulecon = Schedule::find()->where(['id_doc' => $value['id'], 'data' => $datapn])->count(); ?>
<?php $schedule = Schedule::find()->where(['id_doc' => $value['id'], 'data' => $datapn])->all(); ?>
<?php echo '<td>' ?>
<?php if($schedulecon>0){?>
<?php foreach ($schedule as $val) :?>
<?php echo '<div class="notwork">' . date('G:i',strtotime($val->time_start)) .'-'. date('G:i',strtotime($val->time_end)) .'</div>'?>
<?php endforeach; ?>
<?php }else{
echo '<div class="notwork">Нет приема</div></td>';
} ?>
<?php $schedulecon = Schedule::find()->where(['id_doc' => $value['id'], 'data' => $datavt])->count(); ?>
<?php $schedule = Schedule::find()->where(['id_doc' => $value['id'], 'data' => $datavt])->all(); ?>
<?php echo '<td>' ?>
<?php if($schedulecon>0){?>
<?php foreach ($schedule as $val) :?>
<?php echo '<div class="notwork">' . date('G:i',strtotime($val->time_start)) .'-'. date('G:i',strtotime($val->time_end)) .'</div>'?>
<?php endforeach; ?>
<?php }else{
echo '<div class="notwork">Нет приема</div></td>';
} ?>
<?php $schedulecon = Schedule::find()->where(['id_doc' => $value['id'], 'data' => $datasr])->count(); ?>
<?php $schedule = Schedule::find()->where(['id_doc' => $value['id'], 'data' => $datasr])->all(); ?>
<?php echo '<td>' ?>
<?php if($schedulecon>0){?>
<?php foreach ($schedule as $val) :?>
<?php echo '<div class="notwork">' . date('G:i',strtotime($val->time_start)) .'-'. date('G:i',strtotime($val->time_end)) .'</div>'?>
<?php endforeach; ?>
<?php }else{
echo '<div class="notwork">Нет приема</div></td>';
} ?>
<?php $schedulecon = Schedule::find()->where(['id_doc' => $value['id'], 'data' => $datact])->count(); ?>
<?php $schedule = Schedule::find()->where(['id_doc' => $value['id'], 'data' => $datact])->all(); ?>
<?php echo '<td>' ?>
<?php if($schedulecon>0){?>
<?php foreach ($schedule as $val) :?>
<?php echo '<div class="notwork">' . date('G:i',strtotime($val->time_start)) .'-'. date('G:i',strtotime($val->time_end)) .'</div>'?>
<?php endforeach; ?>
<?php }else{
echo '<div class="notwork">Нет приема</div></td>';
} ?>
<?php $schedulecon = Schedule::find()->where(['id_doc' => $value['id'], 'data' => $datapt])->count(); ?>
<?php $schedule = Schedule::find()->where(['id_doc' => $value['id'], 'data' => $datapt])->all(); ?>
<?php echo '<td>' ?>
<?php if($schedulecon>0){?>
<?php foreach ($schedule as $val) :?>
<?php echo '<div class="notwork">' . date('G:i',strtotime($val->time_start)) .'-'. date('G:i',strtotime($val->time_end)) .'</div>'?>
<?php endforeach; ?>
<?php }else{
echo '<div class="notwork">Нет приема</div></td>';
} ?>
<?php $schedulecon = Schedule::find()->where(['id_doc' => $value['id'], 'data' => $datacb])->count(); ?>
<?php $schedule = Schedule::find()->where(['id_doc' => $value['id'], 'data' => $datacb])->all(); ?>
<?php echo '<td>' ?>
<?php if($schedulecon>0){?>
<?php foreach ($schedule as $val) :?>
<?php echo '<div class="notwork">' . date('G:i',strtotime($val->time_start)) .'-'. date('G:i',strtotime($val->time_end)) .'</div>'?>
<?php endforeach; ?>
<?php }else{
echo '<div class="notwork">Нет приема</div></td>';
} ?>
</tr>
<?php } ?>
<?php $i++; ?>
<?php } ?>
</tbody></table>
</td>
<td class="sep"></td>
<td>
<table class="child">
<tbody>
<tr>
<th>ФИО специалиста</th>
<th>Участок</th>
<th><div class="date">Пн</div></th><th><div class="date">Вт</div></th><th><div class="date">Ср</div></th><th><div class="date">Чт</div></th><th><div class="date">Пт</div></th><th><div class="date">Сб</div></th></th>
</tr>
<?php $i=1; ?>
<?php foreach ($doctors as $value) {?>
<?php if($i % 2 == 0) { ?>
<tr>
<td class="doc"><div class="docname"> <?= $value['surname'] .' '. $value['name'] .' '. $value['patronymic'] ?><br><span style="font-size: 12px;"><?= $value['profession_name'] ?></span></div><div class="docspec"></div></td>
<td class="docspec"></td>
<?php $schedulecon = Schedule::find()->where(['id_doc' => $value['id'], 'data' => $datapn])->count(); ?>
<?php $schedule = Schedule::find()->where(['id_doc' => $value['id'], 'data' => $datapn])->all(); ?>
<?php echo '<td>' ?>
<?php if($schedulecon>0){?>
<?php foreach ($schedule as $val) :?>
<?php echo '<div class="notwork">' . date('G:i',strtotime($val->time_start)) .'-'. date('G:i',strtotime($val->time_end)) .'</div>'?>
<?php endforeach; ?>
<?php }else{
echo '<div class="notwork">Нет приема</div></td>';
} ?>
<?php $schedulecon = Schedule::find()->where(['id_doc' => $value['id'], 'data' => $datavt])->count(); ?>
<?php $schedule = Schedule::find()->where(['id_doc' => $value['id'], 'data' => $datavt])->all(); ?>
<?php echo '<td>' ?>
<?php if($schedulecon>0){?>
<?php foreach ($schedule as $val) :?>
<?php echo '<div class="notwork">' . date('G:i',strtotime($val->time_start)) .'-'. date('G:i',strtotime($val->time_end)) .'</div>'?>
<?php endforeach; ?>
<?php }else{
echo '<div class="notwork">Нет приема</div></td>';
} ?>
<?php $schedulecon = Schedule::find()->where(['id_doc' => $value['id'], 'data' => $datasr])->count(); ?>
<?php $schedule = Schedule::find()->where(['id_doc' => $value['id'], 'data' => $datasr])->all(); ?>
<?php echo '<td>' ?>
<?php if($schedulecon>0){?>
<?php foreach ($schedule as $val) :?>
<?php echo '<div class="notwork">' . date('G:i',strtotime($val->time_start)) .'-'. date('G:i',strtotime($val->time_end)) .'</div>'?>
<?php endforeach; ?>
<?php }else{
echo '<div class="notwork">Нет приема</div></td>';
} ?>
<?php $schedulecon = Schedule::find()->where(['id_doc' => $value['id'], 'data' => $datact])->count(); ?>
<?php $schedule = Schedule::find()->where(['id_doc' => $value['id'], 'data' => $datact])->all(); ?>
<?php echo '<td>' ?>
<?php if($schedulecon>0){?>
<?php foreach ($schedule as $val) :?>
<?php echo '<div class="notwork">' . date('G:i',strtotime($val->time_start)) .'-'. date('G:i',strtotime($val->time_end)) .'</div>'?>
<?php endforeach; ?>
<?php }else{
echo '<div class="notwork">Нет приема</div></td>';
} ?>
<?php $schedulecon = Schedule::find()->where(['id_doc' => $value['id'], 'data' => $datapt])->count(); ?>
<?php $schedule = Schedule::find()->where(['id_doc' => $value['id'], 'data' => $datapt])->all(); ?>
<?php echo '<td>' ?>
<?php if($schedulecon>0){?>
<?php foreach ($schedule as $val) :?>
<?php echo '<div class="notwork">' . date('G:i',strtotime($val->time_start)) .'-'. date('G:i',strtotime($val->time_end)) .'</div>'?>
<?php endforeach; ?>
<?php }else{
echo '<div class="notwork">Нет приема</div></td>';
} ?>
<?php $schedulecon = Schedule::find()->where(['id_doc' => $value['id'], 'data' => $datacb])->count(); ?>
<?php $schedule = Schedule::find()->where(['id_doc' => $value['id'], 'data' => $datacb])->all(); ?>
<?php echo '<td>' ?>
<?php if($schedulecon>0){?>
<?php foreach ($schedule as $val) :?>
<?php echo '<div class="notwork">' . date('G:i',strtotime($val->time_start)) .'-'. date('G:i',strtotime($val->time_end)) .'</div>'?>
<?php endforeach; ?>
<?php }else{
echo '<div class="notwork">Нет приема</div></td>';
} ?>
</tr>
<?php } ?>
<?php $i++; ?>
<?php } ?>
</tbody></table>
</td>
</tr>
</tbody>
</table>
</div> | true |
12e79e11e58145856d3a540012a4963651fb6448 | PHP | DangKien/role-permisson | /src/RolePer/RolePerServiceProvider.php | UTF-8 | 3,079 | 2.609375 | 3 | [
"MIT"
] | permissive | <?php
namespace DangKien\RolePer;
/**
* This file is part of DangKien,
* a role & permission management solution for Laravel.
*
* @license MIT
* @package DangKien\RolePer
*/
use Illuminate\Support\ServiceProvider;
use Validator, DB;
class RolePerServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
// Publish config files
$this->publishes([
__DIR__.'/../config/config.php' => base_path('config/roleper.php'),
__DIR__.'/migrations' => base_path('database/migrations'),
__DIR__.'/seeds' => base_path('database/seeds'),
__DIR__.'/Models/Permission.php' => base_path('app/Models/Permission.php'),
__DIR__.'/Models/PermissionGroup.php' => base_path('app/Models/PermissionGroup.php'),
__DIR__.'/Models/Role.php' => base_path('app/Models/Role.php'),
__DIR__.'/Middleware' => base_path('app/Http/Middleware'),
__DIR__.'/../views/role_per' => base_path('resources/views/user_permission'),
]);
$this->bladeDirectives();
Validator::extend('unique_rule', function($attribute, $value, $parameters, $validator) {
$exit = DB::table($parameters[0])->where([
array($attribute, $value),
array('id', '!=', $parameters[1])
])->first();
if (empty($exit) ) {
return true;
}
return false;
});
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->bind('roleper', function($app) {
return new RolePer($app);
});
}
/**
* Register the blade directives
*
* @return void
*/
private function bladeDirectives()
{
if (!class_exists('\Blade')) return;
\Blade::directive('role', function($expression) {
return "<?php if (\\DangKien::hasRole({$expression})) : ?>";
});
\Blade::directive('endrole', function($expression) {
return "<?php endif; // DangKien::hasRole ?>";
});
\Blade::directive('permission', function($expression) {
return "<?php if (\\DangKien::can({$expression})) : ?>";
});
\Blade::directive('endpermission', function($expression) {
return "<?php endif; // DangKien::can ?>";
});
\Blade::directive('ability', function($expression) {
return "<?php if (\\DangKien::ability({$expression})) : ?>";
});
\Blade::directive('endability', function($expression) {
return "<?php endif; // DangKien::ability ?>";
});
}
}
| true |
bffd24ae3b211877b857838f6294a3416c20c7ce | PHP | Ulll/wxpay | /src/WXPayUtil.php | UTF-8 | 5,456 | 3.234375 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
namespace WXPay;
class WXPayUtil
{
/**
* 将array转换为XML格式的字符串
* @param array $data
* @return string
* @throws \Exception
*/
public static function array2xml($data) {
$xml = new \SimpleXMLElement('<xml/>');
foreach($data as $k => $v ) {
if (is_string($k) && (is_numeric($v) || is_string($v))) {
$xml->addChild("$k",htmlspecialchars("$v"));
}
else {
throw new \Exception('Invalid array, will not be converted to xml');
}
}
return $xml->asXML();
}
/**
* 将XML格式字符串转换为array
* 参考: http://php.net/manual/zh/book.simplexml.php
* @param string $str XML格式字符串
* @return array
* @throws \Exception
*/
public static function xml2array($str) {
$xml = simplexml_load_string($str, 'SimpleXMLElement', LIBXML_NOCDATA);
$json = json_encode($xml);
$result = array();
$bad_result = json_decode($json,TRUE); // value,一个字段多次出现,结果中的value是数组
// return $bad_result;
foreach ($bad_result as $k => $v) {
if (is_array($v)) {
if (count($v) == 0) {
$result[$k] = '';
}
else if (count($v) == 1) {
$result[$k] = $v[0];
}
else {
throw new \Exception('Duplicate elements in XML. ' . $str);
}
}
else {
$result[$k] = $v;
}
}
return $result;
}
/**
* 生成签名。注意$data中若有sign_type字段,必须和参数$signType的值一致。这里不做检查。
* @param array $data
* @param string $wxpayKey API密钥
* @param string $signType
* @return string
* @throws \Exception
*/
public static function generateSignature($data, $wxpayKey, $signType=WXPayConstants::SIGN_TYPE_MD5) {
$combineStr = '';
$keys = array_keys($data);
asort($keys); // 排序
foreach($keys as $k) {
$v = $data[$k];
if ($k == WXPayConstants::FIELD_SIGN) {
continue;
}
elseif ((is_string($v) && strlen($v) > 0) || is_numeric($v) ) {
$combineStr = "${combineStr}${k}=${v}&";
}
elseif (is_string($v) && strlen($v) == 0) {
continue;
}
else {
throw new \Exception('Invalid data, cannot generate signature: ' . json_encode($data));
}
}
$combineStr = "${combineStr}key=${wxpayKey}";
if ($signType === WXPayConstants::SIGN_TYPE_MD5) {
return self::MD5($combineStr);
}
elseif ($signType === WXPayConstants::SIGN_TYPE_HMACSHA256) {
return self::HMACSHA256($combineStr, $wxpayKey);
}
else {
throw new \Exception('Invalid sign_type: ' . $signType);
}
}
/**
* 验证签名是否合法
* @param array $data
* @param string $wxpayKey API密钥
* @param string $signType
* @return bool
*/
public static function isSignatureValid($data, $wxpayKey, $signType=WXPayConstants::SIGN_TYPE_MD5) {
if ( !array_key_exists(WXPayConstants::FIELD_SIGN, $data) ) {
return false;
}
$sign = $data[WXPayConstants::FIELD_SIGN];
try {
$generatedSign = WXPayUtil::generateSignature($data, $wxpayKey, $signType);
// echo "签名: ${generatedSign} \n";
if ($sign === $generatedSign) {
return true;
}
else {
return false;
}
} catch (\Exception $e) {
return false;
}
}
/**
* 生成含有签名数据的XML格式字符串
* @param array $data
* @param string $wxpayKey API密钥
* @param string $signType
* @return string
*/
public static function generateSignedXml($data, $wxpayKey, $signType=WXPayConstants::SIGN_TYPE_MD5) {
// clone一份
$newData = array();
foreach ($data as $k => $v) {
$newData[$k] = $v;
}
$sign = WXPayUtil::generateSignature($data, $wxpayKey, $signType);
$newData[WXPayConstants::FIELD_SIGN] = $sign;
return WXPayUtil::array2xml($newData);
}
/**
* 生成 nonce str
* 参考: http://php.net/manual/zh/function.uniqid.php
* @return string
*/
public static function generateNonceStr() {
return sprintf('%04x%04x%04x%04x%04x%04x%04x%04x',
mt_rand(0, 0xffff), mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0x0fff) | 0x4000,
mt_rand(0, 0x3fff) | 0x8000,
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
);
}
/**
* 获取 MD5 结果
* @param string $data
* @return string
*/
public static function MD5($data) {
return strtoupper(md5($data));
}
/**
* 获取 HMAC-SHA256 签名结果
* @param string $data
* @param string $wxpayKey
* @return string
*/
public static function HMACSHA256($data, $wxpayKey) {
return strtoupper(hash_hmac('sha256', $data, $wxpayKey));
}
}
| true |
16e3d957579657791eed91c58a08658aa194ef2e | PHP | DayzerCode/inn_form | /app/Services/Api/StatusNpdApi.php | UTF-8 | 1,212 | 2.6875 | 3 | [] | no_license | <?php
namespace App\Services\Api;
use App\Contracts\Services\Api\TaxpayerApi;
use DateTimeInterface;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\GuzzleException;
use Psr\Log\LoggerInterface;
/**
* Requests to https://statusnpd.nalog.ru/
*/
class StatusNpdApi implements TaxpayerApi
{
private ClientInterface $client;
private ?LoggerInterface $logManager;
public function __construct(ClientInterface $client, LoggerInterface $logManager)
{
$this->client = $client;
$this->logManager = $logManager;
}
/**
* @param string $inn
* @param DateTimeInterface|null $date
* @return array
* @throws GuzzleException
*/
public function getStatusInn(string $inn, DateTimeInterface $date = null): array
{
if ($date === null) {
$date = new \DateTime();
}
$parameters = [
'inn' => $inn,
'requestDate' => $date->format('Y-m-d'),
];
$response = $this->client->request('POST', '/api/v1/tracker/taxpayer_status/', [
'body' => \json_encode($parameters, true)
]);
return \json_decode($response->getBody()->getContents(), true);
}
}
| true |
881784d4574bb52414773929ba7eea05f253fb7c | PHP | afbora/iyzipay-laravel | /src/StorableClasses/Plan.php | UTF-8 | 3,897 | 3.015625 | 3 | [
"MIT"
] | permissive | <?php
namespace Afbora\IyzipayLaravel\StorableClasses;
use Afbora\IyzipayLaravel\Exceptions\Fields\PlanFieldsException;
use Afbora\IyzipayLaravel\ProductContract;
use Iyzipay\Model\BasketItemType;
class Plan extends StorableClass implements ProductContract
{
/**
* The plan's id
*
* @var string
*/
public $id;
/**
* The plan's displayable name
*
* @var string
*/
public $name;
/**
* The plan's price.
*
* @var integer
*/
public $price = 0;
/**
* The plan's interval.
*
* @var string
*/
public $interval = 'monthly';
/**
* The number of trial days that come with the plan.
*
* @var int
*/
public $trialDays = 0;
/**
* The plan's features.
*
* @var array
*/
public $features = [];
/**
* The plan's attributes.
*
* @var array
*/
public $attributes = [];
/**
* The plan's currency
*
* @var string
*/
public $currency = 'TRY';
/**
* Set the name of the plan.
*
* @param string $name
*
* @return $this
*/
public function name($name)
{
$this->name = $name;
return $this;
}
/**
* Set the id of the plan.
*
* @param string $id
*
* @return $this
*/
public function id($id)
{
$this->id = $id;
return $this;
}
/**
* Set the price of the plan.
*
* @param string|integer $price
*
* @return $this
*/
public function price($price)
{
$this->price = $price;
return $this;
}
/**
* Specify that the plan is on a yearly interval.
*
* @return $this
*/
public function yearly()
{
$this->interval = 'yearly';
return $this;
}
/**
* Specify the number of trial days that come with the plan.
*
* @param int $trialDays
*
* @return $this
*/
public function trialDays($trialDays)
{
$this->trialDays = $trialDays;
return $this;
}
/**
* Specify the currency of plan.
*
* @param $currency
*
* @return $this
*/
public function currency($currency)
{
$this->currency = $currency;
return $this;
}
/**
* Specify the plan's features.
*
* @param array $features
*
* @return $this
*/
public function features(array $features)
{
$this->features = $features;
return $this;
}
/**
* Get a given attribute from the plan.
*
* @param string $key
* @param mixed $default
*
* @return mixed
*/
public function attribute($key, $default = null)
{
return array_get($this->attributes, $key, $default);
}
/**
* Specify the plan's attributes.
*
* @param array $attributes
*
* @return $this
*/
public function attributes(array $attributes)
{
$this->attributes = array_merge($this->attributes, $attributes);
return $this;
}
protected function getFieldExceptionClass(): string
{
return PlanFieldsException::class;
}
public function getKey()
{
return $this->name;
}
public function getKeyName()
{
return 'name';
}
public function getName()
{
return $this->name;
}
public function getPrice()
{
return $this->price;
}
public function getCategory()
{
return 'Plan';
}
public function getType()
{
return BasketItemType::VIRTUAL;
}
public function toArray()
{
return [
'name' => $this->name,
'price' => $this->price,
'currency' => $this->currency
];
}
}
| true |
8de24323345ca1f8a49008e98ebad49d13c17465 | PHP | LuisAgapeP/Prueba_DNA | /Parte01/Problema01.php | UTF-8 | 1,867 | 3.515625 | 4 | [] | no_license | <!doctype html>
<html>
<head>
<title>Problema 01</title>
</head>
<body>
<span>
<b>Problema 01</b></br>
Usando PHP, crear una clase llamada ChangeString que tenga un método llamado build el cual tome un parámetro string que debe ser modificado por el siguiente algoritmo.</br>
Reemplazar cada letra de la cadena con la letra siguiente en el alfabeto. Por ejemplo reemplazar a por b ó c por d . Finalmente devolver la cadena.
Indicaciones
<ul>
<li>Crear la solución en un solo archivo llamado ChangeString.php</li>
<li>El método build devuelve la salida del algoritmo</li>
<li>Considerar el siguiente abecedario : a, b, c, d, e, f, g, h, i, j, k, l, m, n, ñ, o, p, q, r,s, t, u, v, w, x, y, z.</li>
</ul>
Ejemplos:
<ul>
<li>entrada : "123 abcd*3" salida : "123 bcde *3"</li>
<li>entrada : "**Casa 52" salida : "** Dbtb 52"</li>
<li>entrada : "**Casa 52Z" salida : "** Dbtb 52 A "</li>
</ul></br>
Texto de Prueba: **Casa 52</br>
</span>
<?php
class ChangeString{
function build($Cadena){
$NuevaCadena='';
$Cadena=trim($Cadena);
$Longitud = strlen($Cadena);
for($i = 0; $i < $Longitud; $i++){
//Obtiene el valor del caracter a evaluar
$Letra=substr($Cadena, $i, 1);
//Obtiene el valor ascci del caracter
$Codigo=ord($Letra);
// Verifica el valor de caratcter para incrementar el valor ascii
if (($Codigo>=65 and $Codigo<=90) or ($Codigo>=97 and $Codigo<=122)) {
switch($Codigo){
case 90:
$Letra=chr(65);
break;
case 122:
$Letra=chr(97);
break;
default:
$Letra=chr($Codigo+1);
}
}
$NuevaCadena=$NuevaCadena.$Letra;
}
return $NuevaCadena;
}
}
// Prueba de la función
$Clase=new ChangeString();
echo "Resultado: ".$Clase->build('**Casa 52');
?>
</body>
</html> | true |
9421da15b1261e6d6f8279ffee0509593693e71a | PHP | ysc8620/lephp | /lib/interface/notice.interface.php | UTF-8 | 2,724 | 2.625 | 3 | [] | no_license | <?php
class interface_notice {
/**
* 获取未读通知列表
* @param unknown_type $user_id
*/
static function get_unread($user_id){
$notice_cache_key = self::get_cache_key($user_id);
$unread_list = core_cache::pools() -> get($notice_cache_key);
if($unread_list === false){
$rt = self::change_unread_cache($user_id);
}else{
$ids = unserialize($unread_list);
foreach ($ids as $id){
$rt[] = core_comm::dao('notice_info') -> get_vo($id);
}
}
return $rt;
}
/**
* 更新未读缓存
* @param unknown_type $user_id
*/
static function change_unread_cache($user_id){
$notice_cache_key = self::get_cache_key($user_id);
$unread_list = core_comm::dao('notice_info') -> get_unread($user_id);
$ids = array();
if($unread_list['list']){
foreach($unread_list['list'] as $r){
$ids[] = $r -> id;
}
}
core_cache::pools() -> set($notice_cache_key,serialize($ids),1800);
$rt = $unread_list['list'];
return $rt;
}
/**
* 发送一个通知
* @param str $type 通知类型 store/user/everyone
* @param str $to_ids
* @param str $title
* @param str $content
*/
static function send_notice($type,$to_ids,$title,$msg){
$notice_info = core_comm::dao('notice_info') -> add_item($type,$to_ids,$title,$msg);
if($to_ids != 0){
self::change_cache($notice_info -> id,$to_ids);
}
return true;
}
/**
* 将某条消息设置为已读
* @param int $notice_id
* @param int $user_id
*/
static function set_read($notice_id,$user_id){
$rs = core_comm::dao('notice_read') -> set_read($notice_id,$user_id);
self::change_cache($user_id);
return $rs;
}
/**
* 更新指定用户通知缓存
* @param unknown_type $notice_id
* @param unknown_type $to_ids
*/
static function change_cache($to_ids){
if(!is_array($to_ids)){
$to_ids = explode(',',$to_ids);
}
if(!$to_ids){
return ;
}
foreach($to_ids as $uid){
self::change_unread_cache($uid);
}
}
/**
* 用户通知缓存KEY
* @param unknown_type $uid
*/
static function get_cache_key($uid){
return "notice_unread_" . $uid;
}
/**
* 更新所有用户通知缓存
* @param unknown_type $notice_id
static function change_cache_everyone($notice_id){
$unread = self::get_everyone_unread();
array_unshift($unread,$notice_id);
$notice_cache_key = self::get_everyone_cacke_key();
core_cache::pools() -> set($notice_cache_key,$unread,1800);
}
*/
/**
* 系统通知缓存KEY
static function get_everyone_cacke_key(){
return "notice_everyone";
}
*/
}
?> | true |
9104b36415fba457483cc2a6446e1ab9a900ef77 | PHP | MNAriel/simulacion_sistemas | /models/model.php | UTF-8 | 615 | 2.59375 | 3 | [
"MIT"
] | permissive | <?php
class Enlaces {
static public function enlacesModel($enlaces) {
if($enlaces == "inicio" ||
$enlaces == "integrantes" ||
$enlaces == "practicas" ||
$enlaces == "practica1" ||
$enlaces == "practica2") {
$module = "views/modules/".$enlaces.".php";
}
else if($enlaces == "index" ){
$module = "views/modules/inicio.php";
}
else{
$module = "views/modules/inicio.php";
}
return $module;
}
}
?> | true |
d2b375a06becc69470296bc99d21fbea67956ba3 | PHP | realtruths/captcha-generator | /src/CaptchaGenerator.php | UTF-8 | 8,771 | 2.90625 | 3 | [
"MIT"
] | permissive | <?php
/*
* This file is part of the realtruths/captcha-generator.
*
* (c) RealTruths <realtruths@126.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace RealTruths\Captcha\Generator;
/**
* Class CaptchaGenerator
* @package RealTruths\Captcha\Generator
*/
class CaptchaGenerator
{
/**
* 配置资源
* @var CaptchaConfig
*/
private $config;
/**
* 验证码画布
* @var resource
*/
private $imgCanvas;
/**
* 验证码
* @var string
*/
private $code;
/**
* 验证码字节
* @var string
*/
private $byte;
/**
* CaptchaGenerator constructor.
* @param array|CaptchaConfig $option 配置对象或配置数组
*/
public function __construct($option = [])
{
$this->init($option);
!$this->config->fontSize && $this->config->fontSize = intval($this->config->width / ($this->config->length * 1.5));
// 加载随机字体
if ($this->config->isRandomFont) {
$fonts = $this->loadFonts(__DIR__ . '/fonts/');
$this->config->fonts && $fonts = $this->config->fonts;
$this->config->codeFont = $fonts[array_rand($fonts)];
}
}
/**
* 加载配置
* @param $option
*/
public function init($option)
{
if (is_array($option)) {
$this->config = new CaptchaConfig();
if (!empty($option)) {
foreach ($option as $key => $value) {
$method = 'set' . ucfirst($key);
if (method_exists($this->config, $method)) {
$this->config->$method($value);
}
}
}
} elseif ($option instanceof CaptchaConfig) {
$this->config = $option;
} else {
$this->config = new CaptchaConfig();
}
}
/**
* 加载目录下字体文件
* @param $fontPath
* @return array
*/
public function loadFonts($fontPath): array
{
$fonts = array_filter(array_slice(scandir($fontPath), 2), function ($file) use ($fontPath) {
return is_file($fontPath . $file) && strcasecmp(pathinfo($file, PATHINFO_EXTENSION), 'ttf') === 0;
});
if (!empty($fonts)) {
foreach ($fonts as &$font) {
$font = $fontPath . $font;
}
unset($font);
}
return $fonts;
}
/**
* 生成验证码
* @param string $code 验证码
* @return $this
*/
public function generate($code = null): self
{
if (!is_null($code)) {
$this->config->length = strlen($code);
} else {
$code = substr(str_shuffle($this->config->charset), 0, $this->config->length);
}
$code = strval($code);
// 创建空白画布
$this->imgCanvas = imagecreate($this->config->width, $this->config->height);
if (is_string($this->config->bgColor)) $this->config->bgColor = $this->config->hexToRgb($this->config->bgColor);
[$red, $blue, $green] = $this->config->isRandomLightBgColor ? $this->getRandomLightBgColor() : ($this->config->bgColor ?: $this->getRandomLightBgColor());
// 设置背景颜色
$this->config->bgColor = imagecolorallocate($this->imgCanvas, $red, $blue, $green);
imagefill($this->imgCanvas, 0, 0, $this->config->bgColor);
// 设置边框
$rect = is_string($this->config->borderColor) ? $this->config->hexToRgb($this->config->borderColor) : $this->config->borderColor;
$this->config->isBorder && imagerectangle($this->imgCanvas, 0, 0, $this->config->width - 1, $this->config->height - 1, $rect);
// 画干扰噪点
$this->config->isDrawNoise && $this->drawNoise();
// 画干扰曲线
$this->config->isDrawCurve && $this->drawCurve();
// 画验证码
$codeNX = 0; // 验证码第N个字符的左边距
for ($i = 0; $i < $this->config->length; $i++) {
$codeNX += mt_rand($this->config->fontSize * 1, $this->config->fontSize * 1.3);
[$red, $green, $blue] = is_string($this->config->fontColor) ? $this->config->hexToRgb($this->config->fontColor) : $this->config->fontColor;
$color = imagecolorallocate($this->imgCanvas, $red, $green, $blue);
!$color && $color = mt_rand(50, 200);
imagettftext($this->imgCanvas, $this->config->fontSize, mt_rand(-40, 40), $codeNX, $this->config->fontSize * 1.2, $color, $this->config->codeFont, $code[$i]);
}
$this->code = strtolower($code);
// 输出字节
ob_start();
imagepng($this->imgCanvas);
$this->byte = ob_get_contents();
ob_end_clean();
imagedestroy($this->imgCanvas);
return $this;
}
/**
* 随机浅色背景
* @return array
*/
public function getRandomLightBgColor(): array
{
$colors[0] = 150 + mt_rand(1, 75);
$colors[1] = 150 + mt_rand(1, 75);
$colors[2] = 150 + mt_rand(1, 75);
return $colors;
}
/**
* 画干扰噪点
*/
public function drawNoise(): void
{
$codeSet = '1234567890abcdefghijklmnopqrstuvwxyz';
for ($i = 0; $i < $this->config->noiseLevel ?: 10; $i++) {
[$red, $blue, $green] = $this->getRandomLightBgColor();
$noiseColor = imagecolorallocate($this->imgCanvas, $red, $blue, $green);
for ($j = 0; $j < 5; $j++) {
// 画杂点
imagestring($this->imgCanvas, 2, mt_rand(-10, $this->config->width), mt_rand(-10, $this->config->height), $codeSet[mt_rand(0, strlen($codeSet) - 1)], $noiseColor);
}
}
}
/**
* 画干扰曲线
*/
protected function drawCurve(): void
{
$py = 0;
// 曲线前部分
$A = mt_rand(1, $this->config->height / 2);// 振幅
$b = mt_rand(-$this->config->height / 4, $this->config->height / 4); // Y轴方向偏移量
$f = mt_rand(-$this->config->height / 4, $this->config->height / 4); // X轴方向偏移量
$T = mt_rand($this->config->height, $this->config->width * 2); // 周期
$w = (2 * M_PI) / $T;
$px1 = 0; // 曲线横坐标起始位置
$px2 = mt_rand($this->config->width / 2, $this->config->width * 0.8); // 曲线横坐标结束位置
[$red, $blue, $green] = is_string($this->config->fontColor) ? $this->config->hexToRgb($this->config->fontColor) : $this->config->fontColor;
!$red && [$red, $blue, $green] = [mt_rand(1, 150), mt_rand(1, 150), mt_rand(1, 150)];
$color = imagecolorallocate($this->imgCanvas, $red, $blue, $green);
for ($px = $px1; $px <= $px2; $px = $px + 1) {
if ($w != 0) {
// y = Asin(ωx+φ) + b
$py = $A * sin($w * $px + $f) + $b + $this->config->height / 2;
$i = $this->config->fontSize / 20;
while ($i > 0) {
// 这里(while)循环画像素点比imagettftext和imagestring用字体大小一次画出(不用这while循环)性能要好很多
imagesetpixel($this->imgCanvas, $px + $i, $py + $i, $color);
$i--;
}
}
}
// 曲线后部分
$A = mt_rand(1, $this->config->height / 2); // 振幅
$f = mt_rand(-$this->config->height / 4, $this->config->height / 4); // X轴方向偏移量
$T = mt_rand($this->config->height, $this->config->width * 2); // 周期
$w = (2 * M_PI) / $T;
$b = $py - $A * sin($w * $px + $f) - $this->config->height / 2;
$px1 = $px2;
$px2 = $this->config->width;
for ($px = $px1; $px <= $px2; $px = $px + 1) {
if ($w != 0) {
// y = Asin(ωx+φ) + b
$py = $A * sin($w * $px + $f) + $b + $this->config->height / 2;
$i = $this->config->fontSize / 20;
while ($i > 0) {
// 这里(while)循环画像素点比imagettftext和imagestring用字体大小一次画出(不用这while循环)性能要好很多
imagesetpixel($this->imgCanvas, $px + $i, $py + $i, $color);
$i--;
}
}
}
}
/**
* 获取base64图片
* @return string
*/
public function getBase64(): string
{
return "data:image/png;base64," . base64_encode($this->byte);
}
/**
* 获取验证码
* @return string
*/
public function getCode(): string
{
return $this->code;
}
}
| true |
4b1f92f2b7df95e2b4bfd1b46ffedbe59de912d9 | PHP | hamedbaftam/e-wallet | /src/Services/StorageService.php | UTF-8 | 1,815 | 2.703125 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types=1);
namespace Bavix\Wallet\Services;
use Bavix\Wallet\Internal\Exceptions\RecordNotFoundException;
use Bavix\Wallet\Internal\LockInterface;
use Bavix\Wallet\Internal\MathInterface;
use Bavix\Wallet\Internal\StorageInterface;
use Illuminate\Cache\CacheManager;
use Illuminate\Config\Repository as ConfigRepository;
use Illuminate\Contracts\Cache\Repository as CacheRepository;
class StorageService implements StorageInterface
{
private CacheRepository $cache;
private LockInterface $lock;
private MathInterface $math;
public function __construct(
CacheManager $cacheManager,
ConfigRepository $config,
LockInterface $lock,
MathInterface $math
) {
$this->math = $math;
$this->lock = $lock;
$this->cache = $cacheManager->driver(
$config->get('wallet.cache.driver', 'array')
);
}
public function flush(): bool
{
return $this->cache->flush();
}
public function missing(string $key): bool
{
return $this->cache->delete($key);
}
public function get(string $key): string
{
$value = $this->cache->get($key);
if ($value === null) {
throw new RecordNotFoundException();
}
return $this->math->round($value);
}
public function sync(string $key, $value): bool
{
return $this->cache->set($key, $value);
}
public function increase(string $key, $value): string
{
return $this->lock->block(
$key,
function () use ($key, $value): string {
$result = $this->math->add($this->get($key), $value);
$this->sync($key, $result);
return $this->math->round($result);
}
);
}
}
| true |
e71f8b67f8ea8a8488cb8b88fed90ae075e0b933 | PHP | MinchoFB/Proyecto-Ingenieria-II | /cookbook/controller/addStateController.php | UTF-8 | 1,227 | 2.734375 | 3 | [] | no_license | <?php
chdir('..');
require_once 'index.php';
require_once 'controller/twigLoader.php';
require_once 'model/statesModel.php';
session_start();
if (isset($_SESSION['user'])) {
if (!($_SESSION['user']['nombreRol'] == "Admin")) {
header('Location: normalUserController.php');
}
} else {
header('Location: homeController.php');
}
$reports = array();
$twig = getTwigEnviroment();
$template = $twig->loadTemplate('addState.html.twig');
function nameIsOk($nombre) {
//Solo letras y espacios
if (preg_match('/^[a-zA-Záéíóú\s]+$/', $nombre)) {
return true;
}
return false;
}
if ($_POST) {
$nombre = $_POST['nombre'];
if (!nameIsOk($nombre)) {
$reports[] = "Ese nombre no es válido. Debe contener solo caracteres alfabéticos.";
echo $template->render(array('logged' => $_SESSION['user'], 'reports' => $reports));
die;
}
if ((stateExist($nombre))) {
$reports[] = "Ese estado ya existe.";
echo $template->render(array('logged' => $_SESSION['user'], 'reports' => $reports));
die;
}
addState($nombre);
header('Location: statesController.php');
}
echo $template->render(array('logged' => $_SESSION['user'])); | true |
6923ee0acbaff6a7f5b5f17e6de1fe6ec1d07c0b | PHP | dawguy/LearningThroughManga | /common/db_lib/get_vocab.php | UTF-8 | 551 | 2.546875 | 3 | [] | no_license | <?php
require_once( $_SERVER['DOCUMENT_ROOT'] . '/common/functions/db_lib.php' );
function get_vocab( $pk_vocab )
{
global $pdo;
$pk_vocab = intval( $pk_vocab, 10 );
$statement = "SELECT vocab, manga_context, english, korean, english_definition, korean_definition FROM tb_vocab WHERE vocab = :vocab";
$sth = $pdo->prepare( $statement );
$sth->bindValue( ':vocab', $pk_vocab );
$sth->execute();
$retval = $sth->fetchAll();
if( is_array( $retval ) )
{
$retval = $retval[0];
}
return $retval;
}
| true |
0bf9271f6f0a38351a7ceb7524f4d273b699786d | PHP | DenisCampos/frete-internacional | /app/Models/User.php | UTF-8 | 1,402 | 2.6875 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Models;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use App\Notifications\ResetPasswordNotification;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContracts;
use \Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContracts;
class User extends Model implements AuthenticatableContracts, CanResetPasswordContracts
{
use Notifiable, Authenticatable, CanResetPassword;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $table = 'users';
protected $fillable = [
'name',
'tipo',
'cpf',
'rg',
'email',
'contato',
'password',
'endereco',
'bairro',
'numero',
'complemento',
'cidade',
'uf',
'pais',
'cep'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* Send the password reset notification.
*
* @param string $token
* @return void
*/
public function sendPasswordResetNotification($token)
{
$this->notify(new ResetPasswordNotification($token));
}
}
| true |
144c632e0d9255ac24b8ee07fd334349f67e7f1f | PHP | kecs/CCE-web | /lib/model/doctrine/base/BaseDevice.class.php | UTF-8 | 2,171 | 2.515625 | 3 | [] | no_license | <?php
/**
* BaseDevice
*
* This class has been auto-generated by the Doctrine ORM Framework
*
* @property integer $id
* @property string $pan_id
* @property string $extended_id
* @property Doctrine_Collection $Sensor
*
* @method integer getId() Returns the current record's "id" value
* @method string getPanId() Returns the current record's "pan_id" value
* @method string getExtendedId() Returns the current record's "extended_id" value
* @method Doctrine_Collection getSensor() Returns the current record's "Sensor" collection
* @method Device setId() Sets the current record's "id" value
* @method Device setPanId() Sets the current record's "pan_id" value
* @method Device setExtendedId() Sets the current record's "extended_id" value
* @method Device setSensor() Sets the current record's "Sensor" collection
*
* @package cce
* @subpackage model
* @author Adam Banko (Cassus)
* @version SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
*/
abstract class BaseDevice extends sfDoctrineRecord
{
public function setTableDefinition()
{
$this->setTableName('device');
$this->hasColumn('id', 'integer', null, array(
'type' => 'integer',
'primary' => true,
'autoincrement' => true,
));
$this->hasColumn('pan_id', 'string', 255, array(
'type' => 'string',
'notnull' => true,
'length' => 255,
));
$this->hasColumn('extended_id', 'string', 16, array(
'type' => 'string',
'notnull' => true,
'length' => 16,
));
$this->index('guid', array(
'type' => 'unique',
'fields' =>
array(
0 => 'pan_id',
1 => 'extended_id',
),
));
}
public function setUp()
{
parent::setUp();
$this->hasMany('Sensor', array(
'local' => 'id',
'foreign' => 'device_id'));
}
} | true |
96ee7d7cd4fd7d077e45aad9088c6f043c9207fc | PHP | vaseninm/payment-laravel | /src/drivers/tinkoff/Receipt.php | UTF-8 | 4,152 | 2.828125 | 3 | [
"MIT"
] | permissive | <?php namespace professionalweb\payment\drivers\tinkoff;
use Illuminate\Contracts\Support\Arrayable;
/**
* Receipt
* @package professionalweb\payment\drivers\tinkoff
*/
class Receipt implements Arrayable
{
/**
* общая СН
*/
const TAX_SYSTEM_COMMON = 'osn';
/**
* упрощенная СН (доходы)
*/
const TAX_SYSTEM_SIMPLE_INCOME = 'usn_income';
/**
* упрощенная СН (доходы минус расходы)
*/
const TAX_SYSTEM_SIMPLE_NO_OUTCOME = 'usn_income_outcome';
/**
* единый налог на вмененный доход
*/
const TAX_SYSTEM_SIMPLE_UNIFIED = 'envd';
/**
* единый сельскохозяйственный налог
*/
const TAX_SYSTEM_SIMPLE_AGRO = 'esn';
/**
* патентная СН
*/
const TAX_SYSTEM_SIMPLE_PATENT = 'patent';
/**
* Phone number
*
* @var string
*/
private $phone;
/**
* Phone number
*
* @var string
*/
private $email;
/**
* Tax system
* Система налогообложения магазина (СНО). Параметр необходим, только если у вас несколько систем налогообложения. В остальных случаях не передается.
*
* @var int
*/
private $taxSystem;
/**
* Items
*
* @var ReceiptItem[]
*/
private $items = [];
/**
* Receipt constructor.
*
* @param string $phone
* @param string $email
* @param array|null $items
* @param int $taxSystem
*/
public function __construct($phone = null, $email = null, array $items = [], $taxSystem = null)
{
$this->setPhone($phone)->setEmail($email)->setItems($items)->setTaxSystem($taxSystem);
}
/**
* @return string
*/
public function getPhone()
{
return $this->phone;
}
/**
* @param $phone
* @return $this
*/
public function setPhone($phone)
{
$this->phone = $phone;
return $this;
}
/**
* @return string
*/
public function getEmail()
{
return $this->email;
}
/**
* @param $email
* @return $this
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get tax system
*
* @return int
*/
public function getTaxSystem()
{
return $this->taxSystem;
}
/**
* Set tax system
*
* @param int $taxSystem
*
* @return $this
*/
public function setTaxSystem($taxSystem)
{
$this->taxSystem = $taxSystem;
return $this;
}
/**
* Get all items in receipt
*
* @return ReceiptItem[]
*/
public function getItems()
{
return $this->items;
}
/**
* Set items in receipt
*
* @param ReceiptItem[] $items
*
* @return $this
*/
public function setItems(array $items)
{
$this->items = $items;
return $this;
}
/**
* Add item
*
* @param ReceiptItem $item
*
* @return $this
*/
public function addItem(ReceiptItem $item)
{
$this->items[] = $item;
return $this;
}
/**
* Receipt to array
*
* @return array
*/
public function toArray()
{
$items = array_map(function ($item) {
/** @var ReceiptItem $item */
return $item->toArray();
}, $this->getItems());
$result = [
'Phone' => $this->getPhone(),
'Email' => $this->getEmail(),
'Items' => $items,
];
if (($taxSystem = $this->getTaxSystem()) !== null) {
$result['Taxation'] = $taxSystem;
}
return $result;
}
/**
* Receipt to json
*
* @return string
*/
public function __toString()
{
return json_encode($this->toArray());
}
} | true |
2e2e2f7732123492b9de00b864ba3bf81a39a322 | PHP | OpenClassrooms/CodeGenerator | /tests/Utility/MethodUtilityTest.php | UTF-8 | 1,761 | 2.53125 | 3 | [] | no_license | <?php
declare(strict_types=1);
namespace OpenClassrooms\CodeGenerator\Tests\Utility;
use OpenClassrooms\CodeGenerator\Utility\DocCommentUtility;
use OpenClassrooms\CodeGenerator\Utility\MethodUtility;
use PHPUnit\Framework\TestCase;
class MethodUtilityTest extends TestCase
{
/**
* @test
*/
public function createArgumentNameFromMethodReturnNull(): void
{
$exceptedValue = MethodUtility::createAccessorNameFromMethod('notWorkingMethodName');
$this->assertNull($exceptedValue);
}
/**
* @test
*/
public function getAccessorsReturnMethodObjects(): void
{
$class = (new class() {
/**
* @return string
*/
public function getValue(string $argument)
{
echo $argument;
}
});
$fields = MethodUtility::getAccessors(get_class($class));
$field = array_shift($fields);
$method = (new \ReflectionClass($class))->getMethod('getValue');
$this->assertSame($field->getName(), $method->getName());
$this->assertSame($field->getDocComment(), $method->getDocComment());
$this->assertSame($field->getReturnType(), DocCommentUtility::getReturnType($method->getDocComment()));
$this->assertSame($field->isNullable(), DocCommentUtility::allowsNull($method->getDocComment()));
}
/**
* @test
*/
public function getAccessorsThrowException(): void
{
$this->expectException(\Exception::class);
$class = (new class() {
public function getMethod(string $argument)
{
return $argument;
}
});
MethodUtility::getAccessors(get_class($class));
}
}
| true |
45a12250f7dc17213f4460d5c28196b3eaea03a5 | PHP | FixterSpb/red-black-tree | /src/Node.php | UTF-8 | 4,273 | 3.234375 | 3 | [] | no_license | <?php
const COLOR_BLACK = "#000";
const COLOR_RED = "#c33";
class Node implements JsonSerializable
{
private ?Node $parent = null;
private ?Node $left = null;
private ?Node $right = null;
private ?int $value = null;
private string $color = COLOR_BLACK;
public function __construct(?int $value = null)
{
$this->value = $value;
}
public function add(?Node $node)
{
if (!$node->value) return;
if ($node->value > $this->value) {
if ($this->right && $this->right->value) {
$this->right->add($node);
} else {
$this->right = $node;
$this->setNodes($node);
}
} else {
if ($this->left && $this->left->value) {
$this->left->add($node);
} else {
$this->left = $node;
$this->setNodes($node);
}
}
}
public function jsonSerialize(): array
{
return [
"value" => $this->value,
"color" => $this->color,
"left" => $this->left,
"right" => $this->right
];
}
public function isRed(): bool
{
return $this->color === COLOR_RED;
}
public function isBlack(): bool
{
return $this->color === COLOR_BLACK;
}
private function getUncle(): ?Node
{
if ($this->parent && $this->parent->parent) {
if ($this->parent->parent->left === $this->parent) return $this->parent->parent->right;
else return $this->parent->parent->left;
}
return null;
}
private function isLeftChild(): bool
{
if (!$this->parent) return false;
return $this === $this->parent->left;
}
private function isRightChild(): bool
{
if (!$this->parent) return false;
return $this === $this->parent->right;
}
private function control()
{
if (!$this->parent) return;
if (!$uncle = $this->getUncle()) return;
if ($this->isRed() && $this->parent->isRed() && $uncle->isRed()) {
$this->parent->color = COLOR_BLACK;
$uncle->color = COLOR_BLACK;
if ($this->parent->parent->parent){
$this->parent->parent->color = COLOR_RED;
}else{
$this->parent->parent->color = COLOR_BLACK;
}
} else if ($this->isRed() && $this->parent->isRed()) {
if ($this->isLeftChild() && $this->parent->isRightChild()){
$this->parent->rotateRight();
}else if ($this->isRightChild() && $this->parent->isLeftChild()){
$this->parent->rotateLeft();
}else if($this->isLeftChild() && $this->parent->isLeftChild()){
$this->parent->parent->rotateRight();
}else if($this->isRightChild() && $this->parent->isRightChild()){
$this->parent->parent->rotateLeft();
}
}
// $this->parent->control();
}
public function rotateLeft(){
$right = $this->right;
$right->parent = $this->parent;
$this->right = $right->left;
if ($this->parent->left === $this) $this->parent->left = $right;
else $this->parent->right = $right;
$this->parent = $right;
$right->left = $this;
if ($this->isBlack() && $this->parent->isRed()){
$this->color = COLOR_RED;
$this->parent->color = COLOR_BLACK;
}
$this->control();
}
public function rotateRight(){
$left = $this->left;
$left->parent = $this->parent;
$this->left = $left->right;
if ($this->parent->left === $this) $this->parent->left = $left;
else $this->parent->right = $left;
$this->parent = $left;
$left->right = $this;
if ($this->isBlack() && $this->parent->isRed()){
$this->color = COLOR_RED;
$this->parent->color = COLOR_BLACK;
}
$this->control();
}
private function setNodes(Node $node)
{
$node->parent = $this;
$node->left = new Node();
$node->right = new Node();
$node->color = COLOR_RED;
$node->control();
}
} | true |
fefe5cf533aa640c402dc405c504211ec4cf03a4 | PHP | grizz-it/services | /src/Common/Registry/ServiceRegistryInterface.php | UTF-8 | 534 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
/**
* Copyright (C) GrizzIT, Inc. All rights reserved.
* See LICENSE for license details.
*/
namespace GrizzIt\Services\Common\Registry;
interface ServiceRegistryInterface
{
/**
* Retrieves the definition by a key.
*
* @param string $key
*
* @return mixed
*/
public function getDefinitionByKey(string $key): mixed;
/**
* Checks whether a definition exists.
*
* @param string $key
*
* @return bool
*/
public function exists(string $key): bool;
}
| true |
1925e4332b895bfb119d5fdb5f6bd2b48c68db92 | PHP | GimmyHchs/PMBook | /app/Project/File/FileEloquent.php | UTF-8 | 373 | 2.75 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Project\File;
use App\Project\ProjectEloquent;
/**
* File類別核心
*/
abstract class FileEloquent extends ProjectEloquent
{
/**
* 所有FileEloquent 必須有類型關聯
*/
abstract public function type();
/**
* 所有FileEloquent 必須能夠被賦予類型
*/
abstract public function assignType($type);
}
| true |
d358e81d2d5df515adf53e3886a10e77016bc354 | PHP | yakovenkoroman1993/lectern_downgrade | /model/Utils.php | UTF-8 | 5,676 | 2.796875 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* Date => 21.05.2016
* Time => 13:10
*/
use Entity\Cv;
use Entity\Person;
class Utils
{
/**
* @param array $list
* @param array $data
* @param array $prevData
* @return array
*/
public static function arraySerialization(array $list, array $data, array $prevData = array()) {
$result = array();
if ($data && is_array($data) && $list && is_array($list)) {
foreach ($list as $item) {
$result[$item] = isset($data[$item]) ? (($data[$item] === '0' || $data[$item] === 0 || $data[$item]) ? $data[$item] : null) : null;
}
}
return array_merge($prevData, $result);
}
/**
* @return string
*/
public static function getHttpHost(){
return 'http://' . $_SERVER['HTTP_HOST'];
}
/**
* @return bool
*/
public static function isAjax()
{
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
}
/**
* @return array
*/
public static function getSpheresTitles()
{
return array(
'programmer' => 'программист',
'system_admin' => 'системный администратор',
'security_admin' => 'администратор ИБ',
'web_designer' => 'веб дизайнер',
'project_manager' => 'проект менеджер',
'software_testing' => 'тестировщик ПО',
'web_developer' => 'веб-разработчик',
);
}
/**
* @return array
*/
public static function getWorkExperiencesTitles()
{
return array(
'nope' => 'без опыта',
'<1' => 'менее года',
'1-3' => '1-3 года',
'3-5' => '3-5 лет',
'5>' => 'более 5 лет'
);
}
/**
* @return array
*/
public static function getEducationsTitles()
{
return array(
'<middle' => 'неполное среднее',
'middle' => 'среднее',
'middle>' => 'среднее профессиональное',
'>high' => 'высшее (бакалавриат)',
'high' => 'высшее (магистратура)',
'many_high' => 'два высших',
'fulltime_student' => 'студент-очник',
'distance_student' => 'студент-заочник',
);
}
/**
* @return array
*/
public static function getSchedulesTitles()
{
return array(
'full' => 'полный рабочий день',
'remote' => 'удаленная работа',
'elastic' => 'гибкий',
'shift' => 'сменный'
);
}
/**
* @param array $params
* @return Cv
*/
public static function fillCv(array $params, Cv $cv)
{
foreach ($params as $key => $value) {
switch ($key) {
case 'sphere': $cv->setSphere($value); break;
case 'access_type': $cv->setAccessType($value); break;
case 'hobbies': $cv->setHobbies($value); break;
case 'skills': $cv->setSkills($value); break;
case 'work_experience': $cv->setWorkExperience($value); break;
case 'education': $cv->setEducation($value); break;
case 'ext_education': $cv->setExtEducation($value); break;
case 'desire_salary': $cv->setDesireSalary($value); break;
case 'schedule': $cv->setSchedule($value); break;
case 'foreign_languages': $cv->setForeignLanguages($value); break;
case 'is_drivers_license': $cv->setIsDriversLicense($value); break;
case 'is_smoking': $cv->setIsSmoking($value); break;
case 'is_married': $cv->setIsMarried($value); break;
case 'about': $cv->setAbout($value); break;
}
}
return $cv;
}
/**
* @param Person $person
* @return array
*/
public static function personInformationToArray(Person $person)
{
return array(
'full_name' => $person->getFullName(),
'date_birth' => $person->getDateBirth()->format('Y-m-d'),
'organisation' => $person->getOrganisation(),
'email' => $person->getUser()->getEmail(),
'phone' => $person->getContact()->getPhone(),
'websites' => $person->getContact()->getWebsites(),
'city' => $person->getContact()->getAddress()->getCity(),
'street' => $person->getContact()->getAddress()->getStreet(),
'house_number' => $person->getContact()->getAddress()->getHouseNumber(),
'apartment_number' => $person->getContact()->getAddress()->getApartmentNumber(),
);
}
/**
* @param $sphere
* @return array|string
*/
public static function getSpheresString($sphere) {
$spheres = array_filter(explode(',', $sphere));
$result = '';
if ($spheres) {
$result = array();
foreach ($spheres as $item) {
$temp = Utils::getSpheresTitles();
$result[] = $temp[$item];
}
$result = implode(',', $result);
}
return $result;
}
} | true |
6a0b339f55ae180db92c150bdb00908a01f4cb7a | PHP | nestauk/DSI4EU | /src/DSI/Controller/CLI/UpdateProjectTagsController.php | UTF-8 | 2,976 | 2.859375 | 3 | [] | no_license | <?php
namespace DSI\Controller\CLI;
use DSI\NotFound;
use DSI\Repository\OrganisationRepo;
use DSI\Repository\ProjectImpactHelpTagRepo;
use DSI\Repository\ProjectRepo;
use DSI\Repository\ProjectRepoInAPC;
use DSI\UseCase\AddImpactHelpTagToProject;
use DSI\UseCase\CalculateOrganisationPartnersCount;
use DSI\UseCase\RemoveImpactHelpTagFromProject;
class UpdateProjectTagsController
{
/** @var String[] */
private $args;
public function exec()
{
if (!isset($this->args[2]))
throw new \Exception('Provide file path');
$filename = basename($this->args[2]);
$filePath = __DIR__ . '/../../../../' . $filename;
if (!file_exists($filePath))
throw new NotFound($filePath);
$this->updateTagsFromFile($filePath);
}
/**
* @param \String[] $args
*/
public function setArgs(array $args)
{
$this->args = $args;
}
/**
* @param $filePath
*/
private function updateTagsFromFile($filePath)
{
if (($handle = fopen($filePath, "r")) !== FALSE) {
while (($data = fgetcsv($handle)) !== FALSE) {
$projectID = (int)$data[1];
$areasOfImpact = explode(',', $data[4]);
$areasOfImpact = array_map('trim', $areasOfImpact);
$areasOfImpact = array_filter($areasOfImpact);
$areasOfImpact = array_unique($areasOfImpact);
$areasOfImpactLowerCase = array_map('strtolower', $areasOfImpact);
try {
$project = (new ProjectRepoInAPC())->getById($projectID);
} catch (NotFound $e) {
echo "project id {$projectID} not found" . PHP_EOL;
continue;
}
$projectTags = (new ProjectImpactHelpTagRepo())->getTagNamesByProject($project);
$projectTagsLowerCase = array_map('strtolower', $projectTags);
foreach ($projectTags AS $oldTagName) {
if (!in_array(strtolower($oldTagName), $areasOfImpactLowerCase)) {
echo "remove $oldTagName" . PHP_EOL;
$remTag = new RemoveImpactHelpTagFromProject();
$remTag->data()->projectID = $projectID;
$remTag->data()->tag = $oldTagName;
$remTag->exec();
}
}
foreach ($areasOfImpact AS $newTagName) {
if (!in_array(strtolower($newTagName), $projectTagsLowerCase)) {
echo "add $newTagName" . PHP_EOL;
$addTag = new AddImpactHelpTagToProject();
$addTag->data()->projectID = $projectID;
$addTag->data()->tag = $newTagName;
$addTag->exec();
}
}
}
fclose($handle);
}
}
} | true |
7d5eb9487400ac1629abe19cdb82d49c94512777 | PHP | catchup-forks/PackageEws365 | /src/ArrayType/EwsArrayOfGroupedItemsType.php | UTF-8 | 4,763 | 2.671875 | 3 | [
"MIT"
] | permissive | <?php
namespace Ews\ArrayType;
use \WsdlToPhp\PackageBase\AbstractStructArrayBase;
/**
* This class stands for ArrayOfGroupedItemsType ArrayType
* @package Ews
* @subpackage Arrays
* @author WsdlToPhp <contact@wsdltophp.com>
*/
class EwsArrayOfGroupedItemsType extends AbstractStructArrayBase
{
/**
* The GroupedItems
* Meta informations extracted from the WSDL
* - maxOccurs: unbounded
* - minOccurs: 0
* @var \Ews\StructType\EwsGroupedItemsType[]
*/
public $GroupedItems;
/**
* Constructor method for ArrayOfGroupedItemsType
* @uses EwsArrayOfGroupedItemsType::setGroupedItems()
* @param \Ews\StructType\EwsGroupedItemsType[] $groupedItems
*/
public function __construct(array $groupedItems = array())
{
$this
->setGroupedItems($groupedItems);
}
/**
* Get GroupedItems value
* @return \Ews\StructType\EwsGroupedItemsType[]|null
*/
public function getGroupedItems()
{
return $this->GroupedItems;
}
/**
* Set GroupedItems value
* @throws \InvalidArgumentException
* @param \Ews\StructType\EwsGroupedItemsType[] $groupedItems
* @return \Ews\ArrayType\EwsArrayOfGroupedItemsType
*/
public function setGroupedItems(array $groupedItems = array())
{
foreach ($groupedItems as $arrayOfGroupedItemsTypeGroupedItemsItem) {
// validation for constraint: itemType
if (!$arrayOfGroupedItemsTypeGroupedItemsItem instanceof \Ews\StructType\EwsGroupedItemsType) {
throw new \InvalidArgumentException(sprintf('The GroupedItems property can only contain items of \Ews\StructType\EwsGroupedItemsType, "%s" given', is_object($arrayOfGroupedItemsTypeGroupedItemsItem) ? get_class($arrayOfGroupedItemsTypeGroupedItemsItem) : gettype($arrayOfGroupedItemsTypeGroupedItemsItem)), __LINE__);
}
}
$this->GroupedItems = $groupedItems;
return $this;
}
/**
* Add item to GroupedItems value
* @throws \InvalidArgumentException
* @param \Ews\StructType\EwsGroupedItemsType $item
* @return \Ews\ArrayType\EwsArrayOfGroupedItemsType
*/
public function addToGroupedItems(\Ews\StructType\EwsGroupedItemsType $item)
{
// validation for constraint: itemType
if (!$item instanceof \Ews\StructType\EwsGroupedItemsType) {
throw new \InvalidArgumentException(sprintf('The GroupedItems property can only contain items of \Ews\StructType\EwsGroupedItemsType, "%s" given', is_object($item) ? get_class($item) : gettype($item)), __LINE__);
}
$this->GroupedItems[] = $item;
return $this;
}
/**
* Returns the current element
* @see AbstractStructArrayBase::current()
* @return \Ews\StructType\EwsGroupedItemsType|null
*/
public function current()
{
return parent::current();
}
/**
* Returns the indexed element
* @see AbstractStructArrayBase::item()
* @param int $index
* @return \Ews\StructType\EwsGroupedItemsType|null
*/
public function item($index)
{
return parent::item($index);
}
/**
* Returns the first element
* @see AbstractStructArrayBase::first()
* @return \Ews\StructType\EwsGroupedItemsType|null
*/
public function first()
{
return parent::first();
}
/**
* Returns the last element
* @see AbstractStructArrayBase::last()
* @return \Ews\StructType\EwsGroupedItemsType|null
*/
public function last()
{
return parent::last();
}
/**
* Returns the element at the offset
* @see AbstractStructArrayBase::offsetGet()
* @param int $offset
* @return \Ews\StructType\EwsGroupedItemsType|null
*/
public function offsetGet($offset)
{
return parent::offsetGet($offset);
}
/**
* Returns the attribute name
* @see AbstractStructArrayBase::getAttributeName()
* @return string GroupedItems
*/
public function getAttributeName()
{
return 'GroupedItems';
}
/**
* Method called when an object has been exported with var_export() functions
* It allows to return an object instantiated with the values
* @see AbstractStructArrayBase::__set_state()
* @uses AbstractStructArrayBase::__set_state()
* @param array $array the exported values
* @return \Ews\ArrayType\EwsArrayOfGroupedItemsType
*/
public static function __set_state(array $array)
{
return parent::__set_state($array);
}
/**
* Method returning the class name
* @return string __CLASS__
*/
public function __toString()
{
return __CLASS__;
}
}
| true |
d2f5f4943479e03f0e6ae2a364d19e119ca79c20 | PHP | ruskov2050/Projet-Synthese-Hypermedia1 | /modele/classes/ContactsEntrs.php | UTF-8 | 904 | 2.78125 | 3 | [] | no_license | <?php
class ContactsEntrs extends Personnes
{
protected $_NumeroPoste;
public function createcontact($prenom,$nom,$numCell,$email,$password,$typeCompte,$numroposte)
{ $today= MyGenerator::getDateNow();
$this->setId(MyGenerator::getIdGenerated());
$this->setPrenom($prenom);
$this->setNom($nom);
$this->setNumCell($numCell);
$this->setMail($email);
$this->setPassword($password);
$this->setTypeCompte($typeCompte);
$this->setDateActivation($today);
$this->setDateModification($today);
$this->_NumeroPoste = $numroposte;
}
/**
* @return mixed
*/
public function getNumeroPoste()
{
return $this->_NumeroPoste;
}
/**
* @param mixed $NumeroPoste
*/
public function setNumeroPoste($NumeroPoste)
{
$this->_NumeroPoste = $NumeroPoste;
}
} | true |
74792077089f2a7c9bd78334a497e4cf04d71c46 | PHP | missxiaolin/blog | /Common/Model/AuthRuleModel.class.php | UTF-8 | 1,732 | 2.75 | 3 | [] | no_license | <?php
namespace Common\Model;
use Think\Model;
/**
* 权限管理
*/
class AuthRuleModel extends Model{
// 添加权限
public function addData($data){
// 去除首尾空格
foreach ($data as $k => $v) {
$data[$k] = trim($v);
}
$this->add($data);
return true;
}
/**
* 修改数据
* @param array $data 数据
*/
public function editData($data){
// 去除键值首位空格
foreach ($data as $k => $v) {
$data[$k]=trim($v);
}
$this->where(array('id'=>$data['id']))->save($data);
return true;
}
/**
* 删除数据
* @param array $map where语句数组形式
* @return boolean 操作是否成功
*/
public function deleteData($map){
$count=$this
->where(array('pid'=>$map['id']))
->count();
if($count!=0){
return false;
}
$this->where($map)->delete();
return true;
}
/**
* 获取全部数据
* @param string $type tree获取树形结构 level获取层级结构
* @param string $order 排序方式
* @return array 结构数据
*/
public function getTreeData($type='tree',$order='',$name='name',$child='id',$parent='pid'){
// 判断是否需要排序
if(empty($order)){
$data=$this->select();
}else{
$data=$this->order($order.' is null,'.$order)->select();
}
// 获取树形或者结构数据
if($type=='tree'){
$data=\Common\Lib\Data::tree($data,$name,$child,$parent);
}elseif($type="level"){
$data=\Common\Lib\Data::channelLevel($data,0,' ',$child);
}
// p($data);
return $data;
}
} | true |
6185026db47d3d6859e03bad358f669f13689220 | PHP | phachon/kofast | /kofast/extends/ueditor/classes/UEditor/Upload/Base64.php | UTF-8 | 1,326 | 2.703125 | 3 | [
"MIT"
] | permissive | <?php
/**
* UEditor Base64 上传类封装
* @author phachon@163.com
*/
class UEditor_Upload_Base64 extends UEditor_Upload {
/**
* execute
*/
public function execute() {
$fileField = $this->_config['fieldName'];
$base64Data = $_POST[$fileField];
$img = base64_decode($base64Data);
$this->_oriName = $this->_config['oriName'];
$this->_fileSize = strlen($img);
$this->_fileType = $this->_getFileExt();
$this->_fullName = $this->_getFullName();
$this->_filePath = $this->_getFilePath();
$this->_fileName = $this->_getFileName();
$dirname = dirname($this->_filePath);
//检查文件大小是否超出限制
if (!$this->_checkSize()) {
$this->_stateInfo = $this->_getStateInfo("ERROR_SIZE_EXCEED");
return;
}
//创建目录失败
if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
$this->_stateInfo = $this->_getStateInfo("ERROR_CREATE_DIR");
return;
} else if (!is_writeable($dirname)) {
$this->_stateInfo = $this->_getStateInfo("ERROR_DIR_NOT_WRITEABLE");
return;
}
//移动文件
if (!(file_put_contents($this->_filePath, $img) && file_exists($this->_filePath))) { //移动失败
$this->_stateInfo = $this->_getStateInfo("ERROR_WRITE_CONTENT");
} else { //移动成功
$this->_stateInfo = $this->_stateMap[0];
}
return $this->results();
}
} | true |
6efd0b50926939eac82bbf31a143423d96a315e6 | PHP | sistemas3stb/migration | /Core/Server.php | UTF-8 | 816 | 3.140625 | 3 | [] | no_license | <?php
namespace Migration\Core;
/**
* Server
*/
abstract class Server
{
protected $_session;
protected $_host;
protected $_port;
public function __construct($params)
{
$this->setPropertyFromArray($params);
}
public function __set($name,$value)
{
$property = "_$name";
if(property_exists(get_called_class(), $property))
{
$this->{$property} = $value;
}
}
private function setPropertyFromArray($array)
{
foreach ($array as $key => $value)
{
$this->{$key} = $value;
}
}
abstract public function connect();
public function getSession()
{
return $this->session;
}
public function __get($name)
{
$property = "_$name";
if(property_exists(get_called_class(), $property))
{
return $this->{$property};
}
return null;
}
abstract public function ping();
}
?> | true |
fa89b526a9e17decd5ea58357a448d99938c2156 | PHP | john2096/eCommerce-PHP-site | /Sales_search.php | UTF-8 | 6,984 | 2.765625 | 3 | [] | no_license | <?php
require_once('DB_Conn.php');
require_once('Admin_Class.php');
$A1 = new Admin;
session_start();
if(isset($_SESSION['Admin']))
{
$A1=$_SESSION['Admin'];
echo "Welcome " . $A1 ->getAFirstName();
}
if(isset($_POST['Logout']))
{
echo "Goodbye " . $A1 ->getAFirstName();
session_destroy();
header("Location: Main.php");
}
if(isset($_POST['Return']))
{
header("Location: Sales.php");
}
$S1= filter_input(INPUT_POST, 'syear');
$S2= filter_input(INPUT_POST, 'smonth');
$S3= filter_input(INPUT_POST, 'sday');
$S4= filter_input(INPUT_POST, 'eyear');
$S5= filter_input(INPUT_POST, 'emonth');
$S6= filter_input(INPUT_POST, 'eday');
$S7= filter_input(INPUT_POST, 'product_id');
$S8= filter_input(INPUT_POST, 'user_id');
$Start = $S1 .'-' .$S2 .'-' .$S3;
$End = $S4 .'-' .$S5 .'-' .$S6;
$query = 'SELECT * FROM sales WHERE UserID = :user AND ProdID = :prod AND Sale_Date BETWEEN :startdate AND :enddate ORDER BY Sale_Date DESC;';
$statement = $db->prepare($query);
$statement->bindValue(':startdate', $Start);
$statement->bindValue(':enddate', $End);
$statement->bindValue(':prod', $S7);
$statement->bindValue(':user', $S8);
$statement->execute();
$sales = $statement->fetchAll();
$statement->closeCursor();
?>
<!DOCTYPE html>
<html>
<head>
<link rel="Stylesheet" href="Styles.css">
<h2 id="Title">Bits and Bytes</h2>
<hr>
</head>
<body>
<div id="navbar">
<h3 id="subhead">Navigation</h3>
<ul>
<li><a href="Sales.php">Sales</a></li>
<li><a href="Database_management.php">Database</a></li>
<li><a href="Report.php">Report</a></li>
<li><form action="#" method="post"><input type="submit" name="Logout" value="Logout"></form></li>
</ul>
</div>
<div id="navbar">
<form action="Sales_search.php" method="post">
<label>Select Starting date:</label><br>
<select name="syear">
<option value="2019">2019</option>
<option value="2020">2020</option>
<option value="2021">2021</option>
</select>
<select name="smonth">
<option value="01">01</option>
<option value="02">02</option>
<option value="03">03</option>
<option value="04">04</option>
<option value="05">05</option>
<option value="06">06</option>
<option value="07">07</option>
<option value="08">08</option>
<option value="09">09</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select>
<select name="sday">
<option value="01">01</option>
<option value="02">02</option>
<option value="03">03</option>
<option value="04">04</option>
<option value="05">05</option>
<option value="06">06</option>
<option value="07">07</option>
<option value="08">08</option>
<option value="09">09</option>
<option value="10">10</option>
<option value="10">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
<option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option>
<option value="29">29</option>
<option value="30">30</option>
<option value="31">31</option>
</select>
<br>
<br>
<label>Select Ending date:</label><br>
<select name="eyear">
<option value="2019">2019</option>
<option value="2020">2020</option>
<option value="2021">2021</option>
</select>
<select name="emonth">
<option value="01">01</option>
<option value="02">02</option>
<option value="03">03</option>
<option value="04">04</option>
<option value="05">05</option>
<option value="06">06</option>
<option value="07">07</option>
<option value="08">08</option>
<option value="09">09</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select>
<select name="eday">
<option value="01">01</option>
<option value="02">02</option>
<option value="03">03</option>
<option value="04">04</option>
<option value="05">05</option>
<option value="06">06</option>
<option value="07">07</option>
<option value="08">08</option>
<option value="09">09</option>
<option value="10">10</option>
<option value="10">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
<option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option>
<option value="29">29</option>
<option value="30">30</option>
<option value="31">31</option>
</select>
<br>
<br>
<label>Product ID:</label>
<input type="text" name="product_id"/>
<br>
<br>
<label>User ID:</label>
<input type="text" name="user_id"/>
<br>
<br>
<input type="submit" name="search" value="Seach sales">
</form>
</div>
<div>
<h3 id="subhead">Sales</h3>
<table>
<tr>
<th>Sale ID</th>
<th>Sale Amount</th>
<th>Date</th>
<th>Product ID</th>
</tr>
<?php foreach ($sales as $sales) : ?>
<tr>
<form action="Sales_delete.php" method="post">
<td><input type="text" name="saleid" value = <?php echo $sales['SaleID']; ?> /></td>
<td><input type="text" name="amount" value = <?php echo $sales['Sale_Amount']; ?> /></td>
<td><input type="text" name="date" value = <?php echo $sales['Sale_Date']; ?> /></td>
<td><input type="text" name="product_id" value = <?php echo $sales['ProdID']; ?> /></td>
<td><input type="text" name="user_id" value = <?php echo $sales['UserID']; ?> /></td>
<td><input type="submit" name="Delete" value="Delete"></td>
</form>
</tr>
<?php endforeach; ?>
</table>
<form action="#" method="post"><input type="submit" name="Return" value="Return"></form>
</div>
</body>
</html> | true |
550411e8fbd7cacf105414b8f4326394275ea1b7 | PHP | EzequielSegota/Prog3 | /Ejercicios/Ejercicio_13.php | UTF-8 | 406 | 2.96875 | 3 | [] | no_license | <?php
$arrayAnimales=array();
$arrayAños=array();
$arrayLenguajes=array();
array_push($arrayAnimales,"Perro", "Gato", "Ratón", "Araña", "Mosca");
array_push($arrayAños,1986, 1996, 2015, 78, 86);
array_push($arrayLenguajes,"php", "mysql", "html5", "typescript", "ajax");
$arrayFinal=array_merge($arrayAnimales,$arrayAños,$arrayLenguajes);
foreach ($arrayFinal as $value) {
echo "<br/>",$value;
} | true |
ceb2388edc911978585085853a5ff7ceaf5c83ba | PHP | bhandaribandanaa/laravel-project | /database/migrations/2017_04_10_130436_create_doctors_table.php | UTF-8 | 680 | 2.703125 | 3 | [
"MIT"
] | permissive | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateDoctorsTable extends Migration
{
public function up(){
Schema::create('doctors', function($table){
$table->increments('id');
$table->string('full_name');
$table->string('professional_title');
$table->string('contact');
$table->string('address');
$table->text('description');
$table->enum('status', ['0', '1']);
$table->timestamps();
$table->softDeletes();
});
}
public function down(){
Schema::dropIfExists('doctors');
}
}
| true |
c4532394f9acf872b401b2183b0f03bdf2bb5abe | PHP | duytc/tagcade-api | /src/Tagcade/Model/Core/BillingConfigurationInterface.php | UTF-8 | 1,537 | 2.59375 | 3 | [
"MIT"
] | permissive | <?php
namespace Tagcade\Model\Core;
use Tagcade\Model\ModelInterface;
use Tagcade\Model\User\Role\PublisherInterface;
interface BillingConfigurationInterface extends ModelInterface
{
/**
* @param mixed $id
* @return self
*/
public function setId($id);
/**
* @return PublisherInterface
*/
public function getPublisher();
/**
* @param PublisherInterface $publisher
* @return self
*/
public function setPublisher($publisher);
/**
* @return mixed
*/
public function getModule();
/**
* @param mixed $module
* @return self
*/
public function setModule($module);
/**
* @return mixed
*/
public function getBillingFactor();
/**
* @param mixed $billingFactor
* @return self
*/
public function setBillingFactor($billingFactor);
/**
* @return array
*/
public function getTiers();
/**
* @param array $tiers
* @return self
*/
public function setTiers($tiers);
/**
* get the CPM rate based on a given weight (slot opportunities, video impressions, visit etc )
* @param $weight
* @return float
*/
public function getCpmRate($weight);
/**
* @return mixed
*/
public function getDefaultConfig();
/**
* @param mixed $defaultConfig
* @return self
*/
public function setDefaultConfig($defaultConfig);
/**
* @return boolean
*/
public function isDefaultConfiguration();
} | true |
55f673d49b55348116310cb82992af97302d05f0 | PHP | maithemewp/mai-theme-engine | /lib/functions/helpers.php | UTF-8 | 20,859 | 2.734375 | 3 | [] | no_license | <?php
/**
* Helper function to get custom image sizes.
*
* @access private
* @since 1.8.0
*
* @return array Image sizes and labels.
*/
function mai_get_image_sizes() {
// Get labels.
$labels = mai_get_image_size_labels();
/**
* Create the initial image sizes.
* @link http://andrew.hedges.name/experiments/aspect_ratio/
*/
$image_sizes = array(
'banner' => array(
'label' => $labels[ 'banner' ],
'width' => 1600,
'height' => 533,
'crop' => true, // 3x1
),
'section' => array(
'label' => $labels[ 'section' ],
'width' => 1600,
'height' => 900,
'crop' => true, // 16x9
),
'full-width' => array(
'label' => $labels[ 'full-width' ],
'width' => 1248,
'height' => 832,
'crop' => true, // 3x2
),
'featured' => array(
'label' => $labels[ 'featured' ],
'width' => 800,
'height' => 600,
'crop' => true, // 4x3 (works better for no sidebar)
),
'one-half' => array(
'label' => $labels[ 'one-half' ],
'width' => 550,
'height' => 413,
'crop' => true, // 4x3
),
'one-third' => array(
'label' => $labels[ 'one-third' ],
'width' => 350,
'height' => 263,
'crop' => true, // 4x3
),
'one-fourth' => array(
'label' => $labels[ 'one-fourth' ],
'width' => 260,
'height' => 195,
'crop' => true, // 4x3
),
'tiny' => array(
'label' => $labels[ 'tiny' ],
'width' => 80,
'height' => 80,
'crop' => true, // square
),
);
/**
* Filter the image sizes to allow the theme to override.
*
* // Change the default Mai image sizes
* add_filter( 'mai_image_sizes', 'prefix_custom_image_sizes' );
* function prefix_custom_image_sizes( $image_sizes ) {
*
* // Change one-third image size
* $image_sizes['one-third'] = array(
* 'width' => 350,
* 'height' => 350,
* 'crop' => true,
* );
*
* // Change one-fourth image size
* $image_sizes['one-fourth'] = array(
* 'width' => 260,
* 'height' => 260,
* 'crop' => true,
* );
*
* return $image_sizes;
*
* }
*
*/
$image_sizes = apply_filters( 'mai_image_sizes', $image_sizes );
/**
* Make sure labels are added.
* 'mai_image_sizes' didn't have 'label' in the array prior to 1.8.0.
* This insures existing filters don't break.
*/
foreach( $image_sizes as $name => $values ) {
if ( ! isset( $values['label'] ) || empty( $values['label'] ) ) {
$image_sizes[ $name ]['label'] = $labels[ $name ];
}
}
return $image_sizes;
}
/**
* Get default image size labels.
*
* @access private
* @since 1.8.0
*
* @return array
*/
function mai_get_image_size_labels() {
return array(
'banner' => __( 'Banner', 'mai-theme-engine' ),
'section' => __( 'Section', 'mai-theme-engine' ),
'full-width' => __( 'Full Width', 'mai-theme-engine' ),
'featured' => __( 'Featured', 'mai-theme-engine' ),
'one-half' => __( 'One Half', 'mai-theme-engine' ),
'one-third' => __( 'One Third', 'mai-theme-engine' ),
'one-fourth' => __( 'One Fourth', 'mai-theme-engine' ),
'tiny' => __( 'Tiny', 'mai-theme-engine' ),
);
}
/**
* Utility method to get a combined list of default and custom registered image sizes.
* Originally taken from CMB2. Static variable added here.
*
* @since 1.11.0
* @link http://core.trac.wordpress.org/ticket/18947
* @global array $_wp_additional_image_sizes.
* @return array The image sizes.
*/
function mai_get_available_image_sizes() {
// Cache.
static $image_sizes = array();
if ( ! empty( $image_sizes ) ) {
return $image_sizes;
}
// Get image sizes.
global $_wp_additional_image_sizes;
$default_image_sizes = array( 'thumbnail', 'medium', 'large' );
foreach ( $default_image_sizes as $size ) {
$image_sizes[ $size ] = array(
'height' => intval( get_option( "{$size}_size_h" ) ),
'width' => intval( get_option( "{$size}_size_w" ) ),
'crop' => get_option( "{$size}_crop" ) ? get_option( "{$size}_crop" ) : false,
);
}
if ( isset( $_wp_additional_image_sizes ) && count( $_wp_additional_image_sizes ) ) {
$image_sizes = array_merge( $image_sizes, $_wp_additional_image_sizes );
}
return $image_sizes;
}
/**
* Get <picture> <sources> HTML.
*
* @version 0.2.0
* @since 1.11.0
*
* @param int The image ID.
* @param string The image size.
*
* @return string The <sources> HTML.
*/
function mai_get_picture_sources( $image_id, $image_size ) {
$sources = '';
$all_sizes = mai_get_available_image_sizes();
// Bail if no sizes.
if ( ! array( $all_sizes ) || empty( $all_sizes ) ) {
return $sources;
}
// Bail if the registered size is not found.
if ( ! isset( $all_sizes[ $image_size ] ) ) {
return $sources;
}
// Bail if not a cropped image size.
if ( ! $all_sizes[ $image_size ]['crop'] ) {
return $sources;
}
// Get picture sizes.
$picture_sizes = mai_get_picture_sizes( $image_size );
// Bail if no picture sizes.
if ( ! array( $picture_sizes ) || empty( $picture_sizes ) ) {
return $sources;
}
/**
* Get only sizes and values we need.
* Tonya says this is faster than array_intersect_key( $all_sizes, array_flip( $picture_sizes ) ).
*/
$sizes = array();
foreach ( $picture_sizes as $key ) {
if ( array_key_exists( $key, $all_sizes ) ) {
$sizes[ $key ] = $all_sizes[ $key ];
}
}
// Bail if no sizes.
if ( ! $sizes ) {
return $sources;
}
// Sort lowest to highest.
$sizes = wp_list_sort( $sizes, 'width', 'ASC', true );
// Loop through the sizes.
foreach( $sizes as $size => $values ) {
// Add the source.
$sources .= sprintf( '<source srcset="%s" media="(max-width: %spx)">', wp_get_attachment_image_url( $image_id, $size ), $values['width'] );
}
return $sources;
}
/**
* Get registered image sizes to be used for <sources> in <picture>.
*
* @since 1.11.0
*
* @param string The image size.
*
* @return array The registered image sizes.
*/
function mai_get_picture_sizes( $image_size ) {
switch ( $image_size ) {
case 'banner':
case 'section':
case 'full-width':
$picture_sizes = array( 'featured', 'one-half', 'one-third', 'one-fourth' );
break;
case 'featured':
$picture_sizes = array( 'one-half', 'one-third', 'one-fourth' );
break;
case 'one-half':
$picture_sizes = array( 'one-third', 'one-fourth' );
break;
case 'one-third':
$picture_sizes = array( 'one-fourth' );
break;
default:
$picture_sizes = array();
}
return apply_filters( 'mai_picture_sizes', $picture_sizes, $image_size );
}
/**
* Get the site layout.
*
* @access private
*
* @since 1.3.0
*
* @return string The site layout.
*/
function mai_get_layout() {
// Setup cache.
static $layout_cache = '';
// If cache is populated, return value.
if ( '' !== $layout_cache ) {
return esc_attr( $layout_cache );
}
$site_layout = '';
global $wp_query;
// If blog.
if ( is_home() ) {
if ( $page_for_posts = get_option( 'page_for_posts' ) ) {
$site_layout = genesis_get_custom_field( '_genesis_layout', $page_for_posts );
}
if ( ! $site_layout ) {
$site_layout = genesis_get_option( 'layout_archive' );
}
}
// If viewing a singular page, post, or CPT.
elseif ( is_singular() ) {
$site_layout = genesis_get_custom_field( '_genesis_layout', get_the_ID() );
if ( ! $site_layout ) {
$site_layout = genesis_get_option( sprintf( 'layout_%s', get_post_type() ) );
}
}
// If viewing a post taxonomy archive.
elseif ( is_category() || is_tag() || is_tax( get_object_taxonomies( 'post', 'names' ) ) ) {
$term = $wp_query->get_queried_object();
$site_layout = $term ? get_term_meta( $term->term_id, 'layout', true) : '';
$site_layout = $site_layout ? $site_layout : genesis_get_option( 'layout_archive' );
}
// If viewing a custom taxonomy archive.
elseif ( is_tax() ) {
$term = $wp_query->get_queried_object();
$site_layout = $term ? get_term_meta( $term->term_id, 'layout', true) : '';
if ( ! $site_layout ) {
$tax = get_taxonomy( $wp_query->get_queried_object()->taxonomy );
if ( $tax ) {
/**
* If we have a tax, get the first one.
* Changed to reset() when hit an error on a term archive that object_type array didn't start with [0]
*/
$post_type = reset( $tax->object_type );
// If we have a post type and it supports mai-cpt-settings.
if ( post_type_exists( $post_type ) && post_type_supports( $post_type, 'mai-cpt-settings' ) ) {
$site_layout = genesis_get_cpt_option( 'layout', $post_type );
}
}
}
$site_layout = $site_layout ? $site_layout : genesis_get_option( 'layout_archive' );
}
// If viewing a supported post type.
elseif ( is_post_type_archive() && post_type_supports( get_post_type(), 'mai-cpt-settings' ) ) {
// $site_layout = genesis_get_option( sprintf( 'layout_archive_%s', get_post_type() ) );
$site_layout = genesis_get_cpt_option( 'layout', get_post_type() );
$site_layout = $site_layout ? $site_layout : genesis_get_option( 'layout_archive' );
}
// If viewing an author archive.
elseif ( is_author() ) {
$site_layout = get_the_author_meta( 'layout', (int) get_query_var( 'author' ) );
$site_layout = $site_layout ? $site_layout : genesis_get_option( 'layout_archive' );
}
// If viewing date archive or search results.
elseif( is_date() || is_search() ) {
$site_layout = genesis_get_option( 'layout_archive' );
}
// Pull the theme option.
if ( ! $site_layout ) {
$site_layout = genesis_get_option( 'site_layout' );
}
// Use default layout as a fallback, if necessary.
if ( ! genesis_get_layout( $site_layout ) ) {
$site_layout = genesis_get_default_layout();
}
// Push layout into cache.
$layout_cache = $site_layout;
// Return site layout.
return esc_attr( $site_layout );
}
/**
* Check if viewing a content archive page.
* This is any archive page that may inherit (custom) archive settings.
*
* @return bool
*/
function mai_is_content_archive() {
global $wp_query;
if ( ! $wp_query->is_main_query() ) {
return false;
}
$is_archive = false;
// Blog.
if ( is_home() ) {
$is_archive = true;
}
// Term archive.
elseif ( is_category() || is_tag() || is_tax() ) {
$is_archive = true;
}
// CPT archive - this may be called too early to use get_post_type().
elseif ( is_post_type_archive() ) {
$is_archive = true;
}
// Author archive.
elseif ( is_author() ) {
$is_archive = true;
}
// Search results.
elseif ( is_search() ) {
$is_archive = true;
}
// Date archives.
elseif( is_date() ) {
$is_archive = true;
}
return $is_archive;
}
/**
* Check if banner area is enabled.
*
* Force this in a template via:
* add_filter( 'theme_mod_enable_banner_area', '__return_true' );
*
* First check global settings, then archive setting (if applicable), then immediate setting.
*
* @return bool
*/
function mai_is_banner_area_enabled() {
$enabled = true;
// If not enabled at all.
if ( ! mai_is_banner_area_enabled_globally() ) {
$enabled = false;
} else {
/**
* If disabled per post_type or taxonomy.
*/
// Singular page/post.
if ( is_singular( array( 'page', 'post' ) ) ) {
// Get 'disabled' post types, typecasted as array because it may return empty string if none
$disable_post_types = (array) genesis_get_option( 'banner_disable_post_types' );
if ( in_array( get_post_type(), $disable_post_types ) ) {
$enabled = false;
}
}
// Singular CPT.
elseif ( is_singular() ) {
$disable_post_type = (bool) genesis_get_option( sprintf( 'banner_disable_%s', get_post_type() ) );
if ( $disable_post_type ) {
$enabled = false;
}
}
// Post taxonomy archive.
elseif ( is_category() || is_tag() ) {
// Get 'disabled' taxonomies, typecasted as array because it may return empty string if none
$disable_taxonomies = (array) genesis_get_option( 'banner_disable_taxonomies' );
if ( $disable_taxonomies && in_array( get_queried_object()->taxonomy, $disable_taxonomies ) ) {
$enabled = false;
}
}
// Custom taxonomy archive.
elseif ( is_tax() ) {
$disable_taxonomies = (array) genesis_get_option( sprintf( 'banner_disable_taxonomies_%s', get_post_type() ) );
if ( $disable_taxonomies && in_array( get_queried_object()->taxonomy, $disable_taxonomies ) ) {
$enabled = false;
}
}
/**
* If still enabled,
* check on the single object level.
*
* These conditionals were mostly adopted from mai_get_archive_setting() function.
*/
if ( $enabled ) {
$hidden = false;
// If single post/page/cpt.
if ( is_singular() ) {
$hidden = get_post_meta( get_the_ID(), 'hide_banner', true );
}
// If content archive (the only other place we'd have this setting).
elseif ( mai_is_content_archive() ) {
// Get the setting directly, without fallbacks.
$hidden = mai_get_the_archive_setting( 'hide_banner' );
}
// If hidden, disable banner.
if ( $hidden ) {
$enabled = false;
}
}
}
return $enabled;
}
/**
* Get the banner image ID.
*
* First check immediate setting, then archive setting (if applicable), then fallback to default image.
*
* @return int|false
*/
function mai_get_banner_id() {
// Start of without an image
$image_id = false;
// Static front page
if ( is_front_page() && $front_page_id = get_option( 'page_on_front' ) ) {
$image_id = get_post_meta( $front_page_id, 'banner_id', true );
// If no image and featured images as banner is enabled
if ( ! $image_id && mai_is_banner_featured_image_enabled() ) {
$image_id = get_post_thumbnail_id( $front_page_id );
}
}
// Static blog page
elseif ( is_home() && $posts_page_id = get_option( 'page_for_posts' ) ) {
$image_id = get_post_meta( $posts_page_id, 'banner_id', true );
// If no image and featured images as banner is enabled
if ( ! $image_id && mai_is_banner_featured_image_enabled( $posts_page_id ) ) {
$image_id = get_post_thumbnail_id( $posts_page_id );
}
}
// Single page/post/cpt, but not static front page or static home page
elseif ( is_singular() ) {
$image_id = get_post_meta( get_the_ID(), 'banner_id', true );
// If no image and featured images as banner is enabled
if ( ! $image_id && mai_is_banner_featured_image_enabled( get_the_ID() ) ) {
$image_id = get_post_thumbnail_id( get_the_ID() );
}
// Fallback
if ( ! $image_id ) {
// Get the post's post_type
$post_type = get_post_type();
// Posts
if ( 'post' === $post_type && ( $posts_page_id = get_option( 'page_for_posts' ) ) ) {
$image_id = get_post_meta( $posts_page_id, 'banner_id', true );
}
// CPTs
elseif ( post_type_supports( $post_type, 'mai-cpt-settings' ) ) {
// if ( mai_is_banner_featured_image_enabled( get_the_ID() ) ) {
// $image_id = get_post_thumbnail_id( $posts_page_id );
// }
// $image_id = $image_id ? $image_id : genesis_get_cpt_option( 'banner_id', $post_type );
$image_id = genesis_get_cpt_option( 'banner_id', $post_type );
}
}
}
// Term archive
elseif ( is_category() || is_tag() || is_tax() ) {
// If WooCommerce product category
if ( class_exists( 'WooCommerce' ) && is_tax( array( 'product_cat', 'product_tag' ) ) && ( $image_id = get_term_meta( get_queried_object()->term_id, 'thumbnail_id', true ) ) ) {
// Woo uses it's own image field/key
$image_id = $image_id;
} else {
// $image_id = get_term_meta( get_queried_object()->term_id, 'banner_id', true );
$image_id = mai_get_archive_setting( 'banner_id', false, false );
}
}
// CPT archive
elseif ( is_post_type_archive() && post_type_supports( get_post_type(), 'mai-cpt-settings' ) ) {
$image_id = genesis_get_cpt_option( 'banner_id' );
}
// Author archive
elseif ( is_author() ) {
$image_id = get_the_author_meta( 'banner_id', get_query_var( 'author' ) );
}
/**
* If no banner, but we have a default,
* use the default banner image.
*/
if ( ! $image_id ) {
if ( $default_id = genesis_get_option( 'banner_id' ) ) {
$image_id = absint( $default_id );
}
}
// Filter so devs can force a specific image ID
$image_id = apply_filters( 'mai_banner_image_id', $image_id );
return $image_id;
}
/**
* Get the col span out of 12 column grid.
* If we want to show posts in 3 columns the size is 4 because 4 out of 12 is 1/3.
*
* @param int The amount of visual columns to display.
*
* @return int The column span out of 12.
*/
function mai_get_size_by_columns( $columns ) {
switch ( (int) $columns ) {
case 1:
$size = 12;
break;
case 2:
$size = 6;
break;
case 3:
$size = 4;
break;
case 4:
$size = 3;
break;
case 6:
$size = 2;
break;
default:
$size = 12;
}
return $size;
}
/**
* Get gutter size name from gutter value.
*
* @since 1.3.8
* @access private
*
* @param mixed Gutter value.
*
* @return string The gutter size.
*/
function mai_get_gutter_size( $gutter ) {
switch ( (string) $gutter ) {
case '0':
case 'none':
$size = '0';
break;
case '5':
case 'xxxs':
$size = 'xxxs';
break;
case '10':
case 'xxs':
$size = 'xxs';
break;
case 'xs':
$size = 'xs';
break;
case '20':
case 'sm':
$size = 'sm';
break;
case '30':
case 'md':
$size = 'md';
break;
case '40':
case 'lg':
$size = 'lg';
break;
case '50':
case 'xl':
$size = 'xl';
break;
case '50':
case 'xl':
$size = 'xl';
break;
case '60':
case 'xxl':
$size = 'xxl';
break;
$size = '0';
}
return $size;
}
/**
* Helper function to check if archive is a flex loop.
* This doesn't check if viewing an actual archive, but this layout should not be an option if ! is_archive()
*
* @return bool Whether the layout is a grid archive.
*/
function mai_is_flex_loop() {
// Bail if not a content archive.
if ( ! mai_is_content_archive() ) {
return false;
}
// Get columns.
$columns = mai_get_columns();
// If we have more than 1 column or if we are using featured image as bg image, it's a flex loop.
if ( ( $columns > 1 ) || ( 'background' === mai_get_archive_setting( 'image_location', true, genesis_get_option( 'image_location' ) ) ) ) {
return true;
}
// Not a flex loop.
return false;
}
function mai_is_no_sidebar() {
$layout = genesis_site_layout();
$no_sidebars = array(
'full-width-content',
'md-content',
'sm-content',
'xs-content',
);
if ( in_array( $layout, $no_sidebars ) ) {
return false;
}
return true;
}
function mai_is_admin_woo_shop_page() {
// False is Woo is not active.
if ( ! class_exists('WooCommerce') ) {
return false;
}
// False if not editing a page/post.
global $pagenow;
if ( 'post.php' != $pagenow ) {
return false;
}
// Get the ids.
$post_id = filter_input( INPUT_GET, 'post', FILTER_SANITIZE_NUMBER_INT );
$shop_page_id = get_option( 'woocommerce_shop_page_id' );
// If WooCommerce shop page
if ( $post_id == $shop_page_id ) {
return true;
}
// Nope.
return false;
}
/**
* Filter the CPT's that get archive settings.
* Add via:
* $post_types['cpt_name'] = get_post_type_object( 'cpt_name' );
*
* Remove via:
* unset( $post_types['cpt_name'] );
*
* @return array key = post type name and value = post type object.
*/
function mai_get_cpt_settings_post_types() {
return apply_filters( 'mai_cpt_settings_post_types', genesis_get_cpt_archive_types() );
}
function mai_sections_has_h1( $post_id ) {
// Get the sections.
$sections = get_post_meta( $post_id, 'mai_sections', true );
// No sections.
if ( ! $sections ) {
return false;
}
// No title yet.
$has_h1 = false;
// Loop through each section.
foreach ( (array) $sections as $section ) {
// If content isset. Sometimes empty content doesn't even save the key.
if ( isset( $section['content'] ) ) {
// If content contains an h1.
if ( false !== strpos( $section['content'], '</h1>' ) ) {
$has_h1 = true;
break;
}
}
}
return $has_h1;
}
function mai_sections_has_title( $post_id ) {
// Get the sections.
$sections = get_post_meta( $post_id, 'mai_sections', true );
// No sections.
if ( ! $sections ) {
return false;
}
// No title yet.
$has_title = false;
// Loop through each section.
foreach ( (array) $sections as $section ) {
// Skip if no title.
if ( empty( $section['title'] ) ) {
continue;
}
// We have a title, change variable and break the loop.
$has_title = true;
break;
}
return $has_title;
}
function mai_has_shrink_header() {
$header_style = genesis_get_option( 'header_style' );
if ( ! $header_style ) {
return false;
}
if ( ! in_array( $header_style, array( 'sticky_shink', 'reveal_shrink' ) ) ) {
return false;
}
return true;
}
function mai_has_scroll_header() {
$header_style = genesis_get_option( 'header_style' );
return ( $header_style && in_array( $header_style, array( 'sticky', 'reveal', 'sticky_shrink', 'reveal_shrink' ) ) );
}
| true |
6e38bb848b56933340a6fe7e4ec3d95869833838 | PHP | goreilly/web-connector | /src/Tests/TaskQueueTest.php | UTF-8 | 2,086 | 2.609375 | 3 | [
"Apache-2.0"
] | permissive | <?php
namespace goreilly\WebConnector\Tests;
use goreilly\WebConnector\TaskInterface;
use goreilly\WebConnector\TaskQueue;
class TaskQueueTest extends \PHPUnit_Framework_TestCase
{
/**
* @return TestTask
*/
protected function getTask()
{
return new TestTask();
}
public function testCount()
{
$queue = new TaskQueue();
$this->assertEquals(0, $queue->count());
$queue->pop();
$this->assertEquals(0, $queue->count());
$task = $this->getTask();
$queue->add($task);
$this->assertEquals(1, $queue->count());
$queue->add($task);
$this->assertEquals(2, $queue->count());
$queue->pop();
$this->assertEquals(1, $queue->count());
}
public function testGetMax()
{
$queue = new TaskQueue();
$task = $this->getTask();
$max = 10;
for ($i = 0; $i < $max; $i++) {
$queue->add($task);
}
$queue->pop();
$queue->pop();
$queue->pop();
$queue->pop();
$this->assertEquals($max, $queue->getMax());
}
public function testPop()
{
/** @var TaskInterface[] $tasks */
$tasks = [
$this->getTask(),
$this->getTask(),
$this->getTask(),
$this->getTask(),
$this->getTask(),
];
$queue = new TaskQueue();
foreach ($tasks as $task) {
$queue->add($task);
}
foreach ($tasks as $task) {
$this->assertEquals($task, $queue->pop());
}
}
public function testAdd()
{
$queue = new TaskQueue();
$task = $this->getTask();
$queue->add($task);
$this->assertEquals($task, $queue->pop());
}
public function testSerialize()
{
$queue = new TaskQueue();
$task = $this->getTask();
$queue->add($task);
$serialized = serialize($queue);
$copy = unserialize($serialized);
$this->assertEquals($copy, $queue);
}
}
| true |
267342c9cb976a50f2ad3d312f8ecbf984de3c6d | PHP | martin-helmich/typo3-web2pdf | /Classes/View/PdfView.php | UTF-8 | 4,765 | 2.71875 | 3 | [] | no_license | <?php
/* * *************************************************************
* Copyright notice
*
* (c) 2014 Kevin Purrmann <entwicklung@purrmann-websolutions.de>
*
* All rights reserved
*
* This script is part of the TYPO3 project. The TYPO3 project is
* free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* The GNU General Public License can be found at
* http://www.gnu.org/copyleft/gpl.html.
*
* This script is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* This copyright notice MUST APPEAR in all copies of the script!
* ************************************************************* */
namespace Mittwald\Web2pdf\View;
use TYPO3\CMS\Core\Utility\GeneralUtility;
/**
* PDFView
*
* @author Kevin Purrmann <entwicklung@purrmann-websolutions.de>, Purrmann Websolutions
* @package Mittwald
* @subpackage Web2Pdf\View
*/
class PdfView {
const PREG_REPLACEMENT_KEY = 'pregReplacements';
const STR_REPLACEMENT_KEY = 'strReplacements';
/**
* @var \Mittwald\Web2pdf\Options\ModuleOptions
* @inject
*/
protected $options;
/**
* @var \Mittwald\Web2pdf\Utility\FilenameUtility
* @inject
*/
protected $fileNameUtility;
/**
* @var \TYPO3\CMS\Extbase\Object\ObjectManagerInterface
*/
protected $objectManager;
/**
* @throws \InvalidArgumentException
*/
public function __construct() {
$this->objectManager = GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');
}
/**
* Renders the view
*
* @param string $content The HTML Code to convert
* @param string $pageTitle
* @return \TYPO3\CMS\Extbase\Mvc\Web\Response The rendered view
*/
public function renderHtmlOutput($content, $pageTitle) {
$fileName = $this->fileNameUtility->convert($pageTitle) . '.pdf';
$filePath = GeneralUtility::getFileAbsFileName('typo3temp/' . $fileName);
$content = $this->replaceStrings($content);
$pdf = $this->getPdfObject();
$pdf->WriteHTML($content);
$pdf->Output($filePath, 'F');
header('Content-Description: File Transfer');
header('Content-Transfer-Encoding: binary');
header('Cache-Control: public, must-revalidate, max-age=0');
header('Pragma: public');
header('Expires: 0');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Content-Type: application/pdf', false);
header('Content-Disposition: attachment; filename="' . $this->fileNameUtility->convert($pageTitle) . '.pdf' . '"');
readfile($filePath);
unlink($filePath);
exit;
}
/**
* Replacements of configured strings
*
* @param $content
* @return string
*/
private function replaceStrings($content) {
if (is_array($this->options->getStrReplacements())) {
foreach ($this->options->getStrReplacements() as $searchString => $replacement) {
$content = str_replace($searchString, $replacement, $content);
}
}
if (is_array($this->options->getPregReplacements())) {
foreach ($this->options->getPregReplacements() as $pattern => $patternReplacement) {
$content = preg_replace($pattern, $patternReplacement, $content);
}
}
return $content;
}
/**
* Returns configured mPDF object
*
* @return \mPDF
*/
protected function getPdfObject() {
// Get options from TypoScript
$pageFormat = ($this->options->getPdfPageFormat()) ? $this->options->getPdfPageFormat() : 'A4';
$pageOrientation = ($orientation = $this->options->getPdfPageOrientation()) ? $orientation : 'L';
$leftMargin = ($this->options->getPdfLeftMargin()) ? $this->options->getPdfLeftMargin() : '15';
$rightMargin = ($this->options->getPdfRightMargin()) ? $this->options->getPdfRightMargin() : '15';
$topMargin = ($this->options->getPdfTopMargin()) ? $this->options->getPdfTopMargin() : '15';
$styleSheet = ($this->options->getPdfStyleSheet()) ? $this->options->getPdfStyleSheet() : 'print';
/* @var $pdf \mPDF */
$pdf = $this->objectManager->get('mPDF', '', $pageFormat . '-' . $pageOrientation);
$pdf->SetMargins($leftMargin, $rightMargin, $topMargin);
$pdf->CSSselectMedia = $styleSheet;
$pdf->AddPage();
return $pdf;
}
} | true |
cfdd1b94b700d1da83beed06997e0b75d3bc7782 | PHP | akimxtreme/inhrrOldWebsite | /catinhrr/conexion_fns.php | UTF-8 | 566 | 2.53125 | 3 | [] | no_license | <!--CONECTOR-->
<?php
function ConectarBD(){
return mysql_connect("172.16.0.10","acruz","10485");
}
?>
<!--EJECUTAR EXEC-->
<?php
function EjecuteExec1($cx,$sql){
mysql_select_db("bdcatinhrr",$cx);
return mysql_query($sql,$cx);
}
?>
<!--EJECUTAR FETCH-->
<?php
function ObtenerFila($cx){
return mysql_fetch_row($cx);
}
?>
<!--NUMERO DE FILAS-->
<?php
function NumFila($cx){
return mysql_num_rows($cx);
}
?>
<!--OBTENER RESULTADO-->
<?php
function ObResultado($cx,$campo,$fila){
return mysql_result($cx,$campo,$fila);
}
?> | true |
06cf93922f186c22184f4bb1f7fcd8eeb727479b | PHP | meeech/expozine | /controllers/components/tidize.php | UTF-8 | 938 | 2.78125 | 3 | [] | no_license | <?php
/**
* Tidize
*
* Component to generate new ids for a model.
* usually useful with importing old data
*
* @package default
* @author Mitchell Amihod
*/
class TidizeComponent extends Object {
/**
* Generate uuid for the field on the originals.
*
* @return void
**/
function tidize($modelName) {
$Model = ClassRegistry::init($modelName);
$Model->recursive = -1;
//Find all, even the stuff that might only be in draft.
$results = $Model->find('all', array(
'fields' => 'id',
'group' => $modelName.'.id'
));
foreach ($results as $item) {
$id = $item[$modelName]['id'];
$translation_id = String::uuid();
$Model->updateAll(
array($modelName.'.id' => "'{$translation_id}'"),
array($modelName.'.id' => $id)
);
}
return true;
}
} | true |
73b834ef4b75bec644bb9a9fa5632f6aafc6f458 | PHP | herrwalter/InterfaceGenerator | /InterfaceObject/PHPInterfaceObject.php | UTF-8 | 474 | 3.125 | 3 | [] | no_license | <?php
/*
* SetlistGenerator project
* @author Wouter Wessendorp
*
*/
class PHPInterfaceObject extends AInterfaceObject {
public function toString() {
$interface = '<?php ' . PHP_EOL;
$interface .= 'interface ' .$this->getName() . ' {' . PHP_EOL . PHP_EOL;
foreach($this->methods as $method){
$interface .= $method->toString();
$interface .= PHP_EOL;
}
$interface .= '}';
return $interface;
}
}
| true |
2614c16313325b77b881bc8dd9bae826bc5b1f5a | PHP | dbierer/php-ii-jun-2021 | /pdo_with_opts.php | UTF-8 | 544 | 2.765625 | 3 | [] | no_license | <?php
$dsn = 'mysql:dbname=phpcourse;host=localhost';
$usr = 'vagrant';
$pwd = 'vagrant';
$opts = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION];
try {
$pdo = new PDO($dsn, $usr, $pwd, $opts);
$result = $pdo->query('SELECT * FROM customers AS c JOIN orders AS o ON c.id = o.customer');
$result->setFetchMode(PDO::FETCH_CLASS, 'ArrayObject');
$total = $result->rowCount();
echo "Total of $total hits were received\n";
if ($total) {
while ($row = $result->fetch())
var_dump($row);
}
} catch (Throwable $t) {
echo $t;
}
echo "\n";
| true |
ecab93921d83a3bc71e2db7f88a824fb65e50102 | PHP | Linkunder/Infosport | /TO/TipoRecinto.php | UTF-8 | 449 | 2.53125 | 3 | [] | no_license | <?php
class TipoRecinto {
private $id_Recinto;
private $id_Categoria;
function __construct(){}
function getId_Recinto() {
return $this->id_Recinto;
}
function getId_Categoria() {
return $this->id_Categoria;
}
function setId_Recinto($id_Recinto) {
$this->id_Recinto = $id_Recinto;
}
function setId_Categoria($id_Categoria) {
$this->id_Categoria = $id_Categoria;
}
}
?> | true |
adcfc9242cac8ba78634d2e8b6dc6893c3d2ad3a | PHP | jbidjeke/zend_expressive | /src/App/Action/AdvertAction.php | UTF-8 | 1,231 | 2.53125 | 3 | [] | no_license | <?php
namespace App\Action;
use Psr\Http\Message\ResponseInterface;
use Interop\Container;
use Psr\Http\Message\ServerRequestInterface;
use Zend\Diactoros\Response\JsonResponse;
use Zend\Expressive\Router;
use Zend\Expressive\Template;
use App\Model\Adverts;
class AdvertAction
{
private $router;
private $template;
private $config;
public function __construct(ArrayObject $config, Router\RouterInterface $router, Template\TemplateRendererInterface $template = null)
{
$this->router = $router;
$this->template = $template;
$this->config = $config;
}
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null)
{
$parram = $request->getQueryParams();
$adverts = new Adverts($this->config);
$adverts->lat = $parram['lat'] ?? 48.451580799999995;
$adverts->lng = $parram['lng'] ?? 6.744914999999992;
$adverts->category = $parram['category'] ?? 'annonces';
$adverts->distance = $parram['distance'] ?? 5000;
$adverts->q = $parram['q'] ?? "";
$adverts->getAround();
$adverts->toArray();
return new JsonResponse($adverts->resultDb, 200, ['Access-Control-Allow-Origin' => '*']);
}
}
| true |
e5648a5a7096b63769895e180a8881830ae69e04 | PHP | penguizz/invoice | /database/migrations/2017_07_12_074159_po_detail.php | UTF-8 | 872 | 2.546875 | 3 | [
"MIT"
] | permissive | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class PoDetail extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('po_details', function (Blueprint $table) {
$table->increments('po_detail_id');
$table->integer('po_id');
$table->string('po_detail_part_no');
$table->string('po_description');
$table->integer('po_quantity');
$table->decimal('po_unit_price',10,2);
$table->decimal('po_amount',10,2);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('po_detail');
}
}
| true |
4e23a4a9de32fd9ae7218ae66572e541c0e90896 | PHP | php-ddd/notification | /tests/ErrorTest.php | UTF-8 | 678 | 2.6875 | 3 | [
"MIT"
] | permissive | <?php
namespace PhpDDD\Notification;
use Exception;
use PHPUnit_Framework_TestCase;
class ErrorTest extends PHPUnit_Framework_TestCase
{
/**
* @expectedException InvalidArgumentException
*/
public function testIntegerThrowException()
{
new Error(100);
}
/**
* @expectedException InvalidArgumentException
*/
public function testExceptionThrowException()
{
new Error(new Exception());
}
public function testValidMessage()
{
$errorMessage = 'This is an error message';
$error = new Error($errorMessage);
$this->assertEquals($errorMessage, $error->getMessage());
}
}
| true |