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.
Related
I have the following select box which lists the all users. I need list users only which groupID is==3 How can I do that ?
Thanks in advance
<div class="form-group " >
<label for="Staff" class=" control-label col-md-4 text-left"> Staff </label>
<div class="col-md-7">
<select name='Staff' rows='5' id='Staff' class='select2 ' ></select>
</div>
<div class="col-md-1">
</div>
</div>
Controller
use App\Http\Controllers\controller; use App\Models\Adminorders; use Illuminate\Http\Request; use Illuminate\Pagination\LengthAwarePaginator as Paginator; use Validator, Input, Redirect ;
class AdminordersController extends Controller {
protected $layout = "layouts.main";
protected $data = array();
public $module = 'adminorders';
static $per_page = '10';
public function __construct()
{
parent::__construct();
$this->beforeFilter('csrf', array('on'=>'post'));
$this->model = new Adminorders();
$this->modelview = new \App\Models\Orderdetail();
$this->info = $this->model->makeInfo( $this->module);
$this->access = $this->model->validAccess($this->info['id']);
$this->data = array(
'pageTitle' => $this->info['title'],
'pageNote' => $this->info['note'],
'pageModule'=> 'adminorders',
'return' => self::returnUrl()
);
$this->data['subgrid'] = (isset($this->info['config']['subgrid']) ? $this->info['config']['subgrid'][0] : array());
}
public function getIndex( Request $request )
{
if($this->access['is_view'] ==0)
return Redirect::to('dashboard')
->with('messagetext', \Lang::get('core.note_restric'))->with('msgstatus','error');
$sort = (!is_null($request->input('sort')) ? $request->input('sort') : 'SiparisID');
$order = (!is_null($request->input('order')) ? $request->input('order') : 'asc');
// End Filter sort and order for query
// Filter Search for query
$filter = '';
if(!is_null($request->input('search')))
{
$search = $this->buildSearch('maps');
$filter = $search['param'];
$this->data['search_map'] = $search['maps'];
}
$page = $request->input('page', 1);
$params = array(
'page' => $page ,
'limit' => (!is_null($request->input('rows')) ? filter_var($request->input('rows'),FILTER_VALIDATE_INT) : static::$per_page ) ,
'sort' => $sort ,
'order' => $order,
'params' => $filter,
'global' => (isset($this->access['is_global']) ? $this->access['is_global'] : 0 )
);
// Get Query
$results = $this->model->getRows( $params );
// Build pagination setting
$page = $page >= 1 && filter_var($page, FILTER_VALIDATE_INT) !== false ? $page : 1;
$pagination = new Paginator($results['rows'], $results['total'], $params['limit']);
$pagination->setPath('adminorders');
$this->data['rowData'] = $results['rows'];
// Build Pagination
$this->data['pagination'] = $pagination;
// Build pager number and append current param GET
$this->data['pager'] = $this->injectPaginate();
// Row grid Number
$this->data['i'] = ($page * $params['limit'])- $params['limit'];
// Grid Configuration
$this->data['tableGrid'] = $this->info['config']['grid'];
$this->data['tableForm'] = $this->info['config']['forms'];
// Group users permission
$this->data['access'] = $this->access;
// Detail from master if any
// Master detail link if any
$this->data['subgrid'] = (isset($this->info['config']['subgrid']) ? $this->info['config']['subgrid'] : array());
// Render into template
return view('adminorders.index',$this->data);
}
function getUpdate(Request $request, $id = null)
{
if($id =='')
{
if($this->access['is_add'] ==0 )
return Redirect::to('dashboard')->with('messagetext',\Lang::get('core.note_restric'))->with('msgstatus','error');
}
if($id !='')
{
if($this->access['is_edit'] ==0 )
return Redirect::to('dashboard')->with('messagetext',\Lang::get('core.note_restric'))->with('msgstatus','error');
}
$row = $this->model->find($id);
if($row)
{
$this->data['row'] = $row;
} else {
$this->data['row'] = $this->model->getColumnTable('tb_orders');
}
$this->data['fields'] = \SiteHelpers::fieldLang($this->info['config']['forms']);
$relation_key = $this->modelview->makeInfo($this->info['config']['subform']['module']);
$this->data['accesschild'] = $this->modelview->validAccess($relation_key['id']);
$this->data['relation_key'] = $relation_key['key'];
$this->data['subform'] = $this->detailview($this->modelview , $this->info['config']['subform'] ,$id );
$this->data['id'] = $id;
return view('adminorders.form',$this->data);
}
public function getShow( Request $request, $id = null)
{
if($this->access['is_detail'] ==0)
return Redirect::to('dashboard')
->with('messagetext', \Lang::get('core.note_restric'))->with('msgstatus','error');
$row = $this->model->getRow($id);
if($row)
{
$this->data['row'] = $row;
$this->data['fields'] = \SiteHelpers::fieldLang($this->info['config']['grid']);
$this->data['id'] = $id;
$this->data['access'] = $this->access;
$this->data['subgrid'] = (isset($this->info['config']['subgrid']) ? $this->info['config']['subgrid'] : array());
$this->data['prevnext'] = $this->model->prevNext($id);
return view('adminorders.view',$this->data);
} else {
return Redirect::to('adminorders')->with('messagetext','Record Not Found !')->with('msgstatus','error');
}
}
function postSave( Request $request)
{
$rules = $this->validateForm();
$validator = Validator::make($request->all(), $rules);
if ($validator->passes()) {
$data = $this->validatePost('tb_adminorders');
$id = $this->model->insertRow($data , $request->input('SiparisID'));
$this->detailviewsave( $this->modelview , $request->all() ,$this->info['config']['subform'] , $id) ;
if(!is_null($request->input('apply')))
{
$return = 'adminorders/update/'.$id.'?return='.self::returnUrl();
} else {
$return = 'adminorders?return='.self::returnUrl();
}
// Insert logs into database
if($request->input('SiparisID') =='')
{
\SiteHelpers::auditTrail( $request , 'New Data with ID '.$id.' Has been Inserted !');
} else {
\SiteHelpers::auditTrail($request ,'Data with ID '.$id.' Has been Updated !');
}
return Redirect::to($return)->with('messagetext',\Lang::get('core.note_success'))->with('msgstatus','success');
} else {
return Redirect::to('adminorders/update/'.$request->input('SiparisID'))->with('messagetext',\Lang::get('core.note_error'))->with('msgstatus','error')
->withErrors($validator)->withInput();
}
}
public function postDelete( Request $request)
{
if($this->access['is_remove'] ==0)
return Redirect::to('dashboard')
->with('messagetext', \Lang::get('core.note_restric'))->with('msgstatus','error');
// delete multipe rows
if(count($request->input('ids')) >=1)
{
$this->model->destroy($request->input('ids'));
\DB::table('tb_orderdetail')->whereIn('SiparisID',$request->input('ids'))->delete();
\SiteHelpers::auditTrail( $request , "ID : ".implode(",",$request->input('ids'))." , Has Been Removed Successfull");
// redirect
return Redirect::to('adminorders?return='.self::returnUrl())
->with('messagetext', \Lang::get('core.note_success_delete'))->with('msgstatus','success');
} else {
return Redirect::to('adminorders?return='.self::returnUrl())
->with('messagetext','No Item Deleted')->with('msgstatus','error');
}
}
public static function display( )
{
$mode = isset($_GET['view']) ? 'view' : 'default' ;
$model = new Adminorders();
$info = $model::makeInfo('adminorders');
$data = array(
'pageTitle' => $info['title'],
'pageNote' => $info['note']
);
if($mode == 'view')
{
$id = $_GET['view'];
$row = $model::getRow($id);
if($row)
{
$data['row'] = $row;
$data['fields'] = \SiteHelpers::fieldLang($info['config']['grid']);
$data['id'] = $id;
return view('adminorders.public.view',$data);
}
} else {
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$params = array(
'page' => $page ,
'limit' => (isset($_GET['rows']) ? filter_var($_GET['rows'],FILTER_VALIDATE_INT) : 10 ) ,
'sort' => 'SiparisID' ,
'order' => 'asc',
'params' => '',
'global' => 1
);
$result = $model::getRows( $params );
$data['tableGrid'] = $info['config']['grid'];
$data['rowData'] = $result['rows'];
$page = $page >= 1 && filter_var($page, FILTER_VALIDATE_INT) !== false ? $page : 1;
$pagination = new Paginator($result['rows'], $result['total'], $params['limit']);
$pagination->setPath('');
$data['i'] = ($page * $params['limit'])- $params['limit'];
$data['pagination'] = $pagination;
return view('adminorders.public.index',$data);
}
}
function postSavepublic( Request $request)
{
$rules = $this->validateForm();
$validator = Validator::make($request->all(), $rules);
if ($validator->passes()) {
$data = $this->validatePost('tb_orders');
$this->model->insertRow($data , $request->input('SiparisID'));
return Redirect::back()->with('messagetext','<p class="alert alert-success">'.\Lang::get('core.note_success').'</p>')->with('msgstatus','success');
} else {
return Redirect::back()->with('messagetext','<p class="alert alert-danger">'.\Lang::get('core.note_error').'</p>')->with('msgstatus','error')
->withErrors($validator)->withInput();
}
}
}
I'm having trouble getting the "stock" blog functionality / template working within FUEL CMS.
I have read that it is already there, stock with the download configuration of the CMS; I have also tried creating one from scratch and uploading a 'blog' theme from a project found in GitHub. None have worked so far.
I found the blog variable at:
_variables/global.php
I have created a 'blog' controller via interpretation of (gappy) docs.
By adding the below code within it; then making a corresponding 'blog.php' view. I get nothing but a 404 error.
<?php
class Blog extends CI_Controller {
public function view($page = 'home')
{
//you can acesse this http://example.com/blog/view/
}
public function new($page = 'home')
{
//you can acesse this http://example.com/blog/new/
}
}
Within the modules folder. I found this 'stock' blog controller file. But don't know how to use it? found at: /fuel/modules/blog/controller/blog.php
<?php
require_once(MODULES_PATH.'/blog/libraries/Blog_base_controller.php');
class Blog extends Blog_base_controller {
function __construct()
{
parent::__construct();
}
function _remap()
{
$year = ($this->uri->rsegment(2) != 'index') ? (int) $this->uri->rsegment(2) : NULL;
$month = (int) $this->uri->rsegment(3);
$day = (int) $this->uri->rsegment(4);
$slug = $this->uri->rsegment(5);
$limit = (int) $this->fuel->blog->config('per_page');
$view_by = 'page';
// we empty out year variable if it is page because we won't be querying on year'
if (preg_match('#\d{4}#', $year) && !empty($year) && empty($slug))
{
$view_by = 'date';
}
// if the first segment is id then treat the second segment as the id
else if ($this->uri->rsegment(2) === 'id' && $this->uri->rsegment(3))
{
$view_by = 'slug';
$slug = (int) $this->uri->rsegment(3);
$post = $this->fuel->blog->get_post($slug);
if (isset($post->id))
{
redirect($post->url);
}
}
else if (!empty($slug))
{
$view_by = 'slug';
}
// set this to false so that we can use segments for the limit
$cache_id = fuel_cache_id();
$cache = $this->fuel->blog->get_cache($cache_id);
if (!empty($cache))
{
$output =& $cache;
}
else
{
$vars = $this->_common_vars();
if ($view_by == 'slug')
{
return $this->post($slug);
}
else if ($view_by == 'date')
{
$page_title_arr = array();
$posts_date = mktime(0, 0, 0, $month, $day, $year);
if (!empty($day)) $page_title_arr[] = $day;
if (!empty($month)) $page_title_arr[] = date('M', strtotime($posts_date));
if (!empty($year)) $page_title_arr[] = $year;
// run before_posts_by_date hook
$hook_params = array('year' => $year, 'month' => $month, 'day' => $day, 'slug' => $slug, 'limit' => $limit);
$this->fuel->blog->run_hook('before_posts_by_date', $hook_params);
$vars = array_merge($vars, $hook_params);
$vars['page_title'] = $page_title_arr;
$vars['posts'] = $this->fuel->blog->get_posts_by_date($year, (int) $month, $day, $slug);
$vars['pagination'] = '';
}
else
{
$limit = $this->fuel->blog->config('per_page');
$this->load->library('pagination');
$config['uri_segment'] = 3;
$offset = $this->uri->segment($config['uri_segment']);
$this->config->set_item('enable_query_strings', FALSE);
$config = $this->fuel->blog->config('pagination');
$config['base_url'] = $this->fuel->blog->url('page/');
//$config['total_rows'] = $this->fuel->blog->get_posts_count();
$config['page_query_string'] = FALSE;
$config['per_page'] = $limit;
$config['num_links'] = 2;
//$this->pagination->initialize($config);
if (!empty($offset))
{
$vars['page_title'] = lang('blog_page_num_title', $offset, $offset + $limit);
}
else
{
$vars['page_title'] = '';
}
// run before_posts_by_date hook
$hook_params = array('offset' => $offset, 'limit' => $limit, 'type' => 'posts');
$this->fuel->blog->run_hook('before_posts_by_page', $hook_params);
$vars['offset'] = $offset;
$vars['limit'] = $limit;
$vars['posts'] = $this->fuel->blog->get_posts_by_page($limit, $offset);
// run hook again to get the proper count
$hook_params['type'] = 'count';
$this->fuel->blog->run_hook('before_posts_by_page', $hook_params);
//$config['total_rows'] = count($this->fuel->blog->get_posts_by_page());
$config['total_rows'] = $this->fuel->blog->get_posts_count();
// create pagination
$this->pagination->initialize($config);
$vars['pagination'] = $this->pagination->create_links();
}
// show the index page if the page doesn't have any uri_segment(3)'
$view = ($this->uri->rsegment(2) == 'index' OR ($this->uri->rsegment(2) == 'page' AND !$this->uri->segment(3))) ? 'index' : 'posts';
$output = $this->_render($view, $vars, TRUE);
$this->fuel->blog->save_cache($cache_id, $output);
}
$this->output->set_output($output);
}
function post($slug = null)
{
if (empty($slug))
{
redirect_404();
}
$this->load->library('session');
$blog_config = $this->fuel->blog->config();
// run before_posts_by_date hook
$hook_params = array('slug' => $slug);
$this->fuel->blog->run_hook('before_post', $hook_params);
$post = $this->fuel->blog->get_post($slug);
if (isset($post->id))
{
$vars = $this->_common_vars();
$vars['post'] = $post;
$vars['user'] = $this->fuel->blog->logged_in_user();
$vars['page_title'] = $post->title;
$vars['next'] = $this->fuel->blog->get_next_post($post);
$vars['prev'] = $this->fuel->blog->get_prev_post($post);
$vars['slug'] = $slug;
$vars['is_home'] = $this->fuel->blog->is_home();
$antispam = md5(random_string('unique'));
$field_values = array();
// post comment
if (!empty($_POST))
{
$field_values = $_POST;
// the id of "content" is a likely ID on the front end, so we use comment_content and need to remap
$field_values['content'] = $field_values['new_comment'];
unset($field_values['antispam']);
if (!empty($_POST['new_comment']))
{
$vars['processed'] = $this->_process_comment($post);
}
else
{
add_error(lang('blog_error_blank_comment'));
}
}
$cache_id = fuel_cache_id();
$cache = $this->fuel->blog->get_cache($cache_id);
if (!empty($cache) AND empty($_POST))
{
$output =& $cache;
}
else
{
$this->load->library('form');
if (is_true_val($this->fuel->blog->config('use_captchas')))
{
$captcha = $this->_render_captcha();
$vars['captcha'] = $captcha;
}
$vars['thanks'] = ($this->session->flashdata('thanks')) ? blog_block('comment_thanks', $vars, TRUE) : '';
$vars['comment_form'] = '';
$this->session->set_userdata('antispam', $antispam);
if ($post->allow_comments)
{
$this->load->module_model(BLOG_FOLDER, 'blog_comments_model');
$this->load->library('form_builder', $blog_config['comment_form']);
$fields['author_name'] = array('label' => 'Name', 'required' => TRUE);
$fields['author_email'] = array('label' => 'Email', 'required' => TRUE);
$fields['author_website'] = array('label' => 'Website');
$fields['new_comment'] = array('label' => 'Comment', 'type' => 'textarea', 'required' => TRUE);
$fields['post_id'] = array('type' => 'hidden', 'value' => $post->id);
$fields['antispam'] = array('type' => 'hidden', 'value' => $antispam);
if (!empty($vars['captcha']))
{
$fields['captcha'] = array('required' => TRUE, 'label' => 'Security Text', 'value' => '', 'after_html' => ' <span class="captcha">'.$vars['captcha']['image'].'</span><br /><span class="captcha_text">'.lang('blog_captcha_text').'</span>');
}
// now merge with config... can't do array_merge_recursive'
foreach($blog_config['comment_form']['fields'] as $key => $field)
{
if (isset($fields[$key])) $fields[$key] = array_merge($fields[$key], $field);
}
if (!isset($blog_config['comment_form']['label_layout'])) $this->form_builder->label_layout = 'left';
if (!isset($blog_config['comment_form']['submit_value'])) $this->form_builder->submit_value = 'Submit Comment';
if (!isset($blog_config['comment_form']['use_form_tag'])) $this->form_builder->use_form_tag = TRUE;
if (!isset($blog_config['comment_form']['display_errors'])) $this->form_builder->display_errors = TRUE;
$this->form_builder->form_attrs = 'method="post" action="'.site_url($this->uri->uri_string()).'#comments_form"';
$this->form_builder->set_fields($fields);
$this->form_builder->set_field_values($field_values);
$this->form_builder->set_validator($this->blog_comments_model->get_validation());
$vars['comment_form'] = $this->form_builder->render();
$vars['fields'] = $fields;
}
$output = $this->_render('post', $vars, TRUE);
// save cache only if we are not posting data
if (!empty($_POST))
{
$this->fuel->blog->save_cache($cache_id, $output);
}
}
if (!empty($output))
{
$this->output->set_output($output);
return;
}
}
else
{
show_404();
}
}
function _process_comment($post)
{
if (!is_true_val($this->fuel->blog->config('allow_comments'))) return;
$notified = FALSE;
// check captcha
if (!$this->_is_valid_captcha())
{
add_error(lang('blog_error_captcha_mismatch'));
}
// check that the site is submitted via the websit
if (!$this->_is_site_submitted())
{
add_error(lang('blog_error_comment_site_submit'));
}
// check consecutive posts
if (!$this->_is_not_consecutive_post())
{
add_error(lang('blog_error_consecutive_comments'));
}
$this->load->module_model(BLOG_FOLDER, 'blog_users_model');
$user = $this->blog_users_model->find_one(array('fuel_users.email' => $this->input->post('author_email', TRUE)));
// create comment
$this->load->module_model(BLOG_FOLDER, 'blog_comments_model');
$comment = $this->blog_comments_model->create();
$comment->post_id = $post->id;
$comment->author_id = (!empty($user->id)) ? $user->id : NULL;
$comment->author_name = $this->input->post('author_name', TRUE);
$comment->author_email = $this->input->post('author_email', TRUE);
$comment->author_website = $this->input->post('author_website', TRUE);
$comment->author_ip = $_SERVER['REMOTE_ADDR'];
$comment->content = trim($this->input->post('new_comment', TRUE));
$comment->date_added = NULL; // will automatically be added
//http://googleblog.blogspot.com/2005/01/preventing-comment-spam.html
//http://en.wikipedia.org/wiki/Spam_in_blogs
// check double posts by IP address
if ($comment->is_duplicate())
{
add_error(lang('blog_error_comment_already_submitted'));
}
// if no errors from above then proceed to submit
if (!has_errors())
{
// submit to akisment for validity
$comment = $this->_process_akismet($comment);
// process links and add no follow attribute
$comment = $this->_filter_comment($comment);
// set published status
if (is_true_val($comment->is_spam) OR $this->fuel->blog->config('monitor_comments'))
{
$comment->published = 'no';
}
// save comment if saveable and redirect
if (!is_true_val($comment->is_spam) OR (is_true_val($comment->is_spam) AND $this->fuel->blog->config('save_spam')))
{
if ($comment->save())
{
$notified = $this->_notify($comment, $post);
$this->load->library('session');
$vars['post'] = $post;
$vars['comment'] = $comment;
$this->session->set_flashdata('thanks', TRUE);
$this->session->set_userdata('last_comment_ip', $_SERVER['REMOTE_ADDR']);
$this->session->set_userdata('last_comment_time', time());
redirect($post->url);
}
else
{
add_errors($comment->errors());
}
}
else
{
add_error(lang('blog_comment_is_spam'));
}
}
return $notified;
}
// check captcha validity
function _is_valid_captcha()
{
$valid = TRUE;
// check captcha
if (is_true_val($this->fuel->blog->config('use_captchas')))
{
if (!$this->input->post('captcha'))
{
$valid = FALSE;
}
else if (!is_string($this->input->post('captcha')))
{
$valid = FALSE;
}
else
{
$post_captcha_md5 = $this->_get_encryption($this->input->post('captcha'));
$session_captcha_md5 = $this->session->userdata('comment_captcha');
if ($post_captcha_md5 != $session_captcha_md5)
{
$valid = FALSE;
}
}
}
return $valid;
}
// check to make sure the site issued a session variable to check against
function _is_site_submitted()
{
return ($this->session->userdata('antispam') AND $this->input->post('antispam') == $this->session->userdata('antispam'));
}
// disallow multiple successive submissions
function _is_not_consecutive_post()
{
$valid = TRUE;
$time_exp_secs = $this->fuel->blog->config('multiple_comment_submission_time_limit');
$last_comment_time = ($this->session->userdata('last_comment_time')) ? $this->session->userdata('last_comment_time') : 0;
$last_comment_ip = ($this->session->userdata('last_comment_ip')) ? $this->session->userdata('last_comment_ip') : 0;
if ($_SERVER['REMOTE_ADDR'] == $last_comment_ip AND !empty($time_exp_secs))
{
if (time() - $last_comment_time < $time_exp_secs)
{
$valid = FALSE;
}
}
return $valid;
}
// process through akisment
function _process_akismet($comment)
{
if ($this->fuel->blog->config('akismet_api_key'))
{
$this->load->module_library(BLOG_FOLDER, 'akismet');
$akisment_comment = array(
'author' => $comment->author_name,
'email' => $comment->author_email,
'body' => $comment->content
);
$config = array(
'blog_url' => $this->fuel->blog->url(),
'api_key' => $this->fuel->blog->config('akismet_api_key'),
'comment' => $akisment_comment
);
$this->akismet->init($config);
if ( $this->akismet->errors_exist() )
{
if ( $this->akismet->is_error('AKISMET_INVALID_KEY') )
{
log_message('error', 'AKISMET :: Theres a problem with the api key');
}
elseif ( $this->akismet->is_error('AKISMET_RESPONSE_FAILED') )
{
log_message('error', 'AKISMET :: Looks like the servers not responding');
}
elseif ( $this->akismet->is_error('AKISMET_SERVER_NOT_FOUND') )
{
log_message('error', 'AKISMET :: Wheres the server gone?');
}
}
else
{
$comment->is_spam = ($this->akismet->is_spam()) ? 'yes' : 'no';
}
}
return $comment;
}
// strip out
function _filter_comment($comment)
{
$this->load->helper('security');
$comment_attrs = array('content', 'author_name', 'author_email', 'author_website');
foreach($comment_attrs as $filter)
{
$text = $comment->$filter;
// first remove any nofollow attributes to clean up... not perfect but good enough
$text = preg_replace('/<a(.+)rel=["\'](.+)["\'](.+)>/Umi', '<a$1rel="nofollow"$3>', $text);
// $text = str_replace('<a ', '<a rel="nofollow"', $text);
$text = strip_image_tags($text);
$comment->$filter = $text;
}
return $comment;
}
function _notify($comment, $post)
{
// send email to post author
if (!empty($post->author))
{
$config['wordwrap'] = TRUE;
$this->load->library('email', $config);
$this->email->from($this->fuel->config('from_email'), $this->fuel->config('site_name'));
$this->email->to($post->author->email);
$this->email->subject(lang('blog_comment_monitor_subject', $this->fuel->blog->config('title')));
$msg = lang('blog_comment_monitor_msg');
$msg .= "\n".fuel_url('blog/comments/edit/'.$comment->id)."\n\n";
$msg .= (is_true_val($comment->is_spam)) ? lang('blog_email_flagged_as_spam')."\n" : '';
$msg .= lang('blog_email_published').": ".$comment->published."\n";
$msg .= lang('blog_email_author_name').": ".$comment->author_name."\n";
$msg .= lang('blog_email_author_email').": ".$comment->author_email."\n";
$msg .= lang('blog_email_author_website').": ".$comment->author_website."\n";
$msg .= lang('blog_email_author_ip').": ".gethostbyaddr($comment->author_ip)." (".$comment->author_ip.")\n";
$msg .= lang('blog_email_content').": ".$comment->content."\n";
$this->email->message($msg);
return $this->email->send();
}
else
{
return FALSE;
}
}
function _render_captcha()
{
$this->load->library('captcha');
$blog_config = $this->config->item('blog');
$assets_folders = $this->config->item('assets_folders');
$blog_folder = MODULES_PATH.BLOG_FOLDER.'/';
$captcha_path = $blog_folder.'assets/captchas/';
$word = strtoupper(random_string('alnum', 5));
$captcha_options = array(
'word' => $word,
'img_path' => $captcha_path, // system path to the image
'img_url' => captcha_path('', BLOG_FOLDER), // web path to the image
'font_path' => $blog_folder.'fonts/',
);
$captcha_options = array_merge($captcha_options, $blog_config['captcha']);
if (!empty($_POST['captcha']) AND $this->session->userdata('comment_captcha') == $this->input->post('captcha'))
{
$captcha_options['word'] = $this->input->post('captcha');
}
$captcha = $this->captcha->get_captcha_image($captcha_options);
$captcha_md5 = $this->_get_encryption($captcha['word']);
$this->session->set_userdata('comment_captcha', $captcha_md5);
return $captcha;
}
function _get_encryption($word)
{
$captcha_md5 = md5(strtoupper($word).$this->config->item('encryption_key'));
return $captcha_md5;
}
}
My goal is:
1.) Enable 'Blog' Module / template / functionality and understand how I did it. I find the docs lacking, I'm also new at code igniter so that could be why. I just want the most basic way to do this for now.
And 2.) I want to create a page 'from scratch' that resolves on the dashboard side as well. I have created pages in /views/ but they resolve with that whole string /fuel/application/views/page/ I want to create a normal page without all that in the URL. I have tried creating corresponding controllers even variables and haven't had much luck!!!!!!!
As of FUEL CMS 1.0 the blog module is no longer bundled with the CMS by default. You would need to do the following:
Download & setup FUEL CMS per the install instructions here: https://github.com/daylightstudio/FUEL-CMS
Next, once you've got that up and running you can download & setup the blog module per the instructions here: https://github.com/daylightstudio/FUEL-CMS-Blog-Module
Once the blog is setup, you should be able to access it at "yourdomain.com/blog". As far as creating themes, there is a views/themes folder in the blog module which contains a default theme and also where you can setup your custom theme. Additional information about the blog module & theming can be found here http://docs.getfuelcms.com/modules/blog
Function fn_redirect($url,true,true) not working when iam adding it in new addon in cscart that i have created. I have added use Tygh\Registry;. But why its not working?
In my buy now addon, im calling fn_redirect in the buy_now.php (controller). It is doing the same functionality as addtocart. But it has to redirected to checkout page after the item is added to cart.
if ($mode == 'add') {
if (empty($auth['user_id']) && Registry::get('settings.General.allow_anonymous_shopping') != 'allow_shopping') {
return array(CONTROLLER_STATUS_REDIRECT, "auth.login_form?return_url=" . urlencode($_REQUEST['return_url']));
}
// Add to cart button was pressed for single product on advanced list
if (!empty($dispatch_extra)) {
if (empty($_REQUEST['product_data'][$dispatch_extra]['amount'])) {
$_REQUEST['product_data'][$dispatch_extra]['amount'] = 1;
}
foreach ($_REQUEST['product_data'] as $key => $data) {
if ($key != $dispatch_extra && $key != 'custom_files') {
unset($_REQUEST['product_data'][$key]);
}
}
}
$prev_cart_products = empty($cart['products']) ? array() : $cart['products'];
fn_add_product_to_cart($_REQUEST['product_data'], $cart, $auth);
fn_save_cart_content($cart, $auth['user_id']);
//header("Location: ". Registry::get('config.https_location') . "/checkout");
fn_redirect(Registry::get('config.https_location') . "/checkout",true);
$previous_state = md5(serialize($cart['products']));
$cart['change_cart_products'] = true;
fn_calculate_cart_content($cart, $auth, 'S', true, 'F', true);
if (md5(serialize($cart['products'])) != $previous_state && empty($cart['skip_notification'])) {
$product_cnt = 0;
$added_products = array();
foreach ($cart['products'] as $key => $data) {
if (empty($prev_cart_products[$key]) || !empty($prev_cart_products[$key]) && $prev_cart_products[$key]['amount'] != $data['amount']) {
$added_products[$key] = $data;
$added_products[$key]['product_option_data'] = fn_get_selected_product_options_info($data['product_options']);
if (!empty($prev_cart_products[$key])) {
$added_products[$key]['amount'] = $data['amount'] - $prev_cart_products[$key]['amount'];
}
$product_cnt += $added_products[$key]['amount'];
}
}
if (!empty($added_products)) {
Registry::get('view')->assign('added_products', $added_products);
if (Registry::get('config.tweaks.disable_dhtml') && Registry::get('config.tweaks.redirect_to_cart')) {
Registry::get('view')->assign('continue_url', (!empty($_REQUEST['redirect_url']) && empty($_REQUEST['appearance']['details_page'])) ? $_REQUEST['redirect_url'] : $_SESSION['continue_url']);
}
// $msg = Registry::get('view')->fetch('views/checkout/checkout.tpl');
// fn_set_notification('I', __($product_cnt > 1 ? 'products_added_to_cart' : 'product_added_to_cart'), $msg, 'I');
$cart['recalculate'] = true;
} else {
fn_set_notification('N', __('notice'), __('product_in_cart'));
}
}
unset($cart['skip_notification']);
$_suffix = '.checkout';
if (Registry::get('config.tweaks.disable_dhtml') && Registry::get('config.tweaks.redirect_to_cart') && !defined('AJAX_REQUEST')) {
if (!empty($_REQUEST['redirect_url']) && empty($_REQUEST['appearance']['details_page'])) {
$_SESSION['continue_url'] = fn_url_remove_service_params($_REQUEST['redirect_url']);
}
unset($_REQUEST['redirect_url']);
}
}
return array(CONTROLLER_STATUS_REDIRECT, 'checkout.cart');
}
in add_to_cart.post.tpl
{$id = "buy_now_{$product.product_id}"}
<button id="opener_{$id}" name="dispatch[buy_now.add..{$product.product_id}]" onclick="goto_checkout()" data-ca-target-id="content_{$id}" class=" buynow_btn">BUY NOW</button>
If you are using it into a controller php file, something like
app/addons/MY_ADDON/controllers/frontend/MY_ADDON.php
you can use
return array(CONTROLLER_STATUS_REDIRECT, $url);
I have this class for show error with session method using PHP.
class Messages {
//-----------------------------------------------------------------------------------------------
// Class Variables
//-----------------------------------------------------------------------------------------------
var $msgId;
var $msgTypes = array( 'help', 'info', 'warning', 'success', 'danger' );
var $msgClass = 'alert';
var $msgWrapper = " <div class='alert %s-%s flashit'>
<button class='close' aria-hidden='true' data-dismiss='alert' type='button'>×</button>
<p><i style='vertical-align: middle;' class='%s icon-2x'></i> %s</p>
</div>";
var $msgBefore = '';
var $msgAfter = "";
public function __construct() {
// Generate a unique ID for this user and session
$this->msgId = md5(uniqid());
// Create the session array if it doesnt already exist
if( !array_key_exists('flash_messages', $_SESSION) ) $_SESSION['flash_messages'] = array();
}
public function add($type, $message, $redirect_to=null) {
if( !isset($_SESSION['flash_messages']) ) return false;
if( !isset($type) || !isset($message[0]) ) return false;
// Replace any shorthand codes with their full version
if( strlen(trim($type)) == 1 ) {
$type = str_replace( array('h', 'i', 'w', 'e', 's'), array('help', 'info', 'warning', 'danger', 'success'), $type );
$icon = str_replace( array('h', 'i', 'w', 'e', 's'), array('fa-help', 'fa-info', 'fa-warning', 'fa-danger', 'fa-success'), $type );
// Backwards compatibility...
} elseif( $type == 'information' ) {
$type = 'info';
$icon = 'fa-info';
}
// Make sure it's a valid message type
if( !in_array($type, $this->msgTypes) ) die('"' . strip_tags($type) . '" is not a valid message type!' );
// If the session array doesn't exist, create it
if( !array_key_exists( $type, $_SESSION['flash_messages'] ) ) $_SESSION['flash_messages'][$type] = array();
$_SESSION['flash_messages'][$type][] = $message;
if( !is_null($redirect_to) ) {
header("Location: $redirect_to");
exit();
}
return true;
}
//-----------------------------------------------------------------------------------------------
// display()
// print queued messages to the screen
//-----------------------------------------------------------------------------------------------
public function display($type='all', $print=true) {
$messages = '';
$data = '';
if( !isset($_SESSION['flash_messages']) ) return false;
if( $type == 'g' || $type == 'growl' ) {
$this->displayGrowlMessages();
return true;
}
// Print a certain type of message?
if( in_array($type, $this->msgTypes) ) {
foreach( $_SESSION['flash_messages'][$type] as $msg ) {
$messages .= $this->msgBefore . $msg . $this->msgAfter;
}
$data .= sprintf($this->msgWrapper, $this->msgClass, $type,$icon,$messages);
// Clear the viewed messages
$this->clear($type);
// Print ALL queued messages
} elseif( $type == 'all' ) {
foreach( $_SESSION['flash_messages'] as $type => $msgArray ) {
$messages = '';
foreach( $msgArray as $msg ) {
$messages .= $this->msgBefore . $msg . $this->msgAfter;
}
$data .= sprintf($this->msgWrapper, $this->msgClass, $type,$icon,$messages);
}
// Clear ALL of the messages
$this->clear();
// Invalid Message Type?
} else {
return false;
}
// Print everything to the screen or return the data
if( $print ) {
echo $data;
} else {
return $data;
}
}
//..... more
}
Call:
$msg = new Messages();
$msg->add('i', 'This is a Information message!');
echo $msg->display();
Now in Output:
<i style="vertical-align: middle;" class=" icon-2x"></i>
Icon class not printed and empty: class=" icon-2x". how do can i fix this ?
EDit: Indeed i need to print for each type One class name.
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");
}