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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
89ab9a6ac52c05c86a07ae18aa3924fb4183e12a | PHP | mvenkat777/server-api | /se/Collab/Commands/ShareMessageCommand.php | UTF-8 | 639 | 3 | 3 | [] | no_license | <?php
namespace Platform\Collab\Commands;
/**
* To share a message with another user
*/
class ShareMessageCommand
{
/**
* Chat Id
* @var number chatId
*/
public $chatId;
/**
* Message Id
* @var number messageId
*/
public $messageId;
/**
* Share Id
* @var number shareId
*/
public $shareId;
/**
* Person with whom shared chat id
* @var number convIdOfSharedUser
*/
public $convIdOfSharedUser;
function __construct($data)
{
$this->chatId = $data['chatId'];
$this->messageId = $data['messageId'];
$this->shareId = $data['shareWith'];
$this->convIdOfSharedUser = $data['convIdOfSharedUser'];
}
} | true |
7b6668333e5752fcee013685a460e0415f78304b | PHP | liu-jack/tcht | /logic/core/function.inc.php | UTF-8 | 748 | 2.53125 | 3 | [] | no_license | <?php
function __autoload($classname){
if(!strstr($classname,'auto')){
return true;
}
if(is_file(AClass.$classname.'.class.php')){
require_once(AClass.$classname.'.class.php');
if (!class_exists($classname, false)) {
common::printlog($classname.'Class not found');
}
}else{
common::printlog('./class in this dir can not find file :'.$classname.'.class.php');
}
}
function D($db){
$obj = new DB($db,HOST,USER,PASS,PORT);
return $obj;
}
//拓展数据库功能
function F($db,$h,$u,$p,$port=3306){
$obj = new DB($db,$h,$u,$p,$port);
return $obj;
}
function DF($config=array()){
if (empty($config)){
return false;
}
return new DB($config['db'],$config['ip'],$config['user'],$config['password'],$config['port']);
}
?> | true |
6f42add2772be2d727370d7f7b2c2fe7c9f14b94 | PHP | megaps29/Tugas-3 | /index.php | UTF-8 | 773 | 2.78125 | 3 | [] | no_license | <?php
//membuat koneksi ke database
$host = 'localhost';
$user = 'root';
$password = '';
$database = 'akademik';
$konek_db = mysql_connect($host, $user, $password);
$find_db = mysql_select_db($database) ;
?>
<center>
DATA MAHASISWA
<br>
<br>
<?php
// Perintah untuk menampilkan data
$queri="Select * From mahasiswa" ; //menampikan SEMUA data dari tabel siswa
$hasil=MySQL_query ($queri); //fungsi untuk SQL
// perintah untuk membaca dan mengambil data dalam bentuk array
while ($data = mysql_fetch_array ($hasil)){
$id = $data['nim'];
$myArr = array($data['nim'], $data['nama'], $data['alamat'], $data['progdi']);
$myJSON = json_encode($myArr);
echo $myJSON;
}
?>
</table> | true |
74dc525b2d0ce32e32fb3c04883ab85036dc0710 | PHP | viktortat/senao_design_pattern | /src/Decorator/Order.php | UTF-8 | 759 | 3.25 | 3 | [] | no_license | <?php
declare(strict_types=1);
namespace App\Decorator;
/**
* Class Order
* @package App\Decorator
*/
final class Order
{
/** @var int */
private $totalPrice;
/** @var array */
private $events;
/**
* @return int
*/
public function getTotalPrice(): int
{
return $this->totalPrice;
}
/**
* @param int $totalPrice
*/
public function setTotalPrice(int $totalPrice): void
{
$this->totalPrice = $totalPrice;
}
/**
* @return array
*/
public function getEvents(): array
{
return $this->events;
}
/**
* @param array $events
*/
public function setEvents(array $events): void
{
$this->events = $events;
}
}
| true |
2ab061a7a4be0ee852da10a2a2f95062dcf31e22 | PHP | BarashKa01/blog_playground | /app/Database/MySqlDatabase.php | UTF-8 | 1,800 | 3.234375 | 3 | [] | no_license | <?php
namespace App\Database;
use \PDO;
class MySqlDatabase extends Database {
private $db_name;
private $db_host;
private $db_username;
private $db_pass;
private $pdo;
public function __construct($db_name, $db_host, $db_username, $db_pass)
{
$this->db_name = $db_name;
$this->db_host = $db_host;
$this->db_username = $db_username;
$this->db_pass = $db_pass;
}
private function getPDO(){
if($this->pdo === null){
if ( $this->db_name != null && $this->db_host != null && $this->db_username != null){
$pdo = new PDO('mysql:dbname='.$this->db_name.';host='.$this->db_host, $this->db_username, $this->db_pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //Verbose mode
$this->pdo = $pdo;
}else{
echo("Can't connect to the database, please review your configuration");
return;
}
}
return $this->pdo;
}
public function query($statement, $className = null, $only_one = false){
$qry = $this->getPDO()->query($statement);
if($className === null){
$qry->setFetchMode(PDO::FETCH_OBJ);
}else{
$qry->setFetchMode(PDO::FETCH_CLASS, $className);
}
if ($only_one){
$datas = $qry->fetch();
}else{
$datas = $qry->fetchAll();
}
return $datas;
}
public function prepare($statement, $attr, $className, $only_one = false){
$request = $this->getPDO()->prepare($statement);
if($request->execute($attr)){
$request->setFetchMode(PDO::FETCH_CLASS, $className);
if ($only_one){
$datas = $request->fetch();
}else{
$datas = $request->fetchAll();
}
return $datas;
}
}
} | true |
08d642d31a024cd83c19b2efae27a82967adeab8 | PHP | XarigamiND/xarigami-modules-articles | /xaruserapi/getpubcatcount.php | UTF-8 | 3,178 | 2.625 | 3 | [] | no_license | <?php
/**
* Articles module
*
* @package modules
* @copyright (C) 2002-2007 The Digital Development Foundation
* @license GPL {@link http://www.gnu.org/licenses/gpl.html}
* @link http://www.xaraya.com
*
* @subpackage Articles Module
* @link http://xaraya.com/index.php/release/151.html
* @author mikespub
*/
/**
* get the number of articles per publication type and category
*
* @param $args['status'] array of requested status(es) for the articles
* @param $args['ptid'] publication type ID
* @param $args['cids'] array of category IDs (OR/AND)
* @param $args['andcids'] true means AND-ing categories listed in cids
* @param $args['groupcids'] the number of categories you want items grouped by
* @param $args['reverse'] default is ptid => cid, reverse (1) is cid => ptid
* @return array array( $ptid => array( $cid => $count) ),
* or false on failure
*/
function articles_userapi_getpubcatcount($args)
{
/*
static $pubcatcount = array();
if (count($pubcatcount) > 0) {
return $pubcatcount;
}
*/
$pubcatcount = array();
// Get database setup
$dbconn = xarDBGetConn();
// Get the LEFT JOIN ... ON ... and WHERE parts from articles
$articlesdef = xarModAPIFunc('articles','user','leftjoin',$args);
// Load API
if (!xarModAPILoad('categories', 'user')) return;
$args['modid'] = xarModGetIDFromName('articles');
if (isset($args['ptid']) && !isset($args['itemtype'])) {
$args['itemtype'] = $args['ptid'];
}
// Get the LEFT JOIN ... ON ... and WHERE parts from categories
$categoriesdef = xarModAPIFunc('categories','user','leftjoin',$args);
// Get count
$query = 'SELECT '. $articlesdef['pubtypeid'] .', '. $categoriesdef['cid']
.', COUNT(*)
FROM '. $articlesdef['table'] . '
LEFT JOIN ' . $categoriesdef['table'] .'
ON '. $categoriesdef['field'] . ' = ' . $articlesdef['field'] .
$categoriesdef['more'] . '
WHERE '. $categoriesdef['where'] .' AND '. $articlesdef['where'] .'
GROUP BY '. $articlesdef['pubtypeid'] .', '. $categoriesdef['cid'];
$result = $dbconn->Execute($query);
if (!$result) return;
if ($result->EOF) {
if (!empty($args['ptid']) && empty($args['reverse'])) {
$pubcatcount[$args['ptid']] = array();
}
return $pubcatcount;
}
while (!$result->EOF) {
// we may have 1 or more cid fields here, depending on what we're
// counting (cfr. AND in categories)
$fields = $result->fields;
$ptid = array_shift($fields);
$count = array_pop($fields);
// TODO: use multi-level array for multi-category grouping ?
$cid = join('+',$fields);
if (empty($args['reverse'])) {
$pubcatcount[$ptid][$cid] = $count;
} else {
$pubcatcount[$cid][$ptid] = $count;
}
$result->MoveNext();
}
foreach ($pubcatcount as $id1 => $val) {
$total = 0;
foreach ($val as $id2 => $count) {
$total += $count;
}
$pubcatcount[$id1]['total'] = $total;
}
return $pubcatcount;
}
?>
| true |
6b10559a2334ecf591ae7d99158fa8481674bf97 | PHP | wahyu28/mahasiswa | /modul/nilai/matkul.php | UTF-8 | 724 | 2.515625 | 3 | [] | no_license | <?php
$mysqli = new mysqli('localhost','root','','mahasiswa');
$nip = $_POST['nip'];
$sql = $mysqli->query("SELECT tb_matakuliah.kode_matkul, tb_matakuliah.matakuliah,tb_matakuliah.kode_matkul, tb_jadwal.nip FROM tb_jadwal, tb_matakuliah WHERE tb_jadwal.matakuliah=tb_matakuliah.kode_matkul and tb_jadwal.nip = '$nip'");
// $sql = $mysqli->query("SELECT * FROM tb_jadwal WHERE nip = '$nip'");
$cek = $sql->num_rows;
if ($cek == 0) {
echo "<option value=''>Matakuliah tidak tersedia</option>";
}else{
echo "<option disabled selected >Pilih Salah satu</option>";
while($row = $sql->fetch_assoc()){
echo "<option value='".$row['kode_matkul']."'>".$row['kode_matkul']." | ".$row['matakuliah']."</option>";
}
}
?> | true |
c1180f378bade09daff870ec78ff2e02bda9f94e | PHP | darochafernandesbismarque/prova-satollo | /library/Consulta.php | UTF-8 | 313 | 2.65625 | 3 | [] | no_license | <?php
error_reporting(E_ALL);
include "Conexao.php";
class Consulta
{
public static function consultar($sql)
{
$conexao = Conexao::conectar();
$stmt = $conexao->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
}
| true |
b8d18b486bbb93b6e15e525b7641921490f4e73c | PHP | Dragonqos/wholesale | /src/Processor/PriceStrategy/PriceStrategyInterface.php | UTF-8 | 267 | 3 | 3 | [] | no_license | <?php
namespace App\Processor\PriceStrategy;
interface PriceStrategyInterface
{
/**
* @param float $sellerCost
* @param float $retailPrice
*
* @return float
*/
public function process(float $sellerCost, float $retailPrice): float;
} | true |
5c449e9340610d1a096c45934e86132e4b9c5102 | PHP | AditiShree22/Clues_Commute | /commute/fetchForPassenger.php | UTF-8 | 1,100 | 2.6875 | 3 | [] | no_license | <?php
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
// json response array
$response = array("error" => FALSE);
if (isset($_GET['employee_id'])){
$employee_id = $_GET['employee_id'];
$passengerArray = $db->fetchForPassengers($route);
$number = count($passengerArray);
if ($passengerArray != false) {
$response["error"] = FALSE;
for ($i=0; $i< $number; $i++){
$response["route"][$i]= array("driver_id"=>$passengerArray[$i][0],"current_latitude"=>$passengerArray[$i][1],"current_longitude"=>$passengerArray[$i][2]);
}
echo json_encode($response);die;
}
else {
// user is not found with the credentials
$response["error"] = TRUE;
$response["error_msg"] = "Route not correct. Please try again!";
echo json_encode($response);
}
}
else {
// required post params is missing
$response["error"] = TRUE;
$response["error_msg"] = "Required parameter is missing!";
echo json_encode($response);
}
?>
| true |
7232d044fd556491bc27b99824e7fa214b28ca85 | PHP | aladrach/Bluefoot-Craft-Starter | /craft/plugins/market/services/Market_ShippingMethodService.php | UTF-8 | 5,285 | 2.578125 | 3 | [] | no_license | <?php
namespace Craft;
use Market\Helpers\MarketDbHelper;
/**
* Class Market_ShippingMethodService
*
* @author Pixel & Tonic, Inc. <support@pixelandtonic.com>
* @copyright Copyright (c) 2015, Pixel & Tonic, Inc.
* @license http://buildwithcraft.com/license Craft License Agreement
* @see http://buildwithcraft.com/commerce
* @package craft.plugins.commerce.services
* @since 1.0
*/
class Market_ShippingMethodService extends BaseApplicationComponent
{
/**
* @param int $id
*
* @return Market_ShippingMethodModel
*/
public function getById($id)
{
$record = Market_ShippingMethodRecord::model()->findById($id);
return Market_ShippingMethodModel::populateModel($record);
}
/**
* Gets the default method or first available if no default set.
*/
public function getDefault()
{
$method = Market_ShippingMethodRecord::model()->findByAttributes(['default'=>true]);
if (!$method){
$records = $this->getAll();
if(!$records){
throw new Exception(Craft::t('You have no Shipping Methods set up.'));
}
return $records[0];
}
return $method;
}
/**
* @return bool
*/
public function exists()
{
return Market_ShippingMethodRecord::model()->exists();
}
/**
* @param Market_OrderModel $cart
*
* @return array
*/
public function calculateForCart(Market_OrderModel $cart)
{
$availableMethods = [];
$methods = $this->getAll(['with'=>'rules']);
foreach ($methods as $method) {
if($method->enabled) {
if ($rule = $this->getMatchingRule($cart, $method)) {
$amount = $rule->baseRate;
$amount += $rule->perItemRate * $cart->totalQty;
$amount += $rule->weightRate * $cart->totalWeight;
$amount += $rule->percentageRate * $cart->itemTotal;
$amount = max($amount, $rule->minRate * 1);
if ($rule->maxRate * 1) {
$amount = min($amount, $rule->maxRate * 1);
}
$availableMethods[$method->id] = [
'name' => $method->name,
'amount' => $amount,
];
}
}
}
return $availableMethods;
}
/**
* @param array|\CDbCriteria $criteria
*
* @return Market_ShippingMethodModel[]
*/
public function getAll($criteria = [])
{
$records = Market_ShippingMethodRecord::model()->findAll($criteria);
return Market_ShippingMethodModel::populateModels($records);
}
/**
* @param Market_OrderModel $order
* @param Market_ShippingMethodModel $method
*
* @return bool|Market_ShippingRuleModel
*/
public function getMatchingRule(
Market_OrderModel $order,
Market_ShippingMethodModel $method
) {
foreach ($method->rules as $rule) {
if (craft()->market_shippingRule->matchOrder($rule, $order)) {
return $rule;
}
}
return false;
}
/**
* @param Market_ShippingMethodModel $model
*
* @return bool
* @throws \Exception
*/
public function save(Market_ShippingMethodModel $model)
{
if ($model->id) {
$record = Market_ShippingMethodRecord::model()->findById($model->id);
if (!$record) {
throw new Exception(Craft::t('No shipping method exists with the ID “{id}”',
['id' => $model->id]));
}
} else {
$record = new Market_ShippingMethodRecord();
}
$record->name = $model->name;
$record->enabled = $model->enabled;
$record->default = $model->default;
$record->validate();
$model->addErrors($record->getErrors());
if (!$model->hasErrors()) {
// Save it!
$record->save(false);
// Now that we have a record ID, save it on the model
$model->id = $record->id;
//If this was the default make all others not the default.
if ($model->default) {
Market_ShippingMethodRecord::model()->updateAll(['default' => 0],
'id != ?', [$record->id]);
}
return true;
} else {
return false;
}
}
public function delete($model)
{
// Delete all rules first.
MarketDbHelper::beginStackedTransaction();
try{
$rules = craft()->market_shippingRule->getAllByMethodId($model->id);
foreach($rules as $rule){
craft()->market_shippingRule->deleteById($rule->id);
}
Market_ShippingMethodRecord::model()->deleteByPk($model->id);
MarketDbHelper::commitStackedTransaction();
return true;
} catch (\Exception $e) {
MarketDbHelper::rollbackStackedTransaction();
return false;
}
MarketDbHelper::rollbackStackedTransaction();
return false;
}
} | true |
f015887ce193dd4ae35d18740ba4372ffb92520a | PHP | metafework/homework4 | /analyze.php | UTF-8 | 720 | 3.453125 | 3 | [] | no_license | <!DOCTYPE html>
<html>
<head>Text Analysis/ File management</head>
<body>
<br>
<?php
$inputFile=fopen("input.txt","r");
$fileContentString= fread($inputFile,filesize("input.txt")) or die("Cannot find input file.");
$wordArray= explode (",", $fileContentString);
/*foreach ($wordArray as $key => $word) {
echo $word;
}*/
$wordAssArray=array();
$count=0;
foreach ($wordArray as $word){
$count+=1;
if (array_key_exists("$word",$wordAssArray)){
$wordAssArray["$word"]+= 1;
}else{
$wordAssArray["$word"] = 1;
}
}
ksort($wordAssArray);
foreach ($wordAssArray as $word => $freq) {
echo $word, " : ", $freq," : ", number_format((($freq/sizeof($wordAssArray))*100),2),"%", "<br>" ;
}
?>
</body>
</html>
| true |
390ab8bae6d2b3a930829d54bd4c76a97ae4fbff | PHP | WebCF2m2017/RevisionMVC | /c/adminController.php | UTF-8 | 4,510 | 2.765625 | 3 | [] | no_license | <?php
// on est connecté en tant qu'admin
// dépendances pour le CRUD des tableaux
require_once 'm/Tableau.class.php';
require_once 'm/TableauManager.class.php';
require_once 'm/Artiste.class.php';
require_once 'm/ArtisteManager.class.php';
require_once 'm/Pagination.class.php';
$manageArtiste = new ArtisteManager($connect);
$manageTableau = new TableauManager($connect);
// appel des dépendances twig
$loader = new Twig_Loader_Filesystem('v/twig'); // chemin vers nos templates
$twig = new Twig_Environment($loader, array(
'debug' => true)); // charhement d'un environement de template
$twig->addExtension(new Twig_Extension_Debug());
// on veut se déconnecter
if (isset($_GET['deco'])) {
// destruction complète de session
$_SESSION = array();
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000, $params["path"], $params["domain"], $params["secure"], $params["httponly"]
);
}
session_destroy();
// redirection
header("Location: ./");
}elseif(isset($_GET['insert'])){
if(empty($_POST)){
// on récupère les artistes pour le formulaire
$artistes = $manageArtiste->listeArtiste();
// Appel de la vue
echo $twig->render("insert.html.twig",array("listeArtistes"=>$artistes));
}else{
$tableau = new Tableau($_POST);
// var_dump ($tableau);
// insertion dans la db
$insert = $manageTableau->insertTab($tableau);
// si l'insertion est réussie
if($insert){
// redirection vers l'accueil
header("Location: ./");
}else{
// erreur et lien de redirection
echo "<h3 onclick='history.go(-1)'>Erreur lors de l'insertion, vérifiez tous les champs!<br/><button>Complétez le formulaire</button></h3>";
}
}
// si on veut updater un tableau
}elseif(isset($_GET['updatetab'])&& ctype_digit($_GET['updatetab'])){
// si on a envoyé le formulaire
if(!empty($_POST)){
// si on a pas chipoté l'id
if($_POST['id']==$_SESSION['pourUpdateTab']){
// création d'un objet de type tableau
$tabobj = new Tableau($_POST);
// mise à jour du tableau
$modifie = $manageTableau->updateTab($tabobj);
// si la modification est bonne
if($modifie){
header("Location: ./");
}else{
echo "<h3 onclick='history.go(-1)'>Erreur lors de la modification, vérifiez tous les champs!<br/><button>Complétez le formulaire</button></h3>";
}
}
// sinon affiche le formulaire
}else{
// création d'une variable pour ne pas pouvoir modifier un autre tableau que celui affiché, le plus sécurisé étant invisible pour l'utilisateur: la session
$_SESSION['pourUpdateTab'] = $_GET['updatetab'];
// on récupère les artistes pour le formulaire
$artistes = $manageArtiste->listeArtiste();
// on récupère les champs du tableau
$tableau = $manageTableau->selectUn($_GET['updatetab']);
if(!$tableau){
echo "<h3 onclick='history.go(-1)'>Ce tableau n'existe plus<br/><button>Retour en arrière</button></h3>";
}else{
// on transforme la réponse en objet tableau
$tab = new Tableau($tableau);
// Appel de la vue
echo $twig->render("update.html.twig",array("listeArtistes"=>$artistes, "tab"=>$tab));
}
}
// si on veut supprimer
}elseif(isset($_GET['del'])&& ctype_digit($_GET['del'])){
$delete = $manageTableau->deletetab($_GET['del']);
if($delete){
// redirection vers l'accueil
header("Location: ./");
}else{
echo "not succesfull";
}
}else{
if(isset($_GET[VAR_GET])&& ctype_digit($_GET[VAR_GET])){
$pageActu = $_GET[VAR_GET];
}else{
$pageActu = 1;
}
$nb_tot = $manageTableau->nombreTotalTableau();
$recupTous = $manageTableau->selectAll(NB_PG,$pageActu);
// $recupTous = $manageTableau->selectAll();
$pagination = Pagination::affiche($nb_tot,$pageActu,"pg",NB_PG);
if ($recupTous) {
foreach ($recupTous as $key => $value) {
$obj[] = new Tableau($value);
}
// Appel de la vue
echo $twig->render("base.html.twig",array('affiche' => $obj,"pagi"=>$pagination));
} else {
echo "soucis !";
}
}
| true |
c28f474f56d16c48c3ca0fc1aad4aee72251d6e6 | PHP | linuxserver/mod-list | /index.php | UTF-8 | 8,231 | 2.625 | 3 | [] | no_license | <?php
class LsMods {
private $url = 'https://linuxserver.github.io/docker-mods/mod-list.yml';
public $yaml;
public $mods;
public $validmods;
public function __construct()
{
$this->yaml = $this->getList();
$mods = [];
foreach($this->yaml['mods'] as $modname => $mod) {
if($mod['mod_count'] > 0) $mods[$modname] = $mod;
}
$this->mods = $mods;
$this->validmods = array_keys($mods);
}
public function getList()
{
$yaml = file_get_contents($this->url);
if (function_exists('yaml_parse')) {
return yaml_parse($yaml);
} else {
require_once "./Spyc.php";
return Spyc::YAMLLoadString($yaml);
}
}
public function render($mod = null)
{
if ($mod === null) {
return $this->modList();
}
if($mod === 'create') {
return $this->create();
}
if(!in_array($mod, $this->validmods)) {
// return 'Invalid mod selected';
return $this->create();
}
return $this->displayMod($mod);
}
public function create()
{
echo '<a class="back-to-list" href=".">Back to list</a>';
echo '
<div class="title">Submitting a PR for a Mod to be added to the official LinuxServer.io repo</div>
<div class="content">
<ul>
<li>Ask the team to create a new branch named <code><baseimagename>-<modname></code> in this repo. Baseimage should be the name of the image the mod will be applied to. The new branch will be based on the [template branch](https://github.com/linuxserver/docker-mods/tree/template).</li>
<li>Fork the repo, checkout the template branch.</li>
<li>Edit the <code>Dockerfile</code> for the mod. <code>Dockerfile.complex</code> is only an example and included for reference; it should be deleted when done.</li>
<li>Inspect the <code>root</code> folder contents. Edit, add and remove as necessary.</li>
<li>Edit this readme with pertinent info, delete these instructions.</li>
<li>Finally edit the <code>travis.yml</code>. Customize the build branch, and the vars for <code>BASEIMAGE</code> and <code>MODNAME</code>.</li>
<li>Submit PR against the branch created by the team.</li>
<li>Make sure that the commits in the PR are squashed.</li>
<li>Also make sure that the commit and PR titles are in the format of <code><imagename>: <modname> <very brief description like "initial release" or "update"></code>. Detailed description and further info should be provided in the body (ie. <code>code-server: python2 add python-pip</code>).</li>
</ul></div>';
}
public function modList()
{
echo '<a class="add-mod" href="./?mod=create">Add a mod</a>';
foreach($this->mods as $modname => $mod) {
echo '
<a class="section" href="./?mod='.$modname.'">
<div class="modcount">'.$mod['mod_count'].'<span>Mods</span></div>
<h2>'.$modname.'</h2>
<div class="go"><svg xmlns="http://www.w3.org/2000/svg" width="44" height="44" viewBox="0 0 24 24"><path style="fill:#cfd4d8;" d="M5 3l3.057-3 11.943 12-11.943 12-3.057-3 9-9z"/></svg></div>
</a>';
}
}
public function displayMod($displaymod)
{
echo '<a class="back-to-list" href=".">Back to list</a>';
echo '<div class="title">'.$displaymod.'</div>';
foreach($this->mods[$displaymod]['container_mods'] as $mod) {
echo '
<a class="section" href="'.current($mod).'">
<div class="modcount"><svg width="40" height="40" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
<path style="fill: #dee4e8;" fill-rule="evenodd" clip-rule="evenodd" d="M512 0C229.12 0 0 229.12 0 512c0 226.56 146.56 417.92 350.08 485.76 25.6 4.48 35.2-10.88 35.2-24.32 0-12.16-.64-52.48-.64-95.36-128.64 23.68-161.92-31.36-172.16-60.16-5.76-14.72-30.72-60.16-52.48-72.32-17.92-9.6-43.52-33.28-.64-33.92 40.32-.64 69.12 37.12 78.72 52.48 46.08 77.44 119.68 55.68 149.12 42.24 4.48-33.28 17.92-55.68 32.64-68.48-113.92-12.8-232.96-56.96-232.96-252.8 0-55.68 19.84-101.76 52.48-137.6-5.12-12.8-23.04-65.28 5.12-135.68 0 0 42.88-13.44 140.8 52.48 40.96-11.52 84.48-17.28 128-17.28 43.52 0 87.04 5.76 128 17.28 97.92-66.56 140.8-52.48 140.8-52.48 28.16 70.4 10.24 122.88 5.12 135.68 32.64 35.84 52.48 81.28 52.48 137.6 0 196.48-119.68 240-233.6 252.8 18.56 16 34.56 46.72 34.56 94.72 0 68.48-.64 123.52-.64 140.8 0 13.44 9.6 29.44 35.2 24.32C877.44 929.92 1024 737.92 1024 512 1024 229.12 794.88 0 512 0z" fill="#1B1F23"/>
</svg></div>
<h2>'.key($mod).'</h2>
<div class="go"><svg xmlns="http://www.w3.org/2000/svg" width="44" height="44" viewBox="0 0 24 24"><path style="fill:#cfd4d8;" d="M5 3l3.057-3 11.943 12-11.943 12-3.057-3 9-9z"/></svg></div>
</a>';
}
echo '<a href="./?mod=create" class="add">Add a mod</a>';
}
}
$lsmods = new LsMods;
?><!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Linuxserver Container Mods</title>
<meta name="description" content="List of mods for Linuxserver.io containers">
<meta name="author" content="linuxserver.io">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css?family=Lato:300,400&display=swap" rel="stylesheet">
<style>
body,html {
padding: 0;
margin: 0;
}
body {
background: #e8e8e8;
font-family: 'Lato', sans-serif;
color: #738694;
font-weight: 400;
font-size: 16px;
}
body * {
box-sizing: border-box;
}
code {
font-family: 'Lato', sans-serif;
font-size: 14px;
background: #e8e8e8;
padding: 2px 5px;
border-radius: 3px;
}
#app {
display: flex;
flex-direction: column;
align-items: center;
padding: 15px;
}
h1 {
font-size: 30px;
letter-spacing: 3px;
text-transform: uppercase;
color: #738694;
margin: 60px 0 45px;
font-weight: 400;
}
h1 span {
color: #9bb0bf;
}
.section, .content {
width: 100%;
max-width: 600px;
display: flex;
align-items: center;
background: #efefef;
justify-content: space-between;
text-decoration: none;
margin: 10px;
box-shadow: 0 0 10px rgba(0,0,0,0.05);
}
.content {
padding: 30px;
}
.content li {
margin: 15px 0;
line-height: 1.4;
}
.section h2 {
margin: 0;
flex: 1;
padding: 0 30px;
color: #738694;
font-weight: 400;
text-transform: uppercase;
font-size: 18px;
}
.section .modcount {
width: 80px;
height: 80px;
display: flex;
justify-content: center;
align-items: center;
font-size: 30px;
flex-direction: column;
background: #3e81b9;
color: #fff;
}
.section .modcount span {
font-size: 12px;
color: #ffffffa8;
text-transform: uppercase;
}
.section .go {
width: 80px;
height: 80px;
background: #f5f5f5;
display: flex;
justify-content: center;
align-items: center;
}
.back-to-list, .add-mod {
position: fixed;
left: 0;
padding: 15px;
background: #3eb99d;
color: #fff;
top: 50%;
transform: rotate(270deg) translateZ(0);
transform-origin: 25px 25px;
text-decoration: none;
font-weight: 400;
}
.add-mod {
background: #b93e93;
}
.title {
font-size: 25px;
padding: 20px;
text-align: center;
text-transform: uppercase;
background: #e4e4e4;
margin-bottom: 25px;
width: 100%;
max-width: 600px;
}
.add {
width: 100%;
max-width: 600px;
display: flex;
justify-content: center;
text-decoration: none;
margin: 10px;
border: 5px dashed #ccc;
font-size: 25px;
padding: 20px;
color: #ccc;
font-weight: 400;
text-transform: uppercase;
}
@media only screen and (min-width: 500px) {
h1 {
font-size: 50px;
letter-spacing: 5px;
}
}
</style>
</head>
<body>
<div id="app">
<header>
<h1>Linux<span>Server</span>.io</h1>
</header>
<?php
echo $lsmods->render($_GET['mod'] ?? null);
?>
</div>
</body>
</html> | true |
8a219f113796fe28e291c82ed3bfcc3289075dcd | PHP | jepihumet/jepifw | /JepiFw/System/Model/MySqlModel.php | UTF-8 | 2,210 | 3 | 3 | [
"MIT"
] | permissive | <?php
/**
* MySqlModel.php
*
* @package JepiFW
* @author Jepi Humet Alsius <jepihumet@gmail.com>
* @link http://jepihumet.com
*/
namespace Jepi\Fw\Model;
use Jepi\Fw\Exceptions\ModelException;
class MySqlModel implements ModelInterface
{
/**
* @var \PDO
*/
protected $pdo;
/**
* If dbConnection is null this model will connect to default database defined in config.ini file
* @var string|null
*/
protected $dbConnection = null;
/**
* @param Connections $connections
*/
public function __construct(Connections $connections){
$this->pdo = $connections->openMySqlConnection($this->dbConnection);
}
/**
* @param $SQL
* @return \PDOStatement
* @throws ModelException
*/
private function execute($SQL) {
try {
$queryPrepare = $this->pdo->prepare($SQL);
$queryPrepare->execute();
} catch (\PDOException $e) {
throw new ModelException('Error in the Select QUERY ('.$SQL.') '
. 'and error message('.$e->getMessage().')');
}
return $queryPrepare;
}
/**
* Returns an array of arrays with data
* @param $query
* @return mixed
*/
public function select($query)
{
$result = $this->execute($query);
return $result->fetchAll(\PDO::FETCH_ASSOC);
}
/**
* Returns the last inserted Id
*
* @param $query
* @return int
*/
public function insert($query)
{
$this->execute($query);
return $this->pdo->lastInsertId();
}
/**
* Returns the affected number of rows
*
* @param $query
* @return int
*/
public function update($query)
{
$result = $this->execute($query);
return $result->rowCount();
}
/**
* Returns the number of deleted rows
*
* @param $query
* @return int
*/
public function delete($query)
{
$result = $this->execute($query);
return $result->rowCount();
}
public function beginTransaction()
{
}
public function endTransaction()
{
}
public function rollback()
{
}
} | true |
7c0390daead809900c1a222c3320d804d96d5e42 | PHP | meikieruputra/khub | /old/kh/backend/models/Post.php | UTF-8 | 3,208 | 2.625 | 3 | [
"BSD-3-Clause",
"MIT"
] | permissive | <?php
namespace backend\models;
use Yii;
/**
* This is the model class for table "post".
*
* @property int $id
* @property string $title
* @property string $slug
* @property int $post_category_id
* @property string $description
* @property string $future_image
* @property string $content
* @property int $tag
* @property int $show
* @property string $created_date
* @property int $created_by
* @property string $updated_date
* @property int $updated_by
*
* @property PostCategory $postCategory
* @property Tag $tag0
* @property User $createdBy
* @property User $updatedBy
*/
class Post extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'post';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['id', 'title', 'post_category_id', 'description', 'content', 'show', 'created_date', 'created_by', 'updated_date', 'updated_by'], 'required'],
[['id', 'post_category_id', 'tag', 'show', 'created_by', 'updated_by'], 'integer'],
[['description', 'content'], 'string'],
[['created_date', 'updated_date'], 'safe'],
[['title', 'slug', 'future_image'], 'string', 'max' => 255],
[['id'], 'unique'],
[['post_category_id'], 'exist', 'skipOnError' => true, 'targetClass' => PostCategory::className(), 'targetAttribute' => ['post_category_id' => 'id']],
[['tag'], 'exist', 'skipOnError' => true, 'targetClass' => Tag::className(), 'targetAttribute' => ['tag' => 'id']],
[['created_by'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['created_by' => 'id']],
[['updated_by'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['updated_by' => 'id']],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'title' => 'Title',
'slug' => 'Slug',
'post_category_id' => 'Post Category ID',
'description' => 'Description',
'future_image' => 'Future Image',
'content' => 'Content',
'tag' => 'Tag',
'show' => 'Show',
'created_date' => 'Created Date',
'created_by' => 'Created By',
'updated_date' => 'Updated Date',
'updated_by' => 'Updated By',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getPostCategory()
{
return $this->hasOne(PostCategory::className(), ['id' => 'post_category_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getTag0()
{
return $this->hasOne(Tag::className(), ['id' => 'tag']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCreatedBy()
{
return $this->hasOne(User::className(), ['id' => 'created_by']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getUpdatedBy()
{
return $this->hasOne(User::className(), ['id' => 'updated_by']);
}
}
| true |
54ee2544b1702eb6c846e69cfb2e893122b291d7 | PHP | andy521/yii2-system | /src/behaviors/LanguageQueryBehavior.php | UTF-8 | 2,054 | 2.59375 | 3 | [
"MIT"
] | permissive | <?php
/**
* @link https://github.com/creocoder/yii2-taggable
* @copyright Copyright (c) 2015 Alexander Kochetov
* @license http://opensource.org/licenses/BSD-3-Clause
*/
namespace yuncms\system\behaviors;
use yii\base\Behavior;
use yii\db\Expression;
/**
* LanguageQueryBehavior
*
* @property \yii\db\ActiveQuery $owner
*/
class LanguageQueryBehavior extends Behavior
{
/**
* Gets entities by any languages.
* @param string|string[] $values
* @param string|null $attribute
* @return \yii\db\ActiveQuery the owner
*/
public function anyLanguageValues($values, $attribute = null)
{
/** @var \yii\db\ActiveRecord $model */
$model = new $this->owner->modelClass();
$languageClass = $model->getRelation($model->languageRelation)->modelClass;
$this->owner
->innerJoinWith($model->languageRelation, false)
->andWhere([$languageClass::tableName() . '.' . ($attribute ?: $model->languageValueAttribute) => $model->filterLanguageValues($values)])
->addGroupBy(array_map(function ($pk) use ($model) {
return $model->tableName() . '.' . $pk;
}, $model->primaryKey()));
return $this->owner;
}
/**
* Gets entities by all languages.
* @param string|string[] $values
* @param string|null $attribute
* @return \yii\db\ActiveQuery the owner
*/
public function allLanguageValues($values, $attribute = null)
{
$model = new $this->owner->modelClass();
return $this->anyLanguageValues($values, $attribute)->andHaving(new Expression('COUNT(*) = ' . count($model->filterLanguageValues($values))));
}
/**
* Gets entities related by languages.
* @param string|string[] $values
* @param string|null $attribute
* @return \yii\db\ActiveQuery the owner
*/
public function relatedByLanguageValues($values, $attribute = null)
{
return $this->anyLanguageValues($values, $attribute)->addOrderBy(new Expression('COUNT(*) DESC'));
}
}
| true |
bf9479a2bad991fce6df51f7b48449f1127dc2fe | PHP | Eoras/WCS_HACKATHON_3_Emoovz | /src/AppBundle/Entity/Room.php | UTF-8 | 2,596 | 2.609375 | 3 | [
"MIT"
] | permissive | <?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Room
*
* @ORM\Table(name="room")
* @ORM\Entity(repositoryClass="AppBundle\Repository\RoomRepository")
*/
class Room
{
/**
* @ORM\OneToMany(targetEntity="AppBundle\Entity\MoveOutRoom", mappedBy="room")
*/
private $moveOutRooms;
// PERSONNAL RELATIONS
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* @var string
*
* @ORM\Column(name="pictureName", type="string", length=255)
*/
private $pictureName;
/**
* Constructor
*/
public function __construct()
{
$this->moveOutRooms = new \Doctrine\Common\Collections\ArrayCollection();
$this->objects = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* @param string $name
*
* @return Room
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Add moveOutRoom
*
* @param \AppBundle\Entity\MoveOutRoom $moveOutRoom
*
* @return Room
*/
public function addMoveOutRoom(\AppBundle\Entity\MoveOutRoom $moveOutRoom)
{
$this->moveOutRooms[] = $moveOutRoom;
return $this;
}
/**
* Remove moveOutRoom
*
* @param \AppBundle\Entity\MoveOutRoom $moveOutRoom
*/
public function removeMoveOutRoom(\AppBundle\Entity\MoveOutRoom $moveOutRoom)
{
$this->moveOutRooms->removeElement($moveOutRoom);
}
/**
* Get moveOutRooms
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getMoveOutRooms()
{
return $this->moveOutRooms;
}
/**
* Set pictureName
*
* @param string $pictureName
*
* @return Room
*/
public function setPictureName($pictureName)
{
$this->pictureName = $pictureName;
return $this;
}
/**
* Get pictureName
*
* @return string
*/
public function getPictureName()
{
return $this->pictureName;
}
}
| true |
65223085329b1a63c76c851e301263d411799760 | PHP | mzcoding/laravel-crud | /app/Http/Controllers/StaffController.php | UTF-8 | 2,329 | 2.640625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers;
use App\Http\Requests\StaffRequest;
use App\Staff;
use Illuminate\Http\Request;
class StaffController extends Controller
{
/**
* Display a listing of the resource.
*
* @return Staff[]|\Illuminate\Database\Eloquent\Collection
*/
public function index()
{
$objStaff = new Staff();
return $objStaff->all();
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function store(StaffRequest $request)
{
$objStaff = new Staff();
$staff = $objStaff->create($request->validated());
if($staff) {
return response()->json(['message' => 'Success']);
}
return response()->json(['message' => 'Error'], 400);
}
/**
* Display the specified resource.
*
* @param \App\Staff $staff
* @return \Illuminate\Http\Response
*/
public function show(Staff $staff)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Staff $staff
* @return \Illuminate\Http\Response
*/
public function edit(Staff $staff)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Staff $staff
* @return \Illuminate\Http\JsonResponse
*/
public function update(StaffRequest $request, Staff $staff)
{
$staff->name = $request->input('name');
$staff->email = $request->input('email');
if($staff->save()) {
return response()->json(['message' => 'Success']);
}
return response()->json(['message' => 'Error'], 400);
}
/**
* Remove the specified resource from storage.
*
* @param \App\Staff $staff
* @return \Illuminate\Http\JsonResponse
*/
public function destroy(Staff $staff)
{
try{
$staff->delete();
return response()->json(['message' => 'Success']);
}catch (\Exception $e) {
return response()->json(['message' => 'Error'], 400);
}
}
}
| true |
b3db61bcf061f13157408fb8b7df43c04f5fe77b | PHP | maria364/webdev | /register-check.php | ISO-8859-7 | 1,371 | 2.703125 | 3 | [] | no_license | <?php
include('connect.inc');
$firstname = mysql_real_escape_string( $_POST['firstname'] );
$lastname = mysql_real_escape_string( $_POST['lastname'] );
$email = mysql_real_escape_string( $_POST['e-mail'] );
$username = mysql_real_escape_string( $_POST['username'] );
$password = md5( mysql_real_escape_string( $_POST['password']));
if( empty($username) || empty($password) )
{
echo " username password";
exit();
}
/* username*/
$first = "SELECT username FROM diplomatiki.users WHERE username LIKE '$username'";
$res = mysqli_query($conn, $first)or die("<br/><br/>".mysql_error());
/* username. Insertion */
$row = mysqli_fetch_row($res);
if ( $row> 0 )
echo "Username has already been taken"; /* */
else {
$sql = "INSERT INTO users VALUES ('$firstname', '$lastname', '$email', '$password', '', '$username' )";
/* ('firstname, lastname, e-mail, usename, password) */
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Insertion failed " .mysql_error();
}
}
/* mysqli_close($conn);
*/
?>
| true |
bb486836cf29df38a28d66c32d95c81d7da43e64 | PHP | hoanganhquang/web-application-development-labs | /labs/Lab03/Practical1/post.php | UTF-8 | 178 | 3.484375 | 3 | [] | no_license | <?php
if(isset($_POST["name"]) && isset($_POST["age"])){
echo "Name: " . $_POST['name'] . "<br>";
echo "Age: " . $_POST['age'];
}
?> | true |
70f579eeea52871e4f8c3ea81df3554343d49d09 | PHP | Konstanta100/onBoarding | /www/app/src/ArgumentValueResolver/ArgumentValueResolver.php | UTF-8 | 2,346 | 2.515625 | 3 | [] | no_license | <?php
declare(strict_types=1);
namespace App\ArgumentValueResolver;
use App\Dto\ValidationError;
use App\Exception\ValidationException;
use JMS\Serializer\SerializerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;
use Symfony\Component\Validator\Validator\ValidatorInterface;
/**
* Class ArgumentValueResolver
* @package App\ArgumentValueResolver
*/
class ArgumentValueResolver implements ArgumentValueResolverInterface
{
protected ValidatorInterface $validator;
protected SerializerInterface $serializer;
/**
* DtoResolver constructor.
* @param ValidatorInterface $validator
* @param SerializerInterface $serializer
*/
public function __construct(ValidatorInterface $validator, SerializerInterface $serializer)
{
$this->validator = $validator;
$this->serializer = $serializer;
}
/**
* @inheritDoc
* @param Request $request
* @param ArgumentMetadata $argument
* @return bool
*/
public function supports(Request $request, ArgumentMetadata $argument): bool
{
return class_exists($argument->getType());
}
/**
* @param Request $request
* @param ArgumentMetadata $argument
* @return \Generator|iterable
* @throws ValidationException
*/
public function resolve(Request $request, ArgumentMetadata $argument)
{
$argumentObj = $this->serializer->deserialize($request->getContent(), $argument->getType(), 'json');
$violationsList = $this->validator->validate($argumentObj);
if (($countViolations = \count($violationsList)) > 0) {
$errors = [];
for ($i = 0; $i < $countViolations; $i++) {
if($violationsList->has($i)){
$violation = $violationsList->get($i);
$error = new ValidationError();
$errors[] = $error->setMessage($violation->getMessage())
->setProperty($violation->getPropertyPath())
->setInvalidValue($violation->getInvalidValue());
}
}
throw new ValidationException($errors);
}
yield $argumentObj;
}
} | true |
568e1bace7a48cd5f291b63b0a66dfa872140db7 | PHP | sam110386/insurance | /database/migrations/2019_07_12_051543_add_more_vehicle_columns.php | UTF-8 | 10,319 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddMoreVehicleColumns extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('leads', function (Blueprint $table) {
$table->smallInteger('sixth_vehicle_year')->nullable();
$table->string('sixth_vehicle_make',100)->nullable();
$table->string('sixth_vehicle_model',100)->nullable();
$table->string('sixth_vehicle_trim',100)->nullable();
$table->string('sixth_vehicle_vin',15)->nullable();
$table->string('sixth_vehicle_owenership',15)->nullable();
$table->string('sixth_vehicle_uses',15)->nullable();
$table->string('sixth_vehicle_mileage',25)->nullable();
$table->smallInteger('seventh_vehicle_year')->nullable();
$table->string('seventh_vehicle_make',100)->nullable();
$table->string('seventh_vehicle_model',100)->nullable();
$table->string('seventh_vehicle_trim',100)->nullable();
$table->string('seventh_vehicle_vin',15)->nullable();
$table->string('seventh_vehicle_owenership',15)->nullable();
$table->string('seventh_vehicle_uses',15)->nullable();
$table->string('seventh_vehicle_mileage',25)->nullable();
$table->smallInteger('eighth_vehicle_year')->nullable();
$table->string('eighth_vehicle_make',100)->nullable();
$table->string('eighth_vehicle_model',100)->nullable();
$table->string('eighth_vehicle_trim',100)->nullable();
$table->string('eighth_vehicle_vin',15)->nullable();
$table->string('eighth_vehicle_owenership',15)->nullable();
$table->string('eighth_vehicle_uses',15)->nullable();
$table->string('eighth_vehicle_mileage',25)->nullable();
$table->smallInteger('ninth_vehicle_year')->nullable();
$table->string('ninth_vehicle_make',100)->nullable();
$table->string('ninth_vehicle_model',100)->nullable();
$table->string('ninth_vehicle_trim',100)->nullable();
$table->string('ninth_vehicle_vin',15)->nullable();
$table->string('ninth_vehicle_owenership',15)->nullable();
$table->string('ninth_vehicle_uses',15)->nullable();
$table->string('ninth_vehicle_mileage',25)->nullable();
$table->smallInteger('tenth_vehicle_year')->nullable();
$table->string('tenth_vehicle_make',100)->nullable();
$table->string('tenth_vehicle_model',100)->nullable();
$table->string('tenth_vehicle_trim',100)->nullable();
$table->string('tenth_vehicle_vin',15)->nullable();
$table->string('tenth_vehicle_owenership',15)->nullable();
$table->string('tenth_vehicle_uses',15)->nullable();
$table->string('tenth_vehicle_mileage',25)->nullable();
//changing size of Int to Sm Int
$table->string('first_name',50)->change();
$table->string('last_name',50)->change();
$table->string('street')->change();
$table->string('city',25)->change();
$table->string('state',15)->change();
$table->string('zip',8)->change();
$table->string('phone',20)->change();
$table->string('email',50)->change();
$table->boolean('married')->default(0)->change();
$table->boolean('children')->default(0)->change();
$table->string('homeowner',10)->change();
$table->boolean('bundled')->default(0)->change();
$table->string('first_driver_first_name',50)->change();
$table->string('first_driver_last_name',50)->change();
$table->date('first_driver_dob')->change();
$table->string('first_driver_gender',10)->change();
$table->string('first_driver_dl',15)->change();
$table->string('first_driver_state',15)->change();
$table->string('second_driver_first_name',50)->nullable()->change();
$table->string('second_driver_last_name',50)->nullable()->change();
$table->date('second_driver_dob')->nullable()->change();
$table->string('second_driver_gender',10)->nullable()->change();
$table->string('second_driver_dl',15)->nullable()->change();
$table->string('second_driver_state',15)->nullable()->change();
$table->string('third_driver_first_name',50)->nullable()->change();
$table->string('third_driver_last_name',50)->nullable()->change();
$table->date('third_driver_dob')->nullable()->change();
$table->string('third_driver_gender',10)->nullable()->change();
$table->string('third_driver_dl',15)->nullable()->change();
$table->string('third_driver_state',15)->nullable()->change();
$table->string('fourth_driver_first_name',50)->nullable()->change();
$table->string('fourth_driver_last_name',50)->nullable()->change();
$table->date('fourth_driver_dob')->nullable()->change();
$table->string('fourth_driver_gender',10)->nullable()->change();
$table->string('fourth_driver_dl',15)->nullable()->change();
$table->string('fourth_driver_state',15)->nullable()->change();
$table->string('fifth_driver_first_name',50)->nullable()->change();
$table->string('fifth_driver_last_name',50)->nullable()->change();
$table->date('fifth_driver_dob')->nullable()->change();
$table->string('fifth_driver_gender',10)->nullable()->change();
$table->string('fifth_driver_dl',15)->nullable()->change();
$table->string('fifth_driver_state',15)->nullable()->change();
$table->smallInteger('first_vehicle_year')->change();
$table->string('first_vehicle_make',100)->change();
$table->string('first_vehicle_model',100)->change();
$table->string('first_vehicle_trim',100)->change();
$table->string('first_vehicle_vin',15)->change();
$table->string('first_vehicle_owenership',15)->change();
$table->string('first_vehicle_uses',15)->change();
$table->string('first_vehicle_mileage',25)->change();
$table->smallInteger('second_vehicle_year')->nullable()->change();
$table->string('second_vehicle_make',100)->nullable()->change();
$table->string('second_vehicle_model',100)->nullable()->change();
$table->string('second_vehicle_trim',100)->nullable()->change();
$table->string('second_vehicle_vin',15)->nullable()->change();
$table->string('second_vehicle_owenership',15)->nullable()->change();
$table->string('second_vehicle_uses',15)->nullable()->change();
$table->string('second_vehicle_mileage',25)->nullable()->change();
$table->smallInteger('third_vehicle_year')->nullable()->change();
$table->string('third_vehicle_make',100)->nullable()->change();
$table->string('third_vehicle_model',100)->nullable()->change();
$table->string('third_vehicle_trim',100)->nullable()->change();
$table->string('third_vehicle_vin',15)->nullable()->change();
$table->string('third_vehicle_owenership',15)->nullable()->change();
$table->string('third_vehicle_uses',15)->nullable()->change();
$table->string('third_vehicle_mileage',25)->nullable()->change();
$table->smallInteger('fourth_vehicle_year')->nullable()->change();
$table->string('fourth_vehicle_make',100)->nullable()->change();
$table->string('fourth_vehicle_model',100)->nullable()->change();
$table->string('fourth_vehicle_trim',100)->nullable()->change();
$table->string('fourth_vehicle_vin',15)->nullable()->change();
$table->string('fourth_vehicle_owenership',15)->nullable()->change();
$table->string('fourth_vehicle_uses',15)->nullable()->change();
$table->string('fourth_vehicle_mileage',25)->nullable()->change();
$table->smallInteger('fifth_vehicle_year')->nullable()->change();
$table->string('fifth_vehicle_make',100)->nullable()->change();
$table->string('fifth_vehicle_model',100)->nullable()->change();
$table->string('fifth_vehicle_trim',100)->nullable()->change();
$table->string('fifth_vehicle_vin',15)->nullable()->change();
$table->string('fifth_vehicle_owenership',15)->nullable()->change();
$table->string('fifth_vehicle_uses',15)->nullable()->change();
$table->string('fifth_vehicle_mileage',25)->nullable()->change();
$table->string('liability',10)->nullable()->change();
$table->string('body_injury',25)->nullable()->change();
$table->string('deduct',25)->nullable()->change();
$table->string('medical',25)->nullable()->change();
$table->boolean('towing')->default(0)->change();
$table->boolean('uninsured')->default(0)->change();
$table->boolean('rental')->default(0)->change();
$table->boolean('previous_insurance')->default(0)->change();
$table->string('current_insurance',50)->nullable()->change();
$table->string('duration',25)->nullable()->change();
$table->boolean('at_fault')->default(0)->change();
$table->boolean('tickets')->default(0)->change();
$table->boolean('dui')->default(0)->change();
$table->string('quality_provides',100)->nullable()->change();
$table->boolean('agent_in_person')->default(0)->change();
$table->string('referrer',100)->nullable()->change();
$table->string('referrer_name',100)->nullable()->change();
$table->string('ip_address',10)->change();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('leads', function (Blueprint $table) {
//
});
}
}
| true |
395b802554bbfa7604a7b1842dec269b84824c8b | PHP | barrozaum/projetoArrecadacao | /site/recursos/includes/retornaValor/retornaSituacaoValorM2Terreno.php | UTF-8 | 786 | 2.828125 | 3 | [] | no_license | <?php
include_once '../estrutura/controle/validarSessao.php';
$cod = $_REQUEST['cod'];
// chamo a conexao com o banco de dados
include_once '../estrutura/conexao/conexao.php';
// preparo para realizar o comando sql
$sql = "select * from Utilizacao where Codigo = '" . $cod . "'";
$query = $pdo->prepare($sql);
//executo o comando sql
$query->execute();
// Faço uma comparação para saber se a busca trouxe algum resultado
if (($dados = $query->fetch()) == true) {
$descricao = $dados['Descricao'];
} else {
$descricao = "Código inválido";
}
$pdo = null;
// array com referente a 3 pessoas
$var = Array(
array(
"descricao" => "$descricao"
)
);
// convertemos em json e colocamos na tela
echo json_encode($var);
?> | true |
7b46b66f5a95fee28d2ff8f71f27a9eaa491845b | PHP | google-code/baseappframework | /baseapp/libraries/mail.php | UTF-8 | 2,498 | 2.90625 | 3 | [] | no_license | <?php
/**
* Mail class for sending E-Mails
*
* A tiny mailing class will use php mailer if it exists.
*
* @version $Id: validation.php 7 2009-03-04 22:18:40Z vikaspatial1983 $
* @package BaseApp Framework (v0.1)
* @link http://code.google.com/p/baseappframework/
* @copyright Copyright (C) 2009 NGCoders. All rights reserved.
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/
$phpmailer = BASEAPP_PATH.'libraries/phpmailer/class.phpmailer.php';
if (file_exists($phpmailer)) {
include($phpmailer);
class Mail extends phpmailer {
}
} else {
/* Use default php mail function in simple mailing class*/
class Mail
{
public $From = "";
public $FromName = "";
public $Subject = "";
public $Body = "";
private $addresses = array();
/**
* Add addresses to send email to
*
* @param string $email Email to which to send the email
* @param string $name Name of the Email owner
*/
public function AddAddress($email,$name = "")
{
$this->addresses[$email] = $name;
}
/**
* Sends out the email
*
* @return boolean Returns true if file is sent else returns false
*/
public function Send()
{
$headers = "";
$to = "";
$toString = "";
foreach ($this->addresses as $email=>$name)
{
$toString .=(empty($toString))?'':', ';
$to .=(empty($to))?'':', ';
$toString .= "$name <$email>";
$to .= "$email";
}
if (empty($this->FromName)) {
$this->FromName = $this->From;
}
// Additional headers
$headers .= "To: $toString \r\n";
$headers .= 'From: $this->FromName <$this->From>' . "\r\n";
// Mail it
return mail($to, $this->Subject, $this->Body, $headers);
}
/**
* Clears addresses stored int the class
*
*/
public function ClearAddresses()
{
$this->addresses = array();
}
}
}
| true |
59b6fc5d7ae757a649ab2110e1cfb15a75839e76 | PHP | harryak/jc_intern | /app/Http/Controllers/FileAccessController.php | UTF-8 | 7,046 | 2.59375 | 3 | [
"AGPL-3.0-only"
] | permissive | <?php
namespace App\Http\Controllers;
use App\Http\Controllers\Auth\AuthController;
use Carbon\CarbonInterval;
use Illuminate\Http\Request;
use Carbon\Carbon;
use GuzzleHttp;
use Illuminate\Support\Facades\Cache;
/*use Psr\Http\Message;*/
class FileAccessController extends Controller
{
/**
* Create a new controller instance.
*/
public function __construct() {
$this->middleware('auth');
}
protected const available_params = ['path', 'shareType', 'publicUpload', 'permissions', 'shareWith', 'expireDate'];
protected $connection = null;
protected function connectCloud($uri, $username, $password) {
if (parse_url($uri, PHP_URL_SCHEME) !== 'https') {
abort(500, 'Only HTTPS-connections allowed for Cloud-Connection');
}
if (substr($uri, -1) !== '/') {
$uri .= '/';
}
/*$redirect_verification = function(Message\RequestInterface $request, Message\ResponseInterface $response, Message\UriInterface $new_uri) use ($uri) {
$original_host = parse_url($uri, PHP_URL_HOST); // Host before any redirect
$old_host = parse_url($request->getUri(), PHP_URL_HOST); // Host before this redirect
$new_host = parse_url($new_uri, PHP_URL_HOST); // Host after this redirect
if ($old_host !== $new_host || $new_host !== $original_host) {
abort(500, 'Cloud-Connection redirects are only allowed to the same host.');
}
};*/
$this->connection = new GuzzleHttp\Client(
[
'base_uri' => $uri . 'v2.php/apps/files_sharing/api/v1/',
'auth' => [$username, $password],
'headers' => ['OCS-APIRequest' => 'true', 'Accept' => 'application/json'],
'allow_redirects' => false
/*
* Just don't allow redirects ever. This causes $this->parseResponse to throw unrelated exceptions in case of redirects, which is not ideal.
* Alternatively, we could use 'allow_redirects' => ['protocols' => ['https'], 'on_redirect' => $redirect_verification, 'strict' => true]
* However, that could be just as bad. Generally, we don't want any redirects because of conversion of different methods (POST becomes GET) and other inconsistencies.
* If the cloud server address changes, it should be changed in .env
*/
]
);
}
protected function parseResponse($request_result) {
return json_decode(
$request_result->getBody()->getContents()
)->ocs->data;
}
protected function createShare($params) {
// https://docs.nextcloud.com/server/14/developer_manual/core/ocs-share-api.html#create-a-new-share
$first_response = $this->parseResponse($this->connection->request('POST', 'shares', ['form_params' => $params]));
// Due to a bug in NextCloud, we need update everything just to be sure
return $this->updateShare($first_response->id, $params);
}
protected function updateShare($id, $params) {
// https://docs.nextcloud.com/server/14/developer_manual/core/ocs-share-api.html#update-share
return $this->parseResponse($this->connection->request('PUT', 'shares/' . $id, ['json' => $params]));
}
private function generateCloudUrl($type, $id) {
$cache_key = 'cloudshare_url_' . $type . '_' . $id; //Cache::flush();
$cloudshare_url = cache_atomic_lock_provider($cache_key, function ($key, &$cache_expiry_time, $lock_time) use ($type, $id) {
$config = \Config::get('cloud');
$folder_config = $config['shares'][$type]['folders'][$id];
// Presumed duration of a typical user's access to the cloud. During this time, the share is guaranteed to stay active.
// After the share expires, the user will have to re-access it through this interface.
$access_duration = CarbonInterval::minutes(30);
// Shares always expire at midnight, but the server might have a different timezone (usually UTC)
$share_expiry_time = Carbon::now($config['timezone'])->add($access_duration)->addDay()->startOfDay();
// The cache should expire before the share expires. Additionally, we don't want to run into trouble if someone accesses the share just before midnight
// There is no need to convert back to our timezone, Cache and Carbon should take care of that
//$cache_expiry_time = $share_expiry_time->copy()->sub($access_duration);
$cache_expiry_time = 60; // Nextcloud currently has a bug that sometimes purges all shared links. Therefore we renew them every hour. Go back to the old system once the bug is fixed.
$this->connectCloud($config['uri'], $config['shares'][$type]['username'], $config['shares'][$type]['password']);
$cloudshare_result = $this->createShare([
'path' => $folder_config['path'],
'shareType' => 3, // 0 = user; 1 = group; 3 = public link; 6 = federated cloud share
'publicUpload' => $folder_config['public_upload'],
'permissions' => $folder_config['permissions'],
'expireDate' => $share_expiry_time->toDateString()
]);
return $cloudshare_result->url;
});
return $cloudshare_url;
}
public function accessFiles($type = null, $id = null, $accepted_warning = false) {
if ($type === null || $id === null) {
abort(404);
}
$config = \Config::get('cloud');
if (!array_key_exists($type, $config['shares'])) {
abort(404);
}
if ($config['shares'][$type]['requires_admin'] !== false && !\Auth::user()->isAdmin()) {
abort(403);
}
if (!array_key_exists($id, $config['shares'][$type]['folders'])) {
abort(404);
}
if ($config['shares'][$type]['folders'][$id]['requires_warning']) {
return view('file_access.warning', ['hide_navbar' => true]);
} else {
return redirect($this->generateCloudUrl($type, $id));
}
}
public function accessFilesAccept(Request $request, $type = null, $id = null) {
if ($type === null || $id === null) {
abort(404);
}
$config = \Config::get('cloud');
if (!array_key_exists($type, $config['shares'])) {
abort(404);
}
if ($config['shares'][$type]['requires_admin'] !== false && !\Auth::user()->isAdmin()) {
abort(403);
}
if (!array_key_exists($id, $config['shares'][$type]['folders'])) {
abort(404);
}
if (filter_var($request->get('accepted_warning', false), FILTER_VALIDATE_BOOLEAN) === true) {
return redirect($this->generateCloudUrl($type, $id));
} else {
return view('file_access.warning', ['hide_navbar' => true]);
}
}
}
| true |
e327b9543d8038fb1a096fd87dc5446f7b904fc8 | PHP | RyoIshiguro/FDCI-TRAINING-RYO | /6_php/exercise15/hw3.php | UTF-8 | 1,547 | 3.828125 | 4 | [] | no_license | <?php
class Sort{
public $numbers_from = [0,0,0,0,0];
// public $numbers = [0,0,0,0,0];
function __construct($numbers_from)
{
$this -> numbrers_from = $numbers_from;
// $this -> numbers_to = $numbers;
}
function sortNumber($numbers_from = [5,12,28,19,20])
{
echo "from :"; echo"<br>\n";
// print_r($numbers_from); echo"<br>\n";
for ($i=0; $i < count($numbers_from) ; $i++) {
echo $numbers_from[$i];
echo " " ;
}
echo"<br>\n";
echo "to :"; echo"<br>\n";
sort($numbers_from);
// var_dump($numbers_from); echo"<br>\n";
// echo $numbers_from[0];
for ($i=0; $i < count($numbers_from); $i++) {
echo $numbers_from[$i];
echo " " ;
}
// var_dump($numbrers_from);
}
}
// $numbers = new Sort;
$numbers_from = new Sort($numbers_from = [5,12,28,19,20]);
$numbers_from -> sortNumber($numbers_from = [5,12,28,19,20]);
// var_dump($numbrers_from);echo"<br>\n";
// print_r($numbrers_from -> sortNumber($numbrers_from));
// $numbrer_from = new Sort($numbers = [5,12,28,19,20]);
// $numbers = new Sort($numbers = [5,12,28,19,20]);
// var_dump($numbers -> sortNumber());
// var_dump($this -> sortNumber());
// $this -> sortNumber();
// sortNumber();
// var_dump($numbers -> sort());
//これは動く
// $number1 = [5,12,28,19,20];echo"<br>\n";
// sort($number1);echo"<br>\n";
// var_dump($number1);echo"<br>\n";
?>
| true |
bb33d17d3cc8823e39c2f0d9d351e9917af4bcf8 | PHP | velebak/Clubhouse | /application/models/User/UserLogin.php | UTF-8 | 805 | 2.578125 | 3 | [] | no_license | <?php if (!defined('FARI')) die();
/**
* Clubhouse, a 37Signals' Campfire port
*
* @copyright Copyright (c) 2010 Radek Stepan
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
* @link http://radekstepan.com
* @category Clubhouse
*/
/**
* User authentication.
*
* @copyright Copyright (c) 2010 Radek Stepan
* @package Clubhouse\Models\User
*/
class UserLogin {
function __construct($username, $password, $token=NULL) {
$authenticator = new Fari_AuthenticatorSimple();
// authenticator authenticates...
if ($authenticator->authenticate($username, $password, $token) != TRUE) {
throw new UserNotAuthenticatedException();
} else {
// return the sweet beans
return new User();
}
}
} | true |
c8145322e2467298476fc4eee4837ab2dfc6447c | PHP | paranoiq/datadog-client | /tests/DatadogClient_test.phpt | UTF-8 | 1,175 | 2.53125 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
require __DIR__ . '/boot.php';
use Tester\Assert;
use DataDog\DatadogClient;
$c = new DatadogClient(123, 456);
Assert::same('', $c->serializeTags(array()));
Assert::same('tag1:123,tag2:456,tag3', $c->serializeTags(array('tag1' => 123, 'tag2' => 456, 'tag3' => TRUE,)));
$c->setTags(array('tag2' => 456, 'tag3' => TRUE));
Assert::same('tag1:123,tag2:456,tag3', $c->serializeTags(array('tag1' => 123,)));
$c->setTags(array());
Assert::throws(function () use ($c) {
$c->serializeTags(array('#tag' => 123));
}, 'DataDog\\DatadogClientException');
Assert::same(array(), $c->preparePackets(array()));
Assert::same(array('stat:1|c'), $c->preparePackets(array('stat' => '1|c')));
Assert::same(array('stat:1|c|#tag:val'), $c->preparePackets(array('stat' => '1|c'), 1, array('tag' => 'val')));
Assert::same(array('stat:123|ms'), $c->timing('stat', 123));
Assert::same(array('stat:123|g'), $c->gauge('stat', 123));
Assert::same(array('stat:123|s'), $c->set('stat', 123));
Assert::same(array('stat:1|c'), $c->increment('stat'));
Assert::same(array('stat:-1|c'), $c->decrement('stat'));
Assert::same(array('a:1|c', 'b:1|c'), $c->updateStats(array('a','b')));
| true |
97bc9a33eb643e1b990b03e93a1a34908f090063 | PHP | sawkea/multiplication | /5_super_revision.php | UTF-8 | 3,762 | 2.6875 | 3 | [] | no_license | <!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Multiplication</title>
<link rel="icon" type="image/png" href="img/favicon.png" />
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="style.scss">
</head>
<body>
<div class="container">
<!-- Header -->
<?php
include 'headerNav.html';
?>
</div>
<main>
<section>
<div class="container text_center color">
<h2 class="font_title text_center color_title">Super révision</h2>
<p>Essai de répondre aux 5 questions</p>
<?php
include 'fonction.php';
?>
<!-- Formulaire "des questions" et bouton "valider"-->
<div class="color-text line-height-text font_title">
<form action="" method="post">
<?php
// boucle : POUR avec ses paramètres (la variable i = 0; la variable i est inférieure à 5; la variable i est incrémentée){
// dans cette boucle on appel la fonction superRevision(avec deux valeur aleatoire entre 0 et 10)
for ($i = 0; $i < 5; $i++){
superRevision(mt_rand(0 , 10), mt_rand(0, 10));
}
?>
<!-- bouton valider -->
<br>
<button type="submit" class="styled">Valider</button>
<br>
</form>
<!-- Boucle SI(la variable du formulaire aléatoire est déclarée et est différente de null
POUR (la variable i = 0; la variable i est inférieure à 5; la variable i est incrémentée){
AFFICHE la variable du formulaire dans le tableau :[var aléatoire] [ensuite incrémenter] X [var nombre] [ensuite incrémenter] = au calcul de la multiplication
}
SI la multiplication est égale à la bonne réponse {
Affiche "super......"
}
SINON {
Affiche "Dommage...."
}
-->
<?php
if (isset($_POST['aleatoire'])){
for ($i = 0; $i < 5; $i++){
echo $_POST['aleatoire'][$i]."<span> X </span>".$_POST['nombre'][$i]."<span> = </span>" .$_POST['aleatoire'][$i]*$_POST['nombre'][$i];
if ($_POST['aleatoire'][$i]*$_POST['nombre'][$i]==$_POST['reponse'][$i]){
echo "<div class=\"color-rep-true\">Super ! C'est juste !</div> <br> ";
}
else {
echo "<div class=\"color-rep-false\">Dommage ! c'est faux.</div> <br> ";
}
}
}
?>
</div>
</section>
</main>
<script src="script.js"></script>
</body>
</html>
| true |
4f7ba6840b322e5571097070bc3d2b2b1e34b78b | PHP | silasrm/redirector | /index.php | UTF-8 | 3,366 | 2.625 | 3 | [] | no_license | <?php
if (!isset($_GET['url']) || !filter_var($_GET['url'], FILTER_VALIDATE_URL) || strpos($_GET['url'], 'http') === false) {
return false;
}
/* gets the data from a URL */
function getData($url) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
function getMetas($content)
{
preg_match_all( '#<\s*meta\s*(name|property|content)\s*=\s*("|\')(.*)("|\')\s*(name|property|content)\s*=\s*("|\')(.*)("|\')(\s+)?\/?>#i', $content, $matches, PREG_SET_ORDER );
if (!empty($matches)) {
$result = array_map(function($arr) {
return array_values(array_filter($arr, function($el) {
$el = trim($el);
return !empty($el) && strpos($el, '<meta') === false
&& $el !== $meta && $el !== 'content' && $el !== 'name'
&& $el !== 'property' && $el !== '"' && $el !== "'";
}));
}, $matches);
} else {
$result = null;
}
return $result;
}
function getMeta($metas, $meta)
{
$result = array_filter($metas, function($arr) use($meta) {
return $arr[0] == $meta;
});
if (!empty($result)) {
$result = array_shift($result);
preg_match('/\.([jpg|jpeg|png|gif]){3,}/i', $result[1], $matches);
if (!empty($matches)) {
if ((($posicao = strpos($result[1], '.jpg')) !== false)
|| (($posicao = strpos($result[1], '.png')) !== false)
|| (($posicao = strpos($result[1], '.gif')) !== false)) {
$tamanho = 4;
} else if (($posicao = strpos($result[1], '.jpeg')) !== false) {
$tamanho = 5;
}
return substr($result[1], 0, ($posicao + $tamanho));
}
return $result[1];
}
return null;
}
$url = filter_var($_GET['url'], FILTER_VALIDATE_URL);
$cache = 'cache/' . sha1($url) . '.html';
if (!file_exists($cache)) {
$content = getData($url);
preg_match('/\<title\>(.*)\<\/title\>/i', $content, $matches);
$title = array_filter($matches, function($el) {
return !empty(trim($el)) && strpos($el, '<title>') === false;
});
$title = array_shift($title);
$metas = getMetas($content);
$description = getMeta($metas, 'description');
if (empty($description)) {
$description = getMeta($metas, 'og:description');
}
if (empty($description)) {
$description = getMeta($metas, 'twitter:description');
}
$image = getMeta($metas, 'og:image');
if (empty($image)) {
$image = getMeta($metas, 'twitter:image');
}
if (empty($image)) {
$image = 'images/marca.png';
}
$tmpl = file_get_contents('tmpl.html');
$tmpl = str_replace('{{title}}', ($title ? $title : ''), $tmpl);
$tmpl = str_replace('{{description}}', ($description ? $description : ''), $tmpl);
$tmpl = str_replace('{{image}}', ($image ? $image : ''), $tmpl);
$tmpl = str_replace('{{url}}', $url, $tmpl);
file_put_contents($cache, $tmpl);
} else {
$tmpl = file_get_contents($cache);
}
echo $tmpl; | true |
ec64b900bd7b25c4269b4ece014af294c4b6c737 | PHP | EM-Creations/101CMS | /cms/pages/admin.Ranks.inc.php | UTF-8 | 6,122 | 2.765625 | 3 | [
"MIT"
] | permissive | <?php
if ($_currUser->type() == "guest") { // If the user isn't logged in, redirect them
header("Location: ../");
exit;
}
if (!$_currUser->checkPermission("ranks")) { // If this user doesn't have the Super Admin permission, redirect them
header("Location: ./");
exit;
}
if (isset($_GET['rank'])) { // If we're editing / viewing a rank
// <editor-fold defaultstate="collapsed" desc="Rank Editing Code">
$rankID = $_mysql->real_escape_string($_GET['rank']);
if (!is_numeric($rankID)) { // If the rank isn't a number
die("<strong>Error:</strong> Rank isn't a number");
}
$rank = new Rank($rankID); // Instantiate the rank object
if (isset($_POST['rankSubmitButton'])) { // If the personal settings form has been submitted
if (isset($_POST['rankNameField']) && !empty($_POST['rankNameField'])) {
$rank->setName($_POST['rankNameField']);
}
if ((isset($_POST['rankLevelField']) && !empty($_POST['rankLevelField']))) {
$rank->setLevel($_POST['rankLevelField']);
}
} else if (isset($_POST['rankPermissionsSubmitButton'])) { // If the permissions form has been submitted
$settings = array();
foreach ($_POST as $key => $var) {
if (substr($key, 0, 11) == "permission_") { // Check this is a setting variable
$key = substr($key, 11);
$key = str_replace(" ", "_", $key); // Replace spaces with underscores
$settings[$key] = $var;
}
}
$rank->savePermissions($settings);
}
print("<h1>Editing " . $rank->name() . "</h1>");
print("<h2>Settings</h2>");
?>
<form id="registerForm" method="post">
<table>
<tr>
<td class="right"><label for="rankNameField">Name:</label> <input type="text" id="rankNameField" name="rankNameField" value="<?php print($rank->name()); ?>" /></td>
</tr>
<tr>
<td class="right"><label for="rankLevelField">Level:</label>
<select id="rankLevelField" name="rankLevelField"><?php
for ($i = 1; $i < 11; $i++) {
print("<option " . (($i == $rank->level()) ? "selected=\"selected\"" : "") . " value=\"" . $i . "\">" . $i . "</option>\n");
}
?></select></td>
</tr>
<tr>
<td style="padding-left: 150px;"><button type="submit" id="rankSubmitButton" name="rankSubmitButton">Update</button></td>
</tr>
</table>
</form>
<?php
print("<h2>Permissions</h2>");
print("<form id=\"settingsForm\" method=\"post\">\n");
$permissions = array();
$permissions['basicAdmin'] = "Basic admin area access.";
$permissions['Super Admin'] = "Super Admin.";
$permissions['managePages'] = "Manage CMS pages.";
$permissions['manageUsers'] = "Manage users.";
$permissions['viewBans'] = "View bans list.";
$permissions['unban'] = "Unban users.";
$permissions['ban'] = "Ban users.";
$permissions['metaTags'] = "Edit meta tags.";
$permissions['ranks'] = "Edit ranks.";
$permissions['rosters'] = "Edit rosters.";
$permissions['polls'] = "Edit polls.";
$permissions['manageApplications'] = "Manage clan applications.";
$permissions['editApplication'] = "Edit the clan application questions.";
print("<table>\n");
print("<th>Yes</th><th>No</th><th>Description</th>\n");
foreach ($permissions as $permKey => $permDesc) {
print("<tr><td><input type=\"radio\" id=\"perrmission_" . $permKey . "1\" name=\"permission_" . $permKey . "\" value=\"1\" " . (($rank->checkPermission($permKey)) ? "checked=\"checked\"" : "") . " /></td><td><input type=\"radio\" id=\"permission_" . $permKey . "1\" name=\"permission_" . $permKey . "\" value=\"0\" " . ((!$rank->checkPermission($permKey)) ? "checked=\"checked\"" : "") . " /></td><td>" . $permDesc . "</td></tr>\n");
}
print("</table>\n");
print("<br /><button type=\"submit\" id=\"rankPermissionsSubmitButton\" name=\"rankPermissionsSubmitButton\">Save Permission</button>");
print("</form>\n");
// </editor-fold>
} else { // If we're on the rank list page
// <editor-fold defaultstate="collapsed" desc="Rank List Code">
if (isset($_POST['addRankButton'])) { // If the add rank form has been submitted
$errors = array();
if (!isset($_POST['rankName'])) {
$errors['name'][] = "Not set";
} else if (empty($_POST['rankName'])) {
$errors['name'][] = "Empty";
} else {
$name = $_mysql->real_escape_string($_POST['rankName']);
}
if (!isset($_POST['rankLevel'])) {
$errors['level'][] = "Not set";
} else if (empty($_POST['rankLevel'])) {
$errors['level'][] = "Empty";
} else if (!is_numeric($_POST['rankLevel'])) {
$errors['level'][] = "Not a number";
} else {
$level = $_mysql->real_escape_string($_POST['rankLevel']);
}
if (count($errors) > 0) { // If there were errors
// TODO: Output errors in a nice way
die("There were errors.");
} else { // There weren't any errors, add the new rank
$_mysql->query("INSERT INTO `ranks` (`name`, `level`, `permissions`) VALUES ('" . $name . "', " . $level . ", '" . serialize(array()) . "')");
}
}
print("<h1>Ranks</h1>");
$ranksQuery = $_mysql->query("SELECT * FROM `ranks`");
if ($ranksQuery->num_rows) { // If there is at least one rank
print("<table id=\"ranksTable\">\n");
print("<th>Rank</th>\n");
print("<th>Level</th>\n");
print("<th>Options</th>\n");
while ($rank = $ranksQuery->fetch_assoc()) {
print("<tr id=\"rank_" . $rank['id'] . "\">\n");
print("<td>" . $rank['name'] . "</td>\n");
print("<td>" . $rank['level'] . "</td>\n");
print("<td><button id=\"edit_" . $rank['id'] . "\" class=\"editRankButton\">Edit</button> <button id=\"delete_" . $rank['id'] . "\" class=\"deleteRankButton\">Delete</button></td>\n");
print("</tr>\n");
}
print("</table>\n");
} else {
print("There are no ranks.");
}
print("<hr />\n");
?>
<h2>Add Rank</h2>
<form id="addRankForm" method="post">
<table>
<th>Name</th>
<th>Level</th>
<tr>
<td><input type="text" name="rankName" id="rankName"/></td>
<td><select name="rankLevel" id="rankLevel"><?php
for ($i = 1; $i < 11; $i++) {
print("<option value=\"" . $i . "\">" . $i . "</option>\n");
}
?></select></td>
<td><button type="submit" name="addRankButton" id="addRankButton">Add Rank</button></td>
</tr>
</table>
</form>
<?php
// </editor-fold>
}
?> | true |
e1b1b66b8f89e5c68ff22cf5ddce56fe2dc8a535 | PHP | jesusangelmateos/empleados1920-22 | /empaltaemp.php | UTF-8 | 2,653 | 2.921875 | 3 | [] | no_license | <?php
require 'funciones.php';
$conn=conectarBD();
if (!isset($_POST) || empty($_POST)) {
/*Función que obtiene el DNI de los empleados de la empresa*/
$departamentos = obtenerDepartamentos($conn);
echo '<form action="" method="post"';
?>
<h1>ALTA EMPLEADO</h1><br><br>
<div>
DNI <input type='text' name='dni' value=''><br><br>
Nombre <input type='text' name='nombre' value=''><br><br>
Apellidos <input type='text' name='apellidos' value=''><br><br>
Fecha de nacimiento <input type='text' name='fechaNac' value=''><br><br>
Salario <input type='text' name='salario' value=''><br><br>
Fecha de alta <input type='text' name='fechaAlta' value=''><br><br>
Departamento<select name="departamento">
<?php foreach($departamentos as $departamento) : ?>
<option> <?php echo $departamento ?> </option>
<?php endforeach; ?></select><br><br>
</div>
<?php
echo '<div><input type="submit" value="Alta Empleado"></div>
</form>';
}
else{
set_error_handler("errores"); // Establecemos la funcion que va a tratar los errores
$dni=limpiar_campo($_REQUEST['dni']);
if($dni==""){
trigger_error('El campo no puede estar vacio');
}
$nombre=limpiar_campo($_REQUEST['nombre']);
if($nombre==""){
trigger_error('El campo no puede estar vacio');
}
$apellidos=limpiar_campo($_REQUEST['apellidos']);
if($apellidos==""){
trigger_error('El campo no puede estar vacio');
}
$fechaNac=limpiar_campo($_REQUEST['fechaNac']);
if($fechaNac==""){
trigger_error('El campo no puede estar vacio');
}
$salario=limpiar_campo($_REQUEST['salario']);
if($salario==""){
trigger_error('El campo no puede estar vacio');
}
$fechaAlta=limpiar_campo($_REQUEST['fechaAlta']);
if($fechaAlta==""){
trigger_error('El campo no puede estar vacio');
}
$sql = "INSERT INTO empleado (dni, nombre, apellidos, fecha_nac, salario) VALUES ('$dni', '$nombre', '$apellidos', '$fechaNac', '$salario')";
if(mysqli_query($conn, $sql)){
echo "Empleado insertado correctamente<br>";
}
else{
echo "error: " .$sql."<br>".mysqli_error($conn);
}
$departamento=$_POST['departamento'];
$sql = "SELECT cod_dpto FROM departamento WHERE nombre= '$departamento'";
$resultado=mysqli_query($conn, $sql);//el resultado no es valido, hay que tratarlo
$row=mysqli_fetch_assoc($resultado);
$codigo=$row['cod_dpto'];
$sql = "INSERT INTO emple_depart (dni, cod_dpto, fecha_ini) VALUES ('$dni', '$codigo', '$fechaAlta')";
if(mysqli_query($conn, $sql)){
echo "Empleado insertado en emple_depart";
}
else{
echo "error: " .$sql."<br>".mysqli_error($conn);
}
}
?> | true |
0532f2337be2b90fc5fefc46359e617bfb06a6a4 | PHP | kerem12345/IMSE-Project | /db_connection.php | UTF-8 | 333 | 2.609375 | 3 | [] | no_license | <?php
$servername = "localhost:3306";
$username = "root";
$password = "1111";
$db = "hotel";
// Create connection
$db = new mysqli($servername, $username, $password, $db);
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
//echo "Hello Hotel-DB :)";
?> | true |
1b917c60a3fa563fe5df4b013d409accabc0de5e | PHP | rahmuna/test | /tests/Stub/Clock.php | UTF-8 | 454 | 2.796875 | 3 | [] | no_license | <?php
declare(strict_types=1);
namespace FeeCalcApp\Stub;
use DateTime;
use FeeCalcApp\Helper\Clock\ClockInterface;
class Clock implements ClockInterface
{
private ?DateTime $dateTime = null;
public function getCurrentDateTime(): DateTime
{
return $this->dateTime ?? new DateTime();
}
public function setCurrentDateTime(DateTime $dateTime): self
{
$this->dateTime = $dateTime;
return $this;
}
}
| true |
a99aae5baeda8787eed485c70e3d73692ae8b306 | PHP | php-ddd/command | /src/Handler/CommandHandlerInterface.php | UTF-8 | 700 | 3.109375 | 3 | [
"MIT"
] | permissive | <?php
namespace PhpDDD\Command\Handler;
use PhpDDD\Command\CommandInterface;
/**
* A Command Handler aims to act on a specific command.
* To respect the single responsibility principle, we force one command handler to handle one and only one command.
*/
interface CommandHandlerInterface
{
/**
* Tells whether the command given in argument can be handle by this handler or not.
*
* @param string $commandClassName
*
* @return bool
*/
public function supports($commandClassName);
/**
* Process the command.
*
* @param CommandInterface $command
*
* @return mixed
*/
public function handle(CommandInterface $command);
}
| true |
64d5c224bcd7ff892fec9c15bccb48be0f6357df | PHP | itfan/android-and-php-zuijia-shijian | /hush-framework/hush-lib/Hush/Process/Storage.php | UTF-8 | 991 | 2.921875 | 3 | [] | no_license | <?php
/**
* Hush Framework
*
* @category Hush
* @package Hush_Process
* @author James.Huang <shagoo@gmail.com>
* @license http://www.apache.org/licenses/LICENSE-2.0
* @version $Id$
*/
/**
* @package Hush_Process
*/
abstract class Hush_Process_Storage
{
/**
* Create storage object
* @param string $engine Engine name (sysv, file)
* @return object
*/
public static function factory ($engine, $config = array())
{
$class_file = 'Hush/Process/Storage/' . ucfirst($engine) . '.php';
$class_name = 'Hush_Process_Storage_' . ucfirst($engine);
require_once $class_file; // include storage class
return new $class_name($config);
}
////////////////////////////////////////////////////////////////////////////////////////////////
// abstract methods
abstract public function get ($k);
abstract public function set ($k, $v);
abstract public function delete ($k);
abstract public function remove ();
} | true |
6137f12865d512d5905655925510eb19cdadb3f4 | PHP | Malopla/SDD-Project | /resources/database/install.php | UTF-8 | 4,897 | 2.59375 | 3 | [] | no_license | <?php
//The default password for all accounts created here is "admin"
try {
include 'db.php';
$users_tbl = "CREATE TABLE users
(
username VARCHAR(255) NOT NULL,
password VARCHAR(255) NOT NULL,
salt VARCHAR(255) NOT NULL,
PRIMARY KEY(username) )
ENGINE=INNODB";
$stmt = $dbconn->prepare($users_tbl);
$stmt->execute();
$profile_tbl = "CREATE TABLE profile
(
prid int AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255) NOT NULL,
firstname VARCHAR(255) NOT NULL,
lastname VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL,
phone VARCHAR(255) NOT NULL,
FOREIGN KEY (username) REFERENCES users(username)
)
ENGINE=INNODB";
$stmt = $dbconn->prepare($profile_tbl);
$stmt->execute();
$lost_found_tbl = "CREATE TABLE lost_found
(
pid INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255) NOT NULL,
found VARCHAR(255),
location VARCHAR(255),
message VARCHAR(255),
time timestamp NOT NULL DEFAULT NOW(),
FOREIGN KEY(username) REFERENCES users(username)
)
ENGINE=INNODB";
$stmt = $dbconn->prepare($lost_found_tbl);
$stmt->execute();
$locations_tbl = "CREATE TABLE locations
(
name VARCHAR(255) PRIMARY KEY
)
ENGINE=INNODB";
$stmt = $dbconn->prepare($locations_tbl);
$stmt->execute();
$permissions_tbl = "CREATE TABLE permissions
(
username VARCHAR(255) NOT NULL PRIMARY KEY,
del enum('true', 'false') NOT NULL,
twitter enum('true', 'false') NOT NULL,
FOREIGN KEY(username) REFERENCES users(username)
)
ENGINE=INNODB";
$stmt = $dbconn->prepare($permissions_tbl);
$stmt->execute();
$users_val = 'INSERT INTO users
VALUES
("Billy", "46fb40f176cc5d5595dffdc7a877c114c30ad8b5", "rZ1par%J)z@e#6L^$I!@DA4@rsnXN_5t"),
("Joe", "46fb40f176cc5d5595dffdc7a877c114c30ad8b5", "rZ1par%J)z@e#6L^$I!@DA4@rsnXN_5t"),
("Bob", "46fb40f176cc5d5595dffdc7a877c114c30ad8b5", "rZ1par%J)z@e#6L^$I!@DA4@rsnXN_5t"),
("admin", "46fb40f176cc5d5595dffdc7a877c114c30ad8b5", "rZ1par%J)z@e#6L^$I!@DA4@rsnXN_5t")';
$stmt = $dbconn->prepare($users_val);
$stmt->execute();
$profile_val = 'INSERT INTO profile
(
username, firstname, lastname, email, phone)
VALUES
("Billy", "John", "Root", "rootj2@rpi.edu", "518-482-1946"),
("Joe", "Wang", "Beer", "beerwang@rpi.edu", "518-557-3728"),
("Bob", "Bang", "Shang", "shangb@rpi.edu", "518-579-3829"),
("admin", "Stephen", "Tobolowsky", "tobos@rpi.edu", "518-555-2135")';
$stmt = $dbconn->prepare($profile_val);
$stmt->execute();
$lost_found_val = 'INSERT INTO lost_found
(username, found, location, message)
VALUES
("Billy", "Found", "Academy Hall", "green scarf of doom"),
("Joe", "Found", "Mueller Center", "orange peel of banana"),
("Joe", "Lost", "Nason Hall", "cell phone from 19th century"),
("Bob", "Found", "Hall Hall", "awesome stuff bro YOLOSWAG"),
("admin", "Found", "Barton Hall", "A carton of milk")';
$stmt = $dbconn->prepare($lost_found_val);
$stmt->execute();
$locations_val = 'INSERT INTO locations
VALUES
("87 Gymnasium"), ("Academy Hall"), ("Alumni House"), ("Amos Eaton Hall"), ("Barton Hall"),
("Biotechnology and Interdisciplinary Studies Building"), ("Bray Hall"), ("Burdett Residence Hall"),
("Carnegie Building"), ("Cary Hall"), ("Cogswell Laboratory"), ("Commons Dining Hall"),
("Crockett Hall"), ("Darrin Communications Center"), ("Davison Hall"), ("E Complex"),
("Experimental Media and Performing Arts Center"), ("Folsom Library"), ("Greene Building"),
("Hall Hall"), ("Java plus plus"), ("Jonsson Engineering Center"),
("Jonsson-rowland Science Center"), ("Lally Hall"), ("Low Center for Industrial Innovation"),
("Materials Research Center"), ("Mueller Center"), ("Nason Hall"), ("North Hall"), ("Nugent Hall"),
("Pittsburgh Building"), ("Playhouse"), ("Public Safety and Parking Access Offices"),
("Quadrangle Complex"), ("Rensselaer Union"), ("Rice Building"), ("Ricketts Building"), ("Robinson Pool"),
("Russell Sage Dining Hall"), ("Russell Sage Lab"), ("Sharp Hall"), ("Stacwyck"), ("Troy Building"),
("VCC"), ("Walker Laboratory"), ("Warren Hall"), ("West Hall")';
$stmt = $dbconn->prepare($locations_val);
$stmt->execute();
$permissions_val = "INSERT INTO permissions
VALUES
('Billy', 'false', 'false'),
('Joe', 'false', 'false'),
('Bob', 'false', 'false'),
('admin', 'true', 'true')";
$stmt = $dbconn->prepare($permissions_val);
$stmt->execute();
echo "Everything should be dandy.";
}
catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
?>
| true |
d57633c97e7964a31d00a6e814779c714df3a7fd | PHP | bread-tan/Blurbspot | /crawlForBio.php | UTF-8 | 735 | 2.515625 | 3 | [] | no_license | <?php
if(empty($_POST['q']))
return;
$bandname = $_POST['q'];
$handle = fopen("config/config.txt", "r");
$contents = fread($handle, filesize("config/config.txt"));
$configurations = explode("\r\n", $contents);
foreach($configurations as $config)
{
$parts = explode("=", $config);
if($parts[0] == "python")
$pythonSource = $parts[1];
}
$string = str_replace("\n", "<br>", shell_exec($pythonSource."python scripts\\biocrawler.py $bandname"));
// echo str_replace("\n", "<br>", $string);
preg_match_all("(http:[/][/][a-zA-Z0-9./]*)", $string, $matches);
foreach($matches[0] as $match)
{
$string = str_replace($match, "<a href='$match'><span style='color:#5555ee'>$match</span></a>", $string);
}
echo $string;
?> | true |
fb9a28037e2289234febce62764793855031daf7 | PHP | bsvm7/cs4380-final-project | /www/api/upload.php | UTF-8 | 6,297 | 2.8125 | 3 | [] | no_license | <?php
// Include reference to sensitive databse information
include("../../../../../db_security/security.php");
$db_user = constant("DB_USER");
$db_host = constant("DB_HOST");
$db_pass = constant("DB_PASS");
$db_database = constant("DB_DATABASE");
// First connect to the database using values from the included file
$db_conn = new mysqli($db_host, $db_user, $db_pass, $db_database);
if ($db_conn->error_code) {
debug_echo( "database connection error ..." . "\n" );
set_error_response( 400 , "I couldn't connect to the database -> " . $db_conn->connect_error);
die("The connection to the database failed: " . $db_conn->connect_error);
}
debug_echo( "database connected" . "\n" );
/*
$req_method = $_SERVER['REQUEST_METHOD'];
switch ($req_method) {
case 'POST':
// Get the raw post data
//$json_raw = file_get_contents("php://input");
//echo $json_raw;
//if ($decoded_json = json_decode($json_raw, true)) {
//$fileToUpload = $decoded_json['image'];
//$target_dir= "http://40.86.85.30/cs4380/content/images/";
//$target_file = $target_dir.basename($_FILES['your_photo']['name']);
*/
if(!isset($_FILES['your_photo'])) {
debug_echo ('Please select an Image'."\n");
break;
}
else{
$image= $_FILES['your_photo']['name'];
debug_echo ('Your original image is '.$image."\n");
$image_check = filesize($image);
debug_echo ("original image size is ".$$_FILES['your_photo']['tmp_name']."\n");
/*
if($image_check==false){
debug_echo ('Not a valid Image...');
break;
}
else{
*/
define ("MAX_SIZE","100");
$file_name= stripslashes($_FILES['your_photo']['name']);
$extension = getExtension($file_name);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) {
debug_echo ("Sorry! Unknown extension. Please JPG,JPEG,PNG and GIF only "."\n");
break;
}
else {
debug_echo ("Image extension is good at ".$extension);
$size=filesize($_FILES['your_photo']['tmp_name']);
debug_echo ("temp image is is ".$_FILES['your_photo']['tmp_name']."\n");
debug_echo ("Image size is ".$size."\n");
if ($size < MAX_SIZE*1024) {
//we will give an unique name, for example the time in unix time format
$image_name=time().'.'.$extension;
debug_echo ("temp Image name is ".$image_name."\n");
//the new name will be containing the full path where will be stored (images folder)
$newname="http://40.86.85.30/cs4380/content/images/".$image_name;
debug_echo ("new Image name url ".$newname."\n");
//we verify if the image has been uploaded, and print error instead
$copied = copy($_FILES['your_photo']['tmp_name'], $newname);
/*
if (!$copied)
{
debug_echo ("Sorry, The Photo Upload was unsuccessfull!"."\n");
break;
}
else{
*/
debug_echo ("file uploaded successfull!"."\n");
//Insert into database.Just use this particular variable "$image_name" when you are inserting into database
$insert_image_sql="INSERT INTO photograph (large_url) VALUES ( ? )";
if(!($insert_image_stmt=$db_conn->prepare($insert_image_sql))) {
debug_echo ("Sorry, insert image stmt prepare failed ... "."\n");
break;
}
if(!($insert_image_stmt->bind_param("s", $newname))) {
debug_echo ("Sorry, insert image stmt bind param failed ...!"."\n");
break;
}
if(!($insert_image_stmt->execute()) ) {
debug_echo ("Sorry, insert image stmt execute failed ...!"."\n");
break;
}
else{
debug_echo ("photo has been successfully uploaded... "."\n");
break;
}
}
else {
debug_echo ("You Have Exceeded The Photo Size Limit"."\n");
break;
}
}
// }
$db_conn->close();
debug_echo ("database has been closed successfully....."."\n");
}
/*
}
else{
set_error_response( 201, "SQL Error -> " . $hash_retrieve_stmt->error);
debug_echo ("input data can not be decoded.....");
break;
}
*/
/*
break;
default:
break;
}
*/
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) {
return "";
}
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
function debug_echo( $str ) {
$echo_debug = true;
if ($echo_debug) {
echo $str;
}
}
?> | true |
1b7af4b6c4373962c0ed78834a855dd7dd57d661 | PHP | opdavies/gmail-filter-builder | /tests/Unit/Console/Command/GenerateFiltersTest.php | UTF-8 | 2,755 | 2.546875 | 3 | [
"MIT"
] | permissive | <?php
namespace Opdavies\Tests\GmailFilterBuilder\Console\Command;
use Opdavies\GmailFilterBuilder\Console\Command\GenerateCommand;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Console\Tester\CommandTester;
use Symfony\Component\Filesystem\Filesystem;
class GenerateFiltersTest extends TestCase
{
const INPUT_FILENAME = __DIR__ . '/../../../fixtures/simple/input.php';
const OUTPUT_FILENAME = 'output.xml';
const TEST_OUTPUT_DIR = 'test';
/** @var CommandTester */
private $commandTester;
/** @var Filesystem */
private $fs;
protected function setUp()
{
parent::setUp();
$this->commandTester = new CommandTester(new GenerateCommand());
$this->fs = new Filesystem();
if (!$this->fs->exists(self::TEST_OUTPUT_DIR)) {
$this->fs->mkdir(self::TEST_OUTPUT_DIR);
}
chdir(self::TEST_OUTPUT_DIR);
}
protected function tearDown()
{
chdir('..');
$this->fs->remove(self::TEST_OUTPUT_DIR);
}
/** @test */
public function the_output_filename_matches_the_input_name()
{
$this->commandTester->execute([
'--input-file' => self::INPUT_FILENAME,
]);
$this->assertTrue($this->fs->exists('input.xml'));
}
/** @test */
public function the_output_filename_can_be_set_explicity()
{
$outputFilename = 'a-different-filename.xml';
$this->commandTester->execute([
'--input-file' => self::INPUT_FILENAME,
'--output-file' => $outputFilename,
]);
$this->assertTrue($this->fs->exists($outputFilename));
}
/** @test */
public function it_converts_filters_from_php_to_minified_xml()
{
$this->commandTester->execute([
'--input-file' => self::INPUT_FILENAME,
'--output-file' => self::OUTPUT_FILENAME,
]);
$this->assertTrue($this->fs->exists(self::OUTPUT_FILENAME));
$expected = file_get_contents(__DIR__ . '/../../../fixtures/simple/output.xml');
$result = file_get_contents(self::OUTPUT_FILENAME);
$this->assertEquals(trim($expected), $result);
}
/** @test */
public function it_converts_filters_from_php_to_expanded_xml()
{
$this->commandTester->execute([
'--input-file' => self::INPUT_FILENAME,
'--output-file' => self::OUTPUT_FILENAME,
'--expanded' => true,
]);
$this->assertTrue($this->fs->exists(self::OUTPUT_FILENAME));
$expected = file_get_contents(__DIR__ . '/../../../fixtures/simple/output-expanded.xml');
$result = file_get_contents(self::OUTPUT_FILENAME);
$this->assertEquals(trim($expected), $result);
}
}
| true |
8a5bf2eb2054d05a40514c003b63b86856d4adc0 | PHP | akbardhany/Project-Manajemen | /config/incoming-order.php | UTF-8 | 2,388 | 2.578125 | 3 | [] | no_license | <?php
require '../config/connection.php';
session_start();
if (empty($_SESSION['username'])){
header("Location:../login.php");
}else{
if ($_SESSION['username']) {
# echo "Log in as ".$_SESSION['username'];
}else {
header("Location:../login.php");
}
}
$selectstore = mysqli_query($connection, "SELECT user_shopname FROM user WHERE (`user_username` LIKE '%".$_SESSION['username']."%')");
if ($selectstore) {
while ($rowy = mysqli_fetch_assoc($selectstore)) {
$seller = $rowy['user_shopname'];
echo "--".$seller."--";
}
}
$myrequest = mysqli_query($connection, "SELECT * FROM request WHERE `product_seller` = '$seller' ORDER BY 1 DESC");
if ($myrequest) {
// output data of each row
echo '<div class="table-responsive">';
echo '<br />'.'<table class="table table-hover">';
echo '<thead>';
echo '<tr>';
echo '<td>'."ID".'</td>';
echo '<td>'."PRODUCT NAME".'</td>';
echo '<td>'."QUANTITY".'</td>';
echo '<td>'."TOTAL PRICE".'</td>';
echo '<td>'."NAME".'</td>';
echo '<td>'."PHONE".'</td>';
echo '<td>'."ADDRESS".'</td>';
echo '<td>'."SUB-DISTRICT".'</td>';
echo '<td>'."CITY".'</td>';
echo '<td>'."PROVINCE".'</td>';
echo '<td>'."COUNTRY".'</td>';
echo '<td>'."POSTAL CODE".'</td>';
echo '<td>'."TIME ORDER".'</td>';
echo '</tr>';
echo '<thead>';
while($row = mysqli_fetch_assoc($myrequest)) {
echo '<tbody>';
echo '<tr>';
echo '<td>'.$row["request_id"].'</td>';
echo '<td>'.$row["request_productname"].'</td>';
echo '<td>'.$row["request_quantity"].'</td>';
echo '<td>'.$row["request_totalprice"].'</td>';
echo '<td>'.$row["request_buyername"].'</td>';
echo '<td>'.$row["request_buyerphone"].'</td>';
echo '<td>'.$row["request_buyeraddress"].'</td>';
echo '<td>'.$row["request_buyersubdis"].'</td>';
echo '<td>'.$row["request_buyercity"].'</td>';
echo '<td>'.$row["request_buyerprovince"].'</td>';
echo '<td>'.$row["request_buyercountry"].'</td>';
echo '<td>'.$row["request_buyerpostalcode"].'</td>';
echo '<td>'.$row["request_time"].'</td>';
echo '</tr>';
echo '</tbody>';
}
echo '</table>';
echo '</div>';
}else{
echo "not selected yet";
}
mysqli_close($connection);
?>
| true |
91aec2f5e9ec8d0001c04065e544eb21a8759fc6 | PHP | fatman2021/phpstorm-plugin-piwikstorm | /testData/inspection/nonApi/allUsingNonApiCases/src/TestCases.php | UTF-8 | 2,323 | 2.78125 | 3 | [] | no_license | <?php
namespace Piwik\Plugins\MyPlugin;
use Piwik\Something\ClassWithApiMembers;
use Piwik\NonApiClass;
use Piwik\NonApiInterface;
use Piwik\Something\NonApiClass as SomethingNonApiClass;
use Piwik\Plugins\AnotherPlugin\NonApiClass as AnotherNonApiClass;
use Piwik\Something\NonApiClassImplementsApiInterface;
class MyTestClass
{
public function myMethod()
{
// class in Piwik namespace (w/o @api annotation) used
$nonApiClass = new NonApiClass();
$nonApiClass->property = 1;
$nonApiClass->doSomething();
NonApiClass::staticDoSomething();
// class in Piwik\Something namespace (w/o @api annotation) used
$somethingNonApiClass = new SomethingNonApiClass();
$somethingNonApiClass->property = 1;
$somethingNonApiClass->doSomething();
SomethingNonApiClass::staticDoSomething();
// class in Piwik\Plugins\AnotherPlugin namespace (w/o @api annotation) used
$anotherNonApiClass = new AnotherNonApiClass();
$anotherNonApiClass->property = 1;
$anotherNonApiClass->doSomething();
AnotherNonApiClass::staticDoSomething();
// non-api method/property use of class w/ some @api methods/properties
$classWithApiMembers = new ClassWithApiMembers();
$classWithApiMembers->nonApiProperty = 1;
$classWithApiMembers->nonApiDoSomethingElse();
ClassWithApiMembers::nonApiStaticDoSomething();
// non-api class that implements api interface used
$nonApiClassImplementsApi= new NonApiClassImplementsApiInterface();
$nonApiClassImplementsApi->property = 1;
$nonApiClassImplementsApi->doSomething();
NonApiClassImplementsApiInterface::staticDoSomething();
}
}
// test deriving from class that is not API
class MyDerived extends NonApiClass
{
// empty
}
// test deriving from API class and overriding non-API methods
class MyOtherDerived extends ClassWithApiMembers
{
public $nonApiProperty = 'other'; // TODO: this & below do not get reported. they should be.
public function nonApiDoSomethingElse()
{
// empty
}
public static function nonApiStaticDoSomething()
{
// empty
}
}
// test implementing non-API interface
class MyImplemented implements NonApiInterface
{
// empty
} | true |
1b04385ac886103942430ecdfb789c3b5c29fae4 | PHP | hung-nv/bdsmydinh | /protected/models/News.php | UTF-8 | 7,120 | 2.59375 | 3 | [] | no_license | <?php
/**
* This is the model class for table "news".
*
* The followings are the available columns in table 'news':
* @property integer $id
* @property string $title
* @property string $alias
* @property string $tag
* @property string $meta_title
* @property string $meta_description
* @property string $meta_keywords
* @property string $image
* @property string $description
* @property string $content
* @property string $keywords
* @property integer $view
* @property string $created_datetime
* @property string $updated_datetime
* @property integer $hot
* @property string $author
* @property integer $is_page
* @property integer $is_explain
* @property integer $is_question
* @property integer $status
*/
class News extends CActiveRecord {
public $parentId, $parentName, $parentAlias, $grandId;
/**
* @return string the associated database table name
*/
function setUrl() {
if ($this->is_page == 1)
$url = Yii::app()->createUrl('news/page', array('alias' => $this->alias));
else
$url = Yii::app()->createUrl('news/view', array('alias' => $this->alias));
return $url;
}
function setImageUrl() {
if (isset($this->image) && $this->image) {
return Yii::app()->request->baseUrl . '/uploads/news/' . $this->image;
}
}
function setShortDescription($leng = null) {
if(!$leng)
$leng = 150;
$array = explode(' ', substr(strip_tags($this->description), 0, $leng));
array_pop($array);
return implode(' ', $array) . '...';
}
function setShortTitle($leng) {
$title = substr(strip_tags($this->title), 0, $leng);
$array = explode(' ', $title);
array_pop($array);
return implode(' ', $array) . '...';
}
function setDescription() {
if (isset($this->description) && $this->description)
return $this->description;
else {
$desc = substr(strip_tags($this->content), 0, 300);
$arDesc = explode(' ', $desc);
array_pop($arDesc);
return implode(' ', $arDesc) . '[...]';
}
}
function setDate() {
return date('M d,Y', strtotime($this->created_datetime));
}
/**
* @return string the associated database table name
*/
public function tableName() {
return 'news';
}
/**
* @return array validation rules for model attributes.
*/
public function rules() {
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('title, alias, image, description, content, view, created_datetime', 'required'),
array('view, hot, is_page, is_explain, is_question, status', 'numerical', 'integerOnly' => true),
array('title, alias, tag, meta_title, meta_description, meta_keywords, image, keywords', 'length', 'max' => 255),
array('author', 'length', 'max' => 50),
array('updated_datetime', 'safe'),
// The following rule is used by search().
// @todo Please remove those attributes that should not be searched.
array('id, title, alias, tag, meta_title, meta_description, meta_keywords, image, description, content, keywords, view, created_datetime, updated_datetime, hot, author, is_page, is_explain, is_question, status', 'safe', 'on' => 'search'),
);
}
/**
* @return array relational rules.
*/
public function relations() {
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels() {
return array(
'id' => 'ID',
'title' => 'Title',
'alias' => 'Alias',
'tag' => 'Tag',
'meta_title' => 'Meta Title',
'meta_description' => 'Meta Description',
'meta_keywords' => 'Meta Keywords',
'image' => 'Image',
'description' => 'Description',
'content' => 'Content',
'keywords' => 'Keywords',
'view' => 'View',
'created_datetime' => 'Created Datetime',
'updated_datetime' => 'Updated Datetime',
'hot' => 'Hot',
'author' => 'Author',
'is_page' => 'Is Page',
'is_explain' => 'Is Explain',
'is_question' => 'Is Question',
'status' => 'Status',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
*
* Typical usecase:
* - Initialize the model fields with values from filter form.
* - Execute this method to get CActiveDataProvider instance which will filter
* models according to data in model fields.
* - Pass data provider to CGridView, CListView or any similar widget.
*
* @return CActiveDataProvider the data provider that can return the models
* based on the search/filter conditions.
*/
public function search() {
// @todo Please modify the following code to remove attributes that should not be searched.
$criteria = new CDbCriteria;
$criteria->compare('id', $this->id);
$criteria->compare('title', $this->title, true);
$criteria->compare('alias', $this->alias, true);
$criteria->compare('tag', $this->tag, true);
$criteria->compare('meta_title', $this->meta_title, true);
$criteria->compare('meta_description', $this->meta_description, true);
$criteria->compare('meta_keywords', $this->meta_keywords, true);
$criteria->compare('image', $this->image, true);
$criteria->compare('description', $this->description, true);
$criteria->compare('content', $this->content, true);
$criteria->compare('keywords', $this->keywords, true);
$criteria->compare('view', $this->view);
$criteria->compare('created_datetime', $this->created_datetime, true);
$criteria->compare('updated_datetime', $this->updated_datetime, true);
$criteria->compare('hot', $this->hot);
$criteria->compare('author', $this->author, true);
$criteria->compare('is_page', $this->is_page);
$criteria->compare('is_explain', $this->is_explain);
$criteria->compare('is_question', $this->is_question);
$criteria->compare('status', $this->status);
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
));
}
/**
* Returns the static model of the specified AR class.
* Please note that you should have this exact method in all your CActiveRecord descendants!
* @param string $className active record class name.
* @return News the static model class
*/
public static function model($className = __CLASS__) {
return parent::model($className);
}
}
| true |
0fb75c60394befab9993907ff616f4ba1fd22deb | PHP | madisvorklaev/vrakendused1 | /7_tagurpidilugeja.php | UTF-8 | 961 | 2.578125 | 3 | [] | no_license | /* <?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
?>
<!DOCTYPE html>
<head>
<style type="text/css">
</style>
<link type="text/css" rel="stylesheet" href="stiilifail.css" />
<meta charset="UTF-8">
<title>7.nädala harjutused</title>
</head>
<body>
<?php
// prints e.g. 'Current PHP version: 4.1.1'
echo 'Current PHP version: ' . phpversion();
// prints e.g. '2.0' or nothing if the extension isn't enabled
echo phpversion('tidy');
?>
<h2>Tagurpidilugeja</h2>
<?php
$text = 'The quick brown fox jumps over the lazy dog';
mb_internal_encoding( "UTF-8" );
mb_http_output( "UTF-8" );
ob_start("mb_output_handler");
$textLength = strlen($text);
$revText = "";
for ($i=strlen($text); $i>0; $i--){
$revText .= $text[$i-1];
};
echo $text;
echo '<br> </br>';
echo $revText
?>
<div class="kassid">
<p>See kõik tuleks loomulikult teha tekstisisestuse ja funktsiooniga...</p>
</div>
</body> | true |
b542e665a91f9afe9baab69392681f9a6774f6bf | PHP | code-generators/trident | /src/Builders/Crud/Controller.php | UTF-8 | 2,296 | 2.6875 | 3 | [
"MIT"
] | permissive | <?php
/**
* Tuhin Bepari <digitaldreams40@gmail.com>
*/
namespace j0hnys\Trident\Builders\Crud;
use Illuminate\Support\Facades\Storage;
class Controller
{
/**
* Controller Name prefix.
* If Model Name is User and no controller name is supplier then it will be User and then Controller will be appended.
* Its name will be UserController
* @var string
*/
protected $controllerName;
/**
* @var string
*/
protected $fileName = '';
/**
* Sub Path of the Controller.
* Generally Controller are stored in Controllers folder. But for grouping Controller may be put into folders.
* @var type
*/
public $path = '';
/**
* @var string
*/
protected $template;
protected $files;
/**
* @var array
*/
protected $only = ['index', 'show', 'create', 'store', 'edit', 'update', 'destroy'];
/**
* @var bool|string
*/
protected $parentModel;
/**
* ControllerCrud constructor.
* @param $model
* @param string $name
* @param array|string $only
* @param bool $api
* @param bool|\Illuminate\Database\Eloquent\Model $parent
* @internal param array $except
* @throws \Exception
*/
public function __construct($name = 'TEST')
{
$this->files = Storage::disk('local');
$path = base_path().'/app/Http/Controllers/'.$name.'.php';
if (file_exists($path)) {
return $this->error($name . ' already exists!');
}
$this->makeDirectory($path);
// $stub = $this->files->get(__DIR__ . '/../../Stubs/Crud/Controller.stub');
$stub = file_get_contents(base_path() . '/../../Stubs/Crud/Controller.stub');
$stub = str_replace('{{td_entity}}', $name, $stub);
file_put_contents($path, $stub);
// $this->info('Controller created successfully.');
}
/**
* Build the directory for the class if necessary.
*
* @param string $path
* @return string
*/
protected function makeDirectory($path)
{
if (!is_dir(dirname($path))) {
mkdir(dirname($path), 0777, true);
}
}
} | true |
db70012e704c404997abc5fce480ac098fb40cae | PHP | VedranSagodic/hellopp21 | /zadaci/zadatak7_08.php | UTF-8 | 359 | 3.265625 | 3 | [] | no_license | <?php
// Funkcija prima broj i vraća ukupan zbroj svih brojeva od 1
// do primljenog broja (uključujući primljeni broj)
// rekurzija
function zbroj($broj){
if($broj===1){
return 1;
}
return $broj-- + zbroj($broj);
}
// prvo slaže ovako
// 100 + 99 + 98 + ... + 2 + 1;
// a konkterno zbrajanje ide s desno na lijevo
echo zbroj(100);
| true |
cf3caca0c4a8b974fca4628cccc93ea16f472223 | PHP | NVerine/old | /src/entity/ObjectGUI.php | ISO-8859-1 | 3,464 | 3.09375 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: Cleiton
* Date: 25/01/2019
* Time: 11:01
*/
namespace src\entity;
abstract class ObjectGUI implements InterfaceGUI
{
public $handle;
// ------------------------------------------------------------------------------------------------------------------
// propriedades que fetch() alimenta
public $itens = array(); // um array de objetos
public $saldo; // para classes que implementam conta de saldo
// ------------------------------------------------------------------------------------------------------------------
// definir no construtor
public $header = array(); // lista com os nomes de campos (obrigatria)
public $header_abrev = array(); // lista alternativa com nomes abreviados
public $exibe = array(); // colunas a exibir por default nos relatrios
// ------------------------------------------------------------------------------------------------------------------
// definir na instncia
public $top; // limite de registros no fetch -- deve ser definido nas pesquisas, mas no em relatrios!
// informar toda a string, no s o valor. ex.: "TOP 500"
// ------------------------------------------------------------------------------------------------------------------
// filtros
public $pesquisa = array(); // filtros em pesquisa (falta padronizar nas extenses que tm as variveis $pesq_stuff)
public function __construct($handle = null)
{
}
// ------------------------------------------------------------------------------------------------------------------
/* FUNES COMPARTILHADAS
* mapeia os parmetros de pesquisa da pgina para este objeto
*/
public function setPesquisa()
{
foreach ($_REQUEST as $key => $value) {
if (strpos($key, "pesq_") !== false) {
$this->pesquisa[$key] = $value;
}
}
}
/* exportao automtica do contedo dos itens em JSON.
* isso facilitar um monte nossas integraes entre sistemas
*/
public function exportaJSON()
{
$json = array();
if (!empty($this->itens)) {
foreach ($this->itens as $item) {
$json_row = array();
foreach ($item as $key => $value) {
$json_row[$key] = $this->trataJSON($value);
}
array_push($json, $json_row);
}
}
return json_encode($json);
}
/* sanitiza valores para gerar JSON correto
* faz recurso de arrays e objetos (EXPERIMENTAL)
*/
private function trataJSON($var)
{
if (is_array($var) || is_object($var)) {
$json_row = array();
foreach ($var as $key => $value) {
$json_row[$key] = $this->trataJSON($value);
}
return $json_row;
} else {
$var = strip_tags($var, "<p><a><br><ul><li>");
$var = utf8_encode($var);
return $var;
}
}
/* wrapper para o retorno de getCampo que permite definir sem enumerar um switch
* (isso pode ser mais lento?)
*/
protected function campos($coluna, $itens)
{
return $itens[$coluna];
}
} | true |
fb9266965ff6f51e57666cb0e1f2b21d83b6b187 | PHP | antlogist/oop | /examples/basic/student/Student.php | UTF-8 | 1,031 | 3.765625 | 4 | [] | no_license | <?php
class Student {
public $marks = array();
function examResults($marks) {
// Check the entry data format
if(!is_array($marks)) {
echo "Entry data is not an array";
return;
}
$total = array_sum($marks);
// If array length less than 3
if (count($marks) < 3) {
echo "Insufficient data";
return;
}
// If array length more than 3
if (count($marks) > 3) {
echo "Redundant data";
return;
}
// Main loop
foreach ($marks as $key=>$mark) {
// If the mark less than 35
if ($mark < 35) {
echo "Exam failed! Total: $total :(";
return;
}
// If the mark more than 100
if ($mark > 100) {
$markNumber = ++$key;
echo "The $markNumber mark is a Wrong mark!";
return;
}
}
echo "Exam passed! Total: $total :)";
return;
}
}
$student = new Student();
$student->marks = array(35, 75, 35);
$student->examResults($student->marks);
?>
| true |
81d7977ebca8227fb94595de4ab88526ec15262d | PHP | jonphipps/registry2 | /app/Http/Controllers/ElementsController.php | UTF-8 | 4,828 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers;
use App\Element;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use App\Http\Requests\StoreElementsRequest;
use App\Http\Requests\UpdateElementsRequest;
use Yajra\Datatables\Datatables;
class ElementsController extends Controller
{
/**
* Display a listing of Element.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
if (! Gate::allows('element_access')) {
return abort(401);
}
if (request()->ajax()) {
$query = Element::query();
$table = Datatables::of($query);
$table->setRowAttr([
'data-entry-id' => '{{$id}}',
]);
$table->addColumn('massDelete', ' ');
$table->addColumn('actions', ' ');
$table->editColumn('actions', function ($row) {
$gateKey = 'element_';
$routeKey = 'elements';
return view('actionsTemplate', compact('row', 'gateKey', 'routeKey'));
});
$table->editColumn('name', function ($row) {
return $row->name ? $row->name : '';
});
$table->editColumn('label', function ($row) {
return $row->label ? $row->label : '';
});
$table->editColumn('uri', function ($row) {
return $row->uri ? $row->uri : '';
});
$table->editColumn('description', function ($row) {
return $row->description ? $row->description : '';
});
$table->editColumn('json', function ($row) {
return $row->json ? $row->json : '';
});
return $table->make(true);
}
return view('elements.index');
}
/**
* Show the form for creating new Element.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
if (! Gate::allows('element_create')) {
return abort(401);
}
return view('elements.create');
}
/**
* Store a newly created Element in storage.
*
* @param \App\Http\Requests\StoreElementsRequest $request
* @return \Illuminate\Http\Response
*/
public function store(StoreElementsRequest $request)
{
if (! Gate::allows('element_create')) {
return abort(401);
}
$element = Element::create($request->all());
return redirect()->route('elements.index');
}
/**
* Show the form for editing Element.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
if (! Gate::allows('element_edit')) {
return abort(401);
}
$element = Element::findOrFail($id);
return view('elements.edit', compact('element'));
}
/**
* Update Element in storage.
*
* @param \App\Http\Requests\UpdateElementsRequest $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(UpdateElementsRequest $request, $id)
{
if (! Gate::allows('element_edit')) {
return abort(401);
}
$element = Element::findOrFail($id);
$element->update($request->all());
return redirect()->route('elements.index');
}
/**
* Display Element.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
if (! Gate::allows('element_view')) {
return abort(401);
}
$relations = [
'translations' => \App\Translation::where('element_id', $id)->get(),
'statements' => \App\Statement::where('element_id', $id)->get(),
];
$element = Element::findOrFail($id);
return view('elements.show', compact('element') + $relations);
}
/**
* Remove Element from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
if (! Gate::allows('element_delete')) {
return abort(401);
}
$element = Element::findOrFail($id);
$element->delete();
return redirect()->route('elements.index');
}
/**
* Delete all selected Element at once.
*
* @param Request $request
*/
public function massDestroy(Request $request)
{
if (! Gate::allows('element_delete')) {
return abort(401);
}
if ($request->input('ids')) {
$entries = Element::whereIn('id', $request->input('ids'))->get();
foreach ($entries as $entry) {
$entry->delete();
}
}
}
}
| true |
f1f29bbd21705e6f05e9f8ccf35c576054008065 | PHP | dereckson/zed | /includes/story/hook_demo.php | UTF-8 | 1,984 | 2.84375 | 3 | [] | no_license | <?php
/**
* Story hook class: example code
*
* Zed. The immensity of stars. The HyperShip. The people.
*
* (c) 2010, Dereckson, some rights reserved.
* Released under BSD license.
*
* This class illustrates how to use the StoryHook class.
*
* @package Zed
* @subpackage Story
* @author Sébastien Santoro aka Dereckson <dereckson@espace-win.org>
* @copyright 2010 Sébastien Santoro aka Dereckson
* @license http://www.opensource.org/licenses/bsd-license.php BSD
* @version 0.1
* @link http://scherzo.dereckson.be/doc/zed
* @link http://zed.dereckson.be/
* @filesource
*/
$class = "DemoStoryHook";
/**
* Story hook demo class
*/
class DemoStoryHook extends StoryHook {
/**
* Initializes resources
*
* @see StoryHook::initialize
*
* The initialize method is called after the constructor and is mandatory,
* even if you've nothing to initialize, as it's an abstract method.
*/
function initialize () {}
/**
* Updates the current section description.
*
* @param string $description the description to update
* @see StoryHook::update_description
*
*/
function update_description (string &$description) {
//Performs the rot13 transform of the current description
$description = str_rot13($description);
//Appends a string to the current description
$description .= "\n\nWazzzzzzzzzzzzzzzzaaaaaaaaaaaaaaaaaaaaaa";
}
/**
* Updates the current section choices
*
* @param Array $links the section links
*@see StoryHook::get_choices_links
*
*/
function get_choices_links (array &$links) {
//Adds a link to /push
$links[] = [lang_get("PushMessage"), get_url('push')];
}
/**
* Adds content after our story content block
*
* @see StoryHook::add_html
*/
function add_html () {
//Adds a html block
return '<div class="black">Lorem ipsum dolor</div>';
}
}
| true |
3354d7f4a64c582d6e3b809698434a91bd328244 | PHP | flavioribeirojr/design-patterns-study | /Creational/AbstractFactory/LondonToyFactory.php | UTF-8 | 228 | 2.765625 | 3 | [] | no_license | <?php
class LondonToyFactory implements ToyFactory
{
public function makeMaze()
{
return new Toys\LondonMazeToy();
}
public function makePuzzle()
{
return new Toys\LondonPuzzleToy();
}
} | true |
65217ec9553aa6268c8c0f04bf544f80f1961d8d | PHP | vladkudinov89/bsa-2018-php-10 | /app/Mail/RateChanged.php | UTF-8 | 1,084 | 2.671875 | 3 | [] | no_license | <?php
namespace App\Mail;
use App\Entity\Currency;
use App\User;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class RateChanged extends Mailable
{
use Queueable, SerializesModels;
protected $user;
protected $currency;
protected $oldRate;
/**
* Create a new message instance.
* @param User $user
* @param Currency $currency
* @param float $oldRate
*/
public function __construct(User $user, Currency $currency, float $oldRate)
{
$this->user = $user;
$this->currency = $currency;
$this->oldRate = $oldRate;
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->view('emails.rate')
->with([
'userName' => $this->user->name,
'currencyName' => $this->currency->name,
'oldRate' => $this->oldRate,
'newRate' => $this->currency->rate,
]);
}
}
| true |
3920bfde381d0321d040975a070e69be13baf834 | PHP | ArneAmeye/laravel-stagevinder | /app/Services/SocialFacebookAccountService.php | UTF-8 | 2,120 | 2.796875 | 3 | [] | no_license | <?php
namespace App\Services;
use App\User;
use App\Student;
use Illuminate\Support\Facades\Hash;
use Laravel\Socialite\Contracts\User as ProviderUser;
use File;
class SocialFacebookAccountService
{
public function createOrGetUser(ProviderUser $providerUser)
{
//Check if user already exists from FB login
$account = Student::whereFacebookUserId($providerUser->getId())
->first();
if ($account) {
//User exists, return the user.
return $account->user;
} else {
//Get the user's FB picture
$profilePicture = file_get_contents($providerUser->getAvatar());
File::put(public_path() . '/images/students/profile_picture/' . $providerUser->getId() . ".jpg", $profilePicture);
$profilePictureName = $providerUser->getId() . ".jpg";
//User via FB does not exist, Make a new student account
$account = new Student([
'facebook_user_id' => $providerUser->getId(),
'firstname' => $providerUser->user['first_name'],
'lastname' => $providerUser->user['last_name'],
'profile_picture' => $profilePictureName
]);
//Check if this new FB user's email might already be registered through the manual register/login method, if so then associate with the newly created Student.
$user = User::whereEmail($providerUser->getEmail())->first();
//If this user is non-existant through our previous check, then create the User also before associating it with the newly create Student.
if (!$user) {
$user = User::create([
'email' => $providerUser->getEmail(),
'password' => Hash::make(rand(1,10000)),
]);
}
$account->user()->associate($user); //Associate both User and Student (linking user_id)
$account->save(); //Save to DB
return $user; //return user to handle login and session in SocialAuthFacebookController
}
}
} | true |
f068745ddf9826747bdab396dfdc6aa35d453f96 | PHP | PeeHaa/feedme | /src/Response/NewArticle.php | UTF-8 | 542 | 2.6875 | 3 | [
"MIT"
] | permissive | <?php declare(strict_types=1);
namespace PeeHaa\FeedMe\Response;
use PeeHaa\FeedMe\Entity\Article;
final class NewArticle implements Response
{
/** @var Article */
private $article;
public function __construct(Article $article)
{
$this->article = $article;
}
public function toJson(): string
{
return json_encode([
'requestId' => 'NewArticle',
'data' => [
'article' => $this->article->toArray(),
],
], JSON_THROW_ON_ERROR);
}
}
| true |
89ca06507d70c7d777f839a08fb9292388d5163d | PHP | ferch01991/BlogLaravel | /app/Http/routes.php | UTF-8 | 1,911 | 2.71875 | 3 | [
"MIT"
] | permissive | <?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
// Los tipos de rutas que podemos tener: GET, POST, DELETE, PUT, RESOURSE
Route::get('/', function () {
return view('welcome');
});
/*
Route::get('article', function(){
echo "Esta es la vista de article";
});
*/
/*
// Con esta ruta podemos pedir parametros
Route::get('article/{nombre}', function($nombre){
echo "El nombre que has colocado es: ".$nombre;
});
//Con este funcion decimos que no es obligatorio un nombre y le asignamos uno por defecto
Route::get('article/{nombre?}', function($nombre = "El parce"){
echo "El nombre que has colocado es: ".$nombre;
});
*/
//Vamos a agregar un grupo de rutas con el cual le asignamos un nombre como prefijo
Route::group(['prefix' => 'admin'], function(){
//funcion resouse: estilo de api Rest full, toma los metodos de un controlador y los define como un estilo de rutas
Route::resource('users','UsersController');
Route::get('users/{id}/destroy', [
'uses' => 'UsersController@destroy',
'as' => 'admin.users.destroy'
]);
Route::resource('categories', 'CategoriesController');
Route::get('categories/{id}/destroy', [
'uses' => 'CategoriesController@destroy',
'as' => 'admin.categories.destroy'
]);
});
Route::get('admin/auth/login', [
'uses' => 'Auth\AuthController@getLogin',
'as' => 'admin.auth.login'
]);
Route::post('admin/auth/login', [
'uses' => 'Auth\AuthController@postLogin',
'as' => 'admin.auth.login'
]);
Route::get('admin/auth/logout', [
'uses' => 'Auth\AuthController@getLogout',
'as' => 'admin.auth.logout'
]);
| true |
9a1d88da1bf8dd34f318cc5060dbc69177182387 | PHP | shurik2k5/sitemap | /src/File.php | UTF-8 | 10,162 | 2.890625 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
/**
* @link https://github.com/yii2tech
* @copyright Copyright (c) 2015 Yii2tech
* @license [New BSD License](http://www.opensource.org/licenses/bsd-license.php)
*/
namespace yii2tech\sitemap;
use yii\base\InvalidArgumentException;
/**
* File is a helper to create the site map XML files.
* Example:
*
* ```php
* use yii2tech\sitemap\File;
*
* $siteMapFile = new File();
* $siteMapFile->writeUrl(['site/index']);
* $siteMapFile->writeUrl(['site/contact'], ['priority' => '0.4']);
* $siteMapFile->writeUrl('http://mydomain.com/mycontroller/myaction', [
* 'lastModified' => '2012-06-28',
* 'changeFrequency' => 'daily',
* 'priority' => '0.7'
* ]);
* ...
* $siteMapFile->close();
* ```
*
* @see BaseFile
* @see http://www.sitemaps.org/
*
* @author Paul Klimov <klimov.paul@gmail.com>
* @since 1.0
*/
class File extends BaseFile
{
// Check frequency constants:
const CHECK_FREQUENCY_ALWAYS = 'always';
const CHECK_FREQUENCY_HOURLY = 'hourly';
const CHECK_FREQUENCY_DAILY = 'daily';
const CHECK_FREQUENCY_WEEKLY = 'weekly';
const CHECK_FREQUENCY_MONTHLY = 'monthly';
const CHECK_FREQUENCY_YEARLY = 'yearly';
const CHECK_FREQUENCY_NEVER = 'never';
/**
* {@inheritdoc}
*/
public $rootTag = [
'xmlns' => 'http://www.sitemaps.org/schemas/sitemap/0.9',
];
/**
* @var array default options for {@see writeUrl()}.
*/
public $defaultOptions = [];
/**
* {@inheritdoc}
*/
public function init()
{
parent::init();
if (!empty($this->rootTag) && !isset($this->rootTag['tag'])) {
$this->rootTag['tag'] = 'urlset';
}
}
/**
* Writes the URL block into the file.
* @param string|array $url page URL or params.
* @param array $options options list, valid options are:
*
* - 'lastModified' - string|int, last modified date in format Y-m-d or timestamp.
* - 'changeFrequency' - string, page change frequency, the following values can be passed:
*
* * always
* * hourly
* * daily
* * weekly
* * monthly
* * yearly
* * never
*
* You may use constants defined in this class here.
* - 'priority' - string|float URL search priority in range 0..1
* - 'images' - array list of images bound to the URL, {@see composeImage()} for details.
* - 'videos' - array list of videos bound to the URL, {@see composeVideo()} for details.
*
* @param string|null $extraContent extra XML content to be placed inside 'url' tag.
* @return int the number of bytes written.
*/
public function writeUrl($url, array $options = [], $extraContent = null)
{
$this->incrementEntriesCount();
if (!is_string($url)) {
$url = $this->getUrlManager()->createAbsoluteUrl($url);
}
$xmlCode = '<url>';
$xmlCode .= "<loc>{$url}</loc>";
if (($unrecognizedOptions = array_diff(array_keys($options), ['lastModified', 'changeFrequency', 'priority', 'images', 'videos'])) !== []) {
throw new InvalidArgumentException('Unrecognized options: ' . implode(', ', $unrecognizedOptions));
}
$options = array_merge($this->defaultOptions, $options);
if (isset($options['lastModified']) && ctype_digit($options['lastModified'])) {
$options['lastModified'] = date('Y-m-d', $options['lastModified']);
}
if (isset($options['lastModified'])) {
$xmlCode .= '<lastmod>' . $this->normalizeDateValue($options['lastModified']) . '</lastmod>';
}
if (isset($options['changeFrequency'])) {
$xmlCode .= '<changefreq>' . $options['changeFrequency'] . '</changefreq>';
}
if (isset($options['priority'])) {
$xmlCode .= '<priority>' . $options['priority'] . '</priority>';
}
if (!empty($options['images'])) {
foreach ($options['images'] as $image) {
$xmlCode .= $this->lineBreak . $this->composeImage($image);
}
}
if (!empty($options['videos'])) {
foreach ($options['videos'] as $video) {
$xmlCode .= $this->lineBreak . $this->composeVideo($video);
}
}
if ($extraContent !== null) {
$xmlCode .= $extraContent;
}
$xmlCode .= '</url>';
return $this->write($xmlCode);
}
/**
* Creates XML code for image tag.
* @see https://www.google.com/schemas/sitemap-image/1.1/
*
* @param array $image image options, valid options are:
*
* - 'url' - string
* - 'title' - string
* - 'caption' - string
* - 'geoLocation' - string
* - 'license' - string
*
* @return string XML code.
* @since 1.1.0
*/
protected function composeImage(array $image)
{
$xmlCode = '<image:image>';
$xmlCode .= '<image:loc>' . $image['url'] . '</image:loc>';
if (isset($image['title'])) {
$xmlCode .= '<image:title>' . $image['title'] . '</image:title>';
}
if (isset($image['caption'])) {
$xmlCode .= '<image:caption>' . $image['caption'] . '</image:caption>';
}
if (isset($image['geoLocation'])) {
$xmlCode .= '<image:geo_location>' . $image['geoLocation'] . '</image:geo_location>';
}
if (isset($image['license'])) {
$xmlCode .= '<image:license>' . $image['license'] . '</image:license>';
}
$xmlCode .= '</image:image>';
return $xmlCode;
}
/**
* Creates XML code for video tag.
* @see https://www.google.com/schemas/sitemap-video/1.1/
*
* @param array $video video options, valid options are:
*
* - 'thumbnailUrl' - string, URL to the thumbnail
* - 'title' - string, video page title
* - 'description' - string, video page meta description
* - 'contentUrl' - string
* - 'duration' - int|string, video length in seconds
* - 'expirationDate' - string|int
* - 'rating' - string
* - 'viewCount' - string|int
* - 'publicationDate' - string|int
* - 'familyFriendly' - string
* - 'requiresSubscription' - string
* - 'live' - string
* - 'player' - array, options:
*
* * 'url' - string, URL to raw video clip
* * 'allowEmbed' - bool|string
* * 'autoplay' - bool|string
*
* - 'restriction' - array, options:
*
* * 'relationship' - string
* * 'restriction' - string
*
* - 'gallery' - array, options:
*
* * 'title' - string
* * 'url' - string
*
* - 'price' - array, options:
*
* * 'currency' - string
* * 'price' - string|float
*
* - 'uploader' - array, options:
*
* * 'info' - string
* * 'uploader' - string
*
* @return string XML code.
* @since 1.1.0
*/
protected function composeVideo(array $video)
{
$xmlCode = '<video:video>';
if (isset($video['thumbnailUrl'])) {
$xmlCode .= '<video:thumbnail_loc>' . $video['thumbnailUrl'] . '</video:thumbnail_loc>';
}
if (isset($video['title'])) {
$xmlCode .= '<video:title><![CDATA[' . $video['title'] . ']]></video:title>';
}
if (isset($video['description'])) {
$xmlCode .= '<video:description><![CDATA[' . $video['description'] . ']]></video:description>';
}
if (isset($video['contentUrl'])) {
$xmlCode .= '<video:content_loc>' . $video['contentUrl'] . '</video:content_loc>';
}
if (isset($video['duration'])) {
$xmlCode .= '<video:duration>' . $video['duration'] . '</video:duration>';
}
if (isset($video['expirationDate'])) {
$xmlCode .= '<video:expiration_date>' . $this->normalizeDateValue($video['expirationDate']) . '</video:expiration_date>';
}
if (isset($video['rating'])) {
$xmlCode .= '<video:rating>' . $video['rating'] . '</video:rating>';
}
if (isset($video['viewCount'])) {
$xmlCode .= '<video:view_count>' . $video['viewCount'] . '</video:view_count>';
}
if (isset($video['publicationDate'])) {
$xmlCode .= '<video:publication_date>' . $this->normalizeDateValue($video['publicationDate']) . '</video:publication_date>';
}
if (isset($video['familyFriendly'])) {
$xmlCode .= '<video:family_friendly>' . $video['familyFriendly'] . '</video:family_friendly>';
}
if (isset($video['requiresSubscription'])) {
$xmlCode .= '<video:requires_subscription>' . $video['requiresSubscription'] . '</video:requires_subscription>';
}
if (isset($video['live'])) {
$xmlCode .= '<video:live>' . $video['live'] . '</video:live>';
}
if (isset($video['player'])) {
$xmlCode .= '<video:player_loc allow_embed="' . $this->normalizeBooleanValue($video['player']['allowEmbed']) . '" autoplay="' . $this->normalizeBooleanValue($video['player']['autoplay']) . '">'
. $video['player']['url']
. '</video:player_loc>';
}
if (isset($video['restriction'])) {
$xmlCode .= '<video:restriction relationship="' . $video['restriction']['relationship'] . '">' . $video['restriction']['restriction'] . '</video:restriction>';
}
if (isset($video['gallery'])) {
$xmlCode .= '<video:gallery_loc title="' . $video['gallery']['title'] . '">' . $video['gallery']['url'] . '</video:gallery_loc>';
}
if (isset($video['price'])) {
$xmlCode .= '<video:price currency="' . $video['price']['currency'] . '">' . $video['price']['price'] . '</video:price>';
}
if (isset($video['uploader'])) {
$xmlCode .= '<video:uploader info="' . $video['uploader']['info'] . '">' . $video['uploader']['uploader'] . '</video:uploader>';
}
$xmlCode .= '</video:video>';
return $xmlCode;
}
}
| true |
b2c01cb8e793f2703eeff4039f0543028a054a11 | PHP | vgates/Campus-Infocom | /photo.php | UTF-8 | 849 | 2.875 | 3 | [] | no_license | <?php
class photoClass
{
function photo($newwidth,$newheight,$newname,$oldname)
{
if ($_FILES["file"]["error"] > 0)
$msg = "Return Code: " . $_FILES["file"]["error"] . "<br />";
else
{
$photo=$oldname.".jpg";
if (file_exists("upload/".$photo))
{
$xxff="upload/".$photo;
unlink($xxff);
}
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
list($width,$height)=getimagesize($uploadedfile);
//$newwidth=150;
//$newheight=180;
$tmp=imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
$filename = "upload/". $newname;
imagejpeg($tmp,$filename,100);
imagedestroy($src);
imagedestroy($tmp);
return $filename;
}
}
}
?> | true |
a679e70703bbe2c00344f4513cbafd58da1a8645 | PHP | alessandroverao/likeTiziana | /php/agrega_cliente.php | UTF-8 | 2,451 | 2.546875 | 3 | [] | no_license | <?php
include('../php/conexion.php');
$id = $_POST['id-clien'];
$proceso = $_POST['pro'];
$nombre = $_POST['nombre'];
$tipo = $_POST['tipo'];
$direccion = $_POST['direccion'];
$celular = $_POST['celular'];
$fecha = date('Y-m-d');
$cuil = $_POST['cuil'];
$email = $_POST['email'];
//VERIFICAMOS EL PROCESO
$sql = "SELECT * FROM tipoclientes WHERE tipo_cliente_tipo = '$tipo'";
$result = mysql_query($sql);
$registro = mysql_fetch_assoc($result);
$idtipo = $registro['id_tipo_client'];
switch($proceso){
case 'Registro':
mysql_query("INSERT INTO clientes (nomb_clien, tipo_clien, direccion_clien, celular_clien, fecha_reg_clien, cuil_clien, email_clien)VALUES('$nombre','$idtipo','$direccion','$celular', '$fecha', '$cuil', '$email')");
break;
case 'Edicion':
mysql_query("UPDATE clientes SET nomb_clien = '$nombre', tipo_clien = '$idtipo', direccion_clien = '$direccion', celular_clien = '$celular', cuil_clien = '$cuil', email_clien = '$email' WHERE id_clien = '$id'");
break;
}
//ACTUALIZAMOS LOS REGISTROS Y LOS OBTENEMOS
$registro = mysql_query("SELECT * FROM clientes, tipoclientes WHERE tipo_clien = id_tipo_client ORDER BY nomb_clien ASC");
//CREAMOS NUESTRA VISTA Y LA DEVOLVEMOS AL AJAX
echo '<table class="table table-striped table-condensed table-hover">
<tr>
<th width="300">Nombre</th>
<th width="200">Tipo</th>
<th width="300">Dirección</th>
<th width="200">Celular</th>
<th width="150">F. Registro</th>
<th width="200">CUIL</th>
<th width="300">Email</th>
<th width="50">Opciones</th>
</tr>';
while($registro2 = mysql_fetch_array($registro)){
echo '<tr>
<td>'.$registro2['nomb_clien'].'</td>
<td>'.$registro2['tipo_cliente_tipo'].'</td>
<td>'.$registro2['direccion_clien'].'</td>
<td>'.$registro2['celular_clien'].'</td>
<td>'.fechaNormal($registro2['fecha_reg_clien']).'</td>
<td>'.$registro2['cuil_clien'].'</td>
<td>'.$registro2['email_clien'].'</td>
<td><a style="font-size: 20px;" href="javascript:editarCliente('.$registro2['id_clien'].');" class="glyphicon glyphicon-edit"></a> <a style="font-size: 20px;" href="javascript:eliminarCliente('.$registro2['id_clien'].');" class="glyphicon glyphicon-remove-circle"></a></td>
</tr>';
}
echo '</table>';
?> | true |
9f97a1ddb219507db3f90df0602288e9545f3942 | PHP | 2rch/Turch-MyLog | /src/MyLogger.php | UTF-8 | 2,234 | 2.703125 | 3 | [] | no_license | <?php
namespace vendor\Turch;
use Monolog\DateTimeImmutable;
class MyLogger implements LoggerInterface
{
public string $name;
public static string $WrongId;
private bool $microsecondTimestamps = true;
protected $timezone;
public function __construct(string $name = '')
{
$this->name = $name;
}
public function emergency($message, array $context = array())
{
$this->log(LogLevel::EMERGENCY, $message, $context);
}
public function alert($message, array $context = array())
{
$this->log(LogLevel::ALERT, $message, $context);
}
public function critical($message, array $context = array())
{
$this->log(LogLevel::CRITICAL, $message, $context);
}
public function error($message, array $context = array())
{
$this->log(LogLevel::ERROR, $message, $context);
}
public function warning($message, array $context = array())
{
$this->log(LogLevel::WARNING, $message, $context);
}
public function notice($message, array $context = array())
{
$this->log(LogLevel::NOTICE, $message, $context);
}
public function info($message, array $context = array())
{
$this->log(LogLevel::INFO, $message, $context);
}
public function debug($message, array $context = array())
{
$this->log(LogLevel::DEBUG, $message, $context);
}
/**
* @param mixed $level
* @param string $message
* @param array|null $context
* @return bool
* @throws \Exception
*/
public function log($level, $message, array $context = array())
{
if ($this->name === '') {
$handle = fopen(__DIR__ . "/logs/Logs.txt", 'a');
$date = date('Y-m-d h:i:s');
$context = implode(',', $context);
$message = (
"Date:". new DateTimeImmutable($this->microsecondTimestamps, $this->timezone) . "\n
Level: {$level}\n
Message: {$message}\n
Context: {$context}\n
______________________\n"
);
fwrite($handle, $message);
fclose($handle);
self::$WrongId = $context;
}
}
}
| true |
2a179f92ac87819e5a4760f46abb2521d83f6b9c | PHP | xiaohongyang/work_clock | /app/WorkClock.php | UTF-8 | 976 | 2.65625 | 3 | [
"MIT"
] | permissive | <?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class WorkClock extends Model
{
//
public $table = 'loaddata_worktime';
public function getForMonth($month, $year=null){
$year = is_null($year) ? date('Y', time()) : $year;
$dateBegin = $year.'-'.$month.'-'.'01';
$dateEnd = $year.'-'.$month.'-'.'31';
return $this->getDataForDateRange($dateBegin, $dateEnd);
}
//指定开始日期到指定结束日期的考情时间
public function getDataForDateRange($dateBegin, $dateEnd=null){
if(is_null($dateBegin) && is_null($dateEnd))
return [];
$query = $this->where('clocktime', '!=', null);
if(!is_null($dateBegin)){
$query->where('clocktime', '>=', $dateBegin);
}
if(!is_null($dateEnd)){
$query->where('clocktime', '<=', $dateEnd);
}
$query->orderBy('clocktime', 'asc');
return $query->get();
}
}
| true |
b1e5d64e617fd8f33c672b9eb006c42285f628cb | PHP | milkcreation/presstify-events | /Query.php | UTF-8 | 8,688 | 2.59375 | 3 | [] | no_license | <?php
namespace tiFy\Plugins\Events;
class Query
{
/* = CONSTRUCTEUR = */
public function __construct()
{
add_filter( 'query_vars', array( $this, 'query_vars' ), 1 );
add_filter( 'posts_clauses', array( $this, 'posts_clauses' ), 99, 2 );
add_filter( 'posts_results', array( $this, 'posts_results' ), 10, 2 );
}
/** == Définition des variables de requête == **/
final public function query_vars( $aVars )
{
$aVars[] = 'tyevquery'; // all | uniq | none
$aVars[] = 'tyevfrom';
$aVars[] = 'tyevto';
$aVars[] = 'tyevorder'; // defaut 1 | 0 permet de désactiver le forçage de l'ordonnacement des éléments par date de début
return $aVars;
}
/** == Modification des condition de requête == **/
final public function posts_clauses( $pieces, $query )
{
//Bypass
if( is_admin() && ! defined( 'DOING_AJAX' ) )
return $pieces;
/// La requête est désactivée
if( $query->get( 'tyevquery' ) === 'none' )
return $pieces;
/// La requête ne cible aucun type de post
if( ! $post_types = $query->get( 'post_type' ) )
return $pieces;
// Traitement des types de post
if( is_string( $post_types ) )
$post_types = array_map( 'trim', explode( ',', $post_types ) );
/// La requête ne doit contenir des types de post déclarés en tant qu'événement
if( in_array( 'any', $post_types ) )
return $pieces;
if( array_diff( $post_types, Events::GetPostTypes() ) )
return $pieces;
global $wpdb;
extract( $pieces );
// Récupération des arguments de contruction de la requête
$Db = tify_db_get( 'tify_events' );
$show = ( ( $_show = $query->get( 'tyevquery' ) ) && in_array( $_show, array( 'all', 'uniq' ) ) ) ? $_show : 'uniq';
$from = ( $_from = $query->get( 'tyevfrom' ) ) ? $_from : current_time( 'mysql' );
$to = ( $_to = $query->get( 'tyevto' ) ) ? $_to : false;
$fields .= ", '{$show}' as tyevquery,'{$from}' as tyevfrom";
if( $to )
$fields .= ",'{$to}' as tyevto";
if( $query->is_singular() ) :
$fields .= ", tify_events.event_id, MIN(tify_events.event_start_datetime) as event_start_datetime, MAX(tify_events.event_end_datetime) as event_end_datetime, GROUP_CONCAT(tify_events.event_start_datetime, '|', tify_events.event_end_datetime ORDER BY tify_events.event_start_datetime ASC) as event_date_range";
else :
$fields .= ", tify_events.event_id, tify_events.event_start_datetime, tify_events.event_end_datetime";
endif;
$join .= " INNER JOIN ". $Db->Name ." as tify_events ON ( $wpdb->posts.ID = tify_events.event_post_id )";
if( ! $query->is_singular() ) :
if( $show === 'uniq' ) :
$inner_where = "SELECT MIN( event_start_datetime ) FROM ". $Db->Name ." WHERE 1";
$inner_where .= " AND event_post_id = {$wpdb->posts}.ID";
$inner_where .= " AND event_end_datetime >= '{$from}'";
if( $to )
$inner_where .= " AND event_start_datetime <= '{$to}'";
$where .= " AND tify_events.event_start_datetime IN ( {$inner_where} )";
// Éviter les doublons lorsqu'un événement à deux dates de démarrage identiques
$groupby = "tify_events.event_post_id";
else :
$where .= " AND tify_events.event_end_datetime >= '{$from}'";
if( $to )
$where .= " AND event_start_datetime <= '{$to}'";
// Autoriser les doublons
$groupby = false;
endif;
if( $query->get( 'tyevorder', true ) )
$orderby = "tify_events.event_start_datetime ASC";
endif;
$_pieces = array( 'where', 'groupby', 'join', 'orderby', 'distinct', 'fields', 'limits' );
//var_dump( compact ( $_pieces ) ); exit;
return compact ( $_pieces );
}
/** == == **/
public function posts_results( $posts, $query )
{
foreach( $posts as $k => $p ) :
if( ! $p->ID )
unset( $posts[$k] );
endforeach;
return $posts;
}
/* = CONTROLEUR = */
/** == Récupération des événements liés à un contenu == **/
public static function PostGetEvents( $post = 0, $args = array() )
{
// Bypass
if( ! $post = get_post( $post ) )
return;
// Traitement des arguments de requête
$defaults = array(
'orderby' => 'start_datetime',
'order' => 'ASC'
);
$args = wp_parse_args( $defaults, $args );
$args['post_id'] = $post->ID;
return tify_db_get( 'tify_events' )->select()->rows( $args );
}
/** == Récupération des dates liées à un contenu == **/
public static function PostGetDates( $post = 0, $args = array() )
{
// Bypass
if( ! $post = get_post( $post ) )
return;
if( ! $events = self::PostGetEvents( $post, $args ) )
return;
$dates = array();
foreach( (array) $events as $n => $event ) :
if( $_dates = self::EventParseAttrs( $event ) ) :
foreach( $_dates as $_date ) :
array_push( $dates, $_date );
endforeach;
endif;
endforeach;
return $dates;
}
/** == Récupération des attributs de date lié à un événement == **/
public static function GetEvent( $event_id )
{
return tify_db_get( 'tify_events' )->select()->row_by_id( $event_id );
}
/** == Traitement des attributs d'un événement == **/
public static function EventParseAttrs( $event )
{
$split = \tiFy\Plugins\Events\Events::GetPostTypeAttr( get_post_type( $event->event_post_id ), 'split' );
$date = array();
$k = 0;
$s = new \DateTime( $event->event_start_datetime ); $e = new \DateTime( $event->event_end_datetime );
// Le jour de fin est identique au jour de début
if( $s->format( 'Ymd' ) === $e->format( 'Ymd' ) ) :
$date[$k]['event_id'] = $event->event_id;
$date[$k]['post_id'] = $event->event_post_id;
$date[$k]['start_date'] = $s->format( 'Y-m-d' );
$date[$k]['end_date'] = false;
if( $s->format( 'Hi' ) === $e->format( 'Hi' ) ) :
$date[$k]['start_time'] = $s->format( 'H:i:s' );
$date[$k]['end_time'] = false;
else :
$date[$k]['start_time'] = $s->format( 'H:i:s' );
$date[$k]['end_time'] = $e->format( 'H:i:s' );
endif;
// Le jour de début est supérieur au jour de fin et ça c'est pas bien
elseif( $s->format( 'Ymd' ) > $e->format( 'Ymd' ) ) :
$date[$k]['event_id'] = $event->event_id;
$date[$k]['post_id'] = $event->event_post_id;
$date[$k]['start_date'] = $s->format( 'Y-m-d' );
$date[$k]['end_date'] = false;
if( $s->format( 'Hi' ) === $e->format( 'Hi' ) ) :
$date[$k]['start_time'] = $s->format( 'H:i:s' );
$date[$k]['end_time'] = false;
else :
$date[$k]['start_time'] = $s->format( 'H:i:s' );
$date[$k]['end_time'] = $e->format( 'H:i:s' );
endif;
//
else :
$sdiff = new \DateTime( $s->format( 'Y-m-d' ) );
$ediff = new \DateTime( $e->format( 'Y-m-d' ) );
$diff = $sdiff->diff( $ediff );
if( $split == -1 )
$split = $diff->days;
if( $diff->days && $diff->days <= $split ) :
foreach( range( 0, $diff->days, 1 ) as $n ) :
if( $n )
$s->add( new \DateInterval( 'P1D' ) );
$date[$n]['event_id'] = $event->event_id;
$date[$n]['post_id'] = $event->event_post_id;
$date[$n]['start_date'] = $s->format( 'Y-m-d' );
$date[$n]['end_date'] = false;
if( $s->format( 'Hi' ) == $e->format( 'Hi' ) ) :
$date[$n]['start_time'] = $s->format( 'H:i:s' );
$date[$n]['end_time'] = false;
else :
$date[$n]['start_time'] = $s->format( 'H:i:s' );
$date[$n]['end_time'] = $e->format( 'H:i:s' );
endif;
endforeach;
else :
$date[$k]['event_id'] = $event->event_id;
$date[$k]['post_id'] = $event->event_post_id;
$date[$k]['start_date'] = $s->format( 'Y-m-d' );
$date[$k]['end_date'] = $e->format( 'Y-m-d' );
if( $s->format( 'Hi' ) == $e->format( 'Hi' ) ) :
$date[$k]['start_time'] = $s->format( 'H:i:s' );
$date[$k]['end_time'] = false;
else :
$date[$k]['start_time'] = $s->format( 'H:i:s' );
$date[$k]['end_time'] = $e->format( 'H:i:s' );
endif;
endif;
endif;
return $date;
}
/** == Calcul le nombre d'événements d'une plage == **/
public static function RangeCount( $from, $to )
{
global $wpdb;
$timezone_string = get_option( 'timezone_string' );
$from = new \DateTime( $from, new \DateTimeZone( $timezone_string ) );
$to = new \DateTime( $to, new \DateTimeZone( $timezone_string ) );
return $wpdb->get_var(
$wpdb->prepare(
"SELECT COUNT(event_id)".
" FROM {$wpdb->tify_events}".
" WHERE (".
" ( UNIX_TIMESTAMP(event_start_datetime) BETWEEN %d AND %d )".
" OR ( UNIX_TIMESTAMP(event_end_datetime) BETWEEN %d AND %d )".
")",
$from->getTimestamp(),
$to->getTimestamp(),
$from->getTimestamp(),
$to->getTimestamp()
)
);
}
} | true |
429b48225fa7125452977f536e2636b1a22bcc61 | PHP | Symfony-Plugins/csDoctrineSlideshowPlugin | /lib/widget/sfWidgetFormJQuerySortableListMany.class.php | UTF-8 | 1,924 | 2.578125 | 3 | [
"MIT"
] | permissive | <?php
/**
*
*/
class sfWidgetFormJQuerySortableListMany extends sfWidgetFormJQuerySortableList
{
public function addRelationsOptions($options)
{
foreach (Doctrine::getTable(get_class($options['object']))->getRelations() as $relation)
{
if ($relation['alias'] == $options['hasMany'])
{
$hasManyClass = $relation['class'];
$refClass = str_replace('Table', '', get_class($relation['refTable']));
}
}
$this->addOption('refClass', $refClass);
$this->addOption('hasManyClass', $hasManyClass);
}
// Pulls default choices based on the passed options if none exist
public function getChoices()
{
return $this->getOption('choices') ?
$this->getOption('choices') : $this->collectionToArray(
Doctrine::getTable($this->getOption('hasManyClass'))
->createQuery('s')
->leftJoin('s.'.$this->getOption('refClass').' ref')
->orderBy('ref.'.$this->getOption('position_field'))
->execute()
);
}
// Returns all refClass objects currently associated with this object
protected function getPositionObjects()
{
$object = $this->getOption('object');
$selectedObjects = Doctrine::getTable($this->getOption('refClass'))
->createQuery('s')
->select('s.*, many.id as has_many_id')
->innerJoin('s.'.get_class($object).' obj')
->innerJoin('s.'.$this->getOption('hasManyClass').' many')
->where('obj.id = ?', $object->id)
->orderBy('s.'.$this->getOption('position_field').' ASC')
->execute();
return $this->collectionToArray($selectedObjects, 'has_many_id');
}
}
| true |
0d17ddf3823746bd14cc001806cfa115dcfac2d0 | PHP | securia/api | /app/commands/Bootstrap.php | UTF-8 | 2,787 | 2.640625 | 3 | [] | no_license | <?php
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
/**
* This is script to Bootstrap
*
* php artisan script:Bootstrap
*
*/
class Bootstrap extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'script:Bootstrap';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Bootstrap data to Mongo';
/**
* Create a new command instance.
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function fire()
{
try {
global $appConfig;
$this->comment('Script : Start');
switch ($this->argument('action')) {
case 'setUp':
$this->comment('setUp : Start');
$request = \Illuminate\Support\Facades\Request::create('scripts/4.0/bootstrap/' . $this->argument('action'), 'POST');
$response = \Illuminate\Support\Facades\Route::dispatch($request)->getContent();
$this->info($response);
$this->comment('setUp : End');
break;
case 'updateDefaultAwsSettings':
$this->comment('updateDefaultAwsSettings : Start');
$request = \Illuminate\Support\Facades\Request::create('scripts/4.0/bootstrap/' . $this->argument('action'), 'POST');
$response = \Illuminate\Support\Facades\Route::dispatch($request)->getContent();
$this->info($response);
$this->comment('updateDefaultAwsSettings : End');
break;
default:
$this->error('Please provide valid action.');
break;
}
$this->comment('Script : End');
} catch (\Exception $e) {
$this->error("Oops something is wrong. Please check your script before executing next time");
$this->error("Error in file: " . $e->getFile());
$this->error("Exception Message: " . $e->getMessage());
$this->error("At line number: " . $e->getLine());
}
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return array(
array('action', InputOption::VALUE_REQUIRED, 'Bootstrap setup script')
);
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return array();
}
}
| true |
b5efc8b045b2a255b734715298934a9ffca10647 | PHP | ruslanix/code-samples | /1_CatalogParser/Application/CatalogParser/Tests/Parser/Rozetka/ParserUnit/PageProductItemsTest.php | UTF-8 | 1,876 | 2.53125 | 3 | [] | no_license | <?php
namespace Application\CatalogParser\Tests\Parser\Rozetka\ParserUnit;
use Application\ParserChain\Container\ResultContainer;
use Application\CatalogParser\Parser\Rozetka\ParserUnit\PageProductItems;
use Application\CatalogParser\Tests\Parser\Rozetka\ParserUnit\DataFixtures\ProductItemsTestData;
class PageProductItemsTest extends \PHPUnit_Framework_TestCase
{
public function providerTestParse_validItems()
{
return array(
array(
ProductItemsTestData::getHtmlData(),
count(ProductItemsTestData::$items)
),
);
}
public function providerTestParse_notValidItems()
{
return array(
array(null),
array(''),
array('<div 234<span>'),
);
}
/**
* @dataProvider providerTestParse_validItems
*/
public function testParse_validItems($html, $itemsCount)
{
// given
$resultContainer = new ResultContainer();
$parserUnit = new PageProductItems();
// when
$parserUnit->parse($html, $resultContainer);
// then
$this->assertArrayHasKey('items', $resultContainer->toArray(), 'result container should have items');
$this->assertCount($itemsCount, $resultContainer->get('items'), "should be $itemsCount in items");
}
/**
* @dataProvider providerTestParse_notValidItems
*/
public function testParse_notValidItems($html)
{
// given
$resultContainer = new ResultContainer();
$parserUnit = new PageProductItems();
// when
$parserUnit->parse($html, $resultContainer);
// then
$this->assertArrayHasKey('items', $resultContainer->toArray(), 'result container should have items');
$this->assertEmpty($resultContainer->get('items'), "items should be empty");
}
}
| true |
5cf0260bee5303198add379aa32dfd3eb12b2e9a | PHP | kemalyen/azurehelper | /src/Logger.php | UTF-8 | 1,586 | 2.859375 | 3 | [
"MIT"
] | permissive | <?php
namespace Gazatem\Phpfunc;
class Logger {
private $messages = [];
public function getMessages()
{
$return = [];
foreach($this->messages as $message){
$return[] = $message[0] .': '. $message[1];
}
return $return;
}
function information(string $message) {
array_push($this->messages, $message);
}
public function emergency($message, array $context = array()){
array_push($this->messages, ['emergency', $message]);
}
public function alert($message, array $context = array()){
array_push($this->messages, ['alert', $message]);
}
public function critical($message, array $context = array()){
array_push($this->messages, ['critical', $message]);
}
public function error($message, array $context = array()){
array_push($this->messages, ['error', $message]);
}
public function warning($message, array $context = array()){
array_push($this->messages, ['warning', $message]);
}
public function notice($message, array $context = array()){
array_push($this->messages, ['notice', $message]);
}
public function info($message, array $context = array()){
array_push($this->messages, ['info', $message]);
}
public function debug($message, array $context = array()){
array_push($this->messages, ['debug', $message]);
}
public function log($message, array $context = array()){
array_push($this->messages, ['log', $message]);
}
} | true |
ce2201508d1f0cc3379eef480abe8ed95166ef61 | PHP | rmit-s3378684-Pavitra-Vathsalaraj/project1 | /app/Registered_user.php | UTF-8 | 1,264 | 2.78125 | 3 | [
"MIT"
] | permissive | <?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Input;
use Hash;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Registered_user extends Authenticatable
{
//
protected $table="registered_users";
public static function formstore($data){
//echo "here model is";
//
//var_dump($data);
$fname=Input::get('fname');
$username=Input::get('username');
$password=Hash::make(Input::get('password'));
$email=Input::get('email');
$usertype=Input::get('usertype');
$company=Input::get('company');
$address=Input::get('address');
$state=Input::get('state');
$country=Input::get('country');
$zip=Input::get('zip');
$phonenum=Input::get('phonenum');
//$remember_token=Input::get('remember_token');
$users= new Registered_user(); //create new user model
$users->fname=$fname;
$users->username=$username;
$users->password=$password;
$users->email=$email;
$users->usertype=$usertype;
$users->company=$company;
$users->address=$address;
$users->state=$state;
$users->country=$country;
$users->zip=$zip;
$users->phonenum=$phonenum;
//$users->remember_token=$remember_token;
// convert data format
$users->save(); //save to 'registered_users' table
}
}
| true |
01e55f3632ff39ff23df3e6e845f4245c368b470 | PHP | BobMcHenry/php-mysqli-demo | /db-connection.php | UTF-8 | 1,168 | 3.46875 | 3 | [] | no_license | <?php
require('credentials.php');
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Make a SELECT query
$searchFor = "'McHenry'";
$selectQuery = "SELECT * FROM actor
WHERE last_name LIKE " . $searchFor;
//INSERT INTO table_name (column1, column2, column3, ...)
//VALUES (value1, value2, value3, ...);
// $insertQuery = "INSERT INTO actor (first_name, last_name)
// VALUES ('Bob', 'McHenry')";
//
// if ($conn->query($insertQuery) === TRUE) {
// echo "New stuff created successfully";
// } else {
// echo "Error: " . $insertQuery . "<br>" . $conn->error;
// }
$result = $conn->query($selectQuery);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo
"actor_id: "
. $row["actor_id"]
. " - Name: "
. $row["first_name"]
. " "
. $row["last_name"]
. "<br>";
}
}
?>
| true |
86e9c3c56aff95aaad0924689505293d424e9c32 | PHP | shivam13juna/web_app | /my_pdo/thanks.php | UTF-8 | 1,044 | 2.953125 | 3 | [] | no_license | <?php
// header('Content-Type: text/enriched/font-woff');
// echo "<pre>";
// echo "This is $_GET";
// echo "</pre>";
require_once "pdo.php";
if (isset($_GET['name']) && isset($_GET['habit'])){
$nam = $_GET['name'];
$hab = $_GET['habit'];
echo "Thank you, the name $nam and their $hab have been inserted in the database successfully ";
}
if (isset($_GET['todel'])){
$todel = $_GET['todel'];
echo "Thank you, $todel has been successfully deleted from the database";
}
$stmt = $pdo->query("SELECT name, habit FROM people");
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo "This is the updated Databas\n";
?>
<table border="1">
<?php
foreach ( $rows as $row ) {
echo "<tr><td>";
echo($row['name']);
echo("</td><td>");
echo($row['habit']);
echo("</td><td>");
echo('<form method="post"><input type="hidden" ');
echo('name="to_del" value="'.$row['name'].'">'."\n");
echo('<input type="submit" value="Del" name="delete">');
echo("\n</form>\n");
echo("</td></tr>\n");
}
?>
</table>
| true |
973651bd39fff81d6609097893ea3e3b48de656b | PHP | bapplistudio/SAF | /locale/Locale.php | UTF-8 | 6,831 | 2.84375 | 3 | [
"MIT"
] | permissive | <?php
namespace SAF\Framework;
use SAF\Framework\Locale\Date_Format;
use SAF\Framework\Locale\Loc;
use SAF\Framework\Locale\Number_Format;
use SAF\Framework\Locale\Translator;
use SAF\Framework\Plugin\Configurable;
use SAF\Framework\Reflection\Interfaces\Reflection_Method;
use SAF\Framework\Reflection\Interfaces\Reflection_Property;
use SAF\Framework\Reflection\Reflection_Property_Value;
use SAF\Framework\Reflection\Type;
use SAF\Framework\Tools\Current;
use SAF\Framework\Tools\Date_Time;
/**
* A Locale object has all locale features, useful for specific locale conversions
*/
class Locale implements Configurable
{
use Current { current as private pCurrent; }
//----------------------------------------------------- Locale configuration array keys constants
//------------------------------------------------------------------------------------------ DATE
const DATE = 'date';
//-------------------------------------------------------------------------------------- LANGUAGE
const LANGUAGE = 'language';
//---------------------------------------------------------------------------------------- NUMBER
const NUMBER = 'number';
//---------------------------------------------------------------------------------- $date_format
/**
* @link Object
* @setter setDateFormat
* @var Date_Format
*/
public $date_format;
//------------------------------------------------------------------------------------- $language
/**
* @setter setLanguage
* @var string
*/
public $language;
//-------------------------------------------------------------------------------- $number_format
/**
* @setter setNumberFormat
* @var Number_Format
*/
public $number_format;
//--------------------------------------------------------------------------------- $translations
/**
* @var Translator
*/
public $translations;
//----------------------------------------------------------------------------------- __construct
/**
* @param $configuration array
*/
public function __construct($configuration)
{
$current = self::current();
if (!isset($current)) {
self::current($this);
}
$this->setDateFormat($configuration[self::DATE]);
$this->setLanguage($configuration[self::LANGUAGE]);
$this->setNumberFormat($configuration[self::NUMBER]);
}
//--------------------------------------------------------------------------------------- current
/**
* @param $set_current Locale
* @return Locale
*/
public static function current(Locale $set_current = null)
{
return self::pCurrent($set_current);
}
//-------------------------------------------------------------------------------- methodToLocale
/**
* Change an ISO value into a locale formatted value, knowing its method
*
* @param $method Reflection_Method
* @param $value string
* @return string
*/
public function methodToLocale(Reflection_Method $method, $value)
{
return $this->toLocale($value, new Type($method->returns()));
}
//--------------------------------------------------------------------------------- propertyToIso
/**
* Change a locale value into an ISO formatted value, knowing its property
*
* @param $property Reflection_Property
* @param $value string
* @return string|integer|float
*/
public function propertyToIso(Reflection_Property $property, $value = null)
{
if (($property instanceof Reflection_Property_Value) && !isset($value)) {
$value = $property->value();
}
return (is_null($value) && $property->getAnnotation('null')->value)
? $value
: $this->toIso($value, $property->getType());
}
//------------------------------------------------------------------------------ propertyToLocale
/**
* Change an ISO value into a locale formatted value, knowing its property
*
* @param $property Reflection_Property
* @param $value string
* @return string
*/
public function propertyToLocale(Reflection_Property $property, $value = null)
{
if (($property instanceof Reflection_Property_Value) && !isset($value)) {
$value = $property->value();
}
if ($value instanceof Date_Time) {
$this->date_format->show_seconds = $property->getAnnotation('show_seconds')->value;
}
return (is_null($value) && $property->getAnnotation('null')->value)
? $value
: (
$property->getListAnnotation('values')->value
? $this->translations->translate($value)
: $this->toLocale($value, $property->getType())
);
}
//--------------------------------------------------------------------------------- setDateFormat
/**
* @param $date_format Date_Format|string if string, must be a date format (ie 'd/m/Y')
*/
private function setDateFormat($date_format)
{
$this->date_format = ($date_format instanceof Date_Format)
? $date_format
: new Date_Format($date_format);
}
//----------------------------------------------------------------------------------- setLanguage
/**
* @param $language string
*/
private function setLanguage($language)
{
$this->language = $language;
$this->translations = new Translator($this->language);
}
//------------------------------------------------------------------------------- setNumberFormat
/**
* Set locale's number format
*
* @param Number_Format|mixed[]
*/
private function setNumberFormat($number_format)
{
$this->number_format = ($number_format instanceof Number_Format)
? $number_format
: new Number_Format($number_format);
}
//----------------------------------------------------------------------------------------- toIso
/**
* Change a locale value into an ISO formatted value, knowing its data type
*
* @param $value string
* @param $type Type
* @return string|integer|float
*/
public function toIso($value, Type $type = null)
{
if (isset($type)) {
if ($type->isDateTime()) {
return $this->date_format->toIso($value);
}
elseif ($type->isFloat()) {
return $this->number_format->floatToIso($value);
}
elseif ($type->isInteger()) {
return $this->number_format->integerToIso($value);
}
}
return $value;
}
//-------------------------------------------------------------------------------------- toLocale
/**
* Change an ISO value into a locale formatted value, knowing its data type
*
* @param $type Type
* @param $value string
* @return string
*/
public function toLocale($value, Type $type = null)
{
if (isset($type)) {
if ($type->isDateTime()) {
return $this->date_format->toLocale($value);
}
elseif ($type->isFloat()) {
return $this->number_format->floatToLocale($value);
}
elseif ($type->isInteger()) {
return $this->number_format->integerToLocale($value);
}
}
$context = $type->isClass() ? $type->getElementTypeAsString() : Loc::getContext();
return $this->translations->translate($value, $context);
}
}
| true |
f1a98d05bff2f0e306d6491d03ed3474cf72f0d0 | PHP | miguelcostero/tesis-api | /enviroment/authentification.php | UTF-8 | 1,196 | 2.609375 | 3 | [] | no_license | <?php
require __DIR__ . '/token.php';
$token = new Token;
$headers = getallheaders();
if (isset($headers['Access-Token'])) {
$access_token = $headers['Access-Token'];
try {
$decoded = $token->decode($access_token);
if ($decoded->exp < time()) {
http_response_code(401);
echo json_encode(array('error' => array('code' => 401, 'message' => 'Token de acceso está expirado')));
die();
}
$request_uri = explode('/', trim($_SERVER['REQUEST_URI']));
if (in_array('admin', $request_uri)) {
if (!$decoded->data->role == 2 || !$decoded->data->role == 3) {
http_response_code(401);
echo json_encode(array('error' => array('code' => 401, 'message' => 'Usted no posee permisos para acceder a este recurso')));
die();
}
}
} catch (Exception $e) {
http_response_code(401);
echo json_encode(array('error' => array('code' => 401, 'message' => 'Token de acceso inválido', 'err_message' => $e->getMessage(), 'err_code' => $e->getCode())));
die();
}
} else {
http_response_code(401);
echo json_encode(array('error' => array('code' => 401, 'message' => 'No existe token de acceso en la petición')));
die();
} | true |
57287b355bb423a2eb3c371e6ff48819a8371c41 | PHP | quan4399/thi_module2 | /App/Models/ProductModel.php | UTF-8 | 2,373 | 3.09375 | 3 | [] | no_license | <?php
namespace App\Models;
class ProductModel
{
public $pdo;
public function __construct()
{
$database = new DBConnect("root", "");
$this->pdo = $database->connect();
}
public function getAllProduct()
{
$sql = "SELECT * FROM products";
$stmt = $this->pdo->prepare($sql);
$stmt->execute();
$products = $stmt->fetchAll();
return $products;
}
public function addProduct($array)
{
$sql = "INSERT INTO products (nameProduct,typeProduct,priceProduct,quantityProduct,description,dateCreate)
VALUES (?,?,?,?,?,?)";
$stmt = $this->pdo->prepare($sql);
$stmt->bindParam(1, $array["nameProduct"]);
$stmt->bindParam(2, $array["typeProduct"]);
$stmt->bindParam(3, $array["priceProduct"]);
$stmt->bindParam(4, $array["quantityProduct"]);
$stmt->bindParam(5, $array["description"]);
$stmt->bindParam(6, $array["dateCreate"]);
$stmt->execute();
}
public function deleteProductById($id)
{
$sql = "DELETE FROM products where id= :id";
$stmt = $this->pdo->prepare($sql);
$stmt->bindParam(":id", $id);
$stmt->execute();
}
public function updateProduct($id,$product)
{
$sql = "UPDATE products
SET nameProduct = :nameProduct , typeProduct = :typeProduct,
priceProduct = :priceProduct, quantityProduct = :quantityProduct ,dateCreate = :dateCreate,
description= :description
where id = :id" ;
$stmt= $this->pdo->prepare($sql);
$stmt->bindParam("nameProduct",$product['nameProduct']);
$stmt->bindParam("typeProduct",$product['typeProduct']);
$stmt->bindParam("priceProduct",$product['priceProduct']);
$stmt->bindParam("quantityProduct",$product['quantityProduct']);
$stmt->bindParam("dateCreate",$product['dateCreate']);
$stmt->bindParam("description",$product['description']);
$stmt->bindParam("id",$id);
$stmt->execute();
}
public function getDetailById($id)
{
$sql = "SELECT * FROM products where id= :id";
$stmt = $this->pdo->prepare($sql);
$stmt->bindParam(":id", $id);
$stmt->execute();
$product = $stmt->fetch();
return $product;
}
} | true |
fa0e55bd54ac6877ddf9752a24d897d6424c464a | PHP | williamRS061/PRW | /POO/includes/atividade1.inc.php | UTF-8 | 347 | 3.453125 | 3 | [] | no_license | <?php
//declaração da classe
class Item {
//atributos da classe
var $nome;
var $preco;
var $categoria;
function __construct($nome, $preco, $categoria){
$this->nome = $nome;
$this->preco = $preco;
$this->categoria = $categoria;
}
function mostrarCategoria(){
return $this->categoria;
}
}
?> | true |
27e149982c9ce01372dc7e8b8ecc457817a0a9b6 | PHP | aurovrata/Savi-Admin-Tool | /enquiry-review.php | UTF-8 | 10,527 | 2.71875 | 3 | [] | no_license | <?php
if(!class_exists('WP_List_Table')){
require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
}
class Enquiry_Review_List_Table extends WP_List_Table {
function __construct(){
global $status, $page;
//Set parent defaults
parent::__construct( array(
'singular' => 'enquiry_review', //singular name of the listed records
'plural' => 'enquiry_reviews', //plural name of the listed records
'ajax' => false, //does this table support ajax?
'screen' => isset( $args['screen'] ) ? $args['screen'] : null,
) );
}
function column_default($item, $column_name){
switch($column_name){
case 'name':
case 'email':
case 'country':
case 'phone':
case 'time_of_stay':
return $item[$column_name];
default:
return print_r($item,true); //Show the whole array for troubleshooting purposes
}
}
function column_action($item){
//Build row actions
$actions = array(
'skills' => sprintf('<a href="javascript:void(0);" class="popper" data-popbox="savi_skill_%1$s">Skills</a>'),
'motivation' => sprintf('<a href="javascript:void(0);" class="popper" data-popbox="savi_motiv_%1$s">Motivation</a>'),
);
$hidden_div = sprintf('
<div id="savi_skill_%1$s" class="popbox">
<h2>Skills</h2>
<p>This is a skill.</p>
</div>
<div id="savi_motiv_%1$s" class="popbox">
<h2>Motivation</h2>
<p>This is the motivation</p>
</div>',
$item['ID']);
//Return the title contents
return sprintf('
%1$s
<span style="color:silver">%2$s</span>',
$hidden_div,
$this->row_actions($actions));
}
function column_cb($item){
return sprintf(
'<input type="checkbox" name="%1$s[]" value="%2$s" />',
/*$1%s*/ $this->_args['singular'], //Let's simply repurpose the table's singular label ("movie")
/*$2%s*/ $item['ID'] //The value of the checkbox should be the record's id
);
}
function get_columns(){
$columns = array(
'cb' => '<input type="checkbox" />', //Render a checkbox instead of text
'name' => 'Name',
'email' => 'Email',
'country' => 'Country',
'phone' => 'Phone Number',
'time_of_stay' => 'Time of Stay',
'action' => 'Action'
);
return $columns;
}
function get_sortable_columns() {
$sortable_columns = array(
'name' => array('Name',false), //true means it's already sorted
'email' => array('Email',false),
'country' => array('Country',false),
);
return $sortable_columns;
}
function get_bulk_actions() {
$actions = array(
'approve' => 'Approve',
'reject' => 'Reject'
);
return $actions;
}
function process_bulk_action() {
//Detect when a bulk action is being triggered...
if( 'apporve'===$this->current_action() ) {
wp_die('Items deleted (or they would be if we had items to delete)!');
}
elseif( 'reject'===$this->current_action() ) {
wp_die('Items deleted (or they would be if we had items to delete)!');
}
}
function prepare_items() {
global $wpdb; //This is used only if making any database queries
/**
* First, lets decide how many records per page to show
*/
//$per_page = 5;
$args = array(
'label' => __('Users per page', 'pippin'),
'default' => 10,
'option' => 'pippin_per_page'
);
add_screen_option( 'per_page', $args );
// get the current user ID
$user = get_current_user_id();
// get the current admin screen
$screen = get_current_screen();
// retrieve the "per_page" option
$screen_option = $screen->get_option('per_page', 'option');
// retrieve the value of the option stored for the current user
$per_page = get_user_meta($user, $screen_option, true);
if ( empty ( $per_page) || $per_page < 1 ) {
// get the default value if none is set
$per_page = $screen->get_option( 'per_page', 'default' );
}
$columns = $this->get_columns();
$hidden = get_hidden_columns( $this->screen );;
$sortable = $this->get_sortable_columns();
$this->_column_headers = array($columns, $hidden, $sortable);
$this->process_bulk_action();
/*$select_custom_List_qry = "select * from wp_custom_list";
$custom_List_records = $wpdb->get_results( $select_custom_List_qry, ARRAY_A );
*/
$args = array('post_type' => 'View_0',);
$cpts = new WP_Query($args);
//echo"<pre>",print_r($cpts),"</pre>";
if($cpts->have_posts()) :
while($cpts->have_posts() ) :
$cpts->the_post();
$meta_values[] = get_post_meta(get_the_ID());
$post_ID['ID'][] =get_the_ID();
endwhile;
endif;
$i=0;
foreach($meta_values as $meta_value) :
$custom_post[$i]['Name']= $meta_value['Name'][0];
$custom_post[$i]['Email']= $meta_value['Email'][0];
$custom_post[$i]['Country']= $meta_value['Country'][0];
$custom_post[$i]['Phone']= $meta_value['Phone'][0];
$custom_post[$i]['Time_of_Stay']= $meta_value['Time_of_Stay'][0];
$custom_post[$i]['Motivation']=$meta_value['Motivation'][0];
$custom_post[$i]['SKills']= $meta_value['Skills'][0];
$i++;
endforeach;
$j=0;
foreach($post_ID['ID'] as $key => $post) :
$custom_post[$j]['ID']= $post;
$j++;
endforeach;
// echo"<pre>",print_r($custom_post),"</pre>";
$data = $custom_post;
function usort_reorder($a,$b){
$orderby = (!empty($_REQUEST['orderby'])) ? $_REQUEST['orderby'] : 'Name'; //If no sort, default to title
$order = (!empty($_REQUEST['order'])) ? $_REQUEST['order'] : 'asc'; //If no order, default to asc
$result = strcmp($a[$orderby], $b[$orderby]); //Determine sort order
return ($order==='asc') ? $result : -$result; //Send final sort direction to usort
}
usort($data, 'usort_reorder');
$current_page = $this->get_pagenum();
$total_items = count($data);
$data = array_slice($data,(($current_page-1)*$per_page),$per_page);
$this->items = $data;
/**
* REQUIRED. We also have to register our pagination options & calculations.
*/
$this->set_pagination_args( array(
'total_items' => $total_items, //WE have to calculate the total number of items
'per_page' => $per_page, //WE have to determine how many items to show on a page
'total_pages' => ceil($total_items/$per_page) //WE have to calculate the total number of pages
) );
}
}
class Enquiry_Review_init extends Enquiry_Review_List_Table {
function __construct(){
add_action('admin_menu', array($this,'enquiry_review_add_menu_items'));
add_filter('set-screen-option', array($this,'enquiry_review_screen_option'), 10, 3);
add_filter('manage_toplevel_page_enquiry_review_columns',array($this,'enquiry_review_set_columns'));
}
function enquiry_review_add_menu_items(){
global $enquiry_review_page;
$enquiry_review_page = add_menu_page('Enquiry Review List Table', 'Enquiry Review',
'activate_plugins', 'enquiry_review', array($this,'enquiry_review_render_list_page'));
add_action("load-$enquiry_review_page", array($this,"enquiry_review_screen_options"));
}
function enquiry_review_screen_options() {
global $enquiry_review_page;
$screen = get_current_screen();
// get out of here if we are not on our settings page
if(!is_object($screen) || $screen->id != $pippin_sample_page)
return;
$args = array(
'label' => __('Members per page', 'pippin'),
'default' => 10,
'option' => 'pippin_per_page'
);
add_screen_option( 'per_page', $args );
}
function enquiry_review_set_screen_option($status, $option, $value) {
if ( 'pippin_per_page' == $option ) return $value;
}
function enquiry_review_set_columns( ) {
$columns = array(
'cb' => '<input type="checkbox" />', //Render a checkbox instead of text
'Name' => 'Name',
'Email' => 'Email',
'Country' => 'Country',
'Phone' => 'Phone Number',
'Time_of_Stay' => 'Time of Stay',
'action' => 'Action'
);
return $columns;
}
function enquiry_review_render_list_page(){
//Create an instance of our package class...
$enquiryReviewListTable = new Enquiry_Review_List_Table();
//Fetch, prepare, sort, and filter our data...
$enquiryReviewListTable->prepare_items();
?>
<div class="wrap">
<div id="icon-users" class="icon32"><br/></div>
<h2>Enquiry Review List</h2>
<!-- Forms are NOT created automatically, so you need to wrap the table in one to use features like bulk actions -->
<form id="movies-filter" method="get">
<!-- For plugins, we also need to ensure that the form posts back to our current page -->
<input type="hidden" name="page" value="<?php echo $_REQUEST['page'] ?>" />
<!-- Now we can render the completed list table -->
<?php $enquiryReviewListTable->display() ?>
</form>
</div>
<?php
}
}
| true |
f0c4896b0f8007da61c1c92c69708b859c112024 | PHP | isabella232/vagrant-catalog | /src/Vube/VagrantCatalog/DirectoryScan.php | UTF-8 | 2,205 | 2.9375 | 3 | [
"MIT"
] | permissive | <?php
/**
* @author Ross Perkins <ross@vubeology.com>
*/
namespace Vube\VagrantCatalog;
use Vube\VagrantCatalog\Exception\HttpException;
/**
* DirectoryScan class
*
* @author Ross Perkins <ross@vubeology.com>
*/
class DirectoryScan {
private $dir;
private $ignoreList;
public function __construct($dir)
{
$this->dir = $dir;
$this->ignoreList = array('.', '..');
}
public function ignoreFile($file)
{
$this->ignoreList[] = $file;
}
public function countMetadataChildren($dir, $depth=0)
{
$dh = opendir($dir);
if(! $dh)
throw new Exception("Cannot read directory: ".$this->dir);
$n = 0;
while($file = readdir($dh))
{
// If we should ignore this file, do so
if(in_array($file, $this->ignoreList))
continue;
// If it's a directory, count it
$path = $dir.'/'.$file;
if(is_dir($path))
$n += $this->countMetadataChildren($path, $depth+1);
// Only count metadata.json in SUB-directories of the original $dir,
// not in the $dir itself.
else if($file == 'metadata.json' && $depth > 0)
$n++;
}
closedir($dh);
return $n;
}
public function scan()
{
if(! file_exists($this->dir))
throw new HttpException("No such file or directory: ".$this->dir, 404);
$dh = opendir($this->dir);
if(! $dh)
throw new Exception("Cannot read directory: ".$this->dir);
$result = array(
'dirs' => array(),
'boxes' => array(),
'metadata' => null,
);
while($file = readdir($dh))
{
// If we should ignore this file, do so
if(in_array($file, $this->ignoreList))
continue;
$path = $this->dir . '/' . $file;
if(is_dir($path))
{
// If there is a metadata.json in this dir, it is a box
if(file_exists($path . '/' . 'metadata.json'))
$result['boxes'][] = $file;
// Only list this as a directory IFF there are more
// directories under it.
if($this->countMetadataChildren($path) > 0)
$result['dirs'][] = $file;
}
else if($file == 'metadata.json')
{
$result['metadata'] = $path;
}
}
closedir($dh);
sort($result['dirs']);
sort($result['boxes']);
return $result;
}
}
| true |
bc32a7d90e49f546253614f944e892db73d28390 | PHP | kakaye-mkubwa/tweet-s | /UserProcessors/Register.php | UTF-8 | 5,498 | 2.875 | 3 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | <?php
include_once '../utils/DBConnection.php';
$connection = new DBConnection();
$link = $connection->connection();
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$email = test_input($_POST["register_email"]);
$username = test_input($_POST["register_name"]);
$password = test_input($_POST["password"]);
$confirmPassword = test_input($_POST["confirm_password"]);
//validate email address
if(empty($email))
{
$offErr = "Email is required";
?>
<hr><div class="alert alert-danger"><p align="center"><strong>
<i class="fa fa-exclamation-triangle"></i> Error Processing Request!</strong>
Email is required</p></div>
<?php
}
//validate username
if (!empty($username))
{
$usernameCheck = "SELECT username FROM users WHERE username = ?";
if($stmt = mysqli_prepare($link,$usernameCheck))
{
mysqli_stmt_bind_param($stmt,"s",$param_username);
$param_username = $username;
if(mysqli_stmt_execute($stmt))
{
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt) == 1)
{
$usernameErr = "That username already exists";
?>
<hr><div class="alert alert-danger"><p align="center"><strong>
<i class="fa fa-exclamation-triangle"></i> Error Processing Request!</strong>
Username already exists</p></div>
<?php
}
}
else
{
?>
<hr><div class="alert alert-danger"><p align="center"><strong>
<i class="fa fa-exclamation-triangle"></i> Error Processing Request!</strong>
Registration failed</p></div>
<?php
}
mysqli_stmt_close($stmt);
}else{
?>
<hr><div class="alert alert-danger"><p align="center"><strong>
<i class="fa fa-exclamation-triangle"></i> Error Processing Request!</strong>
Registration failed</p></div>
<?php
}
}
else
{
$usernameErr="Password is required";
?>
<hr><div class="alert alert-danger"><p align="center"><strong>
<i class="fa fa-exclamation-triangle"></i> Error Processing Request!</strong>
Username is required</p></div>
<?php
}
//validate password
if (!empty($password))
{
if(strlen($password) < 8)
{
$passwordErr = "Password should be at least 8 characters";
?>
<hr><div class="alert alert-danger"><p align="center"><strong>
<i class="fa fa-exclamation-triangle"></i> Error Processing Request!</strong>
Password should be atleast 8 characters</p></div>
<?php
}
}
else
{
$offErr = "Please fill in all the fields";
?>
<hr><div class="alert alert-danger"><p align="center"><strong>
<i class="fa fa-exclamation-triangle"></i> Error Processing Request!</strong>
Password is required</p></div>
<?php
}
//confirm password
if(!empty($confirmPassword))
{
if ($confirmPassword != $password)
{
$confirmPasswordErr = "Passwords do no match";
?>
<hr><div class="alert alert-danger"><p align="center"><strong>
<i class="fa fa-exclamation-triangle"></i> Error Processing Request!</strong>
Password do not match</p></div>
<?php
}
}
else
{
$confirmPasswordErr = "Please confirm your password";
?>
<hr><div class="alert alert-danger"><p align="center"><strong>
<i class="fa fa-exclamation-triangle"></i> Error Processing Request!</strong>
Confirm password entered</p></div>
<?php
}
if (empty($offErr) && empty($confirmPasswordErr) && empty($passwordErr) && empty($offNameErr) &&
empty($usernameErr) && empty($emailErr) && empty($offAddressErr))
{
$insertSql = "INSERT INTO users(username,email,user_pass) VALUES (?,?,?)";
if ($stmt = mysqli_prepare($link, $insertSql))
{
mysqli_stmt_bind_param($stmt,"sss",$paramUsername,$paramEmail,$paramPassword);
$paramEmail = $email;
$paramPassword = password_hash($password,PASSWORD_DEFAULT);
$paramUsername = $username;
if (mysqli_stmt_execute($stmt))
{
session_start();
$_SESSION['user_id'] = $username;
?>
<script>setTimeout(function(){ window.location.href= 'index.php';}, 1500);</script>
<?php
// header("location: index.php");
}
else
{
?>
<hr><div class="alert alert-danger"><p align="center"><strong>
<i class="fa fa-exclamation-triangle"></i> Error Processing Request!</strong>
Registration Failed</p></div>
<?php
}
mysqli_stmt_close($stmt);
}
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
| true |
4c7c5aad9e54105c4c36541f927c39c2584aefdb | PHP | djinorm/djin | /src/Helpers/GetModelByAnyTypeIdHelper.php | UTF-8 | 1,873 | 2.828125 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
/**
* @author Timur Kasumov (aka XAKEPEHOK)
* Datetime: 27.09.2017 20:07
*/
namespace DjinORM\Djin\Helpers;
use DjinORM\Djin\Exceptions\InvalidArgumentException;
use DjinORM\Djin\Exceptions\LogicException;
use DjinORM\Djin\Exceptions\NotFoundException;
use DjinORM\Djin\Id\Id;
use DjinORM\Djin\Model\ModelInterface;
use DjinORM\Djin\Repository\RepositoryInterface;
class GetModelByAnyTypeIdHelper
{
/**
* @param $modelObjectOrAnyId ModelInterface|Id|int|string
* @param RepositoryInterface|null $repo
* @return ModelInterface
* @throws InvalidArgumentException
* @throws LogicException
* @throws NotFoundException
*/
public static function get(
$modelObjectOrAnyId,
RepositoryInterface $repo = null
): ModelInterface
{
if ($modelObjectOrAnyId instanceof ModelInterface) {
return $modelObjectOrAnyId;
}
if (is_null($repo)) {
throw new LogicException('Impossible to find model without repository');
}
if (is_scalar($modelObjectOrAnyId)) {
$model = $repo->findById($modelObjectOrAnyId);
if ($model === null) {
self::throwNotFoundException($modelObjectOrAnyId);
}
return $model;
}
if ($modelObjectOrAnyId instanceof Id) {
$id = $modelObjectOrAnyId->toScalar();
$model = $repo->findById($id);
if ($model === null) {
self::throwNotFoundException($id);
}
return $model;
}
throw new InvalidArgumentException('Incorrect ID type');
}
/**
* @param $modelId
* @throws NotFoundException
*/
private static function throwNotFoundException($modelId)
{
throw new NotFoundException("Model with ID '{$modelId}' was not found");
}
} | true |
61896d89cded1762a3dd92fbdf54ee47c0b1dbd1 | PHP | troycaeser/ReviseITWeb | /php/admin/datesReport.php | UTF-8 | 4,187 | 2.59375 | 3 | [] | no_license | <?php
include '../getConnection.php';
require '../check_logged_in.php';
include '../check_role.php';
checkRoleStudent($_SESSION['Role']);
?>
<!DOCTYPE html>
<html>
<head>
<?php
include '../header_container.php';
?>
<title>ReviseIT - Dates</title>
</head>
<body>
<?php
include 'admin_menu_bar.php';
?>
<br />
<br />
<div class="container">
<div class="page-header bootstro" data-bootstro-placement="bottom" data-bootstro-title="Dates Report" data-bootstro-content="Welcome to the dates report! This page shows all the dates updated for all subjects and their related contents!">
<h1>Report - Dates Last Updated</h1>
</div>
<div class='row-fluid'>
<!-- Displays All subjects etc -->
<?php
include '../getConnection.php';
$userRole = $_SESSION['Role'];
try
{
$subj = $db->prepare("SELECT * FROM subject;");
$subj->execute();
$subjResult = $subj;
}
catch (PDOException $e){
echo "Database Error";
}
echo "<div class='span12 bootstro' data-bootstro-placement='top' data-bootstro-title='Dates Last Updated' data-bootstro-content='Displays dates Content or Details were Last Updated.'>";
echo "<div class='span5'><h4>Subject</h4></div>";
echo "<div class='span3'><h4>Topic</h4></div>";
echo "<div class='span3'><h4>Subtopic</h4></div>";
echo "<div class='span1'><h4>Date Updated</h4></div>";
echo "<div class='row-fluid'>";
//display everything in a row-fluid/spans while looping the result.
//pass SubjectID in the url for each individual link.
while($row = $subjResult->fetch(PDO::FETCH_OBJ))
{
//display subjects in a list style with anchor pointing to the subject's topics
//echo "<a href='../topics/viewTopic.php?ID=".$row->SubjectID."'>";
echo "<div class='span5'>".$row->SubjectCode.": ".$row->SubjectName."</div>";
//echo "</a>";
try {
$topc = $db->prepare("SELECT * FROM topic WHERE SubjectID = ".$row->SubjectID.";");
$topc->bindParam("SubjectID", $row->SubjectID);
$topc->execute();
$topcResult = $topc;
}
catch (PDOException $e){
echo "Database Error";
}
$topFlag = false;
while($row1 = $topcResult->fetch(PDO::FETCH_OBJ))
{
$topFlag = true;
//display topics in a list style with anchor pointing to the topics's subtopics
//echo "<a href='../subtopics/view.php?ID=".$row1->TopicID."'>";
echo "<div class='span3'>".$row1->TopicName."</div>";
//echo "</a>";
try {
$sbtp = $db->prepare("SELECT * FROM subtopic WHERE TopicID = ".$row1->TopicID.";");
$sbtp->bindParam("TopicID", $row1->TopicID);
$sbtp->execute();
$sbtpResult = $sbtp;
}
catch (PDOException $e){
echo "Database Error";
}
$subTFlag = false;
while($row2 = $sbtpResult->fetch(PDO::FETCH_OBJ))
{
$subTFlag = true;
//display subtopicss in a list style with anchor pointing to the subtopics
//echo "<a href='../contents/content.php?ID=".$row2->SubtopicID."'>";
echo "<div class='span3'>".$row2->SubtopicName."</div>";
//echo "</a>";
echo "<div class='span1'>".$row2->DateUpdated."</div>";
echo "</div><div class='row-fluid'>";
echo "<div class='span5'> </div>";
echo "<div class='span3'> </div>";
} // End Subtopics loop
if ($subTFlag == false) echo "<div class='span3'> </div><div class='span1'>".$row1->dateupdated."</div>";
echo "</div><div class='row-fluid'>";
echo "<div class='span5'> </div>";
} // End Topics loop
if ($topFlag == false) echo "<div class='span3'> </div><div class='span3'> </div><div class='span1'>".$row->Dateupdated."</div>";
echo "</div><div class='row-fluid'>";
} // End Subjects loop
echo "</div>";
echo "</div>";
?>
</div>
</div>
<!-- Footer -->
<?php
include '../footer.php';
?>
<script src="http://code.jquery.com/jquery-1.9.0.min.js"></script>
<script src="../../assets/js/bootstrap.js"></script>
<script src="../../assets/js/bootstro.min.js"></script>
<script>
$(document).ready(function()
{
$('#help').click(function()
{
bootstro.start(".bootstro",
{
finishButton: ''
});
});
});
</script>
</body>
</html> | true |
09acf470ad9d4f6474d82c8f64f2f65d92083313 | PHP | Szandra01/AFP2_Genshin | /Frontend/php/protected/admin/edit_user.php | UTF-8 | 1,654 | 2.75 | 3 | [] | no_license | <?php if(!isset($_SESSION['isadmin']) || $_SESSION['isadmin'] != 1) : ?>
<h1>Hozzáférés megtagadva!</h1>
<?php else : ?>
<?php
if (isset($_GET["e"]))
{
$id = $_GET["e"];
}
?>
<?php
if(isset($_GET["e"]) && !empty($_GET['e'])) {
$query = "SELECT id, username, isregistered FROM users WHERE id = '$id'";
require_once DATABASE_CONTROLLER;
$users = getList($query);
}
?>
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['updateuser'])) {
$postData = [
'isregistered' => $_POST['isregistered']
];
if($postData['isregistered'] < 0 || $postData['isregistered'] > 1) {
echo "0 vagy 1-et adj meg!";
}
else {
$query = "UPDATE users SET first_name = :first_name, last_name = :last_name, email = :email, permission = :permission, varos = :varos, utca = :utca WHERE id = '$id'";
$params = [
':isregistered' => $postData['isregistered']
];
require_once DATABASE_CONTROLLER;
if(!executeDML($query, $params)) {
echo "Hiba az adatbevitel során!";
} header('Location: index.php?P=user_list');
}
}
?>
<form method="post">
<?php foreach($users as $u) : ?>
<input type="hidden" name="new" value="1" />
<input name="id" type="hidden" value="<?php echo $id;?>" />
<div class="form-row">
<div class="form-group col-md-3">
<label for="userRegistered">Regisztrált</label>
<input type="text" class="form-control" id="userRegistered" name="isregistered" value="<?php echo $u['isregistered']?>">
</div>
</div>
<button type="submit" class="btn btn-primary" name="updateuser">Felhasználó jogosultságának frissítése</button>
<?php endforeach; ?>
</form>
<?php endif; ?>
| true |
9265557ab431a5409cb0bfd83acb9ee2c838ae06 | PHP | kimich7/kimicmuh | /page_1.php | UTF-8 | 2,563 | 2.921875 | 3 | [] | no_license | <?php
//分頁程式
function page($page,$total,$phpfile,$pagesize=10,$pagelen=7){
$pagecode = '';//定義變數,存放分頁生成的HTML
$page = intval($page);//避免非數字頁碼
$total = intval($total);//保證總記錄數值類型正確
if(!$total) return array();//總記錄數為零返回空數組
$pages = ceil($total/$pagesize);//計算總分頁
//處理頁碼合法性
if($page<1) $page = 1;
if($page>$pages) $page = $pages;
//計算查詢偏移量
$offset = $pagesize*($page-1);
//頁碼範圍計算
$init = 1;//起始頁碼數
$max = $pages;//結束頁碼數
$pagelen = ($pagelen%2)?$pagelen:$pagelen+1;//頁碼個數
$pageoffset = ($pagelen-1)/2;//頁碼個數左右偏移量
//生成html
$pagecode='<div class="page">';
$pagecode.="<span>$page/$pages</span>";//第幾頁,共幾頁
//如果是第一頁,則不顯示第一頁和上一頁的連接
if($page!=1){
$pagecode.="<a href=\"{$phpfile}?page=1\"><<</a>";//第一頁
$pagecode.="<a href=\"{$phpfile}?page=".($page-1)."\"><</a>";//上一頁
}
//分頁數大於頁碼個數時可以偏移
if($pages>$pagelen){
//如果當前頁小於等於左偏移
if($page<=$pageoffset){
$init=1;
$max = $pagelen;
}else{//如果當前頁大於左偏移
//如果當前頁碼右偏移超出最大分頁數
if($page+$pageoffset>=$pages+1){
$init = $pages-$pagelen+1;
}else{
//左右偏移都存在時的計算
$init = $page-$pageoffset;
$max = $page+$pageoffset;
}
}
}
//生成html
for($i=$init;$i<=$max;$i++){
if($i==$page){
$pagecode.='<span>'.$i.'</span>';
} else {
$pagecode.="<a href=\"{$phpfile}?page={$i}\">$i</a>";
}
}
if($page!=$pages){
$pagecode.="<a href=\"{$phpfile}?page=".($page+1)."\">></a>";//下一頁
$pagecode.="<a href=\"{$phpfile}?page={$pages}\">>></a>";//最後一頁
}
$pagecode.='</div>';
return array('pagecode'=>$pagecode,'sqllimit'=>' limit '.$offset.','.$pagesize);
}
?>
<style type="text/css">
body{font-family:Tahoma;}
.page{padding:2px;font-size:20px;}
.page a{border:1px solid #ccc;padding:0 5px 0 5px;margin:2px;text-decoration:none;color:#333;}
.page span{padding:0 5px 0 5px;margin:2px;background:#09f;color:#fff;border:1px solid #09c;}
</style> | true |
2dfbc0d00b6066f38a84a06a61ceaae77c27ce80 | PHP | homework-bazaar/SnakePHP | /lib/system/function/function.get.php | UTF-8 | 2,173 | 3.109375 | 3 | [] | no_license | <?php
/**
* SnakePHP URL parser.
* This is a multifunction with 3 uses, to be used for URL slash-separated parameters.
* 1) no parameter : returns URI
* 2) 1 parameter (integer) : returns one specific URI parameter
* 3) 2 parameters : replace specified URI parameter with $replace param.
*
* @param Integer $get[optional] URI parameter index to get - default: none (all URI)
* @param String $replace[optional] String which will replace specified URI parameter - default: none
*/
function get($get = '', $replace = false) {
$uri = $_SERVER['REQUEST_URI'];
if(strpos($uri, '?')):
$explode = explode('?', $uri);
$uri = $explode[0];
endif;
if(!$replace):
if(!empty($uri)):
if(empty($get)):
return (string) $uri;
else:
if(preg_match('#^\/#', $uri)):
$uri = substr($uri, 1);
endif;
if(preg_match('#\/$#', $uri)):
$uri = substr($uri, 0, -1);
endif;
if(empty($uri)):
return 'index';
endif;
$list = array();
$var = explode('/', $uri);
$i = 1;
foreach($var as $key):
$list[$i] = $key;
$i++;
endforeach;
if(isset($list[$get])):
return $list[$get];
else:
return 'index';
endif;
endif;
else:
return 'index';
endif;
else:
$getArray = explode('/', substr($uri, 1, -1));
if ($getArray[0]==='') {
$getArray = array_slice($getArray, 1);
}
for($i = 0; $i < $get; $i++):
if(!isset($getArray[$i])):
$getArray[$i] = 'index';
endif;
endfor;
$getArray[$get-1] = $replace;
$return = preg_replace('#\/\/#','/','/'.implode('/', $getArray).'/');
$return = preg_replace('#\/index\/$#', '/', $return);
return $return;
endif;
}
| true |
3bba0946187d5eec823c29c2757feec5dc43f2a6 | PHP | Daniel1147/php-design-pattern | /app/src/CompositePattern/Todo.php | UTF-8 | 360 | 3.40625 | 3 | [] | no_license | <?php
namespace DesignPattern\CompositePattern;
class Todo implements TodoComponent
{
private $todo;
public function __construct(string $todo)
{
$this->todo = $todo;
}
public function rendor(string $prefix = ''): string
{
$rendor = sprintf("%s<li>%s<\\li>\n", $prefix, $this->todo);
return $rendor;
}
}
| true |
02a3f2fcf1d11155ec7409ef57e1edeb845516dd | PHP | heldercosta9027/redes | /At10/At10-ex2.php | UTF-8 | 524 | 3.078125 | 3 | [] | no_license | <?php
$Dados=array(2,5,10, 'Maria',2.5,'Rui',8,);
echo "Valores do array";
for($i=0; $i<10; $i++)
echo $Dados[$i]. " ";
echo "<br>";
echo"<br> Valores do array: <br>";
for ($i=0; $i<10; $i++)
echo $Dados[$i]. "<br>";
echo "<br>";
$Dados[]=7;
$Dados[]="Carlos";
$Dados[1]="Pedro";
$Dados[4]=50;
$Dados[5]="Ruizinho";
$Dados[7]=" ";
echo "Valores do array: ";
for ($i=0; $i<12; $i++)
echo $Dados[$i]. " ";
echo "<br>";
echo "<br>";
echo $Dados[2]=" ";
echo $Dados[5]=" ";;
echo $Dados[9]=" ";;
echo "<br>";
?>
| true |
eb3106b373aab3f204f94e72481a5fd58e4c5396 | PHP | eHealth4everyone/owid-grapher | /app/Http/Controllers/LogosController.php | UTF-8 | 4,008 | 2.625 | 3 | [
"MIT"
] | permissive | <?php namespace App\Http\Controllers;
use URL;
use Input;
use Validator;
use Redirect;
//use ARequest;
//use Session;
//use App\Setting;
use Illuminate\Http\Request;
use App\Logo;
use Cache;
class LogosController extends Controller {
public function index()
{
$logos = Logo::all();
return view('logos.index', ['logos' => Logo::all()]);
}
/**
* Show the form for creating a new resource.
*
* @return Response
*/
public function create()
{
return view( 'logos.create' );
}
/**
* Store a newly created resource in storage.
*
* @return Response
*/
public function store(Request $request)
{
$validator = Validator::make($request->all(),
['name' => 'required', 'image' => 'required']
);
if ($validator->fails())
return Redirect::to('logos/create')->withInput()->withErrors($validator);
$file = Input::file('image');
$svg = file_get_contents($file->getRealPath());
Logo::create(['name' => $request->get('name'), 'svg' => $svg]);
return redirect()->route('logos.index')->with('message', 'Logo created.')->with('message-class', 'success');
}
/**
* Display the specified resource.
*
* @param int $id
* @return Response
*/
public function show(Logo $logo)
{
return view( 'logos.show', compact( 'logo' ) );
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return Response
*/
public function edit(Logo $logo)
{
return view( 'logos.edit', compact( 'logo' ) );
}
/**
* Update the specified resource in storage.
*
* @param int $id
* @return Response
*/
public function update(Logo $logo, Request $request)
{
// getting all of the post data
$file = array('image' => Input::file('image'));
// setting up rules
$rules = array(); //mimes:jpeg,bmp,png and for max size max:10000
// doing the validation, passing post data, rules and the messages
$validator = Validator::make($file, $rules);
Cache::flush();
$input = array_except( $request->all(), [ '_method', '_token', 'image' ] );
if ($validator->fails()) {
//send back to the page with the input data and errors
return redirect()->route( 'logos.edit', $request->id )->withInput()->withErrors($validator);
} else {
//checking file is valid.
$image = Input::file( 'image' );
if( !empty( $image ) ) {
//updating new image
$url = $this->uploadFile( Input::file( 'image' ) );
if( $url ) {
$input['url'] = $url;
} else {
Session::flash('error', 'Uploaded file is not valid');
return redirect()->route( 'logos.index' )->with( 'message', 'Uploaded file is not valid.')->with( 'message-class', 'error' );
}
}
$logo->update($input);
return redirect()->route( 'logos.index' )->with( 'message', 'Logo udpated.')->with( 'message-class', 'success' );
}
Cache::flush();
return redirect()->route('sources.show', $source->id)->with( 'message', 'Source updated.')->with( 'message-class', 'success' );
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return Response
*/
public function destroy(Logo $logo, Request $request)
{
//delete database record
$logo->delete();
//delete actual file
\File::delete($logo->url);
Cache::flush();
return redirect()->route('logos.index')->with('message', 'Logo deleted.');
}
private function uploadFile( $imageFile ) {
if( $imageFile->isValid() ) {
$destinationPath = 'uploads'; // upload path
$extension = $imageFile->getClientOriginalExtension(); // getting image extension
$fileName = rand( 11111, 99999 ).'.'.$extension; // renameing image
$imageFile->move( $destinationPath, $fileName ); // uploading file to given path// sending back with message
//construct fileUrl
$fileUrl = $destinationPath .'/'. $fileName;
return $fileUrl;
}
return false;
}
} | true |
e6e02547417f77fd6cf6c9c2a597425d1870bf80 | PHP | thonixon321/designhouse-api | /app/Jobs/UploadImage.php | UTF-8 | 4,180 | 3.015625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Jobs;
use Image;
use File;
use App\Models\Design;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Storage;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
//ShouldQueue makes sure this job can get taken care of in the background
//while the user continues to do other things (like add meta data for the image they are uploading) - this is also set up in the .env file by changing the default 'sync' to 'database' and we made the migration for the jobs table, which will handle these queued jobs by running php artisan queue:table and php artisan migrate; then after that when a user uploads a file, they get an immediate response back and don't have to wait for it to upload to s3 or wherever, the jobs table will get that entry and on the server or in some command you have to run php artisan queue:work (set a timer or something) and that queued job will process or fail. If it fails, you have the option to try again (send an email saying it failed maybe)
class UploadImage implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $design;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct(Design $design)
{
//set as class variable
$this->design = $design;
}
/**
* Execute the job.
*
* @return void
*/
//upload the image file
public function handle()
{
//disk accessed from the design data we passed in
$disk = $this->design->disk;
$file_name = $this->design->image;
//file path on our system
$original_file = storage_path() . '/uploads/original/' . $file_name;
//do a try catch in case there is an error with an upload and we want to notify the user
try {
//create Large image and save to tmp disk (using the Image intervention package we pulled in)
Image::make($original_file)
->fit(800, 600, function($constraint){
//can add in constraints here to the resize image process
//we don't want to distort the aspect ratio of the image (so if image doesn't work at 800, 600 it will change the 600 to fit the aspect ratio)
$constraint->aspectRatio();
})
->save($large = storage_path('uploads/large/'. $file_name)); //save to the similar spot as the original file location
//create Thumbnail image and save to tmp disk (using the Image intervention package we pulled in)
Image::make($original_file)
->fit(250, 200, function($constraint){
$constraint->aspectRatio();
})
->save($thumbnail = storage_path('uploads/thumbnail/'. $file_name)); //save to the similar spot as the original file location
//now store images to permanent disk (could be amazon s3 or local public)
//original image - put() moves image from src location to a destination, first param is the destination you're trying to put the files to, second is the file itself
if(Storage::disk($disk)->put('uploads/designs/original/'.$file_name, fopen($original_file, 'r+'))) {
//delete the temp file from system
File::delete($original_file);
}
//large image
if(Storage::disk($disk)->put('uploads/designs/large/'.$file_name, fopen($large, 'r+'))) {
//delete the temp file from system
File::delete($large);
}
//thumbnail image
if(Storage::disk($disk)->put('uploads/designs/thumbnail/'.$file_name, fopen($thumbnail, 'r+'))) {
//delete the temp file from system
File::delete($thumbnail);
}
//update database record with success flag
$this->design->update([
'upload_successful' => true
]);
} catch(Exception $e) {
Log::error($e->getMessage());
}
}
}
| true |
4e5ebb0a4ea3a531cf8615b360450395db3db1c5 | PHP | edenolam/bilsoc | /src/Bilan_Social/Bundle/ConsoBundle/Services/BsConsoPrecedentPreparator.php | UTF-8 | 9,999 | 2.65625 | 3 | [] | no_license | <?php
namespace Bilan_Social\Bundle\ConsoBundle\Services;
use Symfony\Component\Config\Definition\Exception\Exception;
use PDO;
/**
* Service BsConsoPrecedentPreparator
*
*/
class BsConsoPrecedentPreparator
{
private $config_base_path = __DIR__.'/../Resources/config/bsPrecedentConfig/';
private $jsonFile = 'config.json';
private $em;
private $token_storage;
private $user;
private $user_bdd;
private $host_bdd;
private $name_bdd;
private $port_bdd;
private $password_bdd;
private $annee;
private $driver;
private $idColl;
private $connection;
/**
* BsConsoPrecedentPreparator constructor.
*
* @param $em EntityManager The default EntityManager
*/
public function __construct($em, $token_storage)
{
$this->em = $em;
$this->driver = "pdo_mysql";
$this->token_storage = $token_storage;
$this->user = $token_storage->getToken()->getUser();
if($this->user !== null){
try{
$this->collectivite = $this->user->getCollectivite();
}catch(Exception $exception){
$session = $this->get('session');
$this->idColl = $session->get('coll_id');
}
}
}
/*
* Methode permettant de retourner le tableau du fichier de configuration
*/
public function getJsonConfigfile(){
$json = file_get_contents( $this->config_base_path.$this->jsonFile);
//Decode JSON
$array = json_decode($json,true);
return $array;
}
/* Methode permetant de retourner l indicateur donné dans le fichier de configuration */
public function getJsonIndicateurConfig($indicateur, $annee){
$json = file_get_contents( $this->config_base_path.$this->jsonFile);
//Decode JSON
$array_config = json_decode($json,true);
$array_ind = $array_config[$this->annee]['indicateur'];
$exist = array_key_exists ($indicateur, $array_ind);
if($exist){
return $array_ind[$indicateur];
}else{
return null;
}
}
public function prepareBddConnection($annee){
// Read JSON file
$this->annee = $annee;
$json_data = $this->getJsonConfigfile();
$config = null;
if(isset($json_data[$this->annee])){
$this->password_bdd = $json_data[$this->annee]['bdd_mdp'];
$this->user_bdd = $json_data[$this->annee]['bdd_user'];
$this->name_bdd = $json_data[$this->annee]['bdd_name'];
$this->port_bdd = $json_data[$this->annee]['bdd_port'];
$this->host_bdd = $json_data[$this->annee]['bdd_host'];
$this->indicateur = isset($json_data[$this->annee]['indicateur']) ? $json_data[$this->annee]['indicateur'] : null;
$config = array(
'driver' => $this->driver,
'user' => $this->user_bdd,
'password' => $this->password_bdd,
'dbname' => $this->name_bdd,
'host' => $this->host_bdd,
'port' => $this->port_bdd,
);
}
return $config;
}
public function getDoctrineConnection($annee){
$conn = $this->prepareBddConnection($annee);
$this->connection = \Doctrine\ORM\EntityManager::create(
$conn,
$this->em->getConfiguration(),
$this->em->getEventManager()
);
return $this->connection;
}
public function getPdoConnection($annee){
$conn = $this->prepareBddConnection($annee);
if(isset($conn)){
try {
$conn = new PDO("mysql:host=".$conn['host'].";"."port=".$conn['port'].";"."dbname=".$conn['dbname'], $conn['user'], $conn['password'],array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
$this->connection = $conn;
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
$conn = null;
}
}else{
}
return isset($conn) ? $conn : null ;
}
public function getIdAncienBilanSocial($annee, $username){
$connectionPdo = $this->getPdoConnection($annee);
$bilan_social = null;
if(isset($connectionPdo)){
try{
$stmt = $connectionPdo->prepare(
'SELECT bsc.ID_BILASOCICONS
FROM utilisateur u
JOIN bilan_social_consolide bsc ON bsc.ID_COLL = u.ID_COLL
WHERE u.USERNAME = :Username;'
);
$stmt->bindParam(':Username',$username, PDO::PARAM_STR);
$stmt->execute();
$bilan_social = $stmt->fetch(PDO::FETCH_ASSOC);
$this->annee = $annee;
}catch(\Exception $e){
return $e->getMessage();
}
}
return !empty($bilan_social) ? $bilan_social['ID_BILASOCICONS'] : null;
}
public function getFirstPastIdBilanSocial($startDate,$username){
$annee_minus = $startDate-1;
$id_bilan = null;
if(array_key_exists($startDate, $this->getJsonConfigfile())){
$id_bilan = $this->getIdAncienBilanSocial($startDate, $username);
if($id_bilan===null){
$id_bilan = $this->getFirstPastIdBilanSocial($annee_minus,$username);
}
}
return $id_bilan;
}
public function getIndPrecedent($annee, $username, $indKey, $bilanSocialConsoActuel){
$idAncienBilanSocial = $this->getFirstPastIdBilanSocial($annee,$username);
$strOrder = null;
$array_ind_template = null;
$extra_var = array();
if(isset($idAncienBilanSocial)){
$indConfig = $this->getJsonIndicateurConfig($indKey, $annee);
if(isset($indConfig)){
$strOrder = $this->getOrder($indConfig,$bilanSocialConsoActuel);
$query = $this->preparBddQueryInd($indConfig,$idAncienBilanSocial,$strOrder);
$connectionPdo = $this->connection;
if(isset($query) && isset($connectionPdo)){
$stmt = $connectionPdo->prepare($query);
$stmt->execute();
$ind = $stmt->fetchAll(PDO::FETCH_ASSOC);
$array_ind_template = [
"indicateur" => $ind,
"annee" => $this->annee,
"extra_var" => array()
];
if(isset($indConfig['extra_var'])){
foreach ($indConfig['extra_var'] as $key => $value){
$query_extra_var = $this->preparBddQueryInd($value,$idAncienBilanSocial,null);
$stmt = $connectionPdo->prepare($query_extra_var);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
array_push($array_ind_template['extra_var'], $result[0]);
}
}
}
}
}
return $array_ind_template !== null && !empty($array_ind_template) ? $array_ind_template : null;
}
public function getOrder($indConfig, $bilanSocialConsoActuel){
// dump($bilanSocialConsoActuel); exit();
if($indConfig){
$collections = null;
$orderField = null;
$refMethod = null;
$refMethodCode = null;
$array_str_order_id = [];
if(isset($indConfig['order'])){
$refMethod = $indConfig['order']['refMethod'];
$orderField = $indConfig['order']['orderField'];
$refMethodCode = $indConfig['order']['refMethodCode'];
}
if(isset($refMethod)){
if(method_exists($bilanSocialConsoActuel, $indConfig['method'])){
$strMethod = $indConfig['method'];
$collections = $bilanSocialConsoActuel->$strMethod();
foreach ($collections as $key => $value){
array_push($array_str_order_id, '"' . $value->$refMethod()->$refMethodCode().'"');
}
$str_cd = implode(',',$array_str_order_id);
}
}
}
return isset($str_cd) ? $str_cd : null ;
}
public function preparBddQueryInd($indConfig,$idAncienBilanSocial,$strOrder = null){
if(isset($indConfig) && isset($idAncienBilanSocial)){
/* Creation de la query pour ensuite recuperer sous forme de tableau l indicateur souhaité */
if(isset($indConfig['field'])){
$query = 'SELECT ' . $indConfig['field'];
}else{
$query = 'SELECT * ';
}
$query .= ' FROM '. $indConfig['table'] .' ind';
if(isset($indConfig['order'])){
$query .= ' JOIN ' .$indConfig['order']["tableRef"] . ' ref ON ind.'.$indConfig['order']["joinKey"].' = ref.'.$indConfig['order']["joinKey"];
}
if(isset($indConfig['subRef'])) {
$query .= ' JOIN ' .$indConfig['subRef']['tableRef'] . ' ref2 ON ref.'.$indConfig['order']['subRefJoinKey'].' = ref2.'.$indConfig['subRef']['joinKey'];
}
$query .= ' WHERE ind.ID_BILASOCICONS = ' .$idAncienBilanSocial;
if($strOrder !== null){
$query .= ' AND ref.'.$indConfig['order']['orderField'] . ' IN('.$strOrder.')
ORDER BY FIELD(ref.'.$indConfig['order']['orderField'].','.$strOrder.')';
}
$query .= ';';
}
return isset($query) ? $query : null ;
}
} | true |
6d848eae48188659a4e933246d00402f5e0dddf7 | PHP | sanjayaharshana/thingerbits_core | /vendor/spatie/once/src/Cache.php | UTF-8 | 2,014 | 2.8125 | 3 | [
"MIT"
] | permissive | <?php
namespace Spatie\Once;
class Cache
{
/** @var array */
public static $values = [];
/**
* Determine if a value exists for a given object / hash.
*
* @param mixed $object
* @param string $backtraceHash
*
* @return bool
*/
public static function has($object, string $backtraceHash): bool
{
$objectHash = static::objectHash($object);
if (! isset(static::$values[$objectHash])) {
return false;
}
return array_key_exists($backtraceHash, static::$values[$objectHash]);
}
/**
* Retrieve a value for an object / hash.
*
* @param mixed $object
* @param string $backtraceHash
*
* @return mixed
*/
public static function get($object, string $backtraceHash)
{
return static::$values[static::objectHash($object)][$backtraceHash];
}
/**
* Set a cached value for an object / hash.
*
* @param mixed $object
* @param string $backtraceHash
* @param mixed $value
*/
public static function set($object, string $backtraceHash, $value)
{
static::addDestroyListener($object, $backtraceHash);
static::$values[static::objectHash($object)][$backtraceHash] = $value;
}
/**
* Forget the stored items for the given objectHash.
*
* @param string $objectHash
*/
public static function forget(string $objectHash)
{
unset(static::$values[$objectHash]);
}
protected static function objectHash($object) : string
{
return is_string($object) ? $object : spl_object_hash($object);
}
protected static function addDestroyListener($object)
{
if (is_string($object)) {
return;
}
$randomPropertyName = '___once_listener__'.rand(1, 1000000);
if (isset($object->$randomPropertyName)) {
return;
}
$object->$randomPropertyName = new Listener($object);
}
}
| true |
675bc8be88988fafd4dd01cb807e4bbb357e1edd | PHP | moeinxyz/nodes | /modules/embed/models/Embed.php | UTF-8 | 1,954 | 2.625 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
namespace app\modules\embed\models;
use Yii;
/**
* This is the model class for table "{{%embed}}".
*
* @property string $id
* @property string $hash
* @property string $url
* @property string $type
* @property string $frequency
* @property string $response
* @property string $created_at
* @property string $updated_at
*/
class Embed extends \yii\db\ActiveRecord
{
const TYPE_OEMBED = 'OEMBED';
const TYPE_EXTRACT = 'EXTRACT';
/**
* @inheritdoc
*/
public static function tableName()
{
return Yii::$app->getModule('embed')->embedTable;
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['hash', 'url', 'response'], 'required'],
[['response'], 'string'],
//// [['url'],'url'],
[['type'],'in','range'=>[self::TYPE_EXTRACT,self::TYPE_OEMBED]],
[['frequency'], 'integer'],
//// [['created_at', 'updated_at'], 'safe'],
[['hash'], 'string', 'max' => 32],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'hash' => 'Hash',
'url' => 'Url',
'type' => 'Type',
'frequency' => 'Frequency',
'reponse' => 'Response',
'created_at' => 'Created At',
'updated_at' => 'Updated At',
];
}
public function beforeValidate() {
if (parent::beforeValidate()){
$this->hash = md5($this->url);
$this->updated_at = new \yii\db\Expression('NOW()');
if ($this->isNewRecord){
$this->created_at = new \yii\db\Expression('NOW()');
$this->frequency = 1;
}
return TRUE;
}
return FALSE;
}
}
| true |
06836c4828579ec44638b7bdd92648bafd5c8be9 | PHP | boyonglab/theresia-core | /src/Http/Router.php | UTF-8 | 3,809 | 3.265625 | 3 | [
"MIT"
] | permissive | <?php
namespace Boyonglab\Theresia\Core\Http;
class Router
{
/**
* The request we're working with.
*
* @var string
*/
public $request;
private $httpMethods = ['get', 'post', 'put', 'delete'];
/**
* The $routePaths array will contain our URI's.
* @var array
*/
public $routePaths = [];
// The folling is a list of array containing uri's and callbacks based on request methods.
public $routes = [];
/**
* For this example, the constructor will be responsible
* for parsing the request.
*
* @param array $request
*/
public function __construct($request)
{
/**
* This is a very (VERY) simple example of parsing
* the request. We use the $_SERVER superglobal to
* grab the URI.
*/
$this->request = $request;
}
public function __call($func, $params) {
if(in_array($func, $this->httpMethods)) {
$uri = $params[0];
$pt = stripos ($uri, '{');
if($pt) {
$struct = substr($uri, 0, $pt - 1) . str_repeat('/(.*)', substr_count($uri, '{')) ;
$struct = str_replace('/', '\/', $struct);
$regx = '/^' . $struct . '/';
// preg_match($regx, '/survey/ok/good', $output);
$uri = $regx;
}
$this->routes[$func][$uri] = $params[1];
}
}
/**
* Add a route and callback to our $routes array.
*
* @param string $uri
* @param Callable $fn
*/
public function addRoute(string $uri, \Closure $fn) : void
{
$this->routes[$uri] = $fn;
}
/**
* Check if $routes array has method.
* @return boolean
*/
public function hasMethod() : bool
{
return array_key_exists($this->request->getMethod(), $this->routes);
}
/*
public function get(string $uri, \Closure $fn) : void
{
$this->routes['get'][$uri] = $fn;
}
*/
/**
* Determine is the requested route exists in our
* routes array.
*
* @param string $uri
* @return bool
*/
public function hasRoute(string $uri) : bool
{
return $this->hasMethod() ?
array_key_exists($uri, $this->routes[$this->request->getMethod()]) :
false;
}
/**
* Run the router.
*
* @return mixed
*/
public function run()
{
if(!$this->hasMethod()) {
throw new \Exception('404');
}
if($this->hasRoute($this->request->getPath())) {
$this->routes[$this->request->getMethod()][$this->request->getPath()]->call($this);
} else {
$result = [];
$keys = array_filter(array_keys($this->routes[$this->request->getMethod()]), function($data) {
return substr_count($data, '(.*)') > 0;
});
foreach($keys as $key) {
$match = preg_match($key, $this->request->getPath(), $output);
if($match == 1) {
$result['uri'] = $key;
$result['output'] = $output;
$result['params_count'] = substr_count($key, '(.*)');
}
}
$display = null;
if (count($result) > 0) {
$args = $result['output'];
unset($args[0]);
$this->routes[$this->request->getMethod()][$result['uri']]->call($this, ...$args);
} else {
throw new \Exception('404');
}
}
}
}
/**
* Create a new router instance.
*/
// $router = new Router($_SERVER);
/**
* Add a "hello" route that prints to the screen.
*/
/*$router->addRoute('hello', function() {
echo 'Well, hello there!!';
});
*/
/**
* Run it!
*/
//$router->run();
| true |
db0849cad7abe63419a743aa129b5a79783ac0e9 | PHP | MrStein01/Website | /system/classes/animeform.php | UTF-8 | 2,475 | 2.78125 | 3 | [] | no_license | <?PHP
class AnimeForm {
public function displayAll () {
$rows = DataBase::Current()->ReadRows("SELECT * FROM {'dbprefix'}anime;");
$anime = new Anime();
if($rows) {
foreach ($rows as $row) {
$noLeer = str_replace(' ','',$row->name);
$anime->getAnime($row->name);
?>
<script type="text/javascript">
$(function(){
$(".showAnime<?PHP echo $noLeer; ?>").click(function(){
linkForm<?PHP echo $noLeer ?>();
});
});
function linkForm<?PHP echo $noLeer ?>() {
document.getElementById('oneAnime<?PHP echo $row->name; ?>').submit();
}
</script>
<form id="oneAnime<?PHP echo $row->name; ?>" action="<?PHP echo $_SERVER[REQUEST_URI]; ?>" method="post">
<div class="view col-m-3">
<input type="hidden" value="<?PHP echo $row->name ?>" name="anime" />
<div class="overlay">
<a href="javascript:void(0)" class="showAnime<?PHP echo $noLeer; ?>"><?PHP echo $row->name ?></a>
</div>
<div class="background">
<div class="cover">
<?php
echo $anime->getPicDir();
?>
</div>
</div>
</div>
</form>
<?PHP
}
}
}
public function displayAnime ($name) {
/* TODO: Das hier auf das Modal bekommen */
$anime = new Anime();
$anime->getAnime($name);
?>
<div class="background">
<div class="cover">
<?php echo $anime->getPicDir(); ?>
</div>
<div class="description">
<?php echo $anime->description; ?>
</div>
<div class="eps">
<?php
$eps = DataBase::Current()->ReadRows("SELECT * from {'dbprefix'}episodes WHERE name='".$name."'");
if ($eps) {
foreach ($eps as $ep) {
?>
<div class="episode<?PHP echo $ep->episode; ?>">
<?php
echo $ep->name;
echo $ep->title;
?>
</div>
<?php
}
}
?>
</div>
</div>
<?PHP
}
}
?>
| true |
f91aae4c65d1f54ef5861004738ac2964f2e4631 | PHP | felixlonald99/Proyek_FPW_2020 | /database/seeds/RoomSeeder.php | UTF-8 | 2,052 | 2.953125 | 3 | [
"MIT"
] | permissive | <?php
use App\RoomModel;
use Illuminate\Database\Seeder;
class RoomSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
//101-120 single standard
for ($i = 1; $i <= 20; $i++) {
$room = new RoomModel();
if ($i<10) {
$room->room_number = "10".$i;
} else {
$room->room_number = "1".$i;
}
$room->roomtype_id = 1;
$room->room_status = 0;
$room->save();
}
//201-220 standard twin bed
for ($i = 1; $i <= 20; $i++) {
$room = new RoomModel();
if ($i<10) {
$room->room_number = "20".$i;
} else {
$room->room_number = "2".$i;
}
$room->roomtype_id = 2;
$room->room_status = 0;
$room->save();
}
//301-320 deluxe room
for ($i = 1; $i <= 20; $i++) {
$room = new RoomModel();
if ($i<10) {
$room->room_number = "30".$i;
} else {
$room->room_number = "3".$i;
}
$room->roomtype_id = 3;
$room->room_status = 0;
$room->save();
}
//401-415 luxury room
for ($i = 1; $i <= 15; $i++) {
$room = new RoomModel();
if ($i<10) {
$room->room_number = "40".$i;
} else {
$room->room_number = "4".$i;
}
$room->roomtype_id = 4;
$room->room_status = 0;
$room->save();
}
//501-510 family suite
for ($i = 1; $i <= 10; $i++) {
$room = new RoomModel();
if ($i<10) {
$room->room_number = "50".$i;
} else {
$room->room_number = "5".$i;
}
$room->roomtype_id = 5;
$room->room_status = 0;
$room->save();
}
}
}
| true |
c2ab2a6f700c3cc948929dc5c0c504e80997c2c6 | PHP | tarikmanoar/xenforo | /src/XF/Repository/Phrase.php | UTF-8 | 3,433 | 2.5625 | 3 | [] | no_license | <?php
namespace XF\Repository;
use XF\Mvc\Entity\Repository;
use function count;
class Phrase extends Repository
{
/**
* @param \XF\Entity\Language $language
*
* @return \XF\Finder\PhraseMap
*/
public function findEffectivePhrasesInLanguage(\XF\Entity\Language $language)
{
/** @var \XF\Finder\PhraseMap $finder */
$finder = $this->finder('XF:PhraseMap');
$finder
->where('language_id', $language->language_id)
->with('Phrase', true)
->orderTitle()
->pluckFrom('Phrase', 'phrase_id');
return $finder;
}
/**
* @param \XF\Entity\Language $language
* @param $title
*
* @return \XF\Entity\Phrase
*/
public function getEffectivePhraseByTitle(\XF\Entity\Language $language, $title)
{
$finder = $this->finder('XF:PhraseMap');
return $finder
->where('language_id', $language->language_id)
->where('title', $title)
->pluckFrom('Phrase', 'phrase_id')
->fetchOne();
}
/**
* @param \XF\Entity\Language $language
* @param array $titles
*
* @return \XF\Mvc\Entity\ArrayCollection|\XF\Entity\Phrase[]
*/
public function getEffectivePhrasesByTitles(\XF\Entity\Language $language, array $titles)
{
$finder = $this->finder('XF:PhraseMap');
return $finder
->where('language_id', $language->language_id)
->where('title', $titles)
->pluckFrom('Phrase', 'title')
->fetch();
}
public function countOutdatedPhrases()
{
return count($this->getBaseOutdatedPhraseData());
}
public function getOutdatedPhrases()
{
$data = $this->getBaseOutdatedPhraseData();
$phraseIds = array_keys($data);
if (!$phraseIds)
{
return [];
}
$phrases = $this->em->findByIds('XF:Phrase', $phraseIds);
$output = [];
foreach ($data AS $phraseId => $outdated)
{
if (!isset($phrases[$phraseId]))
{
continue;
}
$outdated['phrase'] = $phrases[$phraseId];
$output[$phraseId] = $outdated;
}
return $output;
}
protected function getBaseOutdatedPhraseData()
{
$db = $this->db();
return $db->fetchAllKeyed('
SELECT phrase.phrase_id,
parent.version_string AS parent_version_string
FROM xf_phrase AS phrase
INNER JOIN xf_language AS language ON (language.language_id = phrase.language_id)
INNER JOIN xf_phrase_map AS map ON (map.language_id = language.parent_id AND map.title = phrase.title)
INNER JOIN xf_phrase AS parent ON (map.phrase_id = parent.phrase_id AND parent.version_id > phrase.version_id)
WHERE phrase.language_id > 0
ORDER BY phrase.title
', 'phrase_id');
}
public function quickCustomizePhrase(\XF\Entity\Language $language, $title, $text, array $extra = [])
{
$existingPhrase = $this->getEffectivePhraseByTitle($language, $title);
if (!$existingPhrase)
{
// first time this phrase exists
$phrase = $this->em->create('XF:Phrase');
$phrase->language_id = $language->language_id;
$phrase->title = $title;
$phrase->addon_id = ''; // very likey to be correct, can be overridden if needed
}
else if ($existingPhrase->language_id != $language->language_id)
{
// phrase exists in a parent
$phrase = $this->em->create('XF:Phrase');
$phrase->language_id = $language->language_id;
$phrase->title = $title;
$phrase->addon_id = $existingPhrase->addon_id;
}
else
{
// phrase already exists in this language
$phrase = $existingPhrase;
}
$phrase->phrase_text = $text;
$phrase->bulkSet($extra);
$phrase->save();
return $phrase;
}
} | true |
09e5a42f62b8d05d13c5fd00010d07725880979e | PHP | stym06/project_web2017001 | /timesjobs/action.php | UTF-8 | 6,064 | 2.65625 | 3 | [] | no_license | <?php
include('dbconnect.php');
//For SIDEBAR CATEGORIES
if(isset($_POST['get_cat'])){
$sql="SELECT * FROM industry";
$run_query=mysqli_query($conn,$sql);
$numrows=mysqli_num_rows($run_query);
echo '
<div class="nav nav-pills nav-stacked" >
<li class="active"><a href="#"><h4>Categories</h4></a></li>
';
if($numrows){
while($row=mysqli_fetch_array($run_query)){
$name=$row['industry_name'];
$id=$row['id'];
echo "
<li><a href='#' id=".$id." class='category_sidebar'>$name</a></li>
";
}
echo '</div>';
}
}
//FOR SIDEBAR COMPANIES
if(isset($_POST['get_comp'])){
$sql="SELECT * FROM company";
$run_query=mysqli_query($conn,$sql);
$numrows=mysqli_num_rows($run_query);
echo '
<div class="nav nav-pills nav-stacked" >
<li class="active"><a href="#"><h4>Companies</h4></a></li>
';
if($numrows){
while($row=mysqli_fetch_array($run_query)){
$name=$row['company_name'];
echo "<li><a href='#' id='".$name."' class='category_sidebar2'>$name</a></li>";
}
echo '</div>';
}
}
//FOR FEATURED JOBS ON INDEX.PHP AND HOME.PHP
if(isset($_POST['feed_jobs'])){
$sql="SELECT * FROM job ORDER BY RAND() LIMIT 3";
$run_query=mysqli_query($conn,$sql);
$numrows=mysqli_num_rows($run_query);
if($numrows){
while($row=mysqli_fetch_array($run_query)){
$id=$row['job_id'];
$title=$row['job_title'];
$company=$row['company_name'];
$exp=$row['experience'];
$salary=$row['salary'];
$location=$row['location'];
$skills=$row['skills'];
$descr=$row['descr'];
$sql2="SELECT * FROM company WHERE company_name='$company'";
$run_query2=mysqli_query($conn,$sql2);
$rowz=mysqli_fetch_array($run_query2);
$logo=$rowz['logo'];
echo "
<div class='col-sm-6 col-md-4 job_thumbnail'>
<div class='thumbnail job_thumbnail'>
<img src='$logo' width='200px' height='220px'>
<div class='caption'>
<h3>$title</h3>
<div class='text-muted' style='display: inline-block;'>$company</div>
<br><br><i class='fa fa-briefcase'></i>
<span class='exp'>$exp</span><br>
<span class='location'>Location: $location</span>
<br>
<p><a href='#' class='btn btn-primary detail' jid='$id' role='button'>View Job</a> </p>
</div>
</div>
</div>
";
}
echo '';
}
}
//FOR CATEGORISE FILTER -- INDUSTRY
if(isset($_POST['category_feed'])){
$id=$_POST['id'];
$sql="SELECT * FROM job WHERE industry='$id'";
$run_query=mysqli_query($conn,$sql);
$numrows=mysqli_num_rows($run_query);
if($numrows){
while($row=mysqli_fetch_array($run_query)){
$id=$row['job_id'];
$title=$row['job_title'];
$company=$row['company_name'];
$exp=$row['experience'];
$salary=$row['salary'];
$location=$row['location'];
$skills=$row['skills'];
$descr=$row['descr'];
$sql2="SELECT * FROM company WHERE company_name='$company'";
$run_query2=mysqli_query($conn,$sql2);
$rowz=mysqli_fetch_array($run_query2);
$logo=$rowz['logo'];
echo "
<div class='col-sm-6 col-md-4 job_thumbnail'>
<div class='thumbnail job_thumbnail'>
<img src='$logo' width='200px' height='200px'>
<div class='caption'>
<h3>$title</h3>
<div class='text-muted' style='display: inline-block;'>$company</div>
<br><br><i class='fa fa-briefcase'></i>
<span class='exp'>$exp</span><br>
<span class='location'>Location: $location</span>
<br>
<p><a href='#' class='btn btn-primary detail' jid='$id' role='button'>View Job</a> </p>
</div>
</div>
</div>
";
}
}
else
{
echo "<img src='assets/images/Nothing_Face-512.png' width='100px' height='100px' style='margin-left:50%; margin-top:20%;'><br><span style='margin-left:49%; color:black;'>Weird. No jobs found!</span>";
}
}
//FOR CATEGORISE FILTER -- COMPANY
if(isset($_POST['category_feed2'])){
$id=$_POST['id'];
$sql="SELECT * FROM job WHERE company_name='$id'";
$run_query=mysqli_query($conn,$sql);
$numrows=mysqli_num_rows($run_query);
if($numrows){
while($row=mysqli_fetch_array($run_query)){
$id=$row['job_id'];
$title=$row['job_title'];
$company=$row['company_name'];
$exp=$row['experience'];
$salary=$row['salary'];
$location=$row['location'];
$skills=$row['skills'];
$descr=$row['descr'];
$sql2="SELECT * FROM company WHERE company_name='$company'";
$run_query2=mysqli_query($conn,$sql2);
$rowz=mysqli_fetch_array($run_query2);
$logo=$rowz['logo'];
echo "
<div class='col-sm-6 col-md-4 job_thumbnail'>
<div class='thumbnail job_thumbnail'>
<img src='$logo' width='200px' height='200px'>
<div class='caption'>
<h3>$title</h3>
<div class='text-muted' style='display: inline-block;'>$company</div>
<br><br><i class='fa fa-briefcase'></i>
<span class='exp'>$exp</span><br>
<span class='location'>Location: $location</span>
<br>
<p><a href='#' class='btn btn-primary detail' jid='$id' role='button'>View Job</a> </p>
</div>
</div>
</div>
";
}
}
else
{
echo "<img src='https://cdn2.iconfinder.com/data/icons/smiling-face/512/Nothing_Face-512.png' width='100px' height='100px' style='margin-left:50%; margin-top:20%;'><br><span style='margin-left:49%; color:black;'>Weird. No jobs found!</span>";
}
}
//For admin-panel
if(isset($_POST['admin_login'])){
session_start();
$email=$_POST['email'];
$pwd=$_POST['password'];
$_SESSION['admin']=$email;
if($email=='admin' && $password=='1234'){
header('location:manage.php');
}
header('location:admin.php');
}
?> | true |
2a86bcc413a8492d8d3c6303eaa3cf5dfad0a637 | PHP | molodoi/Contacts | /Ticme/Contacts/Controller/Test/Registry.php | UTF-8 | 1,164 | 2.578125 | 3 | [] | no_license | <?php
namespace Ticme\Contacts\Controller\Test;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
class Registry extends Action
{
/**
* @var \Magento\Framework\Registry
*/
protected $_registry;
public function __construct(
Context $context,
\Magento\Framework\Registry $registry
)
{
$this->_registry = $registry;
parent::__construct($context);
}
// Check http://domain.com/contacts/test/registry
public function execute()
{
echo 'I create my registry value for MyVar:<br />';
$this->_registry->register('myVar','Ticme');
echo '- value : '.$this->_registry->registry('myVar').'<br /><br />';
echo 'I edit my registry value for MyVar:<br />';
$this->_registry->unregister('myVar');
$this->_registry->register('myVar','Ticme 2');
echo '- value : '.$this->_registry->registry('myVar').'<br /><br />';
echo 'I delete my registry value for MyVar:<br />';
$this->_registry->unregister('myVar');
echo '- value : '.$this->_registry->registry('myVar').'<br /><br />';
}
} | true |
17e6751c59c11e486b449d3628f0b090a14695ed | PHP | MatheusTomaz/sisqrcode | /model/cliente/clienteModel.php | UTF-8 | 3,180 | 2.65625 | 3 | [] | no_license | <?php
session_start();
require_once("../../config/config.php");
require_once("../../bean/cliente/clienteBean.php");
Class ClienteModel{
function getCliente($campos, $tabela, $options=" "){
$query = "SELECT $campos FROM $tabela $options";
// die($query);
return mysql_query($query);
}
function setCliente($values){
$query = "INSERT INTO cliente (nome,endereco_id)
VALUES('{$values->getNome()}',
'{$values->getEnderecoId()}')";
// die($query);
return mysql_query($query);
}
function removeCliente($id){
$query = "DELETE FROM cliente WHERE id = $id";
return mysql_query($query);
}
function removeEndereco($id){
$query = "DELETE FROM endereco WHERE id = $id";
// die($query);
return mysql_query($query);
}
// function setCliente($values){
// $fabricaConexao = new FabricaConexao();
// $pdo = $fabricaConexao->getTransacao();
// $query1 = $pdo->query("INSERT INTO cliente (nome,endereco_id)
// VALUES('{$values->getNome()}',
// '{$values->getEnderecoId()}')");
// $query2 = $pdo->query("INSERT INTO endereco (cidade,estado,pais,rua,numeroCasa,bairro,complemento,telefone,cnpj)
// VALUES ('{$values->getCidade()}',
// '{$values->getEstado()}',
// '{$values->getPais()}',
// '{$values->getRua()}',
// '{$values->getNumeroCasa()}',
// '{$values->getBairro()}',
// '{$values->getComplemento()}',
// '{$values->getTelefone()}',
// '{$values->getCnpj()}')");
// if(!$query1 || !$query2){
// $pdo->rollBack(); /* Desfaz a inserção na tabela de movimentos em caso de erro na query da tabela conta */
// $status = false;
// }else{
// $pdo->commit(); /* Se não houve erro nas querys, confirma os dados no banco */
// $status = true;
// }
// return $status;
// }
function setEndereco($values){
$query = "INSERT INTO endereco (cidade,estado,pais,rua,numeroCasa,bairro,complemento,telefone,cnpj)
VALUES ('{$values->getCidade()}',
'{$values->getEstado()}',
'{$values->getPais()}',
'{$values->getRua()}',
'{$values->getNumeroCasa()}',
'{$values->getBairro()}',
'{$values->getComplemento()}',
'{$values->getTelefone()}',
'{$values->getCnpj()}')";
// die($query);
return mysql_query($query);
}
}
?>
| true |
b393c7f96e641c0ca827338eecf36e78dc1f0488 | PHP | JeremyDps/forum | /logout/logout.php | UTF-8 | 518 | 2.59375 | 3 | [] | no_license | <?php
session_start();
if ($_SESSION['connecte'] == true) {
// Supression des variables de session et de la session
$_SESSION = array();
session_destroy();
// Supression des cookies de connexion automatique
setcookie('login', '');
setcookie('pass_hache', '');
header('Location: ../accueil_base/accueil.html');
}else{ // Dans le cas contraire on t'empêche d'accéder à cette page en te redirigeant vers la page que tu veux.
header('Location: ../connexion/connexion.php');
}
?>
| true |
7a7f1f9a452ab549f843b133b7f972368527352a | PHP | StefanCsPurge/Web-Programming | /Exam_practice/php-channels-2020/back.php | UTF-8 | 4,401 | 2.65625 | 3 | [] | no_license | <?php
include ('connection.php');
//include ('Asset.php');
try {
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$con = OpenConnection();
$json = json_decode(file_get_contents('php://input'), true);
$uid = $json['userid'];
// $names = $json['name'];
// $descriptions = $json['desc'];
// $values = $json['value'];
//
// for($i=0; $i < sizeof($names); $i++){
//
// $sql = sprintf("INSERT INTO assets (userid, name, description, value) VALUES (%d,'%s','%s',%d)",$uid,$names[$i],$descriptions[$i],$values[$i]);
//
// $con->query($sql);
// }
header('HTTP/1.1 200 OK');
CloseConnection($con);
exit;
}
else if (isset($_GET['name']))
{
$name = $_GET['name'];
$con = OpenConnection();
$sql = "SELECT id FROM persons where name = '$name' LIMIT 1";
$query = $con->query($sql);
$row = mysqli_fetch_row($query);
$userId= $row[0];
$query = "SELECT * FROM channels WHERE ownerid='$userId'";
$result = mysqli_query($con, $query);
if(mysqli_num_rows($result)>0){
echo "<table>";
echo "<tr>";
echo "<th>ID</th>";
echo "<th>OwnerID</th>";
echo "<th>Name</th>";
echo "<th>Description</th>";
echo "<th>Subscribers</th>";
echo "</tr>";
while ($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>".$row['id']."</td>";
echo "<td>".$row['ownerid']."</td>";
echo "<td>".$row['name']."</td>";
echo "<td>".$row['description']."</td>";
echo "<td>".$row['subscribers']."</td>";
echo "</tr>";
}
echo "</table>";
}
header('HTTP/1.1 200 OK');
CloseConnection($con);
}
else if (isset($_GET['userid']) && !isset($_GET['channel']))
{
$id = $_GET['userid'];
$con = OpenConnection();
$query = "SELECT name,description,subscribers FROM channels";
$result = mysqli_query($con, $query);
if(mysqli_num_rows($result)>0){
echo "<table>";
echo "<tr>";
echo "<th>Name</th>";
echo "<th>Description</th>";
echo "</tr>";
while ($row = mysqli_fetch_array($result)){
$subs_arr = explode (",", $row['subscribers']);
foreach($subs_arr as $element) {
$sub = explode (":", $element);
if($sub[0] == $id){
echo "<tr>";
echo "<td>".$row['name']."</td>";
echo "<td>".$row['description']."</td>";
echo "</tr>";
break;
}
}
}
echo "</table>";
}
header('HTTP/1.1 200 OK');
CloseConnection($con);
}
else if (isset($_GET['channel']))
{
$id = $_GET['userid'];
$chname = $_GET['channel'];
$newSubs = "";
$con = OpenConnection();
$query = "SELECT subscribers FROM channels where name='".$chname."'";
$result = mysqli_query($con, $query);
if(mysqli_num_rows($result)>0){
if ($row = mysqli_fetch_array($result)){
$subs_arr = explode (",", $row['subscribers']);
$found = false;
foreach($subs_arr as $element) {
$sub = explode (":", $element);
if($sub[0] == $id){
$sub[1] = date("Y-m-d");
$found = true;
}
$newSubs = $newSubs.$sub[0].":".$sub[1].",";
}
if(!$found)
$newSubs = $newSubs.$id.":".date("Y-m-d");
$sql = sprintf("UPDATE channels SET subscribers='%s' WHERE name='%s'",$newSubs,$chname);
$con->query($sql);
echo "Subscription successful";
}
else
echo "Subscription failed";
}
else
echo "Subscription failed";
header('HTTP/1.1 200 OK');
CloseConnection($con);
}
} catch (Exception $e) {
header('HTTP/1.1 500 INTERNAL_SERVER_ERROR');
exit;
}
| true |
0488793bc95a62931ab42bd55bffe4558d315072 | PHP | btrebach/wp-auto-pins | /views.php | UTF-8 | 23,536 | 2.515625 | 3 | [] | no_license | <?php
/*
* General directory views
*/
if (!class_exists('WPBDP_DirectoryController')) {
class WPBDP_DirectoryController {
public $action = null;
public function __construct() {
add_action( 'wp', array( $this, '_handle_action'), 10, 1 );
$this->_extra_sections = array();
}
public function init() {
$this->listings = wpbdp_listings_api();
}
public function check_main_page(&$msg) {
$msg = '';
$wpbdp = wpbdp();
if (!$wpbdp->_config['main_page']) {
if (current_user_can('administrator') || current_user_can('activate_plugins'))
$msg = __('You need to create a page with the [businessdirectory] shortcode for the Business Directory plugin to work correctly.', 'WPBDM');
else
$msg = __('The directory is temporarily disabled.', 'WPBDM');
return false;
}
return true;
}
public function _handle_action(&$wp) {
if ( is_page() && get_the_ID() == wpbdp_get_page_id( 'main' ) ) {
$action = get_query_var('action') ? get_query_var('action') : ( isset( $_REQUEST['action'] ) ? $_REQUEST['action'] : '' );
if (get_query_var('category_id') || get_query_var('category')) $action = 'browsecategory';
if (get_query_var('tag')) $action = 'browsetag';
if (get_query_var('id') || get_query_var('listing')) $action = 'showlisting';
if (!$action) $action = 'main';
$this->action = $action;
} else {
$this->action = null;
}
}
public function get_current_action() {
return $this->action;
}
public function dispatch() {
switch ($this->action) {
case 'showlisting':
return $this->show_listing();
break;
case 'browsecategory':
return $this->browse_category();
break;
case 'browsetag':
return $this->browse_tag();
break;
case 'editlisting':
case 'submitlisting':
return $this->submit_listing();
break;
case 'sendcontactmessage':
return $this->send_contact_message();
break;
case 'deletelisting':
return $this->delete_listing();
break;
case 'upgradetostickylisting':
return $this->upgrade_to_sticky();
break;
case 'viewlistings':
return $this->view_listings(true);
break;
case 'renewlisting':
require_once( WPBDP_PATH . 'views/renew-listing.php' );
$renew_page = new WPBDP_RenewListingPage();
return $renew_page->dispatch();
break;
case 'payment-process':
return $this->process_payment();
break;
case 'search':
return $this->search();
break;
default:
return $this->main_page();
break;
}
}
/* Show listing. */
public function show_listing() {
if (!$this->check_main_page($msg)) return $msg;
if (get_query_var('listing') || isset($_GET['listing'])) {
if ($posts = get_posts(array('post_status' => 'publish', 'numberposts' => 1, 'post_type' => WPBDP_POST_TYPE, 'name' => get_query_var('listing') ? get_query_var('listing') : wpbdp_getv($_GET, 'listing', null) ) )) {
$listing_id = $posts[0]->ID;
} else {
$listing_id = null;
}
} else {
$listing_id = get_query_var('id') ? get_query_var('id') : wpbdp_getv($_GET, 'id', null);
}
if ( !$listing_id )
return;
$html = '';
if ( isset($_GET['preview']) )
$html .= wpbdp_render_msg( _x('This is just a preview. The listing has not been published yet.', 'preview', 'WPBDM') );
$html .= wpbdp_render_listing($listing_id, 'single', false, true);
return $html;
}
/* Display category. */
public function browse_category($category_id=null) {
if (!$this->check_main_page($msg)) return $msg;
if (get_query_var('category')) {
if ($term = get_term_by('slug', get_query_var('category'), WPBDP_CATEGORY_TAX)) {
$category_id = $term->term_id;
} else {
$category_id = intval(get_query_var('category'));
}
}
$category_id = $category_id ? $category_id : intval(get_query_var('category_id'));
$listings_api = wpbdp_listings_api();
query_posts(array(
'post_type' => WPBDP_POST_TYPE,
'post_status' => 'publish',
'posts_per_page' => wpbdp_get_option( 'listings-per-page' ) > 0 ? wpbdp_get_option( 'listings-per-page' ) : -1,
'paged' => get_query_var('paged') ? get_query_var('paged') : 1,
'orderby' => wpbdp_get_option('listings-order-by', 'date'),
'order' => wpbdp_get_option('listings-sort', 'ASC'),
'tax_query' => array(
array('taxonomy' => WPBDP_CATEGORY_TAX,
'field' => 'id',
'terms' => $category_id)
)
));
$html = wpbdp_render( 'category',
array(
'category' => get_term( $category_id, WPBDP_CATEGORY_TAX ),
'is_tag' => false
),
false );
wp_reset_query();
return $html;
}
/* Display category. */
public function browse_tag() {
if (!$this->check_main_page($msg)) return $msg;
$tag = get_term_by('slug', get_query_var('tag'), WPBDP_TAGS_TAX);
$tag_id = $tag->term_id;
$listings_api = wpbdp_listings_api();
query_posts(array(
'post_type' => WPBDP_POST_TYPE,
'post_status' => 'publish',
'posts_per_page' => wpbdp_get_option( 'listings-per-page' ) > 0 ? wpbdp_get_option( 'listings-per-page' ) : -1,
'paged' => get_query_var('paged') ? get_query_var('paged') : 1,
'orderby' => wpbdp_get_option('listings-order-by', 'date'),
'order' => wpbdp_get_option('listings-sort', 'ASC'),
'tax_query' => array(
array('taxonomy' => WPBDP_TAGS_TAX,
'field' => 'id',
'terms' => $tag_id)
)
));
$html = wpbdp_render( 'category',
array(
'category' => get_term( $tag_id, WPBDP_TAGS_TAX ),
'is_tag' => true
),
false );
wp_reset_query();
return $html;
}
/* display listings */
public function view_listings($include_buttons=false) {
/******************************************************************** */
include "map.php";
/*********************************** TEST ********************************/
$paged = 1;
if (get_query_var('page'))
$paged = get_query_var('page');
elseif (get_query_var('paged'))
$paged = get_query_var('paged');
query_posts(array(
'post_type' => WPBDP_POST_TYPE,
'posts_per_page' => wpbdp_get_option( 'listings-per-page' ) > 0 ? wpbdp_get_option( 'listings-per-page' ) : -1,
'post_status' => 'publish',
'paged' => intval($paged),
'orderby' => wpbdp_get_option('listings-order-by', 'date'),
'order' => wpbdp_get_option('listings-sort', 'ASC')
));
$html = wpbdp_capture_action( 'wpbdp_before_viewlistings_page' );
$html .= wpbdp_render('businessdirectory-listings', array(
'excludebuttons' => !$include_buttons
), true);
$html .= wpbdp_capture_action( 'wpbdp_after_viewlistings_page' );
wp_reset_query();
return $html;
}
public function submit_listing() {
require_once( WPBDP_PATH . 'views/submit-listing.php' );
$submit_page = new WPBDP_SubmitListingPage( isset( $_REQUEST['listing_id'] ) ? $_REQUEST['listing_id'] : 0 );
return $submit_page->dispatch();
}
/*
* Send contact message to listing owner.
*/
public function send_contact_message() {
if ($listing_id = wpbdp_getv($_REQUEST, 'listing_id', 0)) {
$current_user = is_user_logged_in() ? wp_get_current_user() : null;
$author_name = htmlspecialchars(trim(wpbdp_getv($_POST, 'commentauthorname', $current_user ? $current_user->data->user_login : '')));
$author_email = trim(wpbdp_getv($_POST, 'commentauthoremail', $current_user ? $current_user->data->user_email : ''));
$message = trim(wp_kses(stripslashes(wpbdp_getv($_POST, 'commentauthormessage', '')), array()));
$validation_errors = array();
if (!$author_name)
$validation_errors[] = _x("Please enter your name.", 'contact-message', "WPBDM");
if ( !wpbdp_validate_value( $author_email, 'email' ) )
$validation_errors[] = _x("Please enter a valid email.", 'contact-message', "WPBDM");
if (!$message)
$validation_errors[] = _x('You did not enter a message.', 'contact-message', 'WPBDM');
if (wpbdp_get_option('recaptcha-on')) {
if ($private_key = wpbdp_get_option('recaptcha-private-key')) {
if ( !function_exists( 'recaptcha_get_html' ) )
require_once(WPBDP_PATH . 'libs/recaptcha/recaptchalib.php');
$resp = recaptcha_check_answer($private_key, $_SERVER['REMOTE_ADDR'], $_POST['recaptcha_challenge_field'], $_POST['recaptcha_response_field']);
if (!$resp->is_valid)
$validation_errors[] = _x("The reCAPTCHA wasn't entered correctly.", 'contact-message', 'WPBDM');
}
}
if (!$validation_errors) {
$headers = "MIME-Version: 1.0\n" .
"From: $author_name <$author_email>\n" .
"Reply-To: $author_email\n" .
"Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n";
$subject = "[" . get_option( 'blogname' ) . "] " . sprintf(_x('Contact via "%s"', 'contact email', 'WPBDM'), wp_kses( get_the_title($listing_id), array() ));
$wpbdmsendtoemail=wpbusdirman_get_the_business_email($listing_id);
$time = date_i18n( __('l F j, Y \a\t g:i a'), current_time( 'timestamp' ) );
$body = wpbdp_render_page(WPBDP_PATH . 'templates/email/contact.tpl.php', array(
'listing_url' => get_permalink($listing_id),
'name' => $author_name,
'email' => $author_email,
'message' => $message,
'time' => $time
), false);
$html = '';
// TODO: should use WPBDP_Email instead
if(wp_mail( $wpbdmsendtoemail, $subject, $body, $headers )) {
$html .= "<p>" . _x("Your message has been sent.", 'contact-message', "WPBDM") . "</p>";
} else {
$html .= "<p>" . _x("There was a problem encountered. Your message has not been sent", 'contact-message', "WPBDM") . "</p>";
}
$html .= sprintf('<p><a href="%s">%s</a></p>', get_permalink($listing_id), _x('Return to listing.', 'contact-message', "WPBDM"));
return $html;
} else {
return wpbdp_listing_contact_form( $listing_id, $validation_errors );
}
}
}
/*
* Directory views/actions
*/
public function main_page() {
$html = '';
/******************************************************************** */
include "map.php";
/*********************************** TEST ********************************/
if ( count(get_terms(WPBDP_CATEGORY_TAX, array('hide_empty' => 0))) == 0 ) {
if (is_user_logged_in() && current_user_can('install_plugins')) {
$html .= wpbdp_render_msg( _x('There are no categories assigned to the business directory yet. You need to assign some categories to the business directory. Only admins can see this message. Regular users are seeing a message that there are currently no listings in the directory. Listings cannot be added until you assign categories to the business directory.', 'templates', 'WPBDM'), 'error' );
} else {
$html .= "<p>" . _x('There are currently no listings in the directory.', 'templates', 'WPBDM') . "</p>";
}
}
if (current_user_can('administrator')) {
if ($errors = wpbdp_payments_api()->check_config()) {
foreach ($errors as $error) {
$html .= wpbdp_render_msg($error, 'error');
}
}
}
$listings = '';
if (wpbdp_get_option('show-listings-under-categories'))
$listings = $this->view_listings(false);
$html .= wpbdp_render(array('businessdirectory-main-page', 'wpbusdirman-index-categories'),
array(
'submit_listing_button' => wpbusdirman_post_menu_button_submitlisting(),
'view_listings_button' => wpbusdirman_post_menu_button_viewlistings(),
'action_links' => wpbusdirman_post_menu_button_submitlisting() . wpbusdirman_post_menu_button_viewlistings(),
'search_form' => wpbdp_get_option('show-search-listings') ? wpbdp_search_form() : '',
'listings' => $listings
));
return $html;
}
/*
* Submit listing process.
*/
/*
* @since 2.1.6
*/
public function register_listing_form_section($id, $section=array()) {
$section = array_merge( array(
'title' => '',
'display' => null,
'process' => null,
'save' => null
), $section);
if (!$section['display'] && !$section['process'])
return false;
$section['id'] = $id;
$this->_extra_sections[$id] = (object) $section;
return true;
}
/* Manage Listings */
public function manage_listings() {
if (!$this->check_main_page($msg)) return $msg;
$current_user = is_user_logged_in() ? wp_get_current_user() : null;
$listings = array();
if ($current_user) {
query_posts(array(
'author' => $current_user->ID,
'post_type' => WPBDP_POST_TYPE,
'post_status' => 'publish',
'paged' => get_query_var('paged') ? get_query_var('paged') : 1
));
}
$html = wpbdp_render('manage-listings', array(
'current_user' => $current_user
), false);
if ($current_user)
wp_reset_query();
return $html;
}
public function delete_listing() {
if ($listing_id = wpbdp_getv($_REQUEST, 'listing_id')) {
if ( (wp_get_current_user()->ID == get_post($listing_id)->post_author) || (current_user_can('administrator')) ) {
$post_update = array('ID' => $listing_id,
'post_type' => WPBDP_POST_TYPE,
'post_status' => wpbdp_get_option('deleted-status'));
wp_update_post($post_update);
return wpbdp_render_msg(_x('The listing has been deleted.', 'templates', 'WPBDM'))
. $this->main_page();
}
}
}
/* Upgrade to sticky. */
public function upgrade_to_sticky() {
$listing_id = wpbdp_getv($_REQUEST, 'listing_id');
if ( !$listing_id || !wpbdp_user_can('upgrade-to-sticky', $listing_id) )
return '';
$upgrades_api = wpbdp_listing_upgrades_api();
$listings_api = wpbdp_listings_api();
if ($listings_api->get_payment_status($listing_id) != 'paid' && !current_user_can('administrator')) {
$html = '';
$html .= wpbdp_render_msg(_x('You can not upgrade your listing until its payment has been cleared.', 'templates', 'WPBDM'));
$html .= sprintf('<a href="%s">%s</a>', get_permalink($listing_id), _x('Return to listing.', 'templates', 'WPBDM'));
return $html;
}
$sticky_info = $upgrades_api->get_info($listing_id);
if ($sticky_info->pending) {
$html = '';
$html .= wpbdp_render_msg(_x('Your listing is already pending approval for "featured" status.', 'templates', 'WPBDM'));
$html .= sprintf('<a href="%s">%s</a>', get_permalink($listing_id), _x('Return to listing.', 'templates', 'WPBDM'));
return $html;
}
$action = isset($_POST['do_upgrade']) ? 'do_upgrade' : 'pre_upgrade';
switch ($action) {
case 'do_upgrade':
$payments_api = wpbdp_payments_api();
$transaction_id = $upgrades_api->request_upgrade($listing_id);
if ($transaction_id && current_user_can('administrator')) {
// auto-approve transaction if we are admins
$transaction = $payments_api->get_transaction($transaction_id);
$transaction->status = 'approved';
$transaction->processed_by = 'admin';
$transaction->processed_on = date('Y-m-d H:i:s', time());
$payments_api->save_transaction($transaction);
$html = '';
$html .= wpbdp_render_msg(_x('Listing has been upgraded.', 'templates', 'WPBDM'));
$html .= sprintf('<a href="%s">%s</a>', get_permalink($listing_id), _x('Return to listing.', 'templates', 'WPBDM'));
return $html;
}
return $payments_api->render_payment_page(array(
'title' => _x('Upgrade listing', 'templates', 'WPBDM'),
'transaction_id' => $transaction_id,
'item_text' => _x('Pay %s upgrade fee via %s', 'templates', 'WPBDM'),
'return_link' => array(
get_permalink($listing_id),
_x('Return to listing.', 'templates', 'WPBDM')
)
));
break;
default:
$html = '';
return wpbdp_render('listing-upgradetosticky', array(
'listing' => get_post($listing_id),
'featured_level' => $sticky_info->upgrade
), false);
return $html;
break;
}
}
/* payment processing */
public function process_payment() {
$html = '';
$api = wpbdp_payments_api();
if ($transaction_id = $api->process_payment($_REQUEST['gateway'], $error_message)) {
if ( $error_message ) {
return wpbdp_render_msg($error_message, $type='error');
}
$transaction = $api->get_transaction($transaction_id);
if ($transaction->payment_type == 'upgrade-to-sticky') {
$html .= sprintf('<h2>%s</h2>', _x('Listing Upgrade Payment Status', 'templates', 'WPBDM'));
} elseif ($transaction->payment_type == 'initial') {
$html .= sprintf('<h2>%s</h2>', _x('Listing Submitted', 'templates', 'WPBDM'));
} else {
$html .= sprintf('<h2>%s</h2>', _x('Listing Payment Confirmation', 'templates', 'WPBDM'));
}
if (wpbdp_get_option('send-email-confirmation')) {
$listing_id = $transaction->listing_id;
$message = wpbdp_get_option('payment-message');
$message = str_replace("[listing]", get_the_title($listing_id), $message);
$email = new WPBDP_Email();
$email->subject = "[" . get_option( 'blogname' ) . "] " . wp_kses( get_the_title($listing_id), array() );
$email->to[] = wpbusdirman_get_the_business_email($listing_id);
$email->body = $message;
$email->send();
}
$html .= sprintf('<p>%s</p>', wpbdp_get_option('payment-message'));
}
return $html;
}
/*
* Search functionality
*/
public function search() {
$results = array();
if ( isset( $_GET['dosrch'] ) ) {
$search_args = array();
$search_args['q'] = wpbdp_getv($_GET, 'q', null);
$search_args['fields'] = array(); // standard search fields
$search_args['extra'] = array(); // search fields added by plugins
foreach ( wpbdp_getv( $_GET, 'listingfields', array() ) as $field_id => $field_search )
$search_args['fields'][] = array( 'field_id' => $field_id, 'q' => $field_search );
foreach ( wpbdp_getv( $_GET, '_x', array() ) as $label => $field )
$search_args['extra'][ $label ] = $field;
$listings_api = wpbdp_listings_api();
$results = $listings_api->search( $search_args );
}
/******************************************************************** */
include "map.php";
/*********************************** TEST ********************************/
$form_fields = wpbdp_get_form_fields( array( 'display_flags' => 'search', 'validators' => '-email' ) );
$fields = '';
foreach ( $form_fields as &$field ) {
$field_value = isset( $_REQUEST['listingfields'] ) && isset( $_REQUEST['listingfields'][ $field->get_id() ] ) ? $field->convert_input( $_REQUEST['listingfields'][ $field->get_id() ] ) : $field->convert_input( null );
$fields .= $field->render( $field_value, 'search' );
}
query_posts( array(
'post_type' => WPBDP_POST_TYPE,
'posts_per_page' => wpbdp_get_option( 'listings-per-page' ) > 0 ? wpbdp_get_option( 'listings-per-page' ) : -1,
'paged' => get_query_var('paged') ? get_query_var('paged') : 1,
'post__in' => $results ? $results : array(0),
'orderby' => wpbdp_get_option( 'listings-order-by', 'date' ),
'order' => wpbdp_get_option( 'listings-sort', 'ASC' )
) );
$html = wpbdp_render( 'search',
array(
'fields' => $fields,
'searching' => isset( $_GET['dosrch'] ) ? true : false,
'show_form' => !isset( $_GET['dosrch'] ) || wpbdp_get_option( 'show-search-form-in-results' )
),
false );
wp_reset_query();
return $html;
}
}
} | true |
80cc71b931fa6989910ccb07cf04d025baca6b50 | PHP | sigitsurendra/magangcake | /app/Controller/JobcategoriesController.php | UTF-8 | 6,124 | 2.546875 | 3 | [] | no_license | <?php
App::uses('AppController', 'Controller');
/**
* Jobcategories Controller
*
* @property Jobcategory $Jobcategory
* @property PaginatorComponent $Paginator
* @property SessionComponent $Session
*/
class JobcategoriesController extends AppController {
public function beforeFilter()
{
parent::beforeFilter();
// Allow users to register and logout.
$this->Auth->allow('listofjobcategories');
}
/**
* Components
*
* @var array
*/
public $components = array('Paginator', 'Session');
/**
* index method
*
* @return void
*/
public function index() {
$this->Jobcategory->recursive = 0;
$this->set('jobcategories', $this->Paginator->paginate());
}
/**
* view method
*
* @throws NotFoundException
* @param string $id
* @return void
*/
public function view($id = null) {
if (!$this->Jobcategory->exists($id)) {
throw new NotFoundException(__('Invalid jobcategory'));
}
$options = array('conditions' => array('Jobcategory.' . $this->Jobcategory->primaryKey => $id));
$this->set('jobcategory', $this->Jobcategory->find('first', $options));
}
/**
* add method
*
* @return void
*/
public function add() {
if ($this->request->is('post')) {
$this->Jobcategory->create();
if ($this->Jobcategory->save($this->request->data)) {
$this->Session->setFlash(__('The jobcategory has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The jobcategory could not be saved. Please, try again.'));
}
}
}
/**
* edit method
*
* @throws NotFoundException
* @param string $id
* @return void
*/
public function edit($id = null) {
if (!$this->Jobcategory->exists($id)) {
throw new NotFoundException(__('Invalid jobcategory'));
}
if ($this->request->is(array('post', 'put'))) {
if ($this->Jobcategory->save($this->request->data)) {
$this->Session->setFlash(__('The jobcategory has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The jobcategory could not be saved. Please, try again.'));
}
} else {
$options = array('conditions' => array('Jobcategory.' . $this->Jobcategory->primaryKey => $id));
$this->request->data = $this->Jobcategory->find('first', $options);
}
}
/**
* delete method
*
* @throws NotFoundException
* @param string $id
* @return void
*/
public function delete($id = null) {
$this->Jobcategory->id = $id;
if (!$this->Jobcategory->exists()) {
throw new NotFoundException(__('Invalid jobcategory'));
}
$this->request->allowMethod('post', 'delete');
if ($this->Jobcategory->delete()) {
$this->Session->setFlash(__('The jobcategory has been deleted.'));
} else {
$this->Session->setFlash(__('The jobcategory could not be deleted. Please, try again.'));
}
return $this->redirect(array('action' => 'index'));
}
/**
* admin_index method
*
* @return void
*/
public function admin_index() {
$this->Jobcategory->recursive = 0;
$this->set('jobcategories', $this->Paginator->paginate());
}
/**
* admin_view method
*
* @throws NotFoundException
* @param string $id
* @return void
*/
public function admin_view($id = null) {
if (!$this->Jobcategory->exists($id)) {
throw new NotFoundException(__('Invalid jobcategory'));
}
$options = array('conditions' => array('Jobcategory.' . $this->Jobcategory->primaryKey => $id));
$this->set('jobcategory', $this->Jobcategory->find('first', $options));
}
/**
* admin_add method
*
* @return void
*/
public function admin_add() {
if ($this->request->is('post')) {
$this->Jobcategory->create();
if ($this->Jobcategory->save($this->request->data)) {
$this->Session->setFlash(__('The jobcategory has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The jobcategory could not be saved. Please, try again.'));
}
}
}
/**
* admin_edit method
*
* @throws NotFoundException
* @param string $id
* @return void
*/
public function admin_edit($id = null) {
if (!$this->Jobcategory->exists($id)) {
throw new NotFoundException(__('Invalid jobcategory'));
}
if ($this->request->is(array('post', 'put'))) {
if ($this->Jobcategory->save($this->request->data)) {
$this->Session->setFlash(__('The jobcategory has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The jobcategory could not be saved. Please, try again.'));
}
} else {
$options = array('conditions' => array('Jobcategory.' . $this->Jobcategory->primaryKey => $id));
$this->request->data = $this->Jobcategory->find('first', $options);
}
}
/**
* admin_delete method
*
* @throws NotFoundException
* @param string $id
* @return void
*/
public function admin_delete($id = null) {
$this->Jobcategory->id = $id;
if (!$this->Jobcategory->exists()) {
throw new NotFoundException(__('Invalid jobcategory'));
}
$this->request->allowMethod('post', 'delete');
if ($this->Jobcategory->delete()) {
$this->Session->setFlash(__('The jobcategory has been deleted.'));
} else {
$this->Session->setFlash(__('The jobcategory could not be deleted. Please, try again.'));
}
return $this->redirect(array('action' => 'index'));
}
public function listofjobcategories(){
$this->autoRender = false;
$temp = '%'.$_GET['term'].'%';
$jobcategories = $this->Jobcategory->find('all',array('conditions'=>array('Jobcategory.Name LIKE'=>$temp)));
//Debugger::dump($this->_encodeCities($cities));
echo json_encode($this->_encodeJobCategory($jobcategories));
}
protected function _encodeJobCategory($postData = array()) {
$temp = array();
foreach ($postData as $Jobcategory) {
array_push($temp, array(
'id' => $Jobcategory['Jobcategory']['idJobCategory'],
'label' => $Jobcategory['Jobcategory']['Name'],
'value' => $Jobcategory['Jobcategory']['Name']
));
}
return $temp;
}
}
| true |
e4038789638ad758c9d64367a975961f00be341e | PHP | saiprasadbanda/chatboat | /rest/application/third_party/mailer/mailer.php | UTF-8 | 2,821 | 2.515625 | 3 | [] | no_license | <?php
//error_reporting(E_ALL);
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
function sendemail($toid,$subject,$message)
{
$mail = new PHPMailer(true);
try {
//Server settings
$mail->isSMTP();
$mail->Host = 'mail.secondopinion.co.in';
$mail->SMTPAuth = true;
$mail->Username = 'admin@secondopinion.co.in';
$mail->Password = 'admin@123';
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
$mail->SMTPSecure = 'tls';
$mail->Port = 26;
//Send Email
$mail->setFrom('admin@secondopinion.co.in');
//Recipients
$mail->addAddress($toid);
$mail->addReplyTo('admin@secondopinion.co.in');
//Content
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $message;
$mail->send();
//echo 'Message has been sent';
return 1;
} catch (Exception $e) {
//echo 'Message could not be sent. Mailer Error: '.$mail->ErrorInfo;
return 0;
}
}
function mailCheck($toid,$subject,$message)
{
$mail = new PHPMailer(true);
try {
//Server settings
$mail->isSMTP();
$mail->Host = 'mail.secondopinion.co.in';
$mail->SMTPAuth = true;
$mail->Username = 'admin@secondopinion.co.in';
$mail->Password = 'admin@123';
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
$mail->SMTPSecure = 'tls';
$mail->Port = 26;
//Send Email
$mail->setFrom('admin@secondopinion.co.in');
//Recipients
$mail->addAddress('saiprasad.b@thresholdsoft.com');
$mail->addReplyTo('admin@secondopinion.co.in');
//Content
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $message;
$mail->send();
//echo 'Message has been sent';
} catch (Exception $e) {
//echo 'Message could not be sent. Mailer Error: '.$mail->ErrorInfo;
}
}
?>
| true |