Problem of Curly Brackets in my controller Php Symfony - php

I want to call my function but when I call it I have a problem with curly Brackets at the end of my code and i have this error Error SYMFONY ( {} ) in my Controller.
I have no idea where to put them for my code to work. I have this problem when I add my function that allows me to retrieve the
history of the action. The mentioned function goes as this:
$this->logHistory->addHistoryConnection($project->getId(), $user->getId(), 'Delete Local Suf', $sf_code);
Function Supp Suf
/**
* #Route("/creation/suf/supp", name="suf_supp")
*/
public function suf(
Request $request,
ShapesRepository $shapesRepository
) {
$params = $this->requestStack->getSession();
$projet = $params->get('projet');
$modules = $params->get('modules');
$fonctionnalites = $params->get('fonctionnalites');
$user = $this->getUser()->getUserEntity();
$manager = $this->graceManager;
$mapManager = $this->mapManager;
$countElements = $mapManager->getCount();
$shapes = $shapesRepository->findBy(array('projet' => $projet->getId()));
$adresseWeb = $this->getParameter('adresse_web');
$carto = $params->get('paramCarto');
$centrage = $params->get('centrage');
$cableColor = $params->get('cableColor');
$sf_code = '';
if ($request->get('suf') != '') {
$sf_code = $request->get('suf');
}
$suf = $manager->getSuf($sf_code);
$success = '';
$error = '';
$warning = '';
if ($request->query->get('success')) {
$success = $request->query->get('success');
} elseif ($request->query->get('error')) {
$error = $request->query->get('error');
} elseif ($request->query->get('warning')) {
$warning = $request->query->get('warning');
}
if ($request->isMethod('POST')) {
if ($request->request->get('sf_code') != '') {
$sf_code = $request->request->get('sf_code');
}
if ($request->get('val') != '') {
$val = $request->get('val');
}
$dir = $this->getparameter('client_directory');
$dossier = str_replace(' ', '_', $projet->getProjet());
$dir = $dir . $dossier . '/documents/';
$cable = $val[0];
$chem = $val[1];
$t_suf = $this->graceCreator->supprimeSuf($sf_code, $cable, $chem);
if ($t_suf[0][0] == '00000') {
$this->logHistorique->addHistoryConnection($projet->getId(), $user->getId(), 'Suppression Suf Local', $sf_code);
// $creator->delDirObjet( $st_code, $dir );
$data = new JsonResponse(array("success" => "create!"));
return $data;
} else {
$data = new JsonResponse(array("error" => "Error : " . $t_suf));
return $data;
}
return $this->render('Modifications/supSuf.html.twig', array(
'user' => $user,
'paramCarto' => $carto,
'cableColor' => $cableColor,
'suf' => $suf,
'adresseWeb' => $adresseWeb,
'centrage' => $centrage,
'shapes' => $shapes,
'projet' => $projet,
'modules' => $modules,
'fonctionnalites' => $fonctionnalites,
'countElements' => $countElements
));
}
}

Your only return statement is inside of an if condition. If the code does not pass the condition, it has nothing to return. The code must return something in all possible cases. If you are not still used to these practices, an IDE might guide you until it becomes a routine. PHPStorm is my personal preference.
BTW, I recommend you to switch from the array() syntax to the more globally accepted [] although you must be in PHP 5.4 or higher.

Related

List Azure files and folders from File share snapshots with php

To list the files and folders from Azure Files can be done with this code:
function ListFolder($shareName, $path)
{
global $fileRestProxy;
$vMaxResultados = 5000;
$vNextMarker = "";
$listResult = null;
try
{
do
{
$options = new ListDirectoriesAndFilesOptions();
$options->setMaxResults($vMaxResultados);
$options->setMarker($vNextMarker);
$listResult = $fileRestProxy->ListDirectoriesAndFiles($shareName,$path,$options);
$vNextMarker = $listResult->getNextMarker();
} while ($vNextMarker != "");
}
catch (Exception $e)
{
$code = $e->getCode();
$error_message = $e->getMessage();
return "ERROR:$code:$error_message";
}
return $listResult;
}
But how is the sintaxis or method to the same with a snapshot from these Share?
This doesn't work:
function ListSnapshotFolder($shareName, $path, $snapshot)
{
global $fileRestProxy;
$vMaxResultados = 5000;
$vNextMarker = "";
$listResult = null;
try
{
do
{
$options = new ListDirectoriesAndFilesOptions();
$options->setMaxResults($vMaxResultados);
$options->setMarker($vNextMarker);
$shareFull = $shareName . "?snapshot=" . $snapshot;
$listResult = $fileRestProxy->ListDirectoriesAndFiles($shareFull,$path,$options);
$vNextMarker = $listResult->getNextMarker();
} while ($vNextMarker != "");
}
catch (Exception $e)
{
$code = $e->getCode();
$error_message = $e->getMessage();
return "ERROR:$code:$error_message";
}
return $listResult;
}
Is there any parameter in the $option object to add?
Or maybe the $shareFull must be created in some format?
$shareFull = $shareName . "?snapshot=" . $snapshot;
Thanks in advance.
I believe you have found a bug in the SDK. I looked up the source code here and there's no provision to provide sharesnapshot query string parameter in the options as well as the code does not even handle it.
public function listDirectoriesAndFilesAsync(
$share,
$path = '',
ListDirectoriesAndFilesOptions $options = null
) {
Validate::notNull($share, 'share');
Validate::canCastAsString($share, 'share');
Validate::canCastAsString($path, 'path');
$method = Resources::HTTP_GET;
$headers = array();
$postParams = array();
$queryParams = array();
$path = $this->createPath($share, $path);
if (is_null($options)) {
$options = new ListDirectoriesAndFilesOptions();
}
$this->addOptionalQueryParam(
$queryParams,
Resources::QP_REST_TYPE,
'directory'
);
$this->addOptionalQueryParam(
$queryParams,
Resources::QP_COMP,
'list'
);
$this->addOptionalQueryParam(
$queryParams,
Resources::QP_PREFIX_LOWERCASE,
$options->getPrefix()
);
$this->addOptionalQueryParam(
$queryParams,
Resources::QP_MARKER_LOWERCASE,
$options->getNextMarker()
);
$this->addOptionalQueryParam(
$queryParams,
Resources::QP_MAX_RESULTS_LOWERCASE,
$options->getMaxResults()
);
$this->addOptionalQueryParam(
$queryParams,
Resources::QP_TIMEOUT,
$options->getTimeout()
);
$dataSerializer = $this->dataSerializer;
return $this->sendAsync(
$method,
$headers,
$queryParams,
$postParams,
$path,
Resources::STATUS_OK,
Resources::EMPTY_STRING,
$options
)->then(function ($response) use ($dataSerializer) {
$parsed = $dataSerializer->unserialize($response->getBody());
return ListDirectoriesAndFilesResult::create(
$parsed,
Utilities::getLocationFromHeaders($response->getHeaders())
);
}, null);
}
You may want to open up an issue here: https://github.com/Azure/azure-storage-php/issues and bring this to SDK team's attention.

Send a data from table to another table from a specific source field

Please help me about this one.
i have a table name 'aptimportdata' and 'aptimportdataaddress'.
the code below is a function for import a microsoft excel data to the website.
i want to send a data from table aptimportdata to aptimportdataaddress, but i don't know how, because in the excel file, there are 2 home address columns for one person, one with the columns name homeaddress1 to 4, and the other one is altaddress1 to 4, the "altaddress" is created for a person who have a home address more than 1.
now when i import the data from the website, the data is sent to the aptimportdata table and it doesn't have a problem when i upload the file from the website, but when i change the "altaddress" data destination table to aptimportdataaddress table, the website just give me an endless loading without a success report.
i already make a column for the "altaddress" in aptimportdataaddress table, but i cant find a solution how to make the "altaddress" data go to aptimportaddress table and its just the "altaddress" column data that i want to put at the aptimportdataaddress table.
if you need a screenshot for the what the table looks like, i'll send it.
this is my code :
= 5.3.3
* #copyright 2014 Sereware
* #developer Yudha Tama Aditiyara
* #application controller/apartement
*/
class import extends Controller
{
protected $_models = array('apartement/import/m_import');
public function dataexcel(){
$config['ajax_upload_dataexcel'] = site_url('apartement/import/ajax_upload_dataexcel');
$config['ajax_process_dataexcel'] = site_url('apartement/import/ajax_process_dataexcel/'.$this->d_page->page('noid'));
$this->load->view('apartement/import/dataexcel',$config);
}
public function ajax_upload_dataexcel(){
$id = str_replace('.','',microtime(true));
$upload = new Sereware\ExcelUpload(array('upload_dir' => SYSPATH.'files/'),false);
$upload->hasNormalFilename = true;
$this->d_page->obstart();
$upload->post();
ob_flush();
}
protected $apttower = array(
'h' => 1,'s'=>2,'y'=>3,'p'=>4
);
#{{{
protected function get_dataexcel(){
if (!isset($_REQUEST['file']) || !trim($_REQUEST['file']))return;
$file = $_REQUEST['file'];
$file = SYSPATH."files/" . $file . (pathinfo($file,PATHINFO_EXTENSION) !== 'xls' ? '.xls' : '');
if (!file_exists($file)) return;
$excel = new Sereware\Excel($file);
$data = $excel->getCells(0);
return $data;
}
protected function matcher_excelfield($dataexcelfields, $appimportdetails){
$fieldnames = array();
foreach($dataexcelfields as $indexField => $dataexcelfield) {
$dataexcelfield = strtolower(preg_replace('#[\n\r]#','',trim($dataexcelfield)));
if (isset($appimportdetails[$dataexcelfield])) {
$destfield = preg_replace('#[\n\r]#','',$appimportdetails[$dataexcelfield]->destfield);
$desttypefield = (int)$appimportdetails[$dataexcelfield]->desttypefield;
$isnormalized = $appimportdetails[$dataexcelfield]->isnormalized;
$defaultvalue = $appimportdetails[$dataexcelfield]->defaultvalue;
$appimportdetail = $appimportdetails[$dataexcelfield];
$appimportdetail_desttables = array_filter(explode(';',$appimportdetail->desttable));
foreach($appimportdetail_desttables as $tablename) {
$fieldnames[$tablename][$indexField] = array(
'destfield' => $destfield,
'desttypefield' => $desttypefield,
'isnormalized' => $isnormalized,
'defaultvalue' => $defaultvalue
);
}
}
}
return $fieldnames;
}
protected function normalize_dataexcel($destfield,$value){
$value = trim($value);
switch($destfield) {
case 25:
$value = str_replace('%','',$value);
break;
case 11:
if ($value){
$value = strtotime(str_replace('/', '-',(string)$value));
$value = date('Y-m-d',$value);
} else {
$value = null;
}
break;
case 34:
if (!$value) {
$value = -1;
} else {
$value = strtolower($value) === 'ok' ? 1 : 0;
}
break;
}
return $value;
}
public function ajax_process_dataexcel($idpage){
$appimport = $this->m_import->get_appimport();
$appimportdetails = $this->m_import->get_appimportdetails($appimport->idconnection,$appimport->noid);
$aptimportdatas = $this->m_import->get_aptimportdatas($appimport->idconnection);
$newid_aptimportdata = $this->m_import->get_maxid_aptimportdata();
$aptsyarats = $this->m_import->data_aptsyarats();
$aptdatabap = $this->m_import->data_aptbap();
$dataexcel = $this->get_dataexcel();
$dataexcelfields = $this->matcher_excelfield(array_shift($dataexcel),$appimportdetails);
$insert_data = array();
$update_data = array();
$insert_data_aptunitroom = array();
$insert_data_aptimportdataaddress = array();
$insert_data_aptunitroomsyarat = array();
$insert_data_aptdatabap = array();
$datamcarduser = $this->d_page->d_login->get_datamcarduser();
// var_dump(json_encode($dataexcelfields));
// exit();
foreach($dataexcel as $data) {
foreach($dataexcelfields as $tablename => $fieldnames) {
##-1
##-build data per-row
$ndata = array();
$ready = true;
$ndata['idcreate'] = $datamcarduser->noid;
$ndata['idupdate'] = $datamcarduser->noid;
$ndata['docreate'] = date('Y-m-d H:i:s');
$ndata['lastupdate'] = date('Y-m-d H:i:s');
foreach($fieldnames as $indexFieldExcel => $datafields) {
$fieldname = $datafields['destfield'];
$isnormalized = intval($datafields['isnormalized']);
$defaultvalue = $datafields['defaultvalue'];
$desttypefield = $datafields['desttypefield'];
if (!$isnormalized) {
$defaultvalue = $data[$indexFieldExcel];
}
$ndata[$fieldname] = $this->normalize_dataexcel($desttypefield,$defaultvalue);
}
##-2
if (isset($ndata['lotno']) && isset($aptimportdatas[$ndata['lotno']])) {
$metadata = $aptimportdatas[$ndata['lotno']];
if ($tablename === 'aptimportdata') {
$update_data[$tablename][$metadata['metadata']->noid] = $ndata;
// if (!empty($ndata['ppjbdate'])) {
// }
$update_data['aptunitroom'][$metadata['metadata']->noid] = array(
'statuslegal' => empty($ndata['ppjbdate']) ? 0 : 1,
'statusproject' => $ndata['isreadytoho']
);
$mimportlog_r = array_merge(array("noid" => $metadata['metadata']->noid), $ndata);
$insert_data['mimportlog'][] = $mimportlog_r;
continue;
}
$matchers = $metadata['matchers'];
$extrafields = $metadata['extrafields'];
if (isset($matchers[$tablename])) {
foreach($matchers[$tablename] as $_fieldname => $value) {
if ($value === (int)$ndata[$_fieldname]) {
$ready = false;
break;
}
}
}
##-
if ($ready) {
if (isset($extrafields[$tablename])) {
foreach($extrafields[$tablename] as $__fieldname => $_value) {
$ndata[$__fieldname] = $_value;
}
}
}
}
##-3
if ($ready) {
$lotno = false;
if ($tablename === 'aptimportdata') {
$lotno = $ndata['lotno'];
$ndata['noid'] = $newid_aptimportdata;
$insert_data_aptunitroom[] = array(
'noid' => $newid_aptimportdata,
'statusproject' => $ndata['isreadytoho'],
'statuslegal' => empty($ndata['ppjbdate']) ? -1 : 1
);
$insert_data_aptimportdataaddress[] = array(
'noid' => $newid_aptimportdata
);
foreach($aptsyarats as $key => &$aptsyaratdata) {
$aptsyaratdata = (array)$aptsyaratdata;
$aptsyaratdata['idaptunitroom'] = $newid_aptimportdata;
$insert_data_aptunitroomsyarat[] = $aptsyaratdata;
}
foreach($aptdatabap as $key => $data){
$data = (array)$data;
$data['idaptunitroom'] = $newid_aptimportdata;
$insert_data_aptdatabap[] = $data;
}
$newid_aptimportdata++;
}
if ($lotno !== false) {
$insert_data[$tablename][$lotno] = $ndata;
} else {
$insert_data[$tablename][] = $ndata;
}
}
}
}
$real_insert_data = array();
if (isset($insert_data['aptimportdata'])) {
$_aptimportdata = $insert_data['aptimportdata'];
$real_insert_data['aptimportdata'] = array_values($_aptimportdata);
$real_insert_data['mimportlog'] = array_values($_aptimportdata);
foreach($insert_data as $tablename => $datas) {
if ($tablename !== 'aptimportdata' && $tablename !== 'aptunitroom') {
$real_insert_data[$tablename] = array();
foreach($datas as $key => $data) {
if ((!isset($data['idaptunitroom']) || intval($data['idaptunitroom']) === 0) || $_aptimportdata[$data['lotno']]) {
$data['idaptunitroom'] = $_aptimportdata[$data['lotno']]['noid'];
}
$real_insert_data[$tablename][$key] = $data;
}
}
}
} else {
$real_insert_data = $insert_data;
}
if (!empty($insert_data_aptunitroom)) {
$real_insert_data['aptunitroom'] = $insert_data_aptunitroom;
$real_insert_data['aptimportdataaddress'] = $insert_data_aptimportdataaddress;
}
if (!empty($insert_data_aptunitroomsyarat)) {
$real_insert_data['aptunitroomsyarat'] = $insert_data_aptunitroomsyarat;
$real_insert_data['aptunitroomdatabap'] = $insert_data_aptdatabap;
}
$gagal = array();
$dbase = new Sereware\Query($appimport->idconnection);
// var_dump(json_encode($real_insert_data));
// exit();
if (!empty($real_insert_data)) {
foreach($real_insert_data as $tablename => $data) {
try {
$db = $dbase->table($tablename);
$db->insert($data);
}catch(Exception $e){
$gagal['insert'][$tablename] = $e->getMessage();
}
}
}
if (!empty($update_data)) {
foreach($update_data as $tablename => $datas) {
foreach($datas as $noid => $data) {
try {
$db = $dbase->table($tablename);
$db->where('noid','=',$noid);
$db->update($data);
}catch(Exception $e){
$gagal['update'][$tablename] = $e->getMessage();
}
}
}
}
ob_start();
echo !count($gagal);
ob_flush();
}
#}}}
}
i'm still using localhost, and sublime text.
the "altaddress" and "homeaddress" are not inside the code, because it's a columns in the table. you can only find a table name on the code.
my question is how can i make the "altaddress" data from aptimportdata table go to aptimportdataaddress table, i dont't want the altaddress go to aptimportdata table, i just want the data get to aptimportdataaddress.

SS_HTTPRequest could not be converted to a string

I have a SilverStripe (3.4) Page with a form that would work if I didn't have a DataObject in it.
public function AntwortForm($ID) {
$Nummer = Vortest_Fragen::get()->byID($ID);
if ($Nummer) {
$Art=$Nummer->Art;
}
if ($Art == 'Normal') {
$fields = new FieldList(
TextAreaField::create('Antwort'),
HiddenField::create('ID', 'ID', $ID),
HiddenField::create('VortestID', 'VortestID', $this->request->param('ID')),
HiddenField::create('Aktion', 'Aktion', $this->request->param('Action'))
);
} else {
$Optionen = explode(';', $Nummer->Optionen);
$a = 'A';
for ( $i = 0 ; $i < count ($Optionen); $i++) {
$Op[$a] ='<div style="width:25px;display:inline;">' . $a . ')</div> ' . $Optionen[$i];
$a++;
}
$fields = new FieldList(
CheckboxSetField::create('Antwort', 'Antwort', $Op),
HiddenField::create('ID', 'ID', $ID),
HiddenField::create('VortestID', 'VortestID', $this->request->param('ID')),
HiddenField::create('Aktion', 'Aktion',$this->request->param('Action')),
HiddenField::create('Art', 'Art', $Nummer->Art)
);
}
$actions = new FieldList(
FormAction::create('AntwortEintragen', 'Eintragen')
);
$form = new Form($this, 'AntwortForm', $fields, $actions);
return $form;
}
function AntwortEintragen($data, $form) {
$Antwort = Vortest_Antwort::get()->filter(array('FrageID' => $data['ID'], 'SchreiberID' => Member::currentUserID()));
foreach($Antwort as $item) {
$item->delete();
}
foreach ($data['Antwort'] as $Antwort) {
$Ant .= $Antwort . ',';
}
$Antwort = new Vortest_Antwort();
if ($data['Antwort']) {
$form->saveInto($Antwort);
if ($data['Art'] == 'Mechanics') {
$Antwort->Antwort = $Ant;
}
$Antwort->SchreiberID = Member::currentUserID();
$Antwort->FrageID = $data['ID'];
$Antwort->write();
}
$VID = $data['VortestID'];
if ($data['Aktion'] == 'AlleFragen') {
$this->redirect('/vortest/AlleFragen/' . $VID . '#' . $data['FrageNr']);
} elseif ($data['Aktion'] == 'Einzelfrage') {
$this->redirect('/vortest/Einzelfrage/' . $VID);
} else {
$this->redirect('/vortest/Test/' . $VID.'#' . $data['FrageNr']);
}
}
It works when I change the $ID to a number in this line $Nummer = Vortest_Fragen::get()->byID($ID);
When I don't change it I get the following error:
[Recoverable Error] Object of class SS_HTTPRequest could not be converted to string
How do I fix this problem?
Althought it is not clearly documented, Silverstripe secretly passes a request argument to and form methods on a controller. Your $ID argument is actually not what you think it is, you will find it is actually an SS_HTTPRequest object that Silverstripe has passed (without you realising).
To fix this, change the first line:
public function AntwortForm($ID) {
To:
public function AntwortForm($request, $ID) {
And make sure you update anywhere that you call this method :-)

accessing 'blog' functionality / template in FUEL CMS

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

Codeigniter when i submit more than one option of form_multiselect(), Only just the last one that saved on database

Codeigniter when i submit more than one option of form_multiselect(), Only just the last one that saved on database.
in my view :
<label>Trimestres :</label>
<div class="controls" >
<?php $options = array(
'trim1' => ' Premier trimestre (Janv,Fév,Mars)',
'trim2' => ' Deuxiéme trimestre (Avril,Mai,Juin)',
'trim3' => ' Troisiéme trimestre (Juill,Aout,Sept)',
'trim4' => ' Quatriéme trimestre (Oct,Nov,Déc)',
);
echo form_multiselect('trimestres', $options , $this->input->post('trimestres') ? $this->input->post('trimestres') : $participant_sport->trimestres, 'id="trim"'); ?>
</div>
</div>
in my controller :
public function inscriresport ($id = NULL)
{
// Fetch a participant or set a new one
if ($id) {
$this->data['participant_sport'] = $this->participantsport_m->get($id);
count($this->data['participant_sport']) || $this->data['errors'][] = 'participant non trouvé';
}
else {
$this->data['participant_sport'] = $this->participantsport_m->get_new();
}
// Process the form
$this->participantsport_m->array_from_post(array('matricule', 'nom', 'prenom', 'beneficiaire', 'sexe', 'telephone', 'date_naissance', 'date_inscription_sport', 'trimestres' ,'sport_montant_paye', 'sport_debut_periode', 'sport_fin_periode'));
$this->participantsport_m->save($data, $id);
redirect('admin/agent/profile/3608');
}
// Load the view
$this->data['subview'] = 'admin/agent/inscriresport';
$this->load->view('admin/_layout_main', $this->data);
}
The function array_from_post() is defined on application\core\MY_Model.php :
public function array_from_post($fields){
$data = array();
foreach ($fields as $field) {
$data[$field] = $this->input->post($field);
}
return $data;
}
in my model :
public function get_new()
{
$participant_sport = new stdClass();
$participant_sport->matricule = '';
$participant_sport->nom = '';
$participant_sport->prenom = '';
$participant_sport->beneficiaire = '';
$participant_sport->sexe = '';
$participant_sport->telephone = '';
$participant_sport->date_naissance = '';
$participant_sport->date_inscription_sport = '';
$participant_sport->trimestres = '';
$participant_sport->sport_montant_paye = '';
$participant_sport->sport_debut_periode = '';
$participant_sport->sport_fin_periode = '';
return $participant_sport;
}
Any help Please? i think that must be an array but i don't know how to do it?
i thing that i must do something like that :
foreach($_POST["strategylist[]"] as $s) {
# do the insert here, but use $s instead of $_POST["strategylist[]"]
$result=mysql_query("INSERT INTO sslink (study_id, strategyname) " .
"VALUES ('$id','" . join(",",$s) . "')")
or die("Insert Error: ".mysql_error());
}
to insert more than one option selected in one row but i don't know how to do it in codeigniter
the get() function :
public function get($id = NULL, $single = FALSE){
if ($id != NULL) {
$filter = $this->_primary_filter;
$id = $filter($id);
$this->db->where($this->_primary_key, $id);
$method = 'row';
}
elseif($single == TRUE) {
$method = 'row';
}
else {
$method = 'result';
}
if (!count($this->db->ar_orderby)) {
$this->db->order_by($this->_order_by);
}
return $this->db->get($this->_table_name)->$method();
}
If select name (in HTML tag) is trimestres it will always remember last selection. Use trimestres[] as a name to get array with all selected values`
<select name="trimestres[]" multiple …
By the way:
I don't know how array_from_post() works but it has to change trimestres[] values to one string to save all of them in one column. It is hard to search/add/delete one value if all values are in one string. It is "SQL Antipattern". You could do another table in database for trimestres - one value in one row.
Edit:
It will change all arrays into string with elements connected by ,. Not tested.
public function array_from_post($fields){
$data = array();
foreach ($fields as $field) {
// print_r($this->input->post($field));
if( is_array( $this->input->post($field) ) ) {
$data[$field] = join(",", $this->input->post($field));
} else {
$data[$field] = $this->input->post($field);
}
// print_r($data[$field]);
}
return $data;
}
Edit:
Not tested.
public function inscriresport ($id = NULL)
{
// Fetch a participant or set a new one
if ($id) {
$this->data['participant_sport'] = $this->participantsport_m->get($id);
count($this->data['participant_sport']) || $this->data['errors'][] = 'participant non trouvé';
// explode to array
// print_r($this->data['participant_sport']->trimestres); // test before explode
// $this->data['participant_sport']['trimestres'] = explode(",", $this->data['participant_sport']['trimestres']);
$this->data['participant_sport']->trimestres = explode(",", $this->data['participant_sport']->trimestres);
// print_r($this->data['participant_sport']->trimestres); // test after explode
} else {
$this->data['participant_sport'] = $this->participantsport_m->get_new();
}
// rest of code
}
There is a easy way to solve this problem that I found today.
you have to serialize the $_POST['trimestres'] array just after array_form_post .
the this array will save to database as a serialize string.
public function inscriresport ($id = NULL)
{
// Fetch a participant or set a new one
if ($id) {
$this->data['participant_sport'] = $this->participantsport_m->get($id);
count($this->data['participant_sport']) || $this->data['errors'][] = 'participant non trouvé';
}
else {
$this->data['participant_sport'] = $this->participantsport_m->get_new();
}
// Process the form
$this->participantsport_m->array_from_post(array('matricule', 'nom', 'prenom', 'beneficiaire', 'sexe', 'telephone', 'date_naissance', 'date_inscription_sport', 'trimestres' ,'sport_montant_paye', 'sport_debut_periode', 'sport_fin_periode'));
$data['trimestres'] = serialize($_POST['trimestres']);
$this->participantsport_m->save($data, $id);
redirect('admin/agent/profile/3608');
}
// Load the view
$this->data['subview'] = 'admin/agent/inscriresport';
$this->load->view('admin/_layout_main', $this->data);
}
When you just need this data back form database just use php unserialize() function .
Hope it will help to do this easily ....
-thanks

Categories