Initial checkin v13.0

This commit is contained in:
Thilina Hasantha
2015-10-10 20:18:50 +05:30
parent 5fdd19b2c5
commit eb3439b29d
1396 changed files with 318492 additions and 0 deletions

View File

@@ -0,0 +1,35 @@
<?php
/*
This file is part of Ice Framework.
Ice Framework is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Ice Framework is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Ice Framework. If not, see <http://www.gnu.org/licenses/>.
------------------------------------------------------------------
Original work Copyright (c) 2012 [Gamonoid Media Pvt. Ltd]
Developer: Thilina Hasantha (thilina.hasantha[at]gmail.com / facebook.com/thilinah)
*/
abstract class AbstractInitialize{
var $baseService = null;
public function setBaseService($baseService){
$this->baseService = $baseService;
}
public function getCurrentProfileId(){
return $this->baseService->getCurrentProfileId();
}
public abstract function init();
}

View File

@@ -0,0 +1,115 @@
<?php
/**
*The base class for module manager classes. ModuleManager classes which extend this class provide core backend functionality
*to each module such as defining models, error handliing and other configuration details
*@class AbstractModuleManager
*/
abstract class AbstractModuleManager{
private $fileFieldMappings = array();
private $userClasses = array();
private $errorMappings = array();
private $modelClasses = array();
/**
* Override this method in module manager class to define user classes.
* A user class is a class that is mapped to a table having a field named profile. The profile field is mapped to the id of a Profile element.
* When a user is saving this type of an object in db, profile field will be set to the id of the Profile of currently logged in or switched user.
* When a user is retriving this type of records, only the records having profile field set to currently logged in users profile id will be released.
* @method initializeUserClasses
* @example
public function initializeUserClasses(){
$this->addUserClass("EmployeeDocument");
}
*
*/
public abstract function initializeUserClasses();
/**
* Override this method in module manager class to define file field mappings. If you have a table field that stores a name of a file which need to be
* deleted from the disk when the record is deleted a file field mapping should be added.
* @method initializeFieldMappings
* @example
public function initializeFieldMappings(){
$this->addFileFieldMapping('EmployeeDocument', 'attachment', 'name');
}
*/
public abstract function initializeFieldMappings();
/**
* Override this method in module manager class to define DB error mappings. Some actions to your model classes trigger database errors.
* These errors need to be translated to user friendly texts using DB error mappings
* @method initializeDatabaseErrorMappings
* @example
public function initializeDatabaseErrorMappings(){
$this->addDatabaseErrorMapping('CONSTRAINT `Fk_User_Employee` FOREIGN KEY',"Can not delete Employee, please delete the User for this employee first.");
$this->addDatabaseErrorMapping("Duplicate entry|for key 'employee'","A duplicate entry found");
}
*/
public abstract function initializeDatabaseErrorMappings();
/**
* Override this method in module manager class to add model classes to this module. All the model classes defind for the module should be added here
* @method setupModuleClassDefinitions
* @example
public function setupModuleClassDefinitions(){
$this->addModelClass('Employee');
$this->addModelClass('EmploymentStatus');
}
*/
public abstract function setupModuleClassDefinitions();
public function setupRestEndPoints(){
}
public function setupFileFieldMappings(&$fileFields){
foreach ($this->fileFieldMappings as $mapping){
if(empty($fileFields[$mapping[0]])){
$fileFields[$mapping[0]] = array();
}
$fileFields[$mapping[0]][$mapping[1]] = $mapping[2];
}
}
public function setupUserClasses(&$userTables){
foreach($this->userClasses as $className){
if(!in_array($className, $userTables)){
$userTables[] = $className;
}
}
}
public function setupErrorMappings(&$mysqlErrors){
foreach($this->errorMappings as $name=>$desc){
$mysqlErrors[$name] = $desc;
}
}
public function getModelClasses(){
return $this->modelClasses;
}
protected function addFileFieldMapping($className, $fieldName, $fileTableFieldName){
$this->fileFieldMappings[] = array($className, $fieldName, $fileTableFieldName);
}
protected function addUserClass($className){
$this->userClasses[] = $className;
}
protected function addDatabaseErrorMapping($error, $description){
$this->errorMappings[$error] = $description;
}
protected function addModelClass($className){
$this->modelClasses[] = $className;
}
}

1119
src/classes/BaseService.php Normal file

File diff suppressed because it is too large Load Diff

33
src/classes/CronUtils.php Normal file
View File

@@ -0,0 +1,33 @@
<?php
class CronUtils{
var $clientBasePath;
var $cronFile;
private static $me = null;
private function __construct($clientBasePath, $cronFile){
$this->clientBasePath = $clientBasePath;
$this->cronFile = $cronFile;
}
public static function getInstance($clientBasePath, $cronFile){
if(empty(self::$me)){
self::$me = new CronUtils($clientBasePath, $cronFile);
}
return self::$me;
}
public function run(){
$ams = scandir($this->clientBasePath);
foreach($ams as $am){
if(is_dir($this->clientBasePath.$am) && $am != '.' && $am != '..'){
$command = "php ".$this->cronFile." -c".$this->clientBasePath.$am;
echo "Run:".$command."\r\n";
passthru($command, $res);
echo "Result :".$res."\r\n";
}
}
}
}

260
src/classes/EmailSender.php Normal file
View File

@@ -0,0 +1,260 @@
<?php
/*
* This file is part of Ice Framework.
* Copyright Thilina Hasantha (thilina.hasantha[at]gmail.com | http://facebook.com/thilinah | https://twitter.com/thilina84)
* Licensed under MIT (https://github.com/thilinah/ice-framework/master/LICENSE)
*/
use Aws\Ses\SesClient;
abstract class EmailSender{
var $settings = null;
public function __construct($settings){
$this->settings = $settings;
}
public function sendEmail($subject, $toEmail, $template, $params, $ccList = array(), $bccList = array()){
$body = $template;
foreach($params as $k=>$v){
$body = str_replace("#_".$k."_#", $v, $body);
}
$fromEmail = APP_NAME." <".$this->settings->getSetting("Email: Email From").">";
//Convert to an html email
$emailBody = file_get_contents(APP_BASE_PATH.'/templates/email/emailBody.html');
$emailBody = str_replace("#_emailBody_#", $body, $emailBody);
$emailBody = str_replace("#_logourl_#",
BASE_URL."images/logo.png"
, $emailBody);
$user = new User();
$user->load("username = ?",array('admin'));
if(empty($user->id)){
$users = $user->Find("user_level = ?",array('Admin'));
$user = $users[0];
}
$emailBody = str_replace("#_adminEmail_#", $user->email, $emailBody);
$emailBody = str_replace("#_url_#", CLIENT_BASE_URL, $emailBody);
foreach($params as $k=>$v){
$emailBody = str_replace("#_".$k."_#", $v, $emailBody);
}
$this->sendMail($subject, $emailBody, $toEmail, $fromEmail, $user->email, $ccList, $bccList);
}
public function sendEmailWithoutWrap($subject, $toEmail, $template, $params, $ccList = array(), $bccList = array()){
$body = $template;
foreach($params as $k=>$v){
$body = str_replace("#_".$k."_#", $v, $body);
}
$fromEmail = APP_NAME." <".$this->settings->getSetting("Email: Email From").">";
//Convert to an html email
$emailBody = $body;
$emailBody = str_replace("#_logourl_#",
BASE_URL."images/logo.png"
, $emailBody);
$user = new User();
$user->load("username = ?",array('admin'));
if(empty($user->id)){
$users = $user->Find("user_level = ?",array('Admin'));
$user = $users[0];
}
$emailBody = str_replace("#_adminEmail_#", $user->email, $emailBody);
$emailBody = str_replace("#_url_#", CLIENT_BASE_URL, $emailBody);
foreach($params as $k=>$v){
$emailBody = str_replace("#_".$k."_#", $v, $emailBody);
}
$this->sendMail($subject, $emailBody, $toEmail, $fromEmail, $user->email, $ccList, $bccList);
}
protected abstract function sendMail($subject, $body, $toEmail, $fromEmail, $replyToEmail = null, $ccList = array(), $bccList = array());
public function sendResetPasswordEmail($emailOrUserId){
$user = new User();
$user->Load("email = ?",array($emailOrUserId));
if(empty($user->id)){
$user = new User();
$user->Load("username = ?",array($emailOrUserId));
if(empty($user->id)){
return false;
}
}
$params = array();
//$params['user'] = $user->first_name." ".$user->last_name;
$params['url'] = CLIENT_BASE_URL;
$newPassHash = array();
$newPassHash["CLIENT_NAME"] = CLIENT_NAME;
$newPassHash["oldpass"] = $user->password;
$newPassHash["email"] = $user->email;
$newPassHash["time"] = time();
$json = json_encode($newPassHash);
$encJson = AesCtr::encrypt($json, $user->password, 256);
$encJson = urlencode($user->id."-".$encJson);
$params['passurl'] = CLIENT_BASE_URL."service.php?a=rsp&key=".$encJson;
$emailBody = file_get_contents(APP_BASE_PATH.'/templates/email/passwordReset.html');
$this->sendEmail("[".APP_NAME."] Password Change Request", $user->email, $emailBody, $params);
return true;
}
}
class SNSEmailSender extends EmailSender{
var $ses = null;
public function __construct($settings){
parent::__construct($settings);
$arr = array(
'key' => $this->settings->getSetting('Email: Amazon Access Key ID'),
'secret' => $this->settings->getSetting('Email: Amazon Secret Access Key'),
'region' => AWS_REGION
);
//$this->ses = new AmazonSES($arr);
$this->ses = SesClient::factory($arr);
}
protected function sendMail($subject, $body, $toEmail, $fromEmail, $replyToEmail = null, $ccList = array(), $bccList = array()) {
if(empty($replyToEmail)){
$replyToEmail = $fromEmail;
}
LogManager::getInstance()->info("Sending email to: ".$toEmail."/ from: ".$fromEmail);
$toArray = array('ToAddresses' => array($toEmail),
'CcAddresses' => $ccList,
'BccAddresses' => $bccList);
$message = array(
'Subject' => array(
'Data' => $subject,
'Charset' => 'UTF-8'
),
'Body' => array(
'Html' => array(
'Data' => $body,
'Charset' => 'UTF-8'
)
)
);
//$response = $this->ses->sendEmail($fromEmail, $toArray, $message);
$response = $this->ses->sendEmail(
array(
'Source'=>$fromEmail,
'Destination'=>$toArray,
'Message'=>$message,
'ReplyToAddresses' => array($replyToEmail),
'ReturnPath' => $fromEmail
)
);
LogManager::getInstance()->info("SES Response:".print_r($response,true));
return $response;
}
}
class SMTPEmailSender extends EmailSender{
public function __construct($settings){
parent::__construct($settings);
}
protected function sendMail($subject, $body, $toEmail, $fromEmail, $replyToEmail = null, $ccList = array(), $bccList = array()) {
if(empty($replyToEmail)){
$replyToEmail = $fromEmail;
}
LogManager::getInstance()->info("Sending email to: ".$toEmail."/ from: ".$fromEmail);
$host = $this->settings->getSetting("Email: SMTP Host");
$username = $this->settings->getSetting("Email: SMTP User");
$password = $this->settings->getSetting("Email: SMTP Password");
$port = $this->settings->getSetting("Email: SMTP Port");
if(empty($port)){
$port = '25';
}
if($this->settings->getSetting("Email: SMTP Authentication Required") == "0"){
$auth = array ('host' => $host,
'auth' => false);
}else{
$auth = array ('host' => $host,
'auth' => true,
'username' => $username,
'port' => $port,
'password' => $password);
}
$smtp = Mail::factory('smtp',$auth);
$headers = array ('MIME-Version' => '1.0',
'Content-type' => 'text/html',
'charset' => 'iso-8859-1',
'From' => $fromEmail,
'To' => $toEmail,
'Reply-To' => $replyToEmail,
'Subject' => $subject);
$mail = $smtp->send($toEmail, $headers, $body);
return true;
}
}
class PHPMailer extends EmailSender{
public function __construct($settings){
parent::__construct($settings);
}
protected function sendMail($subject, $body, $toEmail, $fromEmail, $replyToEmail = null, $ccList = array(), $bccList = array()) {
if(empty($replyToEmail)){
$replyToEmail = $fromEmail;
}
LogManager::getInstance()->info("Sending email to: ".$toEmail."/ from: ".$fromEmail);
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: '.$fromEmail. "\r\n";
$headers .= 'ReplyTo: '.$replyToEmail. "\r\n";
$headers .= 'Ice-Mailer: PHP/' . phpversion();
// Mail it
$res = mail($toEmail, $subject, $body, $headers);
LogManager::getInstance()->info("PHP mailer result : ".$res);
return true;
}
}

View File

@@ -0,0 +1,4 @@
<?php
class ErrorCodes{
}

307
src/classes/FileService.php Normal file
View File

@@ -0,0 +1,307 @@
<?php
/*
This file is part of Ice Framework.
Ice Framework is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Ice Framework is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Ice Framework. If not, see <http://www.gnu.org/licenses/>.
------------------------------------------------------------------
Original work Copyright (c) 2012 [Gamonoid Media Pvt. Ltd]
Developer: Thilina Hasantha (thilina.hasantha[at]gmail.com / facebook.com/thilinah)
*/
class FileService{
private static $me = null;
private $memcache;
private function __construct(){
}
public static function getInstance(){
if(empty(self::$me)){
self::$me = new FileService();
}
return self::$me;
}
public function getFromCache($key){
try{
if(empty($this->memcache)){
$this->memcache = new Memcached();
$this->memcache->addServer("127.0.0.1", 11211);
}
$data = $this->memcache->get($key);
if(!empty($data)){
return $data;
}
return null;
}catch(Exception $e){
return null;
}
}
public function saveInCache($key, $data, $expire){
try{
if(empty($this->memcache)){
$this->memcache = new Memcached();
$this->memcache->addServer("127.0.0.1", 11211);
}
$this->memcache->set($key,$data, $expire);
}catch(Exception $e){
}
}
public function checkAddSmallProfileImage($profileImage){
$file = new File();
$file->Load('name = ?',array($profileImage->name."_small"));
if(empty($file->id)){
LogManager::getInstance()->info("Small profile image ".$profileImage->name."_small not found");
$largeFileUrl = $this->getFileUrl($profileImage->name);
$file->name = $profileImage->name."_small";
$signInMappingField = SIGN_IN_ELEMENT_MAPPING_FIELD_NAME;
$file->$signInMappingField = $profileImage->$signInMappingField;
$file->filename = $file->name.str_replace($profileImage->name,"",$profileImage->filename);
$file->file_group = $profileImage->file_group;
file_put_contents("/tmp/".$file->filename."_orig", file_get_contents($largeFileUrl));
if(file_exists("/tmp/".$file->filename."_orig")){
//Resize image to 100
$img = new abeautifulsite\SimpleImage("/tmp/".$file->filename."_orig");
$img->fit_to_width(100);
$img->save("/tmp/".$file->filename);
$uploadFilesToS3Key = SettingsManager::getInstance()->getSetting("Files: Amazon S3 Key for File Upload");
$uploadFilesToS3Secret = SettingsManager::getInstance()->getSetting("Files: Amazone S3 Secret for File Upload");
$s3Bucket = SettingsManager::getInstance()->getSetting("Files: S3 Bucket");
$uploadname = CLIENT_NAME."/".$file->filename;
$localFile = "/tmp/".$file->filename;
$s3FileSys = new S3FileSystem($uploadFilesToS3Key, $uploadFilesToS3Secret);
$result = $s3FileSys->putObject($s3Bucket, $uploadname, $localFile, 'authenticated-read');
unlink("/tmp/".$file->filename);
unlink("/tmp/".$file->filename."_orig");
LogManager::getInstance()->info("Upload Result:".print_r($result,true));
if(!empty($result)){
$ok = $file->Save();
}
return $file;
}
return null;
}
return $file;
}
public function updateSmallProfileImage($profile){
$file = new File();
$file->Load('name = ?',array('profile_image_'.$profile->id));
if($file->name == 'profile_image_'.$profile->id){
$uploadFilesToS3 = SettingsManager::getInstance()->getSetting("Files: Upload Files to S3");
if($uploadFilesToS3 == "1"){
try{
$fileNew = $this->checkAddSmallProfileImage($file);
if(!empty($fileNew)){
$file = $fileNew;
}
$uploadFilesToS3Key = SettingsManager::getInstance()->getSetting("Files: Amazon S3 Key for File Upload");
$uploadFilesToS3Secret = SettingsManager::getInstance()->getSetting("Files: Amazone S3 Secret for File Upload");
$s3FileSys = new S3FileSystem($uploadFilesToS3Key, $uploadFilesToS3Secret);
$s3WebUrl = SettingsManager::getInstance()->getSetting("Files: S3 Web Url");
$fileUrl = $s3WebUrl.CLIENT_NAME."/".$file->filename;
$expireUrl = $this->getFromCache($fileUrl);
if(empty($expireUrl)){
$expireUrl = $s3FileSys->generateExpiringURL($fileUrl, 600);
$this->saveInCache($fileUrl, $expireUrl, 500);
}
$profile->image = $expireUrl;
}catch (Exception $e){
LogManager::getInstance()->error("Error generating profile image: ".$e->getMessage());
if($profile->gender == 'Female'){
$profile->image = BASE_URL."images/user_female.png";
}else{
$profile->image = BASE_URL."images/user_male.png";
}
}
}else{
$profile->image = CLIENT_BASE_URL.'data/'.$file->filename;
}
}else{
if($profile->gender == 'Female'){
$profile->image = BASE_URL."images/user_female.png";
}else{
$profile->image = BASE_URL."images/user_male.png";
}
}
return $profile;
}
public function updateProfileImage($profile){
$file = new File();
$file->Load('name = ?',array('profile_image_'.$profile->id));
if($file->name == 'profile_image_'.$profile->id){
$uploadFilesToS3 = SettingsManager::getInstance()->getSetting("Files: Upload Files to S3");
if($uploadFilesToS3 == "1"){
$uploadFilesToS3Key = SettingsManager::getInstance()->getSetting("Files: Amazon S3 Key for File Upload");
$uploadFilesToS3Secret = SettingsManager::getInstance()->getSetting("Files: Amazone S3 Secret for File Upload");
$s3FileSys = new S3FileSystem($uploadFilesToS3Key, $uploadFilesToS3Secret);
$s3WebUrl = SettingsManager::getInstance()->getSetting("Files: S3 Web Url");
$fileUrl = $s3WebUrl.CLIENT_NAME."/".$file->filename;
$expireUrl = $this->getFromCache($fileUrl);
if(empty($expireUrl)){
$expireUrl = $s3FileSys->generateExpiringURL($fileUrl, 600);
$this->saveInCache($fileUrl, $expireUrl, 500);
}
$profile->image = $expireUrl;
}else{
$profile->image = CLIENT_BASE_URL.'data/'.$file->filename;
}
}else{
if($profile->gender == 'Female'){
$profile->image = BASE_URL."images/user_female.png";
}else{
$profile->image = BASE_URL."images/user_male.png";
}
}
return $profile;
}
public function getFileUrl($fileName){
$file = new File();
$file->Load('name = ?',array($fileName));
$uploadFilesToS3 = SettingsManager::getInstance()->getSetting("Files: Upload Files to S3");
if($uploadFilesToS3 == "1"){
$uploadFilesToS3Key = SettingsManager::getInstance()->getSetting("Files: Amazon S3 Key for File Upload");
$uploadFilesToS3Secret = SettingsManager::getInstance()->getSetting("Files: Amazone S3 Secret for File Upload");
$s3FileSys = new S3FileSystem($uploadFilesToS3Key, $uploadFilesToS3Secret);
$s3WebUrl = SettingsManager::getInstance()->getSetting("Files: S3 Web Url");
$fileUrl = $s3WebUrl.CLIENT_NAME."/".$file->filename;
$expireUrl = $this->getFromCache($fileUrl);
if(empty($expireUrl)){
$expireUrl = $s3FileSys->generateExpiringURL($fileUrl, 600);
$this->saveInCache($fileUrl, $expireUrl, 500);
}
return $expireUrl;
}else{
return CLIENT_BASE_URL.'data/'.$file->filename;
}
}
public function deleteProfileImage($profileId){
$file = new File();
$file->Load('name = ?',array('profile_image_'.$profileId));
if($file->name == 'profile_image_'.$profileId){
$ok = $file->Delete();
if($ok){
LogManager::getInstance()->info("Delete File:".CLIENT_BASE_PATH.$file->filename);
unlink(CLIENT_BASE_PATH.'data/'.$file->filename);
}else{
return false;
}
}
$file = new File();
$file->Load('name = ?',array('profile_image_'.$profileId."_small"));
if($file->name == 'profile_image_'.$profileId."_small"){
$ok = $file->Delete();
if($ok){
LogManager::getInstance()->info("Delete File:".CLIENT_BASE_PATH.$file->filename);
unlink(CLIENT_BASE_PATH.'data/'.$file->filename);
}else{
return false;
}
}
return true;
}
public function deleteFileByField($value, $field){
LogManager::getInstance()->info("Delete file by field: $field / value: $value");
$file = new File();
$file->Load("$field = ?",array($value));
if($file->$field == $value){
$ok = $file->Delete();
if($ok){
$uploadFilesToS3 = SettingsManager::getInstance()->getSetting("Files: Upload Files to S3");
if($uploadFilesToS3 == "1"){
$uploadFilesToS3Key = SettingsManager::getInstance()->getSetting("Files: Amazon S3 Key for File Upload");
$uploadFilesToS3Secret = SettingsManager::getInstance()->getSetting("Files: Amazone S3 Secret for File Upload");
$s3Bucket = SettingsManager::getInstance()->getSetting("Files: S3 Bucket");
$uploadname = CLIENT_NAME."/".$file->filename;
LogManager::getInstance()->info("Delete from S3:".$uploadname);
$s3FileSys = new S3FileSystem($uploadFilesToS3Key, $uploadFilesToS3Secret);
$res = $s3FileSys->deleteObject($s3Bucket, $uploadname);
}else{
LogManager::getInstance()->info("Delete:".CLIENT_BASE_PATH.'data/'.$file->filename);
unlink(CLIENT_BASE_PATH.'data/'.$file->filename);
}
}else{
return false;
}
}
return true;
}
}

View File

@@ -0,0 +1,156 @@
<?php
class ModuleBuilder {
var $modules = array();
public function addModuleOrGroup($module){
$this->modules[] = $module;
}
public function getTabHeadersHTML(){
$html = "";
foreach($this->modules as $module){
$html .= $module->getHTML()."\r\n";
}
return $html;
}
public function getTabPagesHTML(){
$html = "";
foreach($this->modules as $module){
if(get_class($module) == "ModuleTab"){
$html .= $module->getPageHTML()."\r\n";
}else{
foreach($module->modules as $mod){
$html .= $mod->getPageHTML()."\r\n";
}
}
}
return $html;
}
public function getModJsHTML(){
$html = "var modJsList = new Array();\r\n";
$activeModule = "";
foreach($this->modules as $module){
if(get_class($module) == "ModuleTab"){
$html .= $module->getJSObjectCode()."\r\n";
if($module->isActive){
$activeModule = $module->name;
}
}else{
foreach($module->modules as $mod){
if($module->isActive && $activeModule == ""){
$activeModule = $mod->name;
}
$html .= $mod->getJSObjectCode()."\r\n";
}
}
}
$html .= "var modJs = modJsList['tab".$activeModule."'];\r\n";
return $html;
}
}
class ModuleTab{
public $name;
var $class;
var $label;
var $adapterName;
var $filter;
var $orderBy;
public $isActive = false;
public $isInsideGroup = false;
var $options = array();
public function __construct($name, $class, $label, $adapterName, $filter, $orderBy, $isActive = false, $options = array()){
$this->name = $name;
$this->class = $class;
$this->label = $label;
$this->adapterName = $adapterName;
$this->filter = $filter;
$this->orderBy = $orderBy;
$this->isActive = $isActive;
$this->options = $options;
}
public function getHTML(){
$active = ($this->isActive)?"active":"";
if(!$this->isInsideGroup) {
return '<li class="' . $active . '"><a id="tab' . $this->name . '" href="#tabPage' . $this->name . '">' . $this->label . '</a></li>';
}else{
return '<li class="' . $active . '"><a id="tab' . $this->name . '" href="#tabPage' . $this->name . '">' . $this->label . '</a></li>';
}
}
public function getPageHTML(){
$active = ($this->isActive)?" active":"";
$html = '<div class="tab-pane'.$active.'" id="tabPage'.$this->name.'">'.
'<div id="'.$this->name.'" class="reviewBlock" data-content="List" style="padding-left:5px;"></div>'.
'<div id="'.$this->name.'Form" class="reviewBlock" data-content="Form" style="padding-left:5px;display:none;"></div>'.
'</div>';
return $html;
}
public function getJSObjectCode()
{
$js = '';
if (empty($this->filter)) {
$js.= "modJsList['tab" . $this->name . "'] = new " . $this->adapterName . "('" . $this->class . "','" . $this->name . "','','".$this->orderBy."');";
} else {
$js.= "modJsList['tab" . $this->name . "'] = new " . $this->adapterName . "('" . $this->class . "','" . $this->name . "'," . $this->filter . ",'".$this->orderBy."');";
}
foreach($this->options as $key => $val){
$js.= "modJsList['tab" . $this->name . "'].".$key."(".$val.");";
}
return $js;
}
}
class ModuleTabGroup{
var $name;
var $label;
var $isActive = false;
public $modules = array();
public function __construct($name, $label){
$this->name = $name;
$this->label = $label;
}
public function addModuleTab($moduleTab){
if($moduleTab->isActive){
$this->isActive = true;
$moduleTab->isActive = false;
}
$moduleTab->isInsideGroup = true;
$this->modules[] = $moduleTab;
}
public function getHTML(){
$html = "";
$active = ($this->isActive)?" active":"";
$html.= '<li class="dropdown'.$active.'">'."\r\n".
'<a href="#" id="'.$this->name.'" class="dropdown-toggle" data-toggle="dropdown" aria-controls="'.$this->name.'-contents">'.$this->label.' <span class="caret"></span></a>'."\r\n".
'<ul class="dropdown-menu" role="menu" aria-labelledby="'.$this->name.'" id="'.$this->name.'-contents">';
foreach($this->modules as $module){
$html.= $module->getHTML();
}
$html .= "</ul></li>";
return $html;
}
}

View File

@@ -0,0 +1,78 @@
<?php
class NotificationManager{
var $baseService;
public function setBaseService($baseService){
$this->baseService = $baseService;
}
public function addNotification($toUser, $message, $action, $type){
$profileVar = SIGN_IN_ELEMENT_MAPPING_FIELD_NAME;
$profileClass = ucfirst(SIGN_IN_ELEMENT_MAPPING_FIELD_NAME);
$userEmp = new User();
$userEmp->load("profile = ?",array($toUser));
if(!empty($userEmp->$profileVar) && $userEmp->$profileVar == $toUser){
$toUser = $userEmp->id;
}else{
return;
}
$noti = new Notification();
$user = $this->baseService->getCurrentUser();
$noti->fromUser = $user->id;
$noti->fromProfile = $user->$profileVar;
$noti->toUser = $toUser;
$noti->message = $message;
if(!empty($noti->fromProfile)){
$profile = $this->baseService->getElement($profileClass,$noti->fromProfile,null,true);
if(!empty($profile)){
$fs = new FileService();
$profile = $fs->updateProfileImage($profile);
$noti->image = $profile->image;
}
}
if(empty($noti->image)){
$noti->image = BASE_URL."images/user_male.png";
}
$noti->action = $action;
$noti->type = $type;
$noti->time = date('Y-m-d H:i:s');
$noti->status = 'Unread';
$ok = $noti->Save();
if(!$ok){
LogManager::getInstance()->info("Error adding notification: ".$noti->ErrorMsg());
}
}
public function clearNotifications($userId){
$notification = new Notification();
$listUnread = $notification->Find("toUser = ? and status = ?",array($userId,'Unread'));
foreach($listUnread as $not){
$not->status = "Read";
$not->Save();
}
}
public function getLatestNotificationsAndCounts($userId){
$notification = new Notification();
$listUnread = $notification->Find("toUser = ? and status = ?",array($userId,'Unread'));
$unreadCount = count($listUnread);
$limit = ($unreadCount < 20)?20:$unreadCount;
$list = $notification->Find("toUser = ? order by time desc limit ?",array($userId,$limit));
return array($unreadCount, $list);
}
}

View File

@@ -0,0 +1,143 @@
<?php
class ReportHandler{
public function handleReport($request){
if(!empty($request['id'])){
$report = new Report();
$report->Load("id = ?",array($request['id']));
if($report->id."" == $request['id']){
if($report->type == 'Query'){
$where = $this->buildQueryOmmit(json_decode($report->paramOrder,true), $request);
$query = str_replace("_where_", $where[0], $report->query);
return $this->executeReport($report,$query,$where[1]);
}else if($report->type == 'Class'){
$className = $report->query;
include MODULE_PATH.'/reportClasses/ReportBuilder.php';
include MODULE_PATH.'/reportClasses/'.$className.".php";
$cls = new $className();
$data = $cls->getData($report,$request);
return $this->generateReport($report,$data);
}
}else{
return array("ERROR","Report id not found");
}
}
}
private function executeReport($report,$query,$parameters){
$report->DB()->SetFetchMode(ADODB_FETCH_ASSOC);
$rs = $report->DB()->Execute($query,$parameters);
if(!$rs){
LogManager::getInstance()->info($report->DB()->ErrorMsg());
return array("ERROR","Error generating report");
}
$reportNamesFilled = false;
$columnNames = array();
$reportData = array();
foreach ($rs as $rowId => $row) {
$reportData[] = array();
if(!$reportNamesFilled){
foreach ($row as $name=> $value){
$columnNames[] = $name;
$reportData[count($reportData)-1][] = $value;
}
$reportNamesFilled = true;
}else{
foreach ($row as $name=> $value){
$reportData[count($reportData)-1][] = $value;
}
}
}
array_unshift($reportData,$columnNames);
return $this->generateReport($report, $reportData);
}
private function generateReport($report, $data){
$fileFirst = "Report_".str_replace(" ", "_", $report->name)."-".date("Y-m-d_H-i-s");
$file = $fileFirst.".csv";
$fileName = CLIENT_BASE_PATH.'data/'.$file;
$fp = fopen($fileName, 'w');
foreach ($data as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
$uploadedToS3 = false;
$uploadFilesToS3 = SettingsManager::getInstance()->getSetting("Files: Upload Files to S3");
$uploadFilesToS3Key = SettingsManager::getInstance()->getSetting("Files: Amazon S3 Key for File Upload");
$uploadFilesToS3Secret = SettingsManager::getInstance()->getSetting("Files: Amazone S3 Secret for File Upload");
$s3Bucket = SettingsManager::getInstance()->getSetting("Files: S3 Bucket");
$s3WebUrl = SettingsManager::getInstance()->getSetting("Files: S3 Web Url");
if($uploadFilesToS3.'' == '1' && !empty($uploadFilesToS3Key)
&& !empty($uploadFilesToS3Secret) && !empty($s3Bucket) && !empty($s3WebUrl)){
$uploadname = CLIENT_NAME."/".$file;
$s3FileSys = new S3FileSystem($uploadFilesToS3Key, $uploadFilesToS3Secret);
$res = $s3FileSys->putObject($s3Bucket, $uploadname, $fileName, 'authenticated-read');
if(empty($res)){
return array("ERROR",$file);
}
unlink($fileName);
$file_url = $s3WebUrl.$uploadname;
$file_url = $s3FileSys->generateExpiringURL($file_url);
$uploadedToS3 = true;
}
$fileObj = new File();
$fileObj->name = $fileFirst;
$fileObj->filename = $file;
$fileObj->file_group = "Report";
$ok = $fileObj->Save();
if(!$ok){
LogManager::getInstance()->info($fileObj->ErrorMsg());
return array("ERROR","Error generating report");
}
$headers = array_shift($data);
if($uploadedToS3){
return array("SUCCESS",array($file_url,$headers,$data));
}else{
return array("SUCCESS",array($file,$headers,$data));
}
}
private function buildQueryOmmit($names, $params){
$parameters = array();
$query = "";
foreach($names as $name){
if($params[$name] != "NULL"){
if($query != ""){
$query.=" AND ";
}
$query.=$name." = ?";
$parameters[] = $params[$name];
}
}
if($query != ""){
$query = "where ".$query;
}
return array($query, $parameters);
}
}

View File

@@ -0,0 +1,151 @@
<?php
class RestApiManager{
private static $me = NULL;
var $endPoints = array();
private function __construct(){
}
public static function getInstance(){
if(empty(self::$me)){
self::$me = new RestApiManager();
}
return self::$me;
}
public function generateUserAccessToken($user){
$data = array();
$data['userId'] = $user->id;
$data['expires'] = strtotime('now') + 60*60;
$accessTokenTemp = AesCtr::encrypt(json_encode($data), $user->password, 256);
$accessTokenTemp = $user->id."|".$accessTokenTemp;
$accessToken = AesCtr::encrypt($accessTokenTemp, APP_SEC, 256);
return new IceResponse(IceResponse::SUCCESS, $accessToken);
}
public function getAccessTokenForUser($user){
$accessTokenObj = new RestAccessToken();
$accessTokenObj->Load("userId = ?",array($user->id));
$generateAccessToken = false;
$accessToken = $accessTokenObj->token;
if(!empty($accessToken)){
$resp = $this->validateAccessTokenInner($accessToken);
if($resp->getStatus() != IceResponse::SUCCESS){
$generateAccessToken = true;
}
}else{
$generateAccessToken = true;
}
if($generateAccessToken){
$accessToken = $this->generateUserAccessToken($user)->getData();
if(!empty($accessTokenObj->id)){
$accessTokenObj->token = $accessToken;
$accessTokenObj->hash = base64_encode(CLIENT_BASE_URL).":".md5($accessTokenObj->token);
$accessTokenObj->updated = date("Y-m-d H:i:s");
$accessTokenObj->Save();
}else{
$accessTokenObj = new RestAccessToken();
$accessTokenObj->userId = $user->id;
$accessTokenObj->token = $accessToken;
$accessTokenObj->hash = base64_encode(CLIENT_BASE_URL).":".md5($accessTokenObj->token);
$accessTokenObj->updated = date("Y-m-d H:i:s");
$accessTokenObj->created = date("Y-m-d H:i:s");
$accessTokenObj->Save();
}
}
return new IceResponse(IceResponse::SUCCESS, $accessTokenObj->hash);
}
public function validateAccessToken($hash){
$accessTokenObj = new RestAccessToken();
$accessTokenObj->Load("hash = ?",array($hash));
if(!empty($accessTokenObj->id) && $accessTokenObj->hash == $hash){
return $this->validateAccessTokenInner($accessTokenObj->token);
}
return new IceResponse(IceResponse::ERROR, "Acess Token not found");
}
private function validateAccessTokenInner($accessToken){
$accessTokenTemp = AesCtr::decrypt($accessToken, APP_SEC, 256);
$parts = explode("|", $accessTokenTemp);
$user = new User();
$user->Load("id = ?",array($parts[0]));
if(empty($user->id) || $user->id != $parts[0] || empty($parts[0])){
return new IceResponse(IceResponse::ERROR, -1);
}
$accessToken = AesCtr::decrypt($parts[1], $user->password, 256);
$data = json_decode($accessToken, true);
if($data['userId'] == $user->id){
return new IceResponse(IceResponse::SUCCESS, true);
}
return new IceResponse(IceResponse::ERROR, false);
}
public function addEndPoint($endPoint){
$url = $endPoint->getUrl();
LogManager::getInstance()->info("Adding REST end point for - ".$url);
$this->endPoints[$url] = $endPoint;
}
public function process($type, $url, $parameters){
$accessTokenValidation = $this->validateAccessToken($parameters['access_token']);
if($accessTokenValidation->getStatus() == IceResponse::ERROR){
return $accessTokenValidation;
}
if(isset($this->endPoints[$url])){
return $this->endPoints[$url]->$type($parameters);
}
return new IceResponse(IceResponse::ERROR, "End Point ".$url." - Not Found");
}
}
class RestEndPoint{
var $url;
public function setUrl($url){
$this->url = $url;
}
public function getUrl(){
return $this->url;
}
public function get($parameters){
return new IceResponse(IceResponse::ERROR, false);
}
public function post($parameters){
return new IceResponse(IceResponse::ERROR, false);
}
public function put($parameters){
return new IceResponse(IceResponse::ERROR, false);
}
public function delete($parameters){
return new IceResponse(IceResponse::ERROR, false);
}
}

View File

@@ -0,0 +1,107 @@
<?php
use Aws\S3\S3Client;
class S3FileSystem{
var $s3;
var $key;
var $secret;
public function __construct($key, $secret){
$this->key = $key;
$this->secret = $secret;
$arr = array(
'key' => $key,
'secret' => $secret,
'region' => AWS_REGION
);
$this->s3 = S3Client::factory($arr);
}
public function putObject($bucket, $key, $sourceFile, $acl){
$res = null;
try{
$res = $this->s3->putObject(array(
'Bucket' => $bucket,
'Key' => $key,
'SourceFile' => $sourceFile,
'ACL' => $acl
/*'ContentType' => 'image/jpeg'*/
));
}catch(Exception $e){
LogManager::getInstance()->info($e->getMessage());
return NULL;
}
LogManager::getInstance()->info("Response from s3:".print_r($res,true));
$result = $res->get('RequestId');
if(!empty($result)){
return $result;
}
return NULL;
}
public function deleteObject($bucket, $key){
$res = null;
try{
$res = $this->s3->deleteObject(array(
'Bucket' => $bucket,
'Key' => $key
));
}catch(Exception $e){
LogManager::getInstance()->info($e->getMessage());
return NULL;
}
LogManager::getInstance()->info("Response from s3:".print_r($res,true));
$result = $res->get('RequestId');
if(!empty($result)){
return $result;
}
return NULL;
}
public function generateExpiringURL($url, $expiresIn = 600) {
// Calculate expiry time
$expiresTimestamp = time() + intval($expiresIn);
$path = parse_url($url, PHP_URL_PATH);
$path = str_replace('%2F', '/', rawurlencode($path = ltrim($path, '/')));
$host = parse_url($url, PHP_URL_HOST);
$bucket = str_replace(".s3.amazonaws.com", "", $host);
// Path for signature starts with the bucket
$signpath = '/'. $bucket .'/'. $path;
// S3 friendly string to sign
$signsz = implode("\n", $pieces = array('GET', null, null, $expiresTimestamp, $signpath));
// Calculate the hash
$signature = $this->el_crypto_hmacSHA1($this->secret, $signsz);
// ... to the query string ...
$qs = http_build_query($pieces = array(
'AWSAccessKeyId' => $this->key,
'Expires' => $expiresTimestamp,
'Signature' => $signature,
));
// ... and return the URL!
return $url.'?'.$qs;
}
private function el_crypto_hmacSHA1($key, $data, $blocksize = 64) {
if (strlen($key) > $blocksize) $key = pack('H*', sha1($key));
$key = str_pad($key, $blocksize, chr(0x00));
$ipad = str_repeat(chr(0x36), $blocksize);
$opad = str_repeat(chr(0x5c), $blocksize);
$hmac = pack( 'H*', sha1(
($key ^ $opad) . pack( 'H*', sha1(
($key ^ $ipad) . $data
))
));
return base64_encode($hmac);
}
}

View File

@@ -0,0 +1,44 @@
<?php
class SettingsManager{
private static $me = null;
private function __construct(){
}
public static function getInstance(){
if(empty(self::$me)){
self::$me = new SettingsManager();
}
return self::$me;
}
public function getSetting($name){
if(class_exists("ProVersion")){
$pro = new ProVersion();
$val = $pro->getSetting($name);
if(!empty($val)){
return $val;
}
}
$setting = new Setting();
$setting->Load("name = ?",array($name));
if($setting->name == $name){
return $setting->value;
}
return null;
}
public function setSetting($name, $value){
$setting = new Setting();
$setting->Load("name = ?",array($name));
if($setting->name == $name){
$setting->value = $value;
$setting->Save();
}
}
}

1287
src/classes/SimpleImage.php Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,104 @@
<?php
/*
This file is part of Ice Framework.
Ice Framework is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Ice Framework is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Ice Framework. If not, see <http://www.gnu.org/licenses/>.
------------------------------------------------------------------
Original work Copyright (c) 2012 [Gamonoid Media Pvt. Ltd]
Developer: Thilina Hasantha (thilina.hasantha[at]gmail.com / facebook.com/thilinah)
*/
class IceResponse{
const SUCCESS = "SUCCESS";
const ERROR = "ERROR";
var $status;
var $data;
public function __construct($status,$data = null){
$this->status = $status;
$this->data = $data;
}
public function getStatus(){
return $this->status;
}
public function getData(){
return $this->data;
}
public function getObject(){
return $this->data;
}
public function getJsonArray(){
return array("status"=>$this->status,"data"=>$this->data);
}
}
abstract class SubActionManager{
var $user = null;
protected $baseService = null;
var $emailTemplates = null;
var $emailSender = null;
public function setUser($user){
$this->user = $user;
}
public function setBaseService($baseService){
$this->baseService = $baseService;
}
public function getCurrentProfileId(){
return $this->baseService->getCurrentProfileId();
}
public function setEmailTemplates($emailTemplates){
$this->emailTemplates = $emailTemplates;
}
public function getEmailTemplate($name){
//Read module email templates
if($this->emailTemplates == null){
$this->emailTemplates = array();
if(is_dir(MODULE_PATH.'/emailTemplates/')){
$ams = scandir(MODULE_PATH.'/emailTemplates/');
foreach($ams as $am){
if(!is_dir(MODULE_PATH.'/emailTemplates/'.$am) && $am != '.' && $am != '..'){
$this->emailTemplates[$am] = file_get_contents(MODULE_PATH.'/emailTemplates/'.$am);
}
}
}
}
return $this->emailTemplates[$name];
}
public function setEmailSender($emailSender){
$this->emailSender = $emailSender;
}
public function getUserFromProfileId($profileId){
return $this->baseService->getUserFromProfileId($profileId);
}
}

228
src/classes/UIManager.php Normal file
View File

@@ -0,0 +1,228 @@
<?php
class UIManager{
private static $me = null;
var $user;
var $currentProfile;
var $switchedProfile;
var $currentProfileBlock = null;
var $switchedProfileBlock = null;
var $tempates = array();
var $quickAccessMenuItems = array();
private function __construct(){
}
public static function getInstance(){
if(empty(self::$me)){
self::$me = new UIManager();
}
return self::$me;
}
private function getTemplate($name, $type){
if(isset($this->tempates[$name])){
return $this->tempates[$name];
}
$this->tempates[$name] = file_get_contents(APP_BASE_PATH."templates/".$type."/".$name.".html");
return $this->tempates[$name];
}
public function populateTemplate($name, $type, $params){
$template= $this->getTemplate($name, $type);
foreach($params as $key=>$value){
$template = str_replace("#_".$key."_#", $value, $template);
}
return $template;
}
public function setCurrentUser($user){
$this->user = $user;
}
public function setHomeLink($homeLink){
$this->homeLink = $homeLink;
}
public function setProfiles($profileCurrent, $profileSwitched){
$this->currentProfile = $profileCurrent;
$this->switchedProfile = $profileSwitched;
if(!empty($profileCurrent) && !empty($profileSwitched)){
$this->currentProfileBlock = array(
"profileImage"=>$profileCurrent->image,
"firstName"=>$profileCurrent->first_name,
"lastName"=>$profileCurrent->last_name
);
$this->switchedProfileBlock = array(
"profileImage"=>$profileSwitched->image,
"firstName"=>$profileSwitched->first_name,
"lastName"=>$profileSwitched->last_name
);
} else if(!empty($profileCurrent)){
$this->currentProfileBlock = array(
"profileImage"=>$profileCurrent->image,
"firstName"=>$profileCurrent->first_name,
"lastName"=>$profileCurrent->last_name
);
} else if(!empty($profileSwitched)){
$this->currentProfileBlock = array(
"profileImage"=>BASE_URL."images/user_male.png",
"firstName"=>$this->user->username,
"lastName"=>""
);
$this->switchedProfileBlock = array(
"profileImage"=>$profileSwitched->image,
"firstName"=>$profileSwitched->first_name,
"lastName"=>$profileSwitched->last_name
);
}else{
$this->currentProfileBlock = array(
"profileImage"=>BASE_URL."images/user_male.png",
"firstName"=>$this->user->username,
"lastName"=>""
);
}
}
public function getProfileBlocks(){
$tempateProfileBlock = "";
$tempateProfileBlock = $this->populateTemplate('profile_info', 'app', $this->currentProfileBlock);
if(!empty($this->switchedProfileBlock)){
$tempateProfileBlock .= $this->populateTemplate('switched_profile_info', 'app', $this->switchedProfileBlock);
}
return $tempateProfileBlock;
}
public function getMenuBlocks(){
$manuItems = array();
if(!empty($this->quickAccessMenuItems)){
$itemsHtml = $this->getQuickAccessMenuItemsHTML();
if(!empty($itemsHtml)){
$manuItems[] = new MenuItemTemplate('menuButtonQuick', array("ITEMS"=>$itemsHtml));
}
}
$manuItems[] = new MenuItemTemplate('menuButtonNotification', array());
if($this->user->user_level == "Admin"){
$manuItems[] = new MenuItemTemplate('menuButtonSwitchProfile', array());
}
if(!empty($this->currentProfile)){
$manuItems[] = new MenuItemTemplate('menuButtonProfile', array(
"profileImage"=>$this->currentProfile->image,
"firstName"=>$this->currentProfile->first_name,
"lastName"=>$this->currentProfile->last_name,
"homeLink"=>$this->homeLink,
"CLIENT_BASE_URL"=>CLIENT_BASE_URL
));
}else{
$manuItems[] = new MenuItemTemplate('menuButtonProfile', array(
"profileImage"=>BASE_URL."images/user_male.png",
"firstName"=>$this->user->username,
"lastName"=>"",
"homeLink"=>$this->homeLink,
"CLIENT_BASE_URL"=>CLIENT_BASE_URL
));
}
if($this->user->user_level == "Admin"){
$manuItems[] = new MenuItemTemplate('menuButtonHelp', array(
"APP_NAME"=>APP_NAME,
"VERSION"=>VERSION,
"VERSION_DATE"=>VERSION_DATE
));
}
return $manuItems;
}
public function getMenuItemsHTML(){
$menuItems = $this->getMenuBlocks();
$menuHtml = "";
foreach($menuItems as $item){
$menuHtml.=$item->getHtml();
}
return $menuHtml;
}
public function addQuickAccessMenuItem($name, $icon, $link, $userLevels = array()){
$this->quickAccessMenuItems[] = array($name, $icon, $link, $userLevels);
}
public function getQuickAccessMenuItemsHTML(){
$html = "";
$user = BaseService::getInstance()->getCurrentUser();
foreach($this->quickAccessMenuItems as $item){
if(empty($item[3]) || in_array($user->user_level,$item[3])){
$html .= '<a href="'.$item[2].'"><i class="fa '.$item[1].'"></i> '.$item[0].'</a>';
}
}
return $html;
}
public function renderModule($moduleBuilder){
$str = '<div class="span9"><ul class="nav nav-tabs" id="modTab" style="margin-bottom:0px;margin-left:5px;border-bottom: none;">__tabHeaders__</ul><div class="tab-content">__tabPages__</div></div><script>__tabJs__</script>';
$str = str_replace("__tabHeaders__",$moduleBuilder->getTabHeadersHTML(), $str);
$str = str_replace("__tabPages__",$moduleBuilder->getTabPagesHTML(), $str);
$str = str_replace("__tabJs__",$moduleBuilder->getModJsHTML(), $str);
return $str;
}
}
//Menu Items
class MenuItemTemplate{
public $templateName;
public $params;
public function __construct($templateName, $params){
$this->templateName = $templateName;
$this->params = $params;
}
public function getHtml(){
return UIManager::getInstance()->populateTemplate($this->templateName, 'menu', $this->params);
}
}

View File

@@ -0,0 +1,28 @@
<?php
/*
This file is part of Ice Framework.
Ice Framework is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Ice Framework is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Ice Framework. If not, see <http://www.gnu.org/licenses/>.
------------------------------------------------------------------
Original work Copyright (c) 2012 [Gamonoid Media Pvt. Ltd]
Developer: Thilina Hasantha (thilina.hasantha[at]gmail.com / facebook.com/thilinah)
*/
class UserService{
public function getAuthUser($username, $password){
}
}

165
src/classes/crypt/Aes.php Normal file
View File

@@ -0,0 +1,165 @@
<?php
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* AES implementation in PHP (c) Chris Veness 2005-2011. Right of free use is granted for all */
/* commercial or non-commercial use under CC-BY licence. No warranty of any form is offered. */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
class Aes {
/**
* AES Cipher function: encrypt 'input' with Rijndael algorithm
*
* @param input message as byte-array (16 bytes)
* @param w key schedule as 2D byte-array (Nr+1 x Nb bytes) -
* generated from the cipher key by keyExpansion()
* @return ciphertext as byte-array (16 bytes)
*/
public static function cipher($input, $w) { // main cipher function [§5.1]
$Nb = 4; // block size (in words): no of columns in state (fixed at 4 for AES)
$Nr = count($w)/$Nb - 1; // no of rounds: 10/12/14 for 128/192/256-bit keys
$state = array(); // initialise 4xNb byte-array 'state' with input [§3.4]
for ($i=0; $i<4*$Nb; $i++) $state[$i%4][floor($i/4)] = $input[$i];
$state = self::addRoundKey($state, $w, 0, $Nb);
for ($round=1; $round<$Nr; $round++) { // apply Nr rounds
$state = self::subBytes($state, $Nb);
$state = self::shiftRows($state, $Nb);
$state = self::mixColumns($state, $Nb);
$state = self::addRoundKey($state, $w, $round, $Nb);
}
$state = self::subBytes($state, $Nb);
$state = self::shiftRows($state, $Nb);
$state = self::addRoundKey($state, $w, $Nr, $Nb);
$output = array(4*$Nb); // convert state to 1-d array before returning [§3.4]
for ($i=0; $i<4*$Nb; $i++) $output[$i] = $state[$i%4][floor($i/4)];
return $output;
}
private static function addRoundKey($state, $w, $rnd, $Nb) { // xor Round Key into state S [§5.1.4]
for ($r=0; $r<4; $r++) {
for ($c=0; $c<$Nb; $c++) $state[$r][$c] ^= $w[$rnd*4+$c][$r];
}
return $state;
}
private static function subBytes($s, $Nb) { // apply SBox to state S [§5.1.1]
for ($r=0; $r<4; $r++) {
for ($c=0; $c<$Nb; $c++) $s[$r][$c] = self::$sBox[$s[$r][$c]];
}
return $s;
}
private static function shiftRows($s, $Nb) { // shift row r of state S left by r bytes [§5.1.2]
$t = array(4);
for ($r=1; $r<4; $r++) {
for ($c=0; $c<4; $c++) $t[$c] = $s[$r][($c+$r)%$Nb]; // shift into temp copy
for ($c=0; $c<4; $c++) $s[$r][$c] = $t[$c]; // and copy back
} // note that this will work for Nb=4,5,6, but not 7,8 (always 4 for AES):
return $s; // see fp.gladman.plus.com/cryptography_technology/rijndael/aes.spec.311.pdf
}
private static function mixColumns($s, $Nb) { // combine bytes of each col of state S [§5.1.3]
for ($c=0; $c<4; $c++) {
$a = array(4); // 'a' is a copy of the current column from 's'
$b = array(4); // 'b' is a•{02} in GF(2^8)
for ($i=0; $i<4; $i++) {
$a[$i] = $s[$i][$c];
$b[$i] = $s[$i][$c]&0x80 ? $s[$i][$c]<<1 ^ 0x011b : $s[$i][$c]<<1;
}
// a[n] ^ b[n] is a•{03} in GF(2^8)
$s[0][$c] = $b[0] ^ $a[1] ^ $b[1] ^ $a[2] ^ $a[3]; // 2*a0 + 3*a1 + a2 + a3
$s[1][$c] = $a[0] ^ $b[1] ^ $a[2] ^ $b[2] ^ $a[3]; // a0 * 2*a1 + 3*a2 + a3
$s[2][$c] = $a[0] ^ $a[1] ^ $b[2] ^ $a[3] ^ $b[3]; // a0 + a1 + 2*a2 + 3*a3
$s[3][$c] = $a[0] ^ $b[0] ^ $a[1] ^ $a[2] ^ $b[3]; // 3*a0 + a1 + a2 + 2*a3
}
return $s;
}
/**
* Key expansion for Rijndael cipher(): performs key expansion on cipher key
* to generate a key schedule
*
* @param key cipher key byte-array (16 bytes)
* @return key schedule as 2D byte-array (Nr+1 x Nb bytes)
*/
public static function keyExpansion($key) { // generate Key Schedule from Cipher Key [§5.2]
$Nb = 4; // block size (in words): no of columns in state (fixed at 4 for AES)
$Nk = count($key)/4; // key length (in words): 4/6/8 for 128/192/256-bit keys
$Nr = $Nk + 6; // no of rounds: 10/12/14 for 128/192/256-bit keys
$w = array();
$temp = array();
for ($i=0; $i<$Nk; $i++) {
$r = array($key[4*$i], $key[4*$i+1], $key[4*$i+2], $key[4*$i+3]);
$w[$i] = $r;
}
for ($i=$Nk; $i<($Nb*($Nr+1)); $i++) {
$w[$i] = array();
for ($t=0; $t<4; $t++) $temp[$t] = $w[$i-1][$t];
if ($i % $Nk == 0) {
$temp = self::subWord(self::rotWord($temp));
for ($t=0; $t<4; $t++) $temp[$t] ^= self::$rCon[$i/$Nk][$t];
} else if ($Nk > 6 && $i%$Nk == 4) {
$temp = self::subWord($temp);
}
for ($t=0; $t<4; $t++) $w[$i][$t] = $w[$i-$Nk][$t] ^ $temp[$t];
}
return $w;
}
private static function subWord($w) { // apply SBox to 4-byte word w
for ($i=0; $i<4; $i++) $w[$i] = self::$sBox[$w[$i]];
return $w;
}
private static function rotWord($w) { // rotate 4-byte word w left by one byte
$tmp = $w[0];
for ($i=0; $i<3; $i++) $w[$i] = $w[$i+1];
$w[3] = $tmp;
return $w;
}
// sBox is pre-computed multiplicative inverse in GF(2^8) used in subBytes and keyExpansion [§5.1.1]
private static $sBox = array(
0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5,0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76,
0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0,0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0,
0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc,0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15,
0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a,0x07,0x12,0x80,0xe2,0xeb,0x27,0xb2,0x75,
0x09,0x83,0x2c,0x1a,0x1b,0x6e,0x5a,0xa0,0x52,0x3b,0xd6,0xb3,0x29,0xe3,0x2f,0x84,
0x53,0xd1,0x00,0xed,0x20,0xfc,0xb1,0x5b,0x6a,0xcb,0xbe,0x39,0x4a,0x4c,0x58,0xcf,
0xd0,0xef,0xaa,0xfb,0x43,0x4d,0x33,0x85,0x45,0xf9,0x02,0x7f,0x50,0x3c,0x9f,0xa8,
0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5,0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2,
0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17,0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73,
0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88,0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb,
0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c,0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79,
0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9,0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08,
0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6,0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a,
0x70,0x3e,0xb5,0x66,0x48,0x03,0xf6,0x0e,0x61,0x35,0x57,0xb9,0x86,0xc1,0x1d,0x9e,
0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94,0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf,
0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68,0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16);
// rCon is Round Constant used for the Key Expansion [1st col is 2^(r-1) in GF(2^8)] [§5.2]
private static $rCon = array(
array(0x00, 0x00, 0x00, 0x00),
array(0x01, 0x00, 0x00, 0x00),
array(0x02, 0x00, 0x00, 0x00),
array(0x04, 0x00, 0x00, 0x00),
array(0x08, 0x00, 0x00, 0x00),
array(0x10, 0x00, 0x00, 0x00),
array(0x20, 0x00, 0x00, 0x00),
array(0x40, 0x00, 0x00, 0x00),
array(0x80, 0x00, 0x00, 0x00),
array(0x1b, 0x00, 0x00, 0x00),
array(0x36, 0x00, 0x00, 0x00) );
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
?>

View File

@@ -0,0 +1,164 @@
<?php
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* AES counter (CTR) mode implementation in PHP (c) Chris Veness 2005-2011. Right of free use is */
/* granted for all commercial or non-commercial use under CC-BY licence. No warranty of any */
/* form is offered. */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
class AesCtr extends Aes {
/**
* Encrypt a text using AES encryption in Counter mode of operation
* - see http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf
*
* Unicode multi-byte character safe
*
* @param plaintext source text to be encrypted
* @param password the password to use to generate a key
* @param nBits number of bits to be used in the key (128, 192, or 256)
* @return encrypted text
*/
public static function encrypt($plaintext, $password, $nBits) {
$blockSize = 16; // block size fixed at 16 bytes / 128 bits (Nb=4) for AES
if (!($nBits==128 || $nBits==192 || $nBits==256)) return ''; // standard allows 128/192/256 bit keys
// note PHP (5) gives us plaintext and password in UTF8 encoding!
// use AES itself to encrypt password to get cipher key (using plain password as source for
// key expansion) - gives us well encrypted key
$nBytes = $nBits/8; // no bytes in key
$pwBytes = array();
for ($i=0; $i<$nBytes; $i++) $pwBytes[$i] = ord(substr($password,$i,1)) & 0xff;
$key = Aes::cipher($pwBytes, Aes::keyExpansion($pwBytes));
$key = array_merge($key, array_slice($key, 0, $nBytes-16)); // expand key to 16/24/32 bytes long
// initialise 1st 8 bytes of counter block with nonce (NIST SP800-38A §B.2): [0-1] = millisec,
// [2-3] = random, [4-7] = seconds, giving guaranteed sub-ms uniqueness up to Feb 2106
$counterBlock = array();
$nonce = floor(microtime(true)*1000); // timestamp: milliseconds since 1-Jan-1970
$nonceMs = $nonce%1000;
$nonceSec = floor($nonce/1000);
$nonceRnd = floor(rand(0, 0xffff));
for ($i=0; $i<2; $i++) $counterBlock[$i] = self::urs($nonceMs, $i*8) & 0xff;
for ($i=0; $i<2; $i++) $counterBlock[$i+2] = self::urs($nonceRnd, $i*8) & 0xff;
for ($i=0; $i<4; $i++) $counterBlock[$i+4] = self::urs($nonceSec, $i*8) & 0xff;
// and convert it to a string to go on the front of the ciphertext
$ctrTxt = '';
for ($i=0; $i<8; $i++) $ctrTxt .= chr($counterBlock[$i]);
// generate key schedule - an expansion of the key into distinct Key Rounds for each round
$keySchedule = Aes::keyExpansion($key);
//print_r($keySchedule);
$blockCount = ceil(strlen($plaintext)/$blockSize);
$ciphertxt = array(); // ciphertext as array of strings
for ($b=0; $b<$blockCount; $b++) {
// set counter (block #) in last 8 bytes of counter block (leaving nonce in 1st 8 bytes)
// done in two stages for 32-bit ops: using two words allows us to go past 2^32 blocks (68GB)
for ($c=0; $c<4; $c++) $counterBlock[15-$c] = self::urs($b, $c*8) & 0xff;
for ($c=0; $c<4; $c++) $counterBlock[15-$c-4] = self::urs($b/0x100000000, $c*8);
$cipherCntr = Aes::cipher($counterBlock, $keySchedule); // -- encrypt counter block --
// block size is reduced on final block
$blockLength = $b<$blockCount-1 ? $blockSize : (strlen($plaintext)-1)%$blockSize+1;
$cipherByte = array();
for ($i=0; $i<$blockLength; $i++) { // -- xor plaintext with ciphered counter byte-by-byte --
$cipherByte[$i] = $cipherCntr[$i] ^ ord(substr($plaintext, $b*$blockSize+$i, 1));
$cipherByte[$i] = chr($cipherByte[$i]);
}
$ciphertxt[$b] = implode('', $cipherByte); // escape troublesome characters in ciphertext
}
// implode is more efficient than repeated string concatenation
$ciphertext = $ctrTxt . implode('', $ciphertxt);
$ciphertext = base64_encode($ciphertext);
return $ciphertext;
}
/**
* Decrypt a text encrypted by AES in counter mode of operation
*
* @param ciphertext source text to be decrypted
* @param password the password to use to generate a key
* @param nBits number of bits to be used in the key (128, 192, or 256)
* @return decrypted text
*/
public static function decrypt($ciphertext, $password, $nBits) {
$blockSize = 16; // block size fixed at 16 bytes / 128 bits (Nb=4) for AES
if (!($nBits==128 || $nBits==192 || $nBits==256)) return ''; // standard allows 128/192/256 bit keys
$ciphertext = base64_decode($ciphertext);
// use AES to encrypt password (mirroring encrypt routine)
$nBytes = $nBits/8; // no bytes in key
$pwBytes = array();
for ($i=0; $i<$nBytes; $i++) $pwBytes[$i] = ord(substr($password,$i,1)) & 0xff;
$key = Aes::cipher($pwBytes, Aes::keyExpansion($pwBytes));
$key = array_merge($key, array_slice($key, 0, $nBytes-16)); // expand key to 16/24/32 bytes long
// recover nonce from 1st element of ciphertext
$counterBlock = array();
$ctrTxt = substr($ciphertext, 0, 8);
for ($i=0; $i<8; $i++) $counterBlock[$i] = ord(substr($ctrTxt,$i,1));
// generate key schedule
$keySchedule = Aes::keyExpansion($key);
// separate ciphertext into blocks (skipping past initial 8 bytes)
$nBlocks = ceil((strlen($ciphertext)-8) / $blockSize);
$ct = array();
for ($b=0; $b<$nBlocks; $b++) $ct[$b] = substr($ciphertext, 8+$b*$blockSize, 16);
$ciphertext = $ct; // ciphertext is now array of block-length strings
// plaintext will get generated block-by-block into array of block-length strings
$plaintxt = array();
for ($b=0; $b<$nBlocks; $b++) {
// set counter (block #) in last 8 bytes of counter block (leaving nonce in 1st 8 bytes)
for ($c=0; $c<4; $c++) $counterBlock[15-$c] = self::urs($b, $c*8) & 0xff;
for ($c=0; $c<4; $c++) $counterBlock[15-$c-4] = self::urs(($b+1)/0x100000000-1, $c*8) & 0xff;
$cipherCntr = Aes::cipher($counterBlock, $keySchedule); // encrypt counter block
$plaintxtByte = array();
for ($i=0; $i<strlen($ciphertext[$b]); $i++) {
// -- xor plaintext with ciphered counter byte-by-byte --
$plaintxtByte[$i] = $cipherCntr[$i] ^ ord(substr($ciphertext[$b],$i,1));
$plaintxtByte[$i] = chr($plaintxtByte[$i]);
}
$plaintxt[$b] = implode('', $plaintxtByte);
}
// join array of blocks into single plaintext string
$plaintext = implode('',$plaintxt);
return $plaintext;
}
/*
* Unsigned right shift function, since PHP has neither >>> operator nor unsigned ints
*
* @param a number to be shifted (32-bit integer)
* @param b number of bits to shift a to the right (0..31)
* @return a right-shifted and zero-filled by b bits
*/
private static function urs($a, $b) {
$a &= 0xffffffff; $b &= 0x1f; // (bounds check)
if ($a&0x80000000 && $b>0) { // if left-most bit set
$a = ($a>>1) & 0x7fffffff; // right-shift one bit & clear left-most bit
$a = $a >> ($b-1); // remaining right-shifts
} else { // otherwise
$a = ($a>>$b); // use normal right-shift
}
return $a;
}
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
?>