From eb76d3bbaf14e1aa111224206fae7ea95c26f810 Mon Sep 17 00:00:00 2001
From: Peter Rotich <peter@osticket.com>
Date: Fri, 5 Dec 2014 05:59:49 +0000
Subject: [PATCH] orm: Convert SLA to ORM

---
 include/class.i18n.php         |   2 +-
 include/class.sla.php          | 216 ++++++++++++++-------------------
 include/staff/slaplans.inc.php |  98 ++++++++-------
 scp/slas.php                   |  27 +++--
 4 files changed, 163 insertions(+), 180 deletions(-)

diff --git a/include/class.i18n.php b/include/class.i18n.php
index c0dc5388b..b208feb0e 100644
--- a/include/class.i18n.php
+++ b/include/class.i18n.php
@@ -50,7 +50,7 @@ class Internationalization {
         # notrans -- do not translate the contents of this array
         $models = array(
             'department.yaml' =>    'Dept::__create',
-            'sla.yaml' =>           'SLA::create',
+            'sla.yaml' =>           'SLA::__create',
             'form.yaml' =>          'DynamicForm::create',
             'list.yaml' =>          'DynamicList::create',
             // Note that department, sla, and forms are required for
diff --git a/include/class.sla.php b/include/class.sla.php
index 490508660..083663695 100644
--- a/include/class.sla.php
+++ b/include/class.sla.php
@@ -3,7 +3,6 @@
     class.sla.php
 
     SLA
-
     Peter Rotich <peter@osticket.com>
     Copyright (c)  2006-2013 osTicket
     http://www.osticket.com
@@ -14,75 +13,54 @@
     vim: expandtab sw=4 ts=4 sts=4:
 **********************************************************************/
 
-class SlaModel extends VerySimpleModel {
+class SLA extends VerySimpleModel {
+
     static $meta = array(
         'table' => SLA_TABLE,
-        'pk' => array('sla_id'),
+        'pk' => array('id'),
     );
-}
-
-class SLA {
-
-    var $id;
-
-    var $info;
-    var $config;
-
-    function SLA($id) {
-        $this->id=0;
-        $this->load($id);
-    }
 
-    function load($id=0) {
+    //TODO: Use flags
 
-        if(!$id && !($id=$this->getId()))
-            return false;
-
-        $sql='SELECT * FROM '.SLA_TABLE.' WHERE id='.db_input($id);
-        if(!($res=db_query($sql)) || !db_num_rows($res))
-            return false;
-
-        $this->ht=db_fetch_array($res);
-        $this->id=$this->ht['id'];
-        return true;
-    }
-
-    function reload() {
-        return $this->load();
-    }
+    var $_config;
 
     function getId() {
         return $this->id;
     }
 
     function getName() {
-        return $this->ht['name'];
+        return $this->name;
     }
 
     function getGracePeriod() {
-        return $this->ht['grace_period'];
-    }
-
-    function getNotes() {
-        return $this->ht['notes'];
+        return $this->grace_period;
     }
 
     function getHashtable() {
-        return array_merge($this->getConfig()->getInfo(), $this->ht);
+        $this->getHashtable();
     }
 
     function getInfo() {
-        return $this->getHashtable();
+        return array_merge($this->getConfig()->getInfo(), $this->ht);
     }
 
     function getConfig() {
-        if (!isset($this->config))
-            $this->config = new SlaConfig($this->getId());
-        return $this->config;
+        if (!isset($this->_config))
+            $this->_config = new SlaConfig($this->getId());
+
+        return $this->_config;
+    }
+
+    function getCreateDate() {
+        return $this->created;
+    }
+
+    function getUpdateDate() {
+        return $this->updated;
     }
 
     function isActive() {
-        return ($this->ht['isactive']);
+        return ($this->isactive);
     }
 
     function isTransient() {
@@ -90,7 +68,7 @@ class SLA {
     }
 
     function sendAlerts() {
-        return (!$this->ht['disable_overdue_alerts']);
+        return $this->disable_overdue_alerts;
     }
 
     function alertOnOverdue() {
@@ -98,32 +76,68 @@ class SLA {
     }
 
     function priorityEscalation() {
-        return ($this->ht['enable_priority_escalation']);
+        return ($this->enable_priority_escalation);
     }
 
     function getTranslateTag($subtag) {
-        return _H(sprintf('sla.%s.%s', $subtag, $this->id));
+        return _H(sprintf('sla.%s.%s', $subtag, $this->getId()));
     }
+
     function getLocal($subtag) {
         $tag = $this->getTranslateTag($subtag);
         $T = CustomDataTranslation::translate($tag);
         return $T != $tag ? $T : $this->ht[$subtag];
     }
+
     static function getLocalById($id, $subtag, $default) {
         $tag = _H(sprintf('sla.%s.%s', $subtag, $id));
         $T = CustomDataTranslation::translate($tag);
         return $T != $tag ? $T : $default;
     }
 
-    function update($vars,&$errors) {
+    function update($vars, &$errors) {
+
+        if (!$vars['grace_period'])
+            $errors['grace_period'] = __('Grace period required');
+        elseif (!is_numeric($vars['grace_period']))
+            $errors['grace_period'] = __('Numeric value required (in hours)');
 
-        if(!SLA::save($this->getId(),$vars,$errors))
+        if (!$vars['name'])
+            $errors['name'] = __('Name is required');
+        elseif (($sid=SLA::getIdByName($vars['name'])) && $sid!=$vars['id'])
+            $errors['name'] = __('Name already exists');
+
+        if ($errors)
             return false;
 
-        $this->reload();
-        $this->getConfig()->set('transient', isset($vars['transient']) ? 1 : 0);
+        $this->isactive = $vars['isactive'];
+        $this->name = $vars['name'];
+        $this->grace_period = $vars['grace_period'];
+        $this->disable_overdue_alerts = isset($vars['disable_overdue_alerts']) ? 1 : 0;
+        $this->enable_priority_escalation = isset($vars['enable_priority_escalation'])? 1: 0;
+        $this->notes = Format::sanitize($vars['notes']);
+
+        if ($this->save()) {
+            $this->getConfig()->set('transient', isset($vars['transient']) ? 1 : 0);
+            return true;
+        }
 
-        return true;
+        if (isset($this->id)) {
+            $errors['err']=sprintf(__('Unable to update %s.'), __('this SLA plan'))
+               .' '.__('Internal error occurred');
+        } else {
+            $errors['err']=sprintf(__('Unable to add %s.'), __('this SLA plan'))
+               .' '.__('Internal error occurred');
+        }
+
+        return false;
+    }
+
+    function save($refetch=false) {
+        if ($this->dirty)
+            $this->updated = SqlFunction::NOW();
+
+        return parent::save($refetch || $this->dirty);
     }
 
     function delete() {
@@ -132,6 +146,7 @@ class SLA {
         if(!$cfg || $cfg->getDefaultSLAId()==$this->getId())
             return false;
 
+        //TODO: Use ORM to delete & update
         $id=$this->getId();
         $sql='DELETE FROM '.SLA_TABLE.' WHERE id='.db_input($id).' LIMIT 1';
         if(db_query($sql) && ($num=db_affected_rows())) {
@@ -144,86 +159,43 @@ class SLA {
     }
 
     /** static functions **/
-    function create($vars,&$errors) {
-        if (($id = SLA::save(0,$vars,$errors)) && ($sla = self::lookup($id)))
-            $sla->getConfig()->set('transient',
-                isset($vars['transient']) ? 1 : 0);
-        return $id;
-    }
-
-    function getSLAs() {
+    static function getSLAs($criteria=array()) {
 
-        $slas=array();
+       $slas = self::objects()
+           ->order_by('name')
+           ->values_flat('id', 'name', 'isactive', 'grace_period');
 
-        $sql='SELECT id, name, isactive, grace_period FROM '.SLA_TABLE.' ORDER BY name';
-        if(($res=db_query($sql)) && db_num_rows($res)) {
-            while($row=db_fetch_array($res))
-                $slas[$row['id']] = sprintf(__('%s (%d hours - %s)'
+        $entries = array();
+        foreach ($slas as $row) {
+            $entries[$row[0]] = sprintf(__('%s (%d hours - %s)'
                         /* Tokens are <name> (<#> hours - <Active|Disabled>) */),
-                        self::getLocalById($row['id'], 'name', $row['name']),
-                        $row['grace_period'],
-                        $row['isactive']?__('Active'):__('Disabled'));
+                        self::getLocalById($row[0], 'name', $row[1]),
+                        $row[3],
+                        $row[2] ? __('Active') : __('Disabled'));
         }
 
-        return $slas;
+        return $entries;
     }
 
+    static function getIdByName($name) {
+        $row = static::objects()
+            ->filter(array('name'=>$name))
+            ->values_flat('id')
+            ->first();
 
-    function getIdByName($name) {
-
-        $sql='SELECT id FROM '.SLA_TABLE.' WHERE name='.db_input($name);
-        if(($res=db_query($sql)) && db_num_rows($res))
-            list($id)=db_fetch_row($res);
-
-        return $id;
+        return $row ? $row[0] : 0;
     }
 
-    function lookup($id) {
-        return ($id && is_numeric($id) && ($sla= new SLA($id)) && $sla->getId()==$id)?$sla:null;
+    static function create($vars=false, &$errors=array()) {
+        $sla = parent::create($vars);
+        $sla->created = SqlFunction::NOW();
+        return $sla;
     }
 
-    function save($id,$vars,&$errors) {
-
-        if(!$vars['grace_period'])
-            $errors['grace_period']=__('Grace period required');
-        elseif(!is_numeric($vars['grace_period']))
-            $errors['grace_period']=__('Numeric value required (in hours)');
-
-        if(!$vars['name'])
-            $errors['name']=__('Name is required');
-        elseif(($sid=SLA::getIdByName($vars['name'])) && $sid!=$id)
-            $errors['name']=__('Name already exists');
-
-        if($errors) return false;
-
-        $sql=' updated=NOW() '.
-             ',isactive='.db_input($vars['isactive']).
-             ',name='.db_input($vars['name']).
-             ',grace_period='.db_input($vars['grace_period']).
-             ',disable_overdue_alerts='.db_input(isset($vars['disable_overdue_alerts'])?1:0).
-             ',enable_priority_escalation='.db_input(isset($vars['enable_priority_escalation'])?1:0).
-             ',notes='.db_input(Format::sanitize($vars['notes']));
-
-        if($id) {
-            $sql='UPDATE '.SLA_TABLE.' SET '.$sql.' WHERE id='.db_input($id);
-            if(db_query($sql))
-                return true;
-
-            $errors['err']=sprintf(__('Unable to update %s.'), __('this SLA plan'))
-               .' '.__('Internal error occurred');
-        }else{
-            if (isset($vars['id']))
-                $sql .= ', id='.db_input($vars['id']);
-
-            $sql='INSERT INTO '.SLA_TABLE.' SET '.$sql.',created=NOW() ';
-            if(db_query($sql) && ($id=db_insert_id()))
-                return $id;
-
-            $errors['err']=sprintf(__('Unable to add %s.'), __('this SLA plan'))
-               .' '.__('Internal error occurred');
-        }
-
-        return false;
+    static function __create($vars, &$errors=array()) {
+        $sla = self::create($vars);
+        $sla->save();
+        return $sla;
     }
 }
 
@@ -231,8 +203,8 @@ require_once(INCLUDE_DIR.'class.config.php');
 class SlaConfig extends Config {
     var $table = CONFIG_TABLE;
 
-    function SlaConfig($id) {
-        parent::Config("sla.$id");
+    function __construct($id) {
+        parent::__construct("sla.$id");
     }
 }
 ?>
diff --git a/include/staff/slaplans.inc.php b/include/staff/slaplans.inc.php
index 1eaf4b24e..3565ea760 100644
--- a/include/staff/slaplans.inc.php
+++ b/include/staff/slaplans.inc.php
@@ -2,45 +2,41 @@
 if(!defined('OSTADMININC') || !$thisstaff->isAdmin()) die('Access Denied');
 
 $qstr='';
-$sql='SELECT * FROM '.SLA_TABLE.' sla WHERE 1';
-$sortOptions=array('name'=>'sla.name','status'=>'sla.isactive','period'=>'sla.grace_period','date'=>'sla.created','updated'=>'sla.updated');
-$orderWays=array('DESC'=>'DESC','ASC'=>'ASC');
-$sort=($_REQUEST['sort'] && $sortOptions[strtolower($_REQUEST['sort'])])?strtolower($_REQUEST['sort']):'name';
-//Sorting options...
-if($sort && $sortOptions[$sort]) {
-    $order_column =$sortOptions[$sort];
+$sortOptions=array(
+        'name' => 'name',
+        'status' => 'isactive',
+        'period' => 'grace_period',
+        'created' => 'created',
+        'updated' => 'updated'
+        );
+
+$orderWays = array('DESC'=>'DESC', 'ASC'=>'ASC');
+$sort = ($_REQUEST['sort'] && $sortOptions[strtolower($_REQUEST['sort'])]) ? strtolower($_REQUEST['sort']) : 'name';
+if ($sort && $sortOptions[$sort]) {
+    $order_column = $sortOptions[$sort];
 }
-$order_column=$order_column?$order_column:'sla.name';
 
-if($_REQUEST['order'] && $orderWays[strtoupper($_REQUEST['order'])]) {
-    $order=$orderWays[strtoupper($_REQUEST['order'])];
+$order_column = $order_column ? $order_column : 'name';
+
+if ($_REQUEST['order'] && isset($orderWays[strtoupper($_REQUEST['order'])])) {
+    $order = $orderWays[strtoupper($_REQUEST['order'])];
+} else {
+    $order = 'ASC';
 }
-$order=$order?$order:'ASC';
 
-if($order_column && strpos($order_column,',')){
+if ($order_column && strpos($order_column,',')) {
     $order_column=str_replace(','," $order,",$order_column);
 }
 $x=$sort.'_sort';
 $$x=' class="'.strtolower($order).'" ';
-$order_by="$order_column $order ";
-
-$total=db_count('SELECT count(*) FROM '.SLA_TABLE.' sla ');
-$page=($_GET['p'] && is_numeric($_GET['p']))?$_GET['p']:1;
-$pageNav=new Pagenate($total, $page, PAGE_LIMIT);
-$pageNav->setURL('slas.php',$qstr.'&sort='.urlencode($_REQUEST['sort']).'&order='.urlencode($_REQUEST['order']));
-//Ok..lets roll...create the actual query
+$page = ($_GET['p'] && is_numeric($_GET['p'])) ? $_GET['p'] : 1;
+$count = SLA::objects()->count();
+$pageNav = new Pagenate($count, $page, PAGE_LIMIT);
+$_qstr = $qstr.'&sort='.urlencode($_REQUEST['sort']).'&order='.urlencode($_REQUEST['order']);
+$pageNav->setURL('slas.php', $_qstr);
+$showing = $pageNav->showing().' '._N('SLA plan', 'SLA plans', $count);
 $qstr.='&order='.($order=='DESC'?'ASC':'DESC');
-$query="$sql ORDER BY $order_by LIMIT ".$pageNav->getStart().",".$pageNav->getLimit();
-$res=db_query($query);
-if($res && ($num=db_num_rows($res)))
-    $showing=$pageNav->showing().' '._N('SLA plan',
-        'SLA plans' /* SLA is abbreviation for Service Level Agreement */,
-        $total);
-else
-    $showing=__('No SLA plans found!' /* SLA is abbreviation for Service Level Agreement */);
-
 ?>
-
 <div class="pull-left" style="width:700px;padding-top:5px;">
  <h2><?php echo __('Service Level Agreements');?></h2>
 </div>
@@ -66,38 +62,46 @@ else
     <tbody>
     <?php
         $total=0;
-        $ids=($errors && is_array($_POST['ids']))?$_POST['ids']:null;
-        if($res && db_num_rows($res)):
+        $ids = ($errors && is_array($_POST['ids'])) ? $_POST['ids'] : null;
+        if ($count) {
+            $slas = SLA::objects()
+                ->order_by(sprintf('%s%s',
+                            strcasecmp($order, 'DESC') ? '' : '-',
+                            $order_column))
+                ->limit($pageNav->getLimit())
+                ->offset($pageNav->getStart());
+
             $defaultId = $cfg->getDefaultSLAId();
-            while ($row = db_fetch_array($res)) {
+            foreach ($slas as $sla) {
                 $sel=false;
-                if($ids && in_array($row['id'],$ids))
+                $id = $sla->getId();
+                if($ids && in_array($id, $ids))
                     $sel=true;
 
                 $default = '';
-                if ($row['id'] == $defaultId)
+                if ($id == $defaultId)
                     $default = '<small><em>(Default)</em></small>';
                 ?>
-            <tr id="<?php echo $row['id']; ?>">
+            <tr id="<?php echo $id; ?>">
                 <td width=7px>
-                  <input type="checkbox" class="ckb" name="ids[]" value="<?php echo $row['id']; ?>"
-                    <?php echo $sel?'checked="checked"':''; ?>>
+                  <input type="checkbox" class="ckb" name="ids[]" value="<?php echo $id; ?>"
+                    <?php echo $sel ? 'checked="checked"' :'' ; ?>>
                 </td>
-                <td>&nbsp;<a href="slas.php?id=<?php echo $row['id'];
-                    ?>"><?php echo Format::htmlchars($row['name']);
+                <td>&nbsp;<a href="slas.php?id=<?php echo $id;
+                    ?>"><?php echo Format::htmlchars($sla->getName());
                     ?></a>&nbsp;<?php echo $default; ?></td>
-                <td><?php echo $row['isactive']?__('Active'):'<b>'.__('Disabled').'</b>'; ?></td>
-                <td style="text-align:right;padding-right:35px;"><?php echo $row['grace_period']; ?>&nbsp;</td>
-                <td>&nbsp;<?php echo Format::date($row['created']); ?></td>
-                <td>&nbsp;<?php echo Format::datetime($row['updated']); ?></td>
+                <td><?php echo $sla->isActive() ? __('Active') : '<b>'.__('Disabled').'</b>'; ?></td>
+                <td style="text-align:right;padding-right:35px;"><?php echo $sla->getGracePeriod(); ?>&nbsp;</td>
+                <td>&nbsp;<?php echo Format::date($sla->getCreateDate()); ?></td>
+                <td>&nbsp;<?php echo Format::datetime($sla->getUpdateDate()); ?></td>
             </tr>
             <?php
-            } //end of while.
-        endif; ?>
+            } //end of foreach.
+        } ?>
     <tfoot>
      <tr>
         <td colspan="6">
-            <?php if($res && $num){ ?>
+            <?php if ($count) { ?>
             <?php echo __('Select');?>:&nbsp;
             <a id="selectAll" href="#ckb"><?php echo __('All');?></a>&nbsp;&nbsp;
             <a id="selectNone" href="#ckb"><?php echo __('None');?></a>&nbsp;&nbsp;
@@ -110,7 +114,7 @@ else
     </tfoot>
 </table>
 <?php
-if($res && $num): //Show options..
+if ($count): //Show options..
     echo '<div>&nbsp;'.__('Page').':'.$pageNav->getPageLinks().'&nbsp;</div>';
 ?>
 <p class="centered" id="actions">
diff --git a/scp/slas.php b/scp/slas.php
index b47c73092..f57ba70e7 100644
--- a/scp/slas.php
+++ b/scp/slas.php
@@ -36,11 +36,12 @@ if($_POST){
             }
             break;
         case 'add':
-            if(($id=SLA::create($_POST,$errors))){
+            $_sla = SLA::create();
+            if (($_sla->update($_POST, $errors))) {
                 $msg=sprintf(__('Successfully added %s'),
                     __('a SLA plan'));
                 $_REQUEST['a']=null;
-            }elseif(!$errors['err']){
+            } elseif (!$errors['err']) {
                 $errors['err']=sprintf(__('Unable to add %s. Correct error(s) below and try again.'),
                     __('this SLA plan'));
             }
@@ -53,10 +54,12 @@ if($_POST){
                 $count=count($_POST['ids']);
                 switch(strtolower($_POST['a'])) {
                     case 'enable':
-                        $sql='UPDATE '.SLA_TABLE.' SET isactive=1 '
-                            .' WHERE id IN ('.implode(',', db_input($_POST['ids'])).')';
-
-                        if(db_query($sql) && ($num=db_affected_rows())) {
+                        $num = SLA::objects()->filter(array(
+                            'id__in' => $_POST['ids']
+                        ))->update(array(
+                            'isactive' => 1
+                        ));
+                        if ($num) {
                             if($num==$count)
                                 $msg = sprintf(__('Successfully enabled %s'),
                                     _N('selected SLA plan', 'selected SLA plans', $count));
@@ -69,9 +72,13 @@ if($_POST){
                         }
                         break;
                     case 'disable':
-                        $sql='UPDATE '.SLA_TABLE.' SET isactive=0 '
-                            .' WHERE id IN ('.implode(',', db_input($_POST['ids'])).')';
-                        if(db_query($sql) && ($num=db_affected_rows())) {
+                        $num = SLA::objects()->filter(array(
+                            'id__in' => $_POST['ids']
+                        ))->update(array(
+                            'isactive' => 0
+                        ));
+
+                        if ($num) {
                             if($num==$count)
                                 $msg = sprintf(__('Successfully disabled %s'),
                                     _N('selected SLA plan', 'selected SLA plans', $count));
@@ -85,7 +92,7 @@ if($_POST){
                         break;
                     case 'delete':
                         $i=0;
-                        foreach($_POST['ids'] as $k=>$v) {
+                        foreach ($_POST['ids'] as $k => $v) {
                             if (($p=SLA::lookup($v))
                                 && $p->getId() != $cfg->getDefaultSLAId()
                                 && $p->delete())
-- 
GitLab