Welcome to Gila CMS’s documentation!

Contents:

About

Gila CMS is an open-source and free content management system built with php7. Built with MVC architecture, is very easy to develop on it any customized solution. It is licensed under BSD 3-Clause License. The website is gilacms.com

Why choose Gila?

Gila CMS is a good option for self-hosted blogs or startup websites

  • Installs by default a blogging system with social integrations.
  • No coding skills are required to install or maintain the website
  • Themes that include are responsive, that makes it accessible in all devices.
  • It is fast, and compresses the content where it needs to.

Spreading the word!

You can help us spread the word about Gila CMS! We would surely appreciate it!

Where you can get help

  • Join Slack or Gitter
  • Ask on stackoverflow using the tag gilacms

Installation

Preparation

Before beginning with installation make sure that your web host or local server meets these requirements:

  • Apache 2/ Nginx server
  • MySQL / MariaDB server
  • PHP 7.0+ with the following extensions mysqli, zip, mysqlnd, json, gd and mod_rewrite enabled

If you want to install gila cms in your local machine and not sure how to prepare your server don’t hesitate to ask for help on Slack

First unzip gila in a public html folder e.g /var/www/html/gila and make sure that the folder is writable from the application.

On nginx server you will need to configure the redirects in /etc/nginx/sites-enabled/default (issue #1)

location / {
    index index.php index.html index.htm;
    rewrite gila/(?!install)(?!src)(?!themes)(?!lib)(?!assets)(?!tmp)(?!robots.txt)(.*)$ /gila/index.php?url=$1 last;
}

On apache 2 server you may need to edit default VirtualHost file in order let .htaccess work. On ubuntu/debian you run

sudo nano /etc/apache2/sites-available/000-default.conf

And add these lines after DocumentRoot /var/www/html

<Directory "/var/www/html">
    AllowOverride All
</Directory>

If you need to activate mod_rewrite for apache

sudo a2enmod rewrite

Don’t forget to restart your server if you made any changes.

In order to proceed with the installation, you will need your database settings. If you do not know your database settings, please contact your host and ask for them. You will not be able to continue without them. More precisely you need the database hostname, the database name, the database username and password.

Installer

We access in installation page with the browser e.g http://localhost/gila/install

_images/install.jpgInstall

In the installation page we must fill all the fields

  • Hostname: the hostname of the database, usually it is localhost
  • Database: name of the database
  • DB Username, DB Password: the username and the password in order to connect to the mysql
  • Admin Username, Admin Email, Admin Password: a user will be created for the website as administrator with these data
  • Base Url: the web address of the website e.g. https://mywebsite.com/

After filling the data and submit them, we wait a few seconds untill the installation is finished.

_images/installed.jpg

When installation is finished we can enter on the admin panel using the admin email and password that we wrote before.

_images/login.png

We can always access in the login page from these links mysite.com/ /login it redirects to the front page of the website mysite.com/ /admin it redirects to the administration

We enter in the administration dashboard.

_images/dash.pngDashboard

On the administration menu we see two submenus

  • Content to add or edit content like pages, posts or files
  • Administration to edit users or change the settings of the website.

Content

In the administration menu the Content option gives a submenu of the basic content types of Gila:


Pages

Pages are the basic content type. A page can be just a text or have media. The information of a page is independent of time so you want them to be found by the visitor in the same place, like on the menu of the website.

_images/pages.pngPages Every page have four values:

  • ID: a unique identifier
  • Title: the title of the page
  • Slug: is the path of the page. For example the path of a page with title ‘My Page’ will be mysite.com/my-page
  • Public: an on/off flag. If Public value is off for ‘My Page’ then mysite.com/my-page wont be accessible from the browser.

To create a new page click on button New that you see on the up-right corner of the table. _images/page-new.pngNew Page

Posts

The posts can be news or articles about your business or the interests of the website. They are organized in categories and are listed in chronological order.

To create a new post click on button New that you see on the up-right corner of the table. _images/post-new.pngNew Post

Categories

Categories are used to categorize posts or maybe other popular content that you could use later. You only add or edit the names of the categories.

Media

Media are the images that you want to use for your posts. They are saved as files and not in the database like the other content types. The root directory of media is /assets. The files and subfolders of /assets are visible in the public by the path mysite.com/assets so you should not upload files or images that you don’t want to be found from search engines.

_images/media.pngMedia

Logs

In this page you can navigate inside the log files of the installation.

DB Backups

You can create a new database backup and then download it or restore(Load) it later.

Administration

In the administration menu you the Administration option gives a sub menu of the basic administration areas


Users

Users are the persons that you can grand access to website and give them privileges to create or edit content. On Users tab you can add new or modify existing users.

User Roles

On Roles you can add new roles for the users. Roles represent job functions and through them users acquire specific permissions. _images/user-roles.pngRoles

Permissions

On Permissions you can set the common permissions that all registered users can have or to specific user roles. Permissions grand to the users access to resources or perform certain operations. _images/user-permissions.pngPermissions

Widgets

Widgets are some blocks that you can show them on the layout of the website and improve the user experience of the visitors. Widgets can be for example menus, comment sections, text blocks, lists of links. Every page have four values:

  • ID: a unique identifier
  • Title: the title of the widget
  • Type: widget type
  • Widget Area: is where the widget will be displayed. Can be an area in a view from the website theme or the administration.
  • Position: the position of the widget in the widget area.
  • Active: if the widget is visible or not.

Notice: When you create a new widget you can set the type of the widget, this field cannot not be changed later since it determines the widget’s structure of the data.

Packages

Packages give new functionalities on your web application. They may add a specific widget, a few new links in the administration menu or add new content and new templates to show the content. For example Facebook Comments Plugin add a facebook comments section below every page post. Featured Posts Grid show the thumbnails photos from featured posts in the front page of a blog theme.

You can administrate packages from Administration->Packages

_images/packages.pngPackages

The installed packages usually show an Options button. By clicking this button you can change some parameters for the specific package. When you save the settings the changes will take effect by reloading the page.

_images/packages-options.pngPackages

Themes

Themes change the look and style of your website. They use different colors and fonts and helps your visitors identify your website and improve their user experience (UX).

You can select the theme from Administration->Themes

_images/themes.pngThemes

The selected theme usually shows an Options button. By clicking this button you can change some options for the theme like the header image (logo) of the website or the main color.

Settings

On Administration->Settings page and we can make the following configurations

Basic Settings

  • Title is the website title. It will appear up from the menu if we don’t use a logo from the theme options.
  • Description is a small text that describes the website.
  • Website URL the url path for exmple ‘https://mysite.com’
  • Admin Email sets the email of the administration.
  • New users can register adds the registration form for the visitors so they can register as users.
  • Theme changes the look and style of your website. You can also change the theme from Administration->Themes
  • Timezone The dates and times saved in posts, logs and the rest of the content will be based on the selected timezone.
  • Language The language of the website and the administration menu.
  • Admin Logo set the image to display to administration menu and login screen.
  • Favicon set the icon for your website.

Advanced Setting

You change these setting if you are developing or set up the installtion.

  • Use CDN Use CDN for static files of popular libraries (jquery.js, vue.js). It’s not advised for local installation where internet connection may fail.
  • Pretty Urls turns ?c=blog&action=tag&tag=linux into blog/tag/linux. If is not selected by default then your apache server may not have the mod_rewrite enabled.
  • Default controller The controller that will be used if the calling path do not provide it as first parameter. For example the Admin controller is used when we call mysite.com/admin but when we call mysite.com or mysite.com/my-post the default controller will be used, which is Blog, so these paths are egual with mysite.com and mysite.com/my-post. There is not need to change the default controller unless you want to change how the website will be used.
  • Environment If changes to Development the website wont use the combine load.php from the packages and will display all notices and errors of the back end. Must use it when you make changes in the code.
  • Check For Updates will automatically search for new updates on packages and display alerts.
  • Use WEBP your website will save resized images as webp images, their size is al least 10% small from jpeg or png.
  • Max Media Upload (px) The maximum width and height of uploaded images (in pixels). If these values are set, then the uploaded images with bigger sizes will be resized. This is a way to avoid excessive use of disk space from photos.

The following settings can be set directly in config.php but you be careful, because they could create security issues with your website.

  • trusted_domains An array of domains that your website will work. For example the main domain, the ip and parked domains.
  • cors (Cross-Origin Resource Sharing) An array of domains that your website will respond in requests.

PHPinfo

This option will display the settings of the php moduls on the server. This is for informational purposes only. DO NOT share screenshots in the public of this page as it includes data about the server configuration.

/admin/sql

In this page you can review your database, only administrators have access.

/admin/content

In this page you can see all the registered tables in your system.

Structure

In the main folder we can see these folders and files.

assets/
lib/
log/
tmp/
src/
themes/
index.php
config.php

assets/ A public folder where we upload our media files.

lib/ A public folder. Third-party libraries are inside this folder.

log/ A private folder that save logs and the user sessions.

tmp/ A public folder with temporally files created.

src/ The folder of installed packages. Here is all the code of the system.

themes/ The folder of installed themes.

index.php The main index file. For any call, execution starts from here.

config.php The configuration file. It is generated after installation.

Packages

The source code of Gila CMS is split into packages, even the core files are part of the main package called core. The package folders are placed inside src/ folder and desirably have a similar structure:

assets/
controllers/
models/
views/
lang/
package.json
load.php
logo.png

The folders are optional but very useful to organize better the code. The file package.json is a must have as it has the basic information of the package -without it the package is invisible- and the load.php is the file that will register new values and events of the package.

package.json

A simple package.json file:

{
	"name":"Package Name",
	"version":"1.0.0",
	"description":"A short descriptive text of your package for what it does.",
	"url":"package_url.com",
    "author":"Your Name"
}

You can also add another index in the object called options. It will be an array of objects, the objects are the options to be stored. The index is the option name and it can have optional values with the following indexes:

  • title the option name to be displayed, if not specified, the index is used
  • type select | postcategory
  • options array of {value:display_text}, it is required if is set type:select
{
    ...
	"options":{
        "option1":{},
		"category":{
			"type":"postcategory"
		},
		"lang":{
            "title":"Language",
            "type":"select",
			"options":{
				"en":"English","es":"Spanish","el":"Greek"
			}
		}
	}
}

You can get the option values like that:

// options are saved using as prefix the package's folder name
// for example if the package has the folder my_package/

$option1 = gila::option("my_package.option1");
$lang = gila::option("my_package.lang","en"); // use default value 'en'

More information for package.json schema.

load.php

This file is excecuted in every request to the website, so instead of adding many lines of code we usually register to the system new controllers, new routes or include on more files only when is needed. A simple load.php file could be:

<?php
// display text below any post
event::listen('post.after',function(){
	echo 'This is printed after post.';
}

IMPORTANT: The first line of the load.php file should include only the opening tag <?php and not close with the closing tag.

Some things you can do in a load file:

<?php

// add menu item or menu sub item
gila::amenu(['mymenuitem'=>['Item',"myctr",'icon'=>'link']]);
gila::amenu_child('mymenuitem',['Sub Item',"myctr/sub",'icon'=>'link']);

// add an event listener
event::listen('load', function() {
  // this function will run after all load.php from active packages
  if(gila::hasPrivilege('admin')==false) {
    view::renderFile('landing-page.php', 'mypackage');
    exit;
  }
}

// register new content type
gila::content('mytable', 'mypackage/tables/mytable.php');

// add new column on an existing content type
gila::contentInit('mytable', function(&$table) {
    $table['fields']['newfield'] = [
        'title'=>"New Field",   // the label to display
        'qtype'=>'varchar(80)', // the column type at database schema
    ];
});

// register a controller
// all /blog/* request are processed from class Blog in
// blog/controllers/blogController.php
gila::controller('blog', 'blog/controllers/blogController', 'Blog');

// add a new action for blog controller (/blog/topics)
gila::action('blog','topics',function(){
  view::render('blog-topics.php', 'mypackage');
});

Examples

Here are some examples to you get into the of package creation.

Event: Post Tags

In this example we will list the tags of a post just after it. Create a folder inside src/ and name it post-tags. Inside it create the following files

package.json
load.php
logo.png

package.json

{
	"name":"Post Tags",
	"version":"1.0.0",
	"description":"A package to show tags below the post."
}

load.php will run a code when the package is active. We will register a function to run right after the post display.

<?php

event::listen('post.after', function(){
    global $g; // $g will give us the post id
    $tags = core\models\post::meta($g->id,'tag');     // get the tag list of post
    echo "<strong>TAGS:</strong> ";
    foreach ($tags as $tag) echo " <a href='tag/$tag'>#$tag</a>";
});

This function will run when the post.after event is dispatched. That happens with event::fire(‘post.after’); or event::widget_area(‘post.after’); from single-post.php view file.

logo.png is the package’s logo and is displayed in the package list.

Activate the package in /admin/packages. After that you should see the list of TAGS below any blog post.



Widget: Twitter Timeline

In this example we will create a widget that displays the last tweets of an account. Instead of using an event to run the code we let the user create instances of the widget choose in which widget area want to display the twitter plugin. Inside src/ create a folder twitter-timelines and add the following files:

package.json
load.php
widgets/twitter-timeline/widget.php
widgets/twitter-timeline/twitter-timeline.php

package.json:

{
	"name":"Twitter Timelines",
	"version":"1.0.0",
	"description":"Installs a widget to display twitter timelines."
}

load.php:

<?php

// registers the widget name and its path
gila::widgets([
    'twitter-timeline'=>'twitter-timelines/widgets/twitter-timeline'
]);

widgets/twitter-timeline/widget.php will include the widget options we want to use. In this case we need the user account and the name to be displayed.

<?php

$options=[
    'accountID'=>[
        'title'=>'Twitter Account'
    ]
];

widgets/twitter-timeline/twitter-timeline.php is the view file of the widget, it will generate the html code. We use the embedding Twitter content from here

<?php
$account = gila::option('twitter-timelines.accountID','gilacms');
?>
<a class="twitter-timeline" data-height="400" href="https://twitter.com/<?=$account?>">Tweets by <?=$account?></a>
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>

gila::option() gets the option of the package that we set up in the package settings. A default value can be used if the option is null.

Activate the package. Now in /admin/widgets you can create a new widget with type twitter-timeline and set the widget area sidebar or dashboard to see it.



User: Address

In this example we will add a new field for the users. Instead of adding a new column in the database table we will use the usermeta table to store new values that link to the users. Inside src/ create a folder user-address and add the following files:

package.json
load.php

package.json:

{
	"name":"User Address",
	"version":"1.0.0",
	"description":"Adds a new field for the users."
}

load.php:

<?php

// make changes to the user content type

gila::contentInit('user', function(&$table){
    $table['fields']['useraddress'] = [
        'title'=>"Address",   //the label
        'type'=>'meta',       //the values of the field will be stored in a meta table
        'input-type'=>'text', //use the text input type
        'edit'=>true,         //is editable from user
        'values'=>1,          //this field gets only one value
        "mt"=>['usermeta', 'user_id', 'value'], //meta table, meta column that links to user table,meta column of the value
        'metatype'=>['vartype', 'address'] //meta column of the value type, value type
    ];
});

This package will add a new new Address field for users in Administration->Users

Themes

Themes change the look and style of your website. You can also change the theme from Administration->Themes. They are located in themes/.

What themes do

  • They override the view files from the packages. View files in packages are placed in a views/ folder, in themes are placed directly in their root folder. For example when a controller will try to render a view file from the package core it will call view::renderFile(‘blog-post.php’,’core’). If exists the file themes//blog-post.php it will rendered instead of src/core/views/blog-post
  • They override the response files of the widgets. These files are placed in widgets/ folder of the theme. For example, themes//widgets/text.php will replace src/core/widgets/text/text.php when a widget of text will be rendered. This is useful when you want to add styling to widgets similar to the theme. Note that you don’t have to create folders for each widget.

Structure

Inside a theme folder we need to have the following files:

package.json
screenshot.png
load.php
widgets/
  • package.json has the basic information of the theme and uses a similar schema with the packages.
  • screenshot.png can be an image of maximum width of 320 pixels. It is used to display the theme on the the themes selection.
  • load.php registers new variables to the system, like the widget areas that offers, routes for static files or a parent theme.
  • widgets/ folder include the responses of the widgets that you want to override.

New theme

How to create new theme:

Create a new folder inside themes/ with name my-new-theme. Inside create a new package.json file:

{
    "name": "My New Theme",
    "version": "1.0.0",
    "author": "My Name"
}

Now you have a new but empty theme to choose in Administration->Themes. It is only missing is a screenshot.png file to display.

Although it has no view files of its own, when is selected, it will use the original view files of the src/core/views/ folder.

Child themes

Child themes is the easiest way to make a new theme by making just a few changes on an existing theme. Make changes directly on another theme is a bad idea, since it can be updated any time and you lose all the adjustments you made.

How to create a child theme:

We choose gila-blog as parent, first create a new folder inside themes/ with name my-child-theme and a package.json:

{
    "name": "My Child Theme",
    "version": "1.0.0",
    "author": "My Name",
    "parent": "gila-blog"
}

We create load.php file:

<?php

view::$parent_theme = 'gila-blog';
... copy here the code of themes/gila-blog/load.php

We need to let view class know which is the parent theme, so first the rendering methods will try to find the view files in the parent theme when they fail to find theme in the selected(child) theme.

Now inside the folder of this theme you can edit the view files. Giving to the folder a name with prefix my- or custom- you make sure that the name will not conflict with a public theme from theme manager.

Cloned themes

If you want to create a new theme based on another one you can just copy its files. In this way you dont have to keep installed the original theme.

How to clone a theme:

Make a copy of gila-blog and name it my-clone-theme. In package.json file change the name:

...
    "name": "My Clone Theme",
...

load.php

Some use case of load.php

// add new widget areas that theme includes
array_push(gila::$widget_area, 'footer','sidebar','post.after');

// include stylesheet
view::stylesheet('lib/font-awesome/css/font-awesome.min.css');

Schemas

package.json

package.json is used from both packages and themes to set their values. This schema is saved in json format and uses these indeces:

  • name (string)

Name of the package or theme.

  • version (string)

Version in (semantic versioning)[https://semver.org/]

  • description (string)

A small paragraph explaining what the package does.

  • url (string)

A path to more information for this package.

  • logo (string)

An image path to display as logo. Used only by packages.

  • screenshot (string)

An image path to display as screenshot. Used only by themes.

  • parent (string)

The parent theme. Used only by themes.

  • options (object)

An array of fields that uses this package as options. See Field Schema.

  • permissions (object)

A list of new permissions that this package uses. Used only by packages.

Example

"permissions": {
		"admin":"All administration privileges",
		"admin_user":"Administrate users"
}
  • lang (string)

A relative path to the language prefix that translates the strings set in the package.json like permissions and option labels.

Table Schema

The table schema is used for a content type. It gives to the application the structure of the database table that stores the data. So the content administration page will be generated on its own and the content creators can manipulate the data with no further code.

  • name (string)

The name of the database table that data is stored.

  • title (string)

The title to display at content administration.

  • id (string)

(Optional) The field name that is the primary key on database table. Default value is id.

  • permissions (assoc array)

(Optional) Associative array of user permissions required to run the actions. Example:

'permissions'=>[
        'create'=>['admin','content-contributor'],
        'update'=>['admin','content-editor'],
        'delete'=>['admin']
    ],
  • fields (assoc array)

Associative array of the content fields. They follow the Field Schema. Example:

'field_name'=> [
            'title'=>'Title',
        ],
  • pagination (int)

Number of results per page in content administration.

  • lang (string)

(Optional) A relative path to the language prefix that translates the strings set in thetable schema like permissions and field titles.

  • search-box (boolean)

(Optional) If true, it displays a search box in content administration.

  • tools (array)

(Optional) An array of tools that will be displayed in content administration.

  • commands (array)

(Optional) An array of commands that will be displayed in content administration.

  • search-boxes

(Optional) An array of field names. Their search filters will be displayed in content administration as.

  • children (assoc array)

(Optional) References to other content types that are partials of the parent content. The index of a child must be an existing content type. The child is an associative array with two indeces: - parent_id (string) The field of child table that points to the parent’s id. - list (array) The listed fields of child table. The schema of the child must result in the same list of fields.

Example child for a shop_order content type:

'children'=>[
        'shop_orderitem'=>[
            'parent_id'=>'order_id', 
            'list'=>['id','image','product_id','description','qty','cost']
        ]
    ]
  • events (array of [string,function])

(Optional) The first value is the event name and the second value is the function that will be triggered. The function gets a reference to the specific row of the table. Posible values for the event: - change Runs when a row is created or updated

Field Schema

Fields are used as options from packages and widgets or as columns from table schemas. When are used as options from packages their format is JSON, the other cases are as php associative arrays.

[Field Schema is still unfinished, please join a chat for more information]

  • title (string)

The label of the field to display.

  • default (any)

The default value to use in input field.

  • type (string)

The field type. Specifies how the data is processed. If input-type is not specified it will also be used as input type. These values can be: - text - select - meta

  • input-type (string)

Specifies what input type will be used. Default values for 1.8.0: - select - meta - radio - postcategory - media - textarea - tinymce - checkbox - switcher - list (cannot be used in table schemas)

  • allow-tags (boolean/string)

Lets the field value keep html tags or remove them. The default value of allow-tags is false.

Example

"allow-tags": "<a><p><ul><li>",

Class gila

class gila

Common methods for Gila CMS

controller($c, $file, $name=null)

(static) Register a new controller.

Parameters:
  • $c (string) – Controllers name
  • $file (string) – Controller’s filepath without the php extension
  • $name (string) – Optional. Controller’s class name, $c is used by default

Example:

gila::controller('my-ctrl', 'my_package/controllers/ctrl','myctrl');
route($r, $fn)

(static) Registers a function call on a specific path.

Parameters:
  • $r (string) – The path
  • $fn (Function) – Callback for the route

Example:

gila::route('some.txt', function(){ echo 'Some text.'; });
onController($c, $fn)

(static) Registers a function to run right after the controller class construction.

Parameters:
  • $c (string) – The controller’s class name
  • $fn (Function) – Callback

Example:

gila::route('blog', function(){ blog::ppp = 24; });
action($c, $action, $fn)

(static) Registers a new action or replaces an existing for a controller.

Parameters:
  • $c (string) – The controller’s class name
  • $action (string) – The action
  • $fn (Function) – Callback

Example:

gila::action('blog', 'topics', function(){ blog::tagsAction(); });
onAction($c, $action, $fn)

(static) Runs after an action and before the display of view file.

Parameters:
  • $c (string) – The controller’s class name
  • $action (string) – The action
  • $fn (Function) – Callback

Example:

gila::onAction('blog', 'topics', function(){ view::set('new_variable', 'value'); });
before($c, $action, $fn)

(static) Registers a function to run before the function of a specific action.

Parameters:
  • $c (string) – The controller’s class name
  • $action (string) – The action
  • $fn (Function) – Callback

Example:

gila::action('blog', 'topics', function(){ blog::tagsAction(); });
addLang($path)

(static) Adds language translations from a json file.

Parameters:$path (string) – Path to the folder/prefix of language json files

Example:

gila::addLang('mypackages/lang/');
addList($list, $el)

(static) Adds en element in a global array.

Parameters:
  • $list (string) – Name of the list
  • $el (mixed) – Value
getList($list)

(static) Returns the array of a list.

Parameters:$list (string) – Name of the list
widgets($list)

(static) Register new widgets.

Parameters:$list (Array) –

Example:

gila::widgets( [‘wdg’=>’my_package/widgets/wdg’] );
content($key, $path)

(static) Register new content type.

:param String $key Name of content type :param String $path Path to the table file

Example:

gila::content( 'mytable', 'package_name/content/mytable.php' );
contentInit($key, $init)

(static) Make changes on an existing content type.

Parameters:
  • $key (String) – Name of content type
  • $init (Function) – Function to run when initializes the content type object

Example:

gila::contentInit( 'mytable', function(&$table){
    // unlist a column from content administration
    &$table['fields']['column1']['list] = false;
} );
packages($list)

(static) Returns an array with the active packages names.

amenu($items)

(static) Add new elements on administration menu.

Parameters:Array $items (Assoc) – menu items

Example:

gila::amenu([
  'item'=>['Item','controller/action','icon'=>'item-icon']
]);
amenu_child($key, $item)

(static) Add a child element on administration menu.

Parameters:
  • $key (string) – Index of the parent item.
  • $item (Array) –

Example:

gila::amenu_child('item', ['Child Item','controller/action','icon'=>'item-icon']);
config($key, $value = null)

(static) Sets or gets the value of configuration element.

Parameters:
  • $key (string) – Index of the element.
  • $value (*) – (optional) The value.
Returns:

The value if parameter $value is not sent.

setConfig($key, $value='')

(static) Sets the value of configuration element.

Parameters:
  • $key (string) – Index of the element.
  • $value (*) – The value to set.
updateConfigFile()

(static) Updates the config.php file.

equal($v1, $v2)

(static) Checks if two values are set and have the same value.

Parameters:
  • $v1 (*) – First value.
  • $v2 (*) – Second value.
Returns:

True or false.

hash($pass)

(static) Generates a hash password from a string.

Parameters:$pass (string) – The string to be hashed.
Returns:Hashed password.
option($option, $default='')

(static) Gets an option value.

Parameters:
  • $option (string) – Option name.
  • $default (string) – (optional) The value to return if there option has not saved value.
Returns:

The option value.

setOption($option, $value='')

(static) Sets an option value.

Parameters:
  • $option (string) – Option name.
  • $default (string) – The value to set.
hasPrivilege($pri)

(static) Checks if logged in user has at least one of the required privileges.

Parameters:$pri (string/Array) – The privilege(s) to check.
Returns:True or false.
dir($path)

(static) Creates the folder if does not exist and return the path.

Parameters:$path (string) – Folder path.
Returns:string
make_url($c, $action='', $args=[])

(static) Generates a url.

Parameters:
  • $c (string) – The controller.
  • $action (string) – The action.
  • $args (Array) – The parameters in array.
Returns:

The full url path to print.

Examples:

$url1 = gila::make_url('blog','post',[1]);`` returns mysite.com/blog/post/1
$url1 = gila::make_url('blog','',['page1']);`` returns mysite.com/blog/page1
mt($arg)

(static) Returns modification times in seconds.

Parameters:$arg (string/Array) – Names of keys.
Returns:string/Array

Example:

gila::mt('my-table')
updateMt($arg)

(static) Updates modification time in seconds. You can use this function from your model classes. The cm controller runs updateMt() for any content type in update action.

Parameters:$arg (string/Array) – Names of keys.
Returns:string/Array

Example:

gila::updateMt('my-table')

Class View

Have methods that outputs the HTML

set ()

(static) Sets a parameter from a controller action that can be used later from View file.

Parameters

  • $param:string The parameter name.
  • $value:(mixed) The value.

meta ()

(static) Sets a meta value that is printed later from View::head ().

Parameters

  • $meta:string The meta name.
  • $value:string The value.

stylesheet ()

(static) Adds a new stylesheet link that is printed later from View::head ().

Parameters

  • $href:string The href attribute from the link.

script ()

(static) Adds a new script to be included in the output HTML.

Parameters

  • $script:string The src attribute from the script.
  • $prop:string (optional) A property for the script.

getThemePath ()

(static) Returns the path of the current theme.

head($meta=[])

(static) Prints all the head information in tag.

Parameters

  • $file:Array (optional) Meta values to be printed.

Example

View::head([
  'twitter:image:src'=> 'https://domain.com/img.jpg',
  'og:image'=> 'https://domain.com/img.jpg'
]);

getViewFile ()

(static) Returns the path of a file inside theme or package folder. Return false if file is not found.

  • $file:string The file path.
  • $package:string (optional) The package folder where the file is located if is not found in theme folder.

setViewFile ()

(static) Overrides the path of a View file.

Parameters

  • $file:string The file path.
  • $package:string The package folder where the file is located.

Example:

View::setViewFile('admin/settings.php','new-package');
/*
src/new-package/Views/admin/settings.php
overrides
themes/my-theme/admin/settings.php
src/core/Views/admin/settings.php
*/

render ()

(static) Prints the View file adding the header.php and footer.php from theme.

Parameters

  • $file:string The file path.
  • $package:string (optional) The package folder where the file is located if is not found in theme folder.

renderAdmin ()

(static) Prints the View file adding the admin/header.php and admin/footer.php from theme.

Parameters

  • $file:string The file path.
  • $package:string (optional) The package folder where the file is located if is not found in theme folder.

renderFile ()

(static) Prints the View file alone from theme.

Parameters

  • $file:string The file path.
  • $package:string (optional) The package folder where the file is located if is not found in theme folder.

includeFile ()

(static) Includes the View file without passing the.

Parameters

  • $file:string Relative path of the View file.
  • $package:string (optional) The package folder where the file is located if is not found in theme folder.

setViewFile ()

(static) Overrides a View file. Overrides file from any package or the theme.

Parameters

  • $file:string Relative path of the View file.
  • $package:string (optional) The package folder where the file is located if is not found in theme folder.

widget_area ()

(static) Prints the widgets of a specific area.

Parameters

  • $area:string The widget area name.
  • $div:bool (optional) Also print or not the widget inside a
    tag with its title. Default=true

getWidgetArea ()

(static) Returns the widgets of a specific area.

Parameters

  • $area:string The widget area name.

Example

View::getWidgetArea('sidebar');

getWidgetBody ()

(static) Returns the body of a widget type.

Parameters

  • $type:string Name of the widget type
  • $widget_data:array (optional) The data to be used
  • $widget_file:string (optional) Alternative wiget View file

img ($src, $prefix=’’, $max=180)

(static) Returns the html markup for an image or thumbnail image

Parameters

  • $src:string The path of original image.
  • $prefix:string (optional) The prefix name of the thumbnail. Default=’’
  • $max:integer (optional) The maximum dimension of the thumbnail in pixels. Default=180

Example

View::img('assets/image.png', 'md/', 500);

thumb ()

(static) Returns the path of a thumbnail image of specified dimensions. If thumbnail does not exist it will create one.

Parameters

  • $src:string The path of original image.
  • $prefix:string (optional) The prefix name of the thumbnail. Default=’’
  • $max:int (optional) The maximum width or height of thumbnail in pixels. Default=180

thumb_stack ()

(static) Returns path to revisioned stucked image and the list of stucked photos. If image does not exist it will be created on the fly.

Parameters

  • $src_array:Array The images to stack.
  • $file:string The name of the stucked image. It must have png extension.
  • $max:int (optional) The maximum width or height of thumbnails in pixels.

Example:

$img = ["image1.png","image2.png"];
list($file,$stacked) = View::thumb_stack($img, "tmp/stacked_file.png",80);

/* Returned values

$file: tmp/stacked_file.png?12

$stacked[0]: ["src"=>"image1.png","src_width"=>200,"src_height"=>1"width"=>80,"height"=>60,"type"=>2,"top"=>0]

$stacked[1]: false (2nd image was not stacked)
*/

thumb_srcset ($src, $sizes = [1200,320])

(static) Returns an array of resized versions of an image

Parameters

  • $src:string The image path
  • $sizes:int array (optional) The maximum sizes in pixels

Class Event

Registers and fires events (hooks)

listen ()

(static) Sets a new function to run when an event is triggered later.

Parameters

  • $event:string The event name.
  • $handler:(function) The function to call.

fire ()

(static) Fires an event and calls all handling functions.

Parameters

  • $event:string The event name.
  • $params:array (optional) Parameters to send to handlers.

get ()

(static) Fires an event and calls the handling function (only one should be set). Returns the result of the handler.

Parameters

  • $event:string The event name.
  • $default:mixed The value to return if there was no handler called.
  • $params:array (optional) Parameters to send to handler.

Class db

Class db prepare statements for mysql queries to the connected database. We use the global $db instance to access its methods.

query ()

Runs a query and returns the result.

Parameters

  • $q:string The query.
  • $args:array (optional) Values to prepare the statement.

Examples:

$result1 = $db->query("SELECT title,author FROM post;");
$result2 = $db->query("SELECT title,author FROM post WHERE user_id=?;",[session::user_id()]);

get ()

Runs a query and returns the results as an array.

Parameters

  • $q:string The query.
  • $args:array (optional) Values to prepare the statement.

Example:

$result = $db->get("SELECT title,author FROM post;");
// Returns
[
  0=>[0=>'Lorem ipsum', 'title'=>'Lorem ipsum', 1=>'John', 'author'=>'John'],
  1=>[0=>'Duis aute irure', 'title'=>'Duis aute irure', 1=>'John', 'author'=>'John'],
]

gen ()

Runs a query and returns a generator that yields the rows.

Parameters

  • $q:string The query.
  • $args:array (optional) Values to prepare the statement.

Example:

$generator = $db->gen("SELECT title,author FROM post;");

getRows ()

Runs a query and returns the results as an array. With rows fetched with mysqli_fetch_row().

Parameters

  • $q:string The query.
  • $args:array (optional) Values to prepare the statement.

Example:

$result = $db->get("SELECT title,author FROM post;");
// Returns
[
  0=>[0=>'Lorem ipsum',1=>'John'],
  1=>[0=>'Duis aute irure',1=>'John'],
]

getList ()

Runs a query and returns an array with the values of the first columns from the results.

Parameters

  • $q:string The query.
  • $args:array (optional) Values to prepare the statement.

Example:

$titles = $db->get("SELECT title,author FROM post;");
// Returns
[0=>'Lorem ipsum', 1=>'Duis aute irure']

value ()

Runs a query and returns the value of the first column of the first row of the results.

Parameters

  • $q:string The query.
  • $args:array (optional) Values to prepare the statement.

Example:

$res = $db->get("SELECT title FROM post WHERE id=1;");
// returns
'Lorem ipsum'

error ()

Return an error if exists from the last query executed.

Example:

$res = $db->get("SELECT title,author FROM post;");
if ($error = $db->error()) {
  trigger_error($error);
}

close ()

Closes the connection to the database.

Example

$db->close();

Class gTable

Class gTable is a tool to make queries to the database, that escapes sql injections and checks the user permissions for you.

How to create an instance:

$userTable = new gTable('user');
$userTable = new gTable('src/core/tables/user.php');

Parameters

  • $name:string the table name or the relevant schema file
  • $permissions:assoc the permissions list Default: admin

The permissions that will be send will override this array:

[
  'create'=> ['admin'],
  'read'=> ['admin'],
  'update'=> ['admin'],
  'delete'=> ['admin']
]

So, by default the created gTable instance uses the admin permission, and it will compare them with the permissions that the table schema accepts. The The keys of the array can have a string array of permissions or boolean (true|false) for value.

name ()

Returns the table name

id ()

Returns the field name used as primary key

can ()

Returns true if an action is permited based on permissions. When a field name is no specified the response applies for the default permission for all the fields.

Parameters

  • $action:string the action name
  • $field:string (optional) field name

The permissions that will be send will override this array:

$permissions = user::permissions(session::user_id());
$userTable = new gTable('user', $permissions);
$userTable->can('read', 'password');
$userTable->can('delete'); // create & delete are not specified for fields 

getTable ()

Returns all table schema

getFields ()

Returns field schemas

getEmpty ()

Returns a new row with empty and predefined values

getRow ()

Returns a result in assoc arrow

Parameters

  • $filters: the filters
  • $args: (optional) more arguments

Example

$row = $user->getRow(['id'=>1]);

Argument keys

  • select:array the list of fields to return
  • orderby:assoc the prefered order of the results
  • limit:int/array the limit values for the query
  • page:int the page of total results (calculates the limit values)

getRows ()

Returns all results

Parameters

  • $filters:assoc (optional) the filters
  • $args:assoc (optional) more arguments

Example

$userNames = $user->getRows([
  'active'=> 1
],
[
  'select'=> ['name'],
  'orderby'=> ['name'=>'ASC'],
  'page'=> 1
]);

getRowsIndexed ()

Like getRows(), but rows are indexed arrays not associative arrays

Parameters

  • $filters:assoc (optional) the filters
  • $args:assoc (optional) more arguments

totalRows ()

Returns the number of rows found

Parameters

  • $filters:assoc (optional) the filters

deleteRow ()

Deletes a row from the database table

Parameters

  • $id:int the value of primary key

More classes

Class gpost

Make easy post requests from the server with the constructor of the class. Use:

$postData = ['id'=> 100];
$args = ['type'=> 'x-www-form-urlencoded'];

$response = new gpost('https://api.example.com/get', $postData, $args);
$list = $response->json();

Parameters

  • $url:string the url, or
  • $data:assoc array (optional) posted data
  • $args:assoc array (optional) options
  • $name:string (optional) base name

Option keys

  • type: x-www-form-urlencoded|json Default: json
  • ignore_errors:boolean Default: true
  • header:assoc array of headers
  • method:string Default: POST
  • url:string the url, applies only on method set() (see below)

body ()

Returns the row contents of the response

json ()

Returns the response data in object format or null

set ()

(static) Sets the prefix arguments of a base gpost

Parameters

  • $name:string the base name
  • $args:assoc options to save

Examples

$postData = ['id'=> 100];
$args = ['type'=> 'x-www-form-urlencoded'];

// directly to endpoint
$response = new gpost('https://api.example.com/get', $postData, $args);

// using a base, you can skip sending empty arguments as third parameter,
// and send the base api name
$args['url] = 'https://api.example.com/';
$args['header'] = ['Authorization'=> 'Bearer <token>'];
gpost::set('api_ex', $args);
$response = new gpost('get', $postData, 'api_ex');

Class gForm

Displays forms

posted ()

(static) It compares the value formToken from the request (GET/POST) with the stored token in session. If the name is specified the stored token will be removed in this function. Return boolean.

Parameters

  • $name: (optional) the form token name.

verifyToken ()

Compares a value to the stored token in session. Returns boolean

Parameters

  • $name: the form token name
  • $check: the value

getToken ()

(static) Creates and returns a new form token.

Parameters

  • $name: the form token name

hiddenInput ()

(static) Prints a hidden input with the value of the form token.

Parameters

  • $name: (optional) the form token name

html ()

(static) Prints the input fields for a form.

Parameters

  • $fields:assoc the fields to print as input elements
  • $values:assoc (optional) values
  • $preffic:string (optional) preffix fot the input names
  • $suffix:string (optional) suffix fot the input names

Example

gForm::html([
  'group'=>[
    'type'=>'select',
    'options'=>[0=>'Group A', 0=>'Group B']
  ]
],
[
  'group'=>1
]);

input ()

(static) Prints an input tag.

Parameters

  • $name:string the input name
  • $op:assoc the field schema
  • $ov:string (optional) current value
  • $key:string (optional) input label

addInputType ()

(static) Create a new input type for gForm class.

Parameters

  • $name:string the input type name
  • $function:function a function that returns the html

Function Parameters

  • $name:string the input name
  • $field:assoc the field schema
  • $value:mixed the current value

Example

gForm::addInputType('group-select', function($name, $field, $value) {
  // a web coomponent that will be rendered with vuejs
  $valueProp = 'value="' . $value . '"';
  $dataProp = 'data-group="' . json_encode($field['options']) . '"';
  return "<group-select $valueProp $dataProp></group-select>";
});

Authentication

In order to make the calls of Web APIs from a different domain you will need to use the token from your user.

How to generate a Token

You can generate a unique token key from the /admin/profile page. Keep this key in secret.

Use the Token from server calls (PHP)

You can send the token as post parameter:

$url = "https://example.com/cm/delete/post";
$token = "<UNIQUE_TOKEN>";
$options = [
  'http' => [
    'method'  => 'POST',
    'header'  => "Content-type: application/json",
    'content' => http_build_query(['id'=>2, 'token'=>$token]),
    'ignore_errors' => true
  ]
];

$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);

Authenticate from front-end (Javascript)

In order to make calls from a different domain, you should include the domain of your front-end app in the website’s cors value. In config.php of your installation add:

'cors'=> ['myapp.com']

From javascript you should authenticate first the user with cedentials and then use the token in your calls.

Example using axios:

// authenticate
axios.post('https://example.com/login/auth', {
  email: 'user@mail.com',
  password: 'password'
})
.then((response) => {
  token_key = response.data.token;
});

// send a request
axios.post('https://example.com/cm/delete/post', {
  id: 2,
  token: token_key
})

Content Manager

Content Manager controller gets calls from the front end and responds in json format. In order to make these calls sucessfully you need to be recognised as a user who has the permissions for these actions. For your admin user, you can generate a Unique Token Key from /admin/profile and send it as GET/POST parameter. This token should be kept private and not used from javascript calls.

/cm/describe

Returns the schema of a content type

Parameters

  • t The name of the table (GET)

Example:

curl 'https://gilacms.com/cm/describe/?t=post&token=<unique_token_key>'

Result:

{
    "name": "post",
    "title": "Posts",
    "pagination": 15,
    "id": "id",
    "tools": [
        "new_post",
        "csv"
    ],
    "csv": [
        "id",
        "title",
        "slug",
        "user_id",
        "updated",
        "publish",
        "post"
    ],
    "commands": [
        "edit",
        "clone",
        "delete"
    ],
    "lang": "core\/lang\/admin\/",
    "permissions": {
        "create": [
            "admin"
        ],
        "update": [
            "admin"
        ],
        "delete": [
            "admin"
        ],
        "read": [
            "admin"
        ]
    },
    "search-box": true,
    "search-boxes": [
        "user_id"
    ],
    "fields": {
        "id": {
            "title": "ID",
            "style": "width:5%",
            "create": false,
            "edit": false
        },
        "title": {
            "title": "Title"
        },
        "thumbnail": {
            "type": "meta",
            "list": false,
            "input-type": "media",
            "meta-csv": true,
            "mt": [
                "postmeta",
                "post_id",
                "value"
            ],
            "metatype": [
                "vartype",
                "thumbnail"
            ],
            "title": "thumbnail"
        },
        "slug": {
            "list": false,
            "title": "slug"
        },
        "user_id": {
            "title": "User",
            "type": "select",
            "options": {
                "1": "Admin"
            }
        },
        "updated": {
            "title": "Last updated",
            "type": "date",
            "searchbox": "period",
            "edit": false,
            "create": false
        },
        "categories": {
            "edit": true,
            "type": "meta",
            "mt": [
                "postmeta",
                "post_id",
                "value"
            ],
            "metatype": [
                "vartype",
                "category"
            ],
            "title": "Categories",
            "options": []
        },
        "tags": {
            "list": false,
            "edit": true,
            "type": "meta",
            "meta-csv": true,
            "mt": [
                "postmeta",
                "post_id",
                "value"
            ],
            "metatype": [
                "vartype",
                "tag"
            ],
            "title": "Tags"
        },
        "publish": {
            "title": "Public",
            "style": "width:8%",
            "type": "checkbox",
            "edit": true
        },
        "commands": {
            "title": "",
            "eval": "dv='<a href=\"admin\/posts\/'+rv.id+'\">Edit<\/a>';"
        },
        "post": {
            "list": false,
            "title": "Post",
            "edit": true,
            "type": "textarea",
            "input-type": "tinymce",
            "allow-tags": true
        }
    },
    "events": [
        [
            "change",
            {}
        ]
    ]
}

/cm/list_rows

Returns the rows as array

Parameters

  • t The name of the table (GET)

  • select (optional) The fields to return (GET)

  • orderby (optional) Ordering the results: Examples: id id_ASC id_DESC (GET)

  • groupby (optional) Groups the results by a field or more (comma seperated) (GET)

  • <field_name> (optional) A filter to apply on any field (GET) More options:

    • <field_name>[gt] Greater than
    • <field_name>[ge] Greater or equal than
    • <field_name>[lt] Less than
    • <field_name>[le] Less or equal than
    • <field_name>[begin] A string that begins with
    • <field_name>[end] A string that ends with
    • <field_name>[has] A string includes value
    • <field_name>[in] A number that is in a list

/cm/update_rows

Updates entry

Parameters

  • t The name of the table (GET)
  • id The id of row to update or a comma seperated list od ids, if is not set it will create a new entry. (GET)
  • <field_name> The value of the field for the update or insert action (POST)

/cm/empty_row

Returns a row with the default values

Parameters

  • t The name of the table (GET)

/cm/insert_row

Inserts a new row in the content table

Parameters

  • t The name of the table (GET)
  • <field_name> The value of the field for the update or insert action (POST)

/cm/delete

Deletes a row

Parameters

  • t The name of the table (GET)
  • id The id of row to delete (POST)

/cm/list

Returns the rows as an array of objects in json format. I wont return the total rows Parameters are like /list_rows

/cm/csv

Returns the rows in csv format for download Parameters are like /list_rows

Multiqueries

These actions can be used in a /cm multiquery(https://gilacms.com/blog/43)

  • list
  • list_rows
  • describe

File Manager

File Manager controller gets calls from the front end and responds in json format.

/fm/dir

Returns the contents of a directory

Parameters

  • path The relative path (GET/POST)

Example:

curl 'https://gilacms.com/fm/dir/?t=assets'

Result:

[
  {
    "name": image.jpg,
    "size": 145152,
    "mtime": 2019-02-01 11:01:01,
    "mode": 33206,
    "ext": "jpg"
  },
  .....
]

/fm/save

Saves contents in a file

Parameters

  • path The destination file (GET/POST)
  • contents The data to save (POST)

/fm/newfolder

Creates a new folder

Parameters

  • path The destination folder (GET/POST)

/fm/newfile

Creates a new empty file

Parameters

  • path The destination file (GET/POST)

/fm/move

Renames a folder or a file

Parameters

  • path The source relative path (GET/POST)
  • newpath The destination relative path (POST)

/fm/delete

Deletes a folder or a file

Parameters

  • newpath The relative path (GET/POST)

Indices and tables