Skip to content

Instantly share code, notes, and snippets.

@xrogaan
Created December 24, 2010 14:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xrogaan/754291 to your computer and use it in GitHub Desktop.
Save xrogaan/754291 to your computer and use it in GitHub Desktop.
This will import the lua array into a php array
<div id="content">
<div id="error">
<?php
if (isset($this->errors)) {
echo "<p>Important :</p><p>";
echo implode('<br />', $this->errors);
echo "</p>";
}
?>
</div>
<p>Liste des objets en banque:</p>
<ul>
<?php
foreach ($this->character_vars['banknameitem'] as $id => $value) {
if ($this->character_vars['bankcountitem'][$id] == 0) {
echo "<li><em>rien</em></li>";
} else {
echo "<li>$value, nombre: ", $this->character_vars['bankcountitem'][$id], "</li>\n";
}
}
?>
</ul>
<p>Liste des objets dans l'inventaire:</p>
<ul>
<?php
foreach ($this->character_vars['nameitem'] as $id => $value) {
if ($this->character_vars['countitem'][$id] == 0) {
echo "<li><em>rien</em></li>";
} else {
echo "<li>$value, nombre: ", $this->character_vars['countitem'][$id], "</li>\n";
}
}
?>
</ul>
</div>
<html>
<head>
<title>Gnégnégné</title>
</head>
<body>
<?php
/**
* @param string $data must be the content of a lua file
* @param array $filter will make this function return only the variables listed in this array.
* If one variable is not found, it'll ignore it.
*/
function importVariables($data, $filter=array()) {
if (!is_array($data)) {
$data = explode("\n", $data);
}
$invariable = 0;
$registry = array();
for ($i=0; $i < count($data); $i++) {
if (!$invariable) {
if (strpos($data[$i], ' = {') !== false) {
$invariable = 1;
list($varname, $_) = explode(' = ',$data[$i]);
$registry[$varname] = array();
}
} else {
if ($data[$i][0] == ' ') {
list($rawid, $rawcontent) = explode(' = ', $data[$i]);
$id = trim($rawid, ' []');
if (strpos($rawcontent, '"') !== false) {
$content = substr(trim($rawcontent), 1, -2);
} else {
$content = trim(trim($rawcontent), ',');
}
$registry[$varname][$id] = $content;
}
if ($data[$i][0] == '}') {
$invariable = 0;
unset($varname, $content, $id, $rawid, $rawcontent);
}
}
}
if (!empty($filter)) {
$toreturn = array();
foreach((array) $filter as $name) {
if (array_key_exists($name, $registry)) {
$toreturn[$name] = $registry[$name];
}
}
$registry = $toreturn;
}
return $registry;
}
<?php
require 'libs/templates.php';
$tpl = new templates();
$tpl->addFile('_begin', 'header.tpl.php');
$tpl->addFile('_end', 'footer.tpl.php');
$tpl->addFile('index', 'index.tpl.php');
echo $tpl->render('index');
<div id="content">
<p>Vous pouvez soit <a href="./upload.php">envoyer votre fiche</a>, soit <a href="view_character.php">voir</a> celle qui est déjà présente.
</p>
</div>
<?php
/**
* @copyright Copyright (c) 2008, Bellière Ludovic
* @license http://opensource.org/licenses/mit-license.php MIT license
*/
class templates_exception extends Exception {}
/**
* @author Bellière Ludovic
* @copyright Copyright (c) 2008, Bellière Ludovic
* @license http://opensource.org/licenses/mit-license.php MIT license
*/
class templates {
/**
* File list
*
* @var array
*/
protected $_files = array();
/**
* Path to the templates files
*
* @var string
*/
static protected $_templatePath = './templates/';
protected $_options = array();
private $_escape = array('htmlentities');
public function __construct($template_path='',$options=array()) {
if (!empty($template_path)) {
static::$_templatePath = $template_path;
}
$this->_options = array_merge($this->_options,$options);
}
/**
* Return an option
*
* @param string $key search for $key in $_options
* @param string|null $default default value returned instead of empty data
* @return string|array
*/
function getOptions($key=null,$default=null) {
if (is_null($key)) {
return $this->_options;
} elseif (isset($this->_options[$key])) {
return $this->_options[$key];
} else {
return $default;
}
}
/**
* Return the current tempalte path
*
* @return string
*/
static public function getTemplatePath() {
return static::$_templatePath;
}
/**
* Add a template file
*
* @param string $tag Template id
* @param string $name Template filename.
* @return void
*/
public function addFile($tag,$name) {
$this->_files[$tag] = $name;
}
/**
* Process the templates files by $tag
* $tag can be an array for multi-templates page.
*
* @param array|string $tag
* @return string
*/
public function render($tag) {
ob_start();
try {
if (isset($this->_files['_begin'])) {
include_once $this->_file('_begin');
}
if (!is_array($tag)) {
include_once $this->_file($tag);
} else {
$tags = $tag;
unset($tag);
foreach ($tags as $tag) {
include_once $this->_file($tag);
}
}
if (isset($this->_files['_end'])) {
include_once $this->_file('_end');
}
} catch (templates_exception $e) {
ob_end_clean();
die ($e->getMessage());
} catch (Exception $e) {
ob_end_clean();
die('ex error: '.$e->getMessage());
}
$out = ob_get_clean();
return $out;
}
/**
* Check if the template file is readable and returns its name
*
* @param string $tag
* @return string
* @throw template_exception on missing file
*/
private function _file($tag) {
if (is_readable(static::$_templatePath.$this->_files[$tag])) {
return static::$_templatePath.$this->_files[$tag];
} else {
throw new templates_exception('The file <em>'.$this->_templatePath.$this->_files[$tag]. '</em> is not readable');
}
}
/**
* Return true if the given template file exists.
*
* @param string $file
* @return boolean
*/
static public function templateExists($file) {
if (!file_exists(static::$_templatePath . $file)) {
return false;
}
return true;
}
/**
* Used to set some functions who escape the content
*
* @param function $ref
*/
public function setEscape($ref) {
if (!in_array($ref,$this->_escape)) {
$this->_escape[] = $ref;
}
}
/**
* Used to remove a function from the pool of escape
*
* @param function $ref
* @param boolean $id
* @return boolean
*/
public function remEscape($ref,$id=false) {
if ($id && isset($this->_escape[$id])) {
unset($this->_escape[$id]);
return true;
} elseif (!$id) {
foreach ($this->_escape as $key => $val) {
if ($val == $ref) {
unset($this->_escape[$key]);
return true;
}
}
}
return false;
}
/**
* Force string $var escaping.
*/
public function escape($var) {
foreach($this->_escape as $fnct) {
if (in_array($fnct, array('htmlentities','htmlspecialchars'))) {
$var = call_user_func($fnct, $var, ENT_COMPAT, 'utf8');
} else {
$var = call_user_func($fnc, $var);
}
}
return $var;
}
public function assign($name,$data=null) {
try {
if (is_string($name)) {
self::__set($name, $data);
} elseif (is_array($name)) {
foreach ($name as $key => $value) {
self::__set($key,$value);
}
} else {
throw new templates_exception('Argument 2 passed to ' . __CLASS__ . '::' . __FUNCTION__ . ' must be a string or an array, ' . gettype($arguments) . ' given.');
}
} catch (templates_exception $e) {
throw $e;
}
return $this;
}
/**
* Remove all variable assigned via __set()
* @return void
*/
public function clearVars () {
$vars = get_object_vars($this);
foreach ($vars as $key => $value) {
if (substr($key, 0, 1) != '_' && !in_array($key,$this->_persistentVars)) {
unset($this->$key);
}
}
}
public function setGlobal($name,$data) {
self::__set($name,$data);
$this->_persistentVars[] = $name;
}
public function __set($name,$data) {
if ('_' != substr($name, 0, 1)) {
$this->$name = $data;
return;
}
throw new templates_exception('Setting private or protected class members is not allowed.',$this);
}
public function __unset($name) {
if ('_' != substr($name, 0, 1) && isset($this->$name)) {
unset($this->$name);
}
}
public function __isset($key) {
$strpos = strpos($key,'_');
if (!is_bool($strpos) && $strpos !== 0) {
return isset($this->$key);
}
return false;
}
}
<?php
require 'libs/templates.php';
require 'libs/validator.php';
$validator = new FormFieldUpload();
$validator->set_param('filename', '/.*\.lua/')
->set_param('moveto', './characters/')
->set_param('new_filename', 'current.lua');
$tpl = new templates();
if (isset($_POST['submitted'])) {
$x = $validator->validate($_FILES['svlua']);
if ($validator->has_error()) {
$tpl->errors = $validator->error;
} else {
header('Location: view_character.php');
}
}
$tpl->addFile('_begin', 'header.tpl.php');
$tpl->addFile('_end', 'footer.tpl.php');
$tpl->addFile('upload', 'upload.tpl.php');
echo $tpl->render('upload');
?>
<div id="content">
<div id="errors">
<?php
if (isset($this->errors)) {
echo "<p>L'envois du fichier à échoué :</p><p>";
echo implode('<br />', $this->errors);
echo "</p>";
}
?>
</div>
<form name="uppyupup" action="upload.php" method="post" enctype="multipart/form-data">
Votre SaveVariables.lua : <input type="file" name="svlua" />
<input type="submit" name="submitted" />
</form>
</div>
<?php
/*
* Author: Ludovic Bellière <xrogaan . gmail . com>
* License: New BSD
**/
class FormFieldUpload {
private $config = array(
'min_size' => 0,
'max_size' => 512000
);
public $error = array();
function __construct($params=array()) {
if (!is_array($params)) {
return false;
}
if (!empty($params)) {
array_merge($this->config, $params);
}
}
function set_param($key, $value, $force=false) {
if ($force) {
$this->config[$key] = $value;
} else {
if (!isset($this->config[$key])) {
$this->config[$key] = $value;
}
}
return $this;
}
public function has_error() {
if (count($this->error) > 0) {
return true;
} else {
return false;
}
}
/**
* @param $value doit être $_FILES
*/
public function validate ($value) {
if (is_uploaded_file($value['tmp_name'])) {
$this->_validate($value);
if (!$this->has_error() && (
array_key_exists('moveto', $this->config) &&
array_key_exists('new_filename', $this->config)
)) {
if (!file_exists($this->config['moveto'])) {
$this->error[] = "Le dossier de destination ({$this->config['moveto']}) n'existe pas.";
}
if (!is_writable($this->config['moveto'])) {
$this->error[] = "Impossible d'écrire dans le dossier de destination.";
}
if ($this->has_error()) {
return null;
}
move_uploaded_file($value['tmp_name'], $this->config['moveto'] . '/' . $this->config['new_filename']);
}
return $value;
} else {
switch ($value['error']) {
case UPLOAD_ERR_OK:
return $value;
case UPLOAD_ERR_INI_SIZE:
$this->error[] = "Le fichier téléchargé excède la taille de la variable <em>upload_max_filesize</em>, configurée dans le php.ini.";
break;
case UPLOAD_ERR_FORM_SIZE:
$this->error[] = "Le fichier téléchargé excède la taille de <strong>MAX_FILE_SIZE</strong>, qui a été spécifiée dans le formulaire HTML.";
break;
case UPLOAD_ERR_PARTIAL:
$this->error[] = "Le fichier n'a été que partiellement téléchargé.";
break;
case UPLOAD_ERR_NO_FILE:
if ( $this->required ) {
$this->error[] = "Aucun fichier n'a été téléchargé.";
}
break;
case UPLOAD_ERR_NO_TMP_DIR: // Introduit en PHP 4.3.10 et PHP 5.0.3.
$this->error[] = "Un dossier temporaire est manquant.";
break;
case UPLOAD_ERR_CANT_WRITE: // Introduit en PHP 5.1.0.
$this->error[] = "Échec de l'écriture du fichier sur le disque.";
break;
case UPLOAD_ERR_EXTENSION: // Introduit en PHP 5.2.0.
$this->error[] = "L'envoi de fichier est arrêté par l'extension.";
break;
default:
$this->error[] = "Unknow error : " . $value['error'];
}
return '';
}
}
protected function _validate($value) {
if (array_key_exists('max_size', $this->config) && $value['size'] > $this->config['max_size']) {
$this->error[] = "La taille du fichier est supérieure à la taille maximum autorisée qui est de {$this->config['max_size']} octets.";
return null;
}
if (array_key_exists('min_size', $this->config) && $value['size'] < $this->config['min_size']) {
$this->error[] = "La taille du fichier est inférieure à la taille minimum autorisée qui est de {$this->config['min_size']} octets.";
return null;
}
// Type
if (array_key_exists('content_type', $this->config) &&
!call_user_func_array($this->config['funcCheck'], array($this->config['content_types'], $value['type']))
)
{
$this->error[] = "Seuls les types de fichiers suivants sont autorisés : " .
(is_array($this->config['content_types']) ? implode(',',$this->config['content_types']) : $this->config['content_types']) .
". Vous avez donné : " . $value['type'];
return null;
}
// Nom de fichier
if (!array_key_exists('filename', $this->config)) {
if (!is_array($this->config['filename'])) {
$this->config['filename'] = (array) $this->config['filename'];
}
$match_found = false;
foreach ($this->config['filename'] as $filename) {
if (preg_match($filename, $value['name']) === 1) {
$match_found = true;
}
}
if (!$match_found) {
$this->error[] = "Le nom de fichier ne correspond pas à l'expression régulière de validation : " .
(count($this->config['filename']) > 1 ? implode(',', $this->content_types) : $this->filename);
return null;
}
}
return $value;
}
}
<?php
require 'libs/templates.php';
require 'libs/import_from_lua.php';
$tpl = new templates();
$tpl->addFile('_begin', 'header.tpl.php');
$tpl->addFile('_end', 'footer.tpl.php');
$tpl->addFile('character', 'character.tpl.php');
$errors = array();
if (!file_exists('characters/current.lua')) {
$errors[] = "Il n'existe actuellement aucun fichier sur lesquels je puis travailler. Peut-être devriez-vous en <a href=\"upload.php\">uploader</a> un ?";
}
if (empty($error) && !file_exists('characters/current.php')) {
$errors[] = "Un fichier lua a été trouvé, cependant ce dernier n'a jamais été travaillé. Nous le faisons actuellement, ce qui peu prendre un petit temps. Soyez patient !";
$character_vars = importVariables(htmlentities(file_get_contents('characters/current.lua'), ENT_NOQUOTES, 'UTF-8') , array('bankcountitem', 'banknameitem', 'countitem', 'nameitem'));
$exported_vars = "<?php\nreturn " . var_export($character_vars, true) . ';';
file_put_contents('characters/current.php', $exported_vars, LOCK_EX);
} else {
if (file_exists('characters/current.php')) {
$character_vars = include 'characters/current.php';
}
}
$tpl->errors = $errors;
$tpl->character_vars = $character_vars;
echo $tpl->render('character');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment