Thursday, November 15, 2012

Overloading methods in Php: __call()

Just for the record I know that php does not support multiple classes to be extended and today while talking to a dear friend I thought this would work to sort of workaround this, and it did, for most cases I dont think this is very useful  but if you're in college this might come in handy for a homework or project:


<?php

class Mother
{ 
  public function func2() { return 'Mother knows best'; }
}

class Father
{
  private $_aClasses;
  public function __construct()
    $this->_aClasses = array( 'Mother' => new Mother); 
  }

  public function func1() { return 'func1 from Father'; }

  public function __call($sName, $aArguments)
  {
    foreach ($this->_aClasses as $oObj)
    {
      if (method_exists($oObj, $sName))
        echo $oObj->$sName(); 
      }
      else 
        var_dump($oObj); 
      }
    }
  }
}

$oF = new Father;
$oF->func2();
?>



This outputs "Mother knows best" even thought Father doesnt have a function func2().

Friday, June 29, 2012

Phpfox Developers: Correct way of sending mail (multiple languages)

Well we got a bug report today that at first seemed intimidating, the case was that in some mails being sent the script would not take into account the language of the receiver if it was a registered user. The first approach was to open the callback for that one case and scenario and fix it there, 3 lines of code edited no big deal, the problem is that it was a callback, meaning every module implemented, so 3 lines of code times 61 was too much to do by hand, luckily we have a built in method to change the language just for one phrase and the fix turned out to be site wide and implemented in less than 1 minute, here's the recap:

This code is wrong because it will not take the target user's language into account
Phpfox::getLib('mail')->to($aRow['user_id'])
->subject(Phpfox::getPhrase('module.var'))
->message(Phpfox::getPhrase('module.var'))

This next is correct:
Phpfox::getLib('mail')->to($aRow['user_id'])
->subject(array('module.var'))
->message(array('module.var'))

That is basically it, since you are passing the user_id in the ->to() function the mail library will pick up the language for that user, and by passing an array instead of the actual phrase the mail library will get the correct phrase, you can also include an array of parameters if you like as a second element in the array:

Phpfox::getLib('mail')->to($aRow['user_id'])
->subject(array('module.var', array('param1' => 'val1')))
->message(array('module.var', array('param2' => 'val2')))

and it will run the replacements as if you had done a getPhrase. Our fix was to Replace In Files all
 ->subject(Phpfox::getPhrase
with
->subject(array
and same for
->message.

Thursday, June 28, 2012

Backing up


Backing up is so important that every successful website has at least one person dedicated to this task.
If you have not yet defined your back up policy this post will help you.

Database Backups


There are specific tools for each database manager that you have (a database manager can be "MySQL", "PostgreSQL", "MSSQL"...). For now I will talk about the two kinds of backups:

Full Snapshot

This kind of backup takes your entire database and stores it in a flat file with instructions to delete tables when imported. It is a real copy of your database and is useful when moving your site to a new server, it also serves as the base for an incremental backup.

In MySQL there are two important tools that generate full snapshots: mysqldump and mysqlhotcopy. Since InnoDB is the default engine since MySQL 5.5 let me just give a quick introduction to mysqldump since mysqlhotcopy is meant for MyIsam tables. Keep in mind that these are server tools and you would execute them via console (SSH possibly).

mysqldump receives a number of parameters, not all are mandatory but the following will give you a full database dump that overwrites (deletes and re-creates) your existing data:

$ mysqldump --compact [db-name]

Another way of backing up your database is by directly copying the files. These files depend on the type of tables that you have and more detailed information can be found in the MySQL site.

Incremental Backup


Given a Full Snapshot backup you can store only the changes since the full backup, reducing the space and processing time needed, in mysql this is done using the binlog and not by chance this log is also used in Replication.

Restoring from a binary log file is very easy, for example:

$ mysqlbinlog binlogfile | mysql -u root -p

You can also export your binary log file to a flat file:

$ mysqlbinlog binlogfile > temporalfile.sql

File Backups


A full backup (tar or zip are very common) is also the easiest way to go, this however can lead to much larger storage requirements.


Generally speaking your files do not change that much, you upload an image and it will stay there, you will not update it and often times it will not be deleted until the end of time, a hard disk failure is also rare and if you do not manage your server chances are there are redundant backups (think RAID), I do not mean to ignore this kind of backups but in general terms a hard disk failure is easily mitigated up to a certain size.

The following command will compress the folder myFolder into the file myArchive.tar.gz
$ tar -zcf myArchive.tar.gz myFolder

The 'z' means to use GZip, the 'c' means to create an archive and the 'f' means to write it to a file.
Of course you also need to extract an archive, the following command will do just that:
$ tar -zxf myArchive.tar.gz

The 'x' parameter means to extract.

Another approach to backing up flat files is to use a subversion server, this is similar to the incremental backup and you can actually backup the files that make up for your database in SVN (although this is rather unconventional).

User Group Settings Check

If your custom phpfox module adds user group settings you may want to implement a validation for them, we added a way to run checks based on one bug report related to the custom fields, if you go to the AdminCP and manage settings for a user group, in the "Custom" module there's a setting "Custom field database table name?", this is the name of a table that must exist in the database already, we want to improve this whole routine but meanwhile the admin has to have the table created. So we added a callback in the module "Custom", this function receives an array with two indexes ("variable" and "value") and checks if the table exists. This is how that function looks like:
public function isValidUserGroupSetting($aVal)
{
  switch ($aVal['variable'])
  {
    case 'custom_table_name':
        return $this->database()->tableExists($aVal['value']);  
    default:
        return true;
  }
}

Remember that callback functions are to be placed in your callback.class.php file in your folder "service".

Monday, June 4, 2012

Phpfox: Database Errors

If you ever see the error "Cannot connect to the database", this could mean that your database user is not correct, that your database is not working or that the connection between your HTTP server and your database does not work.
This is not a bug in Phpfox, and you should contact your hosting company.

You can edit your database user in the file /include/setting/server.sett.php

Thursday, April 26, 2012

Phpfox: onReady with Ajax Browsing

Phpfox offers a site wide ajax browsing experience. This allows to load new pages and change the URL without actually going to another page. Clients save on resources since only needed components are loaded (things like the logo and menu are not requested).
This is pretty cool and makes for a smoother experience to the end user but some developers have had a hard time coupling their javascript routines into this model.

Meet $Behavior

$Behavior is a namespace that is triggered every time a page is loaded, even in ajax browsing mode. If your old JavaScript code looked like this:

$(document).ready(function() {
  // Your code here
});
You will have to change that to:
$Behavior.anyNameYouWant = function(){
  // Your code here
};
They are both equivalent except that with ajax browsing enabled it will trigger your "anyNameYouWant" function and not the JQuery one. Similarly this replaces the following:
$(function() {
 // Your code here
});
since that is the same as $(document).ready Even if site wide ajax browsing is disabled, the $Behavior namespace will be triggered, so you can safely code in $Behavior and not worry about site wide ajax browsing being enabled or disabled.

Saturday, April 21, 2012

NginX latest version in Ubuntu Server

The Ubuntu repositories are often outdated in comparison to the developer's release, today I wanted to install NginX in a recently installed Ubuntu Server but first I wanted to see how far behind the repository lagged, the following
~# apt-cache showpkg nginx

gave me the answer:
Package: nginx
Versions:
0.8.54-4 (/var/lib/apt/lists/gb.archive.ubuntu.com_ubuntu_dists_natty_universe_binary-amd64_Packages)

but going to the official site said the newest version was 1.0.15 (stable). Software versions are often split in 3 numbers, in this case the one in the ubuntu repository is "major version 0" and the one available from nginx is "major version 1", so the one from nginx seems more stable.
The next step was to add the NginX repository to Ubuntu so it would pick up the newer version:
~# sudo -s
~# nginx=stable
~# add-apt-repository ppa:nginx/$nginx

The first line there turns my user into root. The second one defines a variable, wherever I use $nginx it will be converted into "stable", this is used internally by the package installer as well. And the last of those lines actually adds the repository. This is what I got in return:
The program 'add-apt-repository' is currently not installed.  You can install it by typing:
apt-get install python-software-properties

No big deal, I just installed that package:
 ~# apt-get install python-software-properties

Since I had already sudo -s I did not need to use "sudo apt-get inst...". 42 KB later I had python-software-properties installed and running the last line (add-apt-repository...) went fine. Now the repository is added but we need to refresh the list of packages:
~# apt-get update

it will gargle some information about the packages its reading and eventually say its done.
Our last step is to actually install nginx:

~# apt-get install nginx

This gave me the next prompt:
After this operation, 2,707 kB of additional disk space will be used.
Do you want to continue [Y/n]?

Only 2707 kb! but each and every kb in that package is filled with pure awesomeness ;) type a y and press enter, it will do all the magic for you, even start nginx after it installed, and since its already running we can check the version with:

~# nginx -v
nginx version: nginx/1.0.15

Much better than 0.8.54.

Friday, April 20, 2012

Basic Installation of Ubuntu Server

In the following video I demonstrate how to install Ubuntu Server in a virtual machine, only the Operating System.
Unless otherwise noted I will assume in my posts that we are using Ubuntu Server.

Ubuntu Server 11.04 64-bit
1024 MB RAM

Related Topics:

Thursday, April 19, 2012

What is your role in your website?

Are you a site owner? a webmaster? or a site administrator? maybe you are all of them and maybe you dont know what is your role. Hobbyist should not worry about this post, but people serious about their site will find this either very useful or old news

Site Administrator

A site administrator most often coordinates with the staff (forum moderators, designers,...) to implement either a change in the policies or address some specific issue, knows the administration panel inside out and notices bugs before most of the site visitors. This role is administrative and deals with the operations of the site. Listening to guests complaints is very normal and spending time in the site is a daily task. This person has people skills but no need for technical knowledge.

Webmaster

A webmaster makes sure that the site works from the technical grounds. The webmaster will speak with the Site Administrator but not with the clients or visitors. Common tasks are running performance tests, defining and executing a backup policy, monitoring and preventing site attacks and should it be needed, remedying site attacks, maintaining the development site and migrating changes to the production site also fall on this person's shoulders. It is the webmaster who should contact the support department because this person has all the accesses, all the logs, knows how to communicate in technical terms and is capable of testing and deploying (should there be more than one server) any change suggested by the support department.

Site Owner

Can be seen as the founder, investor and main planner. This person worries about the money and how to grow the business, coordinating marketing campaigns and the direction of the site is all too normal. This person does not contact support, does not speak with the site visitors to address problems...

These are of course subjective terms and a big site may have even more roles for more people involved (content manager, research and development,...) but hopefully they will help you figure out what sort of tasks should you or someone else in your team be doing.

Wednesday, April 11, 2012

Types of Plug-ins in Phpfox

There are two types of plug-ins in Phpfox, the flat-file ones and the database added ones. Please note that I am not talking about "Plug-in Hooks". The database added ones are the ones you create through the AdminCP, you can disable these from the AdminCP and tie them to a product and module so when you disable either of them the plug-in is also disabled:
The second type of plugins are flat files, there are no control over these from the AdminCP and should in general be avoided. To add this sort of plug-in you would only need to create a php file in the plugins folder of your module, the file name is the hook that will trigger this plug-in, for example: /module/mymodule/include/plugin/url_getdomain_1.php the contents of the php file must still include the php opening and closing tags (<?php and ?>)

Tuesday, April 10, 2012

Phpfox sites attacked

During Easter we learned that some phpfox sites were literally cracked ('hacked' is most commonly used out of context), funny thing is these sites did not apply the security fix that prevented this. We released that security patch over a month before the attacks. Thankfully the affected sites realized it was their mistake and didn't complained to us.

If your site is affected by this attack please contact our support department as soon as possible.

To help alleviate the situation our support department has been attending these cases regardless of their support access, with our without valid support we have been helping sites by cleaning their corrupted files and restoring their site to a working and healthy state.

Word of advise, stay up to date with security patches.

Edit: Ray said something today I had not thought of, people with pirated sites did not get the free clean up that we provided. Just by having a valid license we fixed the site administrator's mistake free of charge. Something to think about...

Sunday, April 8, 2012

An introduction to User Group Settings in Phpfox

Phpfox is built around the idea that one user belongs to a specific group.
With this in mind each user group can be customized in over 300 ways given the number of user group settings available. A user group setting must belong to a module, so we reference them with this format:
<module>.<name>
for example:
user.can_browse_users_in_public

A user group setting is used in the code to control different things. If you simply add a new user group setting via the AdminCP it will not do anything, you need to add the code for that new user group setting to make sense. Adding user group settings is a task for developers and a site administrator should never have to do this.

To change the value of a user group setting you simply go to the AdminCP -> Users -> Manage User Groups:


From here we can get to the user group settings:


Thursday, April 5, 2012

.doc Attachments vs FireShot

Dear Non-techie-customer,

You do not need to put your images in a .doc (Microsoft Word) file. It does not make you or your email look more professional, it makes you look like you do not know how to attach more than one file.

A much better way of doing it is using FireShot, its free to use and free to host your images, then you only send the URL/Link to the image which makes it much easier to see the image. You can add text, pointers, highlight boxes and all for free

Thank you

Wednesday, April 4, 2012

Why CometChat Improves Performance?

Every now and then we get a client in support whose hosting account has been suspended for 'abuse'. The typical case is that the client was in a shared hosting package with more traffic than it could handle, and the real killer is often the default IM that comes with Phpfox. This does not necessarily mean that the default IM is poorly coded and here's why: When a user sends a message via the default IM this message uses an ajax connection and connects to the web server (which in 100% of the cases we've had with this problem is Apache), the web server loads the PHP engine, the PHP engine loads the Phpfox libraries and Phpfox connects to the database and stores the message in the database, which could be as short as one word ("Yes") or even less. A user can send almost one message per second (depends on typing speed) and in these (un)lucky cases that can mean the entire routine all over again for each and every message sent.
At the same time, every client that is connected to your IM is listening for messages, this process means that the client (web browser) opens an ajax connection, this reaches the web server (again, usually Apache), this loads the PHP engine which then loads the Phpfox libraries and it checks for new messages, so far its only a second, but if there are no new messages or no new users online, it simply waits, checks the database 5 seconds later and if nothing new still, it waits... and so on for like 30 seconds, during this time the connection to the server was open, PHP and Phpfox loaded in memory and database being queried constantly, for every client that is connected. Share hosting plans limit the amount of connections open and with good reason, they have to enforce the "good neighbor" policy, but this means one single site cannot support a certain number of connections open at the same time.

Frankly, CometChat has a lot of cool features, but what really boosts performance in the client's server is the CometService, it literally takes the load off the server. Make no mistake, if you do not get CometService you will still get a better IM than the default one, but it will query your server constantly and the benefits will be limited. The CometService adds true Comet technology, meaning it is the server who contacts the client (web browser) when there is anything new.  And it is not even the client's server who takes the load, its CometChat's server.

If you are a Phpfoxer and your server is suffering from the default IM's load, do not blame the IM, blame the architecture, it was built before Comet technology existed, and give CometService a try, it costs $9/month.

Friday, March 30, 2012

Short Guide To A Successful Upgrade of Phpfox

Recently we have heard of a series of failed upgrades from versions 3.0.x to 3.1.0. One thing they all had in common was a human factor, "level 8" in the OSI model as we used to joke back in college.

The upgrade routine is pretty straightforward, you can read the official guide here, but still it seems people have some problems, so here it is to make your life a little bit easier.


  1. If you are upgrading your live site before upgrading your development site, stop and change gears to upgrading your development site. Only when the upgrade has satisfied you in the development site do you upgrade your live site.
  2. If you do not have a development site set up one.
  3. Make a full backup of your site, this may be 'painful' in terms of server load and in 99.99% of the cases not needed, but if you are the lucky one you will regret not having one.
  4. Enable debug mode, if anything goes wrong it will show you very important information.
  5. Only upload recently downloaded files from the account area. In this way you are making sure that you have the most up to date files, and that these have no modifications.
  6. Read everything that the script shows you. Even if you have upgraded thousands of sites, read and assume you do not know by heart what the upgrade says. 
  7. A red warning is worth attention. If you have a working site and you replace the file /include/setting/server.sett.php with an invalid one the upgrade routine will think you are installing fresh and offer you to drop (delete, remove, wipe, lose) the tables in your database. This means if you proceed you will lose your existing site, all the members, all the photos... everything. This warning looks like this, its really hard to miss!
    Warning message when upgrading Phpfox
    (It does not even have a "Next" step, it has a red button with a warning)


  8. Sometimes when you upload files they may land with very limited privileges, if you have debug mode enabled you will see a warning but know what to do because debug mode was enabled. Work with your hosting company to ensure that all files and folders have the least permissions needed for the script to work

Last: If you post a comment here asking for support you will be disappointed. While I might be in a good mood your best option is to go to the forums and look for help there, but look for posts already existing, your problem is most likely already solved in an existing thread.