I need help with a PHP ToDo List. I have most of it working except for the check box to move it from a completed list to a still need to do list. here is the code I have so far:
For the edit screen:
%% views/header.html %%
<h1>{{$title}}</h1>
<div class='inputs'>
<form action="##todo/update##" method="post">
<input type="hidden" id="id" name="id" value="{{$todo['id']}}" />
<label for="description">Description:</label>
<input type="text" id="description" name="description" value="{{$todo ['description']}}" />
<label for="done">Done?:</label>
<input type="checkbox" id="done" name="done" value="1" />
<input type="submit" value="Update" />
<form>
</div>
<p><< Back</p>
%% views/footer.html %%
For the todo.inc file:
<?php
include_once "include/util.inc";
include_once "models/todo.inc";
function safeParam($arr, $index, $default) {
if ($arr && isset($arr[$index])) {
return $arr[$index];
}
return $default;
}
function get_view($params) {
$id = safeParam($params, 0, false);
if ($id === false) {
die("No todo id specified");
}
$todo = findToDoById($id);
if (!$todo) {
die("No todo with id $id found.");
}
// #formatter:off
renderTemplate(
"views/todo_view.inc",
array(
'title' => 'Viewing To Do',
'todo' => $todo
)
);
// #formatter:on
}
function get_list($params) {
$todos = findAllCurrentToDos();
$dones = findAllDoneToDos();
// #formatter:off
renderTemplate(
"views/index.inc",
array(
'title' => 'To Do List',
'todos' => $todos,
'dones' => $dones
)
);
// #formatter:on
}
function get_edit($params) {
$id = safeParam($params, 0, false);
if (!$id) {
die("No todo specified");
}
$todo = findToDoById($id);
if (!$todo) {
die("No todo found.");
}
// #formatter:off
renderTemplate(
"views/todo_edit.inc",
array(
'title' => 'Editing To Do',
'todo' => $todo
)
);
// #formatter:on
}
function post_add($params) {
if (!isset($_POST['description'])) {
die("no description given");
}
$description = htmlentities($_POST['description']);
addToDo($description);
redirectRelative("index");
}
function validate_present($elements) {
$errors = '';
foreach ($elements as $element) {
if (!isset($_POST[$element])) {
$errors .= "Missing $element\n";
}
}
return $errors;
}
function post_update($params) {
$errors = validate_present(array('id', 'description', 'done'));
if ($errors) {
die($errors);
}
$id = $_POST['id'];
$description = $_POST['description'];
$done = $_POST['done'];
updateToDo($id, $description, $done);
redirectRelative("todo/view/$id");
}
function get_delete($params) {
$id = safeParam($params, 0, false);
if (!$id) {
die("No todo specified");
}
$todo = findToDoById($id);
if (!$todo) {
die("No todo found.");
}
deleteToDo($id);
redirectRelative("index");
}
?>
Your error is in these two functions.
function validate_present($elements) {
$errors = '';
foreach ($elements as $element) {
if (!isset($_POST[$element])) {
$errors .= "Missing $element\n";
}
}
return $errors;
}
function post_update($params) {
$errors = validate_present(array('id', 'description', 'done'));
if ($errors) {
die($errors);
}
$id = $_POST['id'];
$description = $_POST['description'];
$done = $_POST['done'];
updateToDo($id, $description, $done);
redirectRelative("todo/view/$id");
}
You are attempting to validate that done exists in validate_present when called by post_update. done obviously cannot exists since it is not sent to the server when the checkbox is not checked. The $_POST does not even contain that variable, so it returns that element is missing (since it technically is). I would leave validate_present alone and change post_update as follows:
function post_update($params) {
$errors = validate_present(array('id', 'description'));
if ($errors) {
die($errors);
}
$id = $_POST['id'];
$description = $_POST['description'];
$done = (isset($_POST['done'])? 1 : 0);
updateToDo($id, $description, $done);
redirectRelative("todo/view/$id");
}
Related
I am using Moodle version 3.8.4+ and PHP version 7.2.33 . Today I noticed a strange issue when I was trying to send a message to students, the message was:
Coding error detected, it must be fixed by a programmer: Url parameters values can not be arrays! More information about this error
I purge all caches as the suggestion was on "more information" section but it did not work.
I run the same Moodle version and PHP version on non production environment with the debugging mode and then I got this error message:
Coding error detected, it must be fixed by a programmer: Url parameters values can not be arrays!
More information about this error
Debug info:
Error code: codingerror
Stack trace:
line 405 of /lib/weblib.php: coding_exception thrown
line 460 of /lib/weblib.php: call to moodle_url->params()
line 49 of /mod/reservation/messageselect.php: call to moodle_url->param()
Output buffer: Invalid array parameter detected in required_param(): messagebody
line 655 of /lib/moodlelib.php: call to debugging()
line 30 of /mod/reservation/messageselect.php: call to optional_param()
The messageselect.php file is this but I am not able to see any issues here:
require_once('../../config.php');
require_once($CFG->dirroot.'/message/lib.php');
$id = required_param('id', PARAM_INT);
$messagebody = optional_param('messagebody', '', PARAM_CLEANHTML);
$send = optional_param('send', '', PARAM_BOOL);
$preview = optional_param('preview', '', PARAM_BOOL);
$edit = optional_param('edit', '', PARAM_BOOL);
$returnto = optional_param('returnto', new moodle_url('/mod/reservation/view.php', array('id' => $id)), PARAM_LOCALURL);
$format = optional_param('format', FORMAT_MOODLE, PARAM_INT);
$deluser = optional_param('deluser', 0, PARAM_INT);
if (isset($id)) {
if (! $cm = get_coursemodule_from_id('reservation', $id)) {
error('Course Module ID was incorrect');
}
if (! $course = $DB->get_record('course', array('id' => $cm->course))) {
error('Course is misconfigured');
}
}
$url = new moodle_url('/mod/reservation/messageselect.php', array('id' => $id));
if ($messagebody !== '') {
$url->param('messagebody', $messagebody);
}
if ($send !== '') {
$url->param('send', $send);
}
if ($preview !== '') {
$url->param('preview', $preview);
}
if ($edit !== '') {
$url->param('edit', $edit);
}
if ($returnto !== '') {
$url->param('returnto', $returnto);
}
if ($format !== FORMAT_MOODLE) {
$url->param('format', $format);
}
if ($deluser !== 0) {
$url->param('deluser', $deluser);
}
$modulecontext = context_module::instance($cm->id);
$PAGE->set_url($url);
$PAGE->set_context($modulecontext);
require_login($course->id, false, $cm);
$coursecontext = context_course::instance($course->id);
$systemcontext = context_system::instance();
require_capability('moodle/course:bulkmessaging', $coursecontext);
if (empty($SESSION->reservation_messageto)) {
$SESSION->reservation_messageto = array();
}
if (!array_key_exists($id, $SESSION->reservation_messageto)) {
$SESSION->reservation_messageto[$id] = array();
}
if ($deluser) {
$idinmessageto = array_key_exists($id, $SESSION->reservation_messageto);
if ($idinmessageto && array_key_exists($deluser, $SESSION->reservation_messageto[$id])) {
unset($SESSION->reservation_messageto[$id][$deluser]);
}
}
if (empty($SESSION->reservation_messageselect[$id]) || $messagebody) {
$SESSION->reservation_messageselect[$id] = array('messagebody' => $messagebody);
}
$messagebody = $SESSION->reservation_messageselect[$id]['messagebody'];
$count = 0;
if ($data = data_submitted()) {
require_sesskey();
foreach ($data as $k => $v) {
if (preg_match('/^(user|teacher)(\d+)$/', $k, $m)) {
if (!array_key_exists($m[2], $SESSION->reservation_messageto[$id])) {
$returnfields = 'id,firstname,lastname,idnumber,email,mailformat,lastaccess, lang, maildisplay';
if ($user = $DB->get_record_select('user', "id = ?", array($m[2]), $returnfields)) {
$SESSION->reservation_messageto[$id][$m[2]] = $user;
$count++;
}
}
}
}
}
$strtitle = get_string('message', 'reservation');
$PAGE->navbar->add($strtitle);
$PAGE->set_title($strtitle);
$PAGE->set_heading($strtitle);
echo $OUTPUT->header();
// If messaging is disabled on site, we can still allow users with capabilities to send emails instead.
if (empty($CFG->messaging)) {
echo $OUTPUT->notification(get_string('messagingdisabled', 'message'));
}
if ($count) {
if ($count == 1) {
$heading = get_string('addedrecip', 'moodle', $count);
} else {
$heading = get_string('addedrecips', 'moodle', $count);
}
echo $OUTPUT->heading($heading);
}
if (!empty($messagebody) && !$edit && !$deluser && ($preview || $send)) {
require_sesskey();
if (count($SESSION->reservation_messageto[$id])) {
if (!empty($preview)) {
echo '<form method="post" action="messageselect.php" style="margin: 0 20px;">
<input type="hidden" name="returnto" value="'.s($returnto).'" />
<input type="hidden" name="id" value="'.$id.'" />
<input type="hidden" name="format" value="'.$format.'" />
<input type="hidden" name="sesskey" value="' . sesskey() . '" />
';
echo "<h3>".get_string('previewhtml')."</h3>";
echo "<div class=\"messagepreview\">\n".format_text($messagebody, $format)."\n</div>\n";
echo '<p align="center"><input type="submit" name="send" value="'.get_string('sendmessage', 'message').'" />'."\n";
echo '<input type="submit" name="edit" value="'.get_string('update').'" /></p>';
echo "\n</form>";
} else if (!empty($send)) {
$fails = array();
foreach ($SESSION->reservation_messageto[$id] as $user) {
if (!message_post_message($USER, $user, $messagebody, $format)) {
$user->fullname = fullname($user);
$fails[] = get_string('messagedselecteduserfailed', 'moodle', $user);
};
}
if (empty($fails)) {
echo $OUTPUT->heading(get_string('messagedselectedusers'));
unset($SESSION->reservation_messageto[$id]);
unset($SESSION->reservation_messageselect[$id]);
} else {
echo $OUTPUT->heading(get_string('messagedselectedcountusersfailed', 'moodle', count($fails)));
echo '<ul>';
foreach ($fails as $f) {
echo '<li>', $f, '</li>';
}
echo '</ul>';
}
echo '<p align="center">'.get_string('backtoparticipants').'</p>';
}
echo $OUTPUT->footer();
exit;
} else {
echo $OUTPUT->notification(get_string('nousersyet'));
}
}
echo '<p align="center">'.get_string("keepsearching").''.
((count($SESSION->reservation_messageto[$id])) ? ', '.get_string('usemessageform') : '').'</p>';
if ((!empty($send) || !empty($preview) || !empty($edit)) && (empty($messagebody))) {
echo $OUTPUT->notification(get_string('allfieldsrequired'));
}
if (count($SESSION->reservation_messageto[$id])) {
require_sesskey();
require("message.html");
}
$PAGE->requires->yui_module('moodle-core-formchangechecker',
'M.core_formchangechecker.init',
array(array(
'formid' => 'theform'
))
);
$PAGE->requires->string_for_js('changesmadereallygoaway', 'moodle');
echo $OUTPUT->footer();
```php
It looks like the massagebody param in the request that initiates this process is using array syntax, like ?messagebody[]=foo instead of ?messagebody=foo, so the error is in whatever page the request originated from. You can either try to figure out why that is and change it, or make a change to this messageselect.php file to flatten the parameter. To do that you would change this:
<?php
if ($messagebody !== '') {
$url->param('messagebody', $messagebody);
}
to this:
<?php
if ($messagebody !== '') {
if(is_array($messagebody))
{
$messagebody = array_shift($messagebody);
}
$url->param('messagebody', $messagebody);
}
However be aware that if the page is sending this parameter as an array, it is quite likely that others will be sent that way as well. Usually you would send parameters using array syntax so that multiple records can be processed in one request, so that messagebody[1] would correlate to format[1], messagebody[2] would correlate to format[2], and so on. The code in messageselect.php is clearly not expecting this. I would be interested to find out what the story is for the page that sends requests here.
I have this code:
public function getJccLineItem($id,$action)
{
$res = array();
$q = 'SELECT * FROM jcc_line_items jli,ipo_line_item ili ,line_items li
WHERE jli.line_item_id= ili.id and li.id = jli.line_item_id
and ili.dn_number_id in ( Select dn_number from ipo where project_id= '.$id.')';
$res = $this->db->query($q);
echo $this->db->last_query();
$jccLineItemArray = array();
echo $id;
print_r($res->result());
if($action == 'array')
{
foreach ( $res->result() as $key => $value) // The error comes in this line
{
$jccLineItemArray[ $value->id ] = $value->item_description;
}
$res = $jccLineItemArray;
}
else
{
$res = $res->result();
}
return $res;
}
The error is in the foreach loop. I have printed the result and it shows the result in object array but when it goes to foreach loop. It show this error
"Call to a member function result() on a non-object "
But when I set db['default']['db_debug']=true , it shows that the $id is missing from the query whereas when it was false it was showing result in object array and giving error at loop. Any Help would be appreciated.Thanks
Controller Code
public function createInvoice( $id = "" )
{
if (empty($id))
{
$id = $this->input->post('dataid');
}
echo $id;
$data['jcc_line_list'] = $this->product_model->getJccLineItem($id,'array');
$data['jcc_line_lists'] = $this->product_model->getJccLineItem($id,'');
$data['items'] = $this->product_model->getAllSubInvoice($id);
$data['single_project'] = $this->product_model->getSingleProject($id);
$data['site'] = $this->product_model->getAllSiteArray();
$data['job_types'] = $this->product_model->getAllJobTypeArray();
$data['title'] = 'Invoice';
$data['operation'] = 'Create';
$data['buttonText'] = 'Save';
$data['id'] = $id;
$this->load->helper(array('form', 'url'));
$this->load->helper('security');
$this->form_validation->set_rules('line_item_id', 'Line Item', 'required|xss_clean|max_length[50]');
$this->form_validation->set_rules('job_type_id', 'Job Type', 'required|xss_clean|max_length[50]');
$this->form_validation->set_rules('site_id', 'Site', 'required|xss_clean|max_length[50]');
$this->form_validation->set_rules('milestone', 'Milestone', 'required|xss_clean|max_length[50]');
$this->form_validation->set_error_delimiters('<span class="error">', '</span>');
if ($this->form_validation->run() == FALSE) {
$this->session->set_flashdata('error_message', validation_errors());
$this->load->view('admin/viewinvoicesub', $data);
} else if ($this->form_validation->run() == TRUE) {
$formData = array(
'invoice_id' => $id,
'line_item_id' => $this->form_validation->set_value('line_item_id'),
'job_type_id' => $this->form_validation->set_value('job_type_id'),
'site_id' => $this->form_validation->set_value('site_id'),
'milestone' => $this->form_validation->set_value('milestone'),
);
$this->product_model->insertInvoiceSub($formData);
$this->session->set_flashdata('sucess_message', "Data successfully save !");
redirect('Products/createInvoice', "refresh");
} else {
$this->load->view('admin/viewinvoicesub', $data);
}
}
Try this and let me know if that helps
public function getJccLineItem($id = '' ,$action = '')
{
if($id != '')
{
$res = array();
$q = 'SELECT * FROM jcc_line_items jli,ipo_line_item ili ,line_items li
WHERE jli.line_item_id= ili.id and li.id = jli.line_item_id
and ili.dn_number_id in ( Select dn_number from ipo where project_id= '.$id.')';
$res = $this->db->query($q)->result();
$jccLineItemArray = array();
if($action == 'array')
{
foreach($res as $key => $value) // The error comes in this line
{
$jccLineItemArray[ $value->id ] = $value->item_description;
}
$res = $jccLineItemArray;
}
return $res;
}
else
{
echo "id is null"; die();
}
}
And your Controller code should be
public function createInvoice( $id = "" )
{
$this->load->helper(array('form', 'url'));
$this->load->helper('security');
if ($id = "")
{
$id = (isset($this->input->post('dataid')))?$this->input->post('dataid'):3;// i am sure your error is from here
}
$data['jcc_line_list'] = $this->product_model->getJccLineItem($id,'array');
$data['jcc_line_lists'] = $this->product_model->getJccLineItem($id,'');
$data['items'] = $this->product_model->getAllSubInvoice($id);
$data['single_project'] = $this->product_model->getSingleProject($id);
$data['site'] = $this->product_model->getAllSiteArray();
$data['job_types'] = $this->product_model->getAllJobTypeArray();
$data['title'] = 'Invoice';
$data['operation'] = 'Create';
$data['buttonText'] = 'Save';
$data['id'] = $id;
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$this->form_validation->set_rules('line_item_id', 'Line Item', 'required|xss_clean|max_length[50]');
$this->form_validation->set_rules('job_type_id', 'Job Type', 'required|xss_clean|max_length[50]');
$this->form_validation->set_rules('site_id', 'Site', 'required|xss_clean|max_length[50]');
$this->form_validation->set_rules('milestone', 'Milestone', 'required|xss_clean|max_length[50]');
$this->form_validation->set_error_delimiters('<span class="error">', '</span>');
if ($this->form_validation->run() === FALSE)
{
$this->session->set_flashdata('error_message', validation_errors());
$this->load->view('admin/viewinvoicesub', $data);
}
else
{
$formData = array(
'invoice_id' => $id,
'line_item_id' => $this->form_validation->set_value('line_item_id'),
'job_type_id' => $this->form_validation->set_value('job_type_id'),
'site_id' => $this->form_validation->set_value('site_id'),
'milestone' => $this->form_validation->set_value('milestone'),
);
$this->product_model->insertInvoiceSub($formData);
$this->session->set_flashdata('sucess_message', "Data successfully save !");
redirect('Products/createInvoice/'.$id, "refresh");
}
}
else
{
$this->load->view('admin/viewinvoicesub', $data);
}
}
I am trying to put my files in a folder from the file_put_contents can someone help me with that.
$invoegen_titel=$_POST['titel_form'];
$invoegen_datum=$_POST['datum'];
$invoegen_tekst=$_POST['tekst'];
$html_tekst= $invoegen_titel."</h1>"."<br>"."<p>".$invoegen_datum."</p>"."<br>"."<p>".$invoegen_tekst."</p>";
$previous = $_SERVER['HTTP_REFERER'];
$folder='blog';
var_dump(file_put_contents($folder."/".time().".html","<h1>".$invoegen_titel."</h1>"."<br>"."<p>".$invoegen_datum."</p>"."<br>"."<p>".$invoegen_tekst."</p>"));
make sure that the directory is present. file_put_contents doesn't create the directory if it is not present.
Please specify what problems you are encountering on your code.
change these parts
$folder = time(); //make sure that time() returns string
$folder = "blog/".$folder.'.html';
file_put_contents($folder, $html_tekst);
var_dump(file_get_contents($folder));
Use this:
$lifeTime = 5; // life time, seconds
$cached = TRUE;
$config = array(
'group'=>'default', // dir
'id' => '1', // id cache
'echo' => TRUE, // echo or return
'log'=>false, // echo log, or not
'ext' => 'js' // extention cache file, default .html
);
$CacheFile = new CacheFile('/usr/cache/', $cached);
$CacheFile->config($config, $lifeTime);
if (!$CacheFile->start()){
echo $invoegen_titel."</h1>"."<br>"."<p>".$invoegen_datum."</p>"."<br>"."<p>".$invoegen_tekst."</p>";
$CacheFile->end();
}
PHP class:
class CacheFile{
private $cacheDir = '';
private $cacheSubDir = '';
private $fileName = '';
private $cache = false;
private $lifeTime = 0;
private $echo = true;
private $group = true;
private $log = true;
private $fileExt = 'html';
public function __construct($cacheDir, $cache){
$this->cacheDir = $cacheDir;
$this->cache = $cache;
}
private function createdPatch(){
if ($this->cache){
if (!is_dir($this->cacheSubDir)){
mkdir($this->cacheSubDir, 0777, true);
}
chmod($this->cacheSubDir, 0755);
}
}
private function getSubDir($keyType, $keyValue){
return (($keyType != '')?($keyType.'/'):'').mb_substr($keyValue, 0, 1)."/".mb_substr($keyValue, 1, 1)."/".mb_substr($keyValue, 2, 1)."/";
}
private function getCacheName($key){
return md5($key).".".$this->fileExt;
}
public function config($conf = array('group'=>'post', 'id' => '0', 'echo' => TRUE), $time = 31536000){
$this->group = $conf['group'];
$this->cacheSubDir = $this->cacheDir.$this->getSubDir($conf['group'], md5($conf['id']));
$this->fileName = $this->getCacheName($conf['group'].$conf['id']);
$this->lifeTime = $time;
if (isset($conf['echo']))
$this->echo = $conf['echo'];
if (isset($conf['log']))
$this->log = $conf['log'];
if (isset($conf['ext']))
$this->fileExt = $conf['ext'];
}
public function start(){
if ($data = $this->get()) {
if ($this->echo){
echo $data;
return true;
}else{
return $data;
}
}
ob_start();
ob_implicit_flush(false);
return false;
}
function end(){
$data = ob_get_contents();
ob_end_clean();
if ($this->cache){
$this->save($data.(($this->log)?'<!-- c:'.$this->group.':('.date("Y-m-d H:i:s", (time()+$this->lifeTime)).'/'.date("Y-m-d H:i:s").') -->':""));
}
$return = $data.(($this->log)?'<!-- g:'.$this->group.':('.date("Y-m-d H:i:s", (time()+$this->lifeTime)).'/'.date("Y-m-d H:i:s").') -->':"");
if ($this->echo){
echo $return;
return true;
}
return $return;
}
public function get(){
if (!file_exists($this->cacheSubDir.$this->fileName))
return false;
if (time() >= filemtime($this->cacheSubDir.$this->fileName) + $this->lifeTime){
unlink($this->cacheSubDir.$this->fileName);
return false;
}
if ($this->cache && file_exists($this->cacheSubDir.$this->fileName))
if ($data = file_get_contents($this->cacheSubDir.$this->fileName, false))
return $data;
return false;
}
public function remove(){
if (file_exists($this->cacheSubDir.$this->fileName)){
echo unlink($this->cacheSubDir.$this->fileName);
return true;
}
return false;
}
public function save($data){
$this->createdPatch();
if (file_put_contents($this->cacheSubDir.$this->fileName, $data, LOCK_EX))
return true;
return false;
}
}
I fixed it
<?php $list = file_get_contents('list.json'); $list = json_decode($list, true); $selector = $_POST['selector']; $d_or_t = $_POST['d_or_t']; if (isset($selector) && isset($d_or_t)) { // overwrite the selected domain of the list with the new value if they are not empty if ($d_or_t == "domain") { $list[$selector]['domain'] = $_POST['new']; } if ($d_or_t == "template") { $list[$selector]['template'] = $_POST['new']; } /*else { echo '<script type="text/javascript">alert("U bent vergeten een veld in te voelen!");</script>'; }*/ // store the new json } ?>
<!DOCTYPE html>
<html>
<head>
<title>Json values veranderen</title>
</head>
<body>
<h2>Domain of Template veranderen met PHP script</h2>
<form action="test.php" id="form" method="post">
<select name="selector">
<?php foreach ($list AS $key => $value) : ?>
<option value="<?php echo $key; ?>">
<?php echo $key; ?>
</option>
<?php endforeach; ?>
</select>
<select name="d_or_t">
<option>domain</option>
<option>template</option>
</select>
<input type="text" name="new" placeholder="Nieuw">
<input type="submit" value="Veranderen">
</form>
</body>
</html>
<?php
echo "<ul>";
foreach ($list as $key => $value)
{
echo "<li>".$key."<ul>";
foreach ($value as $key1 => $value1)
{
echo "<li>".$key1.": ".$value1."</li>"; }
echo "</ul>"."</li>";
}
echo "</ul>";
file_put_contents('list.json', json_encode($list));
?>
I have the following smarty tpl form:
<form name="new_element" action="layout.php?action=newElement&pageId={$data.page.id}" method="POST">
<input type="text" name="name" />
<input type="submit" name="submit" />
</form>
And the layout.php action looks like this:
<?php
require_once('../initialize.php');
$pages = new Smalllight($pdo, 'pages');
$elements = new Smalllight($pdo, 'elements');
$status = new Smalllight($pdo, 'status');
$users = new SmalllightUsers($pdo, 'users');
$profiles = new Smalllight($pdo, 'profiles');
if($users->isLoggedIn() || $users->isRemember()) {
//set user_id
if(isset($_SESSION['user_id'])) { $user_id = $_SESSION['user_id']; }
elseif(isset($_COOKIE['user_id'])) { $user_id = $_COOKIE['user_id']; }
//reset Token
if($users->isRemember()) { $users->resetToken($user_id, $settings['cookie_expire']); }
//check if user is admin
if($users->isAdmin()) {
$data['admin'] = true;
//find all statuses
$getStatus = $status->findAll();
if($getStatus == true) {
foreach($getStatus as $status)
{ $data['status'][$status['id']] = $status; }
}
//-------------------//
//----- ACTIONS -----//
//-------------------//
//----- VIEW LAYOUT -----\\
if($_GET['action'] = 'viewLayout') {
//find page
$getPage = $pages->findById($_GET['pageId']);
if($getPage == true) {
$data['page'] = $getPage;
//find page elements
$pageElements = $elements->findByFieldValue('page_id', $_GET['pageId']);
if($pageElements == true) {
$data['pageElements'] = $pageElements;
}
//find page elements with tree structure
$getElements = $elements->findTree(array('page_id' => $_GET['pageId']), null, array('position' => 'asc'));
if($getElements == true) {
$data['elements'] = $getElements;
}
}
//assign objects
$smarty->assign('elements', $elements);
//assign data and display
$smarty->assign('data', $data);
$smarty->assign('page', 'layout');
$smarty->display('../themes/admin/layout.tpl');
}
echo '<pre>'; print_r($_POST); exit;
//----- NEW ELEMENT ----\\
if($_GET['action'] == 'newElement') {
echo '<pre>'; print_r($_POST); exit;
$elementCount = $elements->countByFieldValue('parent_id', $_POST['parent']);
if($_POST['name'] != NULL) {
$elements->setValue('name', $_POST['name']);
$elements->setValue('type', $_POST['type']);
$elements->setValue('class', $_POST['class']);
$elements->setValue('style', $_POST['style']);
$elements->setValue('content', $_POST['content']);
$elements->setValue('parent_id', $parentId);
$elements->setValue('page_id', $_GET['pageId']);
$elements->setValue('status_id', $_POST['status']);
$elements->setValue('position', $elementCount++);
$elements->store();
}
header('Location: '.$settings['site_url'].'admin/layout.php?action=viewLayout&pageId='.$_GET['pageId']); exit;
}
}
else { header('Location: '.$settings['site_url'].'index.php'); exit; }
}
else { header('Location: '.$settings['site_url'].'index.php'); exit; }
?>
As you can see, i've set echo '<pre>'; print_r($_POST); exit; as the first line of the action, but when i submit the form it just takes me to where the form has to go (here: layout.php?action=newElement&pageId=328) and does nothing.
I have another file called pages.php with the exact similar fasion and that works.
I'm using a WordPress plugin called User Submitted Posts. The plugin allows for users to upload multiple photos. I have it set up so that users can upload 0 to a max of 3. When I try to upload more than one pic, however, only one of them gets posted.
HTML:
<div id="usp">
<form id="usp_form" method="post" enctype="multipart/form-data" action="">
<ul id="usp_list">
<li class="usp_title">
<label for="user-submitted-title" class="usp_label">Post Title</label>
<div>
<input class="usp_input" type="text" name="user-submitted-title" id="user-submitted-title" value="" />
</div>
</li>
<li class="usp_tags">
<label for="user-submitted-tags" class="usp_label">Post Tags <small>(separate tags with commas)</small></label>
<div>
<input class="usp_input" type="text" name="user-submitted-tags" id="user-submitted-tags" value="" />
</div>
</li>
<li class="usp_content">
<label for="user-submitted-content" class="usp_label">Post Content</label>
<div>
<textarea class="usp_textarea" name="user-submitted-content" id="user-submitted-content" rows="5"></textarea>
</div>
</li>
<li class="usp_images">
<label for="user-submitted-image" class="usp_label">Upload an Image</label>
<div id="usp_upload-message"></div>
<div>
<input class="usp_input usp_clone" type="file" size="25" id="user-submitted-image" name="user-submitted-image[]" />
Add another image
</div>
</li>
<li class="usp_submit">
<input class="usp_input" type="submit" name="user-submitted-post" id="user-submitted-post" value="Submit Post" />
</li>
</ul>
</form>
PHP:
if (!class_exists('Public_Submission_Form')) {
class Public_Submission_Form {
var $version = '1.0';
var $_post_meta_IsSubmission = 'is_submission';
var $_post_meta_Submitter = 'user_submit_name';
var $_post_meta_SubmitterUrl = 'user_submit_url';
var $_post_meta_SubmitterIp = 'user_submit_ip';
var $_post_meta_Image = 'user_submit_image';
var $_post_meta_ImageInfo = 'user_submit_image_info';
var $settings = null;
function Public_Submission_Form() {
register_activation_hook(__FILE__, array(&$this, 'saveDefaultSettings'));
add_action('admin_init', array(&$this, 'checkForSettingsSave'));
add_action('admin_menu', array(&$this, 'addAdministrativeElements'));
add_action('init', array(&$this, 'enqueueResources'));
add_action('parse_request', array(&$this, 'checkForPublicSubmission'));
add_action('parse_query', array(&$this, 'addSubmittedStatusClause'));
add_action('restrict_manage_posts', array(&$this, 'outputUserSubmissionLink'));
add_filter('the_author', array(&$this, 'replaceAuthor'));
add_filter('the_author_link', array(&$this, 'replaceAuthorLink'));
add_filter('post_stati', array(&$this, 'addNewPostStatus'));
add_shortcode('user-submitted-posts', array(&$this, 'getPublicSubmissionForm'));
}
function addAdministrativeElements() {
add_options_page(__('User Submitted Posts'), __('User Submitted Posts'), 'manage_options', 'user-submitted-posts', array(&$this, 'displaySettingsPage'));
}
function addNewPostStatus($postStati) {
$postStati['submitted'] = array(__('Submitted'), __('User submitted posts'), _n_noop('Submitted', 'Submitted'));
return $postStati;
}
function addSubmittedStatusClause($wp_query) {
global $pagenow;
if (is_admin() && $pagenow == 'edit.php' && $_GET['user_submitted'] == '1') {
set_query_var('meta_key', $this->_post_meta_IsSubmission);
set_query_var('meta_value', 1);
set_query_var('post_status', 'pending');
}
}
function checkForPublicSubmission() {
if (isset($_POST['user-submitted-post']) && ! empty($_POST['user-submitted-post'])) {
$settings = $this->getSettings();
$title = stripslashes($_POST['user-submitted-title']);
$content = stripslashes($_POST['user-submitted-content']);
$authorName = stripslashes($_POST['user-submitted-name']);
$authorUrl = stripslashes($_POST['user-submitted-url']);
$tags = stripslashes($_POST['user-submitted-tags']);
$category = intval($_POST['user-submitted-category']);
$fileData = $_FILES['user-submitted-image'];
$publicSubmission = $this->createPublicSubmission($title, $content, $authorName, $authorUrl, $tags, $category, $fileData);
if (false == ($publicSubmission)) {
$errorMessage = empty($settings['error-message']) ? __('An error occurred. Please go back and try again.') : $settings['error-message'];
if( !empty( $_POST[ 'redirect-override' ] ) ) {
$redirect = stripslashes( $_POST[ 'redirect-override' ] );
$redirect = add_query_arg( array( 'submission-error' => '1' ), $redirect );
wp_redirect( $redirect );
exit();
}
wp_die($errorMessage);
} else {
$redirect = empty($settings['redirect-url']) ? $_SERVER['REQUEST_URI'] : $settings['redirect-url'];
if (! empty($_POST['redirect-override'])) {
$redirect = stripslashes($_POST['redirect-override']);
}
$redirect = add_query_arg(array('success'=>1), $redirect);
wp_redirect($redirect);
exit();
}
}
}
function checkForSettingsSave() {
if (isset($_POST['save-post-submission-settings']) && current_user_can('manage_options') && check_admin_referer('save-post-submission-settings')) {
$settings = $this->getSettings();
$settings['author'] = get_userdata($_POST['author']) ? $_POST['author'] : $settings['author'];
$settings['categories'] = is_array($_POST['categories']) && ! empty($_POST['categories']) ? array_unique($_POST['categories']) : array(get_option('default_category'));
$settings['number-approved'] = is_numeric($_POST['number-approved']) ? intval($_POST['number-approved']) : - 1;
$settings['redirect-url'] = stripslashes($_POST['redirect-url']);
$settings['error-message'] = stripslashes($_POST['error-message']);
$settings['min-images'] = is_numeric($_POST['min-images']) ? intval($_POST['min-images']) : $settings['max-images'];
$settings['max-images'] = (is_numeric($_POST['max-images']) && ($settings['min-images'] <= $_POST['max-images'])) ? intval($_POST['max-images']) : $settings['max-images'];
$settings['min-image-height'] = is_numeric($_POST['min-image-height']) ? intval($_POST['min-image-height']) : $settings['min-image-height'];
$settings['min-image-width'] = is_numeric($_POST['min-image-width']) ? intval($_POST['min-image-width']) : $settings['min-image-width'];
$settings['max-image-height'] = (is_numeric($_POST['max-image-height']) && ($settings['min-image-height'] <= $_POST['max-image-height'])) ? intval($_POST['max-image-height']) : $settings['max-image-height'];
$settings['max-image-width'] = (is_numeric($_POST['max-image-width']) && ($settings['min-image-width'] <= $_POST['max-image-width'])) ? intval($_POST['max-image-width']) : $settings['max-image-width'];
$settings['usp_name'] = stripslashes($_POST['usp_name']);
$settings['usp_url'] = stripslashes($_POST['usp_url']);
$settings['usp_title'] = stripslashes($_POST['usp_title']);
$settings['usp_tags'] = stripslashes($_POST['usp_tags']);
$settings['usp_category'] = stripslashes($_POST['usp_category']);
$settings['usp_content'] = stripslashes($_POST['usp_content']);
$settings['usp_images'] = stripslashes($_POST['usp_images']);
$settings['upload-message'] = stripslashes($_POST['upload-message']);
$settings['usp_form_width'] = stripslashes($_POST['usp_form_width']);
$this->saveSettings($settings);
wp_redirect(admin_url('options-general.php?page=user-submitted-posts&updated=1'));
}
}
function displaySettingsPage() {
include ('views/settings.php');
}
function enqueueResources() {
wp_enqueue_script('usp_script', WP_PLUGIN_URL.'/'.basename(dirname(__FILE__)).'/resources/user-submitted-posts.js', array('jquery'), $this->version);
wp_enqueue_style('usp_style', WP_PLUGIN_URL.'/'.basename(dirname(__FILE__)).'/resources/user-submitted-posts.css', false, $this->version, 'screen');
}
function getPublicSubmissionForm($atts = array(), $content = null) {
if ($atts === true) {
$redirect = $this->currentPageURL();
}
ob_start();
include (WP_PLUGIN_DIR.'/'.basename(dirname(__FILE__)).'/views/submission-form.php');
return ob_get_clean();
}
function outputUserSubmissionLink() {
global $pagenow;
if ($pagenow == 'edit.php') {
echo '<a id="usp_admin_filter_posts" class="button-secondary" href="'.admin_url('edit.php?post_status=pending&user_submitted=1').'">'.__('User Submitted Posts').'</a>';
}
}
function replaceAuthor($author) {
global $post;
$isSubmission = get_post_meta($post->ID, $this->_post_meta_IsSubmission, true);
$submissionAuthor = get_post_meta($post->ID, $this->_post_meta_Submitter, true);
if ($isSubmission && ! empty($submissionAuthor)) {
return $submissionAuthor;
} else {
return $author;
}
}
function replaceAuthorLink($authorLink) {
global $post;
$isSubmission = get_post_meta($post->ID, $this->_post_meta_IsSubmission, true);
$submissionAuthor = get_post_meta($post->ID, $this->_post_meta_Submitter, true);
$submissionLink = get_post_meta($post->ID, $this->_post_meta_SubmitterUrl, true);
if ($isSubmission && ! empty($submissionAuthor)) {
if ( empty($submissionLink)) {
return $submissionAuthor;
} else {
return "<a href='{$submissionLink}'>{$submissionAuthor}</a>";
}
} else {
return $authorLink;
}
}
function saveDefaultSettings() {
$settings = $this->getSettings();
if ( empty($settings)) {
$currentUser = wp_get_current_user();
$settings = array();
$settings['author'] = $currentUser->ID;
$settings['categories'] = array(get_option('default_category'));
$settings['number-approved'] = -1;
$settings['redirect-url'] = ''; //site_url();
$settings['error-message'] = __('There was an error. Please ensure that you have added a title, some content, and that you have uploaded only images.');
$settings['min-images'] = 0;
$settings['max-images'] = 1;
$settings['min-image-height'] = 0;
$settings['min-image-width'] = 0;
$settings['max-image-height'] = 500;
$settings['max-image-width'] = 500;
$settings['usp_name'] = 'show';
$settings['usp_url'] = 'show';
$settings['usp_title'] = 'show';
$settings['usp_tags'] = 'show';
$settings['usp_category'] = 'show';
$settings['usp_content'] = 'show';
$settings['usp_images'] = 'hide';
$settings['upload-message'] = ''; // 'Please select your image(s) to upload:';
$settings['usp_form_width'] = '300'; // in pixels
$this->saveSettings($settings);
}
}
function getSettings() {
if ($this->settings === null) {
$defaults = array();
$this->settings = get_option('User Submitted Posts Settings', array());
}
return $this->settings;
}
function saveSettings($settings) {
if (!is_array($settings)) {
return;
}
$this->settings = $settings;
update_option('User Submitted Posts Settings', $this->settings);
}
function createPublicSubmission($title, $content, $authorName, $authorUrl, $tags, $category, $fileData) {
$settings = $this->getSettings();
$authorName = strip_tags($authorName);
$authorUrl = strip_tags($authorUrl);
$authorIp = $_SERVER['REMOTE_ADDR'];
if (!$this->validateTitle($title)) {
return false;
}
if (!$this->validateContent($title)) {
return false;
}
if (!$this->validateTags($tags)) {
return false;
}
$postData = array();
$postData['post_title'] = $title;
$postData['post_content'] = $content;
$postData['post_status'] = 'pending';
$postData['author'] = $settings['author'];
$numberApproved = $settings['number-approved'];
if ($numberApproved < 0) {} elseif ($numberApproved == 0) {
$postData['post_status'] = 'publish';
} else {
$posts = get_posts(array('post_status'=>'publish', 'meta_key'=>$this->_post_meta_Submitter, 'meta_value'=>$authorName));
$counter = 0;
foreach ($posts as $post) {
$submitterUrl = get_post_meta($post->ID, $this->_post_meta_SubmitterUrl, true);
$submitterIp = get_post_meta($post->ID, $this->_post_meta_SubmitterIp, true);
if ($submitterUrl == $authorUrl && $submitterIp == $authorIp) {
$counter++;
}
}
if ($counter >= $numberApproved) {
$postData['post_status'] = 'publish';
}
}
$newPost = wp_insert_post($postData);
if ($newPost) {
wp_set_post_tags($newPost, $tags);
wp_set_post_categories($newPost, array($category));
if (!function_exists('media_handle_upload')) {
require_once (ABSPATH.'/wp-admin/includes/media.php');
require_once (ABSPATH.'/wp-admin/includes/file.php');
require_once (ABSPATH.'/wp-admin/includes/image.php');
}
$attachmentIds = array();
$imageCounter = 0;
for ($i = 0; $i < count($fileData['name']); $i++) {
$imageInfo = getimagesize($fileData['tmp_name'][$i]);
if (false === $imageInfo || !$this->imageIsRightSize($imageInfo[0], $imageInfo[1])) {
continue;
}
$key = "public-submission-attachment-{$i}";
$_FILES[$key] = array();
$_FILES[$key]['name'] = $fileData['name'][$i];
$_FILES[$key]['tmp_name'] = $fileData['tmp_name'][$i];
$_FILES[$key]['type'] = $fileData['type'][$i];
$_FILES[$key]['error'] = $fileData['error'][$i];
$_FILES[$key]['size'] = $fileData['size'][$i];
$attachmentId = media_handle_upload($key, $newPost);
if (!is_wp_error($attachmentId) && wp_attachment_is_image($attachmentId)) {
$attachmentIds[] = $attachmentId;
add_post_meta($newPost, $this->_post_meta_Image, wp_get_attachment_url($attachmentId));
$imageCounter++;
} else {
wp_delete_attachment($attachmentId);
}
if ($imageCounter == $settings['max-images']) {
break;
}
}
if (count($attachmentIds) < $settings['min-images']) {
foreach ($attachmentIds as $idToDelete) {
wp_delete_attachment($idToDelete);
}
wp_delete_post($newPost);
return false;
}
update_post_meta($newPost, $this->_post_meta_IsSubmission, true);
update_post_meta($newPost, $this->_post_meta_Submitter, htmlentities(($authorName)));
update_post_meta($newPost, $this->_post_meta_SubmitterUrl, htmlentities(($authorUrl)));
update_post_meta($newPost, $this->_post_meta_SubmitterIp, $authorIp);
}
return $newPost;
}
function imageIsRightSize($width, $height) {
$settings = $this->getSettings();
$widthFits = ($width <= intval($settings['max-image-width'])) && ($width >= $settings['min-image-width']);
$heightFits = ($height <= $settings['max-image-height']) && ($height >= $settings['min-image-height']);
return $widthFits && $heightFits;
}
function validateContent($content) {
return ! empty($content);
}
function validateTags($tags) {
return true;
}
function validateTitle($title) {
return ! empty($title);
}
function currentPageURL() {
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {
$pageURL .= "s";
}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}
}
$publicSubmissionForm = new Public_Submission_Form();
include ('library/template-tags.php');
}
== Template Tags ==
To display the images attached to user-submitted posts, use this template tag:
<?php post_attachments(); ?>
This template tag prints the URLs for all post attachments and accepts the following paramters:
<?php post_attachments($size, $beforeUrl, $afterUrl, $numberImages, $postId); ?>
$size = image size as thumbnail, medium, large or full -> default = full
$beforeUrl = text/markup displayed before the image URL -> default = <img src="
$afterUrl = text/markup displayed after the image URL -> default = " />
$numberImages = the number of images to display for each post -> default = false (display all)
$postId = an optional post ID to use -> default = uses global post
Additionally, the following template tag returns an array of URLs for the specified post image:
<?php get_post_images(); ?>
This tag returns a boolean value indicating whether the specified post is a public submission:
<?php is_public_submission(); ?>
What does var_dump($_FILES) look like? It looks like you're generating a unique field name for each file upload field, using $key = "public-submission-attachment-{$i}";. if that's the case, then your file access structure is incorrect. PHP will generate the $_FILES data for each fieldname 1 of 2 ways:
If you're using a unique somestring field name, you get a structure like:
$_FILES['somestring'] = array(
'name' => 'somefile.txt',
'type' => 'text/plain',
'size' => 1234,
'error' => 0,
'tmp_name'] => '/tmp/asdfasdfasdfa'
);
If you're using the PHP-centric array notation, somestring[] (note the []) for the field name, you get:
$_FILES['somestring'] = array(
'name' => array(
0 => 'somefile1.txt',
1 => 'somepic.jpg'
),
'type' => array(
0 => 'text/plain',
1 => 'image.jpeg'
)
etc...
);
Given that it you seem to be generating a unique field name, WITHOUT the array notation, you'd have to use option #1.