We build. You grow.

Get best community software here

Start a social network, a fan-site, an education project with oxwall - free opensource community software

Oxwall Store Coding Standards

Table of Contents



Oxwall Coding Standard Policies

If you decide to write code for Oxwall regardless if it is for the software package core itself or as a plugin developer: Make sure you observe code style standards described in this policy. Some policies apply to core coding, some apply to plugin coding and some apply to both. We will specify how the rule applies in each rule that follows.

You don't have to make your code look fancy to write a great plugin. However, think how others looking at your code would appreciate if it's written like the rest of the Oxwall code. All rules in this policy are not because it is just our preference. There is a reason behind each policy with regards to security, readability, portability, compatibility, fail-safety and general acceptability in mind.

New policies have been marked with [New]

General

[New] Page Routing: All plugin initial page routing must be in the init.php file.

[New] Custom Plugin Config Declarations: All plugin config declarations should be in the install.php file and should resemble the format below. There should be one declaration for each custom plugin config value.

		  
		    $config = OW::getConfig();		  
		    if( !$config->configExists('plugin_name_goes_here', 'config_name_goes_here') )
                    {
                     $config->addConfig('plugin_name_goes_here', 'config_name_goes_here', 'initial_value_goes_here');
                    }
             
[New] Using Smarty Functions: Since it is known that the > (greater than sign) could break smartys xml parser, when coding html for smarty in your html pages please try to use the smarty functions (gt, eq, lt) greater than, equalto, less than.

[New] Initializing User Role Authorization Group and Options: The initialization of user roles group and options should be in the install.php file. User role initialization is a one time per install process. The actual label assignment for the user roles should be in the init.php file.

Example inside the install.php file:

			
	      //the true option is if you want to allow this option for guests, for false ignore the option (leave it out)
	      $authorization = OW::getAuthorization();
              $groupName = 'plugin_name_goes_here';
              $authorization->addGroup($groupName);
              $authorization->addAction($groupName, 'add_plugin_name_goes_here',true);
              $authorization->addAction($groupName, 'view_plugin_name_goes_here',true);  
              $authorization->addAction($groupName, 'add_comment');
              $authorization->addAction($groupName, 'delete_comment_byowner');		    
             


Example inside the init.php file:

              //here is where you add the language labels you want to use for your user role options

              //role auth
              function pluginname_add_auth_labels(BASE_CLASS_EventCollector $event) 
              {
               $language = OW::getLanguage();
               $event->add(array(
                                 'pluginname' =>array(
                                                      'label' => $language->text('pluginname', 'auth_group_label'),
                                                      'actions' =>array(
                                                                        'add_pluginname' => $language->text('pluginname', 'auth_action_label_add'),
                                                                        'view_pluginname' => $language->text('pluginname', 'auth_action_label_view'), 
                                                                        'add_comment' => $language->text('pluginname', 'auth_action_label_add_comment'),
                                                                        'delete_comment_byowner' => $language->text('pluginname', 'auth_action_label_delete_comment_byowner')                                                
                                                                        )
                                                       )
                                 )
                            );
                }//close function

                OW::getEventManager()->bind('admin.add_auth_labels', 'pluginname_add_auth_labels');		
               
[New] Internal Documentation: We ask that you add internal documentation text to your code when appropriate. It is not required that you document every line of code, but enough so someone can follow your logic. All internal docuemntation should be in plain english. Having some internal documentation of what is happening in the code speeds up approval time as well as other benefits. So please document when you can.

[New] Core File Changes: There is almost no reason that a plugin should ever change the permission or content of a core file. There is usualy a core method/function that will do the task you need to do, so find them and use them. The only exception to this policy is if your plugin is modifying the values of DEV_MODE or DEBUG_MODE. In that case you can edit the file permssions if you need to so you can write to the file and change the values. However, what we would like to see is that code placed inside of a try catch so that in the event the plugin fails, we do not want the config file to be sitting there with a permission value of 777 which is very dangerious. So in your catch portion just set the permission back to 644 to protect the config file.

[New] No Obfuscation: Since this is an open source project, no part of your plugin can be obfuscated in any way and must be viewable and readable without any special application process.

[New] Installation Callbacks: Developer callbacks to gather data regarding your plugin install can only occur during the install process and nowhere else in the plugin. Data that is retrieved during the callback is limited to any of the following values - site url, site ip, site email, timestamp of installation, and license key No other values of any kind shall ever be received by a developer in any format no by any means from a users server. If your plugin uses an installation callback you must include this disclaimer in your product area somewhere and also somewhere in the plugin where the user can see it before installation.

  • Disclaimer: This plugin may send limited static data back to developer including site url, site ip, site email, timestamp of installation, and license key during the installation process. If you do not want this data sent back to developer then do not install this plugin.


[New] Database Query Model: All database queries must be made using the secure BOL model. This means that no sql query should ever be placed in any plugin file outside of the BOL folder. Preferably and correctly all sql queries should only be inside the DAO class file. However, there are exceptions such as if you are getting data from a core table which is outside your plugin. That said, the policy is that at a bare minimum the sql queries should be in the service class file and we would prefer that you use the DAO file but at this time it is not required (this could become a requirement at any time)

[New] Clean and Professional: Your code should be clean and professional looking. You are not only selling your plugin but you are also selling your professionalism and character so put your best foot forward. The plugin should not contain huge sections of commented out code. If there is a small section that you wish to keep for a later version we have no problem with that as long as it is within reason (meaning very short).

[New] Coding In Tiers: We require that you code in tiers. This means that the code starts from the far left and tiers to the right as the code sections are written. Finally ending up back at the far left when everything is closed up. This includes codes in PHP, JS, Jquery, Ajax, CSS and HTML.

For Example:

         //Right way
         If($donuts == $sweet)
         { 
           if($value == $value)
           {
            $value1 = $value;
           }else{
                 $value1 = '';
                }//close else value
         }//close if

         //Wrong way
         If($donuts == $sweet){ if($value == $value) { $value1 = $value; }else{ $value1 = ''; }//close if value }//close if

         All coding should follow this tiering structure below: (unless doing so will deform the parsed output - example: using pre tag).

         -
          -
           -
           -
           -
          -
         -

        


[New] Initializing PHP Variables and Arrays: This is NOT manditory yet but we would prefer if you initialize your PHP arrays and variables. There are several great reasons for doing so:
  • It lets you know at a glance what variables and array names you have already used.
  • It greatly helps prevent server notices regarding non initialed values. If your plugin gets any notices it will be rejected.
  • It helps you to standardize your names throughout the file.


Example: (this is the exception to the tier rule, you may place these items on one line and consecutive)

 
         //init variables
         if(!isset($value))  { $value  = ''; }
         if(!isset($value1)) { $value1 = ''; }
         if(!isset($value2)) { $value2 =  0; }
         ... and so on
 
 
        //init arrays
        $array1 = array();
        $array2 = array();
        .... and so on 
        
Remember that since php 5.4 php has allows shorthand arrays: (visit Arrays section in this document)

		    
        //init arrays
        $array1 = [];
        $array2 = [];
        .... and so on 
        


[New] Requireing Other Plugins: If your plugin has another plugin dependency, then you must check for that dependent plugin availability prior to any process requireing that plugin, you can do so using either method below. For example, our plugin here requires the privacy plugin. This will greatly help reduce the number of crashes caused by dependent plugin not being installed.

Check using class_exists:

       if(class_exists('PRIVACY_BOL_ActionService'))
       { 	
         //do something here  
       }else{	
	         //must show error message on screen			
	        }
       
Check it by check for plugin active

       if(OW::getPluginManager()->isPluginActive('privacy')) 
       {
        //do something here           
        }else{	 
	           //must show error on the screen			 
	         }
       

[New] PHP Tags

Always use full-form of PHP code tags when opening and closeing php: Short tag <? ?> is NOT allowed.

<?php     //php open tag
      
      ?>  //php close must be ommitted if file contains ONLY php code
      

The exception to this policy is if you are doing something like an inline variable assignment, then you can use the <?= ?> (notice the = sign) short tag like in this example where we are building a url:

   
      <a href="example.com?value1=<?= $value1;?>">press here</a>   
      

Supporting Information: The short tag <? has been depricated due to requiring the php.ini flag and will be removed as of php 8.0. However, the <?= short tag with equal sign is unaffected because as of PHP 5.4 it is always available.

Includes

include_once and require_once are statements, not functions. Parentheses should not surround the subject filename.

      //RIGHT
      require_once 'header.php';
      //WRONG
      require_once('header.php');

Indenting

Use 4 spaces instead of tabs for an indent.

Naming conventions

Filenames: (Never use dash ie. file-name in file names. Always use underscore ie. file_name as a name separator if needed

	  view.php 
	  base_dao.php 
	  my_super_class.php
	  

Classes

       class MySuperClass
       {
       //code here
       } 

       class PREFIX_MySuperClass
       {
       //code here
       }
      

Functions

	   function connect()
	   function camelCaseFunction()
	   function fooBar()
	  
global functions
function my_global_function()

Vars

	  public  $myVar;
	  private $hisVar;
	  protected $x;
	  

Constants

define("MY_MEGA_CONSTANT","Hello world");

Control structures

foreach, for, while, if, switch, try, catch etc.

There should be one space between the control keyword and opening parenthesis in control statements, which will distinguish them from function calls.

Use curly braces even in case they are optional, as this will make the code more readable and help to avoid logic errors appearing when new lines are added.

You can use either break or return in switch code. We would prefer you use break so we have standards. Howerver, if you must use return rather than break then just add comment to let us know why. Place the break or return vertically under the case item.

[New] switch

	   switch ( condition ) 
           {
             case 1:action1();
             break;
              
             case 2: action2();
             break;
              
             default:defaultAction();
             break;
           }
	  

or using return

	   switch ( condition ) 
           {
             case 1:action1();
             return;
              
             case 2: action2();
             return;
              
             default:defaultAction();
             return;
           }
	  

if statements

Split up if and if else statements onto several lines

	   if ( condition1 )
	   {
             //code here 
           }
	  
	   if ( condition1 )
	   {
             //code here 
           }else{
                 //code here
                 }
	  

long if statements

Split long if statements onto several lines

	   if ( condition1 
               || condition2
               && condition3 )
           {
           //code here
           }
	  

foreach, for, while

	  foreach ( $a as $v )
          {
          echo $v;
          }
	   

try, catch

	    try
	    {
	       //code here
	    }
	    catch ( Exception $e )
	    {
	       //code here
	    }
	   

Function declaration

All function names must be in a camelCase. Global functions are an exception. They should consist of words in lowercase and underscores.

There should be whitespaces before and after parameter list.

There should be no space between a function name and an opening parenthesis.

There should be a new line before return statement.

	  function fooBar( $param1, $param2 )
          {
            if ( $param1 !=== $param2 )
            {
              //code here 
            }
         
          return true;
          }
	   

You should always declare a type of parameter when possible:

	   function doSomethingGood( MyClass $obj )
           {
             //code here
           }
	   

Global function example:

	   function print_var( $var, $echo = false )
           {
             //code here
           }
	   

Function calls

	  myCoolFunction(1, 2, 3);
          $this->myCoolMethod(1, 2, 3);
	  

Arrays

Indexed arrays

	  $arr = [1, 2, 'no', 'pain', 'no', 'gain' ];
          $longArr = [ 1, 2, 3,
                       4, 5, 6,
                       7, 8, 9 ];
	  

Associative arrays

	    $assoc = [ 'key1' => 'value1',
                       'key2' => 'value2',
                       'key3' => 'value3' ];
	  

You can place the closing parenthesis on the same line or the following line. If you use the following line please line it up with the open parenthesis. Like so:



	    $assoc = [ 'key1' => 'value1',
                       'key2' => 'value2',
                       'key3' => 'value3' 
	             ];
	  
© 2020 Oxwall.com All rights reserved
Last modified by : Dave