Unable to load page with codeigniter - php

On my codeigniter HMVC project. When I try to run my first isset statement in modules foreach section. If I uncomment the code below then, fire fox loads page error The connection was reset.
But if I comment out the code like below the page loads fine very strange.
//if (isset($part[0]) && $this->setting->get($part[0] . '_status')) {
// $data['modules'][] = Modules::run('catalog/module/'.$part[0].'/index');
//}
For some reason does not like using isset($part[0])
How code works
$part[0] it returns the module name example category
$part[1] it returns the module number example 66 category.66
$this->setting->get($part[0] . '_status') returns either 1 if
enabled or 0 if disabled.
What could be the cause of page not loading when I uncomment the code above. Any suggestions
Controller
<?php
class Column_left extends MX_Controller {
public function index() {
$this->load->model('catalog/extension/model_extension_extension');
$this->load->model('catalog/design/model_design_layout');
$route = $this->uri->segment(1).'/'.$this->uri->segment(2);
// $route outputs like pages/category
$layout_id = 0;
if (!$layout_id) {
$layout_id = $this->model_design_layout->get_layout($route);
}
if (!$layout_id) {
// Setting library autoloaded
$layout_id = $this->setting->get('config_layout_id');
}
$data['modules'] = array();
$modules = $this->model_design_layout->get_layout_modules($layout_id, 'column_left');
foreach ($modules as $module) {
$part = explode('.', $module['code']);
echo $part[0];
// Setting library autoloaded
if (isset($part[0]) && $this->setting->get($part[0] . '_status')) {
$data['modules'][] = Modules::run('catalog/module/'.$part[0].'/index');
}
if (isset($part[1])) {
$setting_info = $this->model_extension_module->get_module($part[1]);
if ($setting_info && $setting_info['status']) {
$data['modules'][] = Modules::run('catalog/module/'.$part[0].'/index', $setting_info);
}
}
}
// Setting library autoloaded
if (file_exists(DIR_TEMPLATE .$this->setting->get('config_template'). '/template/common/column_left_view.php')) {
$this->load->view('theme/'.$this->setting->get('config_template').'/template/common/column_left_view', $data);
} else {
$this->load->view('theme/default/template/common/column_left_view', $data);
}
}
}
View
<?php if ($modules) { ?>
<column id="column-left" class="col-sm-3 hidden-xs">
<?php foreach ($modules as $module) { ?>
<?php echo $module; ?>
<?php } ?>
</column>
<?php } ?>

After working on it all after noon, was able to find the cause of the issue.
In my catalog modules folder I had 2 controllers named the same in different folders, catalog/category & module/category. Even though they were in different folders one was over riding other and causing page load error on fire fox.
How I solved problem. By renaming the controller in subfolder catalog to categories I refreshed page and then works.
I also cleaned up code here.
<?php
class Column_left extends MX_Controller {
public function index() {
$this->load->model('catalog/design/model_design_layout');
$route = $this->uri->segment(1).'/'.$this->uri->segment(2);
$layout_id = 0;
if (!$layout_id) {
$layout_id = $this->model_design_layout->get_layout($route);
}
if (!$layout_id) {
$layout_id = $this->setting->get('config_layout_id');
}
$data['modules'] = array();
$results = $this->model_design_layout->get_layout_modules($layout_id);
foreach ($results as $result) {
$part = explode('.', $result['code']);
if (isset($part[0]) && $this->setting->get($part[0] . '_status')) {
$data['modules'][] = Modules::run('catalog/module/'.$part[0].'/index');
}
if (isset($part[1])) {
$this->load->model('catalog/extension/model_extension_module');
$setting_info = $this->model_extension_module->get_module($part[1]);
if ($setting_info && $setting_info['status']) {
$data['modules'][] = Modules::run('catalog/module/'.$part[0].'/index', $setting_info);
}
}
}
$this->load->view('theme/default/template/common/column_left_view', $data);
}
}

Related

Why is my array not being accessed by an included file?

I'm working on a site from scratch. Partially as practice and to help a friend. One of the things I'm doing is creating the menu dynamically off of plugins and modules that we create. My current config defines the base files and then the user plugin is supposed to be able to push more data into the array.
What I have currently is
<?php
function Deny() {
if(!defined("__directaccess")) {
header("Location: /");
}
}
Deny();
$Plugins = array("Bootstrap", "MySQL", "User");
$menuItems = array (
"Home" => "/",
);
And that's inside my config.php file.
Within my User.class.php file which is successfully loaded with the plugin loader I've built I have
require_once(__root.'/config.php');
$menu = array (
"User Panel" => "/index.php?page=user",
"Logout" => "/index.php?page=login&module=logout",
);
print_r($menuItems);
$menuItems Gives that it's not defined.
I've checked with a simple echo "Included"; script inside the config.php file to ensure that it's being included, but at the $menuItems we fail out. What I want to happen is after the Menu has been generated I'll be able to push more data into the menuItems array so that modules/plugins can add to the menu as well and use variables within those functions to make the navigation seamless. Any help would be appreciated as I'm stumped as I don't understand why it can't access the array.
Load order to help see what's going on
index.php
LoadPlugins($Plugins);
LoadModule("TopNav");
LoadPages();
loader.php
session_start();
define("__directaccess", true);
require_once("config.php");
//Loads All Class Functions
function LoadClasses() {
foreach(glob(__class.'/*.class.php') as $class) {
if(file_exists($class)) {
require_once($class);
}
}
}
function LoadPlugins($Plugins) {
foreach($Plugins as $Plugin) {
LoadPlugin($Plugin);
}
}
function LoadPages() {
if(isset($_GET['page'])) {
if(file_exists(__root. '/includes/' . $_GET['page'] . '.php')) {
require_once(__root. '/includes/' . $_GET['page'] . '.php');
} else {
echo "Page not Found"; //Make a 404 Error Page
}
}
if(!isset($_GET['page'])) {
if(file_exists(__root . '/includes/homepage.php')) {
require_once(__root . '/includes/homepage.php');
}
}
}
function LoadModule($moduleName, $page="index") {
$path = __modules . '/' . $moduleName . '/' . $page . '.php';
if(file_exists($path)) {
require_once($path);
} else {
echo "Failed to Load module " . $moduleName;
}
}
function LoadPlugin($pluginName) {
$path = __plugins . '/' . $pluginName . '/' . $pluginName . '.class.php';
if(file_exists($path)) {
require_once($path);
} else {
echo "Failed to load plugin " . $pluginName;
}
}
The $menuItems array is first created in the config.php file and then the plugins are loaded. The thought is that the plugins should be able to access variables from within the config.php file with that format.
Full User.class.php
$menu = array (
"User Panel" => "/index.php?page=user",
"Logout" => "/index.php?page=login&module=logout",
);
print_r($menuItems);
function __isOnline() {
if(isset($_SESSION['username'])) {
return true;
} else {
return false;
}
}
class UserFunctions extends webConn {
public function userDetails($arg, $username) {
$query = <<<SQL
SELECT * FROM account WHERE username = :username
SQL;
$resource = $this->db->prepare( $query );
$resource->execute( array (
":username" => $username,
));
$result = $resource->fetch(PDO::FETCH_ASSOC);
return $result[$arg];
}
}
$userFunction = new UserFunctions();
config.php with SQL Database info Removed
<?php
function Deny() {
if(!defined("__directaccess")) {
header("Location: /");
exit();
}
}
//Deny();
$Plugins = array("Bootstrap", "MySQL", "User");
$menuItems = array (
"Home" => "/",
);
//Create a root directory base name to reference
define('__root', dirname(__file__));
//Create Class Reference Global Variable
define('__class', __root . '/classes');
//Create Module reference
define('__modules', __root.'/modules');
//Create Plugin reference
define('__plugins', __root.'/plugins');
When you call require/include inside a function, the scope is the function itself.
For example the following function
function LoadClasses() {
require_once($class);
}
is equivalent to
function LoadClasses() {
print_r($menuItems);
}
That's why $menuItems is null. To fix the problem, you can use global keyword to always refer a global variable.
gloabl $menuItems;
print_r($menuItems);

Get the function result from a class

I have a function inside a class, and I would like to get the result of this function, something like:
Returned dangerous functions are: dl, system
Here is my code
public final function filterFile(){
$disabled_functions = ini_get('disable_functions');
$disFunctionsNoSpace = str_replace(' ', '', $disabled_functions);
$disFunctions = explode(',', $disFunctionsNoSpace);
$this->disFunctions = $disFunctions;
// get file content of the uploaded file (renamed NOT the temporary)
$cFile = file_get_contents($this->fileDestination, FILE_USE_INCLUDE_PATH);
$found = array();
foreach($this->disFunctions as $kkeys => $vvals)
{
if(preg_match('#'.$vvals.'#i', $cFile))
{
array_push($found, $vvals);
}
} // end foreach
} // end filterFile
// calling the class
$up = new uploadFiles($filename);
$fileterringFile = $up->filterFile();
print_r($fileterringFile);
var_dump($fileterringFile);
EDIT: add 2 functions for errors:
// check if any uErrors
public final function checkErrors(){
$countuErrors = count($this->uErrors);
if((IsSet($this->uErrors) && (is_array($this->uErrors) && ($countuErrors > 0))))
{
return true;
}
return false;
} // end checkErrors()
// print user errors
public final function printErrors(){
$countuErrors = count($this->uErrors);
if((IsSet($this->uErrors) && (is_array($this->uErrors) && ($countuErrors > 0))))
{
echo '<ul>';
foreach($this->uErrors as $uV)
{
echo '<li>';
echo $uV;
echo '</li>';
}
echo '</ul>';
}
} // end printErrors()
Thanks in advance
at the end of end filterFile, add:
return 'Returned dangerous functions are: '.implode(',',$found);

CakePHP Cannot Pass Variable from controller that has Authentication

I'm trying to pass a working variable $count from a controller name dashboard which has authentication.. I tried to insert $this->Auth->allow('_getOnlineUsers'); so that none admin can use the function.
<?php
class DashboardsController extends AppController{
var $name = 'Dashboards';
var $uses = array('Bid', 'Account');
function beforeFilter(){
parent::beforeFilter();
if(!empty($this->Auth)) {
$this->Auth->allow('template_switch');
$this->Auth->allow('_getOnlineUsers');
}
}
function _getOnlineUsers(){
$dir = TMP . DS . 'cache' . DS;
$files = scandir($dir);
$count = 0;
foreach($files as $filename){
if(is_dir($dir . $filename)){
continue;
}
if(substr($filename, 0, 16) == 'cake_user_count_') {
$count++;
}
}
return $count;
}
then inside the same controller I pass the variable to onlineUsers
$this->set('onlineUsers', $this->_getOnlineUsers());
then in my user.ctp I tried the following
<?php echo $count;?>
<?php echo $onlineUsers;?>
nothing happened please help
does location make a difference? because here's my destinations
controller/dashboards_controller.php
/alberta_template/elements/user.ctp

Template engine {var} doesnt work

I have made a template system but the {var} doesnt output the worth.
It just output {var}.
Here is my template class:
<?php
class Template {
public $assignedValues = array();
public $tpl;
function __construct($_path = '')
{
if(!empty($_path))
{
if(file_exists($_path))
{
$this->tpl = file_get_contents($_path);
}
else
{
echo 'Error: No template found. (code 25)';
}
}
}
function assign($_searchString, $_replaceString)
{
if(!empty($_searchString))
{
$this->assignedValues[strtoupper($_searchString)] = $_replaceString;
}
}
function show()
{
if(count($this->assignedValues) > 0)
{
foreach ($this->assignedValues as $key => $value)
{
$this->tpl = str_replace('{'.$key.'}', $value, $this->tpl);
}
}
echo $this->tpl;
}
}
?>
And here is what I execute on the index:
<?php
require_once('inc/classes/class.template.php');
define('PATH', 'tpl');
//new object
$template = new Template(PATH.'/test.tpl.html');
//assign values
$template->assign('title', 'Yupa');
$template->assign('about', 'Hello!');
//show the page
$template->show();
?>
I really need some help, if you can help I'd would be very grateful.
Instead of line:
$this->assignedValues[strtoupper($_searchString)] = $_replaceString;
You should have:
$this->assignedValues[$_searchString] = $_replaceString;
and it will work.
Of course I assume that inside your template file you have content:
{title} {about}
You should change
$this->assignedValues[strtoupper($_searchString)] = $_replaceString;
to this:
$this->assignedValues["{".$_searchString . "}"] = $_replaceString ;
this will only replace your keywords with values.

Is using Controller::render() in a Model::afterSave() possible with CakePHP?

I've got some sample code that I'd like to refactor as I need it to work after a record is saved. It currently works after the record is first rendered (using the afterFilter). What it does is render the view that I want with the layout and saves it to a file.
function afterFilter() {
parent::afterFilter();
if($this->params['pass'][0] == 'contact') {
$surrenderOuput = $this->surrender($this->params['pass'][0]);
$path = WWW_ROOT . 'cache' . DS . $this->params['pass'][0] . DS . 'index.html';
$file = new File($path, true);
$file->write($surrenderOuput);
$file->close();
}
}
function surrender($action = null, $layout = null, $file = null) {
$this->beforeRender();
$viewClass = $this->view;
if ($this->view != 'View') {
if (strpos($viewClass, '.') !== false) {
list($plugin, $viewClass) = explode('.', $viewClass);
}
$viewClass = $viewClass . 'View';
App::import('View', $this->view);
}
$this->Component->beforeRender($this);
$this->params['models'] = $this->modelNames;
if (Configure::read() > 2) {
$this->set('cakeDebug', $this);
}
$View =& new $viewClass($this);
if (!empty($this->modelNames)) {
$models = array();
foreach ($this->modelNames as $currentModel) {
if (isset($this->$currentModel) && is_a($this->$currentModel, 'Model')) {
$models[] = Inflector::underscore($currentModel);
}
$isValidModel = (
isset($this->$currentModel) && is_a($this->$currentModel, 'Model') &&
!empty($this->$currentModel->validationErrors)
);
if ($isValidModel) {
$View->validationErrors[Inflector::camelize($currentModel)] =&
$this->$currentModel->validationErrors;
}
}
$models = array_diff(ClassRegistry::keys(), $models);
foreach ($models as $currentModel) {
if (ClassRegistry::isKeySet($currentModel)) {
$currentObject =& ClassRegistry::getObject($currentModel);
if (is_a($currentObject, 'Model') && !empty($currentObject->validationErrors)) {
$View->validationErrors[Inflector::camelize($currentModel)] =&
$currentObject->validationErrors;
}
}
}
}
$this->autoRender = false;
$output = $View->render($action, $layout, $file);
return $output;
}
So I'm basically rendering the view with it's layout, and returning it as output, and saving it to a file. Great. Is there any way to do something similar in a model?
You may consider setting a member variable in your afterSave() in the model and checking that value in your afterFilter() in your controller.
I found this thread while searching for how to render a view from a model. In my case I'm calling a custom method in the model, so this might not work for afterSave(), but if you're calling a custom method you can do it like this:
Controller:
$this->Model->myFunc($this);
Model
public function myFunc($object) {
$object->render();
}
Hopefully that helps someone else who comes across this thread.

Categories