diff --git a/include/ajax.draft.php b/include/ajax.draft.php
index 5fc24e77a9c5e08d3e8607a6613c4e1a7fdaec6b..8d264ff486639b94df5622028ea611c656f130a0 100644
--- a/include/ajax.draft.php
+++ b/include/ajax.draft.php
@@ -291,7 +291,7 @@ class DraftAjaxAPI extends AjaxController {
 
         $draft = Draft::create(array(
             'staff_id' => $thisstaff->getId(),
-            'namespace' => $namepace
+            'namespace' => $namespace
         ));
         if (!$draft->save())
             Http::response(500, 'Unable to create draft');
diff --git a/include/ajax.i18n.php b/include/ajax.i18n.php
index 38793902e4405e5451c27da173a808f0bda69532..9d3e76b6025600129519afff79d97d551ac02ee5 100644
--- a/include/ajax.i18n.php
+++ b/include/ajax.i18n.php
@@ -67,11 +67,11 @@ class i18nAjaxAPI extends AjaxController {
         }
         foreach ($_POST as $lang => $phrase) {
             if (isset($phrases[$lang])) {
+                $p = $phrases[$lang];
                 if (!$phrase) {
                     $p->delete();
                 }
                 else {
-                    $p = $phrases[$lang];
                     // Avoid XSS injection
                     $p->text = trim(Format::striptags($phrase));
                     $p->agent_id = $thisstaff->getId();
diff --git a/include/class.dept.php b/include/class.dept.php
index b8aaf8b459f588c4a2bf06f54215bec953a848f2..6e819e087f8785f1b1724a9d033c00ebd669954f 100644
--- a/include/class.dept.php
+++ b/include/class.dept.php
@@ -82,6 +82,8 @@ class Dept extends VerySimpleModel {
     }
 
     function getEmail() {
+        global $cfg;
+
         if(!$this->email)
             if(!($this->email = Email::lookup($this->getEmailId())) && $cfg)
                 $this->email = $cfg->getDefaultEmail();
@@ -112,12 +114,12 @@ class Dept extends VerySimpleModel {
                     'onvacation' => 0,
                 ));
 
-            $qs->order_by('lastname', 'firstname');
+            $members->order_by('lastname', 'firstname');
 
             if ($criteria)
-                return $qs->all();
+                return $members->all();
 
-            $this->members = $qs->all();
+            $this->members = $members->all();
         }
         return $this->members;
     }
@@ -236,7 +238,7 @@ class Dept extends VerySimpleModel {
         if ($this->groups)
             return $this->groups;
 
-        $groups = GroupDept::object()
+        $groups = GroupDept::objects()
             ->filter(array('dept_id' => $this->getId()))
             ->values_flat('group_id');
 
@@ -247,28 +249,30 @@ class Dept extends VerySimpleModel {
         return $this->groups;
     }
 
-    function updateSettings($vars) {
+    function updateGroups($groups_ids) {
 
         // Groups allowes to access department
-        if($vars['groups'] && is_array($vars['groups'])) {
-            $groups = GroupDept::object()
+        if (is_array($groups_ids)) {
+            $groups = GroupDept::objects()
                 ->filter(array('dept_id' => $this->getId()));
             foreach ($groups as $group) {
-                if ($idx = array_search($group->group_id, $vars['groups']))
-                    unset($vars['groups'][$idx]);
+                if ($idx = array_search($group->group_id, $groups_ids))
+                    unset($groups_ids[$idx]);
                 else
                     $group->delete();
             }
-            foreach ($vars['groups'] as $id) {
+            foreach ($groups_ids as $id) {
                 GroupDept::create(array(
                     'dept_id'=>$this->getId(), 'group_id'=>$id
                 ))->save();
             }
         }
 
-        // Misc. config settings
-        $this->getConfig()->set('assign_members_only', $vars['assign_members_only']);
+    }
 
+    function updateSettings($vars) {
+        $this->updateGroups($vars['groups'] ?: array());
+        $this->getConfig()->set('assign_members_only', $vars['assign_members_only']);
         return true;
     }
 
diff --git a/include/class.format.php b/include/class.format.php
index 186a02d0e4016766d3d94ab3d5b0ff1572f0f85f..e6761abfea7a62b8f7b19487f202f10f6e19dad4 100644
--- a/include/class.format.php
+++ b/include/class.format.php
@@ -513,7 +513,7 @@ class Format {
         $format = self::getStrftimeFormat($format);
         // TODO: Properly convert to local time
         $time = DateTime::createFromFormat('U', $timestamp, new DateTimeZone('UTC'));
-        $time->setTimeZone(new DateTimeZone($cfg->getTimeZone()));
+        $time->setTimeZone(new DateTimeZone($cfg->getTimezone()));
         $timestamp = $time->getTimestamp();
         return strftime($format ?: $strftimeFallback, $timestamp);
     }
@@ -547,7 +547,7 @@ class Format {
         return self::__formatDate($timestamp,
             $format ?: $cfg->getTimeFormat(), $fromDb,
             IntlDateFormatter::NONE, IntlDateFormatter::SHORT,
-            '%x', $timezone ?: $cfg->getTimeZone());
+            '%x', $timezone ?: $cfg->getTimezone());
     }
 
     function date($timestamp, $fromDb=true, $format=false, $timezone=false) {
@@ -556,25 +556,25 @@ class Format {
         return self::__formatDate($timestamp,
             $format ?: $cfg->getDateFormat(), $fromDb,
             IntlDateFormatter::SHORT, IntlDateFormatter::NONE,
-            '%X', $timezone ?: $cfg->getTimeZone());
+            '%X', $timezone ?: $cfg->getTimezone());
     }
 
     function datetime($timestamp, $fromDb=true, $timezone=false) {
         global $cfg;
 
         return self::__formatDate($timestamp,
-            $format ?: $cfg->getDateTimeFormat(), $fromDb,
-            IntlDateFormatter::SHORT, IntlDateFormatter::SHORT,
-            '%X %x', $timezone ?: $cfg->getTimeZone());
+                $cfg->getDateTimeFormat(), $fromDb,
+                IntlDateFormatter::SHORT, IntlDateFormatter::SHORT,
+                '%X %x', $timezone ?: $cfg->getTimezone());
     }
 
     function daydatetime($timestamp, $fromDb=true, $timezone=false) {
         global $cfg;
 
         return self::__formatDate($timestamp,
-            $format ?: $cfg->getDayDateTimeFormat(), $fromDb,
-            IntlDateFormatter::FULL, IntlDateFormatter::SHORT,
-            '%X %x', $timezone ?: $cfg->getTimeZone());
+                $cfg->getDayDateTimeFormat(), $fromDb,
+                IntlDateFormatter::FULL, IntlDateFormatter::SHORT,
+                '%X %x', $timezone ?: $cfg->getTimezone());
     }
 
     function getStrftimeFormat($format) {
@@ -742,7 +742,7 @@ class Format {
         if (class_exists('IntlBreakIterator')) {
             // Split by word boundaries
             if ($tokenizer = IntlBreakIterator::createWordInstance(
-                    $lang ?: ($cfg ? $cfg->getSystemLanguage() : 'en_US'))
+                    $lang ?: ($cfg ? $cfg->getPrimaryLanguage() : 'en_US'))
             ) {
                 $tokenizer->setText($text);
                 $tokens = array();
diff --git a/include/class.i18n.php b/include/class.i18n.php
index 5941b44d444e5502933302ee1b1f753918a2cae9..c0dc5388bbdf61edcb912a5b4cfea17a91495215 100644
--- a/include/class.i18n.php
+++ b/include/class.i18n.php
@@ -384,10 +384,8 @@ class Internationalization {
             return $thisstaff->getLocale()
                 ?: self::getCurrentLanguage();
         }
-        if (!$locale)
-            $locale = $cfg->getDefaultLocale();
 
-        if (!$locale)
+        if (!($locale = $cfg->getDefaultLocale()))
             $locale = self::getCurrentLanguage();
 
         return $locale;
diff --git a/include/class.lock.php b/include/class.lock.php
index c61771e67f5a3b166734e41d8c6ee3ebd03c977c..6e0588978e29b71d125b0602388923b50edc6898 100644
--- a/include/class.lock.php
+++ b/include/class.lock.php
@@ -71,6 +71,7 @@ class TicketLock extends VerySimpleModel {
 
     //Renew existing lock.
     function renew($lockTime=0) {
+        global $cfg;
 
         if(!$lockTime || !is_numeric($lockTime)) //XXX: test to  make it works.
             $lockTime = $cfg->getLockTime();
diff --git a/include/class.orm.php b/include/class.orm.php
index 5e41edc482fdaeb95e3b36b244a78be4da001b65..ce074a88787a4947e212cae42e635ad5fa943b75 100644
--- a/include/class.orm.php
+++ b/include/class.orm.php
@@ -991,7 +991,7 @@ class ModelInstanceManager extends ResultSet {
      * The annotated fields are in the AnnotatedModel instance and the
      * database-backed fields are managed by the Model instance.
      */
-    function getOrBuild($modelClass, $fields) {
+    function getOrBuild($modelClass, $fields, $cache=true) {
         // Check for NULL primary key, used with related model fetching. If
         // the PK is NULL, then consider the object to also be NULL
         foreach ($modelClass::$meta['pk'] as $pkf) {
@@ -1312,7 +1312,8 @@ class SqlCompiler {
 
         // Call pushJoin for each segment in the join path. A new JOIN
         // fragment will need to be emitted and/or cached
-        $push = function($p, $path, $extra=false) use (&$model) {
+        $self = $this;
+        $push = function($p, $path, $extra=false) use (&$model, $self) {
             $model::_inspect();
             if (!($info = $model::$meta['joins'][$p])) {
                 throw new OrmException(sprintf(
@@ -1322,7 +1323,7 @@ class SqlCompiler {
             $crumb = implode('__', $path);
             $path[] = $p;
             $tip = implode('__', $path);
-            $alias = $this->pushJoin($crumb, $tip, $model, $info, $extra);
+            $alias = $self->pushJoin($crumb, $tip, $model, $info, $extra);
             // Roll to foreign model
             foreach ($info['constraint'] as $local => $foreign) {
                 list($model, $f) = explode('.', $foreign);
@@ -1857,6 +1858,7 @@ class MySqlCompiler extends SqlCompiler {
             }
         }
         $fields = array_keys($fields);
+        $group_by = array();
         // Add in annotations
         if ($queryset->annotations) {
             foreach ($queryset->annotations as $A) {
diff --git a/include/class.search.php b/include/class.search.php
index 68076e619847a82a9ee9bba0736b98fe3cdd0623..ff2ccbdcac8c87a13e1f3774cd85696da9dd54be 100644
--- a/include/class.search.php
+++ b/include/class.search.php
@@ -317,38 +317,13 @@ class MysqlSearchBackend extends SearchBackend {
             $criteria->filter(array('ticket_id'=>new SqlCode($key)));
             $criteria->distinct('ticket_id');
             }
-            /*
-                    case 'email':
-                    case 'org_id':
-                    case 'form_id':
-                    default:
-                        if (strpos($name, 'cdata.') === 0) {
-                            // Search ticket CDATA table
-                            $cdata_search = true;
-                            $name = substr($name, 6);
-                            if (is_array($value)) {
-                                $where[] = '(' . implode(' OR ', array_map(
-                                    function($k) use ($name) {
-                                        return sprintf('FIND_IN_SET(%s, cdata.`%s`)',
-                                            db_input($k), $name);
-                                    }, $value)
-                                ) . ')';
-                            }
-                            else {
-                                $where[] = sprintf("cdata.%s = %s", $name, db_input($value));
-                            }
-                        }
-                    }
-                }
-             */
-
             // TODO: Consider sorting preferences
         }
 
         // TODO: Ensure search table exists;
         if (false) {
-            // Create the search table automatically
-            $class::createSearchTable();
+            // TODO: Create the search table automatically
+            // $class::createSearchTable();
         }
         return $criteria;
     }
diff --git a/include/class.staff.php b/include/class.staff.php
index 57b35bd02a22ef325a5ab4f6352cb627a4425a86..0b53f9296327ac6486b89a8394ea0588e0be8a00 100644
--- a/include/class.staff.php
+++ b/include/class.staff.php
@@ -608,7 +608,7 @@ implements AuthenticatedUser {
 
         $users=array();
         foreach ($members as $M) {
-            $users[$S->id] = $M->getName();
+            $users[$M->id] = $M->getName();
         }
 
         return $users;
@@ -741,14 +741,14 @@ implements AuthenticatedUser {
         if($vars['mobile'] && !Validator::is_phone($vars['mobile']))
             $errors['mobile']=__('Valid phone number is required');
 
-        if($vars['passwd1'] || $vars['passwd2'] || !$id) {
+        if($vars['passwd1'] || $vars['passwd2'] || !$vars['id']) {
             if($vars['passwd1'] && strcmp($vars['passwd1'], $vars['passwd2'])) {
                 $errors['passwd2']=__('Passwords do not match');
             }
             elseif ($vars['backend'] != 'local' || $vars['welcome_email']) {
                 // Password can be omitted
             }
-            elseif(!$vars['passwd1'] && !$id) {
+            elseif(!$vars['passwd1'] && !$vars['id']) {
                 $errors['passwd1']=__('Temporary password is required');
                 $errors['temppasswd']=__('Required');
             } elseif($vars['passwd1'] && strlen($vars['passwd1'])<6) {
diff --git a/include/client/faq-category.inc.php b/include/client/faq-category.inc.php
index a9044f2b77f1c057686dfe87fdeb526284653616..eb6606af8b261f9daf9d3e8fed1d17c345423a90 100644
--- a/include/client/faq-category.inc.php
+++ b/include/client/faq-category.inc.php
@@ -55,7 +55,7 @@ foreach (Topic::objects()
     ->filter(array('faqs__faq__category__category_id'=>$category->getId()))
     as $t) { ?>
         <a href="?topicId=<?php echo urlencode($t->getId()); ?>"
-            ><?php echo $t->getFullname(); ?></a>
+            ><?php echo $t->getFullName(); ?></a>
 <?php } ?>
         </section>
     </div>