diff --git a/file.php b/file.php
index d62d588eb5942b0c0c1f5639ba22cf511f3a8884..ed0a4465e845f90377e05905c53d9b1b37962f58 100644
--- a/file.php
+++ b/file.php
@@ -51,7 +51,7 @@ if ($file->verifySignature($_GET['signature'], $_GET['expires'])) {
         // Download the file..
         $file->download(@$_GET['disposition'] ?: false, $_GET['expires']);
     }
-    catch (Exception $x) {
+    catch (Exception $ex) {
         Http::response(500, 'Unable to find that file: '.$ex->getMessage());
     }
 }
diff --git a/include/class.canned.php b/include/class.canned.php
index bb126d74088ab72b2677d3d0125c9bd0871a71bf..a8847c9ea07b3f61bb57aefe6afdc7caad382ccf 100644
--- a/include/class.canned.php
+++ b/include/class.canned.php
@@ -21,6 +21,10 @@ extends VerySimpleModel {
         'table' => CANNED_TABLE,
         'pk' => array('canned_id'),
         'joins' => array(
+            'dept' => array(
+                'constraint' => array('dept_id' => 'Dept.id'),
+                'null' => true,
+            ),
             'attachments' => array(
                 'constraint' => array(
                     "'C'" => 'Attachment.type',
diff --git a/include/class.dept.php b/include/class.dept.php
index ef6c28d87c9b883d46e3e34dc633eda7c7ad3815..36ffd2ffb00f07258426aa1c9b3f819bc949f297 100644
--- a/include/class.dept.php
+++ b/include/class.dept.php
@@ -320,7 +320,7 @@ implements TemplateVariable {
         if (is_object($staff))
             $staff = $staff->getId();
 
-        return $members->getIterator()->findFirst(array(
+        return $this->getMembers()->findFirst(array(
             'staff_id' => $staff
         ));
     }
@@ -469,7 +469,7 @@ implements TemplateVariable {
     }
 
     /*----Static functions-------*/
-	static function getIdByName($name, $pid=null) {
+    static function getIdByName($name, $pid=null) {
         $row = static::objects()
             ->filter(array(
                         'name' => $name,
@@ -579,9 +579,12 @@ implements TemplateVariable {
 
     static function __create($vars, &$errors) {
         $dept = self::create($vars);
-        $dept->update($vars, $errors);
+        if (!$dept->update($vars, $errors))
+          return false;
+
+       $dept->save();
 
-        return isset($dept->id) ? $dept : null;
+       return $dept;
     }
 
     function save($refetch=false) {
diff --git a/include/class.dynamic_forms.php b/include/class.dynamic_forms.php
index 7bb040814714eeaa7b6f4400ef84d3e98391cccf..9abe6467a74f6b91d5641e679d06548ecac04ee2 100644
--- a/include/class.dynamic_forms.php
+++ b/include/class.dynamic_forms.php
@@ -951,15 +951,11 @@ class DynamicFormEntry extends VerySimpleModel {
     }
 
     function setAnswer($name, $value, $id=false) {
-        foreach ($this->getAnswers() as $ans) {
+
+        if ($ans=$this->getAnswer($name)) {
             $f = $ans->getField();
-            if ($f->isStorable() && $f->get('name') == $name) {
-                $f->reset();
-                $ans->set('value', $value);
-                if ($id !== false)
-                    $ans->set('value_id', $id);
-                break;
-            }
+            if ($f->isStorable())
+                $ans->setValue($value, $id);
         }
     }
 
@@ -1269,7 +1265,7 @@ class DynamicFormEntry extends VerySimpleModel {
             }
             if ($a->dirty)
                 $dirty++;
-            $a->save();
+            $a->save($refetch);
         }
         return $dirty;
     }
@@ -1359,6 +1355,14 @@ class DynamicFormEntryAnswer extends VerySimpleModel {
         return $this->_value;
     }
 
+    function setValue($value, $id=false) {
+        $this->getField()->reset();
+        $this->_value = null;
+        $this->set('value', $value);
+        if ($id !== false)
+            $this->set('value_id', $id);
+    }
+
     function getLocal($tag) {
         return $this->field->getLocal($tag);
     }
@@ -1621,8 +1625,10 @@ class SelectionField extends FormField {
                 }
             } elseif ($config['typeahead']
                     && ($entered = $this->getWidget()->getEnteredValue())
-                    && !in_array($entered, $entry))
+                    && !in_array($entered, $entry)
+                    && $entered != $entry) {
                 $this->_errors[] = __('Select a value from the list');
+           }
         }
     }
 
diff --git a/include/class.filter.php b/include/class.filter.php
index 20bac5ce53b856d13d439a0afedd8e8abe1ab97a..29f49d904949b2318dbd4da9d16c6ebed7f1f299 100644
--- a/include/class.filter.php
+++ b/include/class.filter.php
@@ -383,6 +383,10 @@ class Filter {
     }
 
     function lookup($id) {
+
+        if ($id && !is_numeric($id))
+            $id = self::getIdByName($id);
+
         return ($id && is_numeric($id) && ($f= new Filter($id)) && $f->getId()==$id)?$f:null;
     }
 
diff --git a/include/class.forms.php b/include/class.forms.php
index 318adbbc12b4f3053921f9b13d63f8e10cfa3718..180057e81c3b6ee2c3d340cd6815abb4063c5390 100644
--- a/include/class.forms.php
+++ b/include/class.forms.php
@@ -1582,15 +1582,19 @@ class ChoiceField extends FormField {
             $value = JsonDataParser::parse($value) ?: $value;
 
         // CDATA table may be built with comma-separated key,value,key,value
-        if (is_string($value)) {
+        if (is_string($value) && strpos($value, ',')) {
             $values = array();
             $choices = $this->getChoices();
-            foreach (explode(',', $value) as $V) {
+            $vals = explode(',', $value);
+            foreach ($vals as $V) {
                 if (isset($choices[$V]))
                     $values[$V] = $choices[$V];
             }
             if (array_filter($values))
                 $value = $values;
+            elseif($vals)
+                list($value) = $vals;
+
         }
         $config = $this->getConfiguration();
         if (!$config['multiselect'] && is_array($value) && count($value) < 2) {
diff --git a/include/class.i18n.php b/include/class.i18n.php
index a7e23a8ee63d3fabbcbb2e4568a25b60ab3eb3ef..ac6db0a332a0e97da6b216b5ac56f3c262087222 100644
--- a/include/class.i18n.php
+++ b/include/class.i18n.php
@@ -140,6 +140,7 @@ class Internationalization {
         if (($tpl = $this->getTemplate('templates/premade.yaml'))
                 && ($canned = $tpl->getData())) {
             foreach ($canned as $c) {
+                $c['isenabled'] = 1;
                 if (!($premade = Canned::create($c)) || !$premade->save())
                     continue;
                 if (isset($c['attachments'])) {
diff --git a/include/class.orm.php b/include/class.orm.php
index 3e7dc64dfaab83eebc7b583cf522fd48e8463ea8..1f37f679b60d64ad62dec1939563d16a2f2b405f 100644
--- a/include/class.orm.php
+++ b/include/class.orm.php
@@ -396,9 +396,10 @@ class VerySimpleModel {
     }
 
     function __isset($field) {
-        return array_key_exists($field, $this->ht)
+        return ($this->ht && array_key_exists($field, $this->ht))
             || isset(static::$meta['joins'][$field]);
     }
+
     function __unset($field) {
         if ($this->__isset($field))
             unset($this->ht[$field]);
@@ -1468,6 +1469,13 @@ implements IteratorAggregate, Countable, ArrayAccess {
         }
     }
 
+    function reset() {
+        $this->eoi = false;
+        $this->cache = array();
+        // XXX: Should the inner be recreated to refetch?
+        $this->inner->rewind();
+    }
+
     function asArray() {
         $this->fillTo(PHP_INT_MAX);
         return $this->getCache();
@@ -1908,11 +1916,6 @@ extends ModelResultSet {
                 $object->set($field, null);
     }
 
-    function reset() {
-        $this->cache = array();
-        unset($this->resource);
-    }
-
     /**
      * Slight edit to the standard iteration method which will skip deleted
      * items.
@@ -3106,12 +3109,11 @@ class MySqlPreparedExecutor {
             case is_int($p):
             case is_float($p):
                 return $p;
-
             case $p instanceof DateTime:
                 $p = $p->format('Y-m-d H:i:s');
             default:
-                return db_real_escape($p, true);
-            }
+                return db_real_escape((string) $p, true);
+           }
         }, $this->sql);
     }
 }
diff --git a/include/class.page.php b/include/class.page.php
index 920c2ee88ecfd3cd06c3eb8bf36756bad487c76f..157ad43cdc30d1add90b0270f331d821038feacc 100644
--- a/include/class.page.php
+++ b/include/class.page.php
@@ -319,7 +319,7 @@ class Page extends VerySimpleModel {
                 return false;
         }
         // New translations (?)
-        foreach ($vars['trans'] as $lang=>$parts) {
+        foreach ($vars['trans'] ?: array() as $lang=>$parts) {
             $content = array('name' => @$parts['title'], 'body' => Format::sanitize(@$parts['body']));
             if (!array_filter($content))
                 continue;
diff --git a/include/class.search.php b/include/class.search.php
index 6249498b05601fcc09afa23f753ae5c61fcb6466..61b56a41e61f6c14dd4fa44ccaa6fd914d36453b 100644
--- a/include/class.search.php
+++ b/include/class.search.php
@@ -478,7 +478,7 @@ class MysqlSearchBackend extends SearchBackend {
             LEFT JOIN `".TABLE_PREFIX."_search` A2 ON (A1.`id` = A2.`object_id` AND A2.`object_type`='H')
             WHERE A2.`object_id` IS NULL AND (A1.poster <> 'SYSTEM')
             AND (LENGTH(A1.`title`) + LENGTH(A1.`body`) > 0)
-            ORDER BY A1.`id` DESC";
+            ORDER BY A1.`id` DESC LIMIT 500";
         if (!($res = db_query_unbuffered($sql, $auto_create)))
             return false;
 
@@ -498,7 +498,7 @@ class MysqlSearchBackend extends SearchBackend {
         $sql = "SELECT A1.`ticket_id` FROM `".TICKET_TABLE."` A1
             LEFT JOIN `".TABLE_PREFIX."_search` A2 ON (A1.`ticket_id` = A2.`object_id` AND A2.`object_type`='T')
             WHERE A2.`object_id` IS NULL
-            ORDER BY A1.`ticket_id` DESC";
+            ORDER BY A1.`ticket_id` DESC LIMIT 300";
         if (!($res = db_query_unbuffered($sql, $auto_create)))
             return false;
 
diff --git a/include/class.task.php b/include/class.task.php
index e2c5643a61796d94740ce961da51ce4e492a76af..f97501b002bf8d71ad570de72ee9efbf6bba5c4d 100644
--- a/include/class.task.php
+++ b/include/class.task.php
@@ -1457,7 +1457,7 @@ class TaskForm extends DynamicForm {
     static $cdata = array(
             'table' => TASK_CDATA_TABLE,
             'object_id' => 'task_id',
-            'object_type' => 'A',
+            'object_type' => ObjectModel::OBJECT_TYPE_TASK,
         );
 
     static function objects() {
@@ -1545,8 +1545,7 @@ class TaskThread extends ObjectThread {
         $vars['threadId'] = $this->getId();
         $vars['message'] = $vars['description'];
         unset($vars['description']);
-
-        return MessageThreadEntry::create($vars, $errors);
+        return MessageThreadEntry::add($vars, $errors);
     }
 
     static function create($task=false) {
diff --git a/include/class.ticket.php b/include/class.ticket.php
index d126259da8b1dbb6604b8ab085c3b5ee066395bb..2afbe818f318ea9a54abdccdcf11db8acec8420b 100644
--- a/include/class.ticket.php
+++ b/include/class.ticket.php
@@ -3373,11 +3373,9 @@ implements RestrictedAccess, Threadable {
         // Save the (common) dynamic form
         // Ensure we have a subject
         $subject = $form->getAnswer('subject');
-        if ($subject && !$subject->getValue()) {
-            if ($topic) {
-                $form->setAnswer('subject', $topic->getFullName());
-            }
-        }
+        if ($subject && !$subject->getValue() && $topic)
+            $subject->setValue($topic->getFullName());
+
         $form->setTicketId($ticket->getId());
         $form->save();
 
diff --git a/include/pear/Net/SMTP.php b/include/pear/Net/SMTP.php
index 8f4e92b7532a0c51f97219017a246574d3d17d8c..530f558c9c39e0fca73fa98a431eeb5bd3cbd9fd 100644
--- a/include/pear/Net/SMTP.php
+++ b/include/pear/Net/SMTP.php
@@ -166,6 +166,13 @@ class Net_SMTP
 
         $this->pipelining      = $pipelining;
         $this->socket         = new Net_Socket();
+
+        // Turn off peer name verification by default
+        if (!$socket_options)
+            $socket_options = array(
+                    'ssl' => array('verify_peer_name' => false)
+                    );
+
         $this->socket_options = $socket_options;
         $this->timeout        = $timeout;
 
diff --git a/include/staff/faq-categories.inc.php b/include/staff/faq-categories.inc.php
index e90f06cd88017ce603f952c76eebf535c561ff6c..4c484822751eeb0a6b8e3f5ad8ce59562ad523b6 100644
--- a/include/staff/faq-categories.inc.php
+++ b/include/staff/faq-categories.inc.php
@@ -140,8 +140,7 @@ if($_REQUEST['q'] || $_REQUEST['cid'] || $_REQUEST['topicId']) { //Search.
     }
 } else { //Category Listing.
     $categories = Category::objects()
-        ->annotate(array('faq_count'=>SqlAggregate::COUNT('faqs')))
-        ->all();
+        ->annotate(array('faq_count'=>SqlAggregate::COUNT('faqs')));
 
     if (count($categories)) {
         $categories->sort(function($a) { return $a->getLocalName(); });
diff --git a/include/staff/staff.inc.php b/include/staff/staff.inc.php
index c063948b75a68ed6e7ae6c9c4cac1adc8f1f410c..3a3a27f727298b61d83cf6e10184ba579765d83e 100644
--- a/include/staff/staff.inc.php
+++ b/include/staff/staff.inc.php
@@ -518,6 +518,7 @@ $('#join_team').find('button').on('click', function() {
 
 <?php
 foreach ($staff->dept_access as $dept_access) {
+  if (!$dept_access->dept_id) continue;
   echo sprintf('addAccess(%d, %s, %d, %d, %s);', $dept_access->dept_id,
     JsonDataEncoder::encode($dept_access->dept->getName()),
     $dept_access->role_id,
diff --git a/include/staff/staffmembers.inc.php b/include/staff/staffmembers.inc.php
index 7ddba38eab8213491443aeccdf489eeb7b62ad88..97f7c1265249a845d5bfb49d3705e66638e44569 100644
--- a/include/staff/staffmembers.inc.php
+++ b/include/staff/staffmembers.inc.php
@@ -16,12 +16,6 @@ $sortOptions = array(
 $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 : array('firstname', 'lastname');
-
 switch ($cfg->getAgentNameFormat()) {
 case 'last':
 case 'lastfirst':
@@ -31,6 +25,12 @@ case 'legal':
 // Otherwise leave unchanged
 }
 
+if ($sort && $sortOptions[$sort]) {
+    $order_column = $sortOptions[$sort];
+}
+
+$order_column = $order_column ?: array('firstname', 'lastname');
+
 if ($_REQUEST['order'] && isset($orderWays[strtoupper($_REQUEST['order'])])) {
     $order = $orderWays[strtoupper($_REQUEST['order'])];
 } else {
diff --git a/login.php b/login.php
index 4c7f3b6c12bd668c205d686803b5058d0847fca5..f19c1a3ec8897bb98784793e29222693af5a3277 100644
--- a/login.php
+++ b/login.php
@@ -86,7 +86,7 @@ elseif ($_POST && isset($_POST['lticket'])) {
             Http::redirect('tickets.php');
 
         // This will succeed as it is checked in the authentication backend
-        $ticket = Ticket::lookupByNumber($_POST['lticket']);
+        $ticket = Ticket::lookupByNumber($_POST['lticket'], $_POST['lemail']);
 
         // We're using authentication backend so we can guard aganist brute
         // force attempts (which doesn't buy much since the link is emailed)