How to make custom 404 page in routing system - php

I want to make a 404 error page on this routing. How can this be done?
index.php
<?php
include 'route.php';
include 'control/about.php';
include 'control/home.php';
include 'control/contact.php';
$route = new route();
$route->add('/', function(){
echo 'Hello, this is home pageeees';
});
$route->add('/about', 'about');
$route->add('/contact', 'contact');
echo '<pre>';
print_r($route);
$route->submit();
?>
route.php
<?php
class route
{
private $_uri = array();
private $_method = array();
/**
*Builds a collection of internal URL's to look for
*#parameter type $uri
*/
public function add($uri, $method = null)
{
$this->_uri[] = '/' . trim($uri, '/');
if($method != null){
$this->_method[] = $method;
}
}
/**
*Makes the thing run!
*/
public function submit()
{
$uriGetParam = isset($_GET['uri'])? '/' . $_GET['uri'] : '/';
foreach ($this->_uri as $key => $value)
{
if(preg_match("#^$value$#",$uriGetParam))
{
if(is_string($this->_method[$key]))
{
$useMethod = $this->_method[$key];
new $useMethod();
}
else
{
call_user_func($this->_method[$key]);
}
}
}
}
}
?>

The regex in mind I would just add $route->add("/.+", function()...); after all your other routes.
Proof: https://3v4l.org/nk5PZ
But you could also program some logic which evaluates custom 404-Pages when not being able to find a correspondig route.
For example:
private $_notFound;
public function submit() {
$uriGetParam = isset($_GET['uri'])? '/' . $_GET['uri'] : '/';
$matched = false;
foreach ($this->_uri as $key => $value) {
if(preg_match("#^$value$#", $uriGetParam)) {
if(is_string($this->_method[$key])) {
$useMethod = $this->_method[$key];
new $useMethod();
} else {
call_user_func($this->_method[$key]);
}
$matched = true;
}
}
if(!$matched) {
if(isset($this->_notFound)) {
if(is_string($this->_notFound)) {
$action = $this->_notFound;
new $action();
} else {
call_user_func($this->_notFound);
}
}
}
}
public function notFound($callback) {
$this->_notFound = $callback;
}
Then you'll have to add the 404-action by $route->notFound(function... or "class");

Related

I am trying to get some content from s3 bucket AWS and upon requesting data It takes much longer than I can afford around 15 to 20 seconds

heres my api.php file code in try body else case is taking too much time
<?php
require_once(dirname(__FILE__) . "/constants.php");
includeMonstaConfig();
session_start();
require_once(dirname(__FILE__) . '/lib/helpers.php');
require_once(dirname(__FILE__) . '/lib/response_helpers.php');
require_once(dirname(__FILE__) . '/request_processor/RequestMarshaller.php');
if (file_exists(dirname(__FILE__) . '/../../mftp_extensions.php')) {
include_once(dirname(__FILE__) . '/../../mftp_extensions.php');
}
dieIfNotPOST();
require_once(dirname(__FILE__) . '/lib/access_check.php');
$marshaller = new RequestMarshaller();
try {
$request = json_decode($_POST['request'], true);
if ($request['actionName'] == 'fetchFile' || $request['actionName'] == 'downloadMultipleFiles') {
switch ($request['actionName']) {
case 'fetchFile':
$outputPath = $marshaller->prepareFileForFetch($request);
$outputFileName = monstaBasename($request['context']['remotePath']);
break;
case 'downloadMultipleFiles':
$outputResponse = $marshaller->marshallRequest($request, false, true);
$outputPath = $outputResponse["data"];
$outputFileName = "mftp_zip_" . date("Y_m_d_H_i_s") . ".zip";
}
$fileKey = generateRandomString(16);
$_SESSION[MFTP_SESSION_KEY_PREFIX . $fileKey] = array(
"path" => $outputPath,
"fileName" => $outputFileName
);
$response = array(
"success" => true,
"fileKey" => $fileKey
);
print json_encode($response);
} else {
$skipConfigurationActions = array('checkSavedAuthExists', 'writeSavedAuth', 'readSavedAuth',
'readLicense', 'getSystemVars', 'resetPassword', 'forgotPassword', 'validateSavedAuthPassword',
'downloadLatestVersionArchive', 'installLatestVersion');
$skipConfiguration = in_array($request['actionName'], $skipConfigurationActions);
$serializedResponse = $marshaller->marshallRequest($request, $skipConfiguration);
print $serializedResponse;
}
} catch (Exception $e) {
$marshaller->disconnect();
handleExceptionInRequest($e);
}
$marshaller->disconnect();
here is the RequestMarshaller.php code showing only the request code
<?php
require_once(dirname(__FILE__) . '/RequestDispatcher.php');
require_once(dirname(__FILE__) . "/../lib/helpers.php");
require_once(dirname(__FILE__) . "/../system/ApplicationSettings.php");
class RequestMarshaller {
/**
* #var RequestDispatcher
*/
private $requestDispatcher;
private function initRequestDispatcher($request, $skipConfiguration = false) {
if(!$skipConfiguration)
$request['configuration'] = $this->applyConnectionRestrictions($request['connectionType'],
$request['configuration']);
if (is_null($this->requestDispatcher))
$this->requestDispatcher = new RequestDispatcher($request['connectionType'], $request['configuration'],
null, null, $skipConfiguration);
}
public function marshallRequest($request, $skipConfiguration = false, $skipEncode = false) {
$this->initRequestDispatcher($request, $skipConfiguration);
$response = array();
if ($request['actionName'] == 'putFileContents')
$response = $this->putFileContents($request);
else if ($request['actionName'] == 'getFileContents')
$response = $this->getFileContents($request);
else {
$context = array_key_exists('context', $request) ? $request['context'] : null;
$responseData = $this->requestDispatcher->dispatchRequest($request['actionName'], $context);
$response['success'] = true;
if(is_object($responseData)) {
$response['data'] = method_exists($responseData, 'legacyJsonSerialize') ?
$responseData->legacyJsonSerialize() : $responseData;
} else
$response['data'] = $responseData;
}
if ($skipEncode)
return $response;
return json_encode($response);
}
}
}
and here is my RequestDispatcher.php code
<?php
class RequestDispatcher {
/**
* #var ConnectionBase
*/
private $connection;
/**
* #var string
*/
private $connectionType;
/**
* #var array
*/
private $rawConfiguration;
public $username;
public function getusername(){
$configuration = $this->connection->getConfiguration();
$this->username=$configuration->getRemoteUsername();
return $this->username;
}
public function __construct($connectionType, $rawConfiguration, $configurationFactory = null,
$connectionFactory = null, $skipConfiguration = false) {
$this->connectionType = $connectionType;
/* allow factory objects to be passed in for testing with mocks */
if ($skipConfiguration) {
$this->connection = null;
} else {
$this->rawConfiguration = $rawConfiguration;
$configurationFactory = is_null($configurationFactory) ? new ConfigurationFactory() : $configurationFactory;
$connectionFactory = is_null($connectionFactory) ? new ConnectionFactory() : $connectionFactory;
$configuration = $configurationFactory->getConfiguration($connectionType, $rawConfiguration);
$this->connection = $connectionFactory->getConnection($connectionType, $configuration);
}
}
public function dispatchRequest($actionName, $context = null) {
if (in_array($actionName, array(
'listDirectory',
'downloadFile',
'uploadFile',
'deleteFile',
'makeDirectory',
'deleteDirectory',
'rename',
'changePermissions',
'copy',
'testConnectAndAuthenticate',
'checkSavedAuthExists',
'writeSavedAuth',
'readSavedAuth',
'readLicense',
'getSystemVars',
'fetchRemoteFile',
'uploadFileToNewDirectory',
'downloadMultipleFiles',
'createZip',
'setApplicationSettings',
'deleteMultiple',
'extractArchive',
'updateLicense',
'reserveUploadContext',
'transferUploadToRemote',
'getRemoteFileSize',
'getDefaultPath',
'downloadForExtract',
'cleanUpExtract',
'resetPassword',
'forgotPassword',
'validateSavedAuthPassword',
'downloadLatestVersionArchive',
'installLatestVersion'
))) {
if (!is_null($context))
return $this->$actionName($context);
else
return $this->$actionName();
}
throw new InvalidArgumentException("Unknown action $actionName");
}
public function getConnection() {
return $this->connection;
}
private function connectAndAuthenticate($isTest = false) {
$sessionNeedsStarting = false;
if (function_exists("session_status")) {
if (session_status() == PHP_SESSION_NONE) {
$sessionNeedsStarting = true;
}
} else {
$sessionNeedsStarting = session_id() == "";
}
$configuration = $this->connection->getConfiguration();
$this->username=$configuration->getRemoteUsername();
if ($sessionNeedsStarting && !defined("MONSTA_UNIT_TEST_MODE")) { // TODO: pass in this as parameter to avoid global state
session_start();
$_SESSION["RemoteUsername"]=$configuration->getRemoteUsername();
}
$maxFailures = defined("MFTP_MAX_LOGIN_FAILURES") ? MFTP_MAX_LOGIN_FAILURES : 0;
$loginFailureResetTimeSeconds = defined("MFTP_LOGIN_FAILURES_RESET_TIME_MINUTES")
? MFTP_LOGIN_FAILURES_RESET_TIME_MINUTES * 60 : 0;
if (!isset($_SESSION["MFTP_LOGIN_FAILURES"]))
$_SESSION["MFTP_LOGIN_FAILURES"] = array();
$banManager = new UserBanManager($maxFailures, $loginFailureResetTimeSeconds,
$_SESSION["MFTP_LOGIN_FAILURES"]);
if ($banManager->hostAndUserBanned($configuration->getHost(), $configuration->getRemoteUsername())) {
mftpActionLog("Log in", $this->connection, "", "", "Login and user has exceed maximum failures.");
throw new FileSourceAuthenticationException("Login and user has exceed maximum failures.",
LocalizableExceptionDefinition::$LOGIN_FAILURE_EXCEEDED_ERROR, array(
"banTimeMinutes" => MFTP_LOGIN_FAILURES_RESET_TIME_MINUTES
));
}
try {
$this->connection->connect();
} catch (Exception $e) {
mftpActionLog("Log in", $this->connection, "", "", $e->getMessage());
throw $e;
}
try {
$this->connection->authenticate();
} catch (Exception $e) {
mftpActionLog("Log in", $this->connection, "", "", $e->getMessage());
$banManager->recordHostAndUserLoginFailure($configuration->getHost(),
$configuration->getRemoteUsername());
$_SESSION["MFTP_LOGIN_FAILURES"] = $banManager->getStore();
throw $e;
}
$banManager->resetHostUserLoginFailure($configuration->getHost(), $configuration->getRemoteUsername());
$_SESSION["MFTP_LOGIN_FAILURES"] = $banManager->getStore();
if ($isTest) {
// only log success if it is the first connect from the user
mftpActionLog("Log in", $this->connection, "", "", "");
}
if ($configuration->getInitialDirectory() === "" || is_null($configuration->getInitialDirectory())) {
return $this->connection->getCurrentDirectory();
}
return null;
}
public function disconnect() {
if ($this->connection != null && $this->connection->isConnected())
$this->connection->disconnect();
}
public function listDirectory($context) {
$this->connectAndAuthenticate();
$directoryList = $this->connection->listDirectory($context['path'], $context['showHidden']);
$this->disconnect();
return $directoryList;
}
public function downloadFile($context, $skipLog = false) {
$this->connectAndAuthenticate();
$transferOp = TransferOperationFactory::getTransferOperation($this->connectionType, $context);
$this->connection->downloadFile($transferOp);
if (!$skipLog) {
// e.g. if editing a file don't log that it was also downloaded
mftpActionLog("Download file", $this->connection, dirname($transferOp->getRemotePath()), monstaBasename($transferOp->getRemotePath()), "");
}
$this->disconnect();
}
public function downloadMultipleFiles($context) {
$this->connectAndAuthenticate();
$fileFinder = new RecursiveFileFinder($this->connection, $context['baseDirectory']);
$foundFiles = $fileFinder->findFilesInPaths($context['items']);
foreach ($foundFiles as $foundFile) {
$fullPath = PathOperations::join($context['baseDirectory'], $foundFile);
mftpActionLog("Download file", $this->connection, dirname($fullPath), monstaBasename($fullPath), "");
}
$zipBuilder = new ZipBuilder($this->connection, $context['baseDirectory']);
$zipPath = $zipBuilder->buildZip($foundFiles);
$this->disconnect();
return $zipPath;
}
public function createZip($context) {
$this->connectAndAuthenticate();
$fileFinder = new RecursiveFileFinder($this->connection, $context['baseDirectory']);
$foundFiles = $fileFinder->findFilesInPaths($context['items']);
foreach ($foundFiles as $foundFile) {
$fullPath = PathOperations::join($context['baseDirectory'], $foundFile);
mftpActionLog("Download file", $this->connection, dirname($fullPath), monstaBasename($fullPath), "");
}
$zipBuilder = new ZipBuilder($this->connection, $context['baseDirectory']);
$destPath = PathOperations::join($context['baseDirectory'], $context['dest']);
$zipPath = $zipBuilder->buildLocalZip($foundFiles, $destPath);
$this->connection->uploadFile(new FTPTransferOperation($zipPath, $destPath, FTP_BINARY));
$this->disconnect();
return $zipPath;
}
public function uploadFile($context, $preserveRemotePermissions = false, $skipLog = false) {
$this->connectAndAuthenticate();
$transferOp = TransferOperationFactory::getTransferOperation($this->connectionType, $context);
$this->connection->uploadFile($transferOp, $preserveRemotePermissions);
if (!$skipLog) {
// e.g. if editing a file don't log that it was also uploaded
mftpActionLog("Upload file", $this->connection, dirname($transferOp->getRemotePath()), monstaBasename($transferOp->getRemotePath()), "");
}
$this->disconnect();
}
public function uploadFileToNewDirectory($context) {
// This will first create the target directory if it doesn't exist and then upload to that directory
$this->connectAndAuthenticate();
$transferOp = TransferOperationFactory::getTransferOperation($this->connectionType, $context);
$this->connection->uploadFileToNewDirectory($transferOp);
mftpActionLog("Upload file", $this->connection, dirname($transferOp->getRemotePath()), monstaBasename($transferOp->getRemotePath()), "");
$this->disconnect();
}
public function deleteFile($context) {
$this->connectAndAuthenticate();
$this->connection->deleteFile($context['remotePath']);
mftpActionLog("Delete file", $this->connection, dirname($context['remotePath']), monstaBasename($context['remotePath']), "");
$this->disconnect();
}
public function makeDirectory($context) {
$this->connectAndAuthenticate();
$this->connection->makeDirectory($context['remotePath']);
$this->disconnect();
}
public function deleteDirectory($context) {
$this->connectAndAuthenticate();
$this->connection->deleteDirectory($context['remotePath']);
$this->disconnect();
}
public function rename($context) {
$this->connectAndAuthenticate();
if(array_key_exists('action', $context) && $context['action'] == 'move') {
$action = 'Move';
} else {
$action = 'Rename';
}
$itemType = $this->connection->isDirectory($context['source']) ? 'folder' : 'file';
$this->connection->rename($context['source'], $context['destination']);
if ($action == 'Move') {
mftpActionLog($action . " " . $itemType, $this->connection, dirname($context['source']),
monstaBasename($context['source']) . " to " . $context['destination'],
"");
}
if ($action == 'Rename') {
mftpActionLog($action . " " . $itemType, $this->connection, dirname($context['source']),
monstaBasename($context['source']) . " to " . monstaBasename($context['destination']),
"");
}
$this->disconnect();
}
public function changePermissions($context) {
$this->connectAndAuthenticate();
$itemType = $this->connection->isDirectory($context['remotePath']) ? 'folder' : 'file';
$this->connection->changePermissions($context['mode'], $context['remotePath']);
mftpActionLog("CHMOD " . $itemType, $this->connection, dirname($context['remotePath']),
monstaBasename($context['remotePath']) . " to " . decoct($context['mode']), "");
$this->disconnect();
}
public function copy($context) {
$this->connectAndAuthenticate();
$this->connection->copy($context['source'], $context['destination']);
$this->disconnect();
}
public function testConnectAndAuthenticate($context, $isInitalLogin = true) {
$initialDirectory = $this->connectAndAuthenticate($isInitalLogin);
$serverCapabilities = array("initialDirectory" => $initialDirectory);
if (isset($context['getServerCapabilities']) && $context['getServerCapabilities']) {
$serverCapabilities["changePermissions"] = $this->connection->supportsPermissionChange();
}
clearOldTransfers();
return array("serverCapabilities" => $serverCapabilities);
}
public function checkSavedAuthExists() {
if ($this->readLicense() == null)
return false;
return AuthenticationStorage::configurationExists(AUTHENTICATION_FILE_PATH);
}
public function writeSavedAuth($context) {
if ($this->readLicense() == null)
return;
AuthenticationStorage::saveConfiguration(AUTHENTICATION_FILE_PATH, $context['password'],
$context['authData']);
}
public function readSavedAuth($context) {
if ($this->readLicense() == null)
return array();
return AuthenticationStorage::loadConfiguration(AUTHENTICATION_FILE_PATH, $context['password']);
}
public function readLicense() {
$keyPairSuite = new KeyPairSuite(PUBKEY_PATH);
$licenseReader = new LicenseReader($keyPairSuite);
$license = $licenseReader->readLicense(MONSTA_LICENSE_PATH);
if (is_null($license))
return $license;
$publicLicenseKeys = array("expiryDate", "version", "isTrial", "licenseVersion", "productEdition");
$publicLicense = array();
foreach ($publicLicenseKeys as $publicLicenseKey) {
if (isset($license[$publicLicenseKey]))
$publicLicense[$publicLicenseKey] = $license[$publicLicenseKey];
}
return $publicLicense;
}
private function recordAffiliateSource($licenseEmail) {
$affiliateChecker = new AffiliateChecker();
$installUrl = getMonstaInstallUrl();
$affiliateId = defined("MFTP_AFFILIATE_ID") ? MFTP_AFFILIATE_ID : "";
return $affiliateChecker->recordAffiliateSource($affiliateId, $licenseEmail, $installUrl);
}
public function getSystemVars() {
$systemVars = SystemVars::getSystemVarsArray();
$applicationSettings = new ApplicationSettings(APPLICATION_SETTINGS_PATH);
$systemVars['applicationSettings'] = $applicationSettings->getSettingsArray();
return $systemVars;
}
public function setApplicationSettings($context) {
$applicationSettings = new ApplicationSettings(APPLICATION_SETTINGS_PATH);
$applicationSettings->setFromArray($context['applicationSettings']);
$applicationSettings->save();
}
public function validateSavedAuthPassword($context) {
return AuthenticationStorage::validateAuthenticationPassword(AUTHENTICATION_FILE_PATH, $context["password"]);
}
}
i am not that much experienced in this field i am a beginner and got this task to find out the cause of the delay and resolve it . kindly help me in this regard i have tried many things as i thought that json_encoding(response) might be the cause but just 10 items are returning in response

Redirecting users to a 404 page by using pretty urls

I'm working on a mvc project just for fun.
Pretty urls already work, but i can't find a good way with my code to send visitors to a 404 page, in case the page doesn't exist which people are looking for.
class Route
{
private $_uri = array();
private $_method = array();
/*
* Builds a collection of internal URL's to look for
* #param type $uri
*/
public function add($uri, $method = null)
{
$this->_uri[] = '/' . trim($uri, '/');
if($method != null){
$this->_method[] = $method;
}
}
public function submit()
{
$uriGetParam = isset($_GET['uri']) ? '/' . $_GET['uri'] : '/';
foreach($this->_uri as $key => $value){
if(preg_match("#^$value$#",$uriGetParam)){
if(is_string($this->_method[$key])){
$useMethod = $this->_method[$key];
new $useMethod();
}
else{
call_user_func($this->_method[$key]);
}
}
}
}
}
I didn't analyze your code thoroughly (I couldn't, not sure what is the example route / method you're adding with ->add), but the solution seems simple to me:
public function submit()
{
$uriGetParam = isset($_GET['uri']) ? '/' . $_GET['uri'] : '/';
$routeFound = false;
foreach($this->_uri as $key => $value){
if(preg_match("#^$value$#",$uriGetParam)){
if(is_string($this->_method[$key])){
$routeFound = true;
$useMethod = $this->_method[$key];
new $useMethod();
}
else{
$routeFound = true;
call_user_func($this->_method[$key]);
}
}
}
if(!$routeFound){
http_response_code(404);
echo 'ooooh, not found';
//or:
include('404.php');
die();
}
}
p.s. http_response_code is a built-in function:
https://secure.php.net/manual/en/function.http-response-code.php
edit: you could put the code starting with 'http_response_code(404);' to a separate function and just call it.

How to properly rewrite php code from version 5.6 to 7.x?

I tied it myself but it does not work for me. How to properly change for example this old code to be compatible with php 7.x?
class DbSimple_Generic
{
function& connect($dsn)
{
// Load database driver and create its instance.
$parsed = DbSimple_Generic::parseDSN($dsn);
if (!$parsed) {
$dummy = null;
return $dummy;
}
$class = 'DbSimple_'.ucfirst($parsed['scheme']);
if (!class_exists($class)) {
$file = str_replace('_', '/', $class) . ".php";
if ($f = #fopen($file, "r", true)) {
fclose($f);
require_once($file);
} else {
$base = basename($file);
$dir = dirname(__FILE__);
if (#is_file($path = "$dir/$base")) {
require_once($path);
} else {
trigger_error("Error loading database driver: no file $file in include_path; no file $base in $dir", E_USER_ERROR);
return null;
}
}
}
$object =& new $class($parsed);
if (isset($parsed['ident_prefix'])) {
$object->setIdentPrefix($parsed['ident_prefix']);
}
class DbSimple_Mysql_Blob extends DbSimple_Generic_Blob
{
var $blobdata = null;
var $curSeek = 0;
function DbSimple_Mysql_Blob(&$database, $blobdata=null)
{
$this->blobdata = $blobdata;
$this->curSeek = 0;
}
function read($len)
{
$p = $this->curSeek;
$this->curSeek = min($this->curSeek + $len, strlen($this->blobdata));
return substr($this->blobdata, $this->curSeek, $len);
}
function write($data)
{
$this->blobdata .= $data;
}
function close()
{
return $this->blobdata;
}
function length()
{
return strlen($this->blobdata);
}
}
function& _performNewBlob($blobid=null)
{
$obj =& new DbSimple_Mysql_Blob($this, $blobid);
return $obj;
}
I tried to use every possible way to make this work like this:
$object = new $class($parsed);
$object->method();
Becase it seems for PHP 7.x is this the most problematic part:
$object =& new $class($parsed);
But thisdid not work. I tried to find it on some PHP documentation but no luck so far. So how to properly rewrite this? Thank you
Using this on Ubuntu Server 64bit 16.04+ with Apache and mysql.
Probably it is a better idea to understand that function and rewrite in a cleaner way but please find below my changes, hopefully it helps.
class DbSimple_Generic
{
function connect($dsn)
{
// Load database driver and create its instance.
$parsed = DbSimple_Generic::parseDSN($dsn);
if (!$parsed) {
$dummy = null;
return $dummy;
}
$class = 'DbSimple_'.ucfirst($parsed['scheme']);
if (!class_exists($class)) {
$file = str_replace('_', '/', $class) . ".php";
if ($f = #fopen($file, "r", true)) {
fclose($f);
require_once($file);
} else {
$base = basename($file);
$dir = dirname(__FILE__);
if (#is_file($path = "$dir/$base")) {
require_once($path);
} else {
trigger_error("Error loading database driver: no file $file in include_path; no file $base in $dir", E_USER_ERROR);
return null;
}
}
}
$object = new $class($parsed);
if (isset($parsed['ident_prefix'])) {
$object->setIdentPrefix($parsed['ident_prefix']);
}
}
public static function parseDSN($dsn){ // public or private depends on what you intend to do
// implementation here...
}
public function setIdentPrefix($identPrefix){
// implementation here...
}
}
class DbSimple_Mysql_Blob extends DbSimple_Generic_Blob
{
var $blobdata = null;
var $curSeek = 0;
function __construct($blobdata=null) // use __construct for class constructor
{
$this->blobdata = $blobdata;
$this->curSeek = 0;
}
function read($len)
{
$p = $this->curSeek;
$this->curSeek = min($this->curSeek + $len, strlen($this->blobdata));
return substr($this->blobdata, $this->curSeek, $len);
}
function write($data)
{
$this->blobdata .= $data;
}
function close()
{
return $this->blobdata;
}
function length()
{
return strlen($this->blobdata);
}
}
function _performNewBlob($blobid=null)
{
$obj = new DbSimple_Mysql_Blob($blobid); // no need to use &
return $obj;
}
Just don't ever use =& operator. It's been useless since PHP 5.0 and removed in PHP 7.0:
http://php.net/manual/en/migration70.incompatible.php#migration70.incompatible.other.new-by-ref
You will find more things on that page that no longer work in PHP 7.

Laravel 5 Model Class not found

I am trying to port my web app from laravel 4 to 5 but I am having issues in that one of my model classes is not found.
I have tried to utilize namespacing and have the following my Models which are located locally C:\xampp\htdocs\awsconfig\app\Models
the file which the error appears in looks like
<?php
use App\Models\SecurityGroup;
function from_camel_case($input)
{
preg_match_all('!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!', $input, $matches);
$ret = $matches[0];
foreach ($ret as &$match)
{
$match = $match == strtoupper($match) ? strtolower($match) : lcfirst($match);
}
return implode('_', $ret);
}
$resource_types = array();
$resource_types['AWS::EC2::Instance'] = 'EC2Instance';
$resource_types['AWS::EC2::NetworkInterface'] = 'EC2NetworkInterface';
$resource_types['AWS::EC2::VPC'] = 'VPC';
$resource_types['AWS::EC2::Volume'] = 'Volume';
$resource_types['AWS::EC2::SecurityGroup'] = 'SecurityGroup';
$resource_types['AWS::EC2::Subnet'] = 'Subnet';
$resource_types['AWS::EC2::RouteTable'] = 'RouteTable';
$resource_types['AWS::EC2::EIP'] = 'EIP';
$resource_types['AWS::EC2::NetworkAcl'] = 'NetworkAcl';
$resource_types['AWS::EC2::InternetGateway'] = 'InternetGateway';
$accounts = DB::table('aws_account')->get();
$account_list = array();
foreach(glob('../resources/sns messages/*.json') as $filename)
{
//echo $filename;
$data = file_get_contents($filename);
if($data!=null)
{
$decoded=json_decode($data,true);
if(isset($decoded["Message"]))
{
//echo "found message<br>";
$message= json_decode($decoded["Message"]);
if(isset($message->configurationItem))
{
// echo"found cfi<br>";
$insert_array = array();
$cfi = $message->configurationItem;
switch ($cfi->configurationItemStatus)
{
case "ResourceDiscovered":
//echo"found Resource Discovered<br>";
if (array_key_exists($cfi->resourceType,$resource_types))
{
//var_dump($cfi->resourceType);
$resource = new $resource_types[$cfi->resourceType];
foreach ($cfi->configuration as $key => $value)
{
if (in_array($key,$resource->fields))
{
$insert_array[from_camel_case($key)] = $value;
}
}
$resource->populate($insert_array);
if (!$resource->checkExists())
{
$resource->save();
if(isset($cfi->configuration->tags))
{
foreach ($cfi->configuration->tags as $t )
{
$tag= new Tag;
$tag->resource_type = "instance";
$tag->resource_id = $resource->id;
$tag->key = $t->key;
$tag->value = $t->value;
$tag->save();
/*if(isset($cfi->awsAccountId))
{
foreach ($accounts as $a)
{
$account_list = $a->account_id;
}
if (!in_array($account_id,$account_list))
{
$account_id = new Account;
$account_id->aws_account_id = $cfi->awsAccountId;
$account_list[] = $account_id;
$account_id->save();
}
} */
}
}
}
}
else
{
echo "Creating ".$cfi["resourceType"]." not yet supported<br>";
}
break;
case 'ResourceDeleted':
// echo"found Resource Deleted<br>";
//ITEM DELETED
if (array_key_exists($cfi->resourceType,$resource_types))
{
//var_dump($cfi->resourceType);
$resource = new $resource_types[$cfi->resourceType];
if ($resource->checkExists($cfi->resourceId))
{
$resource->delete();
if( isset($cfi->configuration->tags))
{
foreach ($cfi->configuration->tags as $t )
{
$tag= new Tag;
$tag->resource_type = "instance";
$tag->resource_id = $resource->id;
$tag->key = $t->key;
$tag->value = $t->value;
if ($tag->checkExists($cfi->configuration->tags))
{
$tag->delete();
}
}
}
}
}
else
{
echo "Deleting ".$cfi["resourceType"]." not yet supported<br>";
}
break;
case 'OK':
//echo"found Resource OK<br>";
//ITEM UPDATED
if (array_key_exists($cfi->resourceType, $resource_types))
{
//var_dump($cfi->resourceType);
$resource = new $resource_types[$cfi->resourceType];
if ($resource->checkExists($cfi->resourceId))
{
foreach ($cfi->configuration as $key => $value)
{
if (in_array($key,$resource->fields))
{
$update_array[from_camel_case($key)] = $value;
}
}
$resource->populate($update_array);
$resource->save();
}
}
else
{
echo "Updating ".$cfi["resourceType"]." not yet supported<br>";
}
break;
default:
echo "Status ".$cfi['configurationItemStatus']." not yet supported<br>";
break;
}
}
}
}
}
and the corresponding model whose class cannot be found looks like :
<?php namespace App\Models;
use Eloquent;
class SecurityGroup extends Eloquent
{
protected $table = 'security_group';
public $timestamps = false;
protected $guarded = array('id');
public $fields = array('groupId',
'groupName',
'description',
'ownerId'
);
public function checkExists()
{
return self::where('group_id', $this->group_id)->first();
}
public function populate($array)
{
foreach ($array as $k => $v)
{
$this->$k = $v;
}
}
}
I am lost as to what is causing the problem I don't see any typos but then again who knows as always thanks for any help given.
to solve the resource type needs the full namespace declaration

Message Library , My_Controller and __remap issue

I am creating an application and handling common things in MY_Controller. I am using Message library to display common messages.
Here is MY_Controller.php:
<?php
class MY_Controller extends CI_Controller {
public $data = array();
public $view = TRUE;
public $theme = FALSE;
public $layout = 'default';
protected $redirect;
protected $models = array();
protected $controller_model;
protected $controller_class;
protected $controller_library;
protected $controller_name;
protected $partials = array(
'meta' => 'partials/meta',
'header' => 'partials/header',
'navigation' => 'partials/navigation',
'content' => 'partials/content',
'footer' => 'partials/footer'
);
public function __construct()
{
parent::__construct();
$this->output->enable_profiler(true);
$this->load->helper('inflector');
$this->load->helper('url');
$this->controller_class = $this->router->class;
if(count($this->models)>0)
{
foreach ($this->models as $model)
{
if (file_exists(APPPATH . 'models/' . $model . '.php'))
{
$this->controller_model = $model;
$this->load->model($model);
}
}
}else{
if (file_exists(APPPATH . 'models/' . $this->controller_model . '.php'))
{
$this->load->model($this->controller_model);
}
}
$this->controller_name = $this->router->fetch_class();
$this->action_name = $this->router->fetch_method();
}
public function _remap($method, $parameters)
{
if (method_exists($this, $method))
{
$this->run_filter('before', $parameters);
$return = call_user_func_array(array($this, $method),$parameters);
$this->run_filter('after', $parameters);
}else{
show_404();
}
if($this->theme === TRUE OR $this->theme === '')
{
$this->theme = 'default';
$this->template->set_theme($this->theme);
}else if(strlen($this->theme) > 0){
$this->template->set_theme($this->theme);
}else{
}
if($this->layout === TRUE OR $this->layout === '')
{
$this->layout = 'default';
$this->template->set_layout($this->layout);
}else if(strlen($this->layout) > 0){
$this->template->set_layout($this->layout);
}else{
}
if(isset($this->partials))
{
foreach($this->partials as $key => $value)
{
$this->template->set_partial($key,$value);
}
}
if(isset($this->data) AND count($this->data)>0)
{
foreach($this->data as $key => $value)
{
if(!is_object($value))
{
$this->template->set($key,$value);
}
}
}
if($this->view === TRUE OR $this->view === '')
{
if($this->parse == TRUE)
{
$parse_string = $this->template->build($this->router->method ,'' ,$this->parse);
echo $this->parse($parse_string);
}else{
$this->_call_content($this->router->method);
$this->template->build($this->router->method,array());
}
}else if(strlen($this->view) > 0){
if($this->parse == TRUE){
$parse_string = $this->template->build($this->router->method ,'' ,$this->parse);
echo $this->parse($parse_string);
}else{
$view = $this->view;
$this->_call_content($view);
$this->template->build($view,array());
}
}else{
$checkpoint = $this->session->flashdata('exit');
if($checkpoint){
exit();
}else{
$this->session->set_flashdata('exit',TRUE);
}
$this->redirect();
}
}
public function _call_content($view)
{
$value = $this->load->view($view,$this->data,TRUE);
$this->template->set('content',$value);
}
/* Common Controller Functions */
public function index()
{
$data[$this->controller_model] = $this->{$this->controller_model}->get_all();
$this->data = $data;
$this->view = TRUE;
if($this->input->is_ajax_request() || $this->session->flashdata('ajax')){
$this->layout = FALSE;
}else{
$this->layout = TRUE;
}
}
public function form()
{
if($this->input->is_ajax_request() OR !$this->input->is_ajax_request())
{
$this->load->helper('inflector');
$id = $this->uri->segment(4,0);
if($data = $this->input->post()){
$result = $this->{$this->controller_model}->validate($data);
if($result){
if($id > 0){
}else{
$this->{$this->controller_model}->insert($data);
}
$this->message->set('message','The page has been added successfully.');
$this->view = FALSE;
$this->layout = FALSE;
$this->redirect = "index";
}else{
$this->message->set('message','The Red fields are required');
}
}
$row = $this->{$this->controller_model}->where($id)->get();
$this->data[$module_name]= $row;
}
}
public function delete()
{
$id = $this->uri->segment(3,0);
if($id != 0){
$this->{$this->controller_model}->delete($id);
}
$this->view = FALSE;
$this->layout = FALSE;
}
public function redirect()
{
redirect($this->redirect);
}
public function call_post($data)
{
foreach($data as $key => $row){
$_POST[$key] = $row;
}
}
public function query()
{
echo $this->db->last_query();
}
public function go($data = '')
{
if(isset($data)){
echo '<pre>';
print_r($data);
}else{
echo '<pre>';
print_r($this->data);
}
}
}
/**/
As you can see i am using Phil Sturgeon's template library and i am handling the layout with Jamierumbelow's techniques.
When i set a message on form insertion failure its fine. I can display it in the _remap like this
echo $this->message->display();
In the controller its working finebut when i call it in the partial navigation it does not display the message. What can possibly be the problem. I have tried on the different places in the My_Controller. Its working fine but not in the partial or even i have tried it in the failed form i am loading again.
This is the message library i am using
https://github.com/jeroenvdgulik/codeigniter-message
Here i s my navigation partial
<nav>
<div id = "navigation">
<ul id="menubar">
<li>Home</li>
<li>Downloads</li>
<li>About Us</li>
</ul>
</div>
<div id="breadcrumb">
<div class="breadcrumbs">
<!-- Here i will pull breadcrumbs dynamically-->
</div>
<!--<h3>Dashboard</h3>-->
</div>
<br clear = "all"/>
<div id="message">
<?php
$data['message'] = $message ;
$this->load->view('messages/success',$data);?>
</div>
</nav>
The message library is using session might be flashdata so i think its loosing session data somehow. Although i am using sessions correctly autoloading it.
I have found the issue. It was very simple. I was using the base url in config file as empty
$config['base_url'] = '';
I have to change it like this
$config['base_url'] = 'http://localhost/myproject/';

Categories