JFactory failing to import - php

I am trying to make a login system for an android application that works in with my 2.5 Joomla website. I am trying to do this by making a Joomla plugin which the android application sends post data to a php file which that then authenticates the user to see if the credentials are correct or not for the login. I have been trying to get this working all afternoon but it seems all my attempts of importing JFactory are failing.
I have the below code which bugs out at the first mention of JFactory. My attempt of importing it is not working either.
<?php
//needed to be commented out otherwise the android application cannot send data to the file
//defined('_JEXEC') or die;
define('_JREQUEST_NO_CLEAN', 1);
define('_JEXEC', 1);
define('DS', DIRECTORY_SEPARATOR);
if (file_exists(dirname(__FILE__) . '/defines.php')) {
include_once dirname(__FILE__) . '/defines.php';
}
if (!defined('_JDEFINES')) {
define('JPATH_BASE', dirname(__FILE__));
require_once JPATH_BASE.'/includes/defines.php';
}
require_once JPATH_BASE.'/includes/framework.php';
require_once JPATH_BASE.'/includes/helper.php';
require_once JPATH_BASE.'/includes/toolbar.php';
require JPATH_BASE.'/library/joomla/factory.php';
$email = $_POST['email'];
$password = $_POST['password'];
file_put_contents("Log.txt", "got data: ".$email." and ".$password);
$credentials->email = $email;
$credentials->password = $password;
$responce;
//error occurs here
$db = JFactory::getDbo();
...
?>
I have looked at these other questions about importing JFactory but none of them are working for me:
- JFactory,JDatabase class not found in /var/www/joomla2.5/database.php
- Class 'JFactory' not found
- include Jfactory class in an external php file, Joomla
So my simplified question is how do I import JFactory or at least work around it in this situation? Anyone feeling smarter than me who would be so kind to answer the question :)
General Information:
running php 5.1.13
Joomla 2.5
Testing on wamp server (localhost)

I suggest to go the official Joomla way and bootstrap an application. What I did works pretty well and is the recommended Joomla way (I haven't tested the code below but it should give you a starting point as it was a copy paste from multiple sources in my code).
define('_JEXEC', 1);
define('DS', DIRECTORY_SEPARATOR);
error_reporting(E_ALL | E_NOTICE);
ini_set('display_errors', 1);
define('JPATH_BASE', dirname(dirname(dirname(__FILE__))));
require_once JPATH_BASE.DS.'includes'.DS.'defines.php';
require JPATH_LIBRARIES.DS.'import.php';
require JPATH_LIBRARIES.DS.'cms.php';
JLoader::import('joomla.user.authentication');
JLoader::import('joomla.application.component.helper');
class MyJoomlaServer extends JApplicationWeb {
public function doExecute() {
$config = JFactory::getConfig();
$email = $_POST['email'];
$password = $_POST['password'];
$user = ...;//get the user with the email
file_put_contents("Log.txt", "got data: ".$email." and ".$password);
$authenticate = JAuthentication::getInstance();
$response = $authenticate->authenticate(array('username' => $user->username, 'password' => $password));
return $response->status === JAuthentication::STATUS_SUCCESS;
}
public function isAdmin() {
return false;
}
}
$app = JApplicationWeb::getInstance('MyJoomlaServer');
JFactory::$application = $app;
$app->execute();
Something along the lines works for me. More platform examples can be found here https://github.com/joomla/joomla-platform-examples/tree/master/web.

try this,
define( '_JEXEC', 1 );
define('JPATH_BASE', dirname(__FILE__) );//this is when we are in the root
define( 'DS', DIRECTORY_SEPARATOR );
require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );
$mainframe =& JFactory::getApplication('site');
$mainframe->initialise();
$db = JFactory::getDbo();
It will work, you missed JFactory::getApplication('site');
Hope it helps..

Related

Joomla How to call controller from external script

I try to launch the functions of a joomla controller from an external script. The beginning of the script works very well but the use of the controller does not.
Thank you for your help,
<?php
define('_JEXEC', 1);
// this file is in a subfolder 'cron' under the main joomla folder
define('JPATH_BASE', realpath(dirname(__FILE__) . '/..'));
require_once JPATH_BASE . '/includes/defines.php';
require_once JPATH_BASE . '/includes/framework.php';
use Joomla\CMS\Factory;
// instantiate application
$app = Factory::getApplication('site');
// database connection
$db = Factory::getDbo();
jimport('joomla.application.component.controller');
JLoader::import('Article', JPATH_ROOT . '/components/com_content/controllers');
$controller = JControllerLegacy::getInstance('Article');
var_dump($controller);
I don't get anything to instantiate a controller from any other place instead of the controller's component.
So I visit the BaseController class where the getInstance() method lays. You can hack this by setting a task through application input.
<?php
define('_JEXEC', 1);
// This file is in a subfolder 'cron' under the main joomla folder
define('JPATH_BASE', realpath(dirname(__FILE__) . '/..'));
require_once JPATH_BASE . '/includes/defines.php';
require_once JPATH_BASE . '/includes/framework.php';
use Joomla\CMS\Factory;
// Instantiate application
$app = Factory::getApplication('site');
// Get the input instance
$input = $app->input;
// Database connection
$db = Factory::getDbo();
/**
* You have to provide a task for getting the controller instance.
* The `article` is the controller filename as well as the controller class's suffix
* See the controller class name is `ContentControllerArticle`
*
*/
$input->set('task', 'article.');
/**
* The first argument of the getInstance() function is the type.
* The type is the component name here.
* And you have to pass the base_path of the component through the $config argument.
*/
$controller = JControllerLegacy::getInstance('Content', ['base_path' => JPATH_ROOT . '/components/com_content']);
echo "<pre>";
print_r($controller);
echo "</pre>";

Get Joomla user_id using a Jquery Ajax

I have the following PHP script file.php in my Joomla site:
$user = JFactory::getUser();
$usr_id = $user->get('id');
If I run it directly, using in HTML:
include_once "file.php";
It will get the user id, no problem.
However, if run it through an Ajax request:
$.ajax({
url: "other.php",
...
Where other.php is:
include_once "file.php";
I get the error:
Fatal error: Class 'JFactory' not found in file.php on line 3
Why? Any help!?
You need to import the Joomla library in order to use the JFactory class. To import the library, add the following to the top of your file:
define( '_JEXEC', 1 );
define( 'JPATH_BASE', dirname(__FILE__) ).'/../..' );
require_once ( JPATH_BASE .'/includes/defines.php' );
require_once ( JPATH_BASE .'/includes/framework.php' );
require_once ( JPATH_BASE .'/libraries/joomla/factory.php' );
$mainframe = JFactory::getApplication('site');
$mainframe->initialise();

How to get component instance via code Joomla 1.7

I want to use my Joomla 1.7 Components from a webservices placed inside the same server.
In other words, I have another file that will be used by mobile-apps to do stuff.
I'd like to use joomla core functions nor having to duplicate code nor having to make direct inserts in the DB bypassing joomla and formatting them to match "what Joomla would do".
For now I am able to get the DBO objects and make queries using joomla, but I want to use every component I need.
For example,
<?php
if (!defined('_JEXEC')) { define('_JEXEC', 1); }
if (!defined('DS')) { define('DS', DIRECTORY_SEPARATOR); }
if (file_exists(dirname(dirname(__FILE__)) . '/defines.php'))
{
include_once dirname(dirname(__FILE__)) . '/defines.php';
}
if (!defined('_JDEFINES'))
{
define('JPATH_BASE', dirname(dirname(__FILE__)));
require_once JPATH_BASE.'/includes/defines.php';
}
require_once JPATH_BASE.'/includes/framework.php';
// Mark afterLoad in the profiler.
JDEBUG ? $_PROFILER->mark('afterLoad') : null;
$db = JFactory::getDocument()->getDBO();
$query = $db->getQuery(true);
$query->select('r.id');
$query->from('#__asd as r');
$query->join('LEFT', '#__xxx cc on cc.recipe_id = r.id');
// Prepare where clause
$query->where('r.published = 1');
$query->group('r.id');
$db->setQuery($query);
$objectsList = $db->loadObjectList();
$res = formatResult($objectsList);
function formatResult($obj)
{
if($obj === NULL || !is_array($obj)){ return array('data' => 'Vuoto', 'code' => 0); }
return array('data' => (array)$obj, 'code' => 1);
}
?>
EDIT: More specifically, I have installed (JFBconnect) and I want its functionality to login and register users from app.

External API Rest .PHP of Joomla 2.5

My server with Joomla and API:
web/pruebasmario/joomla
web/public/api
I need use Jfactory..etc, functions plugin, componentes Joomla 2.5 in my Api.
I created a file accesjoomla.php in web/public/api:
<?php
include('../../pruebasmario/extjom.php');
$user = JFactory::getUser();
echo "Usuario " . $user->username . " con id: " . $user->id . " conectado a Joomla";
I created a file extjom.php in web/pruebasmario/joomla:
/* Initialize Joomla framework */
define( '_JEXEC', 1 );
define('JPATH_BASE', dirname(__FILE__) );
define( 'DS', DIRECTORY_SEPARATOR );
/* Required Files */
require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );
/* To use Joomla's Database Class */
require_once ( JPATH_BASE .DS.'libraries'.DS.'joomla'.DS.'factory.php' );
I look this: include Jfactory class in an external php file, Joomla
Access Joomla 2.5 from external script to get article by id
Joomla 2.5 Get User Data from External Script
BUT NO workk!!!!! :-((
Help me plez!
thanks!
EDIT: I managed to take a step.
Adding:
require_once (JPATH_BASE. DS. 'libraries'. DS. 'joomla'. DS. 'error'. DS. 'error.php');
I have no errors. But nothing appears. all white.
The return of the api is not returned.
What is happening?

Manual wp_install() difficulties

I am trying to automatically install a WordPress distribution in PHP with the following code:
$base_dir = '/home/username/wordpress_location';
chdir($base_dir);
define('WP_SITEURL', 'http://www.domain.com/');
define('WP_INSTALLING', true);
require_once 'wp-load.php';
require_once 'wp-admin/includes/upgrade.php';
require_once 'wp-includes/wp-db.php';
$result = wp_install($title, $username, $email, true, null, $password);
When I manually run wp_install() [/wp-admin/includes/upgrade.php], I get this error:
Fatal error: Call to a member function flush_rules() on a non object in /home/username/public_html/wp-admin/includes/upgrade.php on line 85
After looking at the WordPress source code, it appears that $wp_rewrite is trying to call flush_rules() when $wp_rewrite itself doesn't exist.
Another strange twist is that this is virtually the same code as wordpress-cli-installer. My wp-config.php file is automatically generated and ready.
How come wordpress-cli-installer's code works but mine does not?
EDIT:
After a lot of trial and error, I found out that my code was not working because it was defined and executed in a function. After I separated the code from the function and executed it, it worked. However, that raises another question. Is it even possible to execute the above code inside of a function? I have tried using the $GLOBALS += get_defined_vars(); hack after the require_once statements, but that doesn't seem to do anything. In other words:
<?php
$base_dir = '/home/username/wordpress_location';
chdir($base_dir);
define('WP_SITEURL', 'http://www.domain.com/');
define('WP_INSTALLING', true);
require_once 'wp-load.php';
require_once 'wp-admin/includes/upgrade.php';
require_once 'wp-includes/wp-db.php';
$result = wp_install($title, $username, $email, true, null, $password);
// ^ This works.
// v This won't work.
function run(){
$base_dir = '/home/username/wordpress_location';
chdir($base_dir);
define('WP_SITEURL', 'http://www.domain.com/');
define('WP_INSTALLING', true);
require_once 'wp-load.php';
require_once 'wp-admin/includes/upgrade.php';
require_once 'wp-includes/wp-db.php';
$result = wp_install($title, $username, $email, true, null, $password);
}
run();
?>
How do I use the require_once inside of a function while still being able to access and manage the globals?
That idea is wrong in general. You can make global only required variables (which might change from version to version). But the 'dirty' way is
function make_global()
{
$test_var = "I'm local";
$GLOBALS += get_defined_vars();
}
var_dump(isset($test_var));
make_global();
var_dump(isset($test_var));

Categories