php-general Digest 9 Jun 2011 22:28:30 -0000 Issue 7353
Topics (messages 313481 through 313489):
trying to combine two forms into a single form
313481 by: matty jones
313482 by: Alex Nikitin
313483 by: Jim Lucas
313484 by: matty jones
313485 by: Jim Lucas
313486 by: matty jones
313487 by: Alex Nikitin
Class not used as an object (Scope Resolution Operator)
313488 by: George Langley
313489 by: Richard Quadling
Administrivia:
To subscribe to the digest, e-mail:
[email protected]
To unsubscribe from the digest, e-mail:
[email protected]
To post to the list, e-mail:
[email protected]
----------------------------------------------------------------------
--- Begin Message ---
I have a mediawiki extension that allows me to design a form in the wiki to
facilitate data entry into the wiki and it works good except that I also
want to be able to up load images and take the file location/name and enter
that into the wiki so that the image displays on the page as well. I found
code online that works well for uploading an image to a site and it works
good in my mediawiki but when I combined the forms on a single page and
click on the upload button it wipes the other textarea fields clean
and doesn't submit the text data but it does upload the image and return the
path and filename. I know this is supposed to happen but I don't totally
understand why. If I just click on the save form button the image isn't
upload, but the text data is saved, again I understand something having to
do with two different forms/form handlers but I have been trying to combine
them with no luck. My line of thinking was to write a function to submit
the second form and call it when the first form is submitted but
this doesn't seem to be working or I am doing it wrong. The ultimate goal
is to have a form that submits issues into a knowledge base and allows
screenshots of error messages.
Here is the code for the page.
<?php
//define a maxim size for the uploaded images in Kb
define ("MAX_SIZE","1024");
//This function reads the extension of the file. It is used to determine if
the file is an image by checking the extension.
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
//This variable is used as a flag. The value is initialized with 0 (meaning
no error found)
//and it will be changed to 1 if an errro occures.
//If the error occures the file will not be uploaded.
$errors=0;
//checks if the form has been submitted
// if(isset($_POST['Submit']))
//{
//reads the name of the file the user submitted for uploading
$image=$_FILES['image']['name'];
//if it is not empty
if ($image)
{
//get the original name of the file from the clients machine
$filename = stripslashes($_FILES['image']['name']);
//get the extension of the file in a lower case format
$extension = getExtension($filename);
$extension = strtolower($extension);
//if it is not a known extension, we will suppose it is an error and will
not upload the file,
//otherwise we will do more tests
if (($extension != "jpg") && ($extension != "jpeg") && ($extension !=
"png") && ($extension != "gif"))
{
//print error message
echo '<h1>Unknown extension!</h1>';
$errors=1;
}
else
{
//get the size of the image in bytes
//$_FILES['image']['tmp_name'] is the temporary filename of the file
//in which the uploaded file was stored on the server
$size=filesize($_FILES['image']['tmp_name']);
//compare the size with the maxim size we defined and print error if bigger
if ($size > MAX_SIZE*1024)
{
echo '<h1>You have exceeded the size limit!</h1>';
$errors=1;
}
//we will give an unique name, for example the time in unix time format
$image_name=time().'.'.$extension;
//the new name will be containing the full path where will be stored (images
folder)
$newname="images/".$image_name;
//we verify if the image has been uploaded, and print error instead
$copied = copy($_FILES['image']['tmp_name'], $newname);
if (!$copied)
{
echo '<h1>Copy unsuccessfull!</h1>';
$errors=1;
}}}
//If no errors registred, print the success message
if(isset($_POST['Submit']) && !$errors)
{
echo "<h1>File Uploaded Successfully! Try again!</h1>";
echo $newname="images/".$image_name;
}
function wfSpecialAddactivity() {
global $wgOut, $wgScriptPath;
$mine = $wgScriptPath.'/index.php?action=submit';
if (!empty($_GET['id'])) {
$data = StructuredInput::getStructuredData($_GET['id']);
} else {
$data = array();
}
$html = <<<TEMPLATE
<h2>Add Issue</h2>
<script>
function setAction(formEl) {
if (formEl['_title'].value) {
formEl.action += '&title=' + formEl['_title'].value;
return true;
} else {
return false;
}
}
</script>
<form name="text" method="post" enctype="multipart/form-data" action="$mine"
onsubmit="return setAction(this)">
<input type="hidden" name="_type" value="addactivity" />
<!-- input type="hidden" name="wpPreview" value="Show preview" / -->
<!-- This is the title of the page being created -->
<label for="_title">Issue Title:</label>
<input id="_title" name="_title" value="{$data['_title']}" />
<br /><br />
<!-- This is the Software Product -->
<label for="software">Software:</label>
<select id="software" name="software">
<option value="{$data['software']}"></option>
<option value="Server For Windows{$data['software']}">Server For
Windows</option>
<option value="Suite For Windows{$data['software']}">Suite For
Windows</option>
<option value="Job{$data['software']}">Job</option>
</select>
<!-- This is the specific version of the software -->
<label for="version">Software Version:</label>
<input id="version" name="version" value="{$data['version']}" />
<!-- This is the specific Operating System the customer using -->
<label for="os">Customer Operating System:</label>
<input id="os" name="os" value="{$data['os']}" />
<!-- This is for the specific board the issue relates to -->
<label for="board">Customer Board Model:</label>
<input id="board" name="board" value="{$data['board']}" />
<br /><br />
<!-- This is the detailed description of the issue -->
<label for="description">Problem Description:</label>
<textarea rows="10" id="description"
name="description">{$data['description']}</textarea>
<br /><br />
<!-- This is the steps needed to solve the problem -->
<label for="instructions">Problem Solution:</label>
<textarea rows="10" id="instructions"
name="instructions">{$data['instructions']}</textarea>
<br /><br />
<!-- This is the person who wrote the article -->
<label for="items">Author:</label>
<input id="author" name="author" value="{$data['author']}" />
<br /><br />
<input name="submit" type="submit" value="Save">
</form>
<form method="post" enctype="multipart/form-data" action="">
<table>
<tr><td><input type="file" name="image"></td></tr>
<tr><td><input name="Submit" type="submit" value="Upload image"></td></tr>
</table>
</form>
TEMPLATE;
$wgOut->addHTML($html);
}
?>
--- End Message ---
--- Begin Message ---
On Thu, Jun 9, 2011 at 8:37 AM, matty jones <[email protected]> wrote:
> I have a mediawiki extension that allows me to design a form in the wiki to
> facilitate data entry into the wiki and it works good except that I also
> want to be able to up load images and take the file location/name and enter
> that into the wiki so that the image displays on the page as well. I found
> code online that works well for uploading an image to a site and it works
> good in my mediawiki but when I combined the forms on a single page and
> click on the upload button it wipes the other textarea fields clean
> and doesn't submit the text data but it does upload the image and return
> the
> path and filename. I know this is supposed to happen but I don't totally
> understand why. If I just click on the save form button the image isn't
> upload, but the text data is saved, again I understand something having to
> do with two different forms/form handlers but I have been trying to combine
> them with no luck. My line of thinking was to write a function to submit
> the second form and call it when the first form is submitted but
> this doesn't seem to be working or I am doing it wrong. The ultimate goal
> is to have a form that submits issues into a knowledge base and allows
> screenshots of error messages.
>
> Here is the code for the page.
>
> <?php
>
> //define a maxim size for the uploaded images in Kb
> define ("MAX_SIZE","1024");
>
> //This function reads the extension of the file. It is used to determine if
> the file is an image by checking the extension.
> function getExtension($str) {
> $i = strrpos($str,".");
> if (!$i) { return ""; }
> $l = strlen($str) - $i;
> $ext = substr($str,$i+1,$l);
> return $ext;
> }
>
> //This variable is used as a flag. The value is initialized with 0 (meaning
> no error found)
> //and it will be changed to 1 if an errro occures.
> //If the error occures the file will not be uploaded.
> $errors=0;
> //checks if the form has been submitted
> // if(isset($_POST['Submit']))
> //{
> //reads the name of the file the user submitted for uploading
> $image=$_FILES['image']['name'];
> //if it is not empty
> if ($image)
> {
> //get the original name of the file from the clients machine
> $filename = stripslashes($_FILES['image']['name']);
> //get the extension of the file in a lower case format
> $extension = getExtension($filename);
> $extension = strtolower($extension);
> //if it is not a known extension, we will suppose it is an error and will
> not upload the file,
> //otherwise we will do more tests
> if (($extension != "jpg") && ($extension != "jpeg") && ($extension !=
> "png") && ($extension != "gif"))
> {
> //print error message
> echo '<h1>Unknown extension!</h1>';
> $errors=1;
> }
> else
> {
> //get the size of the image in bytes
> //$_FILES['image']['tmp_name'] is the temporary filename of the file
> //in which the uploaded file was stored on the server
> $size=filesize($_FILES['image']['tmp_name']);
>
> //compare the size with the maxim size we defined and print error if bigger
> if ($size > MAX_SIZE*1024)
> {
> echo '<h1>You have exceeded the size limit!</h1>';
> $errors=1;
> }
>
> //we will give an unique name, for example the time in unix time format
> $image_name=time().'.'.$extension;
> //the new name will be containing the full path where will be stored
> (images
> folder)
> $newname="images/".$image_name;
> //we verify if the image has been uploaded, and print error instead
> $copied = copy($_FILES['image']['tmp_name'], $newname);
> if (!$copied)
> {
> echo '<h1>Copy unsuccessfull!</h1>';
> $errors=1;
> }}}
>
> //If no errors registred, print the success message
> if(isset($_POST['Submit']) && !$errors)
> {
> echo "<h1>File Uploaded Successfully! Try again!</h1>";
> echo $newname="images/".$image_name;
> }
>
>
>
> function wfSpecialAddactivity() {
> global $wgOut, $wgScriptPath;
>
> $mine = $wgScriptPath.'/index.php?action=submit';
> if (!empty($_GET['id'])) {
> $data = StructuredInput::getStructuredData($_GET['id']);
> } else {
> $data = array();
> }
>
> $html = <<<TEMPLATE
>
> <h2>Add Issue</h2>
>
> <script>
> function setAction(formEl) {
> if (formEl['_title'].value) {
> formEl.action += '&title=' + formEl['_title'].value;
> return true;
> } else {
> return false;
> }
> }
> </script>
>
> <form name="text" method="post" enctype="multipart/form-data"
> action="$mine"
> onsubmit="return setAction(this)">
> <input type="hidden" name="_type" value="addactivity" />
> <!-- input type="hidden" name="wpPreview" value="Show preview" / -->
>
> <!-- This is the title of the page being created -->
> <label for="_title">Issue Title:</label>
> <input id="_title" name="_title" value="{$data['_title']}" />
>
> <br /><br />
>
> <!-- This is the Software Product -->
> <label for="software">Software:</label>
> <select id="software" name="software">
> <option value="{$data['software']}"></option>
> <option value="Server For Windows{$data['software']}">Server For
> Windows</option>
> <option value="Suite For Windows{$data['software']}">Suite For
> Windows</option>
> <option value="Job{$data['software']}">Job</option>
> </select>
>
> <!-- This is the specific version of the software -->
> <label for="version">Software Version:</label>
> <input id="version" name="version" value="{$data['version']}" />
>
>
> <!-- This is the specific Operating System the customer using -->
> <label for="os">Customer Operating System:</label>
> <input id="os" name="os" value="{$data['os']}" />
>
>
> <!-- This is for the specific board the issue relates to -->
> <label for="board">Customer Board Model:</label>
> <input id="board" name="board" value="{$data['board']}" />
>
> <br /><br />
>
> <!-- This is the detailed description of the issue -->
> <label for="description">Problem Description:</label>
> <textarea rows="10" id="description"
> name="description">{$data['description']}</textarea>
>
> <br /><br />
> <!-- This is the steps needed to solve the problem -->
> <label for="instructions">Problem Solution:</label>
> <textarea rows="10" id="instructions"
> name="instructions">{$data['instructions']}</textarea>
>
> <br /><br />
>
> <!-- This is the person who wrote the article -->
> <label for="items">Author:</label>
> <input id="author" name="author" value="{$data['author']}" />
>
> <br /><br />
>
>
> <input name="submit" type="submit" value="Save">
> </form>
>
> <form method="post" enctype="multipart/form-data" action="">
> <table>
> <tr><td><input type="file" name="image"></td></tr>
> <tr><td><input name="Submit" type="submit" value="Upload image"></td></tr>
> </table>
>
> </form>
>
>
>
> TEMPLATE;
>
> $wgOut->addHTML($html);
> }
>
> ?>
>
AJAX? Upload it via a different or even the same page (there are a number of
jquery plugins, and its not really trivial to write it yourself) and return
the file's location on successful upload back to the page?
And its not too trivial to write, I mean just thinking out loud you could
post or get b64 encoded file with jquery post, and then in the return
function get the returned url or something that you can then embed into your
submit without loosing any data, and also this can happen as the user is
filling out the rest of the form...
--
The trouble with programmers is that you can never tell what a programmer is
doing until it’s too late. ~Seymour Cray
--- End Message ---
--- Begin Message ---
On 6/9/2011 5:37 AM, matty jones wrote:
> formEl.action += '&title=' + formEl['_title'].value;
The only thing I see inconsistent is the above line. But then again, it could
be right. You might be looking for $_GET['title'] in your processing page
instead of $_GET['_title']
--- End Message ---
--- Begin Message ---
The two forms work fine by themselves, my issue is getting to two of them to
work with together, I don't even care if you need to upload the image
seperately from submitting the text data as long as it is all on the same
page. Thanks for the thoughts on jQuerry, I will look into it.
On Thu, Jun 9, 2011 at 10:53 AM, Jim Lucas <[email protected]> wrote:
> On 6/9/2011 5:37 AM, matty jones wrote:
> > formEl.action += '&title=' + formEl['_title'].value;
>
> The only thing I see inconsistent is the above line. But then again, it
> could
> be right. You might be looking for $_GET['title'] in your processing page
> instead of $_GET['_title']
>
--- End Message ---
--- Begin Message ---
On 6/9/2011 8:07 AM, matty jones wrote:
> The two forms work fine by themselves, my issue is getting to two of them to
> work with together, I don't even care if you need to upload the image
> seperately from submitting the text data as long as it is all on the same
> page. Thanks for the thoughts on jQuerry, I will look into it.
>
> On Thu, Jun 9, 2011 at 10:53 AM, Jim Lucas <[email protected]> wrote:
>
>> On 6/9/2011 5:37 AM, matty jones wrote:
>>> formEl.action += '&title=' + formEl['_title'].value;
>>
>> The only thing I see inconsistent is the above line. But then again, it
>> could
>> be right. You might be looking for $_GET['title'] in your processing page
>> instead of $_GET['_title']
>>
>
Can you show the PHP code that you use to process the form data text fields?
--- End Message ---
--- Begin Message ---
I believe this is it. It is part of the mediawiki extension that I used as
a starting point for what I need it to do. I am slowly getting better at
PHP, this was dropped into my lap and I don't have much experience yet with
PHP, I come from bash/sed/awk land. This file is structuredinput.php, there
is only one more php file in the extension call specialstructuredinput.php
and I included that after this one as well.
Thanks
<?php
error_reporting(0);
set_include_path(get_include_path() . PATH_SEPARATOR .
$IP.'/extensions/structuredInput/special' );
$StructuredInput = new StructuredInput();
$wgHooks['SpecialPage_initList'][] = array($StructuredInput,
'addToSpecialPages');
$wgHooks['EditPage::showEditForm:initial'][] = array($StructuredInput,
'editForm');
// Bootleg php namespace
class StructuredInput
{
public static $inputList = array();
function getInputList() {
return StructuredInput::$inputList;
}
function addToSpecialPages(&$list) {
global $wgAllMessagesEn;
global $wgMessageCache;
foreach (StructuredInput::getInputList() as $val) {
$key = str_replace (' ', '', strtolower($val));
if (!array_key_exists($key, $wgAllMessagesEn)) {
$wgAllMessagesEn[$key] = $val;
$wgMessageCache->addMessages( array ($key => $val) );
$pageName = str_replace (' ', '', $val);
$list[$pageName] = array('SpecialPage', $pageName);
}
}
$wgAllMessagesEn['structuredinput'] = 'Structured Input Forms';
$wgMessageCache->addMessages( array ('structuredinput' =>
'Structured Input Forms') );
$list['StructuredInput'] = array('SpecialPage', 'StructuredInput');
return true;
}
function editForm(&$form) {
if (!empty($_POST['_type'])) {
$post = $_POST;
require_once('structuredInput/transformations/'.$_POST['_type'].'.php');
$form->textbox1 = $output;
$form->starttime = wfTimestampNow();
$form->edittime = wfTimestampNow();
} elseif (empty($_GET['viewsource']) &&
strpos($form->mArticle->mContent, '<!--|StructuredInput|-->') !== False){
global $wgServerName, $wgScriptPath;
$inputType = str_replace(array('<','!','-','>'),
array('','','',''),
$this->extractStructuredValue('StructuredInput',
$form->mArticle->mContent)
);
header('Location: http://
'.$wgServerName.$wgScriptPath.'/index.php?title=Special:'.$inputType.'&id='.$_GET['title']);
die();
}
return true;
}
function extractStructuredValue($key, $haystack) {
preg_match('/<!--\|'.$key.'\|-->(.*?)<!--\|'.$key.'\|-->/', $haystack,
$matches);
if (!empty($matches)) {
return $matches[1];
} else {
return '';
}
}
function extractStructuredValues($haystack) {
preg_match_all('/<!--\|(.*)\|-->(.*?)<!--\|\1\|-->/s', $haystack,
$matches);
return array_combine($matches[1], $matches[2]);
}
function makeRadios($key, $data, $selectedValue) {
$output = '';
foreach ($data as $item) {
$id = $key.str_replace(' ', '', $item['value']);
if ($item['value'] == $selectedValue) {
$selected = 'checked="checked"';
} else {
$selected = '';
}
$output .= <<<TEXT
<input type="radio" id="$id" name="$key" value="{$item['value']}"
$selected />
<label for="$id"><strong>{$item['value']}</strong>:
{$item['caption']}</label>
<br />
TEXT;
}
return $output;
}
function makeSelect($key, $data, $selectedValue) {
$output = '<select id="'.$key.'" name="'.$key.'">';
foreach ($data as $value) {
if ($value == $selectedValue) {
$selected = ' selected="selected"';
} else {
$selected = '';
}
$output .= '<option'.$selected.'>'.$value.'</option>';
}
$output .= '</select>';
return $output;
}
function getStructuredData($id) {
$pageContent = Revision::newFromTitle( Title::newFromText($id)
)->getText();
$data = StructuredInput::extractStructuredValues($pageContent);
$data['_title'] = $id;
return $data;
}
}
________________________ NEW FILE ______________________
<?php
function wfSpecialStructuredInput() {
global $wgOut, $wgServerName, $wgScriptPath;
$structuredInputs = '';
foreach (StructuredInput::getInputList() as $input) {
$key = ucfirst(str_replace (' ', '', strtolower($input)));
$structuredInputs .= '<li><a href="http://
'.$wgServerName.$wgScriptPath.'/index.php/Special:'.$key.'">'.$input.'</a></li>';
}
if (!empty($structuredInputs)) $structuredInputs =
'<ul>'.$structuredInputs.'</ul>';
$wgOut->addHTML($structuredInputs);
}
?>
On Thu, Jun 9, 2011 at 11:10 AM, Jim Lucas <[email protected]> wrote:
> On 6/9/2011 8:07 AM, matty jones wrote:
> > The two forms work fine by themselves, my issue is getting to two of them
> to
> > work with together, I don't even care if you need to upload the image
> > seperately from submitting the text data as long as it is all on the same
> > page. Thanks for the thoughts on jQuerry, I will look into it.
> >
> > On Thu, Jun 9, 2011 at 10:53 AM, Jim Lucas <[email protected]> wrote:
> >
> >> On 6/9/2011 5:37 AM, matty jones wrote:
> >>> formEl.action += '&title=' + formEl['_title'].value;
> >>
> >> The only thing I see inconsistent is the above line. But then again, it
> >> could
> >> be right. You might be looking for $_GET['title'] in your processing
> page
> >> instead of $_GET['_title']
> >>
> >
>
> Can you show the PHP code that you use to process the form data text
> fields?
>
--- End Message ---
--- Begin Message ---
Actually if you want a very simple way, with a little JS, you can b64 encode
the file and fill in the file field in the form with it (you can hide it or
dynamically tack it on or something), so that you get everything when you
submit the form including the file (you just gotta make a file back out of
it, but thats simple :) )...? I think that would be by far the easiest
solution, then you can do the shiny ajax stuff later if you feel like it.
--
The trouble with programmers is that you can never tell what a programmer is
doing until it’s too late. ~Seymour Cray
On Thu, Jun 9, 2011 at 11:10 AM, Jim Lucas <[email protected]> wrote:
> On 6/9/2011 8:07 AM, matty jones wrote:
> > The two forms work fine by themselves, my issue is getting to two of them
> to
> > work with together, I don't even care if you need to upload the image
> > seperately from submitting the text data as long as it is all on the same
> > page. Thanks for the thoughts on jQuerry, I will look into it.
> >
> > On Thu, Jun 9, 2011 at 10:53 AM, Jim Lucas <[email protected]> wrote:
> >
> >> On 6/9/2011 5:37 AM, matty jones wrote:
> >>> formEl.action += '&title=' + formEl['_title'].value;
> >>
> >> The only thing I see inconsistent is the above line. But then again, it
> >> could
> >> be right. You might be looking for $_GET['title'] in your processing
> page
> >> instead of $_GET['_title']
> >>
> >
>
> Can you show the PHP code that you use to process the form data text
> fields?
>
> --
> PHP General Mailing List (http://www.php.net/)
> To unsubscribe, visit: http://www.php.net/unsub.php
>
>
--- End Message ---
--- Begin Message ---
Hi all. Am fixing some inherited code, and the previous coder created a
class, ie:
class myClass {
function &doThis($passedVar) {
doSomething;
}
function &doThat($anotherVar) {
doSomethingElse;
}
}
BUT, I don't see anywhere where he created an object, ie:
$myObject = new myClass();
or
$myObject = myClass::doThis("value");
Instead, it's only ever just called directly with a "Scope Resolution
Operator", ie:
myClass::doThis("valueOne");
myClass::doThat($whatever);
myClass::doThis("valueTwo");
myClass::doThat($andSoOn);
It seems that this would be making an object, and then destroying it
again, on each of the four calls above, which I would think would be wasteful -
time, memory, cpu usage, etc.
The class has no constants or variables (properties) for any need for
persistence, and is just a collection of functions (methods), so I don't see a
reason to group them into a class - they could all reside as independent
functions within the php file.
Is this good? Is there some advantage to making a non-persistent class?
Thanks!
George Langley Multimedia Developer Audio/Video Editor Musician,
Arranger, Composer
--- End Message ---
--- Begin Message ---
On 9 June 2011 22:42, George Langley <[email protected]> wrote:
> Hi all. Am fixing some inherited code, and the previous coder created
> a class, ie:
>
> class myClass {
> function &doThis($passedVar) {
> doSomething;
> }
>
> function &doThat($anotherVar) {
> doSomethingElse;
> }
> }
>
> BUT, I don't see anywhere where he created an object, ie:
>
> $myObject = new myClass();
>
> or
>
> $myObject = myClass::doThis("value");
>
> Instead, it's only ever just called directly with a "Scope Resolution
> Operator", ie:
>
> myClass::doThis("valueOne");
> myClass::doThat($whatever);
> myClass::doThis("valueTwo");
> myClass::doThat($andSoOn);
>
> It seems that this would be making an object, and then destroying it
> again, on each of the four calls above, which I would think would be wasteful
> - time, memory, cpu usage, etc.
> The class has no constants or variables (properties) for any need for
> persistence, and is just a collection of functions (methods), so I don't see
> a reason to group them into a class - they could all reside as independent
> functions within the php file.
> Is this good? Is there some advantage to making a non-persistent class?
> Thanks!
Take a look at http://www.php.net/manual/en/language.oop5.static.php
Static methods are quite useful.
An instance is not created and destroyed. Just the static method is
called without any instance being used.
In the most basic sense, a class with only static methods could be
just a library of unrelated functions and the class is really just a
namespace for these functions.
--
Richard Quadling
Twitter : EE : Zend : PHPDoc
@RQuadling : e-e.com/M_248814.html : bit.ly/9O8vFY : bit.ly/lFnVea
--- End Message ---