Install the App?
ZnetDK PHP API
Server-side Application PHP Methods
SUMMARY
The ZnetDK PHP API simplifies the development on the web server side of:
- the views implemented to display data,
- the navigation menu items and icons,
- the controller actions generally called in AJAX by the views of the application,
- the validation of data transmitted by the view
- and the access to the MySQL database in read or write.
Its source code is defined through PHP classes located in the INSTALL_DIR/engine/core/
folder.
Application views
Application views are PHP scripts that are developed to display data and input forms dedicated to the end user.
They are written in pure HTML and include if necessary, PHP and JavaScript code.
A view is usually displayed when you click an item of the Navigation menu.
Once a view is displayed, it remains in the DOM (Document Object Model) of the page, even when another one is displayed as a replacement.
This means that the view is not reloaded when it is displayed again later.
To force the content of the view to refresh each time it is displayed again, simply add the zdk-viewreload
CSS class to any HTML element in the view.
The PHP script of a view, for example myview.php
, is installed into the INSTALL_DIR/applications/default/app/view/
folder.
<h3>My view</h3>
<p class="zdk-viewreload">The name of the application is <?php echo LC_HEAD_TITLE; ?></p>
<p>The current time is <span id="current-time"></span>
<script>
var currentTime = new Date();
$('#current-time').text(currentdate.getHours()
+ ':' + currentdate.getMinutes());
</script>
Navigation menu
The basics
Here is below the definition of the Starter App navigation menu.
The Starter App's menu.php
script
<?php
/**
* ZnetDK, Starter Web Application for rapid & easy development
* See official website http://www.znetdk.fr
* ------------------------------------------------------------
* Custom navigation menu of the application
* YOU CAN FREELY CUSTOMIZE THE CONTENT OF THIS FILE
*/
namespace app;
class Menu implements \iMenu {
static public function initAppMenuItems() {
\MenuManager::addMenuItem(NULL, 'home', 'Home', 'fa-home');
\MenuManager::addMenuItem(NULL, '_authorizations', LC_MENU_AUTHORIZATION, 'fa-unlock-alt');
\MenuManager::addMenuItem('_authorizations', 'z4musers', LC_MENU_AUTHORIZ_USERS, 'fa-user');
\MenuManager::addMenuItem('_authorizations', 'z4mprofiles', LC_MENU_AUTHORIZ_PROFILES, 'fa-key');
}
}
The first call to \MenuManager::addMenuItem()
adds the Home menu item in first position. This is a one level menu item so the Home
label is both displayed on the main vertical menu and the secondary horizontal menu.
The three next calls to \MenuManager::addMenuItem()
add the Authorizations menu item on the main vertical menu. This is a two levels menu item with two subitems named Users and Profiles displayed on the secondary horizontal menu.
Class \MenuManager
Method addMenuItem()
<?php
// The 'my_view.php' view is displayed on clicking on the "My view" menu item.
// The Font Awesome 4 'fa-book' icon is displayed for this menu item.
\MenuManager::addMenuItem(NULL, 'my_view', 'My view', 'fa-book');
Application controllers
\AppController
|
\Request
|
\Response
Here is an example below of the mycontroller.php
PHP script implementing the MyController
class having a myaction
action.
<?php
namespace app\controller;
class MyController extends \AppController {
static protected function action_myaction() {
$request = new \Request();
$postValue = $request->my_param;
$response = new \Response();
$response->my_response = $postValue;
return $response;
}
}
?>
This controller action reads the value of the my_param
POST parameter and returns a JSON object with a property named my_response
and a value matching the my_param
parameter value.
You can notice in this example that the namespace
is set to app\controller
. It matches the folder in which the mycontroller.php
script file must be located, i.e. in the INSTALL_DIR/applications/default/app/controller/
folder if the running application is the Starter Application (default
subfolder).
Class \AppController
doAction()
,
setAllowedActions()
,
setRequiredProfileForAction()
,
setForbiddenProfileForAction()
,
setRequiredMenuItemForAction()
,
isActionAllowed()
Any application controller class must derive from the abstract
\AppController
class.
Method doAction()
<?php
$response = \app\controller\MyCtrl::doAction('getall');
Method setAllowedActions()
<?php
class MyController extends \AppController {
static protected function setAllowedActions() {
// User must not have the 'My Profile' profile to be allowed to execute the 'myaction' action.
self::setForbiddenProfileForAction('myaction', 'My Profile');
// The action named 'myaction' is allowed if user has access to the view named 'my_view'.
self::setRequiredMenuItemForAction('myaction', 'my_view');
}
static protected function action_myaction() {
$response = new \Response();
$response->success = TRUE;
return $response;
}
}
Method setRequiredProfileForAction()
<?php
class MyController extends \AppController {
static protected function setAllowedActions() {
// User must have the 'My Profile' profile to be allowed to execute the 'myaction' action.
// In addition, the 'my_view' menu item must be selected in the 'My Profile' user profile.
self::setRequiredProfileForAction('myaction', 'My Profile', 'my_view');
}
static protected function action_myaction() {
$response = new \Response();
$response->success = TRUE;
return $response;
}
}
Method setForbiddenProfileForAction()
<?php
class MyController extends \AppController {
static protected function setAllowedActions() {
// User must NOT have the 'My Profile' profile with the 'my_view' menu item selected, to be allowed to execute the 'myaction' action.
self::setForbiddenProfileForAction('myaction', 'My Profile', 'my_view');
}
static protected function action_myaction() {
$response = new \Response();
$response->success = TRUE;
return $response;
}
}
Method setRequiredMenuItemForAction()
<?php
class MyController extends \AppController {
static protected function setAllowedActions() {
// The action named 'myaction' is allowed if user has access to the view named 'my_view'.
self::setRequiredMenuItemForAction('myaction', 'my_view');
}
static protected function action_myaction() {
$response = new \Response();
$response->success = TRUE;
return $response;
}
}
Method isActionAllowed()
<?php
class MyController extends \AppController {
static public function isActionAllowed($action) {
// Checking first according the standard process
$status = parent::isActionAllowed($action);
if ($status === FALSE) {
return FALSE; // User not allowed to execute action
}
// Extra custom conditions
$loginName = \UserSession::getLoginName();
if ($action === 'myaction' && $loginName === 'john_doe') {
// Action named 'myaction' is not allowed for user named 'john_doe'
return FALSE;
}
return TRUE;
}
static protected function action_myaction() {
$response = new \Response();
$response->success = TRUE;
return $response;
}
}
Class \Request
The class \Request
when instantiated in a controller action, is used to read the values of the POST parameters sent through an AJAX request from an app view.
Property $[postParameterName]
<?php
namespace app\controller;
class MyController extends \AppController {
static protected function action_myaction() {
$request = new \Request();
/* POST parameter to read is named "address" */
$requestedAddress = $request->address;
/* ... the rest of the source code ... */
}
}
Method getValuesAsMap()
<?php
namespace app\controller;
class MyController extends \AppController {
static protected function action_myaction() {
$request = new \Request();
$postValues = $request->getValuesAsMap('lastname','firstname');
// For example, the returned associative array is ['lastname' => 'DOE','firstname' => 'John']
/* ... the rest of the source code ... */
}
}
Class \Response
A controller action always returns an object of type \Response
in response to the original HTTP request.
The returned object takes one of the following formats, depending on the case:
- HTML if a view is to return by calling the
\Response::setView()
method. - File if a file to download is to return by calling the
\Response::setFileToDownload()
method. - PDF if a PDF document (FPDF is required) is to return by calling the
\Response::setPrinting()
method. - CSV if a CSV file is to return by calling the
\Response::setDataForCsv()
method. - JSON if structured data is to return in JSON format by defining custom properties to the
\Request
object or by calling one of the following methods:\Response::setResponse()
,\Response::setSuccessMessage()
,\Response::setWarningMessage()
,\Response::setFailedMessage()
or\Response::setCriticalMessage()
. - Custom if a custom content is to return (XML, text, ...) by calling the
\Response::setCustomContent()
method.
\Response
PROPERTIES
Property $[propertyName]
<?php
namespace app\controller;
class MyController extends \AppController {
static protected function action_myaction() {
$response = new \Response();
$response->myFirstValue = 'value 1';
$response->myOtherValue = 124.59;
return $response;
}
}
\Response
METHODS
setResponse()
,
setFileToDownload()
,
setView()
,
setDataForCsv()
,
setPrinting()
,
setCustomContent()
,
setSuccessMessage()
,
setWarningMessage()
,
setFailedMessage()
,
setCriticalMessage()
Method setResponse()
<?php
namespace app\controller;
class MyController extends \AppController {
static protected function action_myaction() {
$response = new \Response();
$response->setResponse([
'status' => 'KO',
'message' => 'An error occurred!'
]);
return $response;
}
}
Method setFileToDownload()
<?php
namespace app\controller;
class MyController extends \AppController {
static protected function action_download() {
$response = new \Response();
$fileToDownload = CFG_DOCUMENTS_DIR . DIRECTORY_SEPARATOR . 'mydoc.pdf';
$response->setFileToDownload($fileToDownload, TRUE);
return $response;
}
}
Method setView()
<?php
namespace app\controller;
class MyController extends \AppController {
static protected function action_myaction() {
$response = new \Response();
/* Returns the view "applications\default\app\view\customers.php" */
$response->setView('customers','view');
return $response;
}
}
Method setDataForCsv()
<?php
namespace app\controller;
class MyController extends \AppController {
static protected function action_download() {
$response = new \Response();
$header = array('Column 1','Column 2','Column 3');
$data = array(
array('Row 1 col. 1','Row 1 col. 2','Row 1 col. 3'),
array('Row 2 col. 1','Row 2 col. 2','Row 2 col. 3'),
array('Row 3 col. 1','Row 3 col. 2','Row 3 col. 3'),
);
$response->setDataForCsv($data, 'myfile.csv', $header);
return $response;
}
}
Method setPrinting()
<?php
namespace app\controller;
class MyController extends \AppController {
static protected function action_download() {
$response = new \Response();
$pdf = new \FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'PDF document generated from ZnetDK!');
$response->setPrinting($pdf, 'mydoc.pdf');
return $response;
}
}
Method setCustomContent()
<?php
namespace app\controller;
class MyController extends \AppController {
static protected function action_run() {
$response = new \Response();
$response->setCustomContent('OK');
return $response;
}
}
Method setSuccessMessage()
<?php
namespace app\controller;
class MyController extends \AppController {
static protected function action_myaction() {
$response = new \Response();
$response->setSuccessMessage('New item','Item added successfully.');
return $response;
}
}
Method setWarningMessage()
<?php
namespace app\controller;
class MyController extends \AppController {
static protected function action_myaction() {
$response = new \Response();
$response->setWarningMessage('New item','Item added even if it was incomplete.');
return $response;
}
}
Method setFailedMessage()
<?php
namespace app\controller;
class MyController extends \AppController {
static protected function action_myaction() {
$response = new \Response();
$response->setFailedMessage('New item','Item added even if it was incomplete.');
return $response;
}
}
Method setCriticalMessage()
<?php
namespace app\controller;
class MyController extends \AppController {
static protected function action_myaction() {
$response = new \Response();
$response->setCriticalMessage('Unable to store the item data', $ex);
return $response;
}
}
Database Access
\DAO
|
\SimpleDAO
|
\Database
Access to the data stored into the database of the application is simplified thanks to the ZnetDK PHP classes \DAO
and \SimpleDAO
, both based on the PHP PDO class.
Class \DAO
The ZnetDK class \DAO
allows to achieve complex database operations, in particular when data is to be selected from multiple SQL tables.
See below an example of the custom app\model\TaskDAO
class derived from the ZnetDK \DAO
class.
<?php
namespace app\model;
class TaskDAO extends \DAO {
protected function initDaoProperties() {
$this->table = "zdkapp_tasks";
$this->query = "SELECT tas.*, tas.id AS task_id, usr.user_name,
IF(tas.status_id < 3 AND tas.end_date < CURDATE(), 1, 0) AS late,
IF(tas.status_id < 3, 0, 1) AS display_priority
FROM tasks AS tas
INNER JOIN zdk_users AS usr ON usr.user_id = tas.user_id";
$this->dateColumns = array('begin_date', 'end_date', 'creation_date');
}
public function setNotFinishedAsFilter() {
$this->filterClause = 'WHERE tas.status_id != ?';
$this->setFilterCriteria(3);
}
}
?>
\DAO
PROPERTIES
$table
,
$query
,
$filterClause
,
$groupByClause
,
$idColumnName
,
$dateColumns
,
$moneyColumns
,
$amountColumns
,
$tableAlias
Property $table
<?php
$this->table = 'my_table';
Property $query
<?php
$this->query = "SELECT col1, col2 FROM my_table";
Property $filterClause
<?php
$this->filterClause = "WHERE col1 = ?";
Property $groupByClause
<?php
$this->groupByClause = "GROUP BY col1 HAVING COUNT(col1) > 5";
Property $IdColumnName
<?php
$this->IdColumnName = 'my_row_id';
Property $dateColumns
<?php
$this->dateColumns = ['creation_date', 'update_date'];
Property $moneyColumns
<?php
$this->moneyColumns = ['subtotal', 'total'];
Property $amountColumns
<?php
$this->amountColumns = ['subtotal', 'total'];
Property $tableAlias
<?php
$this->query = "SELECT col1, col2 FROM my_table AS tab";
$this->tableAlias = 'tab';
\DAO
METHODS
initDaoProperties()
,
addCondition()
,
setFilterCriteria()
,
setSortCriteria()
,
setLimit()
,
setSelectedColumns()
,
setForUpdate()
,
setAmountColumns()
,
setMoneyColumns()
,
setDateColumns()
,
getResult()
,
getById()
,
getCount()
,
store()
,
remove()
,
beginTransaction()
,
commit()
,
rollback()
Method initDaoProperties()
<?php
namespace app\model;
class Customers extends \DAO
{
protected function initDaoProperties() {
$this->query = "SELECT id, customer_name FROM customers";
$this->filterClause = "WHERE customer_name LIKE ?";
}
}
Method addCondition()
<?php
namespace app\model;
class Customers extends \DAO
{
protected function initDaoProperties() {
$this->table = "customers";
}
public function setCountryAsFilter($countryCode) {
$this->addCondition("country = ?", [$countryCode]);
}
public function setContactAsFilter($firstName, $lastName) {
$this->addCondition("first_name = ? AND last_name = ?", [$firstName, $lastName]);
}
}
Method setFilterCriteria()
<?php
$customers = [];
$myDao = new \app\model\Customers();
$myDao->setFilterCriteria('spain','france','uk');
while($row = $myDao->getResult()) {
$customers[] = $row;
}
Method setSortCriteria()
<?php
$customers = [];
$myDao = new \app\model\Customers();
$myDao->setSortCriteria('name DESC, city ASC');
while($row = $myDao->getResult()) {
$customers[] = $row;
}
Method setLimit()
<?php
$customers = [];
$myDao = new \app\model\Customers();
$myDao->setLimit(20,40);
while($row = $myDao->getResult()) {
$customers[] = $row;
}
Method setSelectedColumns()
<?php
$customers = [];
$myDao = new \app\model\Customers();
$myDao->setSelectedColumns(array('id','name'));
while($row = $myDao->getResult()) {
$customers[] = $row;
}
Method getResult()
<?php
$customers = [];
$myDao = new \app\model\Customers();
while($row = $myDao->getResult()) {
$customers[] = $row;
}
Method getById()
<?php
$myDao = new \app\model\Customers();
$rowData = $myDao->getById(43);
$customerName = $rowData['customer_name'];
Method getCount()
<?php
$myDao = new \app\model\Customers();
$rowCount = $myDao->getCount();
Method store()
<?php
$row = array('id'=>18,'name'=>'MARTIN','city'=>'Paris');
$myDao = new \app\model\Customers();
$result = $myDao->store($row);
Method remove()
<?php
$customerId = 52;
$myDao = new \app\model\Customers();
$rowCount = $myDao->remove($customerId);
Method beginTransaction()
<?php
$myDao = new \app\model\Customers();
$myDao->beginTransaction();
Method setForUpdate()
<?php
$myDao = new \app\model\Customers();
$myDao->beginTransaction();
$myDao->setForUpdate(TRUE);
$row = $myDao->getById(18);
$row['is_visible'] = 'Y';
$myDao->store($row, FALSE);
$myDao->commit();
Method setAmountColumns()
<?php
$myDao = new \app\model\Customers();
$myDao->setAmountColumns('balance', 'expenses');
$customer = $myDao->getById(18);
$balanceAmount = $customer['balance_amount'];
$expensesAmount = $customer['expenses_amount'];
Method setMoneyColumns()
<?php
$myDao = new \app\model\Customers();
$myDao->setMoneyColumns('balance', 'expenses');
$customer = $myDao->getById(18);
$balanceAsMoney = $customer['balance_money'];
$expensesAsMoney = $customer['expenses_money'];
Method setDateColumns()
<?php
$myDao = new \app\model\Customers();
$myDao->setMoneyColumns('creation_date', 'birthday');
$customer = $myDao->getById(18);
$localeCreationDate = $customer['creation_date_locale'];
$localeBirthday = $customer['birthday_locale'];
Method commit()
<?php
$row = array('id'=>18,'name'=>'MARTIN','city'=>'Paris');
$myDao = new \app\model\Customers();
$myDao->beginTransaction();
$result = $myDao->store($row, FALSE);
$myDao->commit();
Method rollback()
<?php
$row = array('id'=>18,'name'=>'MARTIN','city'=>'Paris');
$myDao = new \app\model\Customer();
$myDao->beginTransaction();
$result = $myDao->store($row);
$myDao->rollback();
Class \SimpleDAO
_construct()
,
getRows()
,
getRowsForCondition()
,
getSuggestions()
,
setKeywordSearchColumn()
The ZnetDK class \SimpleDAO
offers an easy and quick way to operate on a single SQL table or view.
Here is an example of usage of the \SimpleDAO
class.
<?php
$contactsDao = new \SimpleDAO('contacts');
$rowsFound = array();
$rowCount = $contactsDao->getRows($rowsFound, 'name');
?>
Constructor _construct()
<?php
$dao = new \SimpleDAO('customers');
Method getRows()
<?php
/* POST parameters: first='0', count='10', keyword='paul' */
$dao = new \SimpleDAO('customers');
/* keywords searched into the table's column 'name' */
$dao->setKeywordSearchColumn('name');
$customers = array();
/* Rows found are sorted by 'name' (sorting POST parameters not set) */
$total = $dao->getRows($customers, 'name ASC');
Method getRowsForCondition()
<?php
$dao = new \SimpleDAO('customers');
$condition = 'name LIKE ?';
$value = 'jean';
$result = $dao->getRowsForCondition($condition, "%{$value}%");
Method getSuggestions()
<?php
/* POST parameter: query='jean' */
$dao = new \SimpleDAO('customers');
$dao->setKeywordSearchColumn('name');
$suggestions = $dao->getSuggestions(20);
Method setKeywordSearchColumn()
<?php
$dao = new \SimpleDAO('customers');
$dao->setKeywordSearchColumn('name');
Class \Database
getCustomDbConnection()
,
beginTransaction()
,
inTransaction()
,
commit()
,
rollback()
Method getCustomDbConnection()
<?php
$dbConnection = \Database::getCustomDbConnection('localhost', 'my-dbname', 'db-user', 'mypassword', 8083);
Method beginTransaction()
<?php
\Database::beginTransaction();
// Data storage...
\Database::commit();
Method inTransaction()
<?php
if (!\Database::inTransaction()) {
\Database::beginTransaction();
}
// Data storage...
\Database::commit();
Method commit()
<?php
\Database::beginTransaction();
// Data storage...
\Database::commit();
Method rollback()
<?php
\Database::beginTransaction();
// Data storage...
\Database::rollback();
Data Validation
Form data sent to the web server can be verified before storage using a custom PHP class in charge of their validation.
Class \Validator
\Validator
class is abstract and can only be instantiated through a derived class that implements:initVariables()
method to specify the names of the HTTP request data to check,- Optionally, the
initOptionalVariables()
method to indicate the names of the HTTP request data whose values are not mandatory, - Finally, a
check_[dataName]()
control method for each data of the HTTP request to be checked. For example, it will be calledcheck_email()
to check the POST data namedemail
.
The custom derived class is generally stored into the INSTALL_DIR/applications/default/app/validator/
folder.
MyValidator
class derived from the \Validator
class
<?php
namespace app\validator;
class MyValidator extends \Validator {
protected function initVariables() {
return array('user_name','user_email');
}
protected function check_user_name($value) {
// 100 characters maximum
if (strlen($value) > 100) {
$this->setErrorMessage('User name is too long!');
return FALSE;
}
return TRUE;
}
protected function check_user_email($value) {
// Must be a valid email address
if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
$this->setErrorMessage('Email address invalid!');
return FALSE;
}
return TRUE;
}
}
?>
Checking data with a validator object
- In option,
setCheckingMissingValues()
method to specify that empty data (null
) are also checked, validate()
method to check data,getErrorVariable()
method to obtain the name of the first POST data detected in error,getErrorMessage()
method to get the error message returned by thecheck_[dataName]()
method that detected the error,- In option,
getValues()
method to get the values of the POST data that have been checked.
MyValidator
class for data checking
<?php
namespace app\controller;
class MyController extends \AppController {
protected function action_save() {
$request = new \Request();
$response = new \Response();
// Form data validation
$validator = new \app\validator\MyValidator();
$validator->setCheckingMissingValues();
if (!$validator->validate()) {
$response->setFailedMessage(NULL, $validator->getErrorMessage(),
$validator->getErrorVariable());
return $response;
}
// Storage
$request = new \Request();
$row = $validator->getValues();
$row['id'] = $request->id;
$dao = new \SimpleDAO('my_users');
$dao->store($row);
$response->setSuccessMessage('User', 'Stored successfully.');
return $response;
}
}
?>
User Data
\UserSession
|
\User
|
\controller\Users
|
\controller\Security
Class \UserSession
setCustomValue()
,
getCustomValue()
,
removeCustomValue()
,
getUserId()
getLoginName()
,
getLanguage()
,
getUserName()
,
getUserEmail()
,
hasFullMenuAccess()
,
getUserProfiles()
,
hasUserProfile()
,
isAuthenticated()
,
isUITokenValid()
User sessions are managed via the \UserSession
ZnetDK class that is used to get informations about the logged in user and to store custom data.
The session is started automatically and so doesn't need to be started explicitly.
Method setCustomValue()
<?php
\UserSession::setCustomValue('myVarInSession', 18);
?>
Method getCustomValue()
<?php
$myValueInSession = \UserSession::getCustomValue('myVarInSession');
?>
Method removeCustomValue()
<?php
\UserSession::removeCustomValue('myVarInSession');
?>
Method getUserId()
<?php
$userId = \UserSession::getUserId();
?>
Method getLoginName()
<?php
$loginName = \UserSession::getLoginName();
?>
Method getLanguage()
<?php
$userLang = \UserSession::getLanguage();
?>
Method getUserName()
<?php
$userName = \UserSession::getUserName();
?>
Method getUserEmail()
<?php
$userEmail = \UserSession::getUserEmail();
?>
Method hasFullMenuAccess()
<?php
$fullAccess = \UserSession::hasFullMenuAccess();
?>
Method getUserProfiles()
<?php
$userProfiles = \UserSession::getUserProfiles();
?>
Method hasUserProfile()
<?php
$hasProfile = \UserSession::hasUserProfile();
?>
Method isAuthenticated()
<?php
if (!\UserSession::isAuthenticated(TRUE)) {
// User not authenticated!
}
?>
Method isUITokenValid()
<?php
if (!\UserSession::isUITokenValid(TRUE)) {
// Token is invalid!
}
?>
Class \User
__construct()
,
__get()
,
__set()
,
add()
,
addProfile()
disableNotification()
generateLoginName()
generateNewPassword()
getPasswordInClear()
getProfiles()
grantProfiles()
hasProfile()
notify()
,
remove()
,
removeProfile()
,
setCustomDatabaseConnexion()
,
setExpirationDate()
,
update()
,
validate()
The \User
class can be used to manage user accounts programmatically. User accounts are stored in the zdk_users
SQL table.
This class exists in version >=3.3 of ZnetDK.
Method __construct()
<?php
$newUser = new \User();
?>
Method __get()
<?php
$existingUser = new \User(56);
$loginName = $existingUser->login_name;
?>
Method __set()
<?php
$newUser = new \User();
$newUser->login_name = 'john_doe';
?>
Method add()
<?php
$newUser = new \User();
$newUser->login_name = 'john_doe';
$newUser->user_name = 'John DOE';
$newUser->user_email = 'johndoe@myemail.xyz';
$userId = $newUser->add();
?>
Method addProfile()
<?php
$existingUser = new \User(56);
$existingUser->addProfile('Super user');
?>
Method disableNotification()
<?php
$newUser = new \User();
$newUser->disableNotification();
?>
Method generateLoginName()
<?php
$newUser = new \User();
$loginName = $newUser->generateLoginName('John DOE');
?>
Method generateNewPassword()
<?php
$existingUser = new \User(56);
$newPasswordInClear = $existingUser->generateNewPassword();
$existingUser->update(); // Updates new password in database
?>
Method getPasswordInClear()
<?php
$newUser = new \User();
$newUser->login_name = 'john_doe';
$newUser->user_name = 'John DOE';
$newUser->user_email = 'johndoe@myemail.xyz';
$userId = $newUser->add();
$passwordInClear = $newUser->getPasswordInClear();
?>
Method getProfiles()
<?php
$existingUser = new \User(56);
$profileNames = $existingUser->getProfiles();
?>
Method grantProfiles()
<?php
$existingUser = new \User(56);
$existingUser->grantProfiles(['Resource manager', 'Scheduler']);
?>
Method hasProfile()
<?php
$existingUser = new \User(56);
$hasSchedulerProfile = $existingUser->hasProfile('Scheduler');
?>
Method notify()
<?php
$existingUser = new \User(56);
$newPasswordInClear = $existingUser->generateNewPassword();
$existingUser->disableNotification(); // Automatic notification is disabled
\Database::beginTransaction();
$existingUser->update(FALSE); // Updates new password in database
// Other stuff...
\Database::commit();
$existingUser->notify(FALSE);
?>
Method remove()
<?php
$user = new \User(43);
$user->remove();
?>
Method removeProfile()
<?php
$existingUser = new \User(56);
$existingUser->removeProfile('Scheduler');
?>
Method setCustomDatabaseConnexion()
<?php
$dbConnection = \Database::getCustomDbConnection('localhost', 'my-dbname', 'db-user', 'mypassword', 8083);
$newUser = new \User();
$newUser->setCustomDatabaseConnexion($dbConnection);
?>
Method setExpirationDate()
<?php
$newUser = new \User();
$newUser->setExpirationDate();
?>
Method update()
<?php
$user = new \User(43);
$user->user_email = 'johndoe@mynewemail.xyz';
$user->update();
?>
Method validate()
<?php
$newUser = new \User();
$newUser->login_name = 'john_doe';
$newUser->user_name = 'John DOE';
$newUser->user_email = 'johndoe@myemail.xyz';
try {
$newUser->validate(TRUE);
$newUser->add();
} catch(\Exception $ex) {
\General::writeErrorLog(__METHOD__, $ex->getMessage());
}
?>
Class \controller\Users
getUserName()
,
getUserEmail()
,
getUserTheme()
,
hasProfile()
,
hasMenuItem()
,
notify()
,
onRemove()
The \controller\Users
class is used to get informations stored in database about the logged in user.
A custom \controller\Users
class can also be declared within the application or within a module to enhance standard features.
Method getUserName()
<?php
$userName = \controller\Users::getUserName();
?>
Method getUserEmail()
<?php
$userEmail = \controller\Users::getUserEmail();
?>
Method getUserTheme()
<?php
namespace app\controller; // Namespace for the application
// namespace mymodule\mod\controller; // Namespace for the module named 'mymodule'
class Users extends \AppController {
static public function getUserTheme() {
/* Method called to get the logged in user's preferred theme */
$preferredTheme = self::getPreferredThemeForUser(\UserSession::getUserId());
if ($preferredTheme === 'dark') {
/* Dark theme stylesheet relative path is returned */
return 'applications/default/public/css/theme-dark.css';
} else {
return FALSE; // Default theme is applied
}
}
static private function getPreferredThemeForUser($userID) {
// Your code...
}
}
?>
Method hasProfile()
<?php
if (\controller\Users::hasProfile('Manager')) {
// User is manager
}
?>
Method hasMenuItem()
<?php
if (\controller\Users::hasMenuItem('myview')) {
// User has access to "myview.php"
}
?>
Method notify()
<?php
namespace app\controller; // Namespace for the application
// namespace mymodule\mod\controller; // Namespace for the module named 'mymodule'
class Users extends \AppController {
static public function notify($isNewUser, $passwordInClear, $userRow) {
if ($isNewUser) { // New user
/* Method called to send the credentials to a newly created user */
self::sendCredentialsToNewUser($passwordInClear, $userRow);
} else { // Existing user
/* Method called to send the new password to an existing user */
self::sendNewPasswordToExistingUser($passwordInClear, $userRow);
}
}
static private function sendCredentialsToNewUser($passwordInClear, $userRow) {
// Your code...
}
static private function sendNewPasswordToExistingUser($passwordInClear, $userRow) {
// Your code...
}
}
?>
Method onRemove()
<?php
namespace app\controller; // Namespace for the application
// namespace mymodule\mod\controller; // Namespace for the module named 'mymodule'
class Users extends \AppController {
static public function onRemove($userID) {
$dao = new \SimpleDAO('my_custom_table');
$rows = $dao->getRowsForCondition('user_id = ?', $userID);
foreach ($rows as $row) {
$dao->remove($row['id'], FALSE);
}
}
}
?>
Class \controller\Security
A custom \controller\Security
class can be declared within the application or within a module to enhance standard features.
Method loginResult()
<?php
namespace app\controller; // Namespace for the application
// namespace mymodule\mod\controller; // Namespace for the module named 'mymodule'
class Security extends \AppController {
static public function loginResult($loginInfos) {
if ($loginInfos['status'] === FALSE) {
// User failed to log in...
\General::writeErrorLog(__METHOD__, 'User ' . $loginInfos['login_name']
. ' (IP: ' . $loginInfos['ip_address'] . ')'
. ' failed to login on ' . $loginInfos['login_date']
. ' with error: ' . $loginInfos['message']
);
}
}
}
?>
Miscellaneous Tools
The ZnetDK framework provides useful utility classes in PHP through the \General
class.
Data conversion is ensured through the \Convert
class.
Class \General
callRemoteAction()
,
getCurrentW3CDate()
,
getFilledMessage()
,
getURIforDownload()
,
isW3cDateValid()
,
isPictureTooBig()
,
reducePictureSize()
,
writeErrorLog()
Method callRemoteAction()
<?php
print_r(json_decode(\General::callRemoteAction('https://usr:pwd@mydomain.com/', 'POST',
'mycontroller', 'myaction', ['my_param1' => 'val1', 'my_param2' => 'val2'])));
?>
Method getCurrentW3CDate()
<?php
echo \General::getCurrentW3CDate();
?>
Method getFilledMessage()
<?php
echo \General::getFilledMessage('Your car is %1 and %2.','blue','yellow');
/* Display: Your car is blue and yellow. */
?>
Method getURIforDownload()
<?php
$downloadUrl = \General::getURIforDownload('mycontroller', 'doc_id=98&cache=true');
/* The URI returned is "/znetdk/?control=mycontroller&action=download&doc_id=98&cache=true" */
echo '<a href="' . $downloadUrl . '">File to download</a>';
Method isW3cDateValid()
<?php
$isValid = \General::isW3cDateValid('2022-12-29'); // Returns TRUE
$isNotValid = \General::isW3cDateValid('2022-02-30'); // Returns FALSE
Method isPictureTooBig()
<?php
if (!\General::isPictureTooBig('mypicture.jpg')) {
$resizedPicture = \General::reducePictureSize('mypicture.jpg', 260, 220);
}
?>
Method reducePictureSize()
<?php
$resizedPicture = \General::reducePictureSize('mypicture.jpg', 260, 220);
?>
Method writeErrorLog()
<?php
\General::writeErrorLog('MYAPP', 'Error detected...');
?>
Class \Convert
base64UrlToBinary()
,
binaryToBase64Url()
,
toISO88591()
,
toMoney()
,
W3CtoLocaleDate()
,
Method base64UrlToBinary()
<?php
$binaryValue = \Convert::base64UrlToBinary($base64UrlValue);
?>
Method binaryToBase64Url()
<?php
$base64UrlValue = \Convert::binaryToBase64Url($binVal);
?>
Method toISO88591()
<?php
$myIso88591String = \Convert::toISO88591($myUtf8String);
?>
Method toMoney()
<?php
$myMoney = \Convert::toMoney(3451.7399);
?>
Method W3CtoLocaleDate()
<?php
$myDate = \Convert::W3CtoLocaleDate('2013-04-22');
?>
ZnetDK constants
The following PHP constants can be used in the views and in the controllers to get absolute or relative path of specific ZnetDK folders.
Path constants
ZNETDK_APP_NAME
,
ZNETDK_APP_ROOT
,
ZNETDK_APP_URI
,
ZNETDK_ROOT
,
ZNETDK_ROOT_URI
,
ZNETDK_CORE_ROOT
,
ZNETDK_MOD_ROOT
,
CFG_ZNETDK_IMG_DIR
Constant ZNETDK_APP_NAME
Name of the subfolder containing the source code and the documents of the running application.
<?php
/* If ZnetDK is installed into the /home/hosting999/www/znetdk/ folder
and if the Starter Application is currently running... */
echo ZNETDK_APP_NAME; // Display of default
?>
Constant ZNETDK_APP_ROOT
Absolute path of the folder containing the files of the running application.
<?php
/* If ZnetDK is installed into the /home/hosting999/www/znetdk/ folder
and if the Starter Application is currently running... */
echo ZNETDK_APP_ROOT; // Display of /home/hosting999/www/znetdk/applications/default
?>
Constant ZNETDK_APP_URI
Relative file path of the directory containing the web resources of the application.
<?php
/* If ZnetDK is installed into the /home/hosting999/www/znetdk/ folder
and if the Starter Application is currently running... */
echo ZNETDK_APP_URI; // Display of /znetdk/applications/default/public/
?>
Constant ZNETDK_ROOT
Abdolute file path of the root directory of ZnetDK (installation folder).
<?php
/* If ZnetDK is installed into the /home/hosting999/www/znetdk/ folder
and if the Starter Application is currently running... */
echo ZNETDK_ROOT; // Display of /home/hosting999/www/znetdk/
?>
Constant ZNETDK_ROOT_URI
Relative path of the root directory of ZnetDK (installation folder).
<?php
/* If ZnetDK is installed into the /home/hosting999/www/znetdk/ folder
and if the Starter Application is currently running... */
echo ZNETDK_ROOT_URI; // Display of /znetdk/
?>
Constant ZNETDK_CORE_ROOT
Abdolute file path of the core directory of ZnetDK.
<?php
/* If ZnetDK is installed into the /home/hosting999/www/znetdk/ folder
and if the Starter Application is currently running... */
echo ZNETDK_CORE_ROOT; // Display of /home/hosting999/www/znetdk/engine/core
?>
Constant ZNETDK_MOD_ROOT
Abdolute file path of the modules directory of ZnetDK.
<?php
/* If ZnetDK is installed into the /home/hosting999/www/znetdk/ folder
and if the Starter Application is currently running... */
echo ZNETDK_MOD_ROOT; // Display of /home/hosting999/www/znetdk/engine/modules
?>
Constant CFG_ZNETDK_IMG_DIR
Relative file path of the images directory of ZnetDK.
<?php
echo CFG_ZNETDK_IMG_DIR; // Display of engine/public/images
?>