PHP - Register Namespaced Class In Joomla 2.5
I'm trying to implement a library which was written for PSR-0 compliant autoloading in my joomla project. However joomla 2.5 does not support PSR-0 autoloading so I figured that I would have to write my own implementation.
Since I want to use my classes across my entire joomla installation I decided to write a plugin which registers the classes onAfterInitialise() but this is where it goes wrong: it overrides joomla's autoloading methods.
The library i'm trying to implement is located at libraries/Zoho/CRM/ZohoClient.php with several subfolders. Everything is namespaced with accordance to PSR-0 so starting with: \Zoho\CRM.
How do I register the classes in such a way that I can use them globally across joomla? This is my implementation:
public function onAfterInitialise() { spl_autoload_register(function ($className) { $className = ltrim($className, '\\'); $fileName = ''; $namespace = ''; if ($lastNsPos = strripos($className, '\\')) { $namespace = substr($className, 0, $lastNsPos); $className = substr($className, $lastNsPos + 1); $fileName = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR; } $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php'; require $fileName; }); }This obviously wont work because it overrides the joomla autoloading function. I'm running php5.3 (5.4 in 3 months) Similar TutorialsSo I'm pounding away at some of the new 5.3 features to try and get a grasp on setting up a custom MVC. spl_autoload with namespaces is frikkin awesome, however im trying to make life easy by being able to drop a class file in an "objects" folder that holds all the models for the app and have the controller parse out the get request for the proper model call and dynamically create the object. Example: url = www.example.com/?auth controller parses $_GET and see's you are requesting the auth module. Now I'm having an issue instantiating a variable that has a namespace\class inside it: Code: [Select] $namespace = 'objects\\'; $clean['object'] = $namespace.key($clean['get']); $this->object = new $clean['object']; Logfile: PHP Fatal error: spl_autoload(): Class objects\\testobject could not be loaded... OK, its trying to escape the backslash? Maybe some trickery is needed? Code: [Select] $clean['object'] = $namespace.chr(92).key($clean['get']); NOPE, still the same error... Any cluepons? Hello, I'm new to the forum and I'm looking for advice. I use a bunch of classes in namespaces that are I'm attempting to organize for autoloading. In other words, a class called \Foo\Package\Class is loaded from the file at Foo\Package\Class.php. I'm using spl_autoload for this. (If I were on 5.2 I could be using underscore-delimited pseudo-namespaces just as well; the implementation detail isn't important) Now, I want to have multiple separate apps that use a single common library. Each app also has some classes that are local to it. How should I solve the autoloading problem? I thought of the following approach. Is it any good? Try autoloading from the common class library If it fails, try autoloading from the app's own local library Part 2 of the question: Within my apps, though, there are two types of classes: library ("vendor") classes that are only being used in that particular app so they don't need to be in the shared library, and app-specific classes that are the core of the app (so they, by definition, don't need to be in any shared library). I'd probably like to keep these two separate, so I'd need to add point #3 to the list above: search in the "core" class hierarchy of the local app. This gives 3 separate locations, and the problem is that they negate the advantages namespaces since there can be overlap. In which case one class will override the other during autoloading. So order of the above list would matter. And time would be wasted looking for a class in the first two places if it's more often in the third. A solution I was considering is sticking to just one central library of classes (and dumping all app-local libraries there). Then, the core classes that belong to one app would be under an \AppName namespace. I'm looking forward to some insights from the experts. How do you guys organize your class libraries? Hello all,
I have a question. The server I am currently working on is on PHP 5.2 and Joomla 1.5.26. I'd like to migrate or slowly move over to 3.0 on the same server however 3.0 requires at least 5.3 (would go to 5.4). In my cpanel, it tells me "PHP 5.4+ Incompatible Applications Installed". Is it not possible to run Joomla 1.5 on PHP 5.4, or are there certain components/modules that do not work with it?
The two major third party components I have installed are Community Builder and Jumi.
I just don't want my site to explode if I click the button.
Thanks,
Rob
Edited by Spikes, 10 November 2014 - 10:21 PM. Hi ,
My site gives a blank page when i click on an article due to insufficient memory. I tried making changes to the php.ini file but the changes are not getting reflected.
Please advice if a server restart is needed for this, how do i go about it?
Thanks in advance
This topic has been moved to PHP Applications. http://www.phpfreaks.com/forums/index.php?topic=306933.0 I'm trying to implement a custom css style for each of the K2 templates.
I wrote a com_K2 override.
I add this string to a K2 template php files
<link rel="stylesheet" href="<?php echo $this->baseurl ?>/templates/<?php echo $this->template; ?>/html/com_k2/templates/default/k2c.css" type="text/css" />but it adds itself in the body of the page. Is there a way to put this string into <head> tag? I'm not savvy in PHP, so any advice would be appreciated Hi there,
I have decided using the Joomla API however, the documentation was for 1.5 and 2.5 system only but i'm using 3.0. I have a number of files that look like this:
"14-05-14 JoePharnel.pdf"
and
"13-05-12 HarryCollins.pdf"
Basically I want to create a PHP code that when someone ftp uploads those files to the upload folder that it will 1) Create a directory if it doesn't exist using there name 2) Move the files to the correct directory (E.g. JoePharnel to the JoePharnel Directory ignoring the number at the beginning)
My new code creates the folder but won't move the file in the upload into that new folder, code is below:
<?php define( '_JEXEC', 1); define('JPATH', dirname(__FILE__) ); if (!defined('DS')){ define( 'DS', DIRECTORY_SEPARATOR ); $parts = explode( DS, JPATH ); $script_root = implode( DS, $parts ) ; // check path $x = array_search ( 'administrator', $parts ); if (!$x) exit; $path = ''; for ($i=0; $i < $x; $i++){ $path = $path.$parts[$i].DS; } // remove last DS $path = substr($path, 0, -1); if (!defined('JPATH_BASE')){ define('JPATH_BASE', $path ); } if (!defined('JPATH_SITE')){ define('JPATH_SITE', $path ); } /* Required Files */ require_once ( JPATH_SITE . DS . 'includes' . DS . 'defines.php' ); require_once ( JPATH_SITE . DS . 'includes' . DS . 'framework.php' ); require_once ( JPATH_SITE . DS . 'libraries' . DS . 'joomla' . DS . 'factory.php' ); //Import filesystem libraries. Perhaps not necessary, but does not hurt jimport('joomla.filesystem.path'); jimport('joomla.filesystem.file'); jimport('joomla.filesystem.folder'); jimport('joomla.user.user'); //First we set up parameters $searchpath = JPATH_BASE . DS . "upload"; //Then we create the subfolder called png if ( !JFolder::create($searchpath . DS ."Images") ) { //Throw error message and stop script } //Now we read all png files and put them in an array. $png_files = JFolder::files($searchpath,'.png'); //Now we need some stuff from the JFile:: class to move all files into the new folder foreach ($png_files as $file) { JFile::move($searchpath. DS . ".png" . $file, $searchpath . DS. "Images" . $file); } //Lastly, we are moving the complete subdir to the root of the component. if (JFolder::move($searchpath . DS. "Images",JPATH_COMPONENT) ) { //Redirect with perhaps a happy message } else { //Throw an error } } ?> Only error i get is Notice: Use of undefined constant JPATH_COMPONENT - assumed 'JPATH_COMPONENT' in /upload.php on line 70. I have used and adapted multiple php code so any help would be appreciated. Or if you can point me to where i can find the answer that would be brilliant A joomla module have the following code which displays the date of an article, and to a seperate line the linked title of that article.
Please help me on how to change that code so that the date and the title of the article to be presented in the same line?
<div class="smartlatest-title"> <?php if($params->get('show_date',1)) echo '<div class="smartlatest-date">'.strftime($params->get('date_format','%d-%m-%Y'), strtotime($item->publish_up)).'</div>'; ?> <?php if($params->get('link_title',1)) { ?><a href="<?php echo $item->link; ?>" class="smartlatest-title-link"><?php } ?> <?php echo $item->title; ?> <?php if($params->get('link_title',1)) { ?></a><?php } ?> </div> Hello, I'm using the J2Store add-on for Joomla. The store prints out a invoice and I am editing what prints out. Right now it prints out each item ordered and the 'options' with that item. (Ex. You can order a Large shirt the options are its a t-shirt and blue.)
What I'm trying to do is make a list of all the material ('options') and quanities in each order.
Below is the section of code I have been working with. I added '<?php echo count($item); ?>' to the code but it just lists the 'options' then a 1 after, but only for one item in the order.
The J2Store support told me this:
"
first you need to decode the $item->orderitem_attributes Then you need to parse through the array and get the options in a required format by sorting and using multiple loops. Then count each option. Example count($array['large']); " <?php if(!J2StoreOrdersHelper::isJSON(stripslashes($item->orderitem_attribute_names))): ?> <?php if (!empty($item->orderitem_attribute_names)) : ?> <span><?php echo $item->orderitem_attribute_names; ?></span> <?php endif; ?> <br /> <?php else: ?> <!-- since 3.1.0. Parse attributes that are saved in JSON format --> <?php if (!empty($item->orderitem_attribute_names)) : ?> <?php //first convert from JSON to array $registry = new JRegistry; $registry->loadString(stripslashes($item->orderitem_attribute_names), 'JSON'); $product_options = $registry->toObject(); ?> <?php foreach ($product_options as $option) : ?> - <small> <?php echo JText::_($option->name); ?>: <?php echo JText::_($option->value); ?> <?php echo count($item); ?> <?php if(isset($option->option_sku) && JString::strlen($option->option_sku) > 0):?> (<?php echo JText::_('J2STORE_SKU'); ?> : <?php echo $option->option_sku; ?>) <?php endif; ?> </small><br /> <?php endforeach; ?> <br/> <?php endif; ?> <?php endif; ?> Edited by Zane, 23 May 2014 - 11:59 AM. Hi I am trying to knock up a script to create a userid and log someone into a Joomla based site. The script is running on the same server as the site (and is legitimate, not nefarious). I can create an ID OK, and I can retrieve the login page, scrape the details (including the token) and submit the form. When I do this the user is logged in according to the Joomla sessions table, but it has also created a 2nd guest session there. Navigating to the Joomla site (either manually or doing a header redirect) just takes you to the site as though you are not logged in. Code as it stands (and code to deal with being passed user ids and passwords will change to be at least vaguely secure, just trying to get things to work now) Code: [Select] <?php session_start(); session_regenerate_id(); require("configuration.php"); $ConfigDetails = new JConfig(); $dbms = $ConfigDetails->dbtype; $dbhost = $ConfigDetails->host; $dbname = $ConfigDetails->db; $dbuser = $ConfigDetails->user; $dbpasswd = $ConfigDetails->password; $salt = 'somesalt'; $url = "http://localhost/joomla/index.php"; $IncomingUid = $_REQUEST['uid']; $IncomingName = $_REQUEST['name']; $IncomingPassword = $_REQUEST['pwd']; $IncomingEmail = $_REQUEST['email']; // Make the database connection. $SurveyConn = mysql_connect($dbhost,$dbuser,$dbpasswd); mysql_select_db($dbname,$SurveyConn) or die(mysql_error()); $sql = "SELECT * FROM ".$ConfigDetails->dbprefix."users WHERE username = '".mysql_real_escape_string($IncomingUid)."'"; $rs = mysql_query($sql) or die(mysql_error()); if ($row = mysql_fetch_assoc($rs)) { if ($IncomingPassword == $row['password']) { } } else { $PasswordEncrypted = md5($IncomingPassword.$salt).':'.$salt; $sqli = "INSERT INTO ".$ConfigDetails->dbprefix."users (id, name, username, email, password, usertype, block, sendEmail, registerDate, lastvisitDate, activation, params) VALUES(NULL, '".mysql_real_escape_string($IncomingName)."','".mysql_real_escape_string($IncomingUid)."','".mysql_real_escape_string($IncomingEmail)."','".mysql_real_escape_string($PasswordEncrypted)."','deprecated',0,1,NOW(), NOW(), '', '')"; $rs = mysql_query($sqli) or die(mysql_error()." $sqli"); $sqli = "INSERT INTO ".$ConfigDetails->dbprefix."user_usergroup_map (user_id, group_id) VALUES(".mysql_insert_id().", 8)"; $rs = mysql_query($sqli) or die(mysql_error()." $sqli"); } $agent = "'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6'"; $c1 = curl_init(); curl_setopt($c1, CURLOPT_URL, $url ); curl_setopt($c1, CURLOPT_SSL_VERIFYPEER, FALSE ); curl_setopt($c1, CURLOPT_RETURNTRANSFER, TRUE ); curl_setopt($c1, CURLOPT_VERBOSE, 1); curl_setopt($c1, CURLOPT_COOKIEJAR, 'cookie.txt'); curl_setopt($c1, CURLOPT_COOKIEFILE, 'cookie.txt'); curl_setopt($c1, CURLOPT_USERAGENT, $agent ); curl_setopt($c1, CURLOPT_HEADER, TRUE ); curl_setopt($c1, CURLOPT_REFERER, $url1); curl_setopt($c1, CURLOPT_POST, 1); $html = curl_exec($c1); $dom = new DOMDocument(); $FormFieldsArray = array(); if (@$dom->loadHTML($html)) { // yep, not necessarily valid-html... $xpath = new DOMXpath($dom); $nodeListInputs = $xpath->query('//input'); if ($nodeListInputs->length > 0) { $FormFieldsArray = array(); for ($i=0 ; $i<$nodeListInputs->length ; $i++) { $nodeInput = $nodeListInputs->item($i); $name = $nodeInput->getAttribute('name'); $value = $nodeInput->getAttribute('value'); $FormFieldsArray[$name] = $value; } } } else { // too bad... } if (count($FormFieldsArray) > 0) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url ); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE ); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE ); curl_setopt($ch, CURLOPT_VERBOSE, 1); curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt'); curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt'); curl_setopt($ch, CURLOPT_USERAGENT, $agent ); curl_setopt($ch, CURLOPT_HEADER, TRUE ); curl_setopt($ch, CURLOPT_REFERER, $url1); // POST fields $postfields = array(); foreach($FormFieldsArray AS $FormFieldName=>$FormFieldValue) { switch ($FormFieldName) { case 'username' : $postfields['username'] = urlencode($IncomingUid); break; case 'passwd' : $postfields['passwd'] = urlencode($IncomingPassword); break; case 'password' : $postfields['password'] = urlencode($IncomingPassword); break; default : $postfields[$FormFieldName] = $FormFieldValue; break; } } curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields); $ret = curl_exec($ch); // Get logged in cookie and pass it to the browser preg_match('/^Set-Cookie: (.*?);/m', $ret, $m); $cookie = explode('=', $m[1]); setcookie($cookie[0], $cookie[1]); header("location: ".$url); } //echo $ret; ?> Any ideas? All the best Keith Hey guys, Anyone who's used Joomla will know they have a very snazzy system for allowing the user to reorder the "order" field in any given table. You know the one, the blue arrows pointing up and down to move the row up or down. I wanna implement something similar in my own sites CMS, does anyone know a good script to handle it? I have mysqli object in Database class base: [color=]database class:[/color] class Database { private $dbLink = null; public function __construct() { if (is_null($this->dbLink)) { // load db information to connect $init_array = parse_ini_file("../init.ini.inc", true); $this->dbLink = new mysqli($init_array['database']['host'], $init_array['database']['usr'], $init_array['database']['pwd'], $init_array['database']['db']); if (mysqli_connect_errno()) { $this->dbLink = null; } } } public function __destruct() { $this->dbLink->close(); } } Class derived is Articles where I use object dBLink in base (or parent) class and I can't access to mysqli methods (dbLink member of base class): Articles class: require_once ('./includes/db.inc'); class Articles extends Database{ private $id, .... .... $visible = null; public function __construct() { // Set date as 2009-07-08 07:35:00 $this->lastUpdDate = date('Y-m-d H:i:s'); $this->creationDate = date('Y-m-d H:i:s'); } // Setter .... .... // Getter .... .... public function getArticlesByPosition($numArticles) { if ($result = $this->dbLink->query('SELECT * FROM articles ORDER BY position LIMIT '.$numArticles)) { $i = 0; while ($ret = $result->fetch_array(MYSQLI_ASSOC)) { $arts[$i] = $ret; } $result->close(); return $arts; } } } In my front page php I use article class: include_once('./includes/articles.inc'); $articlesObj = new articles(); $articles = $articlesObj->getArticlesByPosition(1); var_dump($articles); [color=]Error that go out is follow[/color] Notice: Undefined property: Articles::$dbLink in articles.inc on line 89 Fatal error: Call to a member function query() on a non-object in articles.inc on line 89 If I remove constructor on derived class Articles result don't change Please help me HI All,
I need some suggestions on how to proceed on with component development. and any logic code or similar coding will be very much appreciated.
The component should display the list of contents displaying some columns from a table(ie.,scncontent) from database similar to web links component along with the tool bar (new,edit,publish,unpublish,trash etc., actions ) and with pagination also . This component should be designed with MVC architecture. On clicking new or edit icons, a form should be opened and data should be saved or updated to database.
This topic has been moved to PHP Applications. http://www.phpfreaks.com/forums/index.php?topic=314053.0 I have a simple register script and some weird things are happening. If i leave blank password or repeat_password then code is still executed. Why? I can't seem to find any mistakes in the code. (only when username is empty then i get "You need to fill everything"). Code: [Select] <?php $submit = $_POST['submit']; $username = strip_tags($_POST['username']); $password = md5(strip_tags($_POST['password'])); $repeat_password = md5(strip_tags($_POST['repeat_password'])); require("connect.php"); if ($submit) { if (!empty($username) && !empty($password) && !empty($repeat_password)) { mysql_query("INSERT INTO users2 VALUES ('', '$username', '$password', '1000', '0', '0','', '', '')"); echo "You are registered <br />Your username is "."<b>$username</b>"."<br /> You may now <a href='index.php'> login </a>"; } else { echo "You have not filled everything."; } } ?> Hi, I'm looking to change my 'Dead' page on my Mafia game to enable users to register a new account as soon as they log in to their dead one. I would like them to be able to just enter a new Username and then the email, password etc stay the same. Is this possible? Just ask for any parts of the register code you guys need. Thanks in advance,. Hi there, There's something wrong with this register form, it's submitting without validation. Code: [Select] <?php require_once('./includes/connectvars.php'); // Connect to the database $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); if (isset($_POST['submit'])) { // Grab the profile data from the POST $username = mysqli_real_escape_string($dbc, trim($_POST['username'])); $password1 = mysqli_real_escape_string($dbc, trim($_POST['password1'])); $password2 = mysqli_real_escape_string($dbc, trim($_POST['password2'])); $firstname = mysqli_real_escape_string($dbc, trim($_POST['first_name'])); $lastname = mysqli_real_escape_string($dbc, trim($_POST['last_name'])); if (!empty($username) && !empty($password1) && !empty($password2) && ($password1 == $password2) && !empty($firstname) && !empty($lastname)) { // Make sure someone isn't already registered using this username $query = "SELECT * FROM users WHERE username = '$username'"; $data = mysqli_query($dbc, $query); if (mysqli_num_rows($data) == 0) { // The username is unique, so insert the data into the database $query = "INSERT INTO users (username, password, join_date, first_name, last_name) VALUES ('$username', SHA('$password1'), NOW(), '$firstname', '$lastname')"; mysqli_query($dbc, $query); // Confirm success with the user echo '<p>Your new account has been successfully created. You\'re now ready to <a href="login.php">log in</a>.</p>'; mysqli_close($dbc); exit(); } else { // An account already exists for this username, so display an error message echo '<p class="error">An account already exists for this username. Please use a different address.</p>'; $username = ""; } } else { echo '<p class="error">You must enter all of the sign-up data, including the desired password twice.</p>'; } } mysqli_close($dbc); ?> <p>Please enter your username and desired password to sign up to Mismatch.</p> <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <legend>Registration Info</legend> <label for="username">Username:</label> <input type="text" id="username" name="username" value="<?php if (!empty($username)) echo $username; ?>" /><br /> <label for="password1">Password:</label> <input type="password" id="password1" name="password1" /><br /> <label for="password2">Password (retype):</label> <input type="password" id="password2" name="password2" /><br /> <label for="first_name">first name:</label> <input type="text" id="first_name" name="first_name" /><br /> <label for="last_name">last name:</label> <input type="text" id="last_name" name="last_name" /><br /> <input type="submit" value="Sign Up" name="submit" /> </form> </body> </html> I've had this problem for a while now and can't figure it out, any suggestions are appreciated. Thank you. Hello everyone, I want to make a re-register script that enables a user to re-register once killed.... BUT keep the same email, same profile pic, same profile quote, same friends and a few other things.... BUT register new username etc. Any help would be great. Hi, I created a previous thread but the problems were too confusing so I've started this thread again. I have a register form and it's supposed to validate if fields are empty. If fields are not empty, it should enter data on submit, into the table. The problem: The form is able to submit without validation and the data does not enter the table. The code: Code: [Select] <?php require_once('./includes/connectvars.php'); // Connect to the database $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); if (isset($_POST['submit'])) { // Grab the profile data from the POST $username = mysqli_real_escape_string($dbc, trim($_POST['username'])); $password1 = mysqli_real_escape_string($dbc, trim($_POST['password1'])); $password2 = mysqli_real_escape_string($dbc, trim($_POST['password2'])); $firstname = mysqli_real_escape_string($dbc, trim($_POST['first_name'])); $lastname = mysqli_real_escape_string($dbc, trim($_POST['last_name'])); if (!empty($username) && !empty($password1) && !empty($password2) && ($password1 == $password2) && !empty($firstname) && !empty($lastname)) { // Make sure someone isn't already registered using this username $query = "SELECT * FROM cuser WHERE username = '$username'"; $data = mysqli_query($dbc, $query); if (mysqli_num_rows($data) == 0) { // The username is unique, so insert the data into the database $query = "INSERT INTO cuser (username, password, join_date, first_name, last_name) VALUES ('$username', SHA('$password1'), NOW(), '$firstname', '$lastname')"; mysqli_query($dbc, $query); // Confirm success with the user echo '<p>Your new account has been successfully created. You\'re now ready to <a href="login.php">log in</a>.</p>'; mysqli_close($dbc); exit(); } else { // An account already exists for this username, so display an error message echo '<p class="error">An account already exists for this username. Please use a different address.</p>'; $username = ""; } } else { echo '<p class="error">You must enter all of the sign-up data, including the desired password twice.</p>'; } } mysqli_close($dbc); ?> <p>Please enter your username and desired password to sign up to Mismatch.</p> <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <legend>Registration Info</legend> <label for="username">Username:</label> <input type="text" id="username" name="username" value="<?php if (!empty($username)) echo $username; ?>" /><br /> <label for="password1">Password:</label> <input type="password" id="password1" name="password1" /><br /> <label for="password2">Password (retype):</label> <input type="password" id="password2" name="password2" /><br /> <label for="first_name">first name:</label> <input type="text" id="first_name" name="first_name" /><br /> <label for="last_name">last name:</label> <input type="text" id="last_name" name="last_name" /><br /> <input type="submit" value="Sign Up" name="submit" /> </form> </body> </html> Any ideas on what the problem is? I've sent my sessions in another file. |