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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
f05c4e47d1d2c6a873f1571227fad5bf3270b7ac | PHP | PEMOHT/gazprom | /src/Domain/ProductValue/ProductValue.php | UTF-8 | 1,579 | 3.125 | 3 | [
"MIT"
] | permissive | <?php
namespace Gazprom\Domain\ProductValue;
use RuntimeException;
/**
* Class ProductValue
* @package Gazprom\Domain\ProductValue
*/
class ProductValue
{
/**
* @var int
*/
private int $id;
/**
* @var string
*/
private string $name;
/**
* @var float
*/
private float $count;
/**
* @var int
*/
private int $type;
/**
* @var int
*/
private int $productId;
/**
* ProductValue constructor.
* @param string $name
* @param float $count
* @param int $type
* @param int $productId
*/
public function __construct(string $name, float $count, int $type, int $productId)
{
$this->checkTypeExist($type);
$this->name = $name;
$this->type = $type;
$this->count = $count;
$this->productId = $productId;
}
/**
* @param int $type
*/
private function checkTypeExist(int $type): void
{
if (!isset(ProductValueTypes::$types[$type])) {
throw new RuntimeException("Type doesn't exist", 500);
}
}
/**
* @param string|null $name
* @param float|null $count
* @param int|null $type
*/
public function update(?string $name, ?float $count, ?int $type): void
{
if (!is_null($type)) {
$this->checkTypeExist($type);
$this->type = $type;
}
if (!is_null($name)) {
$this->name = $name;
}
if (!is_null($count)) {
$this->count = $count;
}
}
} | true |
244ec27d97de5723f4eb9098566305794be693dd | PHP | lidingran/cmf5 | /public/plugins/yunpian/Yunpian.php | UTF-8 | 1,165 | 2.671875 | 3 | [
"Apache-2.0"
] | permissive | <?php
namespace plugins\yunpian;
class Yunpian {
public function sendCode($mobile, $code){
$apikey = "2f89950a6db4a006aea0aa1635548f7d";
$text="【智享云】您的验证码是".$code."。如非本人操作,请忽略本短信";
$ch = curl_init();
/* 设置验证方式 */
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept:text/plain;charset=utf-8',
'Content-Type:application/x-www-form-urlencoded', 'charset=utf-8'));
/* 设置返回结果为流 */
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
/* 设置超时时间*/
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
/* 设置通信方式 */
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// 发送短信
$data=array('text'=>$text,'apikey'=>$apikey,'mobile'=>$mobile);
curl_setopt ($ch, CURLOPT_URL, 'https://sms.yunpian.com/v2/sms/single_send.json');
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
$result = curl_exec($ch);
$error = curl_error($ch);
$array = json_decode($result,true);
return $array;
}
} | true |
edcce8caf5e30444879ccdd655b7e5279b9a53cf | PHP | yozaira/UserAuth | /public/profile.php | UTF-8 | 3,155 | 2.921875 | 3 | [] | no_license | <?php
# Include initialize file to make directories and classes available
require_once '../core/init.php';
# use a short alias for validation class namespace
# or simply call namespace of the used classes
use App\User;
use App\Redirect;
use App\Session;
$user = new User();
# The profile page checks whether the user is indeed logged in,
# if not it redirects him/her to the login page. Otherwise it
# displays the user profile information.
if(!$user->isLoggedIn()){
Redirect::to( 'login-remember.php');
}
?>
<?php include_once 'includes/header.php'; ?>
<div class="wrapper">
<div class="row">
<div class="profile col-md-4 col-centered">
<?php
# display flash messages if available
if(Session::exists('success') ) {
echo '<div class="text-center alert alert-info">'.Session::flashMessage('success').'</div>' ;
}
if(Session::exists('home') ) {
echo '<div class="text-center alert alert-info">'.Session::flashMessage('home').'</div>' ;
}
# The profile page checks whether the user is indeed logged in,
# if not it redirects him/her to the login page. Otherwise it
# displays the user profile information.
if($user->isLoggedIn() ) { ?>
<h1 class="text-center">Hello <?php echo sanitize( $user->getUserData()->name); ?></h1>
<ul class="profile-list">
<li>
<span class="field">Name: </span>
<span class="value"><?php echo sanitize( $user->getUserData()->name); ?></span>
<div class="clear"> </div>
</li>
<li>
<span class="field">Email: </span>
<span class="value"><?php echo sanitize( $user->getUserData()->email ); ?></span>
<div class="clear"> </div>
</li>
<li>
<span class="field">Signup Date: </span>
<span class="value"><?php echo sanitize( $user->getUserData()->joined ); ?></span>
<div class="clear"> </div>
</li>
</ul>
<div>
<ul>
<li> <a href="update.php">Update Profile</a></li>
<li> <a href="changepassword.php">Change Password</a></li>
<!-- When the user clicks Log out, the user is logged out and redirected to the login page again. -->
<li> <a href="logout.php">Log out</a></li>
</ul>
</div>
<?php
# check if user is admin.
# this check can be perform on a page by page basis.
# Administrator has an id of 2 in table group of the db.
# And Users has id of 1
if($user->hasPermission('admin') ) {
echo '<p>You are logged in as an administrator!</p>';
}
else {
echo '<p>If you are an admin, <a href="#">Log in</a> as
administrator or <a href="#">Create an account</a>';
}
} else {
echo '<p> If you dont have an account, <a href="register.php">Register</a> </p>';
echo '<p> Already have an account? <a href="login.php">Log in</a> </p>';
}
?>
</div><!--# end col -->
</div><!--# end row -->
</div><!--# end wrapper -->
| true |
5c65335b64908d8daa73dfc3abd577d1ec0ecf01 | PHP | HugoAlberto/PHP | /Projet Progs/script.php | UTF-8 | 4,623 | 2.984375 | 3 | [] | no_license | <?
function trouverFichier($nom,$emplacement){
include("co.php");
//echo("$emplacement/$nom");
$fichier=fopen("$emplacement/$nom","r");
while($row=fgets($fichier)){
$position1=strpos($row,"function");
$reste=substr($row, $position1-8);
$position2=strpos($reste,"(");
$fin=substr($reste,0,$position2);
$sql="INSERT INTO Fonction (fonNom) VALUES($fin);";
}
}
if(isset($_POST['actionAjout'])&&($_POST['actionAjout']=="Enregistrer")){
include("co.php");
//Récup des infos.
$nomF=$_POST["fonNom"];
$nom=$_POST["inputNom"];
$emplacement=$_POST["inputEmplacement"];
//Requete qui cherche si la fonction entrée existe dans la base.
$sqlNomFonction="SELECT fonNum, fonNom FROM Fonction WHERE fonNom='".$nomF."';";
$resultNomFonction=mysql_query($sqlNomFonction) or die(mysql_error());
while($row = mysql_fetch_array($resultNomFonction)){
if($row["fonNom"]==$nom){
$sql="INSERT INTO Script
VALUES(NULL,'$nom','$emplacement',".$row["fonNom"].");";
echo $sql;
$resultat=mysql_query($sql) or die(mysql_error());
//header('Location: script.php');
}
}
trouverFichier($nom,$emplacement);
}
if(isset($_POST['actionModification']) && ($_POST['actionModification']=="Modifier")){
include("co.php");
//Récup des infos.
$numScript=$_POST["inputNumScript"];
$nom=$_POST["inputNom"];
$emplacement=$_POST["inputEmplacement"];
$sql="UPDATE Script SET scrNom='$nom',scrEmplacement='$emplacement' where scrNum='$numScript'";
$result=mysql_query($sql);
//echo $sql;
header('Location: script.php');
}
if(isset($_POST['actionSupprimer']) && ($_POST['actionSupprimer']=="Supprimer"))
{
include ("co.php");
$numScript=$_POST["scriptSup"];
$sql="DELETE FROM Script WHERE scrNum=".$numScript.";";
$resultat=mysql_query($sql);
header('Location: script.php');
}
?>
<!DOCTYPE html>
<html>
<meta charset="UTF-8"/>
<link rel="stylesheet" href="site.css"/>
<head>
<title>Gestion des scripts</title>
</head>
<div class="accueil"><p><a href="index.php"/>Acceuil</a></p></div>
<center><h1>Gestion des scripts</h1></center>
<body>
<div class="tab">
<p><h2>Scritps présents dans la base de données: </h2></p>
<table>
<thead>
<tr>
<th>Num script</th>
<th>Nom</th>
<th>Emplacement</th>
<th>Nom de la fonction</th>
</tr>
</thead>
<tbody>
<?php
include ("co.php");
$sql="select Script.*, fonNom from Script natural join Fonction";
$result=mysql_query($sql);
while($array=mysql_fetch_array($result))
{
$nomF=$array['fonNom'];
$nom=$array['scrNom'];
$emplacement=$array['scrEmplacement'];
$num=$array['scrNum'];
?>
<tr>
<th><?=$num?></th>
<th><?=$nom?></th>
<th><?=$emplacement?></th>
<th><?=$nomF?></th>
</tr>
<?
}
?>
</tbody>
</table>
</div>
<p><h2>Formulaire de modification: </h2></p>
<div class="tab">
<table>
<?
$sql="select Script.* from Script";
$result=mysql_query($sql);
while($array=mysql_fetch_array($result))
{
$num=$array['scrNum'];
$nom=$array['scrNom'];
$emplacement=$array['scrEmplacement'];
?><tr>
<form name="modif" method="post" action="">
<th>Nom script :<input type="text" name="inputNom" value="<?=$nom?>" size="15"/></th>
<th>Emplacement :<input type="text" name="inputEmplacement" value="<?=$emplacement?>" size="20"/></th>
<input type="hidden" name="inputNumScript" value="<?=$num?>"/>
<th><input type="submit" name="actionModification" value="Modifier"/></th>
</form>
<form name="fSuppression" method="POST" action="">
<input type="hidden" name="scriptSup" value="<?=$num?>"/>
<th><input type="submit" name="actionSupprimer" value="Supprimer"/></th>
</form>
</tr>
<? } ?>
</table>
</div>
</div>
<div class="tab">
<p><h2>Formulaire de saisie: </h2></p>
<table>
<form name="fAjoutFonction" method="POST" action="">
<th>Nom script :<input type="text" name="inputNom" size="15"/></th>
<th>Emplacement :<input type="text" name="inputEmplacement" size="20"/></th>
<th><select name="fonNom">
<?
include("co.php");
$result= mysql_query("SELECT fonNum, fonNom FROM Fonction");
while($row = mysql_fetch_assoc($result)){
echo ('<option value="'.$row['fonNum'].'">'.$row['fonNom'].'</option>');
}
?>
</select></th>
<th><input type="submit" name="actionAjout" value="Enregistrer"/></th>
</form>
</table>
</div>
</body>
</html>
| true |
0320a946667614f490395f3cbe75ed50efaf6e20 | PHP | gobline/flash | /src/FlashInterface.php | UTF-8 | 2,252 | 3.09375 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
/*
* Gobline Framework
*
* (c) Mathieu Decaffmeyer <mdecaffmeyer@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Gobline\Flash;
/**
* Allows to store data across requests and objects with a session or request level scope.
*
* @author Mathieu Decaffmeyer <mdecaffmeyer@gmail.com>
*/
interface FlashInterface
{
/**
* Adds a flash variable for the current request.
*
* @param mixed $name
* @param mixed $value
*
* @throws \InvalidArgumentException
*
* @return mixed
*/
public function now($name, $value);
/**
* Adds a flash variable for the next request.
*
* @param mixed $name
* @param mixed $value
*
* @throws \InvalidArgumentException
*
* @return mixed
*/
public function next($name, $value);
/**
* Keeps flash variables set in the previous request so they will be available in the next request.
*/
public function keep();
/**
* This method takes one or two arguments.
* The first argument is the flash variable you want to get.
* The second optional argument is the default value you want to get back
* in case the flash variable hasn't been found.
* If the second argument is omitted and the variable
* hasn't been found, an exception will be thrown.
*
* @param mixed $args
*
* @throws \InvalidArgumentException
*
* @return mixed
*/
public function get(...$args);
/**
* Check if the flash variable is available in the current request.
*
* @param mixed $name
*
* @throws \InvalidArgumentException
*
* @return bool
*/
public function has($name);
/**
* Returns an array of the flash variables
* available in the current request.
*
* @return array
*/
public function getIterator();
/**
* Returns an array of the flash variables
* available in the current request.
*
* @return array
*/
public function getArrayCopy();
/**
* Returns the number of flash variables available in the current request.
*
* @return int
*/
public function count();
}
| true |
c85259d1e00592018ef618f67725e392a1d941a5 | PHP | ylabio/yii2-rest | /src/filters/FieldsFilter.php | UTF-8 | 1,875 | 2.59375 | 3 | [] | no_license | <?php
namespace ylab\rest\filters;
use yii\helpers\ArrayHelper;
use yii\web\BadRequestHttpException;
/**
* {@inheritdoc}
*
* FieldsFilter for constraints by requested resource fields.
* Example usage:
* ```
* public function behaviors()
* {
* return [
* 'fieldsFilter' => [
* 'class' => FieldsFilter::class,
* 'only' => ['index', 'view'],
* 'fields' => ['id', 'name'],
* ],
* ];
* }
* ```
*
* @property array $fields list of fields which allowed to request:
* - if it's empty, all resource fields are allowed;
* - if it's not empty, only this resource fields are allowed. If in query are requested others fields,
* `BadRequestHttpException` will be thrown.
*/
class FieldsFilter extends AbstractFilter
{
/**
* @inheritdoc
*/
public $queryParam = 'fields';
/**
* @inheritdoc
*/
public function beforeAction($action)
{
foreach ($this->fields as $field) {
if (($pos = mb_strrpos('.', $field)) !== false) {
$this->addRelation(mb_substr($field, 0, $pos));
}
}
$fields = \Yii::$app->request->getQueryParam($this->queryParam);
if (!empty($this->fields)) {
if ($fields === null) {
\Yii::$app->request->setQueryParams(ArrayHelper::merge(
\Yii::$app->request->getQueryParams(),
[$this->queryParam => implode(', ', $this->fields)]
));
} else {
$fields = array_map('trim', explode(',', $fields));
foreach ($fields as $field) {
if (!in_array($field, $this->fields, true)) {
throw new BadRequestHttpException("Getting '$field' field is not allowed.");
}
}
}
}
return true;
}
}
| true |
5a02e1b5dbefac7afe72f86679a0309c2cbc38d7 | PHP | HaR15/PHP-Secure-Authentication-and-Registration-with-Email-Confirmation | /logout.php | UTF-8 | 359 | 2.71875 | 3 | [] | no_license | <?php
//initialize session
session_start();
// regenerates a new session_id to help prevent session hijacking
session_regenerate_id();
//destory all $_SESSION[] variables
session_destroy();
if(isset($_COOKIE['username'])){
setcookie('username', '', time()-3600, '/');
}
header("Location: index.html");
?> | true |
aea205662b220887ad892085729ad9817393b882 | PHP | activismap-projects/activismap-api | /src/ActivisMap/Error/ApiException.php | UTF-8 | 1,258 | 2.8125 | 3 | [] | no_license | <?php
namespace ActivisMap\Error;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
/**
* Created by PhpStorm.
* User: ander
* Date: 4/11/16
* Time: 16:06
*/
class ApiException extends \RuntimeException implements ApiError{
private $error;
private $data;
private $httpCode;
/**
* @param array $apiError
* @param null $data
*/
public function __construct($apiError, $data = null) {
$this->error = $apiError['error'];
$this->httpCode = $apiError['httpCode'];
if ($data == null) {
$this->data = array(
'error' => $this->error
);
} else {
$this->data = array(
'error' => $apiError['error'],
'message' => $data
);
}
parent::__construct($apiError['error'], $apiError['httpCode'], null);
}
/**
* @return string
*/
function getError() {
return $this->error;
}
/**
* @return array
*/
function getData() {
return $this->data;
}
/**
* @return int
*/
function getHttpCode()
{
return $this->httpCode;
}
} | true |
34fea597b665cebaed9d8b743ff843d3fd30bec5 | PHP | dvikas/laravel-vue-admin-panel | /api/app/Transformers/System/TaskTransformer.php | UTF-8 | 652 | 2.5625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Transformers\System;
use App\Entities\ParentTask;
use App\Entities\Task;
use League\Fractal\TransformerAbstract;
class TaskTransformer extends TransformerAbstract
{
protected $parentId;
public function __construct($parentTaskId)
{
$this->parentId = $parentTaskId; //uuid
}
/**
* @param Task $model
* @return array
*/
public function transform(Task $model)
{
return [
'id' => $model->uuid,
'parent_id' => $this->parentId,
'name' => $model->name,
'is_cert_required' => (bool) $model->is_cert_required,
];
}
}
| true |
dd149b87e109a65f778513eab37dcfb958a4491f | PHP | isaq97/isaqsdff2 | /admin/add_hotels.php | UTF-8 | 4,527 | 2.59375 | 3 | [] | no_license | <?php
include "server_hotels.php";
if(isset($_GET['edit'])){
$id = $_GET['edit'];
$edit_state = true;
$rec = mysqli_query($db, "SELECT * FROM hotels WHERE id=$id");
$record = mysqli_fetch_array($rec);
$visit_from = $record['visit_from'];
$visit_to = $record['visit_to'];
$start_date = $record['start_date'];
$return_date = $record['return_date'];
$adult = $record['adult'];
$child = $record['child'];
}
include "header.php";
include "menu.php";
?>
<?php
$link2 = mysqli_connect("localhost","root","");
mysqli_select_db($link2,"sdf2");
?>
<div class="grid_10">
<div class="box round first">
<h2>HOTELS</h2>
<div class="block">
<?php
if(isset($_SESSION['msg'])){ ?>
<div class="msg">
<?php
echo $_SESSION['msg'];}
unset($_SESSION['msg']);
?>
</div>
<table>
<thead>
<tr>
<th>Visit From</th>
<th>Visit To</th>
<th>Start Date</th>
<th>Return Date</th>
<th>Adult</th>
<th>Child</th>
<th colspan="2">action</th>
</tr>
</thead>
<tbody>
<?php while($row = mysqli_fetch_array($results)){ ?>
<tr>
<td>
<?php echo $row['visit_from']; ?>
</td>
<td>
<?php echo $row['visit_to']; ?>
</td>
<td>
<?php echo $row['start_date']; ?>
</td>
<td>
<?php echo $row['return_date']; ?>
</td>
<td>
<?php echo $row['adult']; ?>
</td>
<td>
<?php echo $row['child']; ?>
</td>
<td>
<a class="edit_btn" href="add_hotels.php?edit=<?php echo $row['id']; ?>">Edit</a>
</td>
<td>
<a class="del_btn" href="server_hotels.php?del=<?php echo $row['id']; ?>">Delete</a>
</td>
</tr>
<?php } ?>
</tbody>
</table>
<form method="post" action="server_hotels.php">
<input type="hidden" name="id" value="<?php echo $id; ?>">
<div class="input-group">
<label>Visit From</label>
<input type="text" name="visit_from" value="<?php echo $visit_from; ?>">
</div>
<div class="input-group">
<label>Visit To</label>
<input type="text" name="visit_to" value="<?php echo $visit_to; ?>">
</div>
<div class="input-group">
<label>Start Date</label>
<input type="text" name="start_date" value="<?php echo $start_date; ?>">
</div>
<div class="input-group">
<label>Return Date</label>
<input type="text" name="return_date" value="<?php echo $return_date; ?>">
</div>
<div class="input-group">
<label>Adult</label>
<input type="text" name="adult" value="<?php echo $adult; ?>">
</div>
<div class="input-group">
<label>Child</label>
<input type="text" name="child" value="<?php echo $child; ?>">
</div>
<div class="input-group">
<?php if($edit_state == false){ ?>
<button type="submit" name="save" class="btn">Save</button>
<?php }
else { ?>
<button type="submit" name="update" class="btn">Update</button>
<?php } ?>
</div>
</form>
</div>
</div>
</div>
<?php
include "footer.php";
?>
| true |
78d81b273659286940705e1ed79f3c01c0b8f950 | PHP | JAR-Divine/social-media-clone | /sns/private/functions/login.php | UTF-8 | 1,102 | 2.515625 | 3 | [] | no_license | <?php
if(isset($_POST['Login_btn']))
{
$email = filter_var($_POST['login_email'], FILTER_SANITIZE_EMAIL); //sanitize email
$_SESSION['login_email'] = $email; //store into session variable
$password = md5($_POST['login_password']); //Get password
$check_database_query = mysqli_query($conn,"SELECT * FROM users WHERE email='$email' AND password='$password'");
$check_login_query = mysqli_num_rows($check_database_query);
if($check_login_query == 1) {
$row = mysqli_fetch_array($check_database_query);
$username = $row['username'];
$user_active_query = mysqli_query($conn, "SELECT * FROM users WHERE email='$email' AND user_active='yes'");
if(mysqli_num_rows($user_active_query) == 1) {
$reopen_account = mysqli_query($conn, "UPDATE users SET user_active='no' WHERE email='$email'");
}
$_SESSION['username'] = $username;
header("Location:dashboard.php");
exit();
}
else {
array_push ($error_array, "Email or password is incorrect!<br>");
}
}
?> | true |
def11ccc153096a7d9c8108b811f4e68699c867e | PHP | rahulyhg/echoCMS | /cms/model/admin.php | UTF-8 | 12,313 | 2.5625 | 3 | [
"MIT"
] | permissive | <?php
/**
* model class for admin
*
* @since 1.0.0
* @author Keith Wheatley
* @package echocms\admin
*/
namespace echocms;
class adminModel
{
protected $config;
protected $edit;
protected $dbh;
function __construct(\PDO $dbh, $config)
{
$this->dbh = $dbh;
$this->config = $config;
require CONFIG_DIR. '/model/edit.php';
$this->edit = new editModel($this->dbh, $this->config);
require CONFIG_DIR. '/model/edit_update.php';
$this->editUpdate = new editModelUpdate($this->dbh, $this->config);
}
/**
* Recreate images directory, with sub-directories and images for live and pending items.
* Users SSE(server sent event). See note on SSE in controller/admin/recreateImages.
*
*/
function recreateImages()
{
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$progressPercent = 0;
$imagesCount = $this->countImages();
if (empty($imagesCount)) $imagesCount = 1;
$backupDate = date('Y-m-d-H-i-s');
// backup images file
$this->eventMessage('Backup in progress', 5);
$src = CONFIG_DIR.'/content/images';
$dst = CONFIG_DIR.'/content/backups/images-' . $backupDate;
if ($this->copyDirectory($src, $dst))
$this->eventMessage('Backup complete to directory: images-'. $backupDate, 9);
else
$this->eventMessage('Backing up images FAILED, did not proceed with recreate images', 100);
// create new folders
$percentPerImage = floor(90 / $imagesCount);
$this->eventMessage('Recreating images in progress:', $progressPercent);
ini_set('max_execution_time', 300); //300 seconds = 5 minutes
$baseFolder = 'temp-images-' . $backupDate;
$tempFolder = CONFIG_DIR.'/content/backups/' . $baseFolder;
if (!mkdir($tempFolder)) {
$this->reportError('cms/model/edit_update.php recreateImages. Failed to create folder: '. $tempFolder);
}
$subFolders = array (
'/landscape', '/portrait', '/panorama', '/square',
'/landscape/1x', '/portrait/1x', '/panorama/1x', '/square/1x',
'/landscape/2x', '/portrait/2x', '/panorama/2x', '/square/2x',
'/landscape/3x', '/portrait/3x', '/panorama/3x', '/square/3x',
'/thumbnail', '/uncropped', '/original',);
foreach ($subFolders as $subFolder) {
if (!mkdir($tempFolder . $subFolder)) {
$this->reportError('cms/model/edit_update.php recreateImages. Failed to create folder: '. $tempFolder . $subFolder);
}
}
// recreate live images
$items = $this->edit->getContentItemsList();
foreach ($items as $item) {
$images = $this->edit->getContentImages($item);
foreach ($images as $image) {
$progressPercent += ($percentPerImage);
$this->eventMessage(' ' . $image['src'], $progressPercent);
if (!copy(CONFIG_DIR.'/content/images/original/'.$image['src'], $tempFolder.'/original/'.$image['src']))
error_log('model/edit_update recreateImages. copy to original failed');
if (!copy(CONFIG_DIR.'/content/images/uncropped/'.$image['src'], $tempFolder.'/uncropped/'.$image['src']))
error_log('model/edit_update recreateImages. copy to uncropped failed');
if (!copy(CONFIG_DIR.'/content/images/thumbnail/'.$image['src'], $tempFolder.'/thumbnail/'.$image['src']))
error_log('model/edit_update recreateImages. copy to thumbnail failed');
$this->editUpdate->createWebsiteImages(array($image), 'backups/'.$baseFolder);
}
}
// recreate images for pending items
$items = $this->edit->getPendingItemsList();
foreach ($items as $item) {
$images = $this->edit->getPendingImages($item);
foreach ($images as $image) {
$progressPercent += $percentPerImage;
$this->eventMessage(' ' . $image['src'], $progressPercent);
if (!copy(CONFIG_DIR.'/content/images/original/'.$image['src'], $tempFolder.'/original/'.$image['src']))
error_log('model/edit_update recreateImages. copy to original failed');
if (!copy(CONFIG_DIR.'/content/images/uncropped/'.$image['src'], $tempFolder.'/uncropped/'.$image['src']))
error_log('model/edit_update recreateImages. copy to uncropped failed');
if (!copy(CONFIG_DIR.'/content/images/thumbnail/'.$image['src'], $tempFolder.'/thumbnail/'.$image['src']))
error_log('model/edit_update recreateImages. copy to thumbnail failed');
}
}
// move newly created images to live images directory
$this->removeDirectory(CONFIG_DIR.'/content/images');
rename($tempFolder, CONFIG_DIR.'/content/images');
$this->eventMessage('PROCESS COMPLETE - new images created.', 100);
}
/**
* Send message via SSE(Server-Sent Event)
* used by method recreateImages.
*
* @param string $message
* @param int $progress
*
*/
function eventMessage($message, $progress=0)
{
$d = array('message' => $message , 'progress' => $progress);
echo "data: " . json_encode($d) . PHP_EOL . PHP_EOL;
//ob_flush();
flush();
}
/**
* Count all images, live and pending (but not offline)
* used by method recreateImages.
*
* @return int $imagesCount
*/
function countImages()
{
$stmt = $this->dbh->prepare('SELECT count(*) FROM imagesTable');
$stmt->execute();
$imagesCount = $stmt->fetchColumn();
$status = 'offline';
$stmt = $this->dbh->prepare('SELECT count(*) FROM pendingImagesTable
LEFT JOIN pendingItemsTable ON pendingImagesTable.pending_id=pendingItemsTable.id
WHERE status != "offline"');
$stmt->execute();
$imagesCount = $imagesCount + $stmt->fetchColumn();
return ($imagesCount);
}
/**
* List backups
*
*
* @return string $backups
*/
function listBackups() {
$objects = scandir(CONFIG_DIR.'/content/backups');
foreach ($objects as $key => $value) {
if (!is_dir(CONFIG_DIR.'/content/backups/'.$value) || strtolower(substr($value, 0, 6)) != 'images') {
unset($objects[$key]);
}
}
arsort($objects);
$backups = array();
foreach ($objects as $object) {
$backups[] = array('dir'=>$object, 'size'=>$this->dirSize(CONFIG_DIR.'/content/backups/'.$object));
}
return($backups);
}
/**
* Returns the size of a directory
*
* @param string $dir
*
* @return string $fileSize directory size in human readable format
*/
function dirSize($dir)
{
$size = 0;
foreach(new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dir)) as $file)
{
$size += $file->getSize();
}
if ($size >= 1073741824) {
$fileSize = round($size / 1024 / 1024 / 1024,1) . ' GB';
} elseif ($size >= 1048576) {
$fileSize = round($size / 1024 / 1024,1) . ' MB';
} elseif($size >= 1024) {
$fileSize = round($size / 1024,1) . ' KB';
} else {
$fileSize = $size . ' bytes';
}
return $fileSize;
}
/**
* Create a ZIP archive of directory
*
*
* @param string $dir
*
* @return string $zipPath
*/
function createZipImages($dir)
{
$dirPath = CONFIG_DIR.'/content/backups/'. $dir;
$zipPath = CONFIG_DIR.'/content/backups/'. $dir . '.zip';
$zip = new \ZipArchive();
$result = $zip->open($zipPath, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);
if ($result != true) reportError('Failed to create ZIP archive. zipImages. result: ' . $result);
$files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dirPath),\RecursiveIteratorIterator::LEAVES_ONLY);
foreach ($files as $name => $file)
{
if (!$file->isDir()) // directories are added automatically)
{
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($dirPath) + 1);
$zip->addFile($filePath, $relativePath);
}
}
if (!$zip->close())
reportError('Failed to close ZIP archive.');
return $zipPath;
}
/**
* Download a Zip archive
*
*
* @param string $zipPath
*/
function downloadZip($zipPath) {
if (file_exists($zipPath)) {
ob_get_clean();
header("Pragma: public"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", false); header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=" . basename($zipPath) . ";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . filesize($zipPath));
readfile($zipPath);
}
else $this->reportError('downloadZip. Requested ZIP archive does not exist: ' . $zipPath);
}
/**
* Removes a zip archive including its files and sub-directories
*
*
* @param string $zipPath
*/
function removeZip($zipPath) {
if (!file_exists($zipPath))
$this->reportError('removeZip. Requested ZIP does not exist: ' . $zipPath);
elseif (!unlink($zipPath))
$this->reportError('removeZip. Unable to unlink requested ZIP: ' . $zipPath);
else return true;
}
/**
* Copies a directory including its files and sub-directories
*
*
* @param string $src source directory
* @param string $dst destination directory
*/
function copyDirectory($src, $dst) {
if (!is_dir($src))
$this->reportError('cms/model/admin.php copyDirectory. source is not a directory: '. $src);
if (!mkdir($dst))
$this->reportError('cms/model/admin.php copyDirectory. mkdir - Failed to create directory: '. $dst);
$dir = opendir($src);
while(false !== ( $object = readdir($dir)) ) {
if ( substr($object, 0,1) != '.' ) {
if ( is_dir($src . '/' . $object) ) {
$this->copyDirectory($src . '/' . $object, $dst . '/' . $object);
}
else {
if (!copy($src . '/' . $object, $dst . '/' . $object))
$this->admin->reportError('Copy image FAILED from: ' . $src . '/' . $object);
}
}
}
closedir($dir);
return true;
}
/**
* Removes a directory, including its files and sub-directories
*
*
* @param string $dir
*/
function removeDirectory($dir) {
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (is_dir($dir."/".$object))
$this->removeDirectory($dir."/".$object);
else unlink($dir."/".$object);
}
}
reset($objects);
if (!rmdir($dir)) $this->reportError('cms/model/admin.php removeDirectory. FAILED to remove: '. $dir);
}
else $this->reportError('cms/model/admin.php removeDirectory. not a directory: '. $dir);
}
/**
* Report a system error.
*
* Reports error to error_log then sets header location to error notification page and exits script.
*
* @param string $message
*/
public function reportError($message)
{
error_log ('cms/model/admin.php reportError error message: ' . print_r($message, true) );
header('location: ' . CONFIG_URL. 'error/notify' );
exit();
}
}
| true |
16b70fbc08b19c51da706badbcd9719eadc56587 | PHP | navelpluisje/npCMS | /admin/adminPage.php | UTF-8 | 1,824 | 2.640625 | 3 | [] | no_license | <?php
/**
* Class for creating a admin page
* @author Erwin Goossen
*
*/
global $_DIR;
include_once( $_DIR['dbElements'] . '/dbBlog.php');
include_once( $_DIR['dbElements'] . '/dbNews.php');
include_once( $_DIR['dbElements'] . '/dbUser.php');
include_once( $_DIR['dbElements'] . '/dbPage.php');
include_once( $_DIR['dbElements'] . '/dbPageType.php');
include_once( $_DIR['dbElements'] . '/dbGuest.php');
include_once( $_DIR['dbElements'] . '/dbNewsCategory.php');
include_once( $_DIR['admin'] . '/adminPicsPage.php');
include_once( $_DIR['configs'] . '/clMySmarty.php');
class AdminPage
{
protected $pBreak = '<!-- pagebreak -->';
protected $dbNews;
protected $dbUsers;
protected $dbNewsCategories;
private $page;
public $param;
public $includeTemplate;
public $tpl;
/**
* Constructor
* @param string $param Parameter given with the url
*/
public function __construct($param) {
$this->param = $param;
$id = $this->param[1];
$this->tpl = new SmartyTemplate();
$this->tpl->setTemplate('admin/admin_index.tpl');
$this->tpl->assign('menu', true);
$this->tpl->assign('login', false);
$this->tpl->assign('sessionUser', $_SESSION['user']);
}
private function setPageInfo($id) {
try {
$this->page = new DbPage();
$this->pageInfo = $this->page->getByName($id);
$currentPage = $this->pageInfo;
$this->tpl->assign('cPage',$currentPage);
} catch(Exception $e) {
echo $e->getMessage();
}
}
/**
* Set the template to use withe the page
* @param string $template Name of the template
*/
public function setIncludeTemplate($template) {
$this->includeTemplate = $template;
$this->tpl->assign('template', $this->includeTemplate);
}
/**
* Function for showing the page
*
*/
public function showPage() {
$this->tpl->displayTemplate();
}
}
?> | true |
ec193143250592f9615854bba4e539dedf2e09a3 | PHP | jamr200/Cgpimp | /application/models/ubicacion.php | UTF-8 | 16,263 | 2.640625 | 3 | [] | no_license | <?php
/*
* Copyright (C) 2014 jamr200
*
* This file is part Cgpimp.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>
*/
class Ubicacion extends DataMapper {
var $table = 'ubicaciones';
var $has_one = array('instancia_material','edificio','habitacion','mueble','balda','instancia_dispositivo');
function __construct($id = NULL)
{
parent::__construct($id);
}
//Método para almacenar la ubicacion en la BD
function set_ubicacion($ubicacion)
{//Comprobamos que la ubicacion no se encuentra almacenada
$consulta = $this->db->get_where('ubicaciones',array('id_instancia_material' => $ubicacion->id_instancia_material));
if($consulta->num_rows() === 0)
{//Como NO esta almacenada, la guardamos
$ubicacion->save();
if($this->db->affected_rows() === 1)
{//la hemos almacenado y devolvemos true
return TRUE;
}
else
{//No se ha almacenado porque hay error
return 0;
}
}//Ya se encuentra en la BD y por tanto devolvemos FALSE
return FALSE;
}
//Funcion para eliminar la ubicacion de una instancia dada
function unset_ubicacion($id_instancia)
{//eliminamos la persona de la BD
$this->db->delete('ubicaciones', array('id_instancia_material' => $id_instancia));
if($this->db->affected_rows() == 0)
{
return FALSE;
}
else
{
return TRUE;
}
}
//Funcion para eliminar la ubicacion
function unset_ubicacion2($id_ubicacion)
{//eliminamos la persona de la BD
$this->db->delete('ubicaciones', array('id_ubicacion' => $id_ubicacion));
if($this->db->affected_rows() == 0)
{
return FALSE;
}
else
{
return TRUE;
}
}
//Funcion para obtener los datos de una ubicacion a partir de su id
function obtener_ubicacion($id)
{
$ubicacion = new Ubicacion();
$ubicacion->get_by_id_ubicacion($id);
return $ubicacion;
}
//Para obtener todos los registros de nuestra tabla
function getNumUbicaciones()
{
return $this->db->count_all('ubicaciones');
}
//para obtener todos los registros que se encuentran con los parametros indicados
function getNumUbicaciones2($datos)
{
//Capturo los datos
$edificio = $datos['edificio'];
$habitacion = $datos['habitacion'];
$mueble = $datos['mueble'];
$balda = $datos['balda'];
//////////////////////
//Genero mi consulta//
//////////////////////
$this->db->select('edi.nombre_edificio, hab.nombre_habitacion,mue.nombre_mueble,bal.nombre_balda,inst.id,inst.part_number,inst.num_serie');
$this->db->from('ubicaciones as ubi');
$this->db->join('edificios as edi', 'edi.id = ubi.id_edificio');
$this->db->join('habitaciones as hab','hab.id = ubi.id_habitacion');
$this->db->join('muebles as mue','mue.id = ubi.id_mueble');
$this->db->join('baldas as bal','bal.id = ubi.id_balda');
$this->db->join('instancias_materiales as inst','inst.id = ubi.id_instancia_material');
if(!empty($edificio))
{//Existe la variable
if(!empty($habitacion))
{//Existe la variable
if(!empty($mueble))
{//Existe la variable
if(!empty($balda))
{//Existe la variable
$this->db->where('id_edificio',$edificio);
$this->db->where('id_habitacion',$habitacion);
$this->db->where('id_mueble',$mueble);
$this->db->where('id_balda',$balda);
}
else
{
$this->db->where('id_edificio',$edificio);
$this->db->where('id_habitacion',$habitacion);
$this->db->where('id_mueble',$mueble);
}
}
else
{
$this->db->where('id_edificio',$edificio);
$this->db->where('id_habitacion',$habitacion);
}
}
else
{
$this->db->where('id_edificio',$edificio);
}
}
return $this->db->count_all_results();
}
//Lo uso en las busquedas(para listados paginados)
function busca_ubicacion($datos, $limit, $start)
{
//Capturo los datos
$edificio = $datos['edificio'];
$habitacion = $datos['habitacion'];
$mueble = $datos['mueble'];
$balda = $datos['balda'];
//////////////////////
//Genero mi consulta//
//////////////////////
$this->db->select('ubi.id_ubicacion,edi.nombre_edificio, hab.nombre_habitacion,mue.nombre_mueble,bal.nombre_balda,inst.id,inst.part_number,inst.num_serie');
$this->db->from('ubicaciones as ubi');
$this->db->join('edificios as edi', 'edi.id = ubi.id_edificio');
$this->db->join('habitaciones as hab','hab.id = ubi.id_habitacion');
$this->db->join('muebles as mue','mue.id = ubi.id_mueble');
$this->db->join('baldas as bal','bal.id = ubi.id_balda');
$this->db->join('instancias_materiales as inst','inst.id = ubi.id_instancia_material');
if(!empty($edificio))
{//Existe la variable
if(!empty($habitacion))
{//Existe la variable
if(!empty($mueble))
{//Existe la variable
if(!empty($balda))
{//Existe la variable
$this->db->where('id_edificio',$edificio);
$this->db->where('id_habitacion',$habitacion);
$this->db->where('id_mueble',$mueble);
$this->db->where('id_balda',$balda);
}
else
{
$this->db->where('id_edificio',$edificio);
$this->db->where('id_habitacion',$habitacion);
$this->db->where('id_mueble',$mueble);
}
}
else
{
$this->db->where('id_edificio',$edificio);
$this->db->where('id_habitacion',$habitacion);
}
}
else
{
$this->db->where('id_edificio',$edificio);
}
}
$this->db->order_by("inst.id","ASC");
$this->db->limit($limit,$start);
//////////////////////
//Fin de mi consulta//
//////////////////////
//Obtengo los datos de la BD
$query = $this->db->get();
if ($query->num_rows() > 0)
{
return $query->result();
}
else
{
return $dd='no hay datos';
}
}
//Lo uso en las busquedas (para los pdf's)
function busca_ubicacion2($datos)
{
//Capturo los datos
$edificio = $datos['edificio'];
$habitacion = $datos['habitacion'];
$mueble = $datos['mueble'];
$balda = $datos['balda'];
//////////////////////
//Genero mi consulta//
//////////////////////
$this->db->select('edi.nombre_edificio, hab.nombre_habitacion,mue.nombre_mueble,bal.nombre_balda,inst.id,inst.part_number,inst.num_serie');
$this->db->from('ubicaciones as ubi');
$this->db->join('edificios as edi', 'edi.id = ubi.id_edificio');
$this->db->join('habitaciones as hab','hab.id = ubi.id_habitacion');
$this->db->join('muebles as mue','mue.id = ubi.id_mueble');
$this->db->join('baldas as bal','bal.id = ubi.id_balda');
$this->db->join('instancias_materiales as inst','inst.id = ubi.id_instancia_material');
if(!empty($edificio))
{//Existe la variable
if(!empty($habitacion))
{//Existe la variable
if(!empty($mueble))
{//Existe la variable
if(!empty($balda))
{//Existe la variable
$this->db->where('id_edificio',$edificio);
$this->db->where('id_habitacion',$habitacion);
$this->db->where('id_mueble',$mueble);
$this->db->where('id_balda',$balda);
}
else
{
$this->db->where('id_edificio',$edificio);
$this->db->where('id_habitacion',$habitacion);
$this->db->where('id_mueble',$mueble);
}
}
else
{
$this->db->where('id_edificio',$edificio);
$this->db->where('id_habitacion',$habitacion);
}
}
else
{
$this->db->where('id_edificio',$edificio);
}
}
$this->db->order_by("inst.id","ASC");
//////////////////////
//Fin de mi consulta//
//////////////////////
//Obtengo los datos de la BD
$query = $this->db->get();
if ($query->num_rows() > 0)
{
return $query->result();
}
else
{
return $dd='no hay datos';
}
}
//Lo uso en los listados (para listados paginados)
function lista_ubicaciones($limit, $start)
{
$this->db->select('ubi.id_ubicacion, edificios.nombre_edificio, habitaciones.nombre_habitacion, muebles.nombre_mueble, baldas.nombre_balda, instancias_materiales.id, instancias_materiales.part_number, instancias_materiales.num_serie');
$this->db->from('ubicaciones as ubi');
$this->db->join('edificios','edificios.id = ubi.id_edificio');
$this->db->join('habitaciones','habitaciones.id = ubi.id_habitacion');
$this->db->join('muebles','muebles.id = ubi.id_mueble');
$this->db->join('baldas','baldas.id = ubi.id_balda');
$this->db->join('instancias_materiales','instancias_materiales.id = ubi.id_instancia_material');
$this->db->order_by("ubi.id_ubicacion","ASC");
$this->db->limit($limit,$start);
//Obtengo los datos de la BD
$query = $this->db->get();
if ($query->num_rows() > 0)
{
return $query->result();
}
else
{
return $dd='no hay datos';
}
}
//Lo uso en los listados (para los pdf's)
function lista_ubicaciones2()
{
$this->db->select('ubi.id_ubicacion, edificios.nombre_edificio, habitaciones.nombre_habitacion, muebles.nombre_mueble, baldas.nombre_balda, instancias_materiales.id, instancias_materiales.part_number, instancias_materiales.num_serie');
$this->db->from('ubicaciones as ubi');
$this->db->join('edificios','edificios.id = ubi.id_edificio');
$this->db->join('habitaciones','habitaciones.id = ubi.id_habitacion');
$this->db->join('muebles','muebles.id = ubi.id_mueble');
$this->db->join('baldas','baldas.id = ubi.id_balda');
$this->db->join('instancias_materiales','instancias_materiales.id = ubi.id_instancia_material');
$this->db->order_by("ubi.id_ubicacion","ASC");
//Obtengo los datos de la BD
$query = $this->db->get();
if ($query->num_rows() > 0)
{
return $query->result();
}
else
{
return $dd='no hay datos';
}
}
public function muestra_ubicacion_instancia($id)
{
$rpta = "";
//hago una consulta a la base de datos para obtener los datos de la ubicacion a partir de su id
$ubicacion = $this->db->get_where('ubicaciones',array('id_instancia_material'=>$id));
if($ubicacion->num_rows() > 0)
{
$part_number = $this->Instancia_material->obtener_part_number_por_id($id);
$num_serie = $this->Instancia_material->obtener_num_serie_por_id($id);
foreach ($ubicacion->result() as $fila)
{
//transformo cada valor a su nombre
//Convertimos el id del edificio a su nombre para mostarlo
$nombre_edificio = $this->Edificio->obtener_nombre_edificio_por_id($fila->id_edificio);
//Convertimos el id de la habitacion a su nombre para mostarlo
$nombre_habitacion = $this->Habitacion->obtener_nombre_habitacion_por_id($fila->id_habitacion);
//Convertimos el id del mueble a su nombre para mostarlo
$nombre_mueble = $this->Mueble->obtener_nombre_mueble_por_id($fila->id_mueble);
//Convertimos el id de la balda a su nombre para mostarlo
$nombre_balda = $this->balda->obtener_nombre_balda_por_id($fila->id_balda);
$rpta .= '
<form id="muestraubicacion" method="POST">
<fieldset>
<legend>Información de ubicación para la instancia de material con id = '.$id.' </legend>
<div class="col-md-12">
<div class="form-group">
<label for="nombre_edificio">Edificio</label>:'.$nombre_edificio .'
</div>
</div>
<!-- ************************-->
<div class="col-md-12">
<div class="form-group">
<label for="nombre_habitacion">Habitación</label>:'.$nombre_habitacion .'
</div>
</div>
<!-- ************************-->
<div class="col-md-12">
<div class="form-group">
<label for="nombre_mueble">Mueble</label>:'.$nombre_mueble .'
</div>
</div>
<!-- ************************-->
<div class="col-md-12">
<div class="form-group">
<label for="nombre_balda">Balda</label>:'.$nombre_balda .'
</div>
</div>
<!-- ************************-->
<div class="col-md-12">
<div class="form-group">
<a href="encontrar_ubicacion" class="btn btn-default">Cancelar</a>
</div>
</div>
<!-- ************************-->
</fieldset>
</form>';
}
}
else
{
//Aqui podemos decir la instancia de dispositivo donde se encuentra instalada
$id_inst_dispositivo = $this->Instancia_material->obtener_inst_dispositivo($id);
$instancia_dispositivo = $this->Instancia_dispositivo->obtener_instancia_dispositivo($id_inst_dispositivo);
$rpta .= '<h4>El material elegido se encuentra instalado en el dispositivo con id <strong>'.$instancia_dispositivo->id.'</strong>, part number <strong>'.$instancia_dispositivo->part_number.'</strong> y número de serie <strong>'.$instancia_dispositivo->num_serie.'</strong>.</h4>';
}
echo $rpta;
}
}
/* End of file ubicacion.php */
/* Location: ./application/models/ubicacion.php */ | true |
55d09f7ea06975f114283304e599d9981d9866b4 | PHP | superuomo/xhproflink | /xhprof_prepend.php | UTF-8 | 2,982 | 2.59375 | 3 | [] | no_license | <?php
/*
On-demand profiling using xhprof.
This file should be loaded using auto_prepend
Use by appending a ?profile to the initial URL.
Disable profiling for all subsequent URLs fetched by appending ?noprofile.
You need to install and set up xhprof, as described here:
http://web.archive.org/web/20110514095512/http://mirror.facebook.net/facebook/xhprof/doc.html
*/
# Do not use const for compatibility with old PHP versions.
# Change this according to where your distribution places
# xhprof's files, e.g. /usr/share/php52-xhprof/ in Ubuntu for old PHP5.2
define('XHPROF_ROOT', '/usr/share/webapps/xhprof');
define('XHPROF_DISPLAY', false);
session_name('PHPSESSIONDEBUGID');
session_start();
if (array_key_exists('profile', $_GET)) {
$_SESSION['profile'] = true;
} elseif (array_key_exists('noprofile', $_GET)) {
$_SESSION['profile'] = false;
}
if (isset($_SESSION['profile']) && $_SESSION['profile']
# Exclude xprof pages from profiling!
&& strncmp($_SERVER['SCRIPT_NAME'], '/xhprof/', strlen('/xhprof/'))) {
# Start profiling.
# Add XHPROF_FLAGS_NO_BUILTINS to not profile builtin functions.
xhprof_enable(XHPROF_FLAGS_CPU + XHPROF_FLAGS_MEMORY,
array('ignored_functions' => array('xhprof_disable')));
function xhprof_prepend_finalize() {
# Stop profiler.
$xhprof_data = xhprof_disable();
if (XHPROF_DISPLAY) {
# Display raw xhprof data for the profiler run.
echo '<pre>';
var_export($xhprof_data);
echo '</pre>';
} else {
# Saving the XHProf run using the default implementation of iXHProfRuns.
include_once XHPROF_ROOT . '/xhprof_lib/utils/xhprof_lib.php';
include_once XHPROF_ROOT . '/xhprof_lib/utils/xhprof_runs.php';
$xhprof_runs = new XHProfRuns_Default();
$namespace = isset($_GET['namespace']) ? $_GET['namespace'] : 'xhprof_debug';
/*
Save the run under a namespace.
**NOTE**:
By default save_run() will automatically generate a unique
run id for you. [You can override that behavior by passing
a run id (optional arg) to the save_run() method instead.]
*/
$run_id = $xhprof_runs->save_run($xhprof_data, $namespace);
echo <<<EOH
<hr>
<a href="http://$_SERVER[SERVER_NAME]/xhprof/index.php?run=$run_id&source=$namespace" target="xhprof">View run #$run_id under namespace $namespace.</a>
EOH;
}
}
# BUG: other shutdown functions registered after this won't be profiled.
register_shutdown_function('xhprof_prepend_finalize');
}
session_write_close();
/*
Be sure to reset the session name to the standard one, else you could screw up
some applications. BTW we could use a cookie instead of a session, since we
only need to store a flag and it is no sensitive information, but looks like
our application does not like it. If we unset the cookie in the cookie array,
it can work, but am not sure, I have not tried it. So we will still with
sessions for now.
*/
session_name('PHPSESSID');
?>
| true |
2056ca09a60b01b549a76eadeaa819f5321e15e8 | PHP | vknyvz/vknyvz.com | /app/modules/public/models/Portfolio.php | UTF-8 | 550 | 2.6875 | 3 | [] | no_license | <?php
class Public_Model_Portfolio extends vkNgine_DbTable_Abstract
{
protected $_name = 'portfolio';
protected $_primary = 'portfolioId';
/**
* fetch a single portfolio item
*
* @param int $portfolioId
*/
public function fetch($portfolioId)
{
$select = $this->select();
$select->where('portfolioId = ?', (string) $portfolioId);
$row = $this->fetchRow($select);
return $row;
}
public function fetchAll()
{
$select = $this->select();
$select->order('order ASC');
return parent::fetchAll($select);
}
} | true |
5f642aaad1f86ba5a6167388e161390c6e4ea3b9 | PHP | gogad/babysmile.dp.ua | /classes/Admin/IModel.php | UTF-8 | 755 | 2.640625 | 3 | [] | no_license | <?php
/**
* Общий интерфейс модели данных
*
*/
interface Admin_IModel {
/**
* Возвращает массив данных для формы
*
* @param array $sourced_fields поля с собстенным источником данных
*/
public function getFieldsData ($sourced_fields);
/**
* Выполняет вставку новых записей в таблицы при отправке формы
*
*/
public function insert ();
/**
* Выполняет обновление записей в таблицах при отправке формы
*
*/
public function update ();
}
?>
| true |
1c69872458582d40718da3fb4cb53fcdbb88c14d | PHP | phixuan/POO-in-PHP | /06.php | UTF-8 | 595 | 3.34375 | 3 | [] | no_license | <?php include 'includes/header.php';
//Interface
interface TransporteInterfaz {
public function getInfo() : string;
public function getRuedas() : int;
}
abstract class Transporte implements TransporteInterfaz{
public function __construct(protected int $ruedas, protected int $capacidad)
{
}
public function getInfo() : string{
return "El transporte tiene " . $this->ruedas . " y una capacidad de " . $this->capacidad . " personas";
}
public function getRuedas() : int{
return $this->ruedas;
}
}
include 'includes/footer.php'; | true |
6b8e375372e077064190f7518815257295cbff72 | PHP | civicrm/civicrm-infra | /ansible/roles/icinga2/files/etc/icinga2/scripts/check_cmsversion | UTF-8 | 1,673 | 2.609375 | 3 | [] | no_license | #!/usr/bin/php
<?php
$host = trim($argv[1]);
$cms = trim($argv[2]);
$minimum = trim($argv[3]);
if (empty($host)) {
echo 'Missing host argument.';
exit(3);
}
if (empty($minimum)) {
echo 'Missing minimum version argument.';
exit(3);
}
$tmp = '';
if ($cms == 'drupal' || $cms == 'drupal8') {
exec('sudo -u aegir /usr/local/bin/drush @' . escapeshellarg($host) . ' status version --format=json', $tmp);
}
elseif ($cms == 'wordpress') {
exec('sudo -u aegir /usr/local/bin/drush @' . escapeshellarg($host) . ' wp core version', $tmp);
}
else {
echo 'Unsupported CMS: ' . $cms;
exit(3);
}
if (empty($tmp)) {
if ($cms == 'drupal' || $cms == 'drupal8') {
exec('sudo -u aegir /usr/local/bin/drush @' . escapeshellarg($host) . ' cc drush');
echo 'Failed to check status (2). Drush cache flushed for the next run.';
}
else {
echo 'Failed to check status (2).';
}
exit(3);
}
$version = '';
if ($cms == 'drupal' || $cms == 'drupal8') {
// Drush returns a multi-line json string. To decode, it must be imploded first.
$tmp = implode(' ', $tmp);
$data = json_decode($tmp, TRUE);
if (empty($data)) {
if ($cms == 'drupal' || $cms == 'drupal8') {
exec('sudo -u aegir /usr/local/bin/drush @' . escapeshellarg($host) . ' cc drush');
echo 'Failed to check status (1). Drush cache flushed for the next run.';
}
else {
echo 'Failed to check status (1).';
}
exit(3);
}
$version = $data['drupal-version'];
}
elseif ($cms == 'wordpress') {
$version = $tmp[0];
}
if (version_compare($version, $minimum, '>=')) {
echo 'OK ' . $version;
exit(0);
}
else {
echo 'ERROR ' . $version;
exit(2);
}
| true |
a8f4a012582e33bbb1bf38a3b1189b390e89e006 | PHP | mtave1202/library | /Autoloader.php | UTF-8 | 10,538 | 2.796875 | 3 | [] | no_license | <?php
// declare(encoding='UTF-8');
/**
* クラスのオートローディングを行う。
*
* クラス名に含まれる _ をディレクトリセパレータに置換してファイルパスとする。
* ただしネームスペースに含まれる _ は置換されない。
* 内部では spl_autoload_register() を利用しているので、他のオートローダとの併用が可能。
* @link http://groups.google.com/group/php-standards/web/psr-0-final-proposal?pli=1
*
* <code>
* <?php
* $al = Autoloader::getInstance();
* $al->enable(); // 明示的に呼ばないとオートローディングは有効にならない。
* $al->addDirectory('/foo');
* echo $al->getFileNameByClassName('ns_A\ns_B\Foo_Bar_Baz'); // /foo/ns_A/ns_B/Foo/Bar/Baz.php
* $al->addDirectory('/ns_A_dir', 'ns_A');
* echo $al->getFileNameByClassName('ns_A\ns_b\Foo_Bar_Baz'); // /ns_A_dir/ns_B/Foo/Bar/Baz.php
* $al->addDirectory('/ns_B_dir', 'ns_A\ns_B');
* echo $al->getFileNameByClassName('ns_A\ns_B\Foo_Bar_Baz'); // /ns_B_dir/Foo/Bar/Baz.php
* ?>
* </code>
*/
class Autoloader
{
/**
* @var array
*/
protected $_aliases;
/**
* @var array
*/
protected $_directories;
/**
* @var bool
*/
protected $_enabled;
/**
* @var callback
*/
protected $_cacheGetter;
/**
* @var callback
*/
protected $_cacheSetter;
/**
* @var bool
*/
protected $_cacheModified;
/**
* @var array
*/
protected $_loaded;
/**
* @var Autoloader
*/
protected static $_instance = null;
/**
* @var array
*/
protected static $_instances = null;
public function __construct()
{
$this->_aliases = version_compare(PHP_VERSION, '5.3.0') >= 0 ? array() : null;
$this->_directories = array();
$this->_enabled = false;
$this->_cacheGetter = null;
$this->_cacheSetter = null;
$this->_cacheModified = false;
$this->_loaded = null;
}
public function __destruct()
{
if ($this->_cacheModified && $this->_cacheSetter !== null) {
$setter = $this->_cacheSetter;
@$setter($this->_loaded);
}
}
/**
* @param string $name インスタンス名。
* @return Autoloader
*/
public static function getInstance($name = null)
{
if ($name === null) {
if (self::$_instance === null) {
$c = __CLASS__;
self::$_instance = new $c();
}
return self::$_instance;
}
if (!is_string($name)) {
throw new InvalidArgumentException();
}
if (self::$_instances === null) {
self::$_instances = array();
} else if (isset(self::$_instances[$name])) {
return self::$_instances[$name];
}
$c = __CLASS__;
return self::$_instances[$name] = new $c();
}
public function auto()
{
return $this->enable()->addDirectory(dirname(__FILE__));
}
/**
* @param string $alias 新しい別名。
* @param string $className 元となるクラス名。
* @throws LogicException
* @throws InvalidArgumentException
* @return Autoloader
*/
public function addAlias($alias, $className)
{
if ($this->_aliases === null) {
throw new LogicException(__METHOD__ . ' requires PHP >= 5.3.0');
}
if (!is_string($alias) || $alias === '') {
throw new InvalidArgumentException("Invalid \$alias: $alias");
}
if (!is_string($className) || $className === '') {
throw new InvalidArgumentException("Invalid \$className: $className");
}
$this->_aliases[$alias] = $className;
return $this;
}
/**
* @param array $map キーに新しい別名を、値に元となるクラス名を入れた連想配列。
* @throws LogicException
* @throws InvalidArgumentException
* @return Autoloader
*/
public function setAlias(array $map)
{
if ($this->_aliases === null) {
throw new LogicException(__METHOD__ . ' requires PHP >= 5.3.0');
}
foreach ($map as $alias => $className) {
if (!is_string($alias) || $alias === '') {
throw new InvalidArgumentException("Invalid \$alias: $alias");
}
if (!is_string($className) || $className === '') {
throw new InvalidArgumentException("Invalid \$className: $className");
}
}
$this->_aliases = $map;
return $this;
}
/**
* @param string $path 探索対象となるディレクトリのパス。
* @param string $ns ネームスペース。
* @return Autoloader
* @throws InvalidArgumentException
*/
public function addDirectory($path, $ns = null)
{
if (!is_string($path)
|| $ns !== null && (!is_string($ns) || $ns === '')) {
throw new InvalidArgumentException();
}
if ($ns === null) {
$ns = '';
}
if (!isset($this->_directories[$ns])) {
$this->_directories[$ns] = array();
}
$this->_directories[$ns][$path] = true;
return $this;
}
/**
* @param array $pathes 探索対象となるディレクトリのパスの配列。
* @param string $ns ネームスペース。
* @return Autoloader
* @throws InvalidArgumentException
*/
public function setDirectory(array $pathes, $ns = null)
{
if (!is_array($pathes)
|| $ns !== null && (!is_string($ns) || $ns === '')) {
throw new InvalidArgumentException();
}
$values = array();
foreach ($pathes as $value) {
if (!is_string($value) || $value === '') {
throw new InvalidArgumentException();
}
$values[$value] = true;
}
if ($ns === null) {
$ns = '';
}
$this->_directories[$ns] = $values;
return $this;
}
/**
* @param callback $getter
* @param callback $setter
* @return Autoloader
*/
public function setCacheHandler($getter, $setter)
{
if (!is_callable($getter) || !is_callable($setter)) {
throw new InvalidArgumentException();
}
$this->_cacheGetter = $getter;
$this->_cacheSetter = $setter;
return $this;
}
/**
* @return bool
*/
public function isEnabled()
{
return $this->_enabled;
}
/**
* @return Autoloader
*/
public function enable()
{
if ($this->_enabled) {
return $this;
}
$r = spl_autoload_register(array($this, '_autoload'));
if (!$r) {
throw new LogicException();
}
$this->_enabled = true;
if ($this->_cacheGetter) {
$getter = $this->_cacheGetter;
$loaded = $getter();
$this->_loaded = is_array($loaded) ? $loaded : array();
}
return $this;
}
/**
* @return Autoloader
*/
public function disable()
{
if (!$this->_enabled) {
return $this;
}
$r = spl_autoload_unregister(array($this, '_autoload'));
if (!$r) {
throw new LogicException();
}
$this->_enabled = false;
return $this;
}
/**
* @param string $className 探索するクラスの名前。
* @return string そのクラスが含まれる (と思われる) ファイルのパス。
*/
public function getFileNameByClassName($className)
{
if (!is_string($className) || !preg_match('/\A(?:[_a-z][_a-z0-9]*\\\)*[_a-z][_a-z0-9]*\z/i', $className)) {
throw new InvalidArgumentException();
}
$targetNs = $subNs = $pathes = null;
$rpos = strrpos($className, '\\');
if ($rpos !== false) {
$targetNs = substr($className, 0, $rpos);
$className = substr($className, $rpos + 1);
do {
if (isset($this->_directories[$targetNs])) {
$pathes = $this->_directories[$targetNs];
if (empty($pathes)) {
return null;
}
break;
}
$rpos = strpos($targetNs, '\\');
if ($rpos === false) {
break;
}
$subNs = $subNs === null ? substr($targetNs, $rpos + 1) : substr($targetNs, $rpos + 1) . '\\' . $subNs;
$targetNs = substr($targetNs, 0, $rpos);
} while (true);
}
if ($pathes === null) {
if ($targetNs !== null) {
$subNs = $subNs === null ? $targetNs : $targetNs . '\\' . $subNs;
}
if (empty($this->_directories[''])) {
return null;
}
$pathes = $this->_directories[''];
}
$sep = DIRECTORY_SEPARATOR;
$baseName = strtr($className, array('_' => $sep)) . '.php';
if ($subNs !== null) {
$baseName = strtr($subNs, array('\\' => $sep)) . $sep . $baseName;
}
foreach ($pathes as $directory => $_) {
$path = $directory . $sep . $baseName;
if (is_file($path)) {
return $path;
}
}
return null;
}
/**
* @param string $className ロードするクラスの名前。
* @return void
*/
protected function _autoload($className)
{
if ($this->_loaded !== null && isset($this->_loaded[$className])) {
require $this->_loaded[$className];
return;
}
$alias = null;
if ($this->_aliases !== null && isset($this->_aliases[$className])) {
$alias = $className;
$className = $this->_aliases[$className];
}
$fileName = $this->getFileNameByClassName($className);
if (!$fileName) {
return;
}
require $fileName;
if (!class_exists($className, false)) {
return;
}
if ($this->_loaded !== null) {
$this->_cacheModified = true;
$this->_loaded[$className] = $fileName;
}
if ($alias !== null) {
class_alias($className, $alias);
}
}
} | true |
c3b6aa6c9cccd40e9f81a206028cec8381d13e6d | PHP | ktktok/integravet | /shell/scripts/all/_old/20151013-clean-doctors-petvale-old-manual-campaigns.php | UTF-8 | 695 | 2.59375 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: julio
* Date: 10/13/15
* Time: 5:11 PM
*/
require_once './configScript.php';
$codesWebsites = array(5 => 'doctorsVet', 6 => 'petvale');
foreach ($codesWebsites as $key => $codesWebsite)
{
cleanCampaigns($key, $codesWebsite);
}
function cleanCampaigns($websiteId, $codeStore)
{
global $resource;
global $writeConnection;
/**
* Remove todas as regras deste website
*/
$removeRegraPromocao = "DELETE from ";
$removeRegraPromocao .= $resource->getTableName('salesrule');
$removeRegraPromocao .= " WHERE name LIKE '" . ($codeStore . "_%") . "' or name LIKE '" . ($codeStore . "-%") . "'";
$writeConnection->query($removeRegraPromocao);
} | true |
14bab03c18465e0af236254d2ca2e6039aa007a4 | PHP | F4N70M/fw | /Fw/Components/Modules/TemplateEngine/Block/Structure/Structure.php | UTF-8 | 437 | 2.625 | 3 | [] | no_license | <?php
/**
* User: F4N70M
* Version: 0.1
* Date: 13.07.2020
*/
namespace Fw\Components\Modules\TemplateEngine\Block\Structure;
use Fw\Components\Modules\TemplateEngine\Block;
class Structure extends Block
{
protected $family = 'Structure';
public function __construct(array $data = [], array $blocks = [])
{
parent ::__construct($data, $blocks);
$this->script[] = 'structure.js';
$this->style[] = 'structure.css';
}
} | true |
2db3d6da09a833fa41f161080536d009e1505245 | PHP | tanjiuyusila/php | /6_string.php | UTF-8 | 479 | 3.859375 | 4 | [] | no_license | <?php
//单引双引区别
//都是字符串,但是双引号可以识别变量。如果字符串中没有变量,用单引号更快
$y = "yaozhilin";
echo "my name is $y"."<br>";
echo 'my name is $y'."<br>";
//获取字符串长度
echo strlen("Hello World!")."<br>";
//检索字符串内指定的字符或文本,返回字符串位置,
echo strpos("Hello world!","world");//返回6,(不是7),字符串首字符的位置是0而不是1,如果找不到,返回false | true |
43dd849c107b4549733599c68962b5a0aa82d2c7 | PHP | integer-net/IntegerNet_Varnish | /src/app/code/community/IntegerNet/Varnish/Model/Index/Priority.php | UTF-8 | 1,245 | 2.515625 | 3 | [] | no_license | <?php
/**
* integer_net GmbH Magento Module
*
* @package IntegerNet_Varnish
* @copyright Copyright (c) 2015 integer_net GmbH (http://www.integer-net.de/)
* @author integer_net GmbH <info@integer-net.de>
* @author Viktor Franz <vf@integer-net.de>
*/
/**
* Class IntegerNet_Varnish_Model_Index_Priority
*/
class IntegerNet_Varnish_Model_Index_Priority
{
/**
*
*/
const PRIORITY_HEIGHT = 1;
const PRIORITY_NORMAL = 2;
const PRIORITY_LOW = 3;
/**
* @return array
*/
public function getOptions()
{
return array(
self::PRIORITY_HEIGHT => Mage::helper('integernet_varnish')->__('Height'),
self::PRIORITY_NORMAL => Mage::helper('integernet_varnish')->__('Normal'),
self::PRIORITY_LOW => Mage::helper('integernet_varnish')->__('Low'),
);
}
/**
* @param array $entityIds
* @param int $priority
*
* @return int The number of affected rows.
*/
public function update($entityIds, $priority)
{
if ($entityIds && array_key_exists($priority, $this->getOptions())) {
return Mage::getResourceModel('integernet_varnish/index')->setPriority($entityIds, $priority);
}
return 0;
}
}
| true |
05d56c1d6e6ad649ad87c16792b479336ed17e03 | PHP | brian2303/concesionariophp | /modelo/Van.php | UTF-8 | 322 | 2.921875 | 3 | [] | no_license | <?php
require_once("Vehiculo.php");
class Van extends Vehiculo {
private $cantidadPasajeros;
public function getCantidadPasajeros(){
return $this->cantidadPasajeros;
}
public function setCantidadPasajeros($cantidadPasajeros){
$this->cantidadPasajeros = $cantidadPasajeros;
}
} | true |
470e0af22d85b44628dc27b5536e584becb03598 | PHP | jasonbronson/virtualfitnesscoach | /apps/admin/modules/admin/templates/showworkoutschedulesdetailSuccess.php | UTF-8 | 1,817 | 2.65625 | 3 | [] | no_license | <br><br>
<br><br>
<div align=center>
<h1>Show Workout Detail for <?php echo ucwords($exerciseinfo['user_username']);
switch($row[0]['type']){
case 1:
$type="Resistence Day";
// $modulename = "_resistence";
break;
case 2:
$type="Cardio Day";
// $modulename = "_cardio";
break;
case 3:
$type="Rest Day";
// $modulename = "_rest";
break;
}
?></h1>
<br>
<?php echo link_to('Go BACK', 'admin/showworkoutschedules' ) ?>
<table border=0 width=80%>
<tr>
<th>Workout Type is <?php echo $type ?> on <?php echo date("m-d-Y", strtotime($row[0]['workoutdate'] )) ?></th>
</tr>
</table>
<?php
//echo "<pre>";
//print_r($row);
if($row[0]['type'] == 1){
echo "<table border=1>
<tr>
<td>Graphic Name</td>
<td>Circuit</td>
<td>Sets</td>
<td>Reps</td>
<td>Weights</td>
<td>Exercise</td>
</tr>
";
for($a=0; $a < count($row); $a++ ){
//USER INFO FROM DATABASE
/* $name = $row[$a]['user_firstname']." ".$row[$a]['user_lastname'];
$user_id =$row[$a]['user_id'];
*/
//BUTTONS
//$submit = button_to('Set New Schedule', 'admin/setschedule?user_id='.$id);
// $updateschedule = button_to('Update a Schedule', "admin/updateschedule$modulename?user_id=$user_id&workoutdate=$workoutdate" );
//$change = button_to("View Details ", "admin/showworkoutschedulesdetail?user_id=$user_id&workoutdate={$row[$a]['workoutdate']}");
echo "<tr align=center>
<td>{$row[$a]['exgraphic']}</td>
<td>{$row[$a]['circuit']}</td>
<td>{$row[$a]['sets']}</td>
<td>{$row[$a]['reps']}</td>
<td>{$row[$a]['weights']}</td>
<td>{$row[$a]['exercise']}</td>
</tr>";
}
echo "</table>";
}//end of type 1
?>
</table>
| true |
5792edfdf511ee2fc9a63870e72642b2bd050a66 | PHP | jmfeurprier/crud-engine-bundle | /src/Loading/EntityActionRouteLoaderBase.php | UTF-8 | 2,574 | 2.546875 | 3 | [] | no_license | <?php
namespace Jmf\CrudEngine\Loading;
use Jmf\CrudEngine\Exception\CrudEngineMissingConfigurationException;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
abstract class EntityActionRouteLoaderBase implements EntityActionRouteLoaderInterface
{
public function load(
RouteCollection $routeCollection,
string $entityClass,
array $entityProperties
): void {
$actionName = $this->getActionName();
if (!isset($entityProperties['actions'][$actionName])) {
return;
}
$actionProperties = $entityProperties['actions'][$actionName];
$routeName = $this->getRouteName($entityProperties, $entityClass);
$routePath = $this->getRoutePath($entityProperties, $entityClass);
$route = new Route(
$routePath,
[
'_controller' => $this->getActionClass(),
'entityClass' => $entityClass,
'actionProperties' => $actionProperties,
],
);
$route->setMethods($this->getMethods());
$routeCollection->add(
$routeName,
$route
);
}
abstract protected function getActionName(): string;
/**
* @return string[]
*/
abstract protected function getMethods(): array;
abstract protected function getActionClass(): string;
private function getRouteName(
array $entityProperties,
string $entityClass
): string {
$actionName = $this->getActionName();
if (isset($entityProperties['actions'][$actionName]['route']['name'])) {
return $entityProperties['actions'][$actionName]['route']['name'];
}
if (isset($entityProperties['name'])) {
return "{$entityProperties['name']}.{$actionName}";
}
throw new CrudEngineMissingConfigurationException(
"No CRUD entity routing name property defined for class {$entityClass} and action '{$actionName}'."
);
}
private function getRoutePath(
array $entityProperties,
string $entityClass
): string {
$actionName = $this->getActionName();
if (isset($entityProperties['actions'][$actionName]['route']['path'])) {
return $entityProperties['actions'][$actionName]['route']['path'];
}
throw new CrudEngineMissingConfigurationException(
"No CRUD entity routing path property defined for class {$entityClass} and action '{$actionName}'."
);
}
}
| true |
f95789d1dcf51c56c268f457bc4b9601d84ae70b | PHP | koolreport/examples | /reports/excel/big_spreadsheet/export.php | UTF-8 | 455 | 2.5625 | 3 | [
"MIT"
] | permissive | <?php
include "MyReport.php";
$report = new MyReport;
$report->run();
$type = isset($_GET['type']) ? $_GET['type'] : 'CSV';
if ($type === 'XLSX') {
$report->exportToXLSX('MyReportSpreadsheet')
->toBrowser("MyReport.xlsx");
} elseif ($type === 'ODS') {
$report->exportToODS('MyReportSpreadsheet')
->toBrowser("MyReport.ods");
} elseif ($type === 'CSV') {
$report->exportToCSV('MyReportSpreadsheet')
->toBrowser("MyReport.csv");
}
| true |
3fc7bdd4aff416d0f8bc8f8242273b2786b7fc6c | PHP | one0212/php_note | /data_list.php | UTF-8 | 4,208 | 2.78125 | 3 | [] | no_license | <?php
require __DIR__. '/__connect_db.php';
$page_name = 'data_list';
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
// 用戶自己決定自己要看哪一頁 所以是從get方式過來
// 用戶有設定頁數則轉成整數頁 如果沒有設定則預設頁數為第一頁
$per_page = 10; // 每一頁要顯示幾筆
$t_sql = "SELECT COUNT(1) FROM `address_book`";
//$t_stmt = $pdo->query($t_sql);
//$totalRows = $t_stmt->fetch(PDO::FETCH_NUM)[0]; // 拿到總筆數
$totalRows = $pdo->query($t_sql)->fetch(PDO::FETCH_NUM)[0]; // 拿到總筆數
$totalPages = ceil($totalRows/$per_page); // 取得總頁數
// 總筆數/一頁最多幾筆 = 總頁數(無條件進位)
// echo "$totalRows <br>";
// echo "$totalPages <br>";
// exit;
if($page < 1){
header('Location: data_list.php');
exit;
}
// 判斷頁數如果小於1則回到原檔首頁
if($page > $totalPages){
header('Location: data_list.php?page='. $totalPages);
exit;
}
// 超過頁數則直接轉到最末頁
// $sql為要顯示的資料
$sql = sprintf("SELECT * FROM `address_book` ORDER BY `sid` DESC LIMIT %s, %s",
// order by 依照流水號降冪排序
($page-1)*$per_page, //索引值:頁數-1*一頁幾筆 從哪一個索引值開始呈現 與pk無關 因升幂與降冪呈現不同
$per_page // 一頁呈現最多幾筆
);
$stmt = $pdo->query($sql);
// $rows = $stmt->fetchAll(); 不用fetchAll則用while迴圈
?>
<?php include __DIR__. '/__head.php' ?>
<!-- __DIR__為文件所在的目錄 -->
<?php include __DIR__. '/__navbar.php' ?>
<div class="container">
<div style="margin-top: 2rem;">
<nav aria-label="Page navigation example">
<ul class="pagination">
<li class="page-item">
<a class="page-link" href="?page=<?= $page-1 ?>">
<i class="fas fa-chevron-left"></i>
</a>
</li>
<?php
$p_start = $page-5;
$p_end = $page+5;
// 頁碼只顯是五頁
for($i=$p_start; $i<=$p_end; $i++):
if($i<1 or $i>$totalPages) continue;
// 頁碼超出範圍則跳過進到下次回迴圈
?>
<li class="page-item <?= $i==$page ? 'active' : '' ?>">
<a class="page-link" href="?page=<?= $i ?>"><?= $i ?></a>
</li>
<?php endfor; ?>
<li class="page-item">
<a class="page-link" href="?page=<?= $page+1 ?>">
<i class="fas fa-chevron-right"></i>
</a>
</li>
</ul>
</nav>
<table class="table table-striped table-bordered">
<!-- table-bordered為table框線 -->
<thead>
<tr>
<th scope="col"><i class="fas fa-trash-alt"></i></th>
<th scope="col">姓名</th>
<th scope="col">電子郵箱</th>
<th scope="col">手機</th>
<th scope="col">生日</th>
<th scope="col"><i class="fas fa-edit"></i></th>
<!-- <th scope="col">地址</th> -->
</tr>
</thead>
<tbody>
<?php while($r=$stmt->fetch()){ ?>
<!-- while -->
<tr>
<td>
<a href="javascript:delete_one(<?= $r['sid'] ?>)"><i class="fas fa-trash-alt"></i></a>
</td>
<td><?= htmlentities($r['name']) ?></td>
<td><?= htmlentities($r['email']) ?></td>
<td><?= htmlentities($r['mobile']) ?></td>
<td><?= htmlentities($r['birthday']) ?></td>
<!-- address在資料表中為null -->
<!-- htmlentities()為php的function 會做html跳脫 防範xss攻擊 -->
<td>
<a href="data_edit.php?sid=<?= $r['sid'] ?>"><i class="fas fa-edit"></i></a>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
<script>
function delete_one(sid) {
if(confirm(`確定要刪除編號為 ${sid} 的資料嗎?`)){
location.href = 'data_delete.php?sid=' + sid;
}
}
</script>
<?php include __DIR__. '/__footer.php' ?> | true |
d5d67da71d237bbfa4a47bb945b1365a2d765cf3 | PHP | gterzis/ConnectPlatform | /admin/Reports/Analytics/getSelectedInterests.php | UTF-8 | 2,089 | 2.59375 | 3 | [] | no_license | <?php // called by Analytics.php
// prevent users visit page improperly
if ( !$_SERVER["REQUEST_METHOD"] == "POST" ) {
header("Location: ../../../../index.php");
exit();
}
require '../../../includes/Connection.php';
session_start();
//Interest (or Category) number of selected times range
$selectedFrom = $_POST['selectedFrom'];
$selectedTo = $_POST['selectedTo'];
if (!is_numeric($_POST['selectedFrom'])){
$selectedFrom = 0;
$selectedTo = 1000000;
}
//Group By
$groupBy = $_POST['groupBy'];
//ORDER BY
$orderByType = $_POST['orderByType']; // ascending or descending sorting
$orderBy = "InterestName"; //default value
if (!empty($_POST['orderBy']))
$orderBy = $_POST['orderBy'];
if($sql = $conn ->query("SELECT interests.$groupBy interestName, sum(case when UIID is null then 0 else 1 end) selected
FROM interests LEFT JOIN usersinterests ON interests.InterestName = usersinterests.InterestName
GROUP BY $groupBy
HAVING selected >= $selectedFrom AND selected <= $selectedTo
ORDER BY $orderBy $orderByType")) {
//echo table details
if ($_GET['data'] == "table")
{
echo "
<tr>
<th>Interest</th>
<th>Selected</th>
</tr>";
$total = 0;
while ($data = mysqli_fetch_assoc($sql)) {
$total += $data['selected'];
echo "
<tr>
<td>$data[interestName]</td>
<td>$data[selected]</td>
</tr>";
}
echo "
<tr>
<th>Total</th>
<th>$total</th>
</tr>";
}
// return details for chart
elseif ($_GET['data'] == "chart"){
while ($data = mysqli_fetch_assoc($sql))
{
$output[] = array(
'interest' => $data["interestName"],
'selected' => $data["selected"]
);
}
echo json_encode($output);
}
}
else {
echo mysqli_error($conn);
} | true |
edf86af7e7e0c0cdeeec4cac0a537254866f5632 | PHP | theyasirahmad/rayeebackendremote | /Admin/database/seeds/HouseHoldCategoryTableSeeder.php | UTF-8 | 587 | 2.65625 | 3 | [
"MIT"
] | permissive | <?php
use Illuminate\Database\Seeder;
use App\Models\house_hold_category;
class HouseHoldCategoryTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$category = [
'Grocery',
'Baby',
'Chilled & Frozen',
'Drinks',
'Health & Beauty',
'Household',
'Tobacco'
];
foreach($category as $cat){
house_hold_category::create([
'title' => $cat
]);
}
}
}
| true |
70642edfd3b2d19fccdf6fd032656760efb12e2b | PHP | DCONLINE1984/surveyengine | /module/Application/src/Application/Model/CommonModel.php | UTF-8 | 1,349 | 3.234375 | 3 | [
"MIT"
] | permissive | <?php
/*
* The common model: all models extend from this one
* @author Dean Clow
* @email <dclow@blackjackfarm.com>
* @copyright 2014 Dean Clow
*/
namespace Application\Model;
class CommonModel
{
/**
* Holds the uid
* @var int
*/
protected $id = 0;
/**
* The base constructor
* Optionally, hydrates if possible
* @param string/array $obj Contains the info to hydrate the model
*/
public function __construct($obj="")
{
if(is_array($obj)){
$this->hydrate($obj);
}
}
/**
* Hydrate the model
* @param type $obj
* @return void
*/
public function hydrate($obj)
{
foreach($obj as $key=>$value){
if(property_exists($this, $key) && !empty($value)){
$this->$key = $value;
}
}
return $this;
}
/**
* Set the uid
* @param int $id
* @return \Application\Model\CommonModel
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* Get the uid
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Object to array
* @return array
*/
public function toArray()
{
return get_object_vars($this);
}
} | true |
42b85538a2ba6fd6633478a3b2ac97203e29806d | PHP | iquecode/ev_intra | /controls/parts/Statment.php | UTF-8 | 3,167 | 2.9375 | 3 | [] | no_license | <?php
Class Statment {
private $html;
private $entries;
private $class;
private $title;
private $strTotal;
private $check;
private $userId;
public function __construct($entries=[], $userId, $class='extrato', $title='Demonstrativo Financeiro',
$strTotal='Saldo atual', $check=true)
{
$file = $_SERVER['DOCUMENT_ROOT'] . DIR_BASE . 'html/statment/statment.html';
$this->html = file_get_contents($file);
$this->entries = $entries;
$this->userId = $userId;
$this->class = $class;
$this->title = $title;
$this->strTotal = $strTotal;
$this->check = $check;
}
public function load()
{
$total=0;
$items = '';
$findPend = false;
foreach ($this->entries as $entry)
{
// extrato normal
$date = date('d/m/Y',strtotime($entry->getDate()));
$description = $entry->getDescription();
$value = $entry->getValue();
$neg_pos = $value < 0 ? 'num neg_future' : 'num';
$file = $_SERVER['DOCUMENT_ROOT'] . DIR_BASE . 'html/statment/statment_item.html';
$item = file_get_contents($file);
$item = str_replace( '{date}', $date, $item);
$pend = '';
$status = $entry->getStatus();
if ($status == 0) {
$pend = 'pend';
$findPend = true;
$description .= ' - a validar';
}
$item = str_replace( '{description}', $description, $item);
$item = str_replace( '{pend}', $pend, $item);
$item = str_replace( '{value}', num($value), $item);
$item = str_replace( '{neg_pos}', $neg_pos, $item);
$total = $total + $value;
// armazena lançamentos futuros
$items .= $item;
}
$neg_pos = $total < 0 ? 'num neg_future' : 'num';
$stat = $this->html;
$stat = str_replace('{class}', $this->class, $stat);
$stat = str_replace('{id}', "u_id" . $this->userId, $stat);
$stat = str_replace('{title}', $this->title, $stat);
$stat = str_replace('{items}', $items, $stat);
$stat = str_replace('{neg_pos}', $neg_pos, $stat);
$stat = str_replace('{strTotal}', $this->strTotal, $stat);
$stat = str_replace('{total}', num($total), $stat);
$link = "<a class='a_small' href='_changes.php'>Alterar / excluir lançamentos a validar.</a>";
if ($this->check && $findPend)
{
$stat = str_replace('{link}', $link, $stat);
}
else
{
$stat = str_replace('{link}', '', $stat);
}
$this->html = $stat;
}
public function show()
{
$this->load();
print $this->html;
}
public function getHTML() {
$this->load();
return $this->html;
}
} | true |
7e9382499369d79d44755005823a0961a8a7412c | PHP | bireme/wordpress-themes | /NATS/home_news.php | UTF-8 | 3,834 | 2.640625 | 3 | [] | no_license | <?php
// Widget News Home by Category
/*
*/
class SESSP_Widget_News_Categories extends WP_Widget {
function SESSP_Widget_News_Categories() {
$widget_ops2 = array( 'classname' => 'widget_news_categories', 'description' => __( "Widget com posts por Categrias" ) );
$this->WP_Widget('level_categories', __('Home News Category Widget'), $widget_ops2);
}
function widget( $args, $instance ) {
extract( $args );
$title = apply_filters('widget_title', empty( $instance['title'] ) ? __( 'Categories' ) : $instance['title']);
$category_slug = $instance['category_slug'];
$x_posts = $instance['x_posts'];
echo $before_widget;
?>
<!-- HTML -->
<div class="container">
<div class="row news_highlight">
<?
// Pega a quantidade de posts definida no plugin e divide pelas 12 colunas
// o resultado é classe utilizada para manter o layout *bootstrap
// col-md-1 - col-md-2 - col-md-3 - col-md-4
$md = (int)(12 / $x_posts);
//Looop Wordpress com definições do plugin
query_posts( array(
'category_name' => $category_slug,
'posts_per_page' => $x_posts
) );
?>
<? if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<div class="col-md-12 col-lg-<? echo $md;?> col-xl-<? echo $md;?>">
<div class="thumbnail">
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
<?php
if ( has_post_thumbnail() ) {
?>
<img src="<?php the_post_thumbnail_url( 'news'); ?>" alt="<?php the_title(); ?>" style="width:100%">
<?
}
else {
?>
<img src="<?php echo get_bloginfo( 'stylesheet_directory' );?>/images/default_news.jpg" alt="<?php the_title(); ?>" style="width:100%">
<?
}
?>
<div class="caption">
<p><?php the_title(); ?></p>
</div>
</a>
</div>
</div>
<?php endwhile; endif; ?>
</div>
</div>
<!-- /HTML -->
<?php wp_reset_postdata();
echo $after_widget;
}
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance['title'] = strip_tags($new_instance['title']);
$instance['category_slug'] = strip_tags($new_instance['category_slug']);
$instance['x_posts'] = strip_tags($new_instance['x_posts']);
return $instance;
}
function form( $instance ) {
//Defaults
$instance = wp_parse_args( (array) $instance, array( 'title' => '') );
$title = esc_attr( $instance['title'] );
$category_slug = esc_attr( $instance['category_slug'] );
$x_posts = esc_attr( $instance['x_posts'] );
?>
<p><label for="<?php echo $this->get_field_id('title'); ?>"><?php _e( 'Title:' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" /></p>
<p>Configure a categoria de posts para aparecer no slide</br>
Exemplo: <i>destaques</i></br>
<label for="<?php echo $this->get_field_id('category_slug'); ?>"><?php _e( 'Category Slug:' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('category_slug'); ?>" name="<?php echo $this->get_field_name('category_slug'); ?>" type="text" value="<?php echo $category_slug; ?>" /></p>
<p><label for="<?php echo $this->get_field_id('x_posts'); ?>"><?php _e( 'Número de Posts: (Min=2 - Max=6)' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('x_posts'); ?>" name="<?php echo $this->get_field_name('x_posts'); ?>" type="text" value="<?php echo $x_posts; ?>" /></p>
<?php
}
}
add_action('widgets_init', create_function('', "register_widget('SESSP_Widget_News_Categories');"));
?> | true |
1bcd3cab89877f643995f07b2db58fefc67b697f | PHP | CCUMISIndependentStudy107/robot | /118/kevin/voicetest/player.php | UTF-8 | 2,398 | 2.6875 | 3 | [] | no_license | <!DOCTYPE html>
<html>
<head>
<title>Audio playbackRate Example</title>
</head>
<body>
<?php
error_reporting(0);
$voiceID = $_GET[voiceID];
?>
<div>
<audio id="audio1" style="width:25%" controls>Canvas not supported</audio>
</div>
<div>
<input type="text" id="audioFile" value="<?php echo $voiceID;?>" size="60" />
</div>
<button id="playbutton" onclick="togglePlay();">Play</button>
<button onclick="increaseSpeed();">Increase speed</button>
<button onclick="decreaseSpeed();">Decrease speed</button><br />
<div id="rate"></div>
<script type="text/javascript">
// Create a couple of global variables to use.
var audioElm = document.getElementById("audio1"); // Audio element
var ratedisplay = document.getElementById("rate"); // Rate display area
// Hook the ratechange event and display the current playbackRate after each change
audioElm.addEventListener("ratechange", function () {
ratedisplay.innerHTML = "Rate: " + audioElm.playbackRate;
}, false);
// Alternates between play and pause based on the value of the paused property
function togglePlay() {
if (document.getElementById("audio1")) {
if (audioElm.paused == true) {
playAudio(audioElm); // if player is paused, then play the file
} else {
pauseAudio(audioElm); // if player is playing, then pause
}
}
}
function playAudio(audioElm) {
document.getElementById("playbutton").innerHTML = "Pause"; // Set button text == Pause
// Get file from text box and assign it to the source of the audio element
audioElm.src = document.getElementById('audioFile').value;
audioElm.play();
}
function pauseAudio(audioElm) {
document.getElementById("playbutton").innerHTML = "play"; // Set button text == Play
audioElm.pause();
}
// Increment playbackRate by 1
function increaseSpeed() {
audioElm.playbackRate += 1;
}
// Cut playback rate in half
function decreaseSpeed() {
if (audioElm.playbackRate <= 1) {
var temp = audioElm.playbackRate;
audioElm.playbackRate = (temp / 2);
} else {
audioElm.playbackRate -= 1;
}
}
</script>
</body>
</html>
| true |
0209a673f8504e94198ada722234035da6ec88e8 | PHP | vptrvpr/majot_test | /app/Palindrome/PalindromeBuilder/CollectionPalindromeBuilder.php | UTF-8 | 858 | 3.140625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Palindrome\PalindromeBuilder;
use Illuminate\Support\Collection;
class CollectionPalindromeBuilder implements PalindromeBuilder
{
/**
* @var
*/
public $palindromeCollection;
/**
* Reset
*/
public function reset(): void
{
$this->palindromeCollection = new Collection();
}
/**
* Добавить палиндром в коллекцию
*
* @param $palindrome
*
* @return PalindromeBuilder|void
*/
public function pushPalindrome( $palindrome )
{
$this->palindromeCollection->push( $palindrome );
}
/**
* Вернуть коллекцию со всеми палиндромами
*
* @return Collection
*/
public function getPalindrome()
{
return $this->palindromeCollection;
}
}
| true |
c84541f7113166322c88db41577d19e52df00976 | PHP | aridwinugraha/tech_test | /array_loop.php | UTF-8 | 219 | 2.515625 | 3 | [] | no_license | $dataArray = ["gtAkademik", "gtFinansi", "gtPerizinan", "eCampuz", "eOviz"];
$panjangArray = count($dataArray);
$i = 0;
while ($i < $panjangArray)
{
echo "$aplikasi[".$i."]" .$dataArray[$i] ."<br/>";
$i++;
}
| true |
553f669f5619ac4f2ddb225299e7d756da5a326f | PHP | VinCHT/ProjetBlog | /model/frontend/ChapterManager.php | UTF-8 | 1,090 | 2.75 | 3 | [] | no_license | <?php
require_once('ConnectManager.php');
class ChapterManager extends Manager
{
public function getPosts()
{
$db = $this->dbConnect();
$posts = $db->query('SELECT id, title, content, num_chapter, images, DATE_FORMAT(creation_date, \'%d/%m/%Y à %Hh%i\') AS creation_date_fr FROM chapters WHERE publication= 1 ORDER BY creation_date DESC');
return $posts;
}
public function getLastPost()
{
$db = $this->dbConnect();
$req = $db->query('SELECT id, title, content, num_chapter, images, DATE_FORMAT(creation_date, \'%d/%m/%Y à %Hh%i\') AS creation_date_fr FROM chapters WHERE publication= 1 ORDER BY creation_date DESC LIMIT 1');
return $req;
}
public function getPost($postId)
{
$db = $this->dbConnect();
$req = $db->prepare('SELECT id, title, content, num_chapter, images, DATE_FORMAT(creation_date, \'%d/%m/%Y à %Hh%imin\') AS creation_date_fr FROM chapters WHERE id = ?');
$req->execute(array($postId));
$post = $req->fetch();
return $post;
}
}
| true |
b82fe0bc047bca699515c261e26e2478a9581eca | PHP | aaronmu/calculator | /src/Tests/Calculator/FirstTest.php | UTF-8 | 549 | 2.984375 | 3 | [] | no_license | <?php
namespace Tests\Calculator;
use Calculator\Math;
use Calculator\Tokenizer;
use Calculator\Dictionary;
class FirstTest extends \PHPUnit_Framework_TestCase
{
public function test_simple_addition()
{
$m = new Math(new SimpleAdditionTokenizer(), new Dictionary());
$this->assertSame(intval(2), $m->expression('foobar'));
}
}
class SimpleAdditionTokenizer implements Tokenizer
{
/**
* @param $str
* @return array
*/
public function tokenize($str)
{
return ['1', '+', '1'];
}
} | true |
ae997b55783dc7c09f3c3c41c5b750daefe7efcf | PHP | z38/dynamicdns | /src/Provider/NoIp.php | UTF-8 | 1,721 | 2.625 | 3 | [
"MIT"
] | permissive | <?php
namespace Z38\DynamicDns\Provider;
use Buzz\Listener\BasicAuthListener;
use Buzz\Listener\ListenerChain;
use Z38\DynamicDns\BrowserFactory;
use Z38\DynamicDns\Exception\InvalidHostException;
use Z38\DynamicDns\Exception\UpdateException;
class NoIp implements ProviderInterface
{
protected $browser;
public function __construct()
{
$this->browser = BrowserFactory::create();
}
/**
* {@inheritdoc}
*/
public function getId()
{
return 'noip';
}
/**
* {@inheritdoc}
*/
public function validate($host, $data)
{
if (!isset($data['username']) || !isset($data['password'])) {
throw new InvalidHostException('Please set "username" and "password".', $host);
}
}
/**
* {@inheritdoc}
*/
public function update($host, $ip, $data)
{
$url = sprintf('https://dynupdate.no-ip.com/nic/update?hostname=%s', $host);
if ($ip !== null) {
$url .= '&myip='.$ip;
}
$headers = array(
'User-Agent' => 'ddns-updater/v0.1.1 z38@users.noreply.github.com',
);
$this->browser->setListener(new BasicAuthListener($data['username'], $data['password']));
$response = $this->browser->get($url, $headers);
$this->browser->setListener(new ListenerChain());
$responseContent = $response->getContent();
if (strpos($responseContent, 'good') !== 0 && strpos($responseContent, 'nochg') !== 0) {
throw new UpdateException(sprintf('Updated failed (%s).', substr($responseContent, 0, 200)), $host);
}
}
/**
* {@inheritdoc}
*/
public function isIpRequired()
{
return false;
}
}
| true |
50802c99408f481f8b534f75d893f53f40a8045e | PHP | alainxavier/gaing | /dexc/inscription.php | UTF-8 | 3,727 | 2.5625 | 3 | [] | no_license | <?php
$message = "<h6 class='mb-4'>ou <a href='connexion.php'>cliquer pour vous connecter</a></h6>";
require('config.php');
if (isset($_REQUEST['email'], $_REQUEST['password'], $_REQUEST['confirmPassword'])){
// récupérer l'email et supprimer les antislashes ajoutés par le formulaire
$email = stripslashes($_REQUEST['email']);
$email = mysqli_real_escape_string($conn, $email);
$query = "SELECT * FROM inscriptions WHERE email='$email'";
$result = mysqli_query($conn, $query) or die(mysql_error());
$rows = mysqli_num_rows($result);
if($rows>=1){
$message = "<div class='alert alert-danger' role='alert'>Vous êtes déja inscrit!<br><a href='connexion.php'>Cliquer ici pour vous connectez.</a></div>";
} else {
if($_REQUEST['password'] !== $_REQUEST['confirmPassword']) {
$message = "<div class='alert alert-danger' role='alert'>Les mots de passe saisis sont différents</div>";
} else {
// récupérer le mot de passe et supprimer les antislashes ajoutés par le formulaire
$pass = stripslashes($_REQUEST['password']);
$pass = mysqli_real_escape_string($conn, $pass);
// récupérer le mot de passe et supprimer les antislashes ajoutés par le formulaire
$confirmPassword = stripslashes($_REQUEST['confirmPassword']);
$confirmPassword = mysqli_real_escape_string($conn, $pass);
//requéte SQL + mot de passe crypté
$query = "INSERT into `inscriptions` (email, pass, date_inscription, etats)
VALUES ('$email', '".hash('sha256', $pass)."', NOW(), 'En attente')";
// Exécute la requête sur la base de données
$res = mysqli_query($conn, $query);
if($res){
$message = "<div class='alert alert-success' role='alert'>Vous êtes inscrit avec succès.<br><a href='connexion.php'>Cliquer ici pour vous connectez.</a></div>";
} else{}
}
}
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<!-- Bootstrap core CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<style>
.bd-placeholder-img {
font-size: 1.125rem;
text-anchor: middle;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
@media (min-width: 768px) {
.bd-placeholder-img-lg {
font-size: 3.5rem;
}
}
</style>
<!-- Custom styles for this template -->
<link href="../css/signin.css" rel="stylesheet">
</head>
<body class="text-center">
<div></div>
<form class="form-signin" method="POST" action="">
<h1 class="h3 mb-3 font-weight-normal">Inscrivez-vous</h1>
<?php // Affiche un message
if (! empty($message)) {echo $message;} ?>
<label for="email" class="sr-only">Adresse email</label>
<input type="email" id="email" name="email" class="form-control mb-3" placeholder="Adresse email" required autofocus>
<label for="password" class="sr-only">Mot de passe</label>
<input type="password" id="password" name="password" class="form-control" placeholder="Mot de passe" required>
<label for="confirmPassword" class="sr-only">Retaper le mot de passe</label>
<input type="password" id="confirmPassword" name="confirmPassword" class="form-control" placeholder="Confirmer mot de passe" required>
<button class="btn btn-lg btn-primary btn-block" type="submit">S'inscrire</button>
<p class="mt-5 mb-3 text-muted">© 2020</p>
</form>
</body>
</html> | true |
7de0b6693dee4e001635a3765f581689315ca23b | PHP | vladlenov/htdocs | /MVCNews/system/BaseView.php | UTF-8 | 582 | 2.6875 | 3 | [] | no_license | <?php
namespace system;
class BaseView
{
private $content = '';
/**
* @param string $name
* @param array $params
* @param bool $toVar
* приходит из sendWebResponce
*/
public function load($name, array $params = [], $toVar = false)
{
extract($params);
unset($params);
if ($toVar) {
ob_start();
include "app/views/" . $name . ".php";
return ob_get_clean();
} else {
include "app/views/" . $name . ".php";
}
}
} | true |
a4d4e475471f4778f7ebbd453784738c8882591e | PHP | k-wth/makabeken2016 | /php/Sample/sample3.php | UTF-8 | 926 | 3.46875 | 3 | [] | no_license | <h2> 3.文字列の扱い </h2>
<h3> 3-1.文字列の結合 </h3>
<?php
// javascript : "moji1"+"moji2" -> "moji1moji2"
// phpの文字列結合は「.」
echo "moji1"."moji2"."<br />";
// phpは変数展開があります。
// [変数展開とは????]
// " " の中で、勝手に変数が元に戻っちゃうこと。
$name = "KIMIKO";
echo "私の名前は${name}です."."<br />";
echo "私の名前は".$name."です."."<br />"."<br />"."<br />"."<br />"; // これでも書ける.
// 文字列の変数展開では、${変数の名前}にしましょう.
//
// 注意!!!!!!!!!!!!!
//
echo "私の名前は${name}です."."<br />"."<br />";
echo '私の名前は${name}です.'."<br />"."<br />"."<br />"."<br />";
// こっちは展開されない!!!
$test = '$name'; // $name
echo $test
?>
| true |
ca686cc8e44ace3a33453970df1607780d10d5c0 | PHP | skolodyazhnyy/onesky-bundle | /Onesky/Downloader.php | UTF-8 | 3,628 | 2.71875 | 3 | [] | no_license | <?php
namespace Seven\Bundle\OneskyBundle\Onesky;
use Onesky\Api\Client;
class Downloader
{
/** @var Client */
private $client;
/** @var int */
private $project;
/** @var Mapping[] */
private $mappings = array();
/**
* @param Client $client
* @param int $project
*/
public function __construct(Client $client, $project)
{
$this->client = $client;
$this->project = $project;
}
/**
* @param Mapping $mapping
*
* @return $this
*/
public function addMapping(Mapping $mapping)
{
$this->mappings[] = $mapping;
return $this;
}
/**
* @return $this
*/
public function download()
{
foreach ($this->getAllSources() as $source) {
foreach ($this->getAllLocales() as $locale) {
$this->dump($source, $locale);
}
}
return $this;
}
/**
* @return array
*/
private function getAllLocales()
{
$raw = $this->client->projects('languages', array('project_id' => $this->project));
$response = json_decode($raw, true);
$data = $response['data'];
return array_map(function ($item) { return $item['locale']; }, $data);
}
/**
* @return array
*/
private function getAllSources()
{
$raw = $this->client->files('list', array('project_id' => $this->project, 'per_page' => 100));
$response = json_decode($raw, true);
$data = $response['data'];
return array_map(function ($item) { return $item['file_name']; }, $data);
}
/**
* @param string $source
* @param string $locale
*
* @return $this
*/
private function dump($source, $locale)
{
$content = null;
foreach ($this->mappings as $mapping) {
if (!$mapping->useLocale($locale) || !$mapping->useSource($source)) {
continue;
}
if ($content === null) {
$content = $this->fetch($source, $locale);
}
$this->write($mapping->getOutputFilename($source, $locale), $content);
}
return $this;
}
/**
* @param string $source
* @param string $locale
*
* @return mixed
*/
private function fetch($source, $locale)
{
$content = $this->client->translations(
'export',
array(
'project_id' => $this->project,
'locale' => $locale,
'source_file_name' => $source,
)
);
return $content;
}
/**
* @param $file
* @param $content
*
* @return $this
*/
private function write($file, $content)
{
$this->createFilePath($file);
file_put_contents($file, $content);
return $this;
}
/**
* @param string $filename
*
* @throws \Exception
*/
private function createFilePath($filename)
{
if (file_exists($filename)) {
if (!is_writable($filename)) {
throw new \Exception(sprintf('File path "%s" is not writable', $filename));
}
return;
}
$dir = dirname($filename);
if (is_dir($dir)) {
if (!is_writable($dir)) {
throw new \Exception(sprintf('Directory "%s" is not writable', $dir));
}
return;
}
if (!mkdir($dir, 0777, true)) {
throw new \Exception(sprintf('Unable to create directory "%s"', $dir));
}
}
}
| true |
427e379cdd5f28a637cfdeaca94f2b0dd0d07030 | PHP | maplerain/bumo-sdk-php | /src/model/response/result/data/Key.php | UTF-8 | 724 | 2.75 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: dw
* Date: 2018/9/3
* Time: 2:34
*/
namespace bumo\model\response\result\data;
class Key
{
/**
* @var string
*/
private $code;
/**
* @var string
*/
private $issuer;
/**
* @return string
*/
public function getCode()
{
return $this->code;
}
/**
* @param string $code
*/
public function setCode($code)
{
$this->code = $code;
}
/**
* @return string
*/
public function getIssuer()
{
return $this->issuer;
}
/**
* @param string $issuer
*/
public function setIssuer($issuer)
{
$this->issuer = $issuer;
}
} | true |
4087fc752f3d8e382a7dd00596fdd3e543e88e7a | PHP | ArnoldDev-coder/Mobwiser-IT-Academy | /src/Kernel/Middlewares/RoleMiddleware.php | UTF-8 | 966 | 2.921875 | 3 | [] | no_license | <?php
namespace Kernel\Middlewares;
use App\Authentification\Actions\Authentification;
use App\Authentification\Exception\ForbiddenException;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
class RoleMiddleware implements MiddlewareInterface
{
private Authentification $auth;
private string $role;
public function __construct(Authentification $auth, string $role)
{
$this->auth = $auth;
$this->role = $role;
}
/**
* @throws ForbiddenException
*/
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$user = $this->auth->getUser();
if ($user === null || !in_array($this->role, $user->getRole(), true)){
throw new ForbiddenException();
}
return $handler->handle($request);
}
} | true |
fe36729a337875d9a6595c5f769ea268f87bcd60 | PHP | davamigo/php-event-sourcing | /tests/Unit/Vendor/Uuid/RamseyUuidTest.php | UTF-8 | 1,369 | 2.828125 | 3 | [
"MIT"
] | permissive | <?php
namespace Test\Unit\Vendor\Uuid;
use PHPUnit\Framework\TestCase;
use Ramsey\Uuid\Uuid;
/**
* Test of library ramsey/uuid
*
* @package Test\Unit\Vendor\Uuid
* @author davamigo@gmail.com
*
* @group Test_Unit_Vendor_Uuid
* @group Test_Unit_Vendor
* @group Test_Unit
* @group Test
* @test
*/
class RamseyUuidTest extends TestCase
{
/**
* Test two consecutive calls make different UUIDs
*/
public function testUuidGeneration()
{
$uuid1 = Uuid::uuid1();
$uuid2 = Uuid::uuid1();
$str1 = $uuid1->toString();
$str2 = $uuid2->toString();
$this->assertInternalType('string', $str1);
$this->assertInternalType('string', $str2);
$this->assertNotEquals($str1, $str2);
}
/**
* Test Uuid conversion to string and from string
*/
public function testUuidConversion()
{
$uuid1 = Uuid::uuid1();
$str1 = $uuid1->toString();
$uuid2 = Uuid::fromString($str1);
$str2 = $uuid2->toString();
$this->assertEquals($str1, $str2);
}
/**
* Test Uuid format after converting to a string
*/
public function testUuidFormat()
{
$uuid = Uuid::uuid1();
$str = $uuid->toString();
$this->assertRegExp('/^\{?[0-9a-f]{8}\-?[0-9a-f]{4}\-?[0-9a-f]{4}\-?[0-9a-f]{4}\-?[0-9a-f]{12}\}?$/i', $str);
}
}
| true |
32d9ab5377968683fe2463421fa07621c1d0b827 | PHP | MAXakaWIZARD/xls-writer | /tests/ValidationTest.php | UTF-8 | 2,541 | 2.984375 | 3 | [
"MIT"
] | permissive | <?php
namespace Test;
/**
*
*/
class ValidationTest extends TestAbstract
{
public function testValidation()
{
$sheet = $this->workbook->addWorksheet();
$sheet->setColumnWidth(0, 20);
//positive number
$validator = $this->workbook->addValidator();
$validator->setPrompt('Enter positive number', 'Enter positive number');
$validator->setError('Invalid number', 'Number should be bigger than zero');
$validator->setDataType($validator::TYPE_INTEGER);
$validator->allowBlank();
$validator->setOperator($validator::OP_GT);
$validator->setFormula1('0');
$validator->onInvalidStop();
$sheet->write(0, 0, 'Enter positive number:');
$sheet->setValidation(0, 1, 0, 1, $validator);
//number in range
$validator = $this->workbook->addValidator();
$validator->setPrompt('Enter month number', 'Enter month number');
$validator->setError('Invalid month', 'Number should be in range from 1 to 12');
$validator->allowBlank();
$validator->setOperator($validator::OP_BETWEEN);
$validator->setFormula1('1');
$validator->setFormula2('12');
$validator->onInvalidInfo();
$sheet->write(1, 0, 'Enter month number:');
$sheet->setValidation(1, 1, 1, 1, $validator);
//value from list
$validator = $this->workbook->addValidator();
$validator->setPrompt('Select animal', 'Select animal');
$validator->setError('Invalid selection', 'Select animal from list');
$validator->setDataType($validator::TYPE_USER_LIST);
$validator->setFormula1('"Cat,Dog,Mouse"');
$validator->setShowDropDown();
$validator->onInvalidWarn();
$sheet->write(2, 0, 'Select animal:');
$sheet->setValidation(2, 1, 2, 1, $validator);
//value from list
$validator = $this->workbook->addValidator();
$validator->setPrompt('Select animal', 'Select animal');
$validator->setError('Invalid selection', 'Select animal from list');
$validator->setDataType($validator::TYPE_USER_LIST);
$validator->setShowDropDown();
$validator->setFormula1('$F$2:$F$5');
$sheet->write(3, 0, 'Select animal:');
$sheet->writeCol(0, 5, array('Animals:', 'Horse', 'Elephant', 'Whale', 'Squirrell'));
$sheet->setValidation(3, 1, 3, 1, $validator);
$this->workbook->save($this->testFilePath);
$this->assertTestFileEqualsTo('validation');
}
}
| true |
ca13990ff63685b7044e316a69a74ec19fa8b42f | PHP | Ocejo/stripe | /collect_details.php | UTF-8 | 1,294 | 2.578125 | 3 | [] | no_license | <?php
use \Stripe\Stripe;
try {
# vendor using composer
require_once('vendor/autoload.php');
\Stripe\Stripe::setApiKey('sk_test_51G9HjnKAZZhSOcNl6LxbGVUJd7mZaj1sVuKN3EhWIwW5TS3AvhPy2DnH21vzcydWQWH7z9GOPF1Bt9mURv5BDVSr00Cei1GQRo');
header('Content-Type: application/json');
# retrieve json from POST body
$json_str = file_get_contents('php://input');
$json_obj = json_decode($json_str);
$intent = \Stripe\PaymentIntent::create([
'payment_method' => $json_obj->payment_method_id,
'amount' => 3099,
'currency' => 'mxn',
'payment_method_options' => [
'card' => [
'installments' => [
'enabled' => true
]
]
],
]);
echo json_encode([
'intent_id' => $intent->id,
'available_plans' => $intent->payment_method_options->card->installments->available_plans
]);
}
catch (\Stripe\Exception\CardException $e){
# "e" contains a message explaining why the request failed
echo 'Card Error Message is:' . $e->getError()->message . '
';
echo json_encode([
'error_message' => $e->getError()->message
]);
}
catch (\Stripe\Exception\InvalidRequestException $e) {
// Invalid parameters were supplied to Stripe's API
echo 'Invalid Parameters Message is:' . $e->getError()->message . '
';
echo json_encode([
'error_message' => $e->getError()->message
]);
}
?> | true |
7c304049e6ac8dfb79fdbca58946378ae9e28b4e | PHP | geometria-lab/ZF2Library | /library/GeometriaLab/Test/PHPUnit/Plugin/PluginInterface.php | UTF-8 | 508 | 2.578125 | 3 | [] | no_license | <?php
namespace GeometriaLab\Test\PHPUnit\Plugin;
use GeometriaLab\Test\PHPUnit\TestCaseInterface;
interface PluginInterface
{
/**
* Set test case object
*
* @param TestCaseInterface $test
* @return PluginInterface
*/
public function setTest(TestCaseInterface $test);
/**
* Get test case object
*
* @return TestCaseInterface
*/
public function getTest();
/**
* It will call when a test ended
*/
public function endTest();
}
| true |
33059ac2f8176753babe4bd060054e87e6c54c6b | PHP | allyssalabonete/pcnhs-arms | /registrar/schoolmanagement/phpupdate/curriculum_update.php | UTF-8 | 2,144 | 2.5625 | 3 | [] | no_license | <?php
require_once "../../../resources/config.php";
include('../../../resources/classes/Popover.php');
session_start();
$willInsert = true;
$curr_id = htmlspecialchars($_POST['curr_id'], ENT_QUOTES);
$curr_name = htmlspecialchars($_POST['curr_name'], ENT_QUOTES);
$year_started = htmlspecialchars($_POST['year_started']);
$year_ended = htmlspecialchars($_POST['year_ended'], ENT_QUOTES);
if(is_numeric($year_ended)) {
if($year_ended < $year_started) {
$willInsert = false;
$alert_type = "danger";
$error_message = "Ooops. The system did not accept the value that you entered, please check and enter a valid value.";
$popover = new Popover();
$popover->set_popover($alert_type, $error_message);
$_SESSION['error_pop'] = $popover->get_popover();
header("Location: " . $_SERVER["HTTP_REFERER"]);
die();
}
}else {
if(strtoupper($year_ended) != "PRESENT") {
$willInsert = false;
$alert_type = "danger";
$error_message = "Ooops. The system did not accept the value that you entered, please check and enter a valid value.";
$popover = new Popover();
$popover->set_popover($alert_type, $error_message);
$_SESSION['error_pop'] = $popover->get_popover();
header("Location: " . $_SERVER["HTTP_REFERER"]);
die();
}else {
$year_ended = strtolower($year_ended);
$year_ended = ucfirst($year_ended);
}
}
$updatestm = "UPDATE `pcnhsdb`.`curriculum` SET `curr_name`='$curr_name', `year_ended`='$year_ended' WHERE `curr_id`='$curr_id';";
if($willInsert) {
DB::query($updatestm);
//USER LOGS
date_default_timezone_set('Asia/Manila');
$act_msg= "EDITED CURRICULUM : $curr_name";
$username = $_SESSION['username'];
$currTime = date("h:i:s A");
$log_id = null;
$currDate = date("Y-m-d");
$accnt_type = $_SESSION['accnt_type'];
DB::insert('user_logs', array(
'log_id' => $log_id,
'user_name' => $username,
'time' => $currTime,
'log_date' => $currDate,
'account_type' => $accnt_type,
'user_act' => $act_msg,
));
header("location: ../curriculum.php");
}
?>
| true |
2c5858daafe1df94bb795964c4708a1b6bb6dc6e | PHP | PacktPublishing/Functional-PHP | /Chapter05/05-monads-samples.php | UTF-8 | 1,047 | 3.0625 | 3 | [
"MIT"
] | permissive | <?php
require_once('05-monad.php');
?>
<?php
print_r(check_monad_laws(
10,
IdentityMonad::return(20),
function(int $a) { return IdentityMonad::return($a + 10); },
function(int $a) { return IdentityMonad::return($a * 2); }
));
// Array
// (
// [left identity] => 1
// [right identity] => 1
// [associativity] => 1
// )
?>
<?php
// those lines won't appear in the book, they are here just
// so that PHP can correctly lint the code.
function read_file() {}
function post() {}
class Either {
public static function pure($a) {}
public function bind($a) {}
}
?>
<?php
function upload(string $path, callable $f) {
$content = read_file(filename);
if($content === false) {
return false;
}
$status = post('/uploads', $content);
if($status === false) {
return $false;
}
return $f($status);
}
?>
<?php
function upload_fp(string $path, callable $f) {
return Either::pure($path)
->bind('read_file')
->bind(post('/uploads'))
->bind($f);
}
?>
| true |
2a5c29bcc9c456eea8ab55c50fb1a3e0e9184516 | PHP | wajatimur/cartella | /sabredav/lib/Sabre/DAV/DOCMGR/Directory.php | UTF-8 | 5,253 | 2.5625 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
$GLOBALS["mycounter"] = 0;
/**
* Directory class
*
* @package Sabre
* @subpackage DAV
* @version $Id: Directory.php 706 2010-01-10 15:09:17Z evertpot $
* @copyright Copyright (C) 2007-2010 Rooftop Solutions. All rights reserved.
* @author Evert Pot (http://www.rooftopsolutions.nl/)
* @license http://code.google.com/p/sabredav/wiki/License Modified BSD License
*/
class Sabre_DAV_DOCMGR_Directory extends Sabre_DAV_DOCMGR_Node implements Sabre_DAV_IDirectory, Sabre_DAV_IQuota {
protected $objects;
protected $object;
/**
* Creates a new file in the directory
*
* data is a readable stream resource
*
* @param string $name Name of the file
* @param resource $data Initial payload
* @return void
*/
public function createFile($name, $data = null) {
global $DOCMGR;
//write the file to a temp directory
$tmpdir = TMP_DIR."/".USER_LOGIN;
recurmkdir($tmpdir);
$tmpfile = $tmpdir."/".md5(rand()).".dat";
file_put_contents($tmpfile,$data);
$opt = null;
$opt["name"] = $name;
$opt["filepath"] = $tmpfile;
$opt["parent_path"] = $this->path;
$opt["command"] = "docmgr_file_save";
//make it hidden if it starts with a "."
if ($name[0]==".") $opt["hidden"] = "t";
$arr = $DOCMGR->call($opt);
}
/**
* Creates a new subdirectory
*
* @param string $name
* @return void
*/
public function createDirectory($name) {
global $DOCMGR;
$opt = null;
$opt["name"] = $name;
$opt["parent_path"] = $this->path;
$opt["object_type"] = "collection";
$opt["command"] = "docmgr_object_save";
$arr = $DOCMGR->call($opt);
}
/**
* Returns a specific child node, referenced by its name
*
* @param string $name
* @throws Sabre_DAV_Exception_FileNotFound
* @return Sabre_DAV_INode
*/
public function getChild($name,$objinfo=null) {
global $DOCMGR;
if (!$path) $path = "/";
$path = $this->path . '/' . $name;
$path = str_replace("/webdav.php","/",$path);
$path = str_replace("/DavWWWRoot","/",$path);
$path = str_replace("//","/",$path);
if ($path=="/")
{
return new Sabre_DAV_DOCMGR_Directory($path);
}
else
{
if ($objinfo) $this->object = $objinfo;
else
{
$opt = null;
$opt["command"] = "docmgr_object_getinfo";
$opt["path"] = $path;
$arr = $DOCMGR->call($opt);
$this->object = $arr["object"][0];
}
if ($this->object)
{
if ($this->object["object_type"]=="collection")
{
return new Sabre_DAV_DOCMGR_Directory($path);
}
else
{
return new Sabre_DAV_DOCMGR_File($path);
}
}
else
{
throw new Sabre_DAV_Exception_FileNotFound('File with name ' . $path . ' could not be located');
}
}
}
/**
* Returns an array with all the child nodes
*
* @return Sabre_DAV_INode[]
*/
public function getChildren()
{
global $DOCMGR;
$opt = null;
$opt["command"] = "docmgr_search_browse";
$opt["path"] = $this->path;
$opt["no_paginate"] = 1;
$arr = $DOCMGR->call($opt);
$this->objects = $arr["object"];
$_SESSION["docmgr_objects"] = $this->objects;
$num = count($this->objects);
$nodes = array();
for ($i=0;$i<$num;$i++)
{
$nodes[] = $this->getChild($this->objects[$i]["name"],$this->objects[$i]);
}
return $nodes;
}
/**
* Deletes all files in this directory, and then itself
*
* @return void
*/
public function delete() {
global $DOCMGR;
//just delete the entire directory
$opt = null;
$opt["command"] = "docmgr_object_delete";
$opt["path"] = $this->path;
$arr = $DOCMGR->call($opt);
}
/**
* Returns available diskspace information
*
* @return array
*/
public function getQuotaInfo() {
return array(
@disk_total_space($this->path)-@disk_free_space($this->path),
@disk_free_space($this->path)
);
}
public function getObj($path)
{
global $DOCMGR;
$objects = $_SESSION["docmgr_objects"];
$num = count($objects);
$obj = null;
for ($i=0;$i<$num;$i++)
{
if ($objects[$i]["object_path"]==$path)
{
$obj = $objects[$i];
break;
}
}
//path error, hit the api directly
if (!$obj)
{
$opt = null;
$opt["command"] = "docmgr_object_getinfo";
$opt["path"] = $path;
$arr = $DOCMGR->call($opt);
$obj = $arr["object"][0];
}
return $obj;
}
}
| true |
7f286bcf9186be1304d7f39bc036009ba1555266 | PHP | ncowboy/gu_php2 | /lesson-6/controllers/ProductsController.php | UTF-8 | 609 | 2.703125 | 3 | [] | no_license | <?php
namespace app\controllers;
use app\models\repositories\ProductRepository;
use app\services\Controller;
use Exception;
class ProductsController extends Controller
{
public function indexAction()
{
echo $this->render('catalog', [
'items' => (new ProductRepository())->getAll(),
]);
}
/**
* @throws Exception
*/
public function viewAction()
{
$product = (new ProductRepository())->getOne($this->getId());
if (!$product) {
throw new Exception('Товар не найден');
}
echo $this->render('product', [
'item' => $product
]);
}
} | true |
f2946d091c20df86741192c3ca2623dc5f0791f4 | PHP | rra-am1a-2015/inlogregistratietutorialsite | /tutorials/jquery/tut_jquery_css.php | UTF-8 | 1,383 | 2.609375 | 3 | [] | no_license | <style>
.test345
{
border:30px dashed pink;
}
</style>
<h4>JQuery CSS example</h4>
<button id="btn_css">Klik op mij voor een Jquery CSS voorbeeld met chaining</button>
<button id="btn_cssJSObject">Klik op mij voor een Jquery CSS voorbeeld met een JavaScript Object</button>
<script>
$("document").ready(function(){
// CSS veranderen door chaining
$("#btn_css").click(function(){
//alert("Hallo dan!");
$(this).css("background-color", "rgba(20, 220, 220, 1)")
.css("width", "400px")
.css("height", "200px")
.css("border-radius", "15px")
.css("outline", "0")
.addClass("test345");
});
// 1) Maak een selector voor de button met id btn_cssJSObject
// 2) Voeg een click event toe
// 3) Voeg met de css method een property margin-top = 20px toe en outline = 0
// zodat de buttons loskomen van elkaar na de click
// Veranderen css met een JavaScript Object!
var btnCSSObj = { marginTop : "20px",
outline : "0",
border : "5px solid yellow",
backgroundColor : "#FF0000"};
$("#btn_cssJSObject").click(function(){
$(this).css(btnCSSObj);
var width = parseFloat($(this).css("width"));
if ( width < 500)
{
alert("De breedte is: " + width + ". \nDit is kleiner dan 500. \nIk maak de breedte 600px");
$(this).css("width", "600px");
}
});
});
</script> | true |
cf05cbba451795b2aa5aa06f116ab47cc99a3aad | PHP | 1995tadas/hangman | /app/View/Components/WordForm.php | UTF-8 | 715 | 2.78125 | 3 | [] | no_license | <?php
namespace App\View\Components;
use Illuminate\View\Component;
class WordForm extends Component
{
public $action;
public $value;
public $buttonValue;
/**
* Create a new component instance.
*
* @param $action
* @param $buttonValue
* @param string $value
*/
public function __construct($action, $buttonValue, $value = '')
{
$this->action = $action;
$this->buttonValue = $buttonValue;
$this->value = $value;
}
/**
* Get the view / contents that represent the component.
*
* @return \Illuminate\View\View|string
*/
public function render()
{
return view('components.word-form');
}
}
| true |
35d7d827d6099f1e5e7edd38eb5fd2ed316d3c76 | PHP | latency-pl/php | /response_curl.php | UTF-8 | 1,786 | 2.734375 | 3 | [] | no_license | <?php
// example
// http://localhost:8080/response.php?url=https%3A%2F%2Fsoftreck.com
require("apifunc.php");
header('Content-Type: application/json');
try {
// $url = $_GET['url'];
$url = "https://softreck.com";
$url = urldecode($url);
apifunc([
'https://php.defjson.com/def_json.php',
], function () {
global $url;
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
/* Get the HTML or whatever is linked in $url. */
curl_exec($handle);
if (!empty(curl_error($handle))) {
throw new Exception("Error for url: " . $url . " : " . curl_error($handle));
curl_close($handle);
}
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
echo def_json("", [
"code" => $httpCode,
"url" => $url
]);
curl_close($handle);
});
} catch (Exception $e) {
// Set HTTP response status code to: 500 - Internal Server Error
echo def_json("", [
"message" => $e->getMessage(),
"url" => $url
]
);
}
//echo def_json("", ["no code"]);
//http_response_code();
function is_404($url) {
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
/* Get the HTML or whatever is linked in $url. */
$response = curl_exec($handle);
/* Check for 404 (file not found). */
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
curl_close($handle);
/* If the document has loaded successfully without any redirection or error */
if ($httpCode >= 200 && $httpCode < 300) {
return false;
} else {
return true;
}
} | true |
b013fb54bd84e7743ea87607bba552c0575de7d2 | PHP | Juuro/Dreamapp-Website | /sites/silverstripe/sapphire/thirdparty/simplepie/SimplePie.php | UTF-8 | 130,861 | 2.640625 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
/**
* A PHP-Based RSS and Atom Feed Framework
* Takes the hard work out of managing a complete RSS/Atom solution.
* Version: "Lemon Meringue"
* Updated: 3 November 2006
* Copyright: 2004-2006 Ryan Parman, Geoffrey Sneddon
* http://simplepie.org
* LICENSE: GNU Lesser General Public License 2.1 (LGPL)
* Please submit all bug reports and feature requests to the SimplePie forums. http://simplepie.org/support/
* @package sapphire
* @subpackage integration
*/
class SimplePie
{
// SimplePie Info
var $name = 'SimplePie';
var $version = '1.0 b3.1';
var $build = '20061103';
var $url = 'http://simplepie.org/';
var $useragent;
var $linkback;
// Other objects, instances created here so we can set options on them
var $sanitize;
// Options
var $rss_url;
var $file;
var $timeout = 10;
var $xml_dump = false;
var $enable_cache = true;
var $max_minutes = 60;
var $cache_location = './cache';
var $order_by_date = true;
var $input_encoding = false;
var $cache_class = 'SimplePie_Cache';
var $locator_class = 'SimplePie_Locator';
var $parser_class = 'SimplePie_Parser';
var $file_class = 'SimplePie_File';
var $force_fsockopen = false;
var $cache_name_type = 'sha1';
// Misc. variables
var $data;
var $error;
function SimplePie($feed_url = null, $cache_location = null, $cache_max_minutes = null)
{
// Couple of variables built up from other variables
$this->useragent = $this->name . '/' . $this->version . ' (Feed Parser; ' . $this->url . '; Allow like Gecko) Build/' . $this->build;
$this->linkback = '<a href="' . $this->url . '" title="' . $this->name . ' ' . $this->version . '">' . $this->name . '</a>';
// Other objects, instances created here so we can set options on them
$this->sanitize = new SimplePie_Sanitize;
// Set options if they're passed to the constructor
if (!is_null($feed_url))
{
$this->feed_url($feed_url);
}
if (!is_null($cache_location))
{
$this->cache_location($cache_location);
}
if (!is_null($cache_max_minutes))
{
$this->cache_max_minutes($cache_max_minutes);
}
// If we've passed an xmldump variable in the URL, snap into XMLdump mode
if (isset($_GET['xmldump']))
{
$this->enable_xmldump(true);
}
// Only init the script if we're passed a feed URL
if (!is_null($feed_url))
{
return $this->init();
}
}
function feed_url($url)
{
$this->rss_url = SimplePie_Misc::fix_protocol($url, 1);
}
function set_file(&$file)
{
if (is_a($file, 'SimplePie_File'))
{
$this->rss_url = $file->url;
$this->file =& $file;
}
}
function set_timeout($timeout = 10)
{
$this->timeout = (int) $timeout;
}
function set_raw_data($data)
{
$this->raw_data = trim((string) $data);
}
function enable_xmldump($enable = false)
{
$this->xml_dump = (bool) $enable;
}
function enable_caching($enable = true)
{
$this->enable_cache = (bool) $enable;
}
function cache_max_minutes($minutes = 60)
{
$this->max_minutes = (float) $minutes;
}
function cache_location($location = './cache')
{
$this->cache_location = (string) $location;
}
function order_by_date($enable = true)
{
$this->order_by_date = (bool) $enable;
}
function input_encoding($encoding = false)
{
if ($encoding)
{
$this->input_encoding = (string) $encoding;
}
else
{
$this->input_encoding = false;
}
}
function set_cache_class($class = 'SimplePie_Cache')
{
if (SimplePie_Misc::is_a_class($class, 'SimplePie_Cache'))
{
$this->cache_class = $class;
return true;
}
return false;
}
function set_locator_class($class = 'SimplePie_Locator')
{
if (SimplePie_Misc::is_a_class($class, 'SimplePie_Locator'))
{
$this->locator_class = $class;
return true;
}
return false;
}
function set_parser_class($class = 'SimplePie_Parser')
{
if (SimplePie_Misc::is_a_class($class, 'SimplePie_Parser'))
{
$this->parser_class = $class;
return true;
}
return false;
}
function set_file_class($class = 'SimplePie_File')
{
if (SimplePie_Misc::is_a_class($class, 'SimplePie_File'))
{
$this->file_class = $class;
return true;
}
return false;
}
function set_sanitize_class($object = 'SimplePie_Sanitize')
{
if (class_exists($object))
{
$this->sanitize = new $object;
return true;
}
return false;
}
function set_useragent($ua)
{
$this->useragent = (string) $ua;
}
function force_fsockopen($enable = false)
{
$this->force_fsockopen = (bool) $enable;
}
function set_cache_name_type($type = 'sha1')
{
$type = strtolower(trim($type));
switch ($type)
{
case 'crc32':
$this->cache_name_type = 'crc32';
break;
case 'md5':
$this->cache_name_type = 'md5';
break;
case 'rawurlencode':
$this->cache_name_type = 'rawurlencode';
break;
case 'urlencode':
$this->cache_name_type = 'urlencode';
break;
default:
$this->cache_name_type = 'sha1';
break;
}
}
function bypass_image_hotlink($get = false)
{
$this->sanitize->bypass_image_hotlink($get);
}
function bypass_image_hotlink_page($page = false)
{
$this->sanitize->bypass_image_hotlink_page($page);
}
function replace_headers($enable = false)
{
$this->sanitize->replace_headers($enable);
}
function remove_div($enable = true)
{
$this->sanitize->remove_div($enable);
}
function strip_ads($enable = false)
{
$this->sanitize->strip_ads($enable);
}
function strip_htmltags($tags = array('base', 'blink', 'body', 'doctype', 'embed', 'font', 'form', 'frame', 'frameset', 'html', 'iframe', 'input', 'marquee', 'meta', 'noscript', 'object', 'param', 'script', 'style'), $encode = null)
{
$this->sanitize->strip_htmltags($tags);
if (!is_null($encode))
{
$this->sanitize->encode_instead_of_strip($tags);
}
}
function encode_instead_of_strip($enable = true)
{
$this->sanitize->encode_instead_of_strip($enable);
}
function strip_attributes($attribs = array('bgsound', 'class', 'expr', 'id', 'style', 'onclick', 'onerror', 'onfinish', 'onmouseover', 'onmouseout', 'onfocus', 'onblur'))
{
$this->sanitize->strip_attributes($attribs);
}
function output_encoding($encoding = 'UTF-8')
{
$this->sanitize->output_encoding($encoding);
}
function set_item_class($class = 'SimplePie_Item')
{
return $this->sanitize->set_item_class($class);
}
function set_author_class($class = 'SimplePie_Author')
{
return $this->sanitize->set_author_class($class);
}
function set_enclosure_class($class = 'SimplePie_Enclosure')
{
return $this->sanitize->set_enclosure_class($class);
}
function init()
{
if (!(function_exists('version_compare') && ((version_compare(phpversion(), '4.3.2', '>=') && version_compare(phpversion(), '5', '<')) || version_compare(phpversion(), '5.0.3', '>='))) || !extension_loaded('xml') || !extension_loaded('pcre'))
{
return false;
}
if ($this->sanitize->bypass_image_hotlink && !empty($_GET[$this->sanitize->bypass_image_hotlink]))
{
if (get_magic_quotes_gpc())
{
$_GET[$this->sanitize->bypass_image_hotlink] = stripslashes($_GET[$this->sanitize->bypass_image_hotlink]);
}
SimplePie_Misc::display_file($_GET[$this->sanitize->bypass_image_hotlink], 10, $this->useragent);
}
if (isset($_GET['js']))
{
$embed = <<<EOT
function embed_odeo(link) {
document.writeln('<embed src="http://odeo.com/flash/audio_player_fullsize.swf" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" quality="high" width="440" height="80" wmode="transparent" allowScriptAccess="any" flashvars="valid_sample_rate=true&external_url='+link+'"></embed>');
}
function embed_quicktime(type, bgcolor, width, height, link, placeholder, loop) {
if (placeholder != '') {
document.writeln('<embed type="'+type+'" style="cursor:hand; cursor:pointer;" href="'+link+'" src="'+placeholder+'" width="'+width+'" height="'+height+'" autoplay="false" target="myself" controller="false" loop="'+loop+'" scale="aspect" bgcolor="'+bgcolor+'" pluginspage="http://www.apple.com/quicktime/download/"></embed>');
}
else {
document.writeln('<embed type="'+type+'" style="cursor:hand; cursor:pointer;" src="'+link+'" width="'+width+'" height="'+height+'" autoplay="false" target="myself" controller="true" loop="'+loop+'" scale="aspect" bgcolor="'+bgcolor+'" pluginspage="http://www.apple.com/quicktime/download/"></embed>');
}
}
function embed_flash(bgcolor, width, height, link, loop, type) {
document.writeln('<embed src="'+link+'" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" type="'+type+'" quality="high" width="'+width+'" height="'+height+'" bgcolor="'+bgcolor+'" loop="'+loop+'"></embed>');
}
function embed_wmedia(width, height, link) {
document.writeln('<embed type="application/x-mplayer2" src="'+link+'" autosize="1" width="'+width+'" height="'+height+'" showcontrols="1" showstatusbar="0" showdisplay="0" autostart="0"></embed>');
}
EOT;
if (function_exists('ob_gzhandler'))
{
ob_start('ob_gzhandler');
}
header('Content-type: text/javascript; charset: UTF-8');
header('Cache-Control: must-revalidate');
header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 86400) . ' GMT');
echo $embed;
exit;
}
if (!empty($this->rss_url) || !empty($this->raw_data))
{
$this->data = array();
$cache = false;
if (!empty($this->rss_url))
{
// Decide whether to enable caching
if ($this->enable_cache && preg_match('/^http(s)?:\/\//i', $this->rss_url))
{
$cache = new $this->cache_class($this->cache_location, call_user_func($this->cache_name_type, $this->rss_url), 'spc');
}
// If it's enabled and we don't want an XML dump, use the cache
if ($cache && !$this->xml_dump)
{
// Load the Cache
$this->data = $cache->load();
if (!empty($this->data))
{
// If we've hit a collision just rerun it with caching disabled
if (isset($this->data['url']) && $this->data['url'] != $this->rss_url)
{
$cache = false;
}
// If we've got a feed_url stored (if the page isn't actually a feed, or is a redirect) use that URL
else if (!empty($this->data['feed_url']))
{
if ($this->data['feed_url'] == $this->data['url'])
{
$cache->unlink();
}
else
{
$this->feed_url($this->data['feed_url']);
return $this->init();
}
}
// If the cache is new enough
else if ($cache->mtime() + $this->max_minutes * 60 < time())
{
// If we have last-modified and/or etag set
if (!empty($this->data['last-modified']) || !empty($this->data['etag']))
{
$headers = array();
if (!empty($this->data['last-modified']))
{
$headers['if-modified-since'] = $this->data['last-modified'];
}
if (!empty($this->data['etag']))
{
$headers['if-none-match'] = $this->data['etag'];
}
$file = new $this->file_class($this->rss_url, $this->timeout/10, 5, $headers, $this->useragent, $this->force_fsockopen);
if ($file->success)
{
$headers = $file->headers();
if ($headers['status']['code'] == 304)
{
$cache->touch();
return true;
}
}
else
{
unset($file);
}
}
// If we don't have last-modified or etag set, just clear the cache
else
{
$cache->unlink();
}
}
// If the cache is still valid, just return true
else
{
return true;
}
}
// If the cache is empty, delete it
else
{
$cache->unlink();
}
}
$this->data = array();
// If we don't already have the file (it'll only exist if we've opened it to check if the cache has been modified), open it.
if (!isset($file))
{
if (is_a($this->file, 'SimplePie_File') && $this->file->url == $this->rss_url)
{
$file =& $this->file;
}
else
{
$file = new $this->file_class($this->rss_url, $this->timeout, 5, null, $this->useragent, $this->force_fsockopen);
}
}
// If the file connection has an error, set SimplePie::error to that and quit
if (!$file->success)
{
$this->error = $file->error;
return false;
}
// Check if the supplied URL is a feed, if it isn't, look for it.
$locate = new $this->locator_class($file, $this->timeout, $this->useragent);
if (!$locate->is_feed($file))
{
$feed = $locate->find();
if ($feed)
{
if ($cache && !$cache->save(array('url' => $this->rss_url, 'feed_url' => $feed)))
{
$this->error = "$cache->name is not writeable";
SimplePie_Misc::error($this->error, E_USER_WARNING, __FILE__, __LINE__);
}
$this->rss_url = $feed;
return $this->init();
}
else
{
$this->error = "A feed could not be found at $this->rss_url";
SimplePie_Misc::error($this->error, E_USER_WARNING, __FILE__, __LINE__);
return false;
}
}
$headers = $file->headers();
$data = trim($file->body());
$file->close();
unset($file);
}
else
{
$data = $this->raw_data;
}
// First check to see if input has been overridden.
if (!empty($this->input_encoding))
{
$encoding = $this->input_encoding;
}
// Second try HTTP headers
else if (!empty($headers['content-type']) && preg_match('/charset\s*=\s*([^;]*)/i', $headers['content-type'], $charset))
{
$encoding = $charset[1];
}
// Then prolog, if at the very start of the document
else if (preg_match('/^<\?xml(.*)?>/msiU', $data, $prolog) && preg_match('/encoding\s*=\s*("([^"]*)"|\'([^\']*)\')/Ui', $prolog[1], $encoding))
{
$encoding = substr($encoding[1], 1, -1);
}
// UTF-32 Big Endian BOM
else if (strpos($data, sprintf('%c%c%c%c', 0x00, 0x00, 0xFE, 0xFF)) === 0)
{
$encoding = 'UTF-32be';
}
// UTF-32 Little Endian BOM
else if (strpos($data, sprintf('%c%c%c%c', 0xFF, 0xFE, 0x00, 0x00)) === 0)
{
$encoding = 'UTF-32';
}
// UTF-16 Big Endian BOM
else if (strpos($data, sprintf('%c%c', 0xFE, 0xFF)) === 0)
{
$encoding = 'UTF-16be';
}
// UTF-16 Little Endian BOM
else if (strpos($data, sprintf('%c%c', 0xFF, 0xFE)) === 0)
{
$encoding = 'UTF-16le';
}
// UTF-8 BOM
else if (strpos($data, sprintf('%c%c%c', 0xEF, 0xBB, 0xBF)) === 0)
{
$encoding = 'UTF-8';
}
// Fallback to the default
else
{
$encoding = null;
}
// Change the encoding to UTF-8 (as we always use UTF-8 internally)
$data = SimplePie_Misc::change_encoding($data, $encoding, 'UTF-8');
// Start parsing
$data = new $this->parser_class($data, 'UTF-8', $this->xml_dump);
// If we want the XML, just output that and quit
if ($this->xml_dump)
{
header('Content-type: text/xml; charset=UTF-8');
echo $data->data;
exit;
}
// If it's parsed fine
else if (!$data->error_code)
{
// Parse the data, and make it sane
$this->sanitize->parse_data_array($data->data, $this->rss_url);
unset($data);
// Get the sane data
$this->data['feedinfo'] = $this->sanitize->feedinfo;
unset($this->sanitize->feedinfo);
$this->data['info'] = $this->sanitize->info;
unset($this->sanitize->info);
$this->data['items'] = $this->sanitize->items;
unset($this->sanitize->items);
$this->data['feedinfo']['encoding'] = $this->sanitize->output_encoding;
$this->data['url'] = $this->rss_url;
// Store the headers that we need
if (!empty($headers['last-modified']))
{
$this->data['last-modified'] = $headers['last-modified'];
}
if (!empty($headers['etag']))
{
$this->data['etag'] = $headers['etag'];
}
// If we want to order it by date, check if all items have a date, and then sort it
if ($this->order_by_date && !empty($this->data['items']))
{
$do_sort = true;
foreach ($this->data['items'] as $item)
{
if (!$item->get_date('U'))
{
$do_sort = false;
break;
}
}
if ($do_sort)
{
usort($this->data['items'], create_function('$a, $b', 'if ($a->get_date(\'U\') == $b->get_date(\'U\')) return 1; return ($a->get_date(\'U\') < $b->get_date(\'U\')) ? 1 : -1;'));
}
}
// Cache the file if caching is enabled
if ($cache && !$cache->save($this->data))
{
$this->error = "$cache->name is not writeable";
SimplePie_Misc::error($this->error, E_USER_WARNING, __FILE__, __LINE__);
}
return true;
}
// If we have an error, just set SimplePie::error to it and quit
else
{
$this->error = "XML error: $data->error_string at line $data->current_line, column $data->current_column";
SimplePie_Misc::error($this->error, E_USER_WARNING, __FILE__, __LINE__);
return false;
}
}
}
function get_encoding()
{
if (!empty($this->data['feedinfo']['encoding']))
{
return $this->data['feedinfo']['encoding'];
}
else
{
return false;
}
}
function handle_content_type($mime = 'text/html')
{
if (!headers_sent())
{
$header = "Content-type: $mime;";
if ($this->get_encoding())
{
$header .= ' charset=' . $this->get_encoding();
}
else
{
$header .= ' charset=UTF-8';
}
header($header);
}
}
function get_type()
{
if (!empty($this->data['feedinfo']['type']))
{
return $this->data['feedinfo']['type'];
}
else
{
return false;
}
}
function get_version()
{
if (!empty($this->data['feedinfo']['version']))
{
return $this->data['feedinfo']['version'];
}
else
{
return false;
}
}
function get_favicon($check = false, $alternate = null)
{
if (!empty($this->data['info']['link']['alternate'][0]))
{
$favicon = SimplePie_Misc::absolutize_url('/favicon.ico', $this->get_feed_link());
if ($check)
{
$file = new $this->file_class($favicon, $this->timeout/10, 5, null, $this->useragent, $this->force_fsockopen);
$headers = $file->headers();
$file->close();
if ($headers['status']['code'] == 200)
{
return $favicon;
}
}
else
{
return $favicon;
}
}
if (!is_null($alternate))
{
return $alternate;
}
else
{
return false;
}
}
function subscribe_url()
{
if (!empty($this->rss_url))
{
return $this->rss_url;
}
else
{
return false;
}
}
function subscribe_feed()
{
if (!empty($this->rss_url))
{
return SimplePie_Misc::fix_protocol($this->rss_url, 2);
}
else
{
return false;
}
}
function subscribe_outlook()
{
if (!empty($this->rss_url))
{
return 'outlook' . SimplePie_Misc::fix_protocol($this->rss_url, 2);
}
else
{
return false;
}
}
function subscribe_podcast()
{
if (!empty($this->rss_url))
{
return SimplePie_Misc::fix_protocol($this->rss_url, 3);
}
else
{
return false;
}
}
function subscribe_aol()
{
if ($this->subscribe_url())
{
return 'http://feeds.my.aol.com/add.jsp?url=' . rawurlencode($this->subscribe_url());
}
else
{
return false;
}
}
function subscribe_bloglines()
{
if ($this->subscribe_url())
{
return 'http://www.bloglines.com/sub/' . rawurlencode($this->subscribe_url());
}
else
{
return false;
}
}
function subscribe_eskobo()
{
if ($this->subscribe_url())
{
return 'http://www.eskobo.com/?AddToMyPage=' . rawurlencode($this->subscribe_url());
}
else
{
return false;
}
}
function subscribe_feedfeeds()
{
if ($this->subscribe_url())
{
return 'http://www.feedfeeds.com/add?feed=' . rawurlencode($this->subscribe_url());
}
else
{
return false;
}
}
function subscribe_feedlounge()
{
if ($this->subscribe_url())
{
return 'http://my.feedlounge.com/external/subscribe?url=' . rawurlencode($this->subscribe_url());
}
else
{
return false;
}
}
function subscribe_feedster()
{
if ($this->subscribe_url())
{
return 'http://www.feedster.com/myfeedster.php?action=addrss&confirm=no&rssurl=' . rawurlencode($this->subscribe_url());
}
else
{
return false;
}
}
function subscribe_google()
{
if ($this->subscribe_url())
{
return 'http://fusion.google.com/add?feedurl=' . rawurlencode($this->subscribe_url());
}
else
{
return false;
}
}
function subscribe_gritwire()
{
if ($this->subscribe_url())
{
return 'http://my.gritwire.com/feeds/addExternalFeed.aspx?FeedUrl=' . rawurlencode($this->subscribe_url());
}
else
{
return false;
}
}
function subscribe_msn()
{
if ($this->subscribe_url())
{
$url = 'http://my.msn.com/addtomymsn.armx?id=rss&ut=' . rawurlencode($this->subscribe_url());
if ($this->get_feed_link())
{
$url .= '&ru=' . rawurlencode($this->get_feed_link());
}
return $url;
}
else
{
return false;
}
}
function subscribe_netvibes()
{
if ($this->subscribe_url())
{
return 'http://www.netvibes.com/subscribe.php?url=' . rawurlencode($this->subscribe_url());
}
else
{
return false;
}
}
function subscribe_newsburst()
{
if ($this->subscribe_url())
{
return 'http://www.newsburst.com/Source/?add=' . rawurlencode($this->subscribe_url());
}
else
{
return false;
}
}
function subscribe_newsgator()
{
if ($this->subscribe_url())
{
return 'http://www.newsgator.com/ngs/subscriber/subext.aspx?url=' . rawurlencode($this->subscribe_url());
}
else
{
return false;
}
}
function subscribe_odeo()
{
if ($this->subscribe_url())
{
return 'http://www.odeo.com/listen/subscribe?feed=' . rawurlencode($this->subscribe_url());
}
else
{
return false;
}
}
function subscribe_pluck()
{
if ($this->subscribe_url())
{
return 'http://client.pluck.com/pluckit/prompt.aspx?GCID=C12286x053&a=' . rawurlencode($this->subscribe_url());
}
else
{
return false;
}
}
function subscribe_podnova()
{
if ($this->subscribe_url())
{
return 'http://www.podnova.com/index_your_podcasts.srf?action=add&url=' . rawurlencode($this->subscribe_url());
}
else
{
return false;
}
}
function subscribe_rojo()
{
if ($this->subscribe_url())
{
return 'http://www.rojo.com/add-subscription?resource=' . rawurlencode($this->subscribe_url());
}
else
{
return false;
}
}
function subscribe_yahoo()
{
if ($this->subscribe_url())
{
return 'http://add.my.yahoo.com/rss?url=' . rawurlencode($this->subscribe_url());
}
else
{
return false;
}
}
function get_feed_title()
{
if (!empty($this->data['info']['title']))
{
return $this->data['info']['title'];
}
else
{
return false;
}
}
function get_feed_link()
{
if (!empty($this->data['info']['link']['alternate'][0]))
{
return $this->data['info']['link']['alternate'][0];
}
else
{
return false;
}
}
function get_feed_links()
{
if (!empty($this->data['info']['link']))
{
return $this->data['info']['link'];
}
else
{
return false;
}
}
function get_feed_description()
{
if (!empty($this->data['info']['description']))
{
return $this->data['info']['description'];
}
else if (!empty($this->data['info']['dc:description']))
{
return $this->data['info']['dc:description'];
}
else if (!empty($this->data['info']['tagline']))
{
return $this->data['info']['tagline'];
}
else if (!empty($this->data['info']['subtitle']))
{
return $this->data['info']['subtitle'];
}
else
{
return false;
}
}
function get_feed_copyright()
{
if (!empty($this->data['info']['copyright']))
{
return $this->data['info']['copyright'];
}
else
{
return false;
}
}
function get_feed_language()
{
if (!empty($this->data['info']['language']))
{
return $this->data['info']['language'];
}
else if (!empty($this->data['info']['xml:lang']))
{
return $this->data['info']['xml:lang'];
}
else
{
return false;
}
}
function get_image_exist()
{
if (!empty($this->data['info']['image']['url']) || !empty($this->data['info']['image']['logo']))
{
return true;
}
else
{
return false;
}
}
function get_image_title()
{
if (!empty($this->data['info']['image']['title']))
{
return $this->data['info']['image']['title'];
}
else
{
return false;
}
}
function get_image_url()
{
if (!empty($this->data['info']['image']['url']))
{
return $this->data['info']['image']['url'];
}
else if (!empty($this->data['info']['image']['logo']))
{
return $this->data['info']['image']['logo'];
}
else
{
return false;
}
}
function get_image_link()
{
if (!empty($this->data['info']['image']['link']))
{
return $this->data['info']['image']['link'];
}
else
{
return false;
}
}
function get_image_width()
{
if (!empty($this->data['info']['image']['width']))
{
return $this->data['info']['image']['width'];
}
else
{
return false;
}
}
function get_image_height()
{
if (!empty($this->data['info']['image']['height']))
{
return $this->data['info']['image']['height'];
}
else
{
return false;
}
}
function get_item_quantity($max = 0)
{
if (!empty($this->data['items']))
{
$qty = sizeof($this->data['items']);
}
else
{
$qty = 0;
}
if ($max == 0)
{
return $qty;
}
else
{
return ($qty > $max) ? $max : $qty;
}
}
function get_item($key = 0)
{
if (!empty($this->data['items'][$key]))
{
return $this->data['items'][$key];
}
else
{
return false;
}
}
function get_items($start = 0, $end = 0)
{
if ($this->get_item_quantity() > 0)
{
if ($end == 0)
{
return array_slice($this->data['items'], $start);
}
else
{
return array_slice($this->data['items'], $start, $end);
}
}
else
{
return false;
}
}
}
/**
* @package sapphire
* @subpackage integration
*/
class SimplePie_Item
{
var $data;
function SimplePie_Item($data)
{
$this->data =& $data;
}
function get_id()
{
if (!empty($this->data['guid']['data']))
{
return $this->data['guid']['data'];
}
else if (!empty($this->data['id']))
{
return $this->data['id'];
}
else
{
return false;
}
}
function get_title()
{
if (!empty($this->data['title']))
{
return $this->data['title'];
}
else if (!empty($this->data['dc:title']))
{
return $this->data['dc:title'];
}
else
{
return false;
}
}
function get_description()
{
if (!empty($this->data['content']))
{
return $this->data['content'];
}
else if (!empty($this->data['encoded']))
{
return $this->data['encoded'];
}
else if (!empty($this->data['summary']))
{
return $this->data['summary'];
}
else if (!empty($this->data['description']))
{
return $this->data['description'];
}
else if (!empty($this->data['dc:description']))
{
return $this->data['dc:description'];
}
else if (!empty($this->data['longdesc']))
{
return $this->data['longdesc'];
}
else
{
return false;
}
}
function get_category($key = 0)
{
$categories = $this->get_categories();
if (!empty($categories[$key]))
{
return $categories[$key];
}
else
{
return false;
}
}
function get_categories()
{
$categories = array();
if (!empty($this->data['category']))
{
$categories = array_merge($categories, $this->data['category']);
}
if (!empty($this->data['subject']))
{
$categories = array_merge($categories, $this->data['subject']);
}
if (!empty($this->data['term']))
{
$categories = array_merge($categories, $this->data['term']);
}
if (!empty($categories))
{
return array_unique($categories);
}
else
{
return false;
}
}
function get_author($key = 0)
{
$authors = $this->get_authors();
if (!empty($authors[$key]))
{
return $authors[$key];
}
else
{
return false;
}
}
function get_authors()
{
$authors = array();
if (!empty($this->data['author']))
{
$authors = array_merge($authors, $this->data['author']);
}
if (!empty($this->data['creator']))
{
$authors = array_merge($authors, $this->data['creator']);
}
if (!empty($authors))
{
return array_unique($authors);
}
else
{
return false;
}
}
function get_date($date_format = 'j F Y, g:i a')
{
if (!empty($this->data['pubdate']))
{
return date($date_format, $this->data['pubdate']);
}
else if (!empty($this->data['dc:date']))
{
return date($date_format, $this->data['dc:date']);
}
else if (!empty($this->data['issued']))
{
return date($date_format, $this->data['issued']);
}
else if (!empty($this->data['published']))
{
return date($date_format, $this->data['published']);
}
else if (!empty($this->data['modified']))
{
return date($date_format, $this->data['modified']);
}
else if (!empty($this->data['updated']))
{
return date($date_format, $this->data['updated']);
}
else
{
return false;
}
}
function get_permalink()
{
$link = $this->get_link(0);
$enclosure = $this->get_enclosure(0);
if (!empty($link))
{
return $link;
}
else if (!empty($enclosure))
{
return $enclosure->get_link();
}
else
{
return false;
}
}
function get_link($key = 0, $rel = 'alternate')
{
$links = $this->get_links($rel);
if (!empty($links[$key]))
{
return $links[$key];
}
else
{
return false;
}
}
function get_links($rel = 'alternate')
{
if ($rel == 'alternate')
{
$links = array();
if (!empty($this->data['link'][$rel]))
{
$links = $this->data['link'][$rel];
}
if (!empty($this->data['guid']['data']) && $this->data['guid']['permalink'] == true)
{
$links[] = $this->data['guid']['data'];
}
return $links;
}
else if (!empty($this->data['link'][$rel]))
{
return $this->data['link'][$rel];
}
else
{
return false;
}
}
function get_enclosure($key = 0)
{
$enclosures = $this->get_enclosures();
if (!empty($enclosures[$key]))
{
return $enclosures[$key];
}
else
{
return false;
}
}
function get_enclosures()
{
$enclosures = array();
$links = $this->get_links('enclosure');
if (!empty($this->data['enclosures']))
{
$enclosures = array_merge($enclosures, $this->data['enclosures']);
}
if (!empty($links))
{
$enclosures = array_merge($enclosures, $links);
}
if (!empty($enclosures))
{
return array_unique($enclosures);
}
else
{
return false;
}
}
function add_to_blinklist()
{
if ($this->get_permalink())
{
$url = 'http://www.blinklist.com/index.php?Action=Blink/addblink.php&Description=&Url=' . rawurlencode($this->get_permalink());
if ($this->get_title())
{
$url .= '&Title=' . rawurlencode($this->get_title());
}
return $url;
}
else
{
return false;
}
}
function add_to_blogmarks()
{
if ($this->get_permalink())
{
$url = 'http://blogmarks.net/my/new.php?mini=1&simple=1&url=' . rawurlencode($this->get_permalink());
if ($this->get_title())
{
$url .= '&title=' . rawurlencode($this->get_title());
}
return $url;
}
else
{
return false;
}
}
function add_to_delicious()
{
if ($this->get_permalink())
{
$url = 'http://del.icio.us/post/?v=3&url=' . rawurlencode($this->get_permalink());
if ($this->get_title())
{
$url .= '&title=' . rawurlencode($this->get_title());
}
return $url;
}
else
{
return false;
}
}
function add_to_digg()
{
if ($this->get_permalink())
{
return 'http://digg.com/submit?phase=2&URL=' . rawurlencode($this->get_permalink());
}
else
{
return false;
}
}
function add_to_furl()
{
if ($this->get_permalink())
{
$url = 'http://www.furl.net/storeIt.jsp?u=' . rawurlencode($this->get_permalink());
if ($this->get_title())
{
$url .= '&t=' . rawurlencode($this->get_title());
}
return $url;
}
else
{
return false;
}
}
function add_to_magnolia()
{
if ($this->get_permalink())
{
$url = 'http://ma.gnolia.com/bookmarklet/add?url=' . rawurlencode($this->get_permalink());
if ($this->get_title())
{
$url .= '&title=' . rawurlencode($this->get_title());
}
return $url;
}
else
{
return false;
}
}
function add_to_myweb20()
{
if ($this->get_permalink())
{
$url = 'http://myweb2.search.yahoo.com/myresults/bookmarklet?u=' . rawurlencode($this->get_permalink());
if ($this->get_title())
{
$url .= '&t=' . rawurlencode($this->get_title());
}
return $url;
}
else
{
return false;
}
}
function add_to_newsvine()
{
if ($this->get_permalink())
{
$url = 'http://www.newsvine.com/_wine/save?u=' . rawurlencode($this->get_permalink());
if ($this->get_title())
{
$url .= '&h=' . rawurlencode($this->get_title());
}
return $url;
}
else
{
return false;
}
}
function add_to_reddit()
{
if ($this->get_permalink())
{
$url = 'http://reddit.com/submit?url=' . rawurlencode($this->get_permalink());
if ($this->get_title())
{
$url .= '&title=' . rawurlencode($this->get_title());
}
return $url;
}
else
{
return false;
}
}
function add_to_segnalo()
{
if ($this->get_permalink())
{
$url = 'http://segnalo.com/post.html.php?url=' . rawurlencode($this->get_permalink());
if ($this->get_title())
{
$url .= '&title=' . rawurlencode($this->get_title());
}
return $url;
}
else
{
return false;
}
}
function add_to_simpy()
{
if ($this->get_permalink())
{
$url = 'http://www.simpy.com/simpy/LinkAdd.do?href=' . rawurlencode($this->get_permalink());
if ($this->get_title())
{
$url .= '&title=' . rawurlencode($this->get_title());
}
return $url;
}
else
{
return false;
}
}
function add_to_smarking()
{
if ($this->get_permalink())
{
return 'http://smarking.com/editbookmark/?url=' . rawurlencode($this->get_permalink());
}
else
{
return false;
}
}
function add_to_spurl()
{
if ($this->get_permalink())
{
$url = 'http://www.spurl.net/spurl.php?v=3&url=' . rawurlencode($this->get_permalink());
if ($this->get_title())
{
$url .= '&title=' . rawurlencode($this->get_title());
}
return $url;
}
else
{
return false;
}
}
function add_to_wists()
{
if ($this->get_permalink())
{
$url = 'http://wists.com/r.php?c=&r=' . rawurlencode($this->get_permalink());
if ($this->get_title())
{
$url .= '&title=' . rawurlencode($this->get_title());
}
return $url;
}
else
{
return false;
}
}
function search_technorati()
{
if ($this->get_permalink())
{
return 'http://www.technorati.com/search/' . rawurlencode($this->get_permalink());
}
else
{
return false;
}
}
}
/**
* @package sapphire
* @subpackage integration
*/
class SimplePie_Author
{
var $name;
var $link;
var $email;
// Constructor, used to input the data
function SimplePie_Author($name, $link, $email)
{
$this->name = $name;
$this->link = $link;
$this->email = $email;
}
function get_name()
{
if (!empty($this->name))
{
return $this->name;
}
else
{
return false;
}
}
function get_link()
{
if (!empty($this->link))
{
return $this->link;
}
else
{
return false;
}
}
function get_email()
{
if (!empty($this->email))
{
return $this->email;
}
else
{
return false;
}
}
}
/**
* @package sapphire
* @subpackage integration
*/
class SimplePie_Enclosure
{
var $link;
var $type;
var $length;
// Constructor, used to input the data
function SimplePie_Enclosure($link, $type, $length)
{
$this->link = $link;
$this->type = $type;
$this->length = $length;
}
function get_link()
{
if (!empty($this->link))
{
if (class_exists('idna_convert'))
{
$idn = new idna_convert;
$this->link = $idn->encode($this->link);
}
return $this->link;
}
else
{
return false;
}
}
function get_extension()
{
if (!empty($this->link))
{
return pathinfo($this->link, PATHINFO_EXTENSION);
}
else
{
return false;
}
}
function get_type()
{
if (!empty($this->type))
{
return $this->type;
}
else
{
return false;
}
}
function get_length()
{
if (!empty($this->length))
{
return $this->length;
}
else
{
return false;
}
}
function get_size()
{
$length = $this->get_length();
if (!empty($length))
{
return round($length/1048576, 2);
}
else
{
return false;
}
}
function native_embed($options='')
{
return $this->embed($options, true);
}
function embed($options = '', $native = false)
{
// Set up defaults
$audio = '';
$video = '';
$alt = '';
$altclass = '';
$loop = 'false';
$width = 'auto';
$height = 'auto';
$bgcolor = '#ffffff';
// Process options and reassign values as necessary
if (is_array($options))
{
extract($options);
}
else
{
$options = explode(',', $options);
foreach($options as $option)
{
$opt = explode(':', $option, 2);
if (isset($opt[0], $opt[1]))
{
$opt[0] = trim($opt[0]);
$opt[1] = trim($opt[1]);
switch ($opt[0])
{
case 'audio':
$audio = $opt[1];
break;
case 'video':
$video = $opt[1];
break;
case 'alt':
$alt = $opt[1];
break;
case 'altclass':
$altclass = $opt[1];
break;
case 'loop':
$loop = $opt[1];
break;
case 'width':
$width = $opt[1];
break;
case 'height':
$height = $opt[1];
break;
case 'bgcolor':
$bgcolor = $opt[1];
break;
}
}
}
}
$type = strtolower($this->get_type());
// If we encounter an unsupported mime-type, check the file extension and guess intelligently.
if (!in_array($type, array('audio/3gpp', 'audio/3gpp2', 'audio/aac', 'audio/x-aac', 'audio/aiff', 'audio/x-aiff', 'audio/mid', 'audio/midi', 'audio/x-midi', 'audio/mpeg', 'audio/x-mpeg', 'audio/mp3', 'x-audio/mp3', 'audio/mp4', 'audio/m4a', 'audio/x-m4a', 'audio/wav', 'audio/x-wav', 'video/3gpp', 'video/3gpp2', 'video/m4v', 'video/x-m4v', 'video/mp4', 'video/mpeg', 'video/x-mpeg', 'video/quicktime', 'video/sd-video', 'application/x-shockwave-flash', 'application/futuresplash', 'application/asx', 'application/x-mplayer2', 'audio/x-ms-wma', 'audio/x-ms-wax', 'video/x-ms-asf-plugin', 'video/x-ms-asf', 'video/x-ms-wm', 'video/x-ms-wmv', 'video/x-ms-wvx')))
{
switch (strtolower($this->get_extension()))
{
// Audio mime-types
case 'aac':
case 'adts':
$type = 'audio/acc';
break;
case 'aif':
case 'aifc':
case 'aiff':
case 'cdda':
$type = 'audio/aiff';
break;
case 'bwf':
$type = 'audio/wav';
break;
case 'kar':
case 'mid':
case 'midi':
case 'smf':
$type = 'audio/midi';
break;
case 'm4a':
$type = 'audio/x-m4a';
break;
case 'mp3':
case 'swa':
$type = 'audio/mp3';
break;
case 'wav':
$type = 'audio/wav';
break;
case 'wax':
$type = 'audio/x-ms-wax';
break;
case 'wma':
$type = 'audio/x-ms-wma';
break;
// Video mime-types
case '3gp':
case '3gpp':
$type = 'video/3gpp';
break;
case '3g2':
case '3gp2':
$type = 'video/3gpp2';
break;
case 'asf':
$type = 'video/x-ms-asf';
break;
case 'm1a':
case 'm1s':
case 'm1v':
case 'm15':
case 'm75':
case 'mp2':
case 'mpa':
case 'mpeg':
case 'mpg':
case 'mpm':
case 'mpv':
$type = 'video/mpeg';
break;
case 'm4v':
$type = 'video/x-m4v';
break;
case 'mov':
case 'qt':
$type = 'video/quicktime';
break;
case 'mp4':
case 'mpg4':
$type = 'video/mp4';
break;
case 'sdv':
$type = 'video/sd-video';
break;
case 'wm':
$type = 'video/x-ms-wm';
break;
case 'wmv':
$type = 'video/x-ms-wmv';
break;
case 'wvx':
$type = 'video/x-ms-wvx';
break;
// Flash mime-types
case 'spl':
$type = 'application/futuresplash';
break;
case 'swf':
$type = 'application/x-shockwave-flash';
break;
}
}
$mime = explode('/', $type, 2);
$mime = $mime[0];
// Process values for 'auto'
if ($width == 'auto')
{
if ($mime == 'video')
{
$width = '320';
}
else
{
$width = '100%';
}
}
if ($height == 'auto')
{
if ($mime == 'audio')
{
$height = 0;
}
else if ($mime == 'video')
{
$height = 240;
}
else
{
$height = 256;
}
}
// Set proper placeholder value
if ($mime == 'audio')
{
$placeholder = $audio;
}
else if ($mime == 'video')
{
$placeholder = $video;
}
$embed = '';
// Make sure the JS library is included
// (I know it'll be included multiple times, but I can't think of a better way to do this automatically)
if (!$native)
{
$embed .= '<script type="text/javascript" src="?js"></script>';
}
// Odeo Feed MP3's
if (substr(strtolower($this->get_link()), 0, 15) == 'http://odeo.com') {
if ($native)
{
$embed .= '<embed src="http://odeo.com/flash/audio_player_fullsize.swf" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" quality="high" width="440" height="80" wmode="transparent" allowScriptAccess="any" flashvars="valid_sample_rate=true&external_url=' . $this->get_link() . '"></embed>';
}
else
{
$embed .= '<script type="text/javascript">embed_odeo("' . $this->get_link() . '");</script>';
}
}
// QuickTime 7 file types. Need to test with QuickTime 6.
else if (in_array($type, array('audio/3gpp', 'audio/3gpp2', 'audio/aac', 'audio/x-aac', 'audio/aiff', 'audio/x-aiff', 'audio/mid', 'audio/midi', 'audio/x-midi', 'audio/mpeg', 'audio/x-mpeg', 'audio/mp3', 'x-audio/mp3', 'audio/mp4', 'audio/m4a', 'audio/x-m4a', 'audio/wav', 'audio/x-wav', 'video/3gpp', 'video/3gpp2', 'video/m4v', 'video/x-m4v', 'video/mp4', 'video/mpeg', 'video/x-mpeg', 'video/quicktime', 'video/sd-video')))
{
$height += 16;
if ($native)
{
if ($placeholder != "") {
$embed .= "<embed type=\"$type\" style=\"cursor:hand; cursor:pointer;\" href=\"" . $this->get_link() . "\" src=\"$placeholder\" width=\"$width\" height=\"$height\" autoplay=\"false\" target=\"myself\" controller=\"false\" loop=\"$loop\" scale=\"aspect\" bgcolor=\"$bgcolor\" pluginspage=\"http://www.apple.com/quicktime/download/\"></embed>";
}
else {
$embed .= "<embed type=\"$type\" style=\"cursor:hand; cursor:pointer;\" src=\"" . $this->get_link() . "\" width=\"$width+\" height=\"$height\" autoplay=\"false\" target=\"myself\" controller=\"true\" loop=\"$loop\" scale=\"aspect\" bgcolor=\"$bgcolor\" pluginspage=\"http://www.apple.com/quicktime/download/\"></embed>";
}
}
else
{
$embed .= "<script type='text/javascript'>embed_quicktime('$type', '$bgcolor', '$width', '$height', '" . $this->get_link() . "', '$placeholder', '$loop');</script>";
}
}
// Flash
else if (in_array($type, array('application/x-shockwave-flash', 'application/futuresplash')))
{
if ($native)
{
$embed .= "<embed src=\"" . $this->get_link() . "\" pluginspage=\"http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash\" type=\"$type\" quality=\"high\" width=\"$width\" height=\"$height\" bgcolor=\"$bgcolor\" loop=\"$loop\"></embed>";
}
else
{
$embed .= "<script type='text/javascript'>embed_flash('$bgcolor', '$width', '$height', '" . $this->get_link() . "', '$loop', '$type');</script>";
}
}
// Windows Media
else if (in_array($type, array('application/asx', 'application/x-mplayer2', 'audio/x-ms-wma', 'audio/x-ms-wax', 'video/x-ms-asf-plugin', 'video/x-ms-asf', 'video/x-ms-wm', 'video/x-ms-wmv', 'video/x-ms-wvx')))
{
$height += 45;
if ($native)
{
$embed .= "<embed type=\"application/x-mplayer2\" src=\"" . $this->get_link() . "\" autosize=\"1\" width=\"$width\" height=\"$height\" showcontrols=\"1\" showstatusbar=\"0\" showdisplay=\"0\" autostart=\"0\"></embed>";
}
else
{
$embed .= "<script type='text/javascript'>embed_wmedia('$width', '$height', '" . $this->get_link() . "');</script>";
}
}
// Everything else
else $embed .= '<a href="' . $this->get_link() . '" class="' . $altclass . '">' . $alt . '</a>';
return $embed;
}
}
/**
* @package sapphire
* @subpackage integration
*/
class SimplePie_File
{
var $url;
var $useragent;
var $success = true;
var $headers = array();
var $body;
var $fp;
var $redirects = 0;
var $error;
var $method;
function SimplePie_File($url, $timeout = 10, $redirects = 5, $headers = null, $useragent = null, $force_fsockopen = false)
{
if (class_exists('idna_convert'))
{
$idn = new idna_convert;
$url = $idn->encode($url);
}
$this->url = $url;
$this->useragent = $useragent;
if (preg_match('/^http(s)?:\/\//i', $url))
{
if (empty($useragent))
{
$useragent = ini_get('user_agent');
$this->useragent = $useragent;
}
if (!is_array($headers))
{
$headers = array();
}
if (extension_loaded('curl') && version_compare(SimplePie_Misc::get_curl_version(), '7.10.5', '>=') && !$force_fsockopen)
{
$this->method = 'curl';
$fp = curl_init();
$headers2 = array();
foreach ($headers as $key => $value)
{
$headers2[] = "$key: $value";
}
curl_setopt($fp, CURLOPT_ENCODING, '');
curl_setopt($fp, CURLOPT_URL, $url);
curl_setopt($fp, CURLOPT_HEADER, 1);
curl_setopt($fp, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($fp, CURLOPT_TIMEOUT, $timeout);
curl_setopt($fp, CURLOPT_REFERER, $url);
curl_setopt($fp, CURLOPT_USERAGENT, $useragent);
curl_setopt($fp, CURLOPT_HTTPHEADER, $headers2);
if (!ini_get('open_basedir') && !ini_get('safe_mode'))
{
curl_setopt($fp, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($fp, CURLOPT_MAXREDIRS, $redirects);
}
$this->headers = trim(curl_exec($fp));
if (curl_errno($fp) == 23 || curl_errno($fp) == 61)
{
curl_setopt($fp, CURLOPT_ENCODING, 'none');
$this->headers = trim(curl_exec($fp));
}
if (curl_errno($fp))
{
$this->error = 'cURL error ' . curl_errno($fp) . ': ' . curl_error($fp);
$this->success = false;
return false;
}
$info = curl_getinfo($fp);
$this->headers = explode("\r\n\r\n", $this->headers, $info['redirect_count'] + 2);
if (count($this->headers) == $info['redirect_count'] + 1)
{
$this->headers = array_pop($this->headers);
$this->body = '';
}
else
{
$this->body = array_pop($this->headers);
$this->headers = array_pop($this->headers);
}
$this->headers = $this->parse_headers($this->headers);
if (($this->headers['status']['code'] == 301 || $this->headers['status']['code'] == 302 || $this->headers['status']['code'] == 303 || $this->headers['status']['code'] == 307) && !empty($this->headers['location']) && $this->redirects < $redirects)
{
$this->redirects++;
return $this->SimplePie_File($this->headers['location'], $timeout, $redirects, $headers, $useragent, $force_fsockopen);
}
}
else
{
$this->method = 'fsockopen';
$url_parts = parse_url($url);
if (isset($url_parts['scheme']) && strtolower($url_parts['scheme']) == 'https')
{
$url_parts['host'] = "ssl://$url_parts[host]";
$url_parts['port'] = 443;
}
if (!isset($url_parts['port']))
{
$url_parts['port'] = 80;
}
$this->fp = fsockopen($url_parts['host'], $url_parts['port'], $errno, $errstr, $timeout);
if (!$this->fp)
{
$this->error = 'fsockopen error: ' . $errstr;
$this->success = false;
return false;
}
else
{
stream_set_timeout($this->fp, $timeout);
$get = (isset($url_parts['query'])) ? "$url_parts[path]?$url_parts[query]" : $url_parts['path'];
$out = "GET $get HTTP/1.0\r\n";
$out .= "Host: $url_parts[host]\r\n";
$out .= "User-Agent: $useragent\r\n";
if (function_exists('gzinflate'))
{
$out .= "Accept-Encoding: gzip,deflate\r\n";
}
if (!empty($url_parts['user']) && !empty($url_parts['pass']))
{
$out .= "Authorization: Basic " . base64_encode("$url_parts[user]:$url_parts[pass]") . "\r\n";
}
foreach ($headers as $key => $value)
{
$out .= "$key: $value\r\n";
}
$out .= "Connection: Close\r\n\r\n";
fwrite($this->fp, $out);
$info = stream_get_meta_data($this->fp);
$data = '';
while (strpos($data, "\r\n\r\n") === false && !$info['timed_out'])
{
$data .= fgets($this->fp, 128);
$info = stream_get_meta_data($this->fp);
}
if (!$info['timed_out'])
{
$this->headers = $this->parse_headers($data);
if (($this->headers['status']['code'] == 301 || $this->headers['status']['code'] == 302 || $this->headers['status']['code'] == 303 || $this->headers['status']['code'] == 307) && !empty($this->headers['location']) && $this->redirects < $redirects)
{
$this->redirects++;
return $this->SimplePie_File($this->headers['location'], $timeout, $redirects, $headers, $useragent, $force_fsockopen);
}
}
else
{
$this->close();
$this->error = 'fsocket timed out';
$this->success = false;
return false;
}
}
}
return $this->headers['status']['code'];
}
else
{
$this->method = 'fopen';
if ($this->fp = fopen($url, 'r'))
{
return true;
}
else
{
$this->error = 'fopen could not open the file';
$this->success = false;
return false;
}
}
}
function headers()
{
return $this->headers;
}
function body()
{
if (is_null($this->body))
{
if ($this->fp)
{
$info = stream_get_meta_data($this->fp);
$this->body = '';
while (!$info['eof'] && !$info['timed_out'])
{
$this->body .= fread($this->fp, 1024);
$info = stream_get_meta_data($this->fp);
}
if (!$info['timed_out'])
{
$this->body = trim($this->body);
if ($this->method == 'fsockopen' && !empty($this->headers['content-encoding']) && ($this->headers['content-encoding'] == 'gzip' || $this->headers['content-encoding'] == 'deflate'))
{
if (substr($this->body, 0, 8) == "\x1f\x8b\x08\x00\x00\x00\x00\x00")
{
$this->body = substr($this->body, 10);
}
$this->body = gzinflate($this->body);
}
$this->close();
}
else
{
return false;
}
}
else
{
return false;
}
}
return $this->body;
}
function close()
{
if (!is_null($this->fp))
{
if (fclose($this->fp))
{
$this->fp = null;
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
function parse_headers($headers)
{
$headers = explode("\r\n", trim($headers));
$status = array_shift($headers);
foreach ($headers as $header)
{
$data = explode(':', $header, 2);
$head[strtolower(trim($data[0]))] = trim($data[1]);
}
if (preg_match('/HTTP\/[0-9\.]+ ([0-9]+)(.*)$/i', $status, $matches))
{
if (isset($head['status']))
{
unset($head['status']);
}
$head['status']['code'] = $matches[1];
$head['status']['name'] = trim($matches[2]);
}
return $head;
}
}
/**
* @package sapphire
* @subpackage integration
*/
class SimplePie_Cache
{
var $location;
var $filename;
var $extension;
var $name;
function SimplePie_Cache($location, $filename, $extension)
{
$this->location = $location;
$this->filename = rawurlencode($filename);
$this->extension = rawurlencode($extension);
$this->name = "$location/$this->filename.$this->extension";
}
function save($data)
{
if (file_exists($this->name) && is_writeable($this->name) || file_exists($this->location) && is_writeable($this->location))
{
$fp = fopen($this->name, 'w');
if ($fp)
{
fwrite($fp, serialize($data));
fclose($fp);
return true;
}
}
return false;
}
function load()
{
if (file_exists($this->name) && is_readable($this->name))
{
return unserialize(file_get_contents($this->name));
}
return false;
}
function mtime()
{
if (file_exists($this->name))
{
return filemtime($this->name);
}
return false;
}
function touch()
{
if (file_exists($this->name))
{
return touch($this->name);
}
return false;
}
function unlink()
{
if (file_exists($this->name))
{
return unlink($this->name);
}
return false;
}
}
/**
* @package sapphire
* @subpackage integration
*/
class SimplePie_Misc
{
function absolutize_url($relative, $base)
{
$relative = trim($relative);
$base = trim($base);
if (!empty($relative))
{
$relative = SimplePie_Misc::parse_url($relative, false);
$relative = array('scheme' => $relative[2], 'authority' => $relative[3], 'path' => $relative[5], 'query' => $relative[7], 'fragment' => $relative[9]);
if (!empty($relative['scheme']))
{
$target = $relative;
}
else if (!empty($base))
{
$base = SimplePie_Misc::parse_url($base, false);
$base = array('scheme' => $base[2], 'authority' => $base[3], 'path' => $base[5], 'query' => $base[7], 'fragment' => $base[9]);
$target['scheme'] = $base['scheme'];
if (!empty($relative['authority']))
{
$target = array_merge($relative, $target);
}
else
{
$target['authority'] = $base['authority'];
if (!empty($relative['path']))
{
if (strpos($relative['path'], '/') === 0)
{
$target['path'] = $relative['path'];
}
else
{
if (!empty($base['path']))
{
$target['path'] = dirname("$base[path].") . '/' . $relative['path'];
}
else
{
$target['path'] = '/' . $relative['path'];
}
}
if (!empty($relative['query']))
{
$target['query'] = $relative['query'];
}
$input = $target['path'];
$target['path'] = '';
while (!empty($input))
{
if (strpos($input, '../') === 0)
{
$input = substr($input, 3);
}
else if (strpos($input, './') === 0)
{
$input = substr($input, 2);
}
else if (strpos($input, '/./') === 0)
{
$input = substr_replace($input, '/', 0, 3);
}
else if (strpos($input, '/.') === 0 && SimplePie_Misc::strendpos($input, '/.') === 0)
{
$input = substr_replace($input, '/', -2);
}
else if (strpos($input, '/../') === 0)
{
$input = substr_replace($input, '/', 0, 4);
$target['path'] = preg_replace('/(\/)?([^\/]+)$/msiU', '', $target['path']);
}
else if (strpos($input, '/..') === 0 && SimplePie_Misc::strendpos($input, '/..') === 0)
{
$input = substr_replace($input, '/', 0, 3);
$target['path'] = preg_replace('/(\/)?([^\/]+)$/msiU', '', $target['path']);
}
else if ($input == '.' || $input == '..')
{
$input = '';
}
else
{
if (preg_match('/^(.+)(\/|$)/msiU', $input, $match))
{
$target['path'] .= $match[1];
$input = substr_replace($input, '', 0, strlen($match[1]));
}
}
}
}
else
{
if (!empty($base['path']))
{
$target['path'] = $base['path'];
}
else
{
$target['path'] = '/';
}
if (!empty($relative['query']))
{
$target['query'] = $relative['query'];
}
else if (!empty($base['query']))
{
$target['query'] = $base['query'];
}
}
}
if (!empty($relative['fragment']))
{
$target['fragment'] = $relative['fragment'];
}
}
else
{
return false;
}
$return = '';
if (!empty($target['scheme']))
{
$return .= "$target[scheme]:";
}
if (!empty($target['authority']))
{
$return .= $target['authority'];
}
if (!empty($target['path']))
{
$return .= $target['path'];
}
if (!empty($target['query']))
{
$return .= "?$target[query]";
}
if (!empty($target['fragment']))
{
$return .= "#$target[fragment]";
}
}
else
{
$return = $base;
}
return $return;
}
function strendpos($haystack, $needle)
{
return strlen($haystack) - strpos($haystack, $needle) - strlen($needle);
}
function get_element($realname, $string)
{
$return = array();
$name = preg_quote($realname, '/');
preg_match_all("/<($name)((\s*((\w+:)?\w+)\s*=\s*(\"([^\"]*)\"|'([^']*)'|(.*)))*)\s*((\/)?>|>(.*)<\/$name>)/msiU", $string, $matches, PREG_SET_ORDER);
for ($i = 0; $i < count($matches); $i++)
{
$return[$i]['tag'] = $realname;
$return[$i]['full'] = $matches[$i][0];
if (strlen($matches[$i][10]) <= 2)
{
$return[$i]['self_closing'] = true;
}
else
{
$return[$i]['self_closing'] = false;
$return[$i]['content'] = $matches[$i][12];
}
$return[$i]['attribs'] = array();
if (!empty($matches[$i][2]))
{
preg_match_all('/((\w+:)?\w+)\s*=\s*("([^"]*)"|\'([^\']*)\'|(\S+))\s/msiU', ' ' . $matches[$i][2] . ' ', $attribs, PREG_SET_ORDER);
for ($j = 0; $j < count($attribs); $j++)
{
$return[$i]['attribs'][strtoupper($attribs[$j][1])]['data'] = $attribs[$j][count($attribs[$j])-1];
$first = substr($attribs[$j][2], 0, 1);
$return[$i]['attribs'][strtoupper($attribs[$j][1])]['split'] = ($first == '"' || $first == "'") ? $first : '"';
}
}
}
return $return;
}
function element_implode($element)
{
$full = "<$element[tag]";
foreach ($element['attribs'] as $key => $value)
{
$key = strtolower($key);
$full .= " $key=$value[split]$value[data]$value[split]";
}
if ($element['self_closing'])
{
$full .= ' />';
}
else
{
$full .= ">$element[content]</$element[tag]>";
}
return $full;
}
function error($message, $level, $file, $line)
{
switch ($level)
{
case E_USER_ERROR:
$note = 'PHP Error';
break;
case E_USER_WARNING:
$note = 'PHP Warning';
break;
case E_USER_NOTICE:
$note = 'PHP Notice';
break;
default:
$note = 'Unknown Error';
break;
}
error_log("$note: $message in $file on line $line", 0);
return $message;
}
function display_file($url, $timeout = 10, $useragent = null)
{
$file = new SimplePie_File($url, $timeout, 5, array('X-FORWARDED-FOR' => $_SERVER['REMOTE_ADDR']), $useragent);
$headers = $file->headers();
if ($file->body() !== false)
{
header('Content-type: ' . $headers['content-type']);
echo $file->body();
exit;
}
}
function fix_protocol($url, $http = 1)
{
$parsed = SimplePie_Misc::parse_url($url);
if (!empty($parsed['scheme']) && strtolower($parsed['scheme']) != 'http' && strtolower($parsed['scheme']) != 'https')
{
return SimplePie_Misc::fix_protocol("$parsed[authority]$parsed[path]$parsed[query]$parsed[fragment]", $http);
}
if (!file_exists($url) && empty($parsed['scheme']))
{
return SimplePie_Misc::fix_protocol("http://$url", $http);
}
if ($http == 2 && !empty($parsed['scheme']))
{
return "feed:$url";
}
else if ($http == 3 && strtolower($parsed['scheme']) == 'http')
{
return substr_replace($url, 'podcast', 0, 4);
}
else
{
return $url;
}
}
function parse_url($url, $parse_match = true)
{
preg_match('/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/i', $url, $match);
if (empty($match[0]))
{
return false;
}
else
{
for ($i = 6; $i < 10; $i++)
{
if (!isset($match[$i]))
{
$match[$i] = '';
}
}
if ($parse_match)
{
$match = array('scheme' => $match[2], 'authority' => $match[4], 'path' => $match[5], 'query' => $match[6], 'fragment' => $match[8]);
}
return $match;
}
}
function change_encoding($data, $input, $output)
{
$input = SimplePie_Misc::encoding($input);
$output = SimplePie_Misc::encoding($output);
if ($input != $output)
{
if (function_exists('iconv') && $input['use_iconv'] && $output['use_iconv'] && iconv($input['encoding'], "$output[encoding]//TRANSLIT", $data))
{
return iconv($input['encoding'], "$output[encoding]//TRANSLIT", $data);
}
else if (function_exists('iconv') && $input['use_iconv'] && $output['use_iconv'] && iconv($input['encoding'], $output['encoding'], $data))
{
return iconv($input['encoding'], $output['encoding'], $data);
}
else if (function_exists('mb_convert_encoding') && $input['use_mbstring'] && $output['use_mbstring'])
{
return mb_convert_encoding($data, $output['encoding'], $input['encoding']);
}
else if ($input['encoding'] == 'ISO-8859-1' && $output['encoding'] == 'UTF-8')
{
return utf8_encode($data);
}
else if ($input['encoding'] == 'UTF-8' && $output['encoding'] == 'ISO-8859-1')
{
return utf8_decode($data);
}
}
return $data;
}
function encoding($encoding)
{
$return['use_mbstring'] = false;
$return['use_iconv'] = false;
switch (strtolower($encoding))
{
// 7bit
case '7bit':
case '7-bit':
$return['encoding'] = '7bit';
$return['use_mbstring'] = true;
break;
// 8bit
case '8bit':
case '8-bit':
$return['encoding'] = '8bit';
$return['use_mbstring'] = true;
break;
// ARMSCII-8
case 'armscii-8':
case 'armscii':
$return['encoding'] = 'ARMSCII-8';
$return['use_iconv'] = true;
break;
// ASCII
case 'us-ascii':
case 'ascii':
$return['encoding'] = 'US-ASCII';
$return['use_iconv'] = true;
$return['use_mbstring'] = true;
break;
// BASE64
case 'base64':
case 'base-64':
$return['encoding'] = 'BASE64';
$return['use_mbstring'] = true;
break;
// Big5 - Traditional Chinese, mainly used in Taiwan
case 'big5':
case '950':
$return['encoding'] = 'BIG5';
$return['use_iconv'] = true;
$return['use_mbstring'] = true;
break;
// Big5 with Hong Kong extensions, Traditional Chinese
case 'big5-hkscs':
$return['encoding'] = 'BIG5-HKSCS';
$return['use_iconv'] = true;
$return['use_mbstring'] = true;
break;
// byte2be
case 'byte2be':
$return['encoding'] = 'byte2be';
$return['use_mbstring'] = true;
break;
// byte2le
case 'byte2le':
$return['encoding'] = 'byte2le';
$return['use_mbstring'] = true;
break;
// byte4be
case 'byte4be':
$return['encoding'] = 'byte4be';
$return['use_mbstring'] = true;
break;
// byte4le
case 'byte4le':
$return['encoding'] = 'byte4le';
$return['use_mbstring'] = true;
break;
// EUC-CN
case 'euc-cn':
case 'euccn':
$return['encoding'] = 'EUC-CN';
$return['use_iconv'] = true;
$return['use_mbstring'] = true;
break;
// EUC-JISX0213
case 'euc-jisx0213':
case 'eucjisx0213':
$return['encoding'] = 'EUC-JISX0213';
$return['use_iconv'] = true;
break;
// EUC-JP
case 'euc-jp':
case 'eucjp':
$return['encoding'] = 'EUC-JP';
$return['use_iconv'] = true;
$return['use_mbstring'] = true;
break;
// EUCJP-win
case 'euc-jp-win':
case 'eucjp-win':
case 'eucjpwin':
$return['encoding'] = 'EUCJP-win';
$return['use_iconv'] = true;
$return['use_mbstring'] = true;
break;
// EUC-KR
case 'euc-kr':
case 'euckr':
$return['encoding'] = 'EUC-KR';
$return['use_iconv'] = true;
$return['use_mbstring'] = true;
break;
// EUC-TW
case 'euc-tw':
case 'euctw':
$return['encoding'] = 'EUC-TW';
$return['use_iconv'] = true;
$return['use_mbstring'] = true;
break;
// GB18030 - Simplified Chinese, national standard character set
case 'gb18030-2000':
case 'gb18030':
$return['encoding'] = 'GB18030';
$return['use_iconv'] = true;
break;
// GB2312 - Simplified Chinese, national standard character set
case 'gb2312':
case '936':
$return['encoding'] = 'GB2312';
$return['use_mbstring'] = true;
break;
// GBK
case 'gbk':
$return['encoding'] = 'GBK';
$return['use_iconv'] = true;
break;
// Georgian-Academy
case 'georgian-academy':
$return['encoding'] = 'Georgian-Academy';
$return['use_iconv'] = true;
break;
// Georgian-PS
case 'georgian-ps':
$return['encoding'] = 'Georgian-PS';
$return['use_iconv'] = true;
break;
// HTML-ENTITIES
case 'html-entities':
case 'htmlentities':
$return['encoding'] = 'HTML-ENTITIES';
$return['use_mbstring'] = true;
break;
// HZ
case 'hz':
$return['encoding'] = 'HZ';
$return['use_iconv'] = true;
$return['use_mbstring'] = true;
break;
// ISO-2022-CN
case 'iso-2022-cn':
case 'iso2022-cn':
case 'iso2022cn':
$return['encoding'] = 'ISO-2022-CN';
$return['use_iconv'] = true;
break;
// ISO-2022-CN-EXT
case 'iso-2022-cn-ext':
case 'iso2022-cn-ext':
case 'iso2022cn-ext':
case 'iso2022cnext':
$return['encoding'] = 'ISO-2022-CN';
$return['use_iconv'] = true;
break;
// ISO-2022-JP
case 'iso-2022-jp':
case 'iso2022-jp':
case 'iso2022jp':
$return['encoding'] = 'ISO-2022-JP';
$return['use_iconv'] = true;
$return['use_mbstring'] = true;
break;
// ISO-2022-JP-1
case 'iso-2022-jp-1':
case 'iso2022-jp-1':
case 'iso2022jp-1':
case 'iso2022jp1':
$return['encoding'] = 'ISO-2022-JP-1';
$return['use_iconv'] = true;
break;
// ISO-2022-JP-2
case 'iso-2022-jp-2':
case 'iso2022-jp-2':
case 'iso2022jp-2':
case 'iso2022jp2':
$return['encoding'] = 'ISO-2022-JP-2';
$return['use_iconv'] = true;
break;
// ISO-2022-JP-3
case 'iso-2022-jp-3':
case 'iso2022-jp-3':
case 'iso2022jp-3':
case 'iso2022jp3':
$return['encoding'] = 'ISO-2022-JP-3';
$return['use_iconv'] = true;
break;
// ISO-2022-KR
case 'iso-2022-kr':
case 'iso2022-kr':
case 'iso2022kr':
$return['encoding'] = 'ISO-2022-KR';
$return['use_iconv'] = true;
$return['use_mbstring'] = true;
break;
// ISO-8859-1
case 'iso-8859-1':
case 'iso8859-1':
$return['encoding'] = 'ISO-8859-1';
$return['use_iconv'] = true;
$return['use_mbstring'] = true;
break;
// ISO-8859-2
case 'iso-8859-2':
case 'iso8859-2':
$return['encoding'] = 'ISO-8859-2';
$return['use_iconv'] = true;
$return['use_mbstring'] = true;
break;
// ISO-8859-3
case 'iso-8859-3':
case 'iso8859-3':
$return['encoding'] = 'ISO-8859-3';
$return['use_iconv'] = true;
$return['use_mbstring'] = true;
break;
// ISO-8859-4
case 'iso-8859-4':
case 'iso8859-4':
$return['encoding'] = 'ISO-8859-4';
$return['use_iconv'] = true;
$return['use_mbstring'] = true;
break;
// ISO-8859-5
case 'iso-8859-5':
case 'iso8859-5':
$return['encoding'] = 'ISO-8859-5';
$return['use_iconv'] = true;
$return['use_mbstring'] = true;
break;
// ISO-8859-6
case 'iso-8859-6':
case 'iso8859-6':
$return['encoding'] = 'ISO-8859-6';
$return['use_iconv'] = true;
$return['use_mbstring'] = true;
break;
// ISO-8859-7
case 'iso-8859-7':
case 'iso8859-7':
$return['encoding'] = 'ISO-8859-7';
$return['use_iconv'] = true;
$return['use_mbstring'] = true;
break;
// ISO-8859-8
case 'iso-8859-8':
case 'iso8859-8':
$return['encoding'] = 'ISO-8859-8';
$return['use_iconv'] = true;
$return['use_mbstring'] = true;
break;
// ISO-8859-9
case 'iso-8859-9':
case 'iso8859-9':
$return['encoding'] = 'ISO-8859-9';
$return['use_iconv'] = true;
$return['use_mbstring'] = true;
break;
// ISO-8859-10
case 'iso-8859-10':
case 'iso8859-10':
$return['encoding'] = 'ISO-8859-10';
$return['use_iconv'] = true;
$return['use_mbstring'] = true;
break;
// mbstring/iconv functions don't appear to support 11 & 12
// ISO-8859-13
case 'iso-8859-13':
case 'iso8859-13':
$return['encoding'] = 'ISO-8859-13';
$return['use_iconv'] = true;
$return['use_mbstring'] = true;
break;
// ISO-8859-14
case 'iso-8859-14':
case 'iso8859-14':
$return['encoding'] = 'ISO-8859-14';
$return['use_iconv'] = true;
$return['use_mbstring'] = true;
break;
// ISO-8859-15
case 'iso-8859-15':
case 'iso8859-15':
$return['encoding'] = 'ISO-8859-15';
$return['use_iconv'] = true;
$return['use_mbstring'] = true;
break;
// ISO-8859-16
case 'iso-8859-16':
case 'iso8859-16':
$return['encoding'] = 'ISO-8859-16';
$return['use_iconv'] = true;
break;
// JIS
case 'jis':
$return['encoding'] = 'JIS';
$return['use_mbstring'] = true;
break;
// JOHAB - Korean
case 'johab':
$return['encoding'] = 'JOHAB';
$return['use_iconv'] = true;
break;
// Russian
case 'koi8-r':
case 'koi8r':
$return['encoding'] = 'KOI8-R';
$return['use_iconv'] = true;
$return['use_mbstring'] = true;
break;
// Turkish
case 'koi8-t':
case 'koi8t':
$return['encoding'] = 'KOI8-T';
$return['use_iconv'] = true;
break;
// Ukrainian
case 'koi8-u':
case 'koi8u':
$return['encoding'] = 'KOI8-U';
$return['use_iconv'] = true;
break;
// Russian+Ukrainian
case 'koi8-ru':
case 'koi8ru':
$return['encoding'] = 'KOI8-RU';
$return['use_iconv'] = true;
break;
// Macintosh (Mac OS Classic)
case 'macintosh':
$return['encoding'] = 'Macintosh';
$return['use_iconv'] = true;
break;
// MacArabic (Mac OS Classic)
case 'macarabic':
$return['encoding'] = 'MacArabic';
$return['use_iconv'] = true;
break;
// MacCentralEurope (Mac OS Classic)
case 'maccentraleurope':
$return['encoding'] = 'MacCentralEurope';
$return['use_iconv'] = true;
break;
// MacCroatian (Mac OS Classic)
case 'maccroatian':
$return['encoding'] = 'MacCroatian';
$return['use_iconv'] = true;
break;
// MacCyrillic (Mac OS Classic)
case 'maccyrillic':
$return['encoding'] = 'MacCyrillic';
$return['use_iconv'] = true;
break;
// MacGreek (Mac OS Classic)
case 'macgreek':
$return['encoding'] = 'MacGreek';
$return['use_iconv'] = true;
break;
// MacHebrew (Mac OS Classic)
case 'machebrew':
$return['encoding'] = 'MacHebrew';
$return['use_iconv'] = true;
break;
// MacIceland (Mac OS Classic)
case 'maciceland':
$return['encoding'] = 'MacIceland';
$return['use_iconv'] = true;
break;
// MacRoman (Mac OS Classic)
case 'macroman':
$return['encoding'] = 'MacRoman';
$return['use_iconv'] = true;
break;
// MacRomania (Mac OS Classic)
case 'macromania':
$return['encoding'] = 'MacRomania';
$return['use_iconv'] = true;
break;
// MacThai (Mac OS Classic)
case 'macthai':
$return['encoding'] = 'MacThai';
$return['use_iconv'] = true;
break;
// MacTurkish (Mac OS Classic)
case 'macturkish':
$return['encoding'] = 'MacTurkish';
$return['use_iconv'] = true;
break;
// MacUkraine (Mac OS Classic)
case 'macukraine':
$return['encoding'] = 'MacUkraine';
$return['use_iconv'] = true;
break;
// MuleLao-1
case 'mulelao-1':
case 'mulelao1':
$return['encoding'] = 'MuleLao-1';
$return['use_iconv'] = true;
break;
// Shift_JIS
case 'shift_jis':
case 'sjis':
case '932':
$return['encoding'] = 'Shift_JIS';
$return['use_iconv'] = true;
$return['use_mbstring'] = true;
break;
// Shift_JISX0213
case 'shift-jisx0213':
case 'shiftjisx0213':
$return['encoding'] = 'Shift_JISX0213';
$return['use_iconv'] = true;
break;
// SJIS-win
case 'sjis-win':
case 'sjiswin':
case 'shift_jis-win':
$return['encoding'] = 'SJIS-win';
$return['use_iconv'] = true;
$return['use_mbstring'] = true;
break;
// TCVN - Vietnamese
case 'tcvn':
$return['encoding'] = 'TCVN';
$return['use_iconv'] = true;
break;
// TDS565 - Turkish
case 'tds565':
$return['encoding'] = 'TDS565';
$return['use_iconv'] = true;
break;
// TIS-620 Thai
case 'tis-620':
case 'tis620':
$return['encoding'] = 'TIS-620';
$return['use_iconv'] = true;
$return['use_mbstring'] = true;
break;
// UCS-2
case 'ucs-2':
case 'ucs2':
case 'utf-16':
case 'utf16':
$return['encoding'] = 'UCS-2';
$return['use_iconv'] = true;
$return['use_mbstring'] = true;
break;
// UCS-2BE
case 'ucs-2be':
case 'ucs2be':
case 'utf-16be':
case 'utf16be':
$return['encoding'] = 'UCS-2BE';
$return['use_iconv'] = true;
$return['use_mbstring'] = true;
break;
// UCS-2LE
case 'ucs-2le':
case 'ucs2le':
case 'utf-16le':
case 'utf16le':
$return['encoding'] = 'UCS-2LE';
$return['use_iconv'] = true;
$return['use_mbstring'] = true;
break;
// UCS-2-INTERNAL
case 'ucs-2-internal':
case 'ucs2internal':
$return['encoding'] = 'UCS-2-INTERNAL';
$return['use_iconv'] = true;
break;
// UCS-4
case 'ucs-4':
case 'ucs4':
case 'utf-32':
case 'utf32':
$return['encoding'] = 'UCS-4';
$return['use_iconv'] = true;
$return['use_mbstring'] = true;
break;
// UCS-4BE
case 'ucs-4be':
case 'ucs4be':
case 'utf-32be':
case 'utf32be':
$return['encoding'] = 'UCS-4BE';
$return['use_iconv'] = true;
$return['use_mbstring'] = true;
break;
// UCS-4LE
case 'ucs-4le':
case 'ucs4le':
case 'utf-32le':
case 'utf32le':
$return['encoding'] = 'UCS-4LE';
$return['use_iconv'] = true;
$return['use_mbstring'] = true;
break;
// UCS-4-INTERNAL
case 'ucs-4-internal':
case 'ucs4internal':
$return['encoding'] = 'UCS-4-INTERNAL';
$return['use_iconv'] = true;
break;
// UCS-16
case 'ucs-16':
case 'ucs16':
$return['encoding'] = 'UCS-16';
$return['use_iconv'] = true;
$return['use_mbstring'] = true;
break;
// UCS-16BE
case 'ucs-16be':
case 'ucs16be':
$return['encoding'] = 'UCS-16BE';
$return['use_iconv'] = true;
$return['use_mbstring'] = true;
break;
// UCS-16LE
case 'ucs-16le':
case 'ucs16le':
$return['encoding'] = 'UCS-16LE';
$return['use_iconv'] = true;
$return['use_mbstring'] = true;
break;
// UCS-32
case 'ucs-32':
case 'ucs32':
$return['encoding'] = 'UCS-32';
$return['use_iconv'] = true;
$return['use_mbstring'] = true;
break;
// UCS-32BE
case 'ucs-32be':
case 'ucs32be':
$return['encoding'] = 'UCS-32BE';
$return['use_iconv'] = true;
$return['use_mbstring'] = true;
break;
// UCS-32LE
case 'ucs-32le':
case 'ucs32le':
$return['encoding'] = 'UCS-32LE';
$return['use_iconv'] = true;
$return['use_mbstring'] = true;
break;
// UTF-7
case 'utf-7':
case 'utf7':
$return['encoding'] = 'UTF-7';
$return['use_iconv'] = true;
$return['use_mbstring'] = true;
break;
// UTF7-IMAP
case 'utf-7-imap':
case 'utf7-imap':
case 'utf7imap':
$return['encoding'] = 'UTF7-IMAP';
$return['use_mbstring'] = true;
break;
// VISCII - Vietnamese ASCII
case 'viscii':
$return['encoding'] = 'VISCII';
$return['use_iconv'] = true;
break;
// Windows-specific Central & Eastern Europe
case 'cp1250':
case 'windows-1250':
case 'win-1250':
case '1250':
$return['encoding'] = 'Windows-1250';
$return['use_iconv'] = true;
break;
// Windows-specific Cyrillic
case 'cp1251':
case 'windows-1251':
case 'win-1251':
case '1251':
$return['encoding'] = 'Windows-1251';
$return['use_iconv'] = true;
$return['use_mbstring'] = true;
break;
// Windows-specific Western Europe
case 'cp1252':
case 'windows-1252':
case '1252':
$return['encoding'] = 'Windows-1252';
$return['use_iconv'] = true;
$return['use_mbstring'] = true;
break;
// Windows-specific Greek
case 'cp1253':
case 'windows-1253':
case '1253':
$return['encoding'] = 'Windows-1253';
$return['use_iconv'] = true;
break;
// Windows-specific Turkish
case 'cp1254':
case 'windows-1254':
case '1254':
$return['encoding'] = 'Windows-1254';
$return['use_iconv'] = true;
break;
// Windows-specific Hebrew
case 'cp1255':
case 'windows-1255':
case '1255':
$return['encoding'] = 'Windows-1255';
$return['use_iconv'] = true;
break;
// Windows-specific Arabic
case 'cp1256':
case 'windows-1256':
case '1256':
$return['encoding'] = 'Windows-1256';
$return['use_iconv'] = true;
break;
// Windows-specific Baltic
case 'cp1257':
case 'windows-1257':
case '1257':
$return['encoding'] = 'Windows-1257';
$return['use_iconv'] = true;
break;
// Windows-specific Vietnamese
case 'cp1258':
case 'windows-1258':
case '1258':
$return['encoding'] = 'Windows-1258';
$return['use_iconv'] = true;
break;
// Default to UTF-8
default:
$return['encoding'] = 'UTF-8';
$return['use_iconv'] = true;
$return['use_mbstring'] = true;
break;
}
// Then, return it.
return $return;
}
function get_curl_version()
{
$curl = 0;
if (is_array(curl_version()))
{
$curl = curl_version();
$curl = $curl['version'];
}
else
{
$curl = curl_version();
$curl = explode(' ', $curl);
$curl = explode('/', $curl[0]);
$curl = $curl[1];
}
return $curl;
}
function is_a_class($class1, $class2)
{
if (class_exists($class1))
{
$classes = array(strtolower($class1));
while ($class1 = get_parent_class($class1))
{
$classes[] = strtolower($class1);
}
return in_array(strtolower($class2), $classes);
}
else
{
return false;
}
}
}
/**
* @package sapphire
* @subpackage integration
*/
class SimplePie_Locator
{
var $useragent;
var $timeout;
var $file;
var $local;
var $elsewhere;
var $file_class = 'SimplePie_File';
function SimplePie_Locator(&$file, $timeout = 10, $useragent = null, $file_class = 'SimplePie_File')
{
if (!is_a($file, 'SimplePie_File'))
{
$this->file = new $this->file_class($file, $timeout, $useragent);
}
else
{
$this->file =& $file;
}
$this->file_class = $file_class;
$this->useragent = $useragent;
$this->timeout = $timeout;
}
function find()
{
if ($this->is_feed($this->file))
{
return $this->file->url;
}
$autodiscovery = $this->autodiscovery($this->file);
if ($autodiscovery)
{
return $autodiscovery;
}
if ($this->get_links($this->file))
{
if (!empty($this->local))
{
$extension_local = $this->extension($this->local);
if ($extension_local)
{
return $extension_local;
}
$body_local = $this->body($this->local);
if ($body_local)
{
return $body_local;
}
}
if (!empty($this->elsewhere))
{
$extension_elsewhere = $this->extension($this->elsewhere);
if ($extension_elsewhere)
{
return $extension_elsewhere;
}
$body_elsewhere = $this->body($this->elsewhere);
if ($body_elsewhere)
{
return $body_elsewhere;
}
}
}
return false;
}
function is_feed(&$file)
{
if (!is_a($file, 'SimplePie_File'))
{
if (isset($this))
{
$file2 = new $this->file_class($file, $this->timeout, 5, null, $this->useragent);
}
else
{
$file2 = new $this->file_class($file);
}
$file2->body();
$file2->close();
}
else
{
$file2 =& $file;
}
$body = preg_replace('/<\!-(.*)-\>/msiU', '', $file2->body());
if (preg_match('/<(\w+\:)?rss/msiU', $body) || preg_match('/<(\w+\:)?RDF/mi', $body) || preg_match('/<(\w+\:)?feed/mi', $body))
{
return true;
}
return false;
}
function autodiscovery(&$file)
{
$links = SimplePie_Misc::get_element('link', $file->body());
$done = array();
foreach ($links as $link)
{
if (!empty($link['attribs']['TYPE']['data']) && !empty($link['attribs']['HREF']['data']) && !empty($link['attribs']['REL']['data']))
{
$rel = preg_split('/\s+/', strtolower(trim($link['attribs']['REL']['data'])));
$type = preg_match('/^(application\/rss\+xml|application\/atom\+xml|application\/rdf\+xml|application\/xml\+rss|application\/xml\+atom|application\/xml\+rdf|application\/xml|application\/x\.atom\+xml|text\/xml)(;|$)/msiU', trim($link['attribs']['TYPE']['data']));
$href = SimplePie_Misc::absolutize_url(trim($link['attribs']['HREF']['data']), $this->file->url);
if (!in_array($href, $done) && in_array('alternate', $rel) && $type)
{
$feed = $this->is_feed($href);
if ($feed)
{
return $href;
}
}
$done[] = $href;
}
}
return false;
}
function get_links(&$file)
{
$links = SimplePie_Misc::get_element('a', $file->body());
foreach ($links as $link)
{
if (!empty($link['attribs']['HREF']['data']))
{
$href = trim($link['attribs']['HREF']['data']);
$parsed = SimplePie_Misc::parse_url($href);
if (empty($parsed['scheme']) || $parsed['scheme'] != 'javascript')
{
$current = SimplePie_Misc::parse_url($this->file->url);
if (empty($parsed['authority']) || $parsed['authority'] == $current['authority'])
{
$this->local[] = SimplePie_Misc::absolutize_url($href, $this->file->url);
}
else
{
$this->elsewhere[] = SimplePie_Misc::absolutize_url($href, $this->file->url);
}
}
}
}
if (!empty($this->local))
{
$this->local = array_unique($this->local);
}
if (!empty($this->elsewhere))
{
$this->elsewhere = array_unique($this->elsewhere);
}
if (!empty($this->local) || !empty($this->elsewhere))
{
return true;
}
return false;
}
function extension(&$array)
{
foreach ($array as $key => $value)
{
$value = SimplePie_Misc::absolutize_url($value, $this->file->url);
if (in_array(strrchr($value, '.'), array('.rss', '.rdf', '.atom', '.xml')))
{
if ($this->is_feed($value))
{
return $value;
}
else
{
unset($array[$key]);
}
}
}
return false;
}
function body(&$array)
{
foreach ($array as $key => $value)
{
$value = SimplePie_Misc::absolutize_url($value, $this->file->url);
if (preg_match('/(rss|rdf|atom|xml)/i', $value))
{
if ($this->is_feed($value))
{
return $value;
}
else
{
unset($array[$key]);
}
}
}
return false;
}
}
/**
* @package sapphire
* @subpackage integration
*/
class SimplePie_Parser
{
var $encoding;
var $data;
var $namespaces = array('xml' => 'HTTP://WWW.W3.ORG/XML/1998/NAMESPACE', 'atom' => 'ATOM', 'rss2' => 'RSS', 'rdf' => 'RDF', 'rss1' => 'RSS', 'dc' => 'DC', 'xhtml' => 'XHTML', 'content' => 'CONTENT');
var $xml;
var $error_code;
var $error_string;
var $current_line;
var $current_column;
var $current_byte;
var $tag_name;
var $inside_item;
var $item_number = 0;
var $inside_channel;
var $author_number= 0;
var $category_number = 0;
var $enclosure_number = 0;
var $link_number = 0;
var $item_link_number = 0;
var $inside_image;
var $attribs;
var $is_first;
var $inside_author;
function SimplePie_Parser($data, $encoding, $return_xml = false)
{
$this->encoding = $encoding;
// Strip BOM:
// UTF-32 Big Endian BOM
if (strpos($data, sprintf('%c%c%c%c', 0x00, 0x00, 0xFE, 0xFF)) === 0)
{
$data = substr($data, 4);
}
// UTF-32 Little Endian BOM
else if (strpos($data, sprintf('%c%c%c%c', 0xFF, 0xFE, 0x00, 0x00)) === 0)
{
$data = substr($data, 4);
}
// UTF-16 Big Endian BOM
else if (strpos($data, sprintf('%c%c', 0xFE, 0xFF)) === 0)
{
$data = substr($data, 2);
}
// UTF-16 Little Endian BOM
else if (strpos($data, sprintf('%c%c', 0xFF, 0xFE)) === 0)
{
$data = substr($data, 2);
}
// UTF-8 BOM
else if (strpos($data, sprintf('%c%c%c', 0xEF, 0xBB, 0xBF)) === 0)
{
$data = substr($data, 3);
}
// Make sure the XML prolog is sane and has the correct encoding
if (preg_match('/^<\?xml(.*)?>/msiU', $data, $prolog))
{
$data = substr_replace($data, '', 0, strlen($prolog[0]));
}
$data = "<?xml version='1.0' encoding='$encoding'?>\n" . $data;
// Put some data into CDATA blocks
// If we're RSS
if ((stristr($data, '<rss') || preg_match('/<([a-z0-9]+\:)?RDF/mi', $data)) && (preg_match('/<([a-z0-9]+\:)?channel/mi', $data) || preg_match('/<([a-z0-9]+\:)?item/mi', $data)))
{
$sp_elements = array(
'author',
'category',
'copyright',
'description',
'docs',
'generator',
'guid',
'language',
'lastBuildDate',
'link',
'managingEditor',
'pubDate',
'title',
'url',
'webMaster',
);
}
// Or if we're Atom
else
{
$sp_elements = array(
'content',
'copyright',
'name',
'subtitle',
'summary',
'tagline',
'title',
);
}
foreach ($sp_elements as $full)
{
$data = preg_replace_callback("/<($full)((\s*((\w+:)?\w+)\s*=\s*(\"([^\"]*)\"|'([^']*)'))*)\s*(\/>|>(.*)<\/$full>)/msiU", array(&$this, 'add_cdata'), $data);
}
foreach ($sp_elements as $full)
{
// Deal with CDATA within CDATA (this can be caused by us inserting CDATA above)
$data = preg_replace_callback("/<($full)((\s*((\w+:)?\w+)\s*=\s*(\"([^\"]*)\"|'([^']*)'))*)\s*(\/>|><!\[CDATA\[(.*)\]\]><\/$full>)/msiU", array(&$this, 'cdata_in_cdata'), $data);
}
// Return the XML, if so desired
if ($return_xml)
{
$this->data =& $data;
return;
}
// Create the parser
$this->xml = xml_parser_create_ns($encoding);
xml_parser_set_option($this->xml, XML_OPTION_SKIP_WHITE, 1);
xml_set_object($this->xml, $this);
xml_set_character_data_handler($this->xml, 'data_handler');
xml_set_element_handler($this->xml, 'start_handler', 'end_handler');
xml_set_start_namespace_decl_handler($this->xml, 'start_name_space');
xml_set_end_namespace_decl_handler($this->xml, 'end_name_space');
// Parse!
if (!xml_parse($this->xml, $data))
{
$this->data = null;
$this->error_code = xml_get_error_code($this->xml);
$this->error_string = xml_error_string($this->error_code);
}
$this->current_line = xml_get_current_line_number($this->xml);
$this->current_column = xml_get_current_column_number($this->xml);
$this->current_byte = xml_get_current_byte_index($this->xml);
xml_parser_free($this->xml);
return;
}
function add_cdata($match)
{
if (isset($match[10]))
{
return "<$match[1]$match[2]><![CDATA[$match[10]]]></$match[1]>";
}
return $match[0];
}
function cdata_in_cdata($match)
{
if (isset($match[10]))
{
$match[10] = preg_replace_callback('/<!\[CDATA\[(.*)\]\]>/msiU', array(&$this, 'real_cdata_in_cdata'), $match[10]);
return "<$match[1]$match[2]><![CDATA[$match[10]]]></$match[1]>";
}
return $match[0];
}
function real_cdata_in_cdata($match)
{
return htmlspecialchars($match[1], ENT_NOQUOTES);
}
function do_add_content(&$array, $data)
{
if ($this->is_first)
{
$array['data'] = $data;
$array['attribs'] = $this->attribs;
}
else
{
$array['data'] .= $data;
}
}
function start_handler($parser, $name, $attribs)
{
$this->tag_name = $name;
$this->attribs = $attribs;
$this->is_first = true;
switch ($this->tag_name)
{
case 'ITEM':
case $this->namespaces['rss2'] . ':ITEM':
case $this->namespaces['rss1'] . ':ITEM':
case 'ENTRY':
case $this->namespaces['atom'] . ':ENTRY':
$this->inside_item = true;
$this->do_add_content($this->data['items'][$this->item_number], '');
break;
case 'CHANNEL':
case $this->namespaces['rss2'] . ':CHANNEL':
case $this->namespaces['rss1'] . ':CHANNEL':
$this->inside_channel = true;
break;
case 'RSS':
case $this->namespaces['rss2'] . ':RSS':
$this->data['feedinfo']['type'] = 'RSS';
$this->do_add_content($this->data['feeddata'], '');
if (!empty($attribs['VERSION']))
{
$this->data['feedinfo']['version'] = trim($attribs['VERSION']);
}
break;
case $this->namespaces['rdf'] . ':RDF':
$this->data['feedinfo']['type'] = 'RSS';
$this->do_add_content($this->data['feeddata'], '');
$this->data['feedinfo']['version'] = 1;
break;
case 'FEED':
case $this->namespaces['atom'] . ':FEED':
$this->data['feedinfo']['type'] = 'Atom';
$this->do_add_content($this->data['feeddata'], '');
if (!empty($attribs['VERSION']))
{
$this->data['feedinfo']['version'] = trim($attribs['VERSION']);
}
break;
case 'IMAGE':
case $this->namespaces['rss2'] . ':IMAGE':
case $this->namespaces['rss1'] . ':IMAGE':
if ($this->inside_channel)
{
$this->inside_image = true;
}
break;
}
if (!empty($this->data['feedinfo']['type']) && $this->data['feedinfo']['type'] == 'Atom' && ($this->tag_name == 'AUTHOR' || $this->tag_name == $this->namespaces['atom'] . ':AUTHOR'))
{
$this->inside_author = true;
}
$this->data_handler($this->xml, '');
}
function data_handler($parser, $data)
{
if ($this->inside_item)
{
switch ($this->tag_name)
{
case 'TITLE':
case $this->namespaces['rss1'] . ':TITLE':
case $this->namespaces['rss2'] . ':TITLE':
case $this->namespaces['atom'] . ':TITLE':
$this->do_add_content($this->data['items'][$this->item_number]['title'], $data);
break;
case $this->namespaces['dc'] . ':TITLE':
$this->do_add_content($this->data['items'][$this->item_number]['dc:title'], $data);
break;
case 'CONTENT':
case $this->namespaces['atom'] . ':CONTENT':
$this->do_add_content($this->data['items'][$this->item_number]['content'], $data);
break;
case $this->namespaces['content'] . ':ENCODED':
$this->do_add_content($this->data['items'][$this->item_number]['encoded'], $data);
break;
case 'SUMMARY':
case $this->namespaces['atom'] . ':SUMMARY':
$this->do_add_content($this->data['items'][$this->item_number]['summary'], $data);
break;
case 'LONGDESC':
$this->do_add_content($this->data['items'][$this->item_number]['longdesc'], $data);
break;
case 'DESCRIPTION':
case $this->namespaces['rss1'] . ':DESCRIPTION':
case $this->namespaces['rss2'] . ':DESCRIPTION':
$this->do_add_content($this->data['items'][$this->item_number]['description'], $data);
break;
case $this->namespaces['dc'] . ':DESCRIPTION':
$this->do_add_content($this->data['items'][$this->item_number]['dc:description'], $data);
break;
case 'LINK':
case $this->namespaces['rss1'] . ':LINK':
case $this->namespaces['rss2'] . ':LINK':
case $this->namespaces['atom'] . ':LINK':
$this->do_add_content($this->data['items'][$this->item_number]['link'][$this->item_link_number], $data);
break;
case 'ENCLOSURE':
case $this->namespaces['rss1'] . ':ENCLOSURE':
case $this->namespaces['rss2'] . ':ENCLOSURE':
case $this->namespaces['atom'] . ':ENCLOSURE':
$this->do_add_content($this->data['items'][$this->item_number]['enclosure'][$this->enclosure_number], $data);
break;
case 'GUID':
case $this->namespaces['rss1'] . ':GUID':
case $this->namespaces['rss2'] . ':GUID':
$this->do_add_content($this->data['items'][$this->item_number]['guid'], $data);
break;
case 'ID':
case $this->namespaces['atom'] . ':ID':
$this->do_add_content($this->data['items'][$this->item_number]['id'], $data);
break;
case 'PUBDATE':
case $this->namespaces['rss1'] . ':PUBDATE':
case $this->namespaces['rss2'] . ':PUBDATE':
$this->do_add_content($this->data['items'][$this->item_number]['pubdate'], $data);
break;
case $this->namespaces['dc'] . ':DATE':
$this->do_add_content($this->data['items'][$this->item_number]['dc:date'], $data);
break;
case 'ISSUED':
case $this->namespaces['atom'] . ':ISSUED':
$this->do_add_content($this->data['items'][$this->item_number]['issued'], $data);
break;
case 'PUBLISHED':
case $this->namespaces['atom'] . ':PUBLISHED':
$this->do_add_content($this->data['items'][$this->item_number]['published'], $data);
break;
case 'MODIFIED':
case $this->namespaces['atom'] . ':MODIFIED':
$this->do_add_content($this->data['items'][$this->item_number]['modified'], $data);
break;
case 'UPDATED':
case $this->namespaces['atom'] . ':UPDATED':
$this->do_add_content($this->data['items'][$this->item_number]['updated'], $data);
break;
case 'CATEGORY':
case $this->namespaces['rss1'] . ':CATEGORY':
case $this->namespaces['rss2'] . ':CATEGORY':
case $this->namespaces['atom'] . ':CATEGORY':
$this->do_add_content($this->data['items'][$this->item_number]['category'][$this->category_number], $data);
break;
case $this->namespaces['dc'] . ':SUBJECT':
$this->do_add_content($this->data['items'][$this->item_number]['subject'][$this->category_number], $data);
break;
case $this->namespaces['dc'] . ':CREATOR':
$this->do_add_content($this->data['items'][$this->item_number]['creator'][$this->author_number], $data);
break;
case 'AUTHOR':
case $this->namespaces['rss1'] . ':AUTHOR':
case $this->namespaces['rss2'] . ':AUTHOR':
$this->do_add_content($this->data['items'][$this->item_number]['author'][$this->author_number]['rss'], $data);
break;
}
if ($this->inside_author)
{
switch ($this->tag_name)
{
case 'NAME':
case $this->namespaces['atom'] . ':NAME':
$this->do_add_content($this->data['items'][$this->item_number]['author'][$this->author_number]['name'], $data);
break;
case 'URL':
case $this->namespaces['atom'] . ':URL':
$this->do_add_content($this->data['items'][$this->item_number]['author'][$this->author_number]['url'], $data);
break;
case 'URI':
case $this->namespaces['atom'] . ':URI':
$this->do_add_content($this->data['items'][$this->item_number]['author'][$this->author_number]['uri'], $data);
break;
case 'HOMEPAGE':
case $this->namespaces['atom'] . ':HOMEPAGE':
$this->do_add_content($this->data['items'][$this->item_number]['author'][$this->author_number]['homepage'], $data);
break;
case 'EMAIL':
case $this->namespaces['atom'] . ':EMAIL':
$this->do_add_content($this->data['items'][$this->item_number]['author'][$this->author_number]['email'], $data);
break;
}
}
}
else if (($this->inside_channel && !$this->inside_image) || (isset($this->data['feedinfo']['type']) && $this->data['feedinfo']['type'] == 'Atom'))
{
switch ($this->tag_name)
{
case 'TITLE':
case $this->namespaces['rss1'] . ':TITLE':
case $this->namespaces['rss2'] . ':TITLE':
case $this->namespaces['atom'] . ':TITLE':
$this->do_add_content($this->data['info']['title'], $data);
break;
case 'LINK':
case $this->namespaces['rss1'] . ':LINK':
case $this->namespaces['rss2'] . ':LINK':
case $this->namespaces['atom'] . ':LINK':
$this->do_add_content($this->data['info']['link'][$this->link_number], $data);
break;
case 'DESCRIPTION':
case $this->namespaces['rss1'] . ':DESCRIPTION':
case $this->namespaces['rss2'] . ':DESCRIPTION':
$this->do_add_content($this->data['info']['description'], $data);
break;
case $this->namespaces['dc'] . ':DESCRIPTION':
$this->do_add_content($this->data['info']['dc:description'], $data);
break;
case 'TAGLINE':
case $this->namespaces['atom'] . ':TAGLINE':
$this->do_add_content($this->data['info']['tagline'], $data);
break;
case 'SUBTITLE':
case $this->namespaces['atom'] . ':SUBTITLE':
$this->do_add_content($this->data['info']['subtitle'], $data);
break;
case 'COPYRIGHT':
case $this->namespaces['rss1'] . ':COPYRIGHT':
case $this->namespaces['rss2'] . ':COPYRIGHT':
case $this->namespaces['atom'] . ':COPYRIGHT':
$this->do_add_content($this->data['info']['copyright'], $data);
break;
case 'LANGUAGE':
case $this->namespaces['rss1'] . ':LANGUAGE':
case $this->namespaces['rss2'] . ':LANGUAGE':
$this->do_add_content($this->data['info']['language'], $data);
break;
case 'LOGO':
case $this->namespaces['atom'] . ':LOGO':
$this->do_add_content($this->data['info']['logo'], $data);
break;
}
}
else if ($this->inside_channel && $this->inside_image)
{
switch ($this->tag_name)
{
case 'TITLE':
case $this->namespaces['rss1'] . ':TITLE':
case $this->namespaces['rss2'] . ':TITLE':
$this->do_add_content($this->data['info']['image']['title'], $data);
break;
case 'URL':
case $this->namespaces['rss1'] . ':URL':
case $this->namespaces['rss2'] . ':URL':
$this->do_add_content($this->data['info']['image']['url'], $data);
break;
case 'LINK':
case $this->namespaces['rss1'] . ':LINK':
case $this->namespaces['rss2'] . ':LINK':
$this->do_add_content($this->data['info']['image']['link'], $data);
break;
case 'WIDTH':
case $this->namespaces['rss1'] . ':WIDTH':
case $this->namespaces['rss2'] . ':WIDTH':
$this->do_add_content($this->data['info']['image']['width'], $data);
break;
case 'HEIGHT':
case $this->namespaces['rss1'] . ':HEIGHT':
case $this->namespaces['rss2'] . ':HEIGHT':
$this->do_add_content($this->data['info']['image']['height'], $data);
break;
}
}
$this->is_first = false;
}
function end_handler($parser, $name)
{
$this->tag_name = '';
switch ($name)
{
case 'ITEM':
case $this->namespaces['rss1'] . ':ITEM':
case $this->namespaces['rss2'] . ':ITEM':
case 'ENTRY':
case $this->namespaces['atom'] . ':ENTRY':
$this->inside_item = false;
$this->item_number++;
$this->author_number = 0;
$this->category_number = 0;
$this->enclosure_number = 0;
$this->item_link_number = 0;
break;
case 'CHANNEL':
case $this->namespaces['rss1'] . ':CHANNEL':
case $this->namespaces['rss2'] . ':CHANNEL':
$this->inside_channel = false;
break;
case 'IMAGE':
case $this->namespaces['rss1'] . ':IMAGE':
case $this->namespaces['rss2'] . ':IMAGE':
$this->inside_image = false;
break;
case 'AUTHOR':
case $this->namespaces['rss1'] . ':AUTHOR':
case $this->namespaces['rss2'] . ':AUTHOR':
case $this->namespaces['atom'] . ':AUTHOR':
$this->author_number++;
$this->inside_author = false;
break;
case 'CATEGORY':
case $this->namespaces['rss1'] . ':CATEGORY':
case $this->namespaces['rss2'] . ':CATEGORY':
case $this->namespaces['atom'] . ':CATEGORY':
case $this->namespaces['dc'] . ':SUBJECT':
$this->category_number++;
break;
case 'ENCLOSURE':
case $this->namespaces['rss1'] . ':ENCLOSURE':
case $this->namespaces['rss2'] . ':ENCLOSURE':
$this->enclosure_number++;
break;
case 'LINK':
case $this->namespaces['rss1'] . ':LINK':
case $this->namespaces['rss2'] . ':LINK':
case $this->namespaces['atom'] . ':LINK':
if ($this->inside_item)
{
$this->item_link_number++;
}
else
{
$this->link_number++;
}
break;
}
}
function start_name_space($parser, $prefix, $uri = null)
{
$prefix = strtoupper($prefix);
$uri = strtoupper($uri);
if ($prefix == 'ATOM' || $uri == 'HTTP://WWW.W3.ORG/2005/ATOM' || $uri == 'HTTP://PURL.ORG/ATOM/NS#')
{
$this->namespaces['atom'] = $uri;
}
else if ($prefix == 'RSS2' || $uri == 'HTTP://BACKEND.USERLAND.COM/RSS2')
{
$this->namespaces['rss2'] = $uri;
}
else if ($prefix == 'RDF' || $uri == 'HTTP://WWW.W3.ORG/1999/02/22-RDF-SYNTAX-NS#')
{
$this->namespaces['rdf'] = $uri;
}
else if ($prefix == 'RSS' || $uri == 'HTTP://PURL.ORG/RSS/1.0/' || $uri == 'HTTP://MY.NETSCAPE.COM/RDF/SIMPLE/0.9/')
{
$this->namespaces['rss1'] = $uri;
}
else if ($prefix == 'DC' || $uri == 'HTTP://PURL.ORG/DC/ELEMENTS/1.1/')
{
$this->namespaces['dc'] = $uri;
}
else if ($prefix == 'XHTML' || $uri == 'HTTP://WWW.W3.ORG/1999/XHTML')
{
$this->namespaces['xhtml'] = $uri;
$this->xhtml_prefix = $prefix;
}
else if ($prefix == 'CONTENT' || $uri == 'HTTP://PURL.ORG/RSS/1.0/MODULES/CONTENT/')
{
$this->namespaces['content'] = $uri;
}
}
function end_name_space($parser, $prefix)
{
if ($key = array_search(strtoupper($prefix), $this->namespaces))
{
if ($key == 'atom')
{
$this->namespaces['atom'] = 'ATOM';
}
else if ($key == 'rss2')
{
$this->namespaces['rss2'] = 'RSS';
}
else if ($key == 'rdf')
{
$this->namespaces['rdf'] = 'RDF';
}
else if ($key == 'rss1')
{
$this->namespaces['rss1'] = 'RSS';
}
else if ($key == 'dc')
{
$this->namespaces['dc'] = 'DC';
}
else if ($key == 'xhtml')
{
$this->namespaces['xhtml'] = 'XHTML';
$this->xhtml_prefix = 'XHTML';
}
else if ($key == 'content')
{
$this->namespaces['content'] = 'CONTENT';
}
}
}
}
/**
* @package sapphire
* @subpackage integration
*/
class SimplePie_Sanitize
{
// Private vars
var $feedinfo;
var $info;
var $items;
var $feed_xmlbase;
var $item_xmlbase;
var $attribs;
var $cached_entities;
var $cache_convert_entities;
// Options
var $remove_div = true;
var $strip_ads = false;
var $replace_headers = false;
var $bypass_image_hotlink = false;
var $bypass_image_hotlink_page = false;
var $strip_htmltags = array('base', 'blink', 'body', 'doctype', 'embed', 'font', 'form', 'frame', 'frameset', 'html', 'iframe', 'input', 'marquee', 'meta', 'noscript', 'object', 'param', 'script', 'style');
var $encode_instead_of_strip = false;
var $strip_attributes = array('bgsound', 'class', 'expr', 'id', 'style', 'onclick', 'onerror', 'onfinish', 'onmouseover', 'onmouseout', 'onfocus', 'onblur');
var $input_encoding = 'UTF-8';
var $output_encoding = 'UTF-8';
var $item_class = 'SimplePie_Item';
var $author_class = 'SimplePie_Author';
var $enclosure_class = 'SimplePie_Enclosure';
function remove_div($enable = true)
{
$this->remove_div = (bool) $enable;
}
function strip_ads($enable = false)
{
$this->strip_ads = (bool) $enable;
}
function replace_headers($enable = false)
{
$this->enable_headers = (bool) $enable;
}
function bypass_image_hotlink($get = false)
{
if ($get)
{
$this->bypass_image_hotlink = (string) $get;
}
else
{
$this->bypass_image_hotlink = false;
}
}
function bypass_image_hotlink_page($page = false)
{
if ($page)
{
$this->bypass_image_hotlink_page = (string) $page;
}
else
{
$this->bypass_image_hotlink_page = false;
}
}
function strip_htmltags($tags = array('base', 'blink', 'body', 'doctype', 'embed', 'font', 'form', 'frame', 'frameset', 'html', 'iframe', 'input', 'marquee', 'meta', 'noscript', 'object', 'param', 'script', 'style'))
{
if ($tags)
{
if (is_array($tags))
{
$this->strip_htmltags = $tags;
}
else
{
$this->strip_htmltags = explode(',', $tags);
}
}
else
{
$this->strip_htmltags = false;
}
}
function encode_instead_of_strip($enable = false)
{
$this->encode_instead_of_strip = (bool) $enable;
}
function strip_attributes($attribs = array('bgsound', 'class', 'expr', 'id', 'style', 'onclick', 'onerror', 'onfinish', 'onmouseover', 'onmouseout', 'onfocus', 'onblur'))
{
if ($attribs)
{
if (is_array($attribs))
{
$this->strip_attributes = $attribs;
}
else
{
$this->strip_attributes = explode(',', $attribs);
}
}
else
{
$this->strip_attributes = false;
}
}
function input_encoding($encoding = 'UTF-8')
{
$this->input_encoding = (string) $encoding;
}
function output_encoding($encoding = 'UTF-8')
{
$this->output_encoding = (string) $encoding;
}
function set_item_class($class = 'SimplePie_Item')
{
if (SimplePie_Misc::is_a_class($class, 'SimplePie_Item'))
{
$this->item_class = $class;
return true;
}
return false;
}
function set_author_class($class = 'SimplePie_Author')
{
if (SimplePie_Misc::is_a_class($class, 'SimplePie_Author'))
{
$this->author_class = $class;
return true;
}
return false;
}
function set_enclosure_class($class = 'SimplePie_Enclosure')
{
if (SimplePie_Misc::is_a_class($class, 'SimplePie_Enclosure'))
{
$this->enclosure_class = $class;
return true;
}
return false;
}
function parse_data_array(&$data, $url)
{
// Feed Info (Type and Version)
if (!empty($data['feedinfo']['type']))
{
$this->feedinfo = $data['feedinfo'];
}
// Feed level xml:base
if (!empty($data['feeddata']['attribs']['XML:BASE']))
{
$this->feed_xmlbase = $data['feeddata']['attribs']['XML:BASE'];
}
else if (!empty($data['feeddata']['attribs']['HTTP://WWW.W3.ORG/XML/1998/NAMESPACE:BASE']))
{
$this->feed_xmlbase = $data['feeddata']['attribs']['HTTP://WWW.W3.ORG/XML/1998/NAMESPACE:BASE'];
}
// FeedBurner feeds use alternate link
else if (strpos($url, 'http://feeds.feedburner.com/') !== 0)
{
$this->feed_xmlbase = SimplePie_Misc::parse_url($url);
if (empty($this->feed_xmlbase['authority']))
{
$this->feed_xmlbase = preg_replace('/^' . preg_quote(realpath($_SERVER['DOCUMENT_ROOT']), '/') . '/', '', realpath($url));
}
else
{
$this->feed_xmlbase = $url;
}
}
// Feed link(s)
if (!empty($data['info']['link']))
{
foreach ($data['info']['link'] as $link)
{
if (empty($link['attribs']['REL']))
{
$rel = 'alternate';
}
else
{
$rel = strtolower($link['attribs']['REL']);
}
if ($rel == 'enclosure')
{
$href = null;
$type = null;
$length = null;
if (!empty($link['data']))
{
$href = $this->sanitize($link['data'], $link['attribs'], true);
}
else if (!empty($link['attribs']['HREF']))
{
$href = $this->sanitize($link['attribs']['HREF'], $link['attribs'], true);
}
if (!empty($link['attribs']['TYPE'])) {
$type = $this->sanitize($link['attribs']['TYPE'], $link['attribs']);
}
if (!empty($link['attribs']['LENGTH'])) {
$length = $this->sanitize($link['attribs']['LENGTH'], $link['attribs']);
}
$this->info['link']['enclosure'][] = new $this->enclosure_class($href, $type, $length);
}
else
{
if (!empty($link['data']))
{
$this->info['link'][$rel][] = $this->sanitize($link['data'], $link['attribs'], true);
}
else if (!empty($link['attribs']['HREF']))
{
$this->info['link'][$rel][] = $this->sanitize($link['attribs']['HREF'], $link['attribs'], true);
}
}
}
}
// Use the first alternate link if we don't have any feed xml:base
if (empty($this->feed_xmlbase) && !empty($this->info['link']['alternate'][0]))
{
$this->feed_xmlbase = $this->info['link']['alternate'][0];
}
// Feed Title
if (!empty($data['info']['title']['data']))
{
$this->info['title'] = $this->sanitize($data['info']['title']['data'], $data['info']['title']['attribs']);
}
// Feed Descriptions
if (!empty($data['info']['description']['data']))
{
$this->info['description'] = $this->sanitize($data['info']['description']['data'], $data['info']['description']['attribs'], false, true);
}
if (!empty($data['info']['dc:description']['data']))
{
$this->info['dc:description'] = $this->sanitize($data['info']['dc:description']['data'], $data['info']['dc:description']['attribs']);
}
if (!empty($data['info']['tagline']['data']))
{
$this->info['tagline'] = $this->sanitize($data['info']['tagline']['data'], $data['info']['tagline']['attribs']);
}
if (!empty($data['info']['subtitle']['data']))
{
$this->info['subtitle'] = $this->sanitize($data['info']['subtitle']['data'], $data['info']['subtitle']['attribs']);
}
// Feed Language
if (!empty($data['info']['language']['data']))
{
$this->info['language'] = $this->sanitize($data['info']['language']['data'], $data['info']['language']['attribs']);
}
if (!empty($data['feeddata']['attribs']['XML:LANG']))
{
$this->info['xml:lang'] = $this->sanitize($data['feeddata']['attribs']['XML:LANG'], null);
}
else if (!empty($data['feeddata']['attribs']['HTTP://WWW.W3.ORG/XML/1998/NAMESPACE:LANG']))
{
$this->info['xml:lang'] = $this->sanitize($data['feeddata']['attribs']['HTTP://WWW.W3.ORG/XML/1998/NAMESPACE:LANG'], null);
}
// Feed Copyright
if (!empty($data['info']['copyright']['data']))
{
$this->info['copyright'] = $this->sanitize($data['info']['copyright']['data'], $data['info']['copyright']['attribs']);
}
// Feed Image
if (!empty($data['info']['image']['title']['data']))
{
$this->info['image']['title'] = $this->sanitize($data['info']['image']['title']['data'], $data['info']['image']['title']['attribs']);
}
if (!empty($data['info']['image']['url']['data']))
{
$this->info['image']['url'] = $this->sanitize($data['info']['image']['url']['data'], $data['info']['image']['url']['attribs'], true);
}
if (!empty($data['info']['logo']['data']))
{
$this->info['image']['logo'] = $this->sanitize($data['info']['logo']['data'], $data['info']['logo']['attribs'], true);
}
if (!empty($data['info']['image']['link']['data']))
{
$this->info['image']['link'] = $this->sanitize($data['info']['image']['link']['data'], $data['info']['image']['link']['attribs'], true);
}
if (!empty($data['info']['image']['width']['data']))
{
$this->info['image']['width'] = $this->sanitize($data['info']['image']['width']['data'], $data['info']['image']['width']['attribs']);
}
if (!empty($data['info']['image']['height']['data']))
{
$this->info['image']['height'] = $this->sanitize($data['info']['image']['height']['data'], $data['info']['image']['height']['attribs']);
}
// Items
if (!empty($data['items']))
{
foreach ($data['items'] as $key => $item)
{
$newitem = null;
// Item level xml:base
if (!empty($item['attribs']['XML:BASE']))
{
$this->item_xmlbase = SimplePie_Misc::absolutize_url($item['attribs']['XML:BASE'], $this->feed_xmlbase);
}
else if (!empty($item['attribs']['HTTP://WWW.W3.ORG/XML/1998/NAMESPACE:BASE']))
{
$this->item_xmlbase = SimplePie_Misc::absolutize_url($item['attribs']['HTTP://WWW.W3.ORG/XML/1998/NAMESPACE:BASE'], $this->feed_xmlbase);
}
else
{
$this->item_xmlbase = null;
}
// Title
if (!empty($item['title']['data'])) {
$newitem['title'] = $this->sanitize($item['title']['data'], $item['title']['attribs']);
}
if (!empty($item['dc:title']['data']))
{
$newitem['dc:title'] = $this->sanitize($item['dc:title']['data'], $item['dc:title']['attribs']);
}
// Description
if (!empty($item['content']['data']))
{
$newitem['content'] = $this->sanitize($item['content']['data'], $item['content']['attribs']);
}
if (!empty($item['encoded']['data']))
{
$newitem['encoded'] = $this->sanitize($item['encoded']['data'], $item['encoded']['attribs']);
}
if (!empty($item['summary']['data']))
{
$newitem['summary'] = $this->sanitize($item['summary']['data'], $item['summary']['attribs']);
}
if (!empty($item['description']['data']))
{
$newitem['description'] = $this->sanitize($item['description']['data'], $item['description']['attribs'], false, true);
}
if (!empty($item['dc:description']['data']))
{
$newitem['dc:description'] = $this->sanitize($item['dc:description']['data'], $item['dc:description']['attribs']);
}
if (!empty($item['longdesc']['data']))
{
$newitem['longdesc'] = $this->sanitize($item['longdesc']['data'], $item['longdesc']['attribs']);
}
// Link(s)
if (!empty($item['link']))
{
foreach ($item['link'] as $link)
{
if (empty($link['attribs']['REL']))
{
$rel = 'alternate';
}
else
{
$rel = strtolower($link['attribs']['REL']);
}
if ($rel == 'enclosure')
{
$href = null;
$type = null;
$length = null;
if (!empty($link['data']))
{
$href = $this->sanitize($link['data'], $link['attribs'], true);
}
else if (!empty($link['attribs']['HREF']))
{
$href = $this->sanitize($link['attribs']['HREF'], $link['attribs'], true);
}
if (!empty($link['attribs']['TYPE'])) {
$type = $this->sanitize($link['attribs']['TYPE'], $link['attribs']);
}
if (!empty($link['attribs']['LENGTH'])) {
$length = $this->sanitize($link['attribs']['LENGTH'], $link['attribs']);
}
if (!empty($href))
{
$newitem['link'][$rel][] = new $this->enclosure_class($href, $type, $length);
}
}
else
{
if (!empty($link['data']))
{
$newitem['link'][$rel][] = $this->sanitize($link['data'], $link['attribs'], true);
}
else if (!empty($link['attribs']['HREF']))
{
$newitem['link'][$rel][] = $this->sanitize($link['attribs']['HREF'], $link['attribs'], true);
}
}
}
}
// Enclosure(s)
if (!empty($item['enclosure']))
{
foreach ($item['enclosure'] as $enclosure)
{
if (!empty($enclosure['attribs']['URL']))
{
$type = null;
$length = null;
$href = $this->sanitize($enclosure['attribs']['URL'], $enclosure['attribs'], true);
if (!empty($enclosure['attribs']['TYPE']))
{
$type = $this->sanitize($enclosure['attribs']['TYPE'], $enclosure['attribs']);
}
if (!empty($enclosure['attribs']['LENGTH']))
{
$length = $this->sanitize($enclosure['attribs']['LENGTH'], $enclosure['attribs']);
}
$newitem['enclosures'][] = new $this->enclosure_class($href, $type, $length);
}
}
}
// ID
if (!empty($item['guid']['data']))
{
if (!empty($item['guid']['attribs']['ISPERMALINK']) && strtolower($item['guid']['attribs']['ISPERMALINK']) == 'false')
{
$newitem['guid']['permalink'] = false;
}
else
{
$newitem['guid']['permalink'] = true;
}
$newitem['guid']['data'] = $this->sanitize($item['guid']['data'], $item['guid']['attribs']);
}
if (!empty($item['id']['data']))
{
$newitem['id'] = $this->sanitize($item['id']['data'], $item['id']['attribs']);
}
// Date
if (!empty($item['pubdate']['data']))
{
$newitem['pubdate'] = $this->parse_date($this->sanitize($item['pubdate']['data'], $item['pubdate']['attribs']));
}
if (!empty($item['dc:date']['data']))
{
$newitem['dc:date'] = $this->parse_date($this->sanitize($item['dc:date']['data'], $item['dc:date']['attribs']));
}
if (!empty($item['issued']['data']))
{
$newitem['issued'] = $this->parse_date($this->sanitize($item['issued']['data'], $item['issued']['attribs']));
}
if (!empty($item['published']['data']))
{
$newitem['published'] = $this->parse_date($this->sanitize($item['published']['data'], $item['published']['attribs']));
}
if (!empty($item['modified']['data']))
{
$newitem['modified'] = $this->parse_date($this->sanitize($item['modified']['data'], $item['modified']['attribs']));
}
if (!empty($item['updated']['data']))
{
$newitem['updated'] = $this->parse_date($this->sanitize($item['updated']['data'], $item['updated']['attribs']));
}
// Categories
if (!empty($item['category']))
{
foreach ($item['category'] as $category)
{
if (!empty($category['data']))
{
$newitem['category'][] = $this->sanitize($category['data'], $category['attribs']);
}
else if (!empty($category['attribs']['TERM']))
{
$newitem['term'][] = $this->sanitize($category['attribs']['TERM'], $category['attribs']);
}
}
}
if (!empty($item['subject']))
{
foreach ($item['subject'] as $category)
{
if (!empty($category['data']))
{
$newitem['subject'][] = $this->sanitize($category['data'], $category['attribs']);
}
}
}
// Author
if (!empty($item['creator']))
{
foreach ($item['creator'] as $creator)
{
if (!empty($creator['data']))
{
$newitem['creator'][] = new $this->author_class($this->sanitize($creator['data'], $creator['attribs']), null, null);
}
}
}
if (!empty($item['author']))
{
foreach ($item['author'] as $author)
{
$name = null;
$link = null;
$email = null;
if (!empty($author['rss']))
{
$sane = $this->sanitize($author['rss']['data'], $author['rss']['attribs']);
if (preg_match('/(.*)@(.*) \((.*)\)/msiU', $sane, $matches)) {
$name = trim($matches[3]);
$email = trim("$matches[1]@$matches[2]");
} else {
$email = $sane;
}
}
else
{
if (!empty($author['name']))
{
$name = $this->sanitize($author['name']['data'], $author['name']['attribs']);
}
if (!empty($author['url']))
{
$link = $this->sanitize($author['url']['data'], $author['url']['attribs'], true);
}
else if (!empty($author['uri']))
{
$link = $this->sanitize($author['uri']['data'], $author['uri']['attribs'], true);
}
else if (!empty($author['homepage']))
{
$link = $this->sanitize($author['homepage']['data'], $author['homepage']['attribs'], true);
}
if (!empty($author['email'])) {
$email = $this->sanitize($author['email']['data'], $author['email']['attribs']);
}
}
$newitem['author'][] = new $this->author_class($name, $link, $email);
}
}
unset($data['items'][$key]);
$this->items[] = new $this->item_class($newitem);
}
}
}
function sanitize($data, $attribs, $is_url = false, $force_decode = false)
{
$this->attribs = $attribs;
if (isset($this->feedinfo['type']) && $this->feedinfo['type'] == 'Atom')
{
if ((!empty($attribs['MODE']) && $attribs['MODE'] == 'base64') || (!empty($attribs['TYPE']) && $attribs['TYPE'] == 'application/octet-stream'))
{
$data = trim($data);
$data = base64_decode($data);
}
else if ((!empty($attribs['MODE']) && $attribs['MODE'] == 'escaped' || !empty($attribs['TYPE']) && ($attribs['TYPE'] == 'html' || $attribs['TYPE'] == 'text/html')))
{
$data = $this->entities_decode($data);
}
if (!empty($attribs['TYPE']) && ($attribs['TYPE'] == 'xhtml' || $attribs['TYPE'] == 'application/xhtml+xml'))
{
if ($this->remove_div)
{
$data = preg_replace('/<div( .*)?>/msiU', '', strrev(preg_replace('/>vid\/</i', '', strrev($data), 1)), 1);
}
else
{
$data = preg_replace('/<div( .*)?>/msiU', '<div>', $data, 1);
}
$data = $this->convert_entities($data);
}
}
else
{
$data = $this->convert_entities($data);
}
if ($force_decode)
{
$data = $this->entities_decode($data);
}
$data = trim($data);
$data = preg_replace('/<\!--([^-]|-[^-])*-->/msiU', '', $data);
// If Strip Ads is enabled, strip them.
if ($this->strip_ads)
{
$data = preg_replace('/<a (.*)href=(.*)click\.phdo\?s=(.*)<\/a>/msiU', '', $data); // Pheedo links (tested with Dooce.com)
$data = preg_replace('/<p(.*)>(.*)<a href="http:\/\/ad.doubleclick.net\/jump\/(.*)<\/p>/msiU', '', $data); // Doubleclick links (tested with InfoWorld.com)
$data = preg_replace('/<p><map (.*)name=(.*)google_ad_map(.*)<\/p>/msiU', '', $data); // Google AdSense for Feeds (tested with tuaw.com).
// Feedflare, from Feedburner
}
// Replace H1, H2, and H3 tags with the less important H4 tags.
// This is because on a site, the more important headers might make sense,
// but it most likely doesn't fit in the context of RSS-in-a-webpage.
if ($this->replace_headers)
{
$data = preg_replace('/<h[1-3]((\s*((\w+:)?\w+)\s*=\s*("([^"]*)"|\'([^\']*)\'|(.*)))*)\s*>/msiU', '<h4\\1>', $data);
$data = preg_replace('/<\/h[1-3]>/i', '</h4>', $data);
}
if ($is_url)
{
$data = $this->replace_urls($data, true);
}
else
{
$data = preg_replace_callback('/<(\S+)((\s*((\w+:)?\w+)\s*=\s*("([^"]*)"|\'([^\']*)\'|(.*)))*)\s*(\/>|>(.*)<\/\S+>)/msiU', array(&$this, 'replace_urls'), $data);
}
// If Bypass Image Hotlink is enabled, rewrite all the image tags.
if ($this->bypass_image_hotlink)
{
$images = SimplePie_Misc::get_element('img', $data);
foreach ($images as $img)
{
if (!empty($img['attribs']['SRC']['data']))
{
$pre = '';
if ($this->bypass_image_hotlink_page)
{
$pre = $this->bypass_image_hotlink_page;
}
$pre .= "?$this->bypass_image_hotlink=";
$img['attribs']['SRC']['data'] = $pre . rawurlencode(strtr($img['attribs']['SRC']['data'], array_flip(get_html_translation_table(HTML_SPECIALCHARS, ENT_QUOTES))));
$data = str_replace($img['full'], SimplePie_Misc::element_implode($img), $data);
}
}
}
// Strip out HTML tags and attributes that might cause various security problems.
// Based on recommendations by Mark Pilgrim at:
// http://diveintomark.org/archives/2003/06/12/how_to_consume_rss_safely
if ($this->strip_htmltags)
{
foreach ($this->strip_htmltags as $tag)
{
$data = preg_replace_callback("/<($tag)((\s*((\w+:)?\w+)(\s*=\s*(\"([^\"]*)\"|'([^']*)'|(.*)))?)*)\s*(\/>|>(.*)<\/($tag)((\s*((\w+:)?\w+)(\s*=\s*(\"([^\"]*)\"|'([^']*)'|(.*)))?)*)\s*>)/msiU", array(&$this, 'do_strip_htmltags'), $data);
}
}
if ($this->strip_attributes)
{
foreach ($this->strip_attributes as $attrib)
{
$data = preg_replace('/ '. trim($attrib) .'=("|")(\w|\s|=|-|:|;|\/|\.|\?|&|,|#|!|\(|\)|\'|'|<|>|\+|{|})*("|")/i', '', $data);
$data = preg_replace('/ '. trim($attrib) .'=(\'|')(\w|\s|=|-|:|;|\/|\.|\?|&|,|#|!|\(|\)|"|"|<|>|\+|{|})*(\'|')/i', '', $data);
$data = preg_replace('/ '. trim($attrib) .'=(\w|\s|=|-|:|;|\/|\.|\?|&|,|#|!|\(|\)|\+|{|})*/i', '', $data);
}
}
// Convert encoding
$data = SimplePie_Misc::change_encoding($data, $this->input_encoding, $this->output_encoding);
return $data;
}
function do_strip_htmltags($match)
{
if ($this->encode_instead_of_strip)
{
if (isset($match[12]) && !in_array(strtolower($match[1]), array('script', 'style')))
{
return "<$match[1]$match[2]>$match[12]</$match[1]>";
}
else if (isset($match[12]))
{
return "<$match[1]$match[2]></$match[1]>";
}
else
{
return "<$match[1]$match[2]/>";
}
}
else
{
if (isset($match[12]) && !in_array(strtolower($match[1]), array('script', 'style')))
{
return $match[12];
}
else
{
return '';
}
}
}
function replace_urls($data, $raw_url = false)
{
if (!empty($this->attribs['XML:BASE']))
{
$xmlbase = $attribs['XML:BASE'];
}
else if (!empty($this->attribs['HTTP://WWW.W3.ORG/XML/1998/NAMESPACE:BASE']))
{
$xmlbase = $this->attribs['HTTP://WWW.W3.ORG/XML/1998/NAMESPACE:BASE'];
}
if (!empty($xmlbase))
{
if (!empty($this->item_xmlbase))
{
$xmlbase = SimplePie_Misc::absolutize_url($xmlbase, $this->item_xmlbase);
}
else
{
$xmlbase = SimplePie_Misc::absolutize_url($xmlbase, $this->feed_xmlbase);
}
}
else if (!empty($this->item_xmlbase))
{
$xmlbase = $this->item_xmlbase;
}
else
{
$xmlbase = $this->feed_xmlbase;
}
if ($raw_url)
{
return SimplePie_Misc::absolutize_url($data, $xmlbase);
}
else
{
$attributes = array(
'background',
'href',
'src',
'longdesc',
'usemap',
'codebase',
'data',
'classid',
'cite',
'action',
'profile',
'for'
);
foreach ($attributes as $attribute)
{
if (preg_match("/$attribute='(.*)'/siU", $data[0], $attrib) || preg_match("/$attribute=\"(.*)\"/siU", $data[0], $attrib) || preg_match("/$attribute=(.*)[ |\/|>]/siU", $data[0], $attrib))
{
$new_tag = str_replace($attrib[1], SimplePie_Misc::absolutize_url($attrib[1], $xmlbase), $attrib[0]);
$data[0] = str_replace($attrib[0], $new_tag, $data[0]);
}
}
return $data[0];
}
}
function entities_decode($data)
{
return preg_replace_callback('/&(#)?(x)?([0-9a-z]+);/mi', array(&$this, 'do_entites_decode'), $data);
}
function do_entites_decode($data)
{
if (isset($this->cached_entities[$data[0]]))
{
return $this->cached_entities[$data[0]];
}
else
{
$return = SimplePie_Misc::change_encoding(html_entity_decode($data[0], ENT_QUOTES), 'ISO-8859-1', $this->input_encoding);
if ($return == $data[0])
{
$return = SimplePie_Misc::change_encoding(preg_replace_callback('/&#([x]?[0-9a-f]+);/mi', array(&$this, 'replace_num_entity'), $data[0]), 'UTF-8', $this->input_encoding);
}
$this->cached_entities[$data[0]] = $return;
return $return;
}
}
function convert_entities($data)
{
return preg_replace_callback('/&#(x)?([0-9a-z]+);/mi', array(&$this, 'do_convert_entities'), $data);
}
function do_convert_entities($data)
{
if (isset($this->cache_convert_entities[$data[0]]))
{
return $this->cache_convert_entities[$data[0]];
}
else if (isset($this->cached_entities[$data[0]]))
{
$return = htmlentities($this->cached_entities[$data[0]], ENT_QUOTES, 'UTF-8');
}
else
{
$return = htmlentities(preg_replace_callback('/&#([x]?[0-9a-f]+);/mi', array(&$this, 'replace_num_entity'), $data[0]), ENT_QUOTES, 'UTF-8');
}
$this->cache_convert_entities[$data[0]] = $return;
return $return;
}
/*
* Escape numeric entities
* From a PHP Manual note (on html_entity_decode())
* Copyright (c) 2005 by "php dot net at c dash ovidiu dot tk",
* "emilianomartinezluque at yahoo dot com" and "hurricane at cyberworldz dot org".
*
* This material may be distributed only subject to the terms and conditions set forth in
* the Open Publication License, v1.0 or later (the latest version is presently available at
* http://www.opencontent.org/openpub/).
*/
function replace_num_entity($ord)
{
$ord = $ord[1];
if (preg_match('/^x([0-9a-f]+)$/i', $ord, $match))
{
$ord = hexdec($match[1]);
}
else
{
$ord = intval($ord);
}
$no_bytes = 0;
$byte = array();
if ($ord < 128)
{
return chr($ord);
}
if ($ord < 2048)
{
$no_bytes = 2;
}
else if ($ord < 65536)
{
$no_bytes = 3;
}
else if ($ord < 1114112)
{
$no_bytes = 4;
}
else
{
return;
}
switch ($no_bytes)
{
case 2:
$prefix = array(31, 192);
break;
case 3:
$prefix = array(15, 224);
break;
case 4:
$prefix = array(7, 240);
break;
}
for ($i = 0; $i < $no_bytes; $i++)
{
$byte[$no_bytes-$i-1] = (($ord & (63 * pow(2,6*$i))) / pow(2,6*$i)) & 63 | 128;
}
$byte[0] = ($byte[0] & $prefix[0]) | $prefix[1];
$ret = '';
for ($i = 0; $i < $no_bytes; $i++)
{
$ret .= chr($byte[$i]);
}
return $ret;
}
function parse_date($date)
{
$military_timezone = array('A' => '-0100', 'B' => '-0200', 'C' => '-0300', 'D' => '-0400', 'E' => '-0500', 'F' => '-0600', 'G' => '-0700', 'H' => '-0800', 'I' => '-0900', 'K' => '-1000', 'L' => '-1100', 'M' => '-1200', 'N' => '+0100', 'O' => '+0200', 'P' => '+0300', 'Q' => '+0400', 'R' => '+0500', 'S' => '+0600', 'T' => '+0700', 'U' => '+0800', 'V' => '+0900', 'W' => '+1000', 'X' => '+1100', 'Y' => '+1200', 'Z' => '-0000');
$north_american_timezone = array('GMT' => '-0000', 'EST' => '-0500', 'EDT' => '-0400', 'CST' => '-0600', 'CDT' => '-0500', 'MST' => '-0700', 'MDT' => '-0600', 'PST' => '-0800', 'PDT' => '-0700');
if (preg_match('/([0-9]{2,4})-?([0-9]{2})-?([0-9]{2})T([0-9]{2}):?([0-9]{2})(:?([0-9]{2}(\.[0-9]*)?))?(UT|GMT|EST|EDT|CST|CDT|MST|MDT|PST|PDT|[a-z]|(\\+|-)[0-9]{4}|(\\+|-)[0-9]{2}:[0-9]{2})?/i', $date, $matches))
{
if (!isset($matches[7]))
{
$matches[7] = '';
}
if (!isset($matches[9]))
{
$matches[9] = '';
}
$matches[7] = str_pad(round($matches[7]), 2, '0', STR_PAD_LEFT);
switch (strlen($matches[9]))
{
case 0:
$timezone = '';
break;
case 1:
$timezone = $military_timezone[strtoupper($matches[9])];
break;
case 2:
$timezone = '-0000';
break;
case 3:
$timezone = $north_american_timezone[strtoupper($matches[9])];
break;
case 5:
$timezone = $matches[9];
break;
case 6:
$timezone = substr_replace($matches[9], '', 3, 1);
break;
}
$date = strtotime("$matches[1]-$matches[2]-$matches[3] $matches[4]:$matches[5]:$matches[7] $timezone");
}
else if (preg_match('/([0-9]{1,2})\s*(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s*([0-9]{2}|[0-9]{4})\s*([0-9]{2}):([0-9]{2})(:([0-9]{2}(\.[0-9]*)?))?\s*(UT|GMT|EST|EDT|CST|CDT|MST|MDT|PST|PDT|[a-z]|(\\+|-)[0-9]{4}|(\\+|-)[0-9]{2}:[0-9]{2})?/i', $date, $matches))
{
$three_month = array('Jan' => 1, 'Feb' => 2, 'Mar' => 3, 'Apr' => 4, 'May' => 5, 'Jun' => 6, 'Jul' => 7, 'Aug' => 8, 'Sep' => 9, 'Oct' => 10, 'Nov' => 11, 'Dec' => 12);
$month = $three_month[$matches[2]];
if (strlen($matches[3]) == 2)
{
$year = ($matches[3] < 70) ? "20$matches[3]" : "19$matches[3]";
}
else
{
$year = $matches[3];
}
if (!isset($matches[7]))
{
$matches[7] = '';
}
if (!isset($matches[9]))
{
$matches[9] = '';
}
$second = str_pad(round($matches[7]), 2, '0', STR_PAD_LEFT);
switch (strlen($matches[9]))
{
case 0:
$timezone = '';
break;
case 1:
$timezone = $military_timezone[strtoupper($matches[9])];
break;
case 2:
$timezone = '-0000';
break;
case 3:
$timezone = $north_american_timezone[strtoupper($matches[9])];
break;
case 5:
$timezone = $matches[9];
break;
case 6:
$timezone = substr_replace($matches[9], '', 3, 1);
break;
}
$date = strtotime("$year-$month-$matches[1] $matches[4]:$matches[5]:$second $timezone");
}
else
{
$date = strtotime($date);
}
if ($date !== false && $date !== -1)
{
return $date;
}
else
{
return false;
}
}
}
?> | true |
472df118ddb48c08bc1261a1f4b2f6f3b39d0be9 | PHP | ewolden/Storytelling-backend | /personalization/runRecommender.php | UTF-8 | 2,339 | 2.78125 | 3 | [
"Apache-2.0"
] | permissive | <?php
/*Contributors: Kjersti Fagerholt, Roar Gj�vaag, Ragnhild Krogh, Espen Str�mjordet,
Audun S�ther, Hanne Marie Trelease, Eivind Halm�y Wolden
"Copyright 2015 The TAG CLOUD/SINTEF project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License."
*/
require_once(__DIR__.'/computePreferenceValues.php');
require_once(__DIR__.'/../database/dbUser.php');
require_once(__DIR__.'/../models/userModel.php');
class runRecommender {
private $user;
private $method;
private $db;
/*If we are adding recommendations to the existing ones, this will be "true", otherwise "false"
Both "true" and "false" are string-values, not boolean */
private $add;
public function __construct($user){
$this->user = $user;
/*By default, we are creating brand new recommendations. If we should recommend
stories not in the recommendation view at front end, the setAdd-method needs to be called*/
$this->add = "false";
$this->findMethod();
$cpv = new computePreferenceValues($user);
$cpv->computeAllValues();
}
/**
* Find out which recommendation type to run, collaborative or content-based.
*/
public function findMethod(){
$this->db = new dbUser();
//print_r($numberOfRatesByThisUser);
/*If there is more than ten stories rated by more than 10 people shared by this user their other recommendations are valid*/
if($this->db->getNumRatedStoriesShared($this->user->getUserId()) >= 10){
$this->method = 'collaborative';
} else{
$this->method = 'content';
}
}
public function setAdd($add){
$this->add = $add;
}
public function getAdd(){
return $this->add;
}
public function getUser(){
return $this->user;
}
public function getMethod(){
return $this->method;
}
public function runRecommender(){
$output = shell_exec("java -jar ../java/recommender/recommender.jar ".$this->getUser()->getUserId()." ".$this->getMethod()." ".$this->getAdd()." 2>&1");
return $output;
}
}
?>
| true |
93fdcb9bc308ddce27c1f5c114c3c1bae2752973 | PHP | mohamedjs/multi-vue | /app/Http/Requests/Api/AdvertismentRequest.php | UTF-8 | 1,227 | 2.546875 | 3 | [] | no_license | <?php
namespace App\Http\Requests\Api;
use Illuminate\Foundation\Http\FormRequest;
use Validator;
use App\Advertisement;
class AdvertismentRequest extends FormRequest
{
/**
* Determine if the advertisment is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
switch($this->method())
{
case 'GET':
case 'DELETE':
{
return [];
}
case 'POST':
{
return [
'ads_url' => 'required|url|max:255',
'image' => 'required|mimes:jpeg,bmp,png,svg',
];
}
case 'PUT':
case 'PATCH':
{
return [
'ads_url' => 'required|url|max:255',
'image' => isset($this->image) ? 'mimes:jpeg,bmp,png,svg' : '',
];
}
default:break;
}
}
protected function formatValidationErrors(Validator $validator)
{
return $validator->errors()->all();
}
}
| true |
73c8c2745115879ca38cc33318139827d5f0e980 | PHP | xp-forge/address | /src/test/php/util/address/unittest/ValueOfTest.class.php | UTF-8 | 5,779 | 2.53125 | 3 | [
"BSD-3-Clause"
] | permissive | <?php namespace util\address\unittest;
use test\verify\Runtime;
use test\{Action, Assert, Test, Values};
use util\Date;
use util\address\{ValueOf, XmlStreaming};
class ValueOfTest {
#[Test]
public function compact_form() {
$address= new XmlStreaming('<book>Name</book>');
Assert::equals(
['name' => 'Name'],
$address->next(new ValueOf([], [
'.' => function(&$self) { $self['name']= yield; }
]))
);
}
/** @see https://wiki.php.net/rfc/arrow_functions_v2 */
#[Test, Runtime(php: '>=7.4')]
public function can_use_fn() {
$address= new XmlStreaming('<book>Name</book>');
Assert::equals(
['name' => 'Name'],
$address->next(new ValueOf([], [
'.' => eval('return fn(&$self, $it) => $self["name"]= yield;')
]))
);
}
#[Test]
public function child_node() {
$address= new XmlStreaming('<book><name>Name</name></book>');
Assert::equals(
['name' => 'Name'],
$address->next(new ValueOf([], [
'name' => function(&$self) { $self['name']= yield; }
]))
);
}
#[Test, Values(['<book><name>Name</name><author><name/></author></book>', '<book><author><name/></author><name>Name</name></book>', '<book><name>Name</name><author><name>Test</name></author></book>', '<book><author><name>Test</name></author><name>Name</name></book>'])]
public function child_node_ordering_irrelevant($xml) {
$address= new XmlStreaming($xml);
Assert::equals(
['name' => 'Name', 'author' => 'Test'],
$address->next(new ValueOf([], [
'name' => function(&$self) { $self['name']= yield; },
'author/name' => function(&$self) { $self['author']= yield ?? 'Test'; },
]))
);
}
#[Test]
public function child_node_and_attributes() {
$address= new XmlStreaming('<book author="Test"><name>Name</name></book>');
Assert::equals(
['name' => 'Name', 'author' => 'Test'],
$address->next(new ValueOf([], [
'@author' => function(&$self) { $self['author']= yield; },
'name' => function(&$self) { $self['name']= yield; }
]))
);
}
#[Test]
public function uses_default_value() {
$address= new XmlStreaming('<book asin="B01N1UPZ10">Name</book>');
Assert::equals(
['name' => 'Name', 'asin' => 'B01N1UPZ10', 'authors' => []],
$address->next(new ValueOf(['authors' => []], [
'.' => function(&$self) { $self['name']= yield; },
'@asin' => function(&$self) { $self['asin']= yield; },
]))
);
}
#[Test]
public function any_child() {
$address= new XmlStreaming('<book><name>Name</name><author>Test</author></book>');
Assert::equals(
['name' => 'Name', 'author' => 'Test'],
$address->next(new ValueOf([], [
'*' => function(&$self, $name) { $self[$name]= yield; }
]))
);
}
#[Test]
public function any_attribute() {
$address= new XmlStreaming('<book asin="B01N1UPZ10" author="Test">Name</book>');
Assert::equals(
['name' => 'Name', 'asin' => 'B01N1UPZ10', 'author' => 'Test'],
$address->next(new ValueOf([], [
'@*' => function(&$self, $name) { $self[$name]= yield; },
'.' => function(&$self) { $self['name']= yield; }
]))
);
}
#[Test]
public function can_use_subpaths() {
$address= new XmlStreaming('<book><name>Name</name><authors><name>A</name><name>B</name></authors></book>');
Assert::equals(
['name' => 'Name', 'authors' => ['A', 'B']],
$address->next(new ValueOf(['authors' => []], [
'name' => function(&$self) { $self['name']= yield; },
'authors/name' => function(&$self) { $self['authors'][]= yield; },
]))
);
}
#[Test]
public function can_produce_arrays() {
$address= new XmlStreaming('<books><book>Book #1</book><book>Book #2</book></books>');
Assert::equals(
['Book #1', 'Book #2'],
$address->next(new ValueOf([], [
'book' => function(&$self) { $self[]= yield; },
]))
);
}
#[Test]
public function can_reassing_value() {
$address= new XmlStreaming('<book>Book #1</book>');
Assert::equals(
'Book #1',
$address->next(new ValueOf(null, [
'.' => function(&$self) { $self= yield; },
]))
);
}
#[Test]
public function can_select_multiple() {
$address= new XmlStreaming('<tests><unit>a</unit><unit>b</unit><integration>c</integration><system>d</system></tests>');
Assert::equals(
['unit:a', 'unit:b', 'integration:c'],
$address->next(new ValueOf([], [
'unit|integration' => function(&$self, $name) { $self[]= $name.':'.yield; },
]))
);
}
#[Test]
public function combine_values_during_finalization() {
$address= new XmlStreaming('<created><date>2022-10-31</date><time>16:26:53</time></created>');
$values= [];
Assert::equals(
['date' => new Date('2022-10-31 16:26:53')],
$address->next(new ValueOf([], [
'date' => function(&$self) use(&$values) { $values[0]= yield; },
'time' => function(&$self) use(&$values) { $values[1]= yield; },
'/' => function(&$self) use(&$values) { $self['date']= new Date(implode(' ', $values)); },
]))
);
}
#[Test, Values([1, 2, 3])]
public function call_value_repeatedly($times) {
$definition= new ValueOf([], [
'@*' => function(&$self, $name) { $self[$name]= yield; },
'.' => function(&$self) { $self['name']= yield; }
]);
$address= new XmlStreaming('<book asin="B01N1UPZ10" author="Test">Name</book>');
for ($i= 1; $i <= $times; $i++) {
Assert::equals(
['name' => 'Name', 'asin' => 'B01N1UPZ10', 'author' => 'Test'],
$address->value($definition),
"Invocation #{$i}"
);
}
}
} | true |
7f749fee77e9259a9c5a281a22ec2a633ca8fe3d | PHP | sabrinaMS/VacinaDigital | /Dao/NurseDAO.php | UTF-8 | 3,244 | 3.140625 | 3 | [] | no_license | <?php
include_once 'Model/Nurse.php';
include_once 'Model/PDOFactory.php';
class NurseDAO{
public function insert(Nurse $nurse){
$qInsert = "INSERT INTO nurse(name, coren, password) VALUES (:name, :coren, :password)";
$pdo = PDOFactory::getConexao();
$comando = $pdo->prepare($qInsert);
$comando->bindParam(":name",$nurse->name);
$comando->bindParam(":coren",$nurse->coren);
$comando->bindParam(":password",$nurse->password);
$comando->execute();
$nurse->id = $pdo->lastInsertId();
return $nurse;
}
public function list(){
$query = 'SELECT * FROM nurse';
$pdo = PDOFactory::getConexao();
$comando = $pdo->prepare($query);
$comando->execute();
$nurses=array();
while($row = $comando->fetch(PDO::FETCH_OBJ)){
$nurses[] = new Nurse($row->id, $row->name, $row->coren, $row->password);
}
return $nurses;
}
public function listById($id){
$query = 'SELECT * FROM nurse WHERE id=:id';
$pdo = PDOFactory::getConexao();
$comando = $pdo->prepare($query);
$comando->bindParam(':id', $id);
$comando->execute();
$result = $comando->fetch(PDO::FETCH_OBJ);
if(!$result){
$e = new PDOException("Não foi possível encontrar um enfermeiro com id $id", 23000);
$e->errorInfo = array(23000, 9999, "Não foi possível encontrar um enfermeiro com id $id");
throw $e;
}
return new Nurse($result->id,$result->name, $result->coren, $result->password);
}
public function listByCoren($coren){
$query = 'SELECT * FROM nurse WHERE coren=:coren';
$pdo = PDOFactory::getConexao();
$comando = $pdo->prepare($query);
$comando->bindParam (':coren', $coren);
$comando->execute();
$result = $comando->fetch(PDO::FETCH_OBJ);
if(!$result){
$e = new PDOException("Não foi possível encontrar um enfermeiro com coren $coren", 23000);
$e->errorInfo = array(23000, 9999, "Não foi possível encontrar um enfermeiro com coren $coren");
throw $e;
}
return new Nurse($result->id,$result->name, $result->coren, $result->password);
}
public function update(Nurse $nurse){
$this->listById($nurse->id); //checks if id exists
$qUpdate = "UPDATE nurse SET name=:name, coren=:coren, password=:password WHERE id=:id";
$pdo = PDOFactory::getConexao();
$comando = $pdo->prepare($qUpdate);
$comando->bindParam(":name",$nurse->name);
$comando->bindParam(":coren",$nurse->coren);
$comando->bindParam(":password",$nurse->password);
$comando->bindParam(":id",$nurse->id);
$comando->execute();
return($nurse);
}
public function delete($id){
$qDelete = "DELETE FROM nurse WHERE id=:id";
$nurse = $this->listById($id);
$pdo = PDOFactory::getConexao();
$comando = $pdo->prepare($qDelete);
$comando->bindParam(":id",$id);
$comando->execute();
return $nurse;
}
}
?>
| true |
0255822f648d5961c1b028470453616eb6b169a0 | PHP | otavioeiji/php | /aula09/exercicio03.php | UTF-8 | 692 | 2.75 | 3 | [] | no_license | <!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="_css/estilo.css"/>
<meta charset="UTF-8"/>
<title>Curso de PHP - CursoemVideo.com</title>
</head>
<body>
<div>
<?php
$n1 = isset($_GET["nota1"])?$_GET["nota1"]:0;
$n2 = isset($_GET["nota2"])?$_GET["nota2"]:0;
$m = ($n1 + $n2) / 2;
if($m < 5) {
$s = "REPROVADO";
}
elseif($m >= 5 && $m <7) {
$s = "RECUPERAÇÃO";
}
else {
$s = "APROVADO";
}
echo "Sua média é $m. Situação do aluno: $s";
?>
<a href="exercicio03.html" class="botao">Voltar</a>
</div>
</body>
</html>
| true |
236abf151b35ede2b7c301623df279e4da7b3efd | PHP | onaka-black/line_ranking_exporter | /application/exceptions/not_found_exception.php | UTF-8 | 145 | 2.5625 | 3 | [] | no_license | <?php
class not_found_exception extends Exception {
public function __construct($message) {
$this->message = $message;
}
} | true |
6577b610c900d1d0e6c44a9b8b541a83cee44ed4 | PHP | shrestsav/iscent | /myAdmin/quote/classes/order.php | UTF-8 | 45,240 | 2.5625 | 3 | [] | no_license | <?php
class order extends object_class{
public $productF;
public function __construct(){
parent::__construct('3');
if (isset($GLOBALS['productF'])) $this->productF = $GLOBALS['productF'];
else {
require_once(__DIR__."/../../product_management/functions/product_function.php");
$this->productF=new product_function();
}
/**
* MultiLanguage keys Use where echo;
* define this class words and where this class will call
* and define words of file where this class will called
**/
global $_e;
global $adminPanelLanguage;
$_w=array();
//newOrder.php
$_w['Add New Quote'] = '' ;
$_w['Add New Quotes'] = '' ;
$_w['InComplete Orders'] = '' ;
$_w['All Orders'] = '' ;
$_w['All Quotes'] = '' ;
$_w['Complete Orders'] = '' ;
$_w['Cancel Orders'] = '' ;
$_w['InProcess Invoices'] = '' ;
$_w['Quote Create/View'] = '' ;
//New order form Function
$_w['Store Country'] = '' ;
$_w['Select Country'] = '' ;
$_w['User'] = '' ;
$_w['Select User'] = '' ;
$_w['No User'] = '' ;
$_w['Invoice Status'] = '' ;
$_w['Payment Type'] = '' ;
$_w['Payment Info'] = '' ;
$_w['Enter Vendor Payment Information'] = '' ;
$_w['PRODUCT SCALE'] = '' ;
$_w['PRODUCT COLOR'] = '' ;
$_w['STORE'] = '' ;
$_w['QUANTITY'] = '' ;
$_w['PRICE'] = '' ;
$_w['Select Product Name'] = '' ;
$_w['Select Scale'] = '' ;
$_w['Select Color'] = '' ;
$_w['Select Store'] = '' ;
$_w['Product QTY'] = '' ;
$_w['Single Price'] = '' ;
$_w['Product Discount'] = '' ;
$_w['Add Product'] = '' ;
$_w['Remove Checked Items'] = '' ;
$_w['Check/Uncheck All'] = '' ;
$_w['NO'] = '' ;
$_w['PRODUCT'] = '' ;
$_w['WEIGHT'] = '' ;
$_w['QTY'] = '' ;
$_w['(QTY*PRICE) - DISCOUNT = TOTAL PRICE'] = '' ;
$_w['(QTY*PRICE) = TOTAL PRICE'] = '' ;
$_w['DISCOUNT'] = '' ;
$_w['TOTAL WEIGHT'] = '' ;
$_w['TOTAL PRICE'] = '' ;
$_w['Sender And Receiver Information'] = '' ;
$_w['I am sender And Receiver'] = '' ;
$_w['I am Sender And Friend Is receiver'] = '' ;
$_w['Sender Information'] = '' ;
$_w['Sender Name'] = '' ;
$_w['Sender Phone'] = '' ;
$_w['Sender Email'] = '' ;
$_w['Sender City'] = '' ;
$_w['Sender Country'] = '' ;
$_w['Country'] = '' ;
$_w['Sender Post Code'] = '' ;
$_w['Sender Address'] = '' ;
$_w['Receiver Information'] = '' ;
$_w['Receiver Name'] = '' ;
$_w['Receiver Phone'] = '' ;
$_w['Receiver Email'] = '' ;
$_w['Receiver City'] = '' ;
$_w['Receiver Country'] = '' ;
$_w['Receiver Post Code'] = '' ;
$_w['Receiver Address'] = '' ;
$_w['Last Order View'] = '' ;
$_w['ORDER'] = '' ;
$_w['Order Price'] = '' ;
$_w['Shipping Price'] = '' ;
$_w['Total'] = '' ;
$_w['ORDER AND PROCESS'] = '' ;
$_w['Selected Products'] = '' ;
//Add new order function
$_w['Order QTY is Greater Than stock Quantity'] = '' ;
$_w['Shipping Error'] = '' ;
$_w['Some thing went wrong Please try again'] = '' ;
$_w['Product Submit Fail'] = '' ;
$_w['Product Submit'] = '' ;
$_w['Product Submit Failed'] = '' ;
$_w['New Order Added Successfully'] = '' ;
$_w['New Order'] = '' ;
$_w['Product Successfully Submit'] = '' ;
$_w['Thank you your product is successfully submit'] = '' ;
//Order view function
$_w['SNO'] = '' ;
$_w['INVOICE'] = '' ;
$_w['CUSTOMER NAME'] = '' ;
$_w['INVOICE DATE'] = '' ;
$_w['SOLD PRICE'] = '' ;
$_w['PAYMENT METHOD'] = '' ;
$_w['ORDER PROCESS'] = '' ;
$_w['ACTION'] = '' ;
$_w['Yes'] = '' ;
$_w['PURCHASE PRICE'] = '' ;
$_w['VIEW ORDER'] = '' ;
$_w['Delete All Old Incomplete Orders'] = '' ;
$_w['Search By Date Range'] = '' ;
$_w['Date To'] = '' ;
$_w['Date From'] = '' ;
$_w['Selected SubTotal'] = '' ;
$_w['Quote Information'] = '' ;
$_w['Terms & Conditions'] = '' ;
$_e = $this->dbF->hardWordsMulti($_w,$adminPanelLanguage,'Admin Order');
}
public function deleteOrders($type){
$days = $this->functions->ibms_setting('order_invoice_deleteOn_request_after_days');
$minusDays = date('Y-m-d',strtotime("-$days days"));
try {
$this->db->beginTransaction();
$sql = "SELECT order_pIds FROM `order_invoice_product` WHERE dateTime <= '$minusDays' AND orderStatus = 'inComplete'";
$oldData = $this->dbF->getRows($sql);
foreach ($oldData as $val) {
$orderId = $val['order_invoice_id'];
$pIds = $val['order_pIds'];
$pArray = explode("-", $pIds); // 491-246-435-5 => p_ pid - scaleId - colorId - storeId;
$pId = $pArray[0]; // 491
$scaleId = $pArray[1]; // 426
$colorId = $pArray[2]; // 435
$storeId = $pArray[3]; // 5
@$customId = $pArray[4]; // 5
//delete custom if has
if ($customId != '0' && !empty($customId)) {
$sql = "DELETE FROM p_custom_submit WHERE id = '$customId'";
$this->dbF->setRow($sql);
}
$sql = "DELETE FROM order_invoice WHERE order_invoice_pk = '$orderId' '";
$this->dbF->setRow($sql);
}
$this->db->commit();
}catch (Exception $e){
$this->db->rollBack();
}
$this->deleteCartOld();
}
public function deleteCartOld(){
//delete Old Cart and custom From table...
$date = date('Y-m-d',strtotime("-30 days"));
$sql = "DELETE FROM p_custom_submit WHERE dateTime <= '$date' AND id in (SELECT customId FROM cart WHERE dateTime <= '$date')";
$this->dbF->setRow($sql);
$sql = "DELETE FROM cart WHERE dateTime <= '$date'";
$this->dbF->setRow($sql);
}
/**
* Simple Form For New Order
*/
public function newOrderForm(){
global $_e;
$this->functions->require_once_custom('store');
$storeC = new store();
$paymentSelectOption = $this->productF->paymentSelect();
$invoiceStatus = $this->productF->invoiceStatus();
$country_list = $this->functions->countrySelectOption();
$storeList = $storeC->storeNamesCountryValueOption();
$token = $this->functions->setFormToken('orderAdd',false);
//user list
$this->functions->require_once_custom('webUsers.class');
$userC = new webUsers();
$usersOption = $userC->userSelectOptionList();
echo '
<form method="post" class="form-horizontal" action="quote/classes/quote.php">
'.$token.'
<input type="hidden" id="priceCode" name="priceCode"/>
<input type="hidden" name="pay_terms" value="Cash On Devlivery" />
<div class="form-horizontal">
<div class="col-md-6">
<div class="form-group">
<label for="input2" class="col-sm-2 col-md-3 control-label">'. _uc($_e['Store Country']) .'</label>
<div class="col-sm-10 col-md-9">
<input type="hidden" name="storeCountry" class="form-control storeCountry" data-val="">
<select id="storeCountry" onchange="orderProductJson(this);" name="storeCountry" class="form-control" required="required">
<option value="">'. _uc($_e['Select Country']) .'</option>
'. $storeList .'
</select>
</div>
</div>
<div class="form-group" style="position: relative;margin-bottom: 30px;">
<div id="loadingProgress" style="position: absolute;width: 100%;"></div>
</div>
</div><!-- First col-md-6 end -->
<div class="table-responsive inline-block newProduct " >
<div id="productNotFoundInCountry"></div>
<table id="newProduct" class="table sTable table-hover " width="100%" border="0" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th>'. _u($_e['PRODUCT']) .'</th>
<th>'. _u($_e['STORE']) .'</th>
<th width="110">'. _u($_e['QUANTITY']) .'</th>
<th>'. _u($_e['PRICE']) .'</th>
<th>'. _u($_e['TOTAL PRICE']) .'</th>
</tr>
</thead>
<tbody>
<td>
<input type="text" class="form-control" id="invoice_product_id" placeholder="'. _uc($_e['Select Product Name']) .'">
<input type="hidden" class="form-control invoice_product_id" data-val="">
<input type="hidden" class="form-control invoice_product_shipping" data-val="">
<input type="hidden" class="" id="invoice_product_weight">
</td>
<td>
<input type="text" class="form-control" id="invoice_product_store" placeholder="'. _uc($_e['Select Store']) .'" readonly value="No Store Avaiable">
<input type="hidden" class="form-control invoice_product_store" data-val="">
</td>
<td>
<input type="number" class="form-control" data-val="" data-max="0" min="1" id="invoice_qty" placeholder="'. _uc($_e['Product QTY']) .'">
</td>
<td>
<input type="number" class="form-control" data-val="" min="0" id="invoice_price" placeholder="'. _uc($_e['Single Price']) .'">
</td>
<td>
<input type="number" readonly class="form-control" min="0" id="invoice_total_price" placeholder="'. _uc($_e['TOTAL PRICE']) .'">
</td>
</tbody>
</table>
<div class="form-group">
<div class="col-sm-10">
<button type="button" onclick="invoiceFormValid();" id="AddProduct" class="btn btn-default">'. _uc($_e['Add Product']) .'</button>
</div>
</div>
</div> <!-- first table end-->
<div style="margin:70px 0 0 0;">
<input type="button" class="btn btn-danger" onclick="removechecked()" value="'. _uc($_e['Remove Checked Items']) .'" >
<input type="button" class="btn btn-danger" onclick="uncheckall()" value="'. _uc($_e['Check/Uncheck All']) .'">
<br><br>
<div class="table-responsive" >
<table id="addSelectedProduct" class="table sTable table-hover" width="100%" border="0" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th>'. _u($_e['NO']) .'</th>
<th>'. _u($_e['PRODUCT']) .'</th>
<th>'. _u($_e['QTY']) .'</th>
<th width="300">'. _u($_e['(QTY*PRICE) = TOTAL PRICE']) .'</th>
</tr>
</thead>
<tbody id="vendorProdcutList">
</tbody>
</table>
</div><!-- table-responsive added -->
<div class="container-fluid text-right">
<div class="h4"> '. _u($_e['QUANTITY']) .': <span class="totalQuantity bold">0</span></div>
<div class="h4"> '. _u($_e['TOTAL PRICE']) .': <span class="totalPrice bold">0</span></div>
<input type="hidden" name="totalPrice" class="totalPriceInput" />
<input type="hidden" name="totalWeight" class="totalWeightInput" />
</div>
<div class="container-fluid">
<h3 class="navbar-inverse bg-black text-center" >'. _uc($_e['Quote Information']) .'</h3>
<div class="col-sm-8">
<div class="navbar-inverse bg-black" style="color:#fff">'. _uc($_e['Quote Information']) .'</div>
<div class="col-sm-12">
<div class="form-group">
<label for="receipt_vendor" class="col-sm-3 control-label">'. _uc($_e['Name']) .'</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="reciver_name" id="sender_name" required="" placeholder="'. _uc($_e['Name']) .'"/>
</div>
</div>
<div class="form-group">
<label for="receipt_vendor" class="col-sm-3 control-label">'. _uc($_e['Phone']) .'</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="reciver_phone" id="sender_phone" placeholder="'. _uc($_e['Phone']) .'"/>
</div>
</div>
<div class="form-group">
<label for="receipt_vendor" class="col-sm-3 control-label">'. _uc($_e['Email']) .'</label>
<div class="col-sm-9">
<input type="email" class="form-control" name="reciver_email" id="sender_email" placeholder="'. _uc($_e['Email']) .'"/>
</div>
</div>
<div class="form-group">
<label for="receipt_vendor" class="col-sm-3 control-label">'. _uc($_e['City']) .'</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="sender_city" id="sender_city" placeholder="'. _uc($_e['City']) .'"/>
</div>
</div>
<div class="form-group">
<label for="receipt_vendor" class="col-sm-3 control-label">'. _uc($_e['Country']) .'</label>
<div class="col-sm-9">
<fieldset class="sender_countryFieldset">
<select required id="sender_country" name="sender_country" class="form-control">
<option value="">------</option>
'. $country_list .'
</select>
</fieldset>
</div>
</div>
<div class="form-group">
<label for="receipt_vendor" class="col-sm-3 control-label">'. _uc($_e['Address']) .'</label>
<div class="col-sm-9">
<textarea class="form-control" name="sender_address" id="sender_address" placeholder="'. _uc($_e['Address']) .'"></textarea>
</div>
</div>
<div class="form-group">
<label for="receipt_vendor" class="col-sm-3 control-label">'. _uc($_e['Terms & Conditions']) .'</label>
<div class="col-sm-9">
<textarea class="form-control ckeditor" name="reciver_note" id="sender_address" ></textarea>
</div>
</div>
</div><!-- col-md-12 sender info end -->
</div>
<!-- col-md-6 sender info end -->
</div> <!-- Send Receiver Info-->
<div class="clearfix"></div>
<div class="clearfix"></div>
<br>
<div class="container-fluid ReviewButtons">
<input type="submit" name="submit" value="ORDER" class="submit btn btn-primary btn-lg">
</div>
<div class="clearfix"></div>
<br/>';
$viewBody ='
<div class="FinalPriceReport">
<div class="h4"> '. _uc($_e['Order Price']) .' : <span class="totalPriceModel bold"></span></div>
<div class="h4"> '. _uc($_e['Shipping Price']) .' : <span class="totalPriceShipping bold"></span></div>
<div class="h4"> '. _uc($_e['Total']) .' : <span class="totalFinal bold"></span></div>
</div>
<br>
<br>';
$this->functions->customDialogView('Check Out',$viewBody,'Close');
echo '
<!-- if you change value of button then must change from addNewOrder();
</div> <!-- added product script div end -->
</div> <!-- form-horizontal end -->
</form>
</div>
<div class="container-fluid lastReview displaynone">
<div class="reportReview">
<div class="form-horizontal">
<div class="col-md-6">
<div class="form-group">
<label class="col-sm-4 col-md-5">'. _uc($_e['Store Country']) .'</label>
<div class="col-sm-8 col-md-7">
<div id="reportStoreCountry">View</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 col-md-5">'. _uc($_e['Payment Type']) .'</label>
<div class="col-sm-8 col-md-7">
<div id="reportPaymentType">View</div>
</div>
</div>
</div><!-- col-md-6 end -->
<div class="col-md-6">
<div class="form-group">
<label class="col-sm-4 col-md-5">'. _uc($_e['Invoice Status']) .'</label>
<div class="col-sm-8 col-md-7">
<div id="reportInvoiceStatus">View</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 col-md-5">'. _uc($_e['Payment Info']) .'</label>
<div class="col-sm-8 col-md-7">
<div id="reportPaymentInfo">View</div>
</div>
</div>
</div><!-- col-md-6 end -->
</div><!-- Form horizontal 1 end-->
<hr>
<h4>'. _uc($_e['Selected Products']) .'</h4>
<div class="col-sm-12" id="reportSelectedProduct"></div>
<hr>
<h4>'. _uc($_e['Sender And Receiver Information']) .'</h4>
<div class="form-horizontal">
<div class="col-md-6">
<div class="form-group">
<label class="col-sm-4 col-md-5">'. _uc($_e['Sender Name']) .'</label>
<div class="col-sm-8 col-md-7">
<div id="reportSenderName">View</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 col-md-5">'. _uc($_e['Sender Phone']) .'</label>
<div class="col-sm-8 col-md-7">
<div id="reportSenderPhone">View</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 col-md-5">'. _uc($_e['Sender Email']) .'</label>
<div class="col-sm-8 col-md-7">
<div id="reportSenderEmail">View</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 col-md-5">'. _uc($_e['Sender City']) .'</label>
<div class="col-sm-8 col-md-7">
<div id="reportSenderCity">View</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 col-md-5">'. _uc($_e['Sender Country']) .'</label>
<div class="col-sm-8 col-md-7">
<div id="reportSenderCountry">View</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 col-md-5">'. _uc($_e['Sender Address']) .'</label>
<div class="col-sm-8 col-md-7">
<div id="reportSenderAddress">View</div>
</div>
</div>
</div><!-- col-sm-6 end 1-->
<div class="col-md-6">
<div class="form-group">
<label class="col-sm-4 col-md-5">'. _uc($_e['Receiver Name']) .'</label>
<div class="col-sm-8 col-md-7">
<div id="reportReceiverName">View</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 col-md-5">'. _uc($_e['Receiver Phone']) .'</label>
<div class="col-sm-8 col-md-7">
<div id="reportReceiverPhone">View</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 col-md-5">'. _uc($_e['Receiver Email']) .'</label>
<div class="col-sm-8 col-md-7">
<div id="reportReceiverEmail">View</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 col-md-5">'. _uc($_e['Receiver City']) .'</label>
<div class="col-sm-8 col-md-7">
<div id="reportReceiverCity">View</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 col-md-5">'. _uc($_e['Receiver Country']) .'</label>
<div class="col-sm-8 col-md-7">
<div id="reportReceiverCountry">View</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 col-md-5">'. _uc($_e['Receiver Address']) .'</label>
<div class="col-sm-8 col-md-7">
<div id="reportReceiverAddress">View</div>
</div>
</div>
</div> <!--col sm 6 end 2-->
</div><!-- Form horizontal 2 end-->
</div>
</div><!-- Last review Info-->';
}
public function addNewOrder(){
global $_e;
if(!$this->functions->getFormToken('orderAdd')){ return false;}
$btn1 = 'ORDER';
$btn2 = 'ORDER AND PROCESS';
//set Submit buttons value here
if(isset($_POST) && !empty($_POST) && !empty($_POST['cart_list']) && !empty($_POST['receiver_name']) && !empty($_POST['receiver_country']) ){
try{
$this->db->beginTransaction();
if($_POST['submit'] == $btn1){
$process = 0;
}else if($_POST['submit'] == $btn2){
$process = 1; //submit product quantity from inventory
}else{
throw new Exception("");
}
$invoiceId = '';
@$paymentType = $_POST['paymentType']; //int
@$payment_info = $_POST['paymentInfo']; //text
@$invoiceStatus = $_POST['invoiceStatus']; // varchar
@$total_price = $_POST['totalPrice']; //Using In Security, If price from web form or php calculated not match, mean Hacking Attempt
@$price_code = $_POST['priceCode'];
@$country = $_POST['storeCountry'];
@$userId = $_POST['userId'];
@$totalWeightReceiveFromForm = $_POST['totalWeight']; //Using In Security, If Weight from web form or php calculated not match, mean Hacking Attempt
$total_priceNew = 0; //Calculateing in foreach loop, test with $total_price after loop, If not match its hacking attempt
$total_weightNew = 0;//Calculateing in foreach loop, test with $totalWeightReceiveFromForm after loop, If not match its hacking attempt
$countryData = $this->productF->productCountryId($country);
$countryId = $countryData['cur_id'];
//major data submit here, will later here, update this table
$now = date('Y-m-d H:i:s');
$sql = "INSERT INTO `order_invoice`
(
`paymentType`,
`invoice_date`,
`orderUser`,
`payment_info`,
`price_code`,
`invoice_status`
)
VALUES (
?,?,?,?,?,?
)";
$array=array($paymentType,$now,$userId,$payment_info,$price_code,$invoiceStatus);
$this->dbF->setRow($sql,$array,false);
$invoiceId=$this->dbF->rowLastId;
// invoice first data Enter
//Invoice Product add
foreach($_POST['cart_list'] as $key=>$id){
$pArray = explode("_",$id); //p_491-246-435-5 => p_ pid - scaleId - colorId - storeId;
$pIds = $pArray[1];
$pArray = explode("-",$pIds); // 491-246-435-5 => p_ pid - scaleId - colorId - storeId;
$pId = $pArray[0]; // 491
$scaleId = $pArray[1]; // 426
$colorId = $pArray[2]; // 435
$storeId = $pArray[3]; // 5
@$customId = $pArray[4]; // 5
$pName = $this->productF->getProductFullName($pId,$scaleId,$colorId);
$storeName = $this->productF->getStoreName($storeId);
$pPrice = $this->productF->productTotalPrice($pId,$scaleId,$colorId,$customId,$country);
//price calculation
$salePrice = $_POST['pTotalprice_'.$id];
/*$discountArray = $this->productF->productDiscount($pId,$countryId);
if(!empty($discountArray)){
$discount = $discountArray['discount'];
$discountFormat = $discountArray['discountFormat'];
if($discountFormat=='price'){
$discount = $pPrice-$discount;
}else if($discountFormat=='percent'){
$discount = ($pPrice*$discount)/100;
}
}else{
$discount = 0;
}*/
$discount = floatval($_POST['pDiscount_'.$id]);
$total_priceNew += floatval($salePrice);
$saleQTY = $_POST['pQty_'.$id];
$salePrice = ($salePrice+$discount)/$saleQTY; // get single product QTY price
//Weight Calculation
$weight = $this->productF->getProductWeight($pId,$scaleId,$colorId);
$total_weightNew += $weight*$saleQTY;
@$hashVal = $pId.":".$scaleId.":".$colorId.":".$storeId;
$hash = md5($hashVal);
$sql = "INSERT INTO `order_invoice_product`
(
`order_invoice_id`,
`order_pIds`,
`order_pName`,
`order_pStore`,
`order_pPrice`,
`order_salePrice`,
`order_discount`,
`order_pQty`,
`order_pWeight`,
`order_process`,
`order_hash`
) VALUES (
?,?,?,?,?,?,?,?,?,?,?
)";
$array = array($invoiceId,$pIds,$pName,$storeName,$pPrice,$salePrice,$discount,$saleQTY,$weight,$process,$hash);
$this->dbF->setRow($sql,$array,false);
// Remove QTY FROM inventory
if($process==1){
$invQty = $this->productF->stockProductQty($hash);
if($invQty >= $saleQTY){
if($this->productF->stockProductQtyMinus($hash,$saleQTY)){
}else{
throw new Exception($_e['Quote QTY is Greater Than stock Quantity']);
}
}else{
throw new Exception($_e['Quote QTY is Greater Than stock Quantity']);
}
} // If Process Order End
} // Foreach loop End
//check php calculate price and javascript price
if(floatval($total_price) != floatval($total_priceNew)){
throw new Exception("Hacking Attempt Found Code : 151");
}
//check php calculate weight and javascript weight
if(floatval($totalWeightReceiveFromForm) != floatval($total_weightNew)){
throw new Exception("Hacking Attempt Found Code : 152");
}
// User Info Add
//first add order invoice,, addNewOrder(); // not klarna
if(intval($paymentType) !=intval('2')){
$sql = "INSERT INTO `order_invoice_info`
(
`order_invoice_id`,
`sender_name`,
`sender_phone`,
`sender_email`,
`sender_address`,
`sender_city`,
`sender_country`,
`sender_post`,
`receiver_name`,
`receiver_phone`,
`receiver_email`,
`receiver_address`,
`receiver_city`,
`receiver_country`,
`receiver_post`
)
VALUES (
?,
?,?,?,?,?,?,?,
?,?,?,?,?,?,?
)";
$array = array(
$invoiceId,
$_POST['sender_name'] , $_POST['sender_phone'] , $_POST['sender_email'] , $_POST['sender_address'] , $_POST['sender_city'] , $_POST['sender_country'],$_POST['sender_post'],
$_POST['receiver_name'],$_POST['receiver_phone'],$_POST['receiver_email'],$_POST['receiver_address'],$_POST['receiver_city'],$_POST['receiver_country'],$_POST['receiver_post'],
);
$this->dbF->setRow($sql,$array,false);
}
//Update invoice after
//Calculating Shiping price
$shippingData = $this->productF->shippingPrice($country,$_POST['receiver_country']);
if($shippingData==false){
//throw new Exception("Hacking Attempt Found OR Shipping Error");
throw new Exception($_e["Shipping Error"]);
}
$shippingWeight = $shippingData['shp_weight'];
$shippingPrice = $shippingData['shp_price'];
//calculating
@$unitWeight = ceil($total_weightNew/$shippingWeight);
$unitWeight = round($unitWeight,2);
$finalShippingPrice= $shippingPrice*$unitWeight;
$total_priceNew += $finalShippingPrice;
$invoiceKey = $this->functions->ibms_setting('invoice_key_start_with'); // Invoice Number start with
if(intval($paymentType)===intval('2') ){
$processStatus = 'inComplete';
}else{
$processStatus= 'process';
}
$sql = "UPDATE `order_invoice` SET
`invoice_id` = '".$invoiceKey.''.$invoiceId."',
`total_price` = '$total_priceNew',
`ship_price` = '$finalShippingPrice',
`total_weight` = '$total_weightNew',
`orderStatus` = '$processStatus',
`shippingCountry` = ?
WHERE `order_invoice_pk` = '$invoiceId'";
$this->dbF->setRow($sql,array($_POST['receiver_country']),false);
$this->db->commit();
if($this->dbF->rowCount>0){
$msg = $this->functions->notificationError(_js(_uc($_e['Product Successfully Submit'])),_js($_e['Thank you your product is successfully submit']),'btn-success');
$_SESSION['msg'] =base64_encode($msg);
$this->functions->setlog(_uc($_e['New Quote']),_uc($_e['Quote']),$invoiceKey.''.$invoiceId,$_e['New Quote Added Successfully']);
}else{
$msg = $this->functions->notificationError(_js(_uc($_e['Product Submit'])),_js(_uc($_e['Product Submit Failed'])),'btn-danger');
$_SESSION['msg'] =base64_encode($msg);
}
$this->productF->paymentProcess($paymentType);
// $this->functions->submitRefresh();
}catch(Exception $e){
$this->dbF->error_submit($e);
$this->db->rollBack();
$msg = '';
$msg = $e->getMessage();
if($msg != ''){
$msg = $this->functions->notificationError(_js(_uc($_e['Product Submit Fail'])),$msg,'btn-danger');
}
$msg = $this->functions->notificationError(_js(_uc($_e['Product Submit Fail'])),_js($_e['Some thing went wrong Please try again']),'btn-danger');
$_SESSION['msg'] =base64_encode($msg);
}
}else if(isset($_POST) && !empty($_POST) && ($_POST['submit']==$btn1 || $_POST['submit']==$btn2) ){
$msg = $this->functions->notificationError(_js(_uc($_e['Product Submit Fail'])),_js($_e['Some thing went wrong Please try again']),'btn-danger');
$_SESSION['msg'] =base64_encode($msg);
}
} // Function End
public function invoiceOrdersSql(){
$sql="SELECT * FROM `order_invoice` WHERE orderStatus != 'inComplete' AND invoice_status != '3' AND invoice_status != '0' ORDER BY order_invoice_pk DESC";
$invoice = $this->dbF->getRows($sql);
return $invoice;
}
public function all($user_id=false){
$user = "";
$array = array();
if( ! empty($user_id) ) {
$user = " WHERE `orderUser` = ? ";
$array[] = $user_id;
}
$sql = "SELECT * FROM `order_invoice` $user ORDER BY order_invoice_pk DESC";
$invoice = $this->dbF->getRows($sql,$array);
return $invoice;
}
public function completeOrdersSql(){
$sql="SELECT * FROM `order_invoice` WHERE invoice_status = '3' ORDER BY order_invoice_pk DESC";
$invoice = $this->dbF->getRows($sql);
return $invoice;
}
public function cancelOrdersSql(){
$sql="SELECT * FROM `order_invoice` WHERE invoice_status = '0' ORDER BY order_invoice_pk DESC";
$invoice = $this->dbF->getRows($sql);
return $invoice;
}
public function inCompleteOrdersSql(){
$sql="SELECT * FROM `order_invoice` WHERE orderStatus = 'inComplete' ORDER BY order_invoice_pk DESC";
$invoice = $this->dbF->getRows($sql);
return $invoice;
}
public function invoiceList($order= '',$user_id = false){
global $_e;
$href = "quote/order_ajax.php?page=data_ajax_all";
$class = "dTable";
$data_attr = '';
$sql="SELECT * FROM `quote` ORDER BY `qId` DESC";
$invoice = $this->dbF->getRows($sql);
//$class = "dTable_ajax";
echo '
<div class="table-responsive">
<table class="table table-hover dTable tableIBMS">
<thead>
<th>'. _u('SNO') .'</th>
<th>'. _u('Name') .'</th>
<th>'. _u('Email') .'</th>
<th>'. _u('File') .'</th>
<th>'. _u('Date') .'</th>
<th width="120">'. _u('ACTION') .'</th>
</thead>
<tbody>';
$i=0;
foreach($invoice as $val){
$i++;
$divInvoice ='';
$id = $val['qId'];
$link = WEB_URL.'/uploads/files/quote/'.$val['qFile'];
echo "<tr>
<td>$i</td>
<td>$val[qName]</a></td>
<td>$val[qEmail]</td>
<td><a href=".$link.">Download</a></td>
<td>$val[qDate]</td>
<td>
<div class='btn-group btn-group-sm'>
<a data-id='$id' onclick='return delOrderInvoice(this);' class='btn'>
<i class='glyphicon glyphicon-trash trash'></i>
<i class='fa fa-refresh waiting fa-spin' style='display: none'></i>
</a>
</div>
</td>
</tr>";
}
echo '
</tbody>
</table>
</div> <!-- .table-responsive End -->';
}
public function orderInvoiceInfo($orderId){
$sql = "SELECT * FROM order_invoice_info WHERE order_invoice_id = '$orderId'";
$data = $this->dbF->getRow($sql);
return $data;
}
public function invoiceListUser($userId,$echo = true){
global $_e;
$temp = '';
$temp .= '
<div class="table-responsive">
<table class="table table-hover dTable tableIBMS">
<thead>
<th class="hidden-xs">'. _u($_e['SNO']) .'</th>
<th>'. _u($_e['INVOICE']) .'</th>
<th class="hidden-xs">'. _u($_e['CUSTOMER NAME']) .'</th>
<th class="hidden-xs">'. _u($_e['INVOICE DATE']) .'</th>
<th>'. _u($_e['PURCHASE PRICE']) .'</th>
<th class="hidden-xs hidden-sm">'. _u($_e['PAYMENT METHOD']) .'</th>
<th class="hidden-xs">'. _u($_e['ORDER PROCESS']) .'</th>
<th>'. _u($_e['Invoice Status']) .'</th>
<th>'. _u($_e['VIEW ORDER']) .'</th>
</thead>
<tbody>';
$sql="SELECT * FROM `order_invoice` WHERE orderUser = '$userId' ORDER BY order_invoice_pk DESC";
$invoice = $this->dbF->getRows($sql);
if(!$this->dbF->rowCount){
$noFound = "<div class='alert alert-danger text-center'>".$this->dbF->hardWords('No Invoice Found',false)."</div>";
if($echo){
echo $noFound;
}else{
return $noFound;
}
return "";
}
$i=0;
foreach($invoice as $val){
$i++;
$divInvoice = '';
$invoiceStatus = $this->productF->invoiceStatusFind($val['invoice_status']);
$st = $val['invoice_status'];
if($st=='0') $divInvoice = "<div class='btn btn-danger btn-sm' style='min-width:80px;'>$invoiceStatus</div>";
else if($st=='1') $divInvoice = "<div class='btn btn-warning btn-sm' style='min-width:80px;'>$invoiceStatus</div>";
else if($st=='2') $divInvoice = "<div class='btn btn-info btn-sm' style='min-width:80px;'>$invoiceStatus</div>";
else if($st=='3') $divInvoice = "<div class='btn btn-success btn-sm' style='min-width:80px;'>$invoiceStatus</div>";
else $divInvoice = "<div class='btn btn-default btn-sm' style='min-width:80px;'>$invoiceStatus</div>";
$invoiceDate = date('Y-m-d H:i:s',strtotime($val['dateTime']));
$invoiceId = $val['order_invoice_pk'];
$orderInfo = $this->orderInvoiceInfo($invoiceId);
$customeName = $orderInfo['sender_name'];
//Check order process or not,, if single product process it show 1
$sql = "SELECT * FROM `order_invoice_product` WHERE `order_invoice_id` = '$invoiceId' AND `order_process` = '1'";
$this->dbF->getRow($sql);
$orderProcess ="<div class='btn btn-danger btn-sm' style='width:50px;'>". _uc($_e['NO']) ."</div>";
if($this->dbF->rowCount>0){
//make sure all order process or custome process
$sql = "SELECT * FROM `order_invoice_product` WHERE `order_invoice_id` = '$invoiceId' AND `order_process` = '0' ";
$this->dbF->getRow($sql);
if($this->dbF->rowCount>0){
$orderProcess ="<div class='btn btn-warning btn-sm' style='width:50px;'>". _uc($_e['Yes']) ."</div>";
}else{
$orderProcess ="<div class='btn btn-success btn-sm' style='width:50px;'>". _uc($_e['Yes']) ."</div>";
}
}
$days = $this->functions->ibms_setting('order_invoice_deleteOn_request_after_days');
$link = $this->functions->getLinkFolder();
$date = date('Y-m-d',strtotime($val['dateTime']));
$minusDays = date('Y-m-d',strtotime("-$days days"));
$class = "
<a href='invoicePrint?mailId=$invoiceId&orderId=".$this->functions->encode($invoiceId)."' target='_blank' class='btn btn-success'>
<i class='fa fa-file-pdf-o'></i>
</a>
<a href='?view=$invoiceId&orderId=".$this->functions->encode($invoiceId)."' class='btn btn-success'>
<i class='glyphicon glyphicon-list-alt'></i>
</a>";
if($val['orderStatus']=='inComplete'
|| $val['orderStatus']=='pendingPaypal'
|| $val['orderStatus']=='pendingPayson'){
$class = "
<a href='orderInvoice.php?inv=$invoiceId' target='_blank' class='btn btn-danger'>
<i class='glyphicon glyphicon-share-alt '></i>
</a>
<a href='?view=$invoiceId&orderId=".$this->functions->encode($invoiceId)."' class='btn btn-success'>
<i class='glyphicon glyphicon-list-alt'></i>
</a>
";
}
$paymentMethod = $val['paymentType'];
$paymentMethod = $this->productF->paymentArrayFindWeb($paymentMethod);
$temp .= "<tr>
<td class='hidden-xs'>$i</td>
<td>$val[invoice_id]</td>
<td class='hidden-xs'>$customeName</td>
<td class='hidden-xs'>$invoiceDate</td>
<td>$val[total_price] $val[price_code]</td>
<td class='hidden-xs hidden-sm'>$paymentMethod</td>
<td class='hidden-xs'>$orderProcess</td>
<td>$divInvoice</td>
<td>
<div class='btn-group btn-group-sm'>
$class";
$temp .= "</div>
</td>
</tr>";
}
$temp .= '
</tbody>
</table>
</div> <!-- .table-responsive End -->';
if($echo){
echo $temp;
}else{
return $temp;
}
}
public function invoiceSQL($column = '*'){
$sql="SELECT ".$column." FROM `order_invoice`";
return $this->dbF->getRows($sql);
}
}
?> | true |
1c6372482f3888bf42a86afe45b6ef6b4f9864c3 | PHP | sandstorm/NeosH5P | /Classes/Domain/Repository/ContentRepository.php | UTF-8 | 1,882 | 2.53125 | 3 | [
"MIT"
] | permissive | <?php
namespace Sandstorm\NeosH5P\Domain\Repository;
use Neos\Flow\Persistence\Doctrine\Repository;
use Neos\Flow\Annotations as Flow;
use Neos\Flow\Persistence\QueryInterface;
use Neos\Flow\Persistence\QueryResultInterface;
use Sandstorm\NeosH5P\Domain\Model\Library;
/**
* @Flow\Scope("singleton")
*/
class ContentRepository extends Repository
{
/**
* @var array
*/
protected $defaultOrderings = ['contentId' => QueryInterface::ORDER_DESCENDING];
/**
* @param Library $library
* @return QueryResultInterface
*/
public function findFirstTenContentsByLibrary(Library $library)
{
$query = $this->createQuery();
$query->getQueryBuilder()
->where('e.library = ?0')->setMaxResults(10)
->setParameters([$library]);
return $query->execute();
}
/**
* @param string $title
* @param string $orderBy
* @param string $orderDirection
* @return QueryResultInterface
*/
public function findByContainsTitle($title, $orderBy, $orderDirection)
{
$query = $this->createQuery();
$query->getQueryBuilder()
->where('e.title LIKE :title')
->orderBy('e.' . $orderBy, $orderDirection)
->setParameters(['title' => '%' . $title . '%']);
return $query->execute();
}
/**
* @param $id
*/
public function removeByContentId($id)
{
$content = $this->findOneByContentId($id);
if ($content !== null) {
$this->remove($content);
}
}
/**
* @param Library $library
*/
public function countContents(Library $library)
{
$query = $this->createQuery();
$query->getQueryBuilder()
->where('e.library = ?0')
->setParameters([$library]);
return $query->execute()->count();
}
}
| true |
08f1ef725b5cb9a540623f11b6b913b9df696451 | PHP | Clemards/TypingGame | /scripts/playJs.php | UTF-8 | 3,201 | 2.8125 | 3 | [] | no_license | <?php
$filename = 'inc/quote.txt';
$contents = file($filename);
$tabArray = array();
foreach($contents as $cont)
$tabArray[] = preg_replace( "/\r|\n/", "", $cont);
?>
<script>
var quoteArray;
var i;
var score = 1;
var hours; var minutes; var seconds;
$( document ).ready(function() {
// Gestion du timer
var dateLoad = new Date().getTime();
document.cookie = "start="+new Date().getTime();
setInterval(function() {
var now = new Date().getTime();
var distance = now - dateLoad;
hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
seconds = Math.floor((distance % (1000 * 60)) / 1000);
if(hours != 0)
$("#timer").html(hours + " h " + minutes + " min " + seconds + " sec");
else if(minutes != 0)
$("#timer").html(minutes + " min " + seconds + " sec");
else
$("#timer").html(seconds + " sec");
}, 1000);
// Affichage des quotes
var quotes = <?php echo json_encode($tabArray),';'; ?>
quoteArray = getRandomSentence(quotes);
displayQuote(quoteArray);
// Gestion des events de l'ecriture
$('#typing').keyup(function() {
// Reset class
var correct = 0;
var elems = document.querySelectorAll(".qp");
for (i = 0; i < elems.length; ++i) {
elems[i].classList.remove("correct");
elems[i].classList.remove("incorrect");
}
// Ajout de la classe selon la valeur
var tabTyp = $(this).val().split('');
var elem = document.getElementsByClassName("qp");
for (i = 0; i < tabTyp.length; ++i) {
if(elem[i].innerHTML == tabTyp[i]) {
elem[i].classList.add("correct");
correct ++;
} else {
elem[i].classList.add("incorrect");
correct --;
}
}
if(elem.length == correct) {
quoteArray = getRandomSentence(quotes);
displayQuote(quoteArray);
score ++;
$('#score').text(score + " / 5");
if(score > 5) {
document.cookie = "finish="+new Date().getTime();
window.location.replace("../win.php");
}
}
});
});
function getRandomSentence(quotes) {
var idx = getRandomInt(quotes.length);
var splitSentece = quotes[idx];
return splitSentece.split('');
}
function displayQuote(array) {
$("#quote").html("");
$('#typing').val("");
var html;
for (i = 0; i < array.length; ++i) {
html = $("#quote").html();
$("#quote").html(html+"<span class='qp'>"+array[i]+"</span>");
}
}
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
</script> | true |
c6b2cc5811d99a2f0ec9e394c4821c94dee232d7 | PHP | Aurous/MySQLChat | /pages/register.php | UTF-8 | 1,995 | 2.578125 | 3 | [
"Apache-2.0"
] | permissive | <?PHP
if(isset($_POST['user']) and isset($_POST['email']) and isset($_POST['password']) and isset($_POST['retype_password']) and isset($_POST['submit'])){
if(!empty($_POST['user']) and !empty($_POST['email']) and !empty($_POST['password']) and !empty($_POST['retype_password'])){
if($_POST['password'] == $_POST['retype_password']){
$con = connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
$register = register($con, DB_LOGINTABLE, $_POST['user'], $_POST['email'], md5($_POST['password']));
$registerchat = registerchat($con, DB_FRIENDTABLE, $_POST['user']);
if($register == '1' and $registerchat == '1'){
$_SESSION['pages'] = 'login';
require 'pages/login.php';
exit();
}else{
if(isset($register)){
echo $register;
}
if(isset($registerchat)){
echo $registerchat;
}
}
}else{
$message = "Error";
}
}
}
if(isset($_POST['login'])){
$_SESSION['pages'] = 'login';
require 'pages/login.php';
exit();
}
?>
<html>
<head>
<?PHP require 'parts/strap.php';?>
</head>
<body>
<?PHP require 'parts/navbar.php';?>
<div class="container-fluid">
<h1>Register</h1>
<p><?PHP if(isset($register)){echo $register;} ?></p>
<form action="" method="POST" >
<div class=" col-lg-4 col-md-6 col-sm-9 col-xs-12">
<div class="form-group">
<label>Username:</label>
<input type="text" class="form-control " name="user" id="textbox"/>
</div>
<div class="form-group">
<label>Email:</label>
<input type="text" class="form-control" name="email" id="textbox"/>
</div>
<div class="form-group">
<label>Password:</label>
<input type="password" class="form-control" name="password" id="textbox"/>
</div>
<div class="form-group">
<label>Retype Password:</label>
<input type="password" class="form-control" name="retype_password" id="textbox"/>
</div>
<div class="form-group">
<input type="submit" name="submit" value="Submit" class="btn btn-default"/>
</div>
</div>
</form>
</div>
</body>
</html> | true |
6ee31810007e2369da34b6ae9670c3910135979d | PHP | brydzu/composer-patches | /src/Utils/DataUtils.php | UTF-8 | 1,776 | 2.75 | 3 | [
"MIT"
] | permissive | <?php
/**
* Copyright © Vaimo Group. All rights reserved.
* See LICENSE_VAIMO.txt for license details.
*/
namespace Vaimo\ComposerPatches\Utils;
class DataUtils
{
public function removeKeysByPrefix(array $data, $prefix)
{
return array_intersect_key(
$data,
array_flip(
array_filter(
array_keys($data),
function ($key) use ($prefix) {
return strpos($key, $prefix) !== 0;
}
)
)
);
}
public function walkArrayNodes(array $list, \Closure $callback)
{
$list = $callback($list);
foreach ($list as $key => $value) {
if (!is_array($value)) {
continue;
}
$list[$key] = $this->walkArrayNodes($value, $callback);
}
return $list;
}
public function getNodeReferencesByPaths(array &$data, array $paths)
{
$stack = array();
foreach ($paths as $path) {
$stack[] = array(array(&$data), explode('/', $path));
}
$result = array();
while ($item = array_shift($stack)) {
$segment = array_shift($item[1]);
foreach ($item[0] as &$node) {
if ($segment === null) {
$result[] = &$node;
} else {
if ($segment === '*') {
$stack[] = array(&$node, $item[1]);
} else if (isset($node[$segment])) {
$stack[] = array(array(&$node[$segment]), $item[1]);
}
}
unset($node);
}
}
return $result;
}
}
| true |
851f23d268ffd6a5240688474c535b7006cd2b74 | PHP | pokebrian/teste | /src/NerdHerd/HelloBundle/Controller/FormTestController.php | UTF-8 | 1,243 | 2.765625 | 3 | [
"MIT"
] | permissive | <?php
namespace NerdHerd\HelloBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use NerdHerd\HelloBundle\Entity\Product;
use Symfony\Component\HttpFoundation\Request;
class FormTestController extends Controller
{
public function newAction(Request $request)
{
// create a task and give it some dummy data for this example
$product = new Product();
//$product->setName('Product Name');
//$product->setDescription("Descriçaõ");
$form = $this->createFormBuilder($product)
->add('name', 'text')
->add('description', 'text')
->getForm();
if ($request->getMethod() == 'POST') {
$form->bindRequest($request);
//if ($form->isValid()) {
// perform some action, such as saving the task to the database
//var_dump($form);
$dados= $form->get('name')->getData() . " - " . $form->get('description')->getData();
return $this->render('NerdHerdHelloBundle:FormTest:produtoform.html.twig', array('dados' => $dados));
//}
}
// return $this->render('AcmeTaskBundle:Default:new.html.twig', array(
// 'form' => $form->createView(),
// ));
return $this->render('NerdHerdHelloBundle:FormTest:produtoform.html.twig', array('form' => $form->createView()));
}
}
?> | true |
e92675a1c0068a94abc2ede1643f74b104561b1d | PHP | mozartbrito/learning-php | /index.php | UTF-8 | 555 | 3.203125 | 3 | [] | no_license | <!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
$sobre_nome2 = 'Soares';
$nome = "Geovane";
$nascimento = '10/02/1998';
$sobre_nome = "$sobre_nome2 Fonseca da Silva";
/*echo $nome;
echo '<br />';
echo $nascimento;
echo '<br />';
echo $sobre_nome;*/
//esse é um comentário
/*
esse comentário é de
várias linhas de
texto e pode aumentar
*/
#outro tipo de comentário
?>
<p><?php echo $nome; ?></p>
<p><?php echo $sobre_nome ?></p>
<p><?php echo $nascimento ?></p>
</body>
</html> | true |
e8aff0642fba4d971a92a09f41197c81230a5c8a | PHP | ScriptSB/Community_coyote | /app/Services/Parser/Factories/AbstractFactory.php | UTF-8 | 2,528 | 2.78125 | 3 | [
"MIT"
] | permissive | <?php
namespace Coyote\Services\Parser\Factories;
use Illuminate\Http\Request;
use Illuminate\Container\Container as App;
use Illuminate\Contracts\Cache\Repository as Cache;
use Illuminate\Contracts\Auth\Factory as Auth;
abstract class AbstractFactory
{
const CACHE_EXPIRATION = 60 * 24 * 30; // 30d
/**
* @var App
*/
protected $app;
/**
* @var Request
*/
protected $request;
/**
* @var Cache
*/
protected $cache;
/**
* @var Auth
*/
protected $auth;
/**
* @var bool
*/
protected $enableCache = true;
/**
* @param App $app
*/
public function __construct(App $app)
{
$this->app = $app;
$this->cache = $app[Cache::class];
$this->request = $app[Request::class];
$this->auth = $app[Auth::class];
}
/**
* @param string $text
* @return string
*/
abstract public function parse(string $text) : string;
/**
* @param bool $flag
* @return $this
*/
public function setEnableCache($flag)
{
$this->enableCache = (bool) $flag;
return $this;
}
/**
* @return bool
*/
public function isCacheEnabled()
{
return $this->enableCache;
}
/**
* @return bool
*/
public function isSmiliesAllowed()
{
return $this->auth->check() && $this->auth->user()->allow_smilies;
}
/**
* @param $text
* @return string
*/
protected function cacheKey($text)
{
return 'text:' . class_basename($this) . md5($text);
}
/**
* @param string $text
* @return bool
*/
protected function isInCache($text)
{
return $this->enableCache && $this->cache->has($this->cacheKey($text));
}
/**
* @param string $text
* @return mixed
*/
protected function getFromCache($text)
{
return $this->cache->get($this->cacheKey($text));
}
/**
* Parse text and store it in cache
*
* @param $text
* @param \Closure $closure
* @return mixed
*/
public function cache($text, \Closure $closure)
{
/** @var \Coyote\Services\Parser\Container $parser */
$parser = $closure();
$key = $this->cacheKey($text);
$text = $parser->parse($text);
if ($this->enableCache) {
$this->cache->put($key, $text, self::CACHE_EXPIRATION);
}
$parser->detach();
return $text;
}
}
| true |
b0963b80d43096d4c370d71b279c5b1fab3a657e | PHP | Jeket/xml | /src/Xml/Xmlns/Xmlns.php | UTF-8 | 1,160 | 2.859375 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types=1);
namespace VeeWee\Xml\Xmlns;
/**
* @psalm-immutable
*/
final class Xmlns
{
private string $xmlns;
private function __construct(string $xmlns)
{
$this->xmlns = $xmlns;
}
/**
* @psalm-pure
*/
public static function xmlns(): self
{
return new self('http://www.w3.org/2000/xmlns/');
}
/**
* @psalm-pure
*/
public static function xml(): self
{
return new self('http://www.w3.org/XML/1998/namespace');
}
/**
* @psalm-pure
*/
public static function xsi(): self
{
return new self('http://www.w3.org/2001/XMLSchema-instance');
}
/**
* @psalm-pure
*/
public static function phpXpath(): self
{
return new self('http://php.net/xpath');
}
/**
* @psalm-pure
*/
public static function load(string $namespace): self
{
return new self($namespace);
}
public function value(): string
{
return $this->xmlns;
}
public function matches(Xmlns $other): bool
{
return $this->value() === $other->value();
}
}
| true |
d10e48d6f6cd7806b8f9a1d08d16bdde5766725f | PHP | jeansebastienh/xdtp | /Afdn/Xdebug/ExecutionNode/Decorator/Dot.php | UTF-8 | 2,046 | 2.734375 | 3 | [] | no_license | <?php
/**
* PHP execution node DOT decorator
*
* PHP version 5
*
* @category AfdnFramework
* @package Xdebug
* @author Jean-Sébastien H. <jeanseb@au-fil-du.net>
* @copyright 2011 AuFilDuNet http://www.au-fil-du.net
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
*/
require_once 'Afdn/Xdebug/ExecutionNode/Decorator.php';
/**
* Afdn_Xdebug_ExecutionNode_Decorator_Dot
*
* @category AfdnFramework
* @package Xdebug
* @author Jean-Sébastien H. <jeanseb@au-fil-du.net>
* @copyright 2011 AuFilDuNet http://www.au-fil-du.net
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
*/
class Afdn_Xdebug_ExecutionNode_Decorator_Dot implements Afdn_Xdebug_ExecutionNode_Decorator
{
const EDGE_STMT = '"%d" -> "%d" [label="%s" style="setlinewidth(2.0)" color="#AAAAFF"];';
const NOTE_STMT = '"%d" [label="%s"];';
/**
* @see Afdn_Xdebug_ExecutionNode_Decorator::decorate();
*
* @param Afdn_Xdebug_ExecutionNode $node
*
* @return string
*/
public function decorate(Afdn_Xdebug_ExecutionNode $node)
{
$before = 'digraph G {' . PHP_EOL;
$before .= 'rankdir=TB;' . PHP_EOL;
$before .= 'edge [labelfontsize=12];' . PHP_EOL;
$before .= 'node [shape=box, style=filled];' . PHP_EOL;
$after = '}';
return $before . $this->_decorate($node) . $after;
}
protected function _decorate(Afdn_Xdebug_ExecutionNode $node, $content = '', $percent = 1)
{
$content .= sprintf(self::NOTE_STMT, $node->getFunctionNumber(), $node->getFunctionName()) . PHP_EOL;
foreach ($node->getChildren() as $child) {
$pourcentage = ($child->duration()/$node->duration()) * $percent;
if ($pourcentage > 0.01) {
$content .= sprintf(self::EDGE_STMT, $node->getFunctionNumber(), $child->getFunctionNumber(), number_format($pourcentage * 100, 2) . "%") . PHP_EOL;
$content = $this->_decorate($child, $content, $pourcentage);
}
}
return $content;
}
} | true |
50d1207d3d55ea9af4f71dfe2d57fbd11dfdb363 | PHP | Mubiridziri/patterns | /Builder/Builder/CottageBuilder.php | UTF-8 | 796 | 2.984375 | 3 | [] | no_license | <?php
/**
* @project Patterns
* @author Yury Potapov on 17.10.2020.
*/
namespace App\Builder;
use App\Entity\House;
class CottageBuilder implements Builder
{
/**
* @var House
*/
private $house;
public function reset()
{
$this->house = new House();
}
public function buildWall()
{
$this->house->setHasWalls(8);
}
public function buildDoors()
{
$this->house->setHasDoors(3);
}
public function buildWindows()
{
$this->house->setHasWindows(4);
}
public function buildPool()
{
$this->house->setHasPool(true);
}
public function buildGarage()
{
$this->house->setHasGarage(1);
}
public function getResult(): House
{
return $this->house;
}
} | true |
5986982de9034f4a6965dabf02abd40f476f3cb3 | PHP | Nightzio/htmlPtech | /Auth_ldap.php | UTF-8 | 1,956 | 2.59375 | 3 | [] | no_license | <?php
require "constants.php";
session_start();
if(!empty($_POST)){
if ( isset( $_POST['username'] ) && isset( $_POST['password'] ))
{
$user = $_POST["username"];// timo.boll
$ldap_dn = $user."@sdis60.fr"; // timo.boll@pingpong.fr
$ldap_pwd = $_POST["password"];
//$ldap_DN = "DC=SDIS60,DC=FR";
//ini_set('display_errors', 1);
//ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Connexion au serveur LDAP
$conn = ldap_connect(LDAP_SERVER) or die("Impossible de se connecter au serveur LDAP.");
ldap_set_option($conn, LDAP_OPT_REFERRALS, 0);
ldap_set_option($conn, LDAP_OPT_PROTOCOL_VERSION, 3);
if ($conn) {
// LDAP
$ldapbind = ldap_bind($conn,$ldap_dn,$ldap_pwd);
if ($ldapbind) {
// Recherche AD
$filter ="(sAMAccountName=" .$user.")";
$attr = array("memberof","givenname","sn","mail","distinguishedname");
$result = ldap_search($conn,LDAP_DN,$filter,$attr) or exit ("impossible de rechercher dans le LDAP");
$entries = ldap_get_entries($conn,$result);
$memberof = $entries[0]['memberof'];
$givenname = $entries[0]['givenname'][0]." ".$entries[0]['sn'][0];// timo boll
echo "Connexion reussi pour ".$givenname. "<BR />";
echo "<BR>";
$isMember = false;
//nom du groupe dans l'AD
foreach($memberof as $group){
$groupNames = explode(",",$group);
$groupName = substr($groupNames[0],3);
if($groupName == DRONE_GROUP) $isMember = true;
}
if($isMember){
echo "vous êtes Membre du groupe ".DRONE_GROUP. " ! <a href='".PAGE_INDEX."'>Acces au Stream</a> ";
$_SESSION['username'] = $givenname;
$_SESSION['loggedin'] = true;
$_SESSION['message'] = "";
header('Location:'.PAGE_INDEX);
exit();
}
}
else
{
$_SESSION['message'] = "Identifiants Incorrects";
echo "Droits invalides !!";
header('Location:'.PAGE_LOGIN);
exit();
}
}
}
}
?> | true |
5d5a7666a1b2b0bad630dea6a76a1777a6a827ba | PHP | goksagun/pre-order-api | /src/Utils/StringHelper.php | UTF-8 | 1,008 | 3.390625 | 3 | [] | no_license | <?php
namespace App\Utils;
class StringHelper
{
/**
* Generate a more truly "random" alpha-numeric string.
*
* @param int $length
* @return string
*/
public static function random($length = 16): string
{
$string = '';
while (($len = strlen($string)) < $length) {
$size = $length - $len;
$bytes = random_bytes($size);
$string .= substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $size);
}
return $string;
}
/**
* Determine if a given string starts with a given substring.
*
* @param string $haystack
* @param string|array $needles
* @return bool
*/
public static function startsWith($haystack, $needles): bool
{
foreach ((array)$needles as $needle) {
if ('' !== $needle && substr($haystack, 0, strlen($needle)) === (string)$needle) {
return true;
}
}
return false;
}
} | true |
8cafaf70b561f3e53c9149d5ceeef2382dffd644 | PHP | crysfel/budgeting-app | /app/Http/Controllers/Api/AuthController.php | UTF-8 | 17,966 | 2.625 | 3 | [] | no_license | <?php
namespace App\Http\Controllers\Api;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Mail;
use App\Mail\RecoverPassword;
use Tymon\JWTAuth\Exceptions\JWTException;
use App\Http\Serializers\UserSerializer;
use App\User;
use App\Activity;
use GuzzleHttp\Client;
use Carbon\Carbon;
use Validator;
use JWTAuth;
use JWT;
use Log;
use URL;
use GeoIP;
use Config;
use Response;
class AuthController extends Controller
{
public function __construct(UserSerializer $userSerializer)
{
$this->userSerializer = $userSerializer;
$this->validations = [
'email' => 'required|email',
];
}
/**
* Login a user with email/password
*/
public function authenticate(Request $request)
{
$credentials = $request->only('email', 'password');
try {
// verify the credentials and create a token for the user
if (!$token = $this->guard()->attempt($credentials)) {
return response()->json([
'success'=> false,
'errors' => [
'Invalid credentials, please try again.'
]
], 401);
}
} catch (JWTException $e) {
// something went wrong
return response()->json([
'success'=> false,
'errors' => ['could_not_create_token']
], 500);
}
$user = User::where('email', $credentials['email'])->get()->first();
// if no errors are encountered we can return a JWT
return response()->json([
'success' => true,
'token' => $token,
'user' => $this->userSerializer->one($user, ['basic', 'full', 'private']),
]);
}
/**
* Register a new user with email/password
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function signup(Request $request)
{
// 1.- Validate the required fields
$validator = Validator::make($request->all(), [
'name' => 'required|min:3|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6',
]);
if ($validator->fails()) {
return response()->json([
'success'=> false,
'errors' => $validator->errors()->all()
], 400);
}
try{
// 2.- Get the location for the new user based on their IP
$geo = GeoIP::getLocation();
}catch(Exception $e){
$geo = [];
}
try {
//3.- Set the avatar URL from gravatar
$default = URL::to('/')."/images/avatar.png";
$gravatar = "https://www.gravatar.com/avatar/" . md5( strtolower( trim( $request->input('email') ) ) ) . "?d=" . urlencode( $default ) . "&s=400";
//4.- Create the user
$user = new User();
$user->fill([
'name' => $request->input('name'),
'password' => bcrypt($request->input('password')),
'image' => $gravatar,
'country' => $geo['country']
]);
$user->email = $request->input('email');
$user->latitude = $geo['lat'];
$user->longitude= $geo['lon'];
$user->postcode = $geo['postal_code'];
// $user->author = Config::get('app.is_new_user_author');
$user->save();
} catch (Exception $e) {
return Response::json([
'success' => false,
'errors' => ['User already exists.'],
], HttpResponse::HTTP_CONFLICT);
}
//5.- Create activity
$activity = new Activity();
$activity->fill([
'action' => 'signup',
'user_id' => $user->id,
'reference_type' => 'App\\User',
'reference_id' => $user->id
]);
$activity->save();
//6.- Authenticate
$token = JWTAuth::fromUser($user);
return response()->json([
'success' => true,
'token' => $token,
'user' => $this->userSerializer->one($user, ['basic', 'full', 'private']),
]);
}
/**
* Login with Facebook.
*/
public function facebook(Request $request)
{
$accessTokenUrl = 'https://graph.facebook.com/v2.9/oauth/access_token';
$graphApiUrl = 'https://graph.facebook.com/v2.9/me';
$params = [
'code' => $request->input('code'),
'client_id' => $request->input('clientId'),
'redirect_uri' => $request->input('redirectUri'),
'client_secret' => Config::get('jwt.facebook_secret')
];
$client = new Client();
// Step 1. get the access token.
if($request->input('accessToken')){
// 1.1 Get token from param. (Login from Mobile App)
$accessToken = [
'access_token' => $request->input('accessToken'),
'fields' => 'id,name,email,picture,gender'
];
}else{
// 1.2 Exchange authorization code for access token. (Login from web)
$accessToken = $client->get(
$accessTokenUrl,
['query' => $params]
)->getBody();
$accessToken = (array) json_decode($accessToken);
}
// Step 2. Retrieve profile information about the current user.
$profile = $client->get($graphApiUrl, ['query' => $accessToken])->getBody();
$profile = (array) json_decode($profile);
// Step 3a. If user is already signed in, then link accounts.
if ($request->header('Authorization'))
{
$user = User::where('facebook', $profile['id'])->first();
if ($user){
return response()->json([
'success' => false,
'errors' => ['There is already a Facebook account that belongs to you']
], 409);
}
$token = explode(' ', $request->header('Authorization'))[1];
$payload = (array) JWT::decode($token, Config::get('jwt.secret'), array('HS256'));
$user = User::find($payload['sub']);
$user->facebook = $profile['id'];
$user->name = $profile['name'];
$user->image = "https://graph.facebook.com/".$profile['id']."/picture?type=large";
$user->gender = studly_case($profile['gender']);
$user->author = Config::get('app.is_new_user_author');
$user->save();
return response()->json([
'success' => true,
'token' => JWTAuth::fromUser($user),
'user' => $this->userSerializer->one($user, ['basic', 'full', 'private']),
]);
}
// Step 3b. Create a new user account or return an existing one.
else
{
$user = User::where('facebook', $profile['id'])->first();
if ($user){
// User already exist in database, generate a new token to allow login
$user->playlists;
return response()->json([
'success' => true,
'token' => JWTAuth::fromUser($user),
'user' => $this->userSerializer->one($user, ['basic', 'full', 'private']),
]);
}else {
// Some users doesn't have email on facebook
// they use mobile phone number
if (!array_key_exists('email', $profile)) {
// If user doesn't have email on facebook
// we will create a fake email using the default domain
$profile['email'] = $profile['id'].'@'.Config::get('mail.default_domain');
}
$user = User::where('email', $profile['email'])->first();
// check if email exist and link accounts
if ($user){
//update data from facebook
$user->name = $profile['name'];
$user->image = "https://graph.facebook.com/".$profile['id']."/picture?type=large";
$user->gender = studly_case($profile['gender']);
$user->facebook = $profile['id'];
$user->save();
$user->playlists;
return response()->json([
'success' => true,
'token' => JWTAuth::fromUser($user),
'user' => $this->userSerializer->one($user, ['basic', 'full', 'private']),
]);
}
}
// If is a complete new user, get the GEO location
// and create a new user in database
try{
// Get the location for the new user based on their IP
$geo = GeoIP::getLocation();
}catch(Exception $e){
$geo = [];
}
$gender = '';
if (array_key_exists('gender', $profile)) {
$gender = studly_case($profile['gender']);
}
$user = new User;
$user->facebook = $profile['id'];
$user->email = $profile['email'];
$user->password = bcrypt(str_random(20)); //generate a random password
$user->name = $profile['name'];
$user->image = "https://graph.facebook.com/".$profile['id']."/picture?type=large";
$user->gender = $gender;
$user->country = $geo['country'];
$user->latitude = $geo['lat'];
$user->longitude= $geo['lon'];
$user->postcode = $geo['postal_code'];
$user->author = Config::get('app.is_new_user_author');
$user->save();
//create activity for signup
$activity = new Activity();
$activity->fill([
'action' => 'signup',
'user_id' => $user->id,
'reference_type' => 'App\\User',
'reference_id' => $user->id
]);
$activity->save();
return response()->json([
'success' => true,
'token' => JWTAuth::fromUser($user),
'user' => $this->userSerializer->one($user, ['basic', 'full', 'private']),
]);
}
}
/**
* Login with Twitter.
* THIS IS NOT SUPPORTED YET!
*/
public function twitter(Request $request)
{
$requestTokenUrl = 'https://api.twitter.com/oauth/request_token';
$accessTokenUrl = 'https://api.twitter.com/oauth/access_token';
$profileUrl = 'https://api.twitter.com/1.1/users/show.json?screen_name=';
$client = new GuzzleHttp\Client();
// Part 1 of 2: Initial request from Satellizer.
if (!$request->input('oauth_token') || !$request->input('oauth_verifier'))
{
$requestTokenOauth = new Oauth1([
'consumer_key' => Config::get('app.twitter_key'),
'consumer_secret' => Config::get('app.twitter_secret'),
'callback' => Config::get('app.twitter_callback')
]);
$client->getEmitter()->attach($requestTokenOauth);
// Step 1. Obtain request token for the authorization popup.
$requestTokenResponse = $client->post($requestTokenUrl, ['auth' => 'oauth']);
$oauthToken = array();
parse_str($requestTokenResponse->getBody(), $oauthToken);
// Step 2. Send OAuth token back to open the authorization screen.
return response()->json($oauthToken);
}
// Part 2 of 2: Second request after Authorize app is clicked.
else
{
$accessTokenOauth = new Oauth1([
'consumer_key' => Config::get('app.twitter_key'),
'consumer_secret' => Config::get('app.twitter_secret'),
'token' => $request->input('oauth_token'),
'verifier' => $request->input('oauth_verifier')
]);
$client->getEmitter()->attach($accessTokenOauth);
// Step 3. Exchange oauth token and oauth verifier for access token.
$accessTokenResponse = $client->post($accessTokenUrl, ['auth' => 'oauth'])->getBody();
$accessToken = array();
parse_str($accessTokenResponse, $accessToken);
$profileOauth = new Oauth1([
'consumer_key' => Config::get('app.twitter_key'),
'consumer_secret' => Config::get('app.twitter_secret'),
'oauth_token' => $accessToken['oauth_token']
]);
$client->getEmitter()->attach($profileOauth);
// Step 4. Retrieve profile information about the current user.
$profile = $client->get($profileUrl . $accessToken['screen_name'], ['auth' => 'oauth'])->json();
// Step 5a. Link user accounts.
if ($request->header('Authorization'))
{
$user = User::where('twitter', '=', $profile['id']);
if ($user->first())
{
return response()->json(['message' => 'There is already a Twitter account that belongs to you'], 409);
}
$token = explode(' ', $request->header('Authorization'))[1];
$payload = (array) JWT::decode($token, Config::get('app.token_secret'), array('HS256'));
$user = User::find($payload['sub']);
$user->twitter = $profile['id'];
$user->name = $user->name || $profile['screen_name'];
$user->save();
return response()->json(['token' => JWTAuth::fromUser($user)]);
}
// Step 5b. Create a new user account or return an existing one.
else
{
$user = User::where('twitter', '=', $profile['id']);
if ($user->first())
{
return response()->json(['token' => JWTAuth::fromUser($user->first())]);
}
$user = new User;
$user->twitter = $profile['id'];
$user->name = $profile['screen_name'];
$user->save();
return response()->json(['token' => JWTAuth::fromUser($user)]);
}
}
}
/**
* Forgot password, generates token and sends an email
* to update the password.
*/
public function forgot(Request $request) {
$validator = Validator::make($request->all(), $this->validations);
if ($validator->fails()) {
return response()->json([
'success'=> false,
'errors' => $validator->errors()->all(),
], 400);
}
$user = User::where('email', $request->input('email'))->get()->first();
if ($user) {
// Setting the recovery token
$user->recovery_token = str_random(50);
$user->recovery_sent_at = Carbon::now();
$user->save();
// Send email with token
Mail::to($user)->send(new RecoverPassword($user));
return response()->json([
'success' => true,
'message' => 'Please check your email, we will send you a link to update your password. It will only be valid for the next 6 hours.',
]);
}
return response()->json([
'success'=> false,
'errors' => [
'This user doesn\'t exist in our system, please make sure your spelling is correct.',
],
], 400);
}
/**
* Login the user by the recovery token, basically a login using
* email's token in case user forgot his password
*/
public function recover(Request $request, $token) {
$user = $this->userRepository->findUserByRecoveryToken($token);
if ($user) {
$sent_at = new Carbon($user->recovery_sent_at);
$sent_at->addHours(6);
$now = Carbon::now();
// Check if is valid
if ($sent_at >= $now) {
return response()->json([
'success' => true,
'token' => JWTAuth::fromUser($user),
'user' => $user,
]);
}
return response()->json([
'success' => false,
'errors' => [
'Your recovery link has expired. It\'s only valid for 6 hours. Try to recover your password again.',
],
], 401);
}
return response()->json([
'success' => false,
'errors' => ['User not found, seems like your recovery link is old. Try to recover your password again.'],
], 404);
}
/**
* Logs out the user
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function logout()
{
JWTAuth::invalidate(JWTAuth::getToken());
return response()->json(compact('success'));
}
/**
* Unlink provider.
* @return \Illuminate\Http\Response
*/
public function unlink(Request $request, $provider)
{
$user = User::find($request['user']['sub']);
if (!$user)
{
return response()->json(['message' => 'User not found']);
}
$user->$provider = '';
$user->save();
return response()->json(array('token' => JWTAuth::fromUser($user)));
}
}
| true |
9ca80d2d62f2c9267273b64bff00f597f301787d | PHP | szerko/Respond2 | /plugins/cart/process.php | UTF-8 | 1,662 | 2.828125 | 3 | [] | no_license | <?php
// load dao
include '../../global.php';
include 'dao/Product.php';
// create controller
class ProcessCart extends Actions
{
private $AuthUser;
function __construct($authUser){
parent::__construct();
$this->AuthUser = $authUser;
$this->Ajax = $this->GetPostData("Ajax"); /* check for any ajax calls */
if($this->Ajax=='product.add'){
$this->Add();
}
else if($this->Ajax=='product.remove'){
$this->Remove();
}
else if($this->Ajax=='product.get'){
$this->Get();
}
}
// adds a product
function Add(){
$pageUniqId = $this->GetPostData("PageUniqId");
$sku = $this->GetPostData("SKU");
$name = $this->GetPostData("Name");
$price = $this->GetPostData("Price");
$createdBy = $this->AuthUser->UserId;
$product = Product::Add($sku, $name, $price, $pageUniqId, $createdBy);
// creates a response object
$tojson = array (
"ProductUniqId" => $product->ProductUniqId
);
// encode to json
$encoded = json_encode($tojson);
die($encoded);
}
// removes a product
function Remove(){
}
// gets a list of products
function Get(){
$pageUniqId = $this->GetPostData("PageUniqId");
$products = Product::GetProductsByPageUniqId($pageUniqId);
$html = '';
while($row = mysql_fetch_array($products)){
$html=$html.'<tr data-productuniqid="'.$row['ProductUniqId'].'">'.
'<td>'.$row['SKU'].'</td>'.
'<td>'.$row['Name'].'</td>'.
'<td>$'.$row['Price'].'</td><td><a id="remove-product">Remove</a></td></tr>';
}
die($html);
}
}
$authUser = new AuthUser(); // get auth user
$authUser->Authenticate('All');
$p = new ProcessCart($authUser); // setup controller
?> | true |
c2c3db212159a1d3ad85eb61aa4f22585c5cfaa3 | PHP | sarmentof/CursoPHP7 | /operadores/exemplo-05.php | UTF-8 | 186 | 3.265625 | 3 | [] | no_license | <?php
###############
// Operadores
###############
// Space chip
$a = 50;
$b = 35;
var_dump($a <=> $b); // Caracteres "<=>" faz comparação do tipo Maior(-1)/Menor(1)/Igual(0)
?> | true |
0edeb47acc97ccd3e51410e60736df44cfc71a01 | PHP | CynthiaDanielaGG/Manejo-de-archivos-basico-HTML---PHP | /registro.php | UTF-8 | 345 | 2.828125 | 3 | [] | no_license | <?php
$mostrar=fopen('datos.txt','r');
while(!feof($mostrar))
{
$id=fgets($mostrar);
$nombre=fgets($mostrar);
$calificacion=fgets($mostrar);
if($id!=""){
echo "<br> ID: ".$id."<br>";
echo "<br> Nombre: ".$nombre."<br>";
echo "<br> calificacion: ".$calificacion."<br>";
}
}
?>
| true |
ab6307a7f9c38b7d2162b7516bad0cf2dbc80c98 | PHP | rahulyhg/happy-giraffe | /site/frontend/modules/community/models/CommunityQuestionForm.php | UTF-8 | 2,846 | 2.5625 | 3 | [] | no_license | <?php
/**
* Форма вопроса специалисту
*
* @property CommunityContent $post
* @property User $user
*/
class CommunityQuestionForm extends CFormModel
{
const FORUM_ID = 2;
const RUBRIC_TITLE = 'Вопросы будущих мам';
public $title;
public $text;
public $first_name;
public $email;
private $_post;
private $_user;
public function __construct()
{
$this->setScenario(Yii::app()->user->isGuest ? 'guest' : 'registered');
}
public function rules()
{
return array(
array('title, text', 'required'),
array('first_name, email', 'required', 'on' => 'guest'),
array('email', 'email'),
array('email', 'unique', 'className' => 'User', 'criteria' => array('condition' => 'deleted = 0'))
);
}
public function attributeLabels()
{
return array(
'title' => 'Тема вопроса',
'text' => 'Вопрос',
'first_name' => 'Имя',
'email' => 'E-mail',
);
}
public function getPost()
{
return $this->_post;
}
public function getUser()
{
return $this->_user;
}
public function save()
{
$this->_post = new CommunityContent();
$this->_post->attributes = $this->attributes;
$this->_post->rubric_id = $this->getRubric()->id;
$this->_post->type_id = CommunityContent::TYPE_QUESTION;
$question = new CommunityQuestion();
$question->attributes = $this->attributes;
$this->_post->question = $question;
if ($this->scenario == 'guest') {
$this->_user = new User();
$this->_user->attributes = $this->attributes;
} else
$this->_user = Yii::app()->user->model;
$this->_user->communityPosts = array($this->_post);
$success = $this->_user->withRelated->save(true, array('communityPosts' => array('question')));
if ($success && $this->scenario == 'guest')
Yii::app()->user->setState('newUser', array(
'id' => $this->_user->id,
'email' => $this->_user->email,
'first_name' => $this->_user->first_name,
));
return $success;
}
protected function getRubric()
{
$criteria = new CDbCriteria();
$criteria->compare('title', self::RUBRIC_TITLE);
$criteria->compare('community_id', self::FORUM_ID);
$rubric = CommunityRubric::model()->find($criteria);
if ($rubric !== null)
return $rubric;
$rubric = new CommunityRubric();
$rubric->title = 'Вопросы будущих мам';
$rubric->community_id = self::FORUM_ID;
return $rubric->save() ? $rubric : null;
}
} | true |
e8dacef2012b80f0b836b2d454e26da812de08c7 | PHP | hatake04/new-eastbury | /viewAllClasses.php | UTF-8 | 804 | 3 | 3 | [] | no_license | <?php
$query = "SELECT * FROM CLASSES;";
$result = mysqli_query($conn, $query);
if(mysqli_num_rows($conn) == 0)
{
echo("No classes found.");
}
else{
echo("<table><tr><td>CRN</td><td>Faculty ID</td><td>Course ID</td><td>Room ID</td><td>Semester ID</td><td>Class Section</td><td>Seats Available</td></tr>");
while($record = mysqli_fetch_assoc($result))
{
echo("<tr><td>".$record['CRN'] ."</td><td>". $record['Faculty_ID'] . "</td><td>" . $result['Course_ID'] . "</td><td>" . $result['Room_ID'] . "</td><td>" . $result['Semester_ID'] . "</td><td>" . $result['Class_Section'] . "</td><td>" . $result['Seats_Available'] . "</td></tr>");
}
echo("</table>");
}
mysqli_free_result($result);
mysqli_close($conn);
?>
| true |
c7c41a5cb7d5c816f76e9b5b990f24bdd563ba4f | PHP | jasontwong/modup | /modup/module/GoogleAnalytics/module.php | UTF-8 | 1,425 | 2.515625 | 3 | [] | no_license | <?php
class GoogleAnalytics
{
public function hook_admin_nav()
{
return array(
'Google Analytics' => array(
'Show report' => '<a href="/admin/module/GoogleAnalytics/data/">Show report</a>'
)
);
}
public function hook_admin_dashboard()
{
return array(
array(
'title' => 'Google Analytics',
'content' => $this->_admin_dashboard_overview()
)
);
}
public function hook_admin_module_page($page){}
private function _admin_dashboard_overview()
{
/* $uac = Doctrine_Query::create()
->select('COUNT(id)')
->from('UserAccount')
->fetchOne(array(), Doctrine::HYDRATE_ARRAY);
$ugc = Doctrine_Query::create()
->select('COUNT(id)')
->from('UserGroup')
->fetchOne(array(), Doctrine::HYDRATE_ARRAY);
$o = '
<ul>
<li>Total User Accounts: '.$uac['COUNT'].'</li>
<li>Total User Groups: '.$ugc['COUNT'].'</li>
</ul>';
return $o;*/
}
/*public function hook_user_perm()
{
return array(
'Hello, World' => array(
'can say hi'
),
'Goodbye, World' => array(
'can say bye'
)
);
}*/
}
?>
| true |
a10ea5b304a295168547488cb0d5bca226ac75e5 | PHP | devboyarif/laravel-repository-crud | /app/Http/Controllers/DoctorController.php | UTF-8 | 2,374 | 2.671875 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers;
use App\Models\Doctor;
use App\Repositories\Doctor\DoctorInterface;
use Illuminate\Http\Request;
class DoctorController extends Controller
{
protected $doctor;
public function __construct(DoctorInterface $doctor)
{
$this->doctor = $doctor;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$doctors = $this->doctor->all();
return view('doctor.index', compact('doctors'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('doctor.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->doctor->store($request->all());
session()->flash('success', 'Doctor Add');
return back();
}
/**
* Display the specified resource.
*
* @param \App\Models\Doctor $doctor
* @return \Illuminate\Http\Response
*/
public function show(Doctor $doctor)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\Doctor $doctor
* @return \Illuminate\Http\Response
*/
public function edit(Doctor $doctor)
{
return view('doctor.edit', compact('doctor'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\Doctor $doctor
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Doctor $doctor)
{
$this->doctor->update($request->all(), $doctor);
session()->flash('success', 'Doctor Update');
return redirect(route('doctor.index'));
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Doctor $doctor
* @return \Illuminate\Http\Response
*/
public function destroy(Doctor $doctor)
{
$this->doctor->delete($doctor);
session()->flash('success', 'Doctor Delete');
return redirect(route('doctor.index'));
}
}
| true |
9661e63e0c34e6a244fcff24eb41f209c633a456 | PHP | ludoliv/projet_olympiadeSI1A12B | /GestionBD_Android/user.php | UTF-8 | 2,514 | 2.59375 | 3 | [] | no_license | <?php
include '../BD/Interactions/Connexion.php';
$cnn = connect_database();
//Define some value
define("ACTION_LOGIN", "login");
define("RESULT_SUCCESS", 0);
define("RESULT_ERROR", 1);
define("RESULT_USER_EXISTS", 2);
//$action = $_POST["action"];
$action="login";
$result = RESULT_ERROR;
$jury=array();
if(isset($action))
{
$username = $_POST["username"];
$pwd = $_POST["password"];
// $username='Login';
// $pwd='MDP';
if($action==ACTION_LOGIN) //Action login
{
if(login($cnn, $username, $pwd))
{
try{
$result = RESULT_SUCCESS;
$listeGrp=array();
$listeHeure=array();
$relation=array();
//Login success + envoi bd
$sql = 'SELECT DISTINCT * FROM GROUPE NATURAL JOIN JUGE NATURAL JOIN JURY NATURAL JOIN HEURE where login_="'.$username.'" and password_="'.$pwd.'"order by hDeb;';
$res = $cnn->query($sql);
while ($row = $res->fetch()) {
array_push($listeGrp, array('NumGroupe'=>$row[2],"NomProj"=>$row[4],"Lycee"=>$row[5],"image_Projet"=>$row[6], "numSalle"=>$row[3]));
array_push($relation, array('NumJury'=>$row[1],'NumGroupe'=>$row[2],'idHeure'=>$row[0]));
array_push($listeHeure, array('idHeure'=>$row[0],'hDeb'=>$row[9],'hFin'=>$row[10]));
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
else
{
//login fail
$result = RESULT_ERROR;
}
}
}
//Print result as json
echo json_encode(array('result' => $result,"Jury"=>$jury,"Groupe"=>$listeGrp,"Heures"=>$listeHeure,"relation"=>$relation));
function insertUser($cnn, $username, $pwd)
{
$query = "INSERT INTO JURY(login_, password_) VALUES(?, ?)";
$stmt = $cnn->prepare($query);
$stmt->bindParam(1, $username);
$stmt->bindParam(2, $pwd);
$stmt->execute();
}
function isExistUser($cnn, $username)
{
$query = "SELECT * FROM JURY WHERE login_ = ?";
$stmt = $cnn->prepare($query);
$stmt->bindParam(1, $username);
$stmt->execute();
$rowcount = $stmt->rowCount();
//for debug
//var_dump($rowcount);
return $rowcount;
}
function login($cnn, $username, $pwd)
{
global $jury;
$query = "SELECT * FROM JURY WHERE login_ = ? AND password_ = ?";
$stmt = $cnn->prepare($query);
$stmt->bindParam(1, $username);
$stmt->bindParam(2, $pwd);
$stmt->execute();
while($row=$stmt->fetch()){
$jury=array("id"=>$row[0],"Login"=>$row[1],"pwd"=>$row[2]);
}
$rowcount = $stmt->rowCount();
//for debug
//var_dump($rowcount);
return $rowcount;
}
| true |
f59d99c52a47922a2002fa1aec3a30c10ef43ae4 | PHP | sanmark/quotesharp-api | /app/butlers/SessionButler.php | UTF-8 | 261 | 2.515625 | 3 | [] | no_license | <?php
class SessionButler
{
public static function setOrganization ( $organization )
{
return Session::set ( SESSION_ORGANIZATION , $organization ) ;
}
public static function getOrganization ()
{
return Session::get ( SESSION_ORGANIZATION ) ;
}
}
| true |
5d9cbe8c8d6c0831340a663b37522866b70244f1 | PHP | baptistechev/L3-Projet-ComplexeSportif- | /html/score.php | UTF-8 | 4,680 | 2.578125 | 3 | [] | no_license | <?php
if(isset($_POST['up'])){
foreach ($_POST as $k => $v) {
if($k != 'up' && $k!='next'){
$vals = explode("_", $k);
if($vals[0] == "format"){
$pouls=$em->getRepository('Poule')->findBy(array(
'id' => $vals[1]
));
$pouls[0]->setFormat($v);
$em->persist($pouls[0]);
}elseif($vals[0] == "score"){
$match=$em->getRepository('MatchPoule')->findBy(array(
'equipe1' => $vals[1],
'equipe2' => $vals[2],
'poule' => $vals[3]
));
$match[0]->setScore($v);
$em->persist($match[0]);
}else{
$match=$em->getRepository('MatchPoule')->findBy(array(
'equipe1' => $vals[1],
'equipe2' => $vals[2],
'poule' => $vals[3]
));
$match[0]->setTerrain($v);
$em->persist($match[0]);
}
}
}
$em->flush();
}
$poules=$em->getRepository('Poule')->findBy(array(
'tournoi' => $_GET['id'],
'tour' => $tournoi->getTour()
));
?>
<form method="post" action="gestion.php?id=<?php echo $tournoi->getId();?>"><button id="nextTour" name='next' value="1">Tour suivant</button></form>
<form method="post" action="gestion.php?id=<?php echo $tournoi->getId();?>"><button id="fin" name='fin' value="1">Terminer le tournoi</button></form>
<h2>Scores</h2>
<div class="content">
<nav class="gauche">
<?php
$poules=$em->getRepository('Poule')->findBy(array(
'tournoi' => $tournoi->getId()
));
foreach ($poules as $p) {
echo sprintf("<a href='#%d'>%s</a>",$p->getId(),$p->getNom());
}
?>
</nav>
<section class="droite">
<form action="gestion.php?id=<?php echo $_GET['id']; ?>" method="post">
<?php
foreach ($poules as $p) {
echo sprintf("<article id='%d'>
<h3>%s <input type='text' placeholder='Format des matchs' name='format_%d' value='%s'></h3>
<br />
<table>
<tr>
<th>Match</th>
<th>Terrain</th>
<th>Score</th>
</tr>",$p->getId(),$p->getNom(), $p->getId(),$p->getFormat());
$matchs=$em->getRepository('MatchPoule')->findBy(array(
'poule' => $p->getId()
));
foreach ($matchs as $m) {
echo sprintf("<tr>
<td>%s VS %s</td>
<td><input type='text' class='terrain' name='terrain_%s_%s_%d' value='%s'</td>
<td><input type='text' class='score' name='score_%s_%s_%d' value='%s'></td>
</tr>",
$m->getEquipe1()->getNom(), $m->getEquipe2()->getNom(),$m->getEquipe1()->getNom(), $m->getEquipe2()->getNom(),$m->getPoule()->getId(), $m->getTerrain(),$m->getEquipe1()->getNom(), $m->getEquipe2()->getNom(),$m->getPoule()->getId(),$m->getScore());
}
echo "</table></article>";
}
?>
<input type="submit" name="up" id="maj" value="Mettre à jour" />
</form>
</section>
</div> | true |
212ea8ee9f452ff9c1a5ca203bd965ce11e09a49 | PHP | norazmira/clinic-appointment-Rabbitmq | /hospitalApp/src/publisher.php | UTF-8 | 3,011 | 2.671875 | 3 | [] | no_license | <?php
require dirname(__DIR__) . '/vendor/autoload.php';
include_once 'conn.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
$host = 'spider.rmq.cloudamqp.com';
$port = 5672;
$user = 'ydjtkfhg';
$pass = 'SnRM9CiwuIasm1rIDD72gaqsFtsNa5zI';
$vhost = 'ydjtkfhg';
$exchange = 'hospital-exchange'; //exchage name
//this is the exchange types that we can use
// amq.direct
// amq.fanout
//amq.headers
//amq.match
// amq.rabbitmq.trace
// amq.topic
$queue = 'hospitalq'; //can be any name we want (its the queue name)
$connection = new AMQPStreamConnection($host, $port, $user, $pass, $vhost);//we create a connection to broker using default TCP
$channel = $connection->channel(); //create a channel, on top of TCP, we can create as many channel as we want, for now just create 1 channel
/*
The following code is the same both in the consumer and the producer.
In this way we are sure we always have a queue to consume from and an
exchange where to publish messages.
*/
/*
name: $queue
passive: false
durable: true // the queue will survive server restarts
exclusive: false // the queue can be accessed in other channels
auto_delete: false //the queue won't be deleted once the channel is closed.
*/
$channel->queue_declare($queue, false, true, false, false);
/*
name: $exchange
type: direct
passive: false
durable: true // the exchange will survive server restarts
auto_delete: false //the exchange won't be deleted once the channel is closed.
*/
$channel->exchange_declare($exchange, 'direct', false, true, false);
//new component introduced in rabbit (differ from jms, only have 3 components, pqc), rabbit use AMQP (advance messaging queing protocol). the publisher always send the message to exchange, and the queue bind to that exchage
$channel->queue_bind($queue, $exchange);
//queue is binded to the exchange in oder to receive those messages
$sql = "SELECT * FROM appointmentstatus";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
$messageBody = json_encode([
'appointmentid' => $row["appointmentid"],
'patient_ic' => $row["patient_ic"],
'patient_name' => $row["patient_name"],
'patient_phone' => $row["patient_phone"],
'dr_name' => $row["dr_name"],
'appointment_date' => $row["appointment_date"],
'appointment_time' => $row["appointment_time"],
'status' => $row["status"],
]);
$message = new AMQPMessage($messageBody, [
'content_type' => 'application/json',
'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT,
]);
$channel->basic_publish($message, $exchange);
//just displaya
$body = json_decode($messageBody);
echo $messageBody;
}
} else {
echo "0 results";
}
$conn->close();
// echo 'Finished publishing to queue: ' . $queue . PHP_EOL;
$channel->close();
$connection->close();
| true |
97299d0b69206ca0fc9cf91362ebde29521a3f23 | PHP | danleuter/Peter-Mckinnon-kal | /assets/dashboard/create.php | UTF-8 | 4,399 | 2.515625 | 3 | [] | no_license | <?php
require('../../config/config.php');
require('../../config/db.php');
if(isset($_POST['submit1'])){
// Get form data text
$title = mysqli_real_escape_string($conn, $_POST['art_title']);
$desc = mysqli_real_escape_string($conn, $_POST['art_desc']);
$body = mysqli_real_escape_string($conn, $_POST['art_content']);
$author = mysqli_real_escape_string($conn, $_POST['art_author']);
// Get form data files
$image = mysqli_real_escape_string($conn, $_FILES['art_image']['name']);
$image_tmp = $_FILES['art_image']['tmp_name'];
move_uploaded_file($image_tmp, "assets/images/$image");
$query = "INSERT INTO posts (art_title, art_author, art_desc, art_content, art_image, art_status) VALUES('$title', '$author', '$desc', '$body', '$image', 1)";
if(mysqli_query($conn, $query)){
header('Location: '.ROOT_URL_ADMIN.'');
} else {
echo 'ERROR: '. mysqli_error($conn);
}
}
include('../inc/profile.inc.php');
// Free Result
mysqli_free_result($result);
// Close Connection
mysqli_close($conn);
if(isset($_POST['submit2'])){
//Get form data
$title = mysqli_real_escape_string($conn, $_POST['art_title']);
$body = mysqli_real_escape_string($conn, $_POST['art_content']);
$desc = mysqli_real_escape_string($conn, $_POST['art_desc']);
$author = mysqli_real_escape_string($conn, $_POST['art_author']);
$image = mysqli_real_escape_string($conn, $_FILES['art_image']['name']);
$image = mysqli_real_escape_string($conn, $_FILES['art_image']['name']);
$image_tmp = $_FILES['art_image']['tmp_name'];
move_uploaded_file($image_tmp, "assets/images/$image");
$query = "INSERT INTO posts (art_title, art_author, art_desc, art_content, art_image, art_status) VALUES('$title', '$author', '$desc', '$body', '$image', 2)";
if(mysqli_query($conn, $query)){
header('Location: '.ROOT_URL_ADMIN.'');
} else {
echo 'ERROR: '. mysqli_error($conn);
}
}
include("../inc/header_dashboard.php");
include('../inc/navbar.php');
?>
<form class="create-article" method="post" action="<?php $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">
<div class="article-editor text bg-primary mb-3">
<!-- <div class="card-header">What's going on?</div> -->
<div class="card-body">
<h6 class="card-title"><label>Title</label>
<input type="text" class="form-control" name="art_title" placeholder="Title"/></h6>
<h6 class="card-title"><label>Description</label>
<input type="text" class="form-control" name="art_desc" placeholder="Short Description"/></h6>
<h6 class="card-title"><label>Author</label>
<input type="text" class="form-control" name="art_author" placeholder="Peter Mckinnon"/></h6>
<h6 class="card-title"><label>Category</label>
<input type="text" class="form-control" name="art_category" placeholder="Category"/></h6>
<!-- dito bugs -->
<h6 class="card-title"><label>Upload Thumbnail</label>
<div class="input-group-append"><input class="input-group-text" type="file" name="art_image">
</div></h6>
<!-- dito bugs -->
<hr class="my-4">
<h6 class="card-title"><label>Content</label></h6>
<textarea class="text-primary" id="editor" name="art_content" placeholder="Some quick example text to build on the card title and make up the bulk of the card's content."></textarea>
<hr class="my-4">
<input type="submit" name="submit1" value="Publish Now" class="btn btn-outline-success"/>
<input type="submit" name="submit2" value="Save to Draft" class="btn btn-outline-info"/>
<button type="button" class="btn btn-outline-danger">Cancel</button>
</div>
</div>
</form>
<script>
var editor = new Jodit('#editor');
editor.value = '';
// $('textarea').each(function () {
// var editor = new Jodit(this);
// editor.value = '<p>start</p>';
// });
</script>
</body>
</html> | true |
c3d8d2803a6910693f9d8e841cdabf2ba9c62bac | PHP | sneha2245/online-chatting-system | /chatcontentprocess.php | UTF-8 | 891 | 2.53125 | 3 | [] | no_license | <?php
if(sizeof($_POST)>0){
$servername="localhost";
$username="root";
$password="";
$dbName="chatting-system";
$port="3308";
//var_dump($_POST);
$sen=$_POST["sender"];
$rev=$_POST["receiver"];
if($_POST["content"]==null){
return 0;
}else{
$text=$_POST["content"];
$contentQuery="insert into `chat_content` (`senderId`,`receiverId`,`content`,`current_time`) values ('".$sen."','".$rev."','".$text."',CURRENT_TIMESTAMP)";
}
$conn = mysqli_connect($servername, $username, $password, $dbName, $port);
/*
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($conn->query($contentQuery) === TRUE) {
// echo "New record created successfully";
} else {
echo "Error: " . $contentQuery . "<br>" . $conn->error;
}
$conn->close();
*/
}
?> | true |
9ed60d2f922595713d921057c97ae7ff011a03d4 | PHP | xseduard/FestCar | /app/Models/PagoRelRuta.php | UTF-8 | 1,242 | 2.65625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Models;
use Eloquent as Model;
use Illuminate\Database\Eloquent\SoftDeletes;
/**
* Class PagoRelRuta
* @package App\Models
* @version June 25, 2017, 8:35 pm COT
*/
class PagoRelRuta extends Model
{
use SoftDeletes;
public $table = 'pago_rel_rutas';
protected $dates = ['deleted_at'];
public $fillable = [
'pago_id',
'ruta_id',
'valor_final',
'cantidad_viajes',
'user_id'
];
/**
* Estos atributos son casteados en su tipo nativo.
*/
protected $casts = [
'pago_id' => 'integer',
'ruta_id' => 'integer',
'user_id' => 'integer'
];
/**
* Reglas de Validacón
*/
public static $rules = [
];
/**
* Relaciones entre Modelos
*/
/*
public function modelo(){
return $this->belongsTo('App\Models\Modelo');
}
*/
public function ruta(){
return $this->belongsTo('App\Models\Ruta');
}
public function pago(){
return $this->belongsTo('App\Models\Pago');
}
/**
* Funciones Especiales
*/
public function getTotalAttribute()
{
return $this->cantidad_viajes * $this->valor_final;
}
}
| true |
a130ad65dcdef7f5ec08cc903878001495024095 | PHP | nunoluciano/uxcl | /public_html/modules/openid/class/UpdateCert.php | UTF-8 | 4,303 | 2.625 | 3 | [] | no_license | <?php
/**
* Update Cert File.
* @author Original author: Kisara (http://www.kisara-s.com/)
* @version $Rev$
* @link $URL$
*/
class UpdateCert
{
function download_convert_cert($crt, $txt)
{
$url = 'http://mxr.mozilla.org/seamonkey/source/security/nss/lib/ckfw/builtins/certdata.txt?raw=1';
$parsed_url = parse_url($url);
if (!isset($parsed_url['port'])) {
$parsed_url['port'] = 80;
}
//if (!is_file($txt)) {
$path_and_query = $parsed_url['path'];
if ($parsed_url['query'] != '') {
$path_and_query .= '?' . $parsed_url['query'];
}
$request_header = 'GET ' . $path_and_query . ' HTTP/1.0' . "\x0D\x0A";
$request_header .= 'Host: ' . $parsed_url['host'] . "\x0D\x0A";
$request_header .= 'User-Agent: mk-ca-bundle.php' . "\x0D\x0A";
$fp_sock = fsockopen($parsed_url['host'], $parsed_url['port'], $errno, $errstr, 15);
if (!$fp_sock) {
return false;
}
fwrite($fp_sock, $request_header."\x0D\x0A");
$code = fgets($fp_sock, 4096);
if (!preg_match('/\s(\d{3})\s/', $code, $match) || $match[1] != '200') {
return false;
}
while (!feof($fp_sock)) {
$line = fgets($fp_sock, 4096);
if ($line == "\x0D\x0A") {
break;
}
}
// Content
$fpw = fopen($txt, 'wt');
while (!feof($fp_sock)) {
fwrite($fpw, fread($fp_sock, 4096));
}
fclose($fpw);
fclose($fp_sock);
//}
$fpw = fopen($crt, 'wt');
$currentdate = date(DATE_RFC822);
$crt_head = <<<EOT
##
## $crt -- Bundle of CA Root Certificates
##
## Converted at: $currentdate
##
## This is a bundle of X.509 certificates of public Certificate Authorities
## (CA). These were automatically extracted from Mozilla's root certificates
## file (certdata.txt). This file can be found in the mozilla source tree:
## '/mozilla/security/nss/lib/ckfw/builtins/certdata.txt'
##
## It contains the certificates in PEM format and therefore
## can be directly used with curl / libcurl / php_curl, or with
## an Apache+mod_ssl webserver for SSL client authentication.
## Just configure this file as the SSLCACertificateFile.
##
EOT;
fputs($fpw, $crt_head);
$caname = '';
$fpr = fopen($txt, 'rt');
while ($line = fgets($fpr)) {
if (preg_match('/\*\*\*\*\* BEGIN LICENSE BLOCK \*\*\*\*\*/', $line)) {
fputs($fpw, $line);
while ($line = fgets($fpr)) {
fputs($fpw, $line);
if (preg_match('/\*\*\*\*\* END LICENSE BLOCK \*\*\*\*\*/', $line)) {
break;
}
}
}
if (preg_match('/^#|^\s*$/', $line)) {
continue;
}
$line = rtrim($line);
if (preg_match('/^CVS_ID\s+\"(.*)\"/', $line, $match)) {
fputs($fpw, "# $match[1]\n");
}
if (preg_match('/^CKA_LABEL\s+[A-Z0-9]+\s+\"(.*)\"/', $line, $match)) {
$caname = $match[1];
}
if (preg_match('/^CKA_VALUE MULTILINE_OCTAL/', $line)) {
$data = '';
while ($line = fgets($fpr)) {
if (preg_match('/^END/', $line)) {
break;
}
$line = rtrim($line);
$octets = explode('\\', $line);
array_shift($octets);
foreach ($octets as $oct) {
$data .= chr(octdec($oct));
}
}
$pem = "-----BEGIN CERTIFICATE-----\n"
. chunk_split(base64_encode($data), 76, "\n")
. "-----END CERTIFICATE-----\n";
fputs($fpw, "\n$caname\n");
fputs($fpw, str_repeat('=', strlen($caname))."\n");
fputs($fpw, $pem);
}
}
fclose($fpw);
fclose($fpr);
unlink($txt);
return true;
}
}
| true |
cfe43a5d713b680b5426f73c63f46111d2549a32 | PHP | dnaber-de/wp-provisioner | /src/Wp/WpCliPlugin.php | UTF-8 | 7,724 | 3.140625 | 3 | [] | no_license | <?php # -*- coding: utf-8 -*-
namespace WpProvision\Wp;
use WpProvision\Command\Command;
use InvalidArgumentException;
use Exception;
/**
* Class WpCliPlugin
*
* @package WpProvision\Wp
*/
final class WpCliPlugin implements Plugin {
/**
* @var Command
*/
private $wp_cli;
/**
* @param Command $wp_cli
*/
public function __construct( Command $wp_cli ) {
$this->wp_cli = $wp_cli;
}
/**
* @link http://wp-cli.org/commands/plugin/activate/
*
* @param string|array $plugin The plugin slug or a list of slugs (e.g. 'multilingual-press', 'akismet' )
* @param array $options
* bool $options[ 'network' ] If set to TRUE, the plugin gets activated networkwide, default: false
* bool $options[ 'all' ] If set to TRUE, all plugins gets activated (regardless of $plugin parameter)
* string $option[ 'site_url' ] The site_url the plugin should be activated in, default: network main site
*
* @return bool
*/
public function activate( $plugin, array $options = [ ] ) {
if ( ! is_array( $plugin ) && ! is_string( $plugin ) ) {
// Todo
throw new InvalidArgumentException( "First argument \$plugin must be of type string or array" );
}
$arguments = [ 'plugin', 'activate' ];
if ( isset( $options[ 'all' ] ) && TRUE === $options[ 'all' ] ) {
$arguments[] = '--all';
} else {
if ( is_string( $plugin ) ) {
$arguments[] = $plugin;
} else {
$arguments = array_merge( $arguments, $plugin );
}
}
if ( isset( $options[ 'network' ] ) && TRUE === $options[ 'network' ] ) {
$arguments[] = '--network';
}
if ( isset( $options[ 'site_url' ] ) ) {
$arguments[] = "--url={$options[ 'site_url' ]}";
}
try {
// Todo: Maybe parse response
$this->wp_cli->run( $arguments );
return true;
} catch ( \Throwable $e ) {
// Todo: Wrap any possible Exception with a WpProvison\Exception
throw $e;
}
}
/**
* Deactivates plugins. Note that plugins only gets deactivated when the plugins activation status matches the
* given $option[ 'network' ] parameter.
* If in doubt, check $this->isActive( 'plugin' ) and $this->isActive( 'plugin', ['network' => TRUE ] ) for
* the plugins status.
*
* @link http://wp-cli.org/commands/plugin/deactivate/
*
* @param string|array $plugin The plugin slug or a list of slugs (e.g. 'multilingual-press', 'akismet' )
* @param array $options
* bool $options[ 'network' ] If set to TRUE, the plugin gets activated network wide, default: false
* bool $options[ 'all' ] If set to TRUE, all plugins gets activated (regardless of $plugin parameter), default: false
* bool $options[ 'uninstall' ] If set to TRUE, the plugin gets uninstalled after deactivation, default: false
* string $option[ 'site_url' ] The site_url the plugin should be deactivated, default: network main site
*
* @return bool
*/
public function deactivate( $plugin, array $options = [ ] ) {
if ( ! is_array( $plugin ) && ! is_string( $plugin ) ) {
// Todo
throw new InvalidArgumentException( "First argument \$plugin must be of type string or array" );
}
$arguments = [ 'plugin', 'deactivate' ];
if ( isset( $options[ 'all' ] ) && TRUE === $options[ 'all' ] ) {
$arguments[] = '--all';
} else {
if ( is_string( $plugin ) ) {
$arguments[] = $plugin;
} else {
$arguments = array_merge( $arguments, $plugin );
}
}
if ( isset( $options[ 'network' ] ) && TRUE === $options[ 'network' ] ) {
$arguments[] = '--network';
}
if ( isset( $options[ 'uninstall' ] ) && TRUE == $options[ 'uninstall' ] ) {
$arguments[] = '--uninstall';
}
if ( isset( $options[ 'site_url' ] ) ) {
$arguments[] = "--url={$options[ 'site_url' ]}";
}
try {
$this->wp_cli->run( $arguments );
return true;
} catch ( \Throwable $e ) {
// Todo: Wrap any possible Exception with a WpProvison\Exception
throw $e;
}
}
/**
* Is installed means that the plugin is available for activation
*
* @link http://wp-cli.org/commands/plugin/is-installed/
*
* @param string $plugin The plugin slug (e.g. 'multilingual-press', 'akismet' )
* @param array $options (No options supported at the moment)
*
* @return bool
*/
public function isInstalled( $plugin, array $options = [ ] ) {
if ( ! is_string( $plugin ) ) {
// Todo
throw new InvalidArgumentException( "First parameter \$plugin must be of type string" );
}
$arguments = [ 'plugin', 'is-installed', $plugin ];
try {
$this->wp_cli->run( $arguments );
return true;
} catch ( \Throwable $e ) {
// Todo: Wrap any possible Exception with a WpProvison\Exception
throw $e;
}
}
/**
* Check if a plugin is active. Method will return false if a plugin is active for network but the parameter
* $option[ 'network' ] is omitted or set to 'false'.
*
* @param string $plugin The plugin slug (e.g. 'multilingual-press', 'akismet' )
* @param array $options
* bool $options[ 'network' ] Check if the plugin is activated network wide, default: false
* string $options[ 'site_url' ] The URL of the site to check (default: the network main site, unused in single-site installs)
*
* @return bool
*/
public function isActive( $plugin, array $options = [ ] ) {
if ( ! is_string( $plugin ) ) {
// Todo
throw new InvalidArgumentException( "First parameter \$plugin must be of type string" );
}
$arguments = [ 'plugin', 'list', "--name={$plugin}", '--field=status' ];
if ( isset( $options[ 'site_url' ] ) ) {
$arguments[] = "--url={$options[ 'site_url' ]}";
}
try {
$result = trim( $this->wp_cli->run( $arguments ) );
if ( isset( $options[ 'network' ] ) && true === $options[ 'network' ] && 'active-network' === $result ) {
return true;
}
return 'active' === $result;
} catch ( \Throwable $e ) {
// Todo: Wrap any possible Exception with a WpProvison\Exception
throw $e;
}
}
/**
* Run plugin uninstall hooks and remove plugin files (if $option[ 'delete' ] is set to TRUE).
* Note: WP-CLI seems to have an issue, when a plugin is activated network-wide. To be save, you should check
* the plugins status and deactivate it explicitly before.
*
* Todo: Find out what that issue is
*
* @link http://wp-cli.org/commands/plugin/uninstall/
*
* @param string|array $plugin The plugin slug or a list of slugs (e.g. 'multilingual-press', 'akismet' )
* @param array $options
* bool $options[ 'deactivate' ] Deactivate plugin before uninstallation, default: TRUE
* bool $option[ 'delete' ] Deletes files after uninstallation , default: false
* string $option[ 'site_url' ] The site_url the uninstall routines should run in, default: network main site
*
* @return bool
*/
public function uninstall( $plugin, array $options = [ ] ) {
if ( ! is_array( $plugin ) && ! is_string( $plugin ) ) {
throw new InvalidArgumentException( "First argument \$plugin must be of type string or array" );
}
$arguments = [ 'plugin', 'uninstall' ];
if ( is_string( $plugin ) ) {
$arguments[] = $plugin;
} else {
$arguments = array_merge( $arguments, $plugin );
}
if ( ! isset( $options[ 'deactivate'] ) || false !== $options[ 'deactivate' ] ) {
$arguments[] = '--deactivate';
}
if ( ! isset( $options[ 'delete' ] ) || TRUE !== $options[ 'delete' ] ) {
$arguments[] = '--skip-delete';
}
if ( isset( $options[ 'site_url' ] ) ) {
$arguments[] = "--url={$options[ 'site_url' ]}";
}
try {
$result = $this->wp_cli->run( $arguments );
return true;
} catch ( \Throwable $e ) {
// Todo: Wrap any possible Exception with a WpProvison\Exception
throw $e;
}
}
}
| true |
e581a9839015790d0e96b70eba467bda4ae9b127 | PHP | zachzidan/shopping_cart_management | /DisplayProducts.php | UTF-8 | 3,288 | 2.984375 | 3 | [] | no_license | <?php
require_once("./config.php");
// First, include the common database access functions, if they're not already included
require_once("./common_db.php");
require_once("./session.php");
require_once("./login.php");
?>
<HTML>
<HEAD>
<TITLE> <?php echo $store_name; ?> - Products</TITLE>
</HEAD>
<BODY>
<?php include "header.php"; ?>
<div id="main">
<div class="col-md-2">
</div>
<!-- Variables are returned as $_GET["varname"] or $_POST["varname"] -->
<!-- Notice that the "<?= expression ?>" nugget to print an expression in the middle of HTML -->
<!-- won't work on all versions or installs of PHP and you may have to -->
<!-- use "<?php echo expression ?>" instead -->
<?php
// PHP/C++-style comments inside the PHP code
# Get a PDO database connection - see http://www.php.net/manual/en/book.pdo.php
$dbo = db_connect();
# Construct an SQL query as multiple lines for readability
$query = "SELECT Product.prod_id, Product.prod_name AS Product, Product.prod_desc AS Description, Product.prod_disp_cmd";
# Append to the $query string - note the required space
$query .= " FROM Product, CgPrRel";
$cat_id = 1;
# If a category id has been provided, set the category id for WHERE clause
if (isset($_GET["cat_id"])) {
$cat_id = $_GET["cat_id"];
}
$query .= " WHERE Product.prod_id = CgPrRel.cgPr_prod_id AND CgPr_cat_id = $cat_id";
# Sort on category name, not ID
$query .= " ORDER BY Product.prod_name";
# Run the query, returning a PDOStatement object - see http://www.php.net/manual/en/class.pdostatement.php
# Notice, this statement will throw a PDOException object if any problems - see http://www.php.net/manual/en/class.pdoexception.php
# There's another thing wrong with this query which we'll look at when we discuss SQL injection
try {
$statement = $dbo->query($query);
}
# Provide the exception handler - in this case, just print an error message and die,
# but see the provided default exception handler in common_db.php, which logs to the Apache error log
catch (PDOException $ex) {
echo $ex->getMessage();
die ("Invalid query");
}
?>
<!-- A fluid div which is responsive to the users screen and resizing-->
<div class='container-fluid'>
<!-- Creates a div which puts the items in a row when possible-->
<div class='row'>
<div class='col-md-7 '>
<!-- Mixed-up HTML and embedded bits of PHP from here on; read the tags carefully -->
<!-- Print the table headers, with 2px borders around cells so you can see the structure -->
<TABLE BORDER=2>
<TR>
<!-- First, print the column headers -->
<TH>ID</TH>
<TH>Product</TH>
<TH>Description</TH>
</TR>
<?php
# Print the rest of the table
# fetch() returns an array (by default, both indexed and name-associated) of result values for the row
while($row = $statement->fetch(PDO::FETCH_ASSOC)) { ?> <!-- see http://www.php.net/manual/en/pdostatement.fetch.php -->
<TR>
<TD><?php echo $row['prod_id'];?></TD>
<TD><a href="<?php echo $row['prod_disp_cmd'].'?prod_id='.$row['prod_id'];?>"><?php echo $row['Product'];?></a></TD>
<TD><?php echo $row['Description'];?></TD>
</TR>
<?php }
# Drop the reference to the database
$dbo = null;
?>
</TABLE>
</div>
</div>
</div>
</div>
<div id="footer">
<?php include("footer.php"); ?>
</div>
</BODY>
</HTML>
| true |
1e19fe94e173aeef08d1f4a1552b63175d2459ea | PHP | dip7501686040/notredamedelhi | /upload.php | UTF-8 | 1,419 | 2.875 | 3 | [] | no_license | <?php
// Include the database configuration file
include 'connect.php';
$statusMsg = '';
// File upload path
$targetDir = "uploads/";
$fileName = basename($_FILES["file"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
$category=$_POST['category'];
$type=$_POST['type'];
if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"])){
// Allow certain file formats
$allowTypes = array('jpg','png','jpeg','gif','pdf','mp4','MPG','mkv');
if(in_array($fileType, $allowTypes)){
// Upload file to server
if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
// Insert image file name into database
$insert = mysqli_query($conn,"INSERT into files (file_name,category,type, uploaded_on) VALUES ('".$fileName."','".$category."','".$type."', NOW())");
if($insert){
$statusMsg = "The file ".$fileName. " has been uploaded successfully.";
}else{
$statusMsg = "Error: " . $insert . "<br>" . mysqli_error($conn);;
}
}else{
$statusMsg = "Sorry, there was an error uploading your file.";
}
}else{
$statusMsg = 'Sorry, only JPG, JPEG, PNG, GIF, & PDF files are allowed to upload.';
}
}else{
$statusMsg = 'Please select a file to upload.';
}
// Display status message
echo $statusMsg;
?> | true |
4e9bcc51da3ed9e0cbe0d585c90df7c8e49a8ee5 | PHP | cloudinary/cloudinary_php | /src/Tag/JsConfigTag.php | UTF-8 | 1,591 | 2.578125 | 3 | [
"MIT"
] | permissive | <?php
/**
* This file is part of the Cloudinary PHP package.
*
* (c) Cloudinary
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Cloudinary\Tag;
use Cloudinary\ArrayUtils;
use Cloudinary\Configuration\Configuration;
/**
* Generates an HTML `<script/>` tag for JavaScript:
*
* ```
* <script type="text/javascript">
* $.cloudinary.config({"api_key":"key","cloud_name":"name"});
* </script>
* ```
*
* @api
*/
class JsConfigTag extends BaseTag
{
const NAME = 'script';
/**
* @var array $attributes An array of tag attributes.
*/
protected $attributes = [
'type' => 'text/javascript',
];
/**
* JsConfigTag constructor.
*
* @param Configuration $configuration The configuration instance.
*/
public function __construct($configuration = null)
{
parent::__construct();
if ($configuration === null) {
$configuration = Configuration::instance();
}
$params = [
'api_key' => $configuration->cloud->apiKey,
'cloud_name' => $configuration->cloud->cloudName,
'private_cdn' => $configuration->url->privateCdn,
'secure_distribution' => $configuration->url->secureCname, // secure_distribution is still used in v1
'cdn_subdomain' => $configuration->url->cdnSubdomain,
];
$this->setContent('$.cloudinary.config('.json_encode(ArrayUtils::safeFilter($params)).');');
}
}
| true |
0ad00e67862de36735d1ed32e9f0e60456a19584 | PHP | barbietunnie/guzzle-playground | /psr7-response.php | UTF-8 | 1,070 | 2.953125 | 3 | [] | no_license | <?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;
$client = new Client();
$response = $client->request(
'GET',
'http://jsonplaceholder.typicode.com/posts/1'
);
var_dump($response);
echo "Status code: " . $response->getStatusCode() . "\r\n";
echo "Reason Phrase: " . $response->getReasonPhrase() . "\r\n";
// Create a new response as a response object is immutable
$response = $response->withStatus(418);
echo "Status code: " . $response->getStatusCode() . "\r\n";
echo "Reason Phrase: " . $response->getReasonPhrase() . "\r\n";
// Create a non-existent response code
$response = $response->withStatus(419);
echo "Status code: " . $response->getStatusCode() . "\r\n";
echo "Reason Phrase: " . $response->getReasonPhrase() . "\r\n";
// Create a custom reason phrase
$response = $response->withStatus(419, 'Coffee is better than tea.');
echo "Status code: " . $response->getStatusCode() . "\r\n";
echo "Reason Phrase: " . $response->getReasonPhrase() . "\r\n";
| true |
269479dfd2559a0adc5b22967cc769f679cdfc88 | PHP | sgh1986915/php-oop-mvc-unbeatablecar | /checkoutfolder/shared/model/filetype/filetypefield.class.php | UTF-8 | 2,218 | 2.640625 | 3 | [] | no_license | <?php
class InvFiletypeField {
protected $value = '';
protected $settings = array();
protected $obj_tokenmanager = null;
public function __construct() {
$this->obj_tokenmanager = InvTokenManager::getInstance();
$this->sitesettings = SiteSettings::getInstance();
}
public function create($settings , $value){
$this->settings = $settings;
$this->setValue($value);
}
public function getEmptyFields() {
$fields = array();
if(isset($this->settings['fields'])){
foreach($this->settings['fields'] as $field){
switch($field['type']){
case 'selectivenavplacement':
case 'html':
case 'selectother':
// We don't allow these in repeating blocks
// selectothers behave flakily
break;
default:
$field['id'] = 'form_' . $this->settings['name'] . '_' . $field['name'];
$field['name'] = $field['name'] . '[]';
$field_obj = new InvFiletypeField;
$field_obj->create($field , '');
$fields[] = $field_obj;
unset($field_obj);
}
}
}
return $fields;
}
public function getFields($values) {
$fields = array();
if(isset($this->settings['fields'])){
foreach($this->settings['fields'] as $field){
$value = $values[$field['name']];
switch($field['type']){
case 'selectivenavplacement':
case 'html':
case 'selectother':
// We don't allow these in repeating blocks
// selectothers behave flakily
break;
default:
$field['id'] = 'form_' . $this->settings['name'] . '_' . $field['name'];
$field['name'] = $field['name'] . '[]';
$field_obj = new InvFiletypeField;
$field_obj->create($field , $value);
$fields[] = $field_obj;
unset($field_obj);
}
}
}
return $fields;
}
public function getValue() {
return $this->value;
}
public function setValue($value) {
$this->value = $value;
}
public function getHTML(){
if(isset($this->settings['type'])){
/*
if($this->settings['type'] == 'fieldgroup'){
$this->setFields();
}
*/
$path = MODEL_PATH . '/filetype/html/' . $this->settings['type'] . '.html';
if(is_file($path)){
include($path);
}
}
return '';
}
}
?> | true |
db4407d6432b7c1d0cf564102056ad44f9160e2d | PHP | hackeroM/webosen04 | /exit.php | UTF-8 | 2,699 | 2.5625 | 3 | [] | no_license | <?php
// Страница авторизации
# Функция для генерации случайной строки
function generateCode($length=6) {
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHI JKLMNOPRQSTUVWXYZ0123456789";
$code = "";
$clen = strlen($chars) - 1;
while (strlen($code) < $length) {
$code .= $chars[mt_rand(0,$clen)];
}
return $code;
}
# Соединямся с БД
include_once "bd_connect.php";
if(isset($_GET['log']))
{
# Вытаскиваем из БД запись, у которой логин равняеться введенному
$query = mysqli_query($connect,"SELECT user_id, user_hash FROM users WHERE user_id='".mysql_real_escape_string($_GET['log'])."' LIMIT 1");
$data = mysqli_fetch_assoc($query);
# Соавниваем пароли
# удаляем куки
setcookie("id", $data['user_id'], time()-999);
setcookie("hash", $data['user_hash'], time()-999);
# Переадресовываем браузер на страницу проверки нашего скрипта
header("Location: index.php"); exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Авторизация</title>
<link rel="stylesheet" href="css/style.css" media="screen" type="text/css" />
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Varela+Round">
<link rel="icon" href="http://vladmaxi.net/favicon.ico" type="image/x-icon">
<link rel="shortcut icon" href="http://vladmaxi.net/favicon.ico" type="image/x-icon">
</head>
<body>
<!-- vladmaxi top bar -->
<!--/ vladmaxi top bar -->
<div id="login">
<h2><span class="fontawesome-lock"></span>Вход в личный кабинет</h2>
<form action="login.php" method="POST">
<fieldset>
<p><label for="email">Логин или Email:</label></p>
<p><input type="email" name="login" id="email" value="Логин" onBlur="if(this.value=='')this.value='логин'" onFocus="if(this.value=='Логин')this.value=''"></p>
<p><label for="password">Пароль:</label></p>
<p><input type="password" name="password" id="password" value="Пароль" onBlur="if(this.value=='')this.value='Пароль'" onFocus="if(this.value=='Пароль')this.value=''"></p>
<p><input type="submit" value="ВОЙТИ"></p>
</fieldset>
</form>
</div>
</body>
</html> | true |