App::uses('Component', 'Controller');
class UtilComponent extends Component {
public $SMS = null;
public $controller;
public function initialize(Controller $controller) {
// saving the controller reference for later use
$this->controller =& $controller;
}
function userHasPrivilage($UserId,$privilege,$value=0) {
$privilegesText = $this->controller->DB->getOne("select privileges from users u where u.email = ?",array($UserId));
$privileges = preg_split('/[\s,;]+/',$privilegesText);
if(in_array('admin',$privileges)) return true;
if(in_array($privilege,$privileges)) return true;
return false;
}
function AuditControl() {
//$this->controller->log('AuditControl Request = [%s]',prr($this->controller->request));
$Request = $this->controller->request;
if(!empty($Request->params['pass'])) $AuditData['pass']=$Request->params['pass'];
if(!empty($Request->data)) $AuditData['data']=$Request->data;
if(!empty($Request->query)) $AuditData['query']=$Request->query;
if(!empty($AuditData)) {
$AuditData['HTTP_USER_AGENT'] = $_SERVER['HTTP_USER_AGENT'];
$Stmt = $this->controller->DB->prepare("insert into user_audit (username, created_dtm, action, msisdn, arguments, ip) values (?,now(),?,?,?,?)");
$Ret = $this->controller->DB->execute(
$Stmt,
array(
$this->controller->user,
nvl($Request->params['controller']).'/'.nvl($Request->params['action']),
'',
json_encode($AuditData),
$_SERVER['REMOTE_ADDR']
)
);
if (PEAR::isError($Ret)) {
$this->controller->error("Unable to insert audit. Error [%s]",$Ret->getMessage());
}
}
}
function GetFormDetails($formId = null,$data=array()) {
if (empty($formId) ) {
$this->controller->Session->setFlash("Form Id should be specified"."error");
return false;
}
if(!empty($data) && is_array($data)) {extract($data,EXTR_OVERWRITE);}
$this->controller->log('data=[%s]',prr($data));
//Get Report Details;
$FormDetails = $this->controller->DB->getRow("select * from ajax_forms where form_id=?", array($formId), DB_FETCHMODE_ASSOC);
if (empty($FormDetails) ) {
$this->controller->Session->setFlash("Could not find the specified form [$formId]","error");
return false;
}
//Get the Report parameters;
$FormFields = $this->controller->DB->getAll("select * from ajax_forms_parameters where form_id=? order by order_num", array($formId), DB_FETCHMODE_ASSOC);
foreach ($FormFields as &$FF) {
if (!empty($FF['selection_list_type'])) {
if ($FF['selection_list_type'] == 'IVP') {
$lines = explode("\n",$FF['selection_list_values_text']);
foreach ($lines as $line ) {
if (empty($line)) continue;
$data = explode(";",$line);
$FF['selection_list'][strval(stripslashes(trim(trim($data[0]),"\"")))]=stripslashes(trim(trim($data[1]),"\""));
}
}
else if (($FF['selection_list_type'] == 'SSV') || ($FF['selection_list_type'] == 'CSV')) {
$FF['selection_list'] = explode(";",$FF['selection_list_values_text']);
}
else if (preg_match("/^DB-(.+)/",$FF['selection_list_type'],$matches)) {
if(empty($matches[1])) {
$this->controller->Session->setFlash("Data Base is not defined for the parameter [{$FF['parameter_id']}]","error");
return false;
}
$Dsl = $matches[1];
$this->controller->ConnectToDsl($Dsl);
if(empty($FF['selection_list_values_text'])) {
$this->controller->Session->setFlash("Select List SQL is not defined for the parameter [{$FF['parameter_id']}]","error");
return false;
}
preg_match_all ("/\?\[([^\]]*)\]/",$FF['selection_list_values_text'],$matches);
$binds = array();
$sql =$FF['selection_list_values_text'];
if (!empty($matches[1])) foreach ($matches[1] as $ParamId) {
$sql = str_replace("?[$ParamId]","?",$sql);
$binds[] = nvl($data[$ParamId]);
$this->log('Binding [%s] with [%s]',$ParamId,nvl($data[$ParamId]));
}
$this->log('Binds are [%s]',prr($binds));
$Ret = $this->controller->$Dsl->getAll($sql,$binds);
if (PEAR::isError($Ret)) {
$this->controller->Session->setFlash(sprintf("Could not get selection list for [{$FF['parameter_id']}]. Error %s",$Ret->getMessage()),"error");
return false;
}
foreach($Ret as $R){
$FF['selection_list'][$R[0]]=$R[1];
}
}
}
}
return (array(
'FormDetails' => $FormDetails,
'FormFields' => $FormFields
));
}
function SendSms($msisdns=null,$message=null, $senderId='infOOman', $arguments=array(),$p_options=array()) {
$options = array_merge(array(
'priority'=>5,
'args'=>'numbers',
), $p_options);
if(empty($msisdns) || empty($message)) {
$this->controller->error("To/Message arguments are not passed.");
return false;
}
//Convert CSV list of MSISDNs to array.
if (is_string($msisdns)) {
if(preg_match("/,/",$msisdns)) {
$msisdns = explode(",",$msisdns);
} else if(preg_match("/;/",$msisdns)) {
$msisdns = explode(";",$msisdns);
} else {
$msisdns = explode(",",$msisdns);
}
}
//Replace the arguments
if (!empty($arguments)) {
if($options['args']=='numbers') {
$message = vsprintf($message,$arguments);
} else {
$message = vnsprintf($message,$arguments);
}
}
//For each number as per language
$InsertSmsQSql="insert into sms_q(`from`,`to`,`message`,`priority`,`unicode`, schedule_dtm) values(?,?,?,?,?,?)";
$InsertSmsQStmt=$this->controller->DB->prepare($InsertSmsQSql);
sort($msisdns);
$Unicode = 0;
$message = trim ($message);
if (strlen($message) != strlen(utf8_decode($message))) {
$Unicode = 1;
}
//Insert into SMS Q table.
$errors = 0;
foreach($msisdns as $msisdn) {
$Ret = $this->controller->DB->execute($InsertSmsQStmt,array(
$senderId,
'+968'.$msisdn,
$message,
$options['priority'],
$Unicode,
nvl($options['schedule_dtm'],date('Y-m-d H:i:s'))
));
if (PEAR::isError($Ret)) {
$this->controller->error("Error While Q'ing the SMS to [%s]. %s", $msisdn, $Ret->getMessage() );
$errors++;
continue;
}
$this->controller->log('SMS sent to [%s]',$msisdn);
}
if (!empty($errors))
return false;
else
return true;
}
function SendMail($to,$subject,$content,$p_options=array()) {
$args = func_get_args();
$options = array_merge(
array(
'sendAs'=>'text',
'template'=>'default',
'set'=>'',
'attachments'=>array(),
'from'=>array('praveen@infooman.com' => 'Info Oman')
), $p_options);
$this->controller->trace("Arguments [%s]",print_r($args,true));
if (empty($to)) {
throw new SoapFault("1000", "to email address should be provided");
}
if (empty($subject)) {
throw new SoapFault("1000", "email subject should be provided");
}
try {
App::uses('CakeEmail', 'Network/Email');
$Email = new CakeEmail();
$Email->config('smtp');
$Email->from($options['from'])
->to($to)
->subject($subject)
->template($options['template'])
->attachments($options['attachments'])
->send($content);
$this->controller->trace("Email Sent..");
}
catch (Exception $e) {
$this->controller->error("Unable to send email. Error [%s]",$e->getMessage);
$this->controller->log("Email service arguments are [%s]",print_r($args,true));
return $e;
}
}
function SendTextMail($to,$subject,$content,$p_options=array()) {
$options = array_merge(array('sendAs'=>'text'),$p_options);
$this->SendMail($to,$subject,$content,$options);
}
function SendHtmlMail($to,$subject,$content,$p_options=array()) {
$options = array_merge(array('sendAs'=>'html'),$p_options);
$this->SendMail($to,$subject,$content,$options);
}
public function QSMSText($to, $text, $args=array(), $options=array()) {
$defaultOptions = array(
'args'=>'numbers',
'from'=>'MuscatDeals',
'type'=>'text',
'instantsend'=>false,
'priority'=>5
);
$options = array_merge($defaultOptions,$options);
if (empty($to)) {
$this->controller->error("To Mobile number is not specified.");
throw new SoapFault("1","To Mobile number is not specified.");
}
if (empty($text)) {
$this->controller->error("Message text is not specified.");
throw new SoapFault("1","Message text is not specified.");
}
if(!empty($args)) {
if($options['args']=='numbers') {
$text = vsprintf($text,$args);
} else {
$text = vnsprintf($text,$args);
}
}
if (is_string($to)) {
if(preg_match("/,/",$to)) {
$to = explode(",",$to);
} else if(preg_match("/;/",$to)) {
$to = explode(";",$to);
} else {
$to = explode(",",$to);
}
}
$this->controller->ConnectToDsl("SMS");
foreach ($to as $Number) {
$status = $this->controller->SMS->execute($this->controller->SMS->prepare("insert into sms_q(`from`, `to`, `message`, `type`,`priority`,`schedule_dtm`) values(?,?,?,?,?, now())"),array($options['from'],$Number,$text,$options['type'],$options['priority']));
if (PEAR::isError($status)) {
$errMsg = sprintf("Error While Queing SMS to [%s]. [%s]",$Number,$status->getMessage());
$this->controller->error($errMsg);
throw new SoapFault("1",$errMsg);
}
/*
if($options['instantsend']) {
//Get the inserted msg Id
$id = $this->controller->SMS->getOne("select id from sms_q where to=? order by id desc",array($Number));
$this->QSMSSend($id);
}
*/
}
return true;
}
public function QSMSTemplate($to,$template=null,$args=array(), $options=array()) {
if(!isset($template)) {
throw new SoapFault("1","template (2nd argument) is not set.");
}
$templateId = -999;
$templateName= "fgkjsadggsdahkdkjsaghjs";
if(is_int($template)) {
$templateId = $template;
}else if(is_string($template)) {
$templateName = $template;
} else {
throw new SoapFault("2","template (2nd argument) is not of valid type.");
}
$this->controller->ConnectToDsl("SMS");
$templateInfo = $this->controller->SMS->getRow("select * from sms_templates where id=? or template_name=?", array($templateId, $templateName), DB_FETCHMODE_ASSOC);
if (PEAR::isError($templateInfo)) {
$errMsg = sprintf("Unable to get template for [%s]. [%s]",$template,$templateInfo->getMessage());
$this->controller->error($errMsg);
throw new SoapFault("1",$errMsg);
}
if(empty($templateInfo)){
throw new SoapFault("3","No template found with [$template]");
}
if(!empty($templateInfo['type'])) $options['type']=$templateInfo['type'];
$this->QSMSText($to, $templateInfo['text'], $args, $options);
}
function pushbullet($to=null, $title=null, $body=null, $url=null) {
$AccessToken = 'v1Ppsf4UkDuYWcLHht2shB14e8H2fJFpFTujyVcLJ9lUi';
$data = array();
//Check if $to is a email then set email.
if(preg_match('/@/',$to)) {
$data['email'] = $to;
} else {
$data['channel_tag'] = $to;
}
if(!empty($url)) {
$data['type'] = 'link';
$data['url'] = $url;
} else {
$data['type'] = 'note';
}
$data['title'] = $title;
$data['body'] = $body;
$this->controller->trace('data=[%s]',prr($data));
App::uses('HttpSocket', 'Network/Http');
$HttpSocket = new HttpSocket();
$request=array('header'=>array('Authorization'=>"Bearer $AccessToken"));
$response = $HttpSocket->post('https://api.pushbullet.com/v2/pushes', $data,$request);
$code = $response->code;
$body = $response->body;
$responseJson = json_decode($response->body,true);
if(!empty($responseJson)) {
$this->controller->trace('Response=[%s]',prr($responseJson));
}
if($response->code != 200) {
$this->controller->error("Unable to send push. Response code [%s]",$response->code);
} else {
$this->log("Pushed successfuly to [%s], title [%s]",$to,$title);
}
}
}
App::uses('Component', 'Controller');
class UtilComponent extends Component {
public $SMS = null;
public $controller;
public function initialize(Controller $controller) {
// saving the controller reference for later use
$this->controller =& $controller;
}
function userHasPrivilage($UserId,$privilege,$value=0) {
$privilegesText = $this->controller->DB->getOne("select privileges from users u where u.email = ?",array($UserId));
$privileges = preg_split('/[\s,;]+/',$privilegesText);
if(in_array('admin',$privileges)) return true;
if(in_array($privilege,$privileges)) return true;
return false;
}
function AuditControl() {
//$this->controller->log('AuditControl Request = [%s]',prr($this->controller->request));
$Request = $this->controller->request;
if(!empty($Request->params['pass'])) $AuditData['pass']=$Request->params['pass'];
if(!empty($Request->data)) $AuditData['data']=$Request->data;
if(!empty($Request->query)) $AuditData['query']=$Request->query;
if(!empty($AuditData)) {
$AuditData['HTTP_USER_AGENT'] = $_SERVER['HTTP_USER_AGENT'];
$Stmt = $this->controller->DB->prepare("insert into user_audit (username, created_dtm, action, msisdn, arguments, ip) values (?,now(),?,?,?,?)");
$Ret = $this->controller->DB->execute(
$Stmt,
array(
$this->controller->user,
nvl($Request->params['controller']).'/'.nvl($Request->params['action']),
'',
json_encode($AuditData),
$_SERVER['REMOTE_ADDR']
)
);
if (PEAR::isError($Ret)) {
$this->controller->error("Unable to insert audit. Error [%s]",$Ret->getMessage());
}
}
}
function GetFormDetails($formId = null,$data=array()) {
if (empty($formId) ) {
$this->controller->Session->setFlash("Form Id should be specified"."error");
return false;
}
if(!empty($data) && is_array($data)) {extract($data,EXTR_OVERWRITE);}
$this->controller->log('data=[%s]',prr($data));
//Get Report Details;
$FormDetails = $this->controller->DB->getRow("select * from ajax_forms where form_id=?", array($formId), DB_FETCHMODE_ASSOC);
if (empty($FormDetails) ) {
$this->controller->Session->setFlash("Could not find the specified form [$formId]","error");
return false;
}
//Get the Report parameters;
$FormFields = $this->controller->DB->getAll("select * from ajax_forms_parameters where form_id=? order by order_num", array($formId), DB_FETCHMODE_ASSOC);
foreach ($FormFields as &$FF) {
if (!empty($FF['selection_list_type'])) {
if ($FF['selection_list_type'] == 'IVP') {
$lines = explode("\n",$FF['selection_list_values_text']);
foreach ($lines as $line ) {
if (empty($line)) continue;
$data = explode(";",$line);
$FF['selection_list'][strval(stripslashes(trim(trim($data[0]),"\"")))]=stripslashes(trim(trim($data[1]),"\""));
}
}
else if (($FF['selection_list_type'] == 'SSV') || ($FF['selection_list_type'] == 'CSV')) {
$FF['selection_list'] = explode(";",$FF['selection_list_values_text']);
}
else if (preg_match("/^DB-(.+)/",$FF['selection_list_type'],$matches)) {
if(empty($matches[1])) {
$this->controller->Session->setFlash("Data Base is not defined for the parameter [{$FF['parameter_id']}]","error");
return false;
}
$Dsl = $matches[1];
$this->controller->ConnectToDsl($Dsl);
if(empty($FF['selection_list_values_text'])) {
$this->controller->Session->setFlash("Select List SQL is not defined for the parameter [{$FF['parameter_id']}]","error");
return false;
}
preg_match_all ("/\?\[([^\]]*)\]/",$FF['selection_list_values_text'],$matches);
$binds = array();
$sql =$FF['selection_list_values_text'];
if (!empty($matches[1])) foreach ($matches[1] as $ParamId) {
$sql = str_replace("?[$ParamId]","?",$sql);
$binds[] = nvl($data[$ParamId]);
$this->log('Binding [%s] with [%s]',$ParamId,nvl($data[$ParamId]));
}
$this->log('Binds are [%s]',prr($binds));
$Ret = $this->controller->$Dsl->getAll($sql,$binds);
if (PEAR::isError($Ret)) {
$this->controller->Session->setFlash(sprintf("Could not get selection list for [{$FF['parameter_id']}]. Error %s",$Ret->getMessage()),"error");
return false;
}
foreach($Ret as $R){
$FF['selection_list'][$R[0]]=$R[1];
}
}
}
}
return (array(
'FormDetails' => $FormDetails,
'FormFields' => $FormFields
));
}
function SendSms($msisdns=null,$message=null, $senderId='infOOman', $arguments=array(),$p_options=array()) {
$options = array_merge(array(
'priority'=>5,
'args'=>'numbers',
), $p_options);
if(empty($msisdns) || empty($message)) {
$this->controller->error("To/Message arguments are not passed.");
return false;
}
//Convert CSV list of MSISDNs to array.
if (is_string($msisdns)) {
if(preg_match("/,/",$msisdns)) {
$msisdns = explode(",",$msisdns);
} else if(preg_match("/;/",$msisdns)) {
$msisdns = explode(";",$msisdns);
} else {
$msisdns = explode(",",$msisdns);
}
}
//Replace the arguments
if (!empty($arguments)) {
if($options['args']=='numbers') {
$message = vsprintf($message,$arguments);
} else {
$message = vnsprintf($message,$arguments);
}
}
//For each number as per language
$InsertSmsQSql="insert into sms_q(`from`,`to`,`message`,`priority`,`unicode`, schedule_dtm) values(?,?,?,?,?,?)";
$InsertSmsQStmt=$this->controller->DB->prepare($InsertSmsQSql);
sort($msisdns);
$Unicode = 0;
$message = trim ($message);
if (strlen($message) != strlen(utf8_decode($message))) {
$Unicode = 1;
}
//Insert into SMS Q table.
$errors = 0;
foreach($msisdns as $msisdn) {
$Ret = $this->controller->DB->execute($InsertSmsQStmt,array(
$senderId,
'+968'.$msisdn,
$message,
$options['priority'],
$Unicode,
nvl($options['schedule_dtm'],date('Y-m-d H:i:s'))
));
if (PEAR::isError($Ret)) {
$this->controller->error("Error While Q'ing the SMS to [%s]. %s", $msisdn, $Ret->getMessage() );
$errors++;
continue;
}
$this->controller->log('SMS sent to [%s]',$msisdn);
}
if (!empty($errors))
return false;
else
return true;
}
function SendMail($to,$subject,$content,$p_options=array()) {
$args = func_get_args();
$options = array_merge(
array(
'sendAs'=>'text',
'template'=>'default',
'set'=>'',
'attachments'=>array(),
'from'=>array('praveen@infooman.com' => 'Info Oman')
), $p_options);
$this->controller->trace("Arguments [%s]",print_r($args,true));
if (empty($to)) {
throw new SoapFault("1000", "to email address should be provided");
}
if (empty($subject)) {
throw new SoapFault("1000", "email subject should be provided");
}
try {
App::uses('CakeEmail', 'Network/Email');
$Email = new CakeEmail();
$Email->config('smtp');
$Email->from($options['from'])
->to($to)
->subject($subject)
->template($options['template'])
->attachments($options['attachments'])
->send($content);
$this->controller->trace("Email Sent..");
}
catch (Exception $e) {
$this->controller->error("Unable to send email. Error [%s]",$e->getMessage);
$this->controller->log("Email service arguments are [%s]",print_r($args,true));
return $e;
}
}
function SendTextMail($to,$subject,$content,$p_options=array()) {
$options = array_merge(array('sendAs'=>'text'),$p_options);
$this->SendMail($to,$subject,$content,$options);
}
function SendHtmlMail($to,$subject,$content,$p_options=array()) {
$options = array_merge(array('sendAs'=>'html'),$p_options);
$this->SendMail($to,$subject,$content,$options);
}
public function QSMSText($to, $text, $args=array(), $options=array()) {
$defaultOptions = array(
'args'=>'numbers',
'from'=>'MuscatDeals',
'type'=>'text',
'instantsend'=>false,
'priority'=>5
);
$options = array_merge($defaultOptions,$options);
if (empty($to)) {
$this->controller->error("To Mobile number is not specified.");
throw new SoapFault("1","To Mobile number is not specified.");
}
if (empty($text)) {
$this->controller->error("Message text is not specified.");
throw new SoapFault("1","Message text is not specified.");
}
if(!empty($args)) {
if($options['args']=='numbers') {
$text = vsprintf($text,$args);
} else {
$text = vnsprintf($text,$args);
}
}
if (is_string($to)) {
if(preg_match("/,/",$to)) {
$to = explode(",",$to);
} else if(preg_match("/;/",$to)) {
$to = explode(";",$to);
} else {
$to = explode(",",$to);
}
}
$this->controller->ConnectToDsl("SMS");
foreach ($to as $Number) {
$status = $this->controller->SMS->execute($this->controller->SMS->prepare("insert into sms_q(`from`, `to`, `message`, `type`,`priority`,`schedule_dtm`) values(?,?,?,?,?, now())"),array($options['from'],$Number,$text,$options['type'],$options['priority']));
if (PEAR::isError($status)) {
$errMsg = sprintf("Error While Queing SMS to [%s]. [%s]",$Number,$status->getMessage());
$this->controller->error($errMsg);
throw new SoapFault("1",$errMsg);
}
/*
if($options['instantsend']) {
//Get the inserted msg Id
$id = $this->controller->SMS->getOne("select id from sms_q where to=? order by id desc",array($Number));
$this->QSMSSend($id);
}
*/
}
return true;
}
public function QSMSTemplate($to,$template=null,$args=array(), $options=array()) {
if(!isset($template)) {
throw new SoapFault("1","template (2nd argument) is not set.");
}
$templateId = -999;
$templateName= "fgkjsadggsdahkdkjsaghjs";
if(is_int($template)) {
$templateId = $template;
}else if(is_string($template)) {
$templateName = $template;
} else {
throw new SoapFault("2","template (2nd argument) is not of valid type.");
}
$this->controller->ConnectToDsl("SMS");
$templateInfo = $this->controller->SMS->getRow("select * from sms_templates where id=? or template_name=?", array($templateId, $templateName), DB_FETCHMODE_ASSOC);
if (PEAR::isError($templateInfo)) {
$errMsg = sprintf("Unable to get template for [%s]. [%s]",$template,$templateInfo->getMessage());
$this->controller->error($errMsg);
throw new SoapFault("1",$errMsg);
}
if(empty($templateInfo)){
throw new SoapFault("3","No template found with [$template]");
}
if(!empty($templateInfo['type'])) $options['type']=$templateInfo['type'];
$this->QSMSText($to, $templateInfo['text'], $args, $options);
}
function pushbullet($to=null, $title=null, $body=null, $url=null) {
$AccessToken = 'v1Ppsf4UkDuYWcLHht2shB14e8H2fJFpFTujyVcLJ9lUi';
$data = array();
//Check if $to is a email then set email.
if(preg_match('/@/',$to)) {
$data['email'] = $to;
} else {
$data['channel_tag'] = $to;
}
if(!empty($url)) {
$data['type'] = 'link';
$data['url'] = $url;
} else {
$data['type'] = 'note';
}
$data['title'] = $title;
$data['body'] = $body;
$this->controller->trace('data=[%s]',prr($data));
App::uses('HttpSocket', 'Network/Http');
$HttpSocket = new HttpSocket();
$request=array('header'=>array('Authorization'=>"Bearer $AccessToken"));
$response = $HttpSocket->post('https://api.pushbullet.com/v2/pushes', $data,$request);
$code = $response->code;
$body = $response->body;
$responseJson = json_decode($response->body,true);
if(!empty($responseJson)) {
$this->controller->trace('Response=[%s]',prr($responseJson));
}
if($response->code != 200) {
$this->controller->error("Unable to send push. Response code [%s]",$response->code);
} else {
$this->log("Pushed successfuly to [%s], title [%s]",$to,$title);
}
}
}
CakePHP: the rapid development php framework:
Errors
Missing Component
Error:
UtilComponent could not be found.
Error:
Create the class UtilComponent below in file: rm.om.dev/Controller/Component/UtilComponent.php
<?php
class UtilComponent extends Component {
}
Notice:
If you want to customize this error message, create rm.om.dev/View/Errors/missing_component.ctp
Stack Trace