public function scoresImportAction()
    {
        require_once 'models/table/Person.php';
        require_once 'models/table/PersonToTraining.php';
        //labels
        $id = $this->getSanParam('training');
        $db = Zend_Db_Table_Abstract::getDefaultAdapter();
        $status = ValidationContainer::instance();
        $trainingObj = new Training();
        $this->viewAssignEscaped('courseName', $trainingObj->getCourseName($id));
        $this->view->assign('training_id', $id);
        //CSV import -- post
        if (@$_FILES['import']['tmp_name']) {
            $filename = $_FILES['import']['tmp_name'];
            if ($filename) {
                // we need a table to compare names to
                $table = new ITechTable(array('name' => 'score'));
                $persons = new ITechTable(array('name' => 'person'));
                $sql = 'select distinct person_to_training.id as pid,person.first_name,person.last_name from person_to_training
					   left join person on person.id = person_id
					   where person_to_training.training_id = ' . $id;
                $ppl = $db->fetchAll($sql);
                while ($row = $this->_csv_get_row($filename)) {
                    if (is_array($row)) {
                        if (isset($row[0]) && isset($row[4]) && !empty($row[0]) && !empty($row[4])) {
                            // find person
                            $row[0] = trim($row[0]);
                            $row[1] = trim($row[1]);
                            $pid = null;
                            foreach ($ppl as $v) {
                                if ($v['first_name'] == $row[0] && $v['last_name'] == $row[1]) {
                                    $pid = $v['pid'];
                                    break;
                                }
                            }
                            if ($pid) {
                                $new_row = $table->createRow();
                                $new_row->person_to_training_id = $pid;
                                $new_row->training_date = $row[2];
                                $new_row->score_label = $row[3];
                                $new_row->score_value = $row[4];
                                $new_row->save();
                            } else {
                                // err
                                if (!isset($notfound)) {
                                    $notfound = array();
                                }
                                if ($row[0] != t('First Name')) {
                                    $notfound[] = $row[0] . ' ' . $row[1] . '<br>';
                                }
                            }
                        }
                    }
                }
            }
            $_POST['redirect'] = null;
            if ($notfound) {
                $status->setStatusMessage(t('The following users could not be found while importing, perhaps they were not adding to the training:<br>'));
                foreach ($notfound as $v) {
                    $status->setStatusMessage($v);
                }
            }
            // done
        }
        // score view (edit table)
        require_once 'views/helpers/EditTableHelper.php';
        $label = 'Score';
        $fields = array('name' => t('Name'), 'score_label' => t('Label'), 'score_value' => t('Score'));
        $rowRay = $db->fetchAll("select score.*,CONCAT(person.first_name, CONCAT(' ', person.last_name)) as name from person_to_training\r\n\t\t\t\t\t\tinner join score on score.person_to_training_id = person_to_training.id\r\n\t\t\t\t\t\tleft join person on person.id = person_id\r\n\t\t\t\t\t\twhere person_to_training.training_id = {$id}\r\n\t\t\t\t\t\t");
        $this->view->assign('editTable', EditTableHelper::generateHtml($label, $rowRay, $fields, array(), array(), true));
    }
 public function execute()
 {
     $params = $this->_getAllParams();
     if (isset($params['merge']) && $this->allowMerge) {
         $this->merge();
         return;
     }
     if (isset($params['default']) && $this->allowDefault) {
         $this->setDefault();
     }
     if (isset($params['redirect']) and $params['redirect']) {
         // editTable is part of a "wizard" (redirect to the next step)
         header("Location: {$params['redirect']}");
         exit;
     } elseif (isset($params['saveonly'])) {
         $status = ValidationContainer::instance();
         $status->setStatusMessage('Your settings have been updated.');
     }
     require_once 'models/table/EditTable.php';
     $editTable = new EditTable(array('name' => $this->table));
     $request = $this->controller->getRequest();
     $validateOnly = $request->isXmlHttpRequest();
     // Delete, insert, or update?
     if ($validateOnly) {
         //$id = $params['id'];
         $id = isset($_POST['id']) && is_numeric($_POST['id']) ? $_POST['id'] : null;
         // Get field to update
         foreach ($this->fields as $key => $devnull) {
             if (isset($params[$key])) {
                 $fieldEdit = $key;
                 $fieldValue = $params[$key];
                 break;
             }
         }
         if ($id == 0 && isset($params['undelete'])) {
             // undelete record
             try {
                 $row = $editTable->undelete($fieldEdit, $fieldValue);
                 $sendRay['insert'] = $row->id;
                 $sendRay['undelete'] = $row->{$fieldEdit};
                 $this->sendData($sendRay);
             } catch (Zend_Exception $e) {
                 $this->sendData(array("insert" => 0, 'error' => $e->getMessage()));
             }
         } elseif ($id == 0) {
             // user added new record
             try {
                 if (!$this->insertExtra) {
                     $insert = $editTable->insertUnique($fieldEdit, $fieldValue);
                 } else {
                     $data = array($fieldEdit => $fieldValue);
                     $insert = $editTable->insert(array_merge($data, $this->insertExtra));
                 }
                 $sendRay['insert'] = "{$insert}";
                 if ($insert == -1) {
                     $sendRay['error'] = 'A record already exists with this value.';
                 }
                 if ($insert == -2) {
                     $sendRay['error'] = '"%s" already exists, but was deleted.  Would you like to undelete?';
                 }
                 $this->sendData($sendRay);
             } catch (Zend_Exception $e) {
                 $this->sendData(array("insert" => 0, 'error' => $e->getMessage()));
             }
         } elseif ($id > 0) {
             // update or delete
             if (isset($params['delete'])) {
                 try {
                     $delete = $editTable->delete("id={$id}", true);
                     //force the delete, changed 06/16/08 Todd W
                     $this->sendData(array("delete" => $delete));
                 } catch (Zend_Exception $e) {
                     $this->sendData(array("delete" => 0, 'error' => $e->getMessage()));
                 }
             } elseif (isset($fieldEdit)) {
                 // update
                 try {
                     $update = $editTable->update(array($fieldEdit => $fieldValue), "id={$id}");
                     $this->sendData(array("update" => $id));
                 } catch (Zend_Exception $e) {
                     if (strpos($e->getMessage(), 'Duplicate entry') !== false) {
                         $this->sendData(array("update" => 0, 'error' => t('A record already exists with this value.')));
                     } else {
                         $this->sendData(array("update" => 0, 'error' => $e->getMessage()));
                     }
                 }
             }
         }
     } else {
         // view
         $selectFields = array_keys($this->fields);
         if ($this->allowDefault) {
             $selectFields[] = 'is_default';
         }
         require_once 'views/helpers/EditTableHelper.php';
         $rowRay = $editTable->getRowsSingle($this->table, $selectFields, $this->where);
         foreach ($rowRay as $key => $row) {
             foreach ($selectFields as $field) {
                 if ($field != 'id') {
                     $rowRay[$key][$field] = htmlspecialchars($row[$field]);
                 }
             }
         }
         // Modify rows
         if ($this->rowHook) {
             $func_name = $this->rowHook;
             eval('$rowRay = ' . $func_name . "(unserialize('" . serialize($rowRay) . "'));");
         }
         $noDelete = array();
         // look up dependencies
         if (!empty($this->dependencies)) {
             foreach ($this->dependencies as $colDependent => $tableDependent) {
                 if (is_numeric($colDependent)) {
                     $colDependent = $this->table . '_id';
                 }
                 if (is_array($tableDependent)) {
                     // in case multiple tables use the same field name
                     $colDependent = key($tableDependent);
                     $tableDependent = current($tableDependent);
                 }
                 $ray = $editTable->getDependencies($this->table, $tableDependent, $colDependent);
                 $noDelete += array_merge($noDelete, $ray);
             }
             $noDelete = array_unique($noDelete);
         }
         // disable delete on all rows
         if ($this->noDelete) {
             foreach ($rowRay as $key => $row) {
                 $noDelete[$row['id']] = $row['id'];
             }
         }
         // merge checkbox
         if ($this->allowMerge) {
             foreach ($rowRay as $key => $row) {
                 $rowRay[$key]['merge'] = '
       <input type="checkbox" name="merge[]" value="' . $row['id'] . '" id="merge' . $row['id'] . '">';
             }
             $this->customColDef['merge'] = 'editor:false';
             $this->fields['merge'] = 'Merge?';
         }
         // default radio
         if ($this->allowDefault) {
             foreach ($rowRay as $key => $row) {
                 $isChecked = $row['is_default'] ? ' checked="checked"' : '';
                 $rowRay[$key]['default'] = '
       <input type="radio" name="default" value="' . $row['id'] . '" id="merge' . $row['id'] . '"' . $isChecked . '>';
             }
             $this->customColDef['default'] = 'editor:false';
             $this->fields['default'] = 'Default?';
         }
         $html = '';
         if ($this->allowMerge) {
             $mergehtml = '
     <input type="hidden" name="table_option" value="' . $this->table . '">
     <input type="hidden" name="table_dependent" value="' . implode(',', $this->dependencies) . '">
     <input type="submit" name="mergesubmit" value="Merge Selected" class="submitArrow">';
             $html .= $mergehtml;
         }
         if ($html) {
             $html .= '<div class="clear"></div><br>';
         }
         $html .= EditTableHelper::generateHtml($this->label, $rowRay, $this->fields, $this->customColDef, $noDelete, $this->noEdit);
         // merge form
         if ($this->allowMerge) {
             $html .= $mergehtml;
         }
         $this->controller->view->assign($this->viewVar, $html);
     }
 }
 public function trainingApproversAction()
 {
     // ajax handler
     if ($this->getRequest()->isPost() && $this->getSanParam('ajax')) {
         // Update db
         $table = new ITechTable(array('name' => 'user_to_acl'));
         $msg = '';
         $success = false;
         $proceed = true;
         $id = $this->getSanParam('id');
         if (!trim($id) || !is_numeric($id)) {
             $proceed = false;
         }
         if ($this->getSanParam('ajaxAction') == 'elevate' && $proceed) {
             $user_acl = $table->createRow();
             $user_acl->acl_id = 'master_approver';
             $user_acl->user_id = $id;
             $user_acl = $user_acl->save();
             $msg = $user_acl ? t('That user is now a master approver') : t('Unable to make that user a master approver');
             if ($user_acl) {
                 $success = true;
             }
         }
         if ($this->getSanParam('ajaxAction') == 'deelevate' && $proceed) {
             $user_acl = $table->delete("acl_id = 'master_approver' and user_id = {$id}");
             $msg = $user_acl ? t('That user is now a regular approver') : t('Unable to remove that user as a master approver');
             if ($user_acl) {
                 $success = true;
             }
         }
         if ($this->getSanParam('ajaxAction') == 'remove' && $proceed) {
             $user_acl = $table->delete("acl_id = 'approve_trainings' and user_id = {$id}");
             $msg = $user_acl ? t('That user is no longer an approver') : t('Unable to delete that approver');
             if ($user_acl) {
                 $success = true;
             }
         }
         // done
         $_SESSION['status'] = $msg;
         $this->setNoRenderer();
         $output = array('success' => $success, 'msg' => $msg);
         echo json_encode($output);
         exit;
         // no view now
     }
     require_once 'models/table/System.php';
     require_once 'models/table/Translation.php';
     $sysTable = new System();
     $labelNames = array();
     // input name => key_phrase (changes translation table)
     $checkboxFields = array('master_approver' => 'allow_multi_approvers');
     // field => key phrase (changes _system table)
     // edit table & data
     require_once 'views/helpers/EditTableHelper.php';
     $db = Zend_Db_Table_Abstract::getDefaultAdapter();
     $hideMasterLinks = false;
     $noDelete = array();
     $fieldDefs = array('fullname' => t('Name'));
     $fieldDefs['approver'] = t('Approver');
     if ($this->getSanParam('master_approver') || $this->setting('allow_multi_approvers')) {
         $fieldDefs['master_approver'] = t('Master Approver');
         $hideMasterLinks = true;
     }
     $fieldDefs['lnks'] = t('Actions');
     $rows = $db->fetchAll("select *,\r\n\t\t\tCONCAT(first_name, CONCAT(' ', last_name)) as fullname, '" . t('Yes') . "' as approver, m1.id as master_approver, user.id as id\r\n\t\t\tfrom user\r\n\t\t\tinner join user_to_acl acl on (acl.user_id = user.id and acl.acl_id = 'approve_trainings')\r\n\t\t\tleft join  user_to_acl m1 on (m1.user_id = user.id and m1.acl_id = 'master_approver')\r\n\t\t\twhere user.is_blocked = 0 limit 100");
     foreach ($rows as $i => $row) {
         // lets add some data to the resultset to show in the EditTable
         $noDelete[] = $row['id'];
         // add to nodelete array
         $rows[$i]['fullname'] = htmlspecialchars(ucwords($rows[$i]['fullname']), ENT_QUOTES);
         // format name
         if (empty($rows[$i]['master_approver'])) {
             $rows[$i]['master_approver'] = t('No');
             // master approver?
             $rows[$i]['lnks'] = "<a href='#' onclick='ajaxApprover(\"remove\", {$row['id']});return false'>" . t('Remove') . "</a>";
             // links
             if ($hideMasterLinks) {
                 $rows[$i]['lnks'] = " <a href='#' onclick='ajaxApprover(\"elevate\", {$row['id']});return false'>" . t('Make Master') . '</a>';
             }
         } else {
             $rows[$i]['master_approver'] = t('Yes');
             // is approver?
             if ($hideMasterLinks) {
                 $rows[$i]['lnks'] = "<a href='#' onclick='ajaxApprover(\"deelevate\", {$row['id']});return false'>" . t('Make Low Level Approver') . '</a>';
             } else {
                 $rows[$i]['lnks'] = "<a href='#' onclick='ajaxApprover(\"remove\", {$row['id']});return false'>" . t('Remove') . "</a>";
             }
             // same as first 'remove' link above
         }
     }
     // print a edit table
     $html = EditTableHelper::generateHtml('Approvers', $rows, $fieldDefs, array(), $noDelete, true);
     // array(1) and select 1 as id = bugfix: remove delete col
     $this->view->assign('editTable', $html);
     // done
     // process form (copied from other pages)
     if ($this->getRequest()->isPost()) {
         // Update db
         $updateData = array();
         // update translation labels
         $tranTable = new Translation();
         foreach ($labelNames as $input_key => $db_key) {
             if ($this->_getParam($input_key)) {
                 try {
                     $tranTable->update(array('phrase' => $this->_getParam($input_key)), "key_phrase = '{$db_key}'");
                     $this->viewAssignEscaped($input_key, $this->_getParam($input_key));
                 } catch (Zend_Exception $e) {
                     error_log($e);
                 }
             }
         }
         // update _system (checkboxes)
         foreach ($checkboxFields as $input_key => $db_field) {
             $value = $this->_getParam($input_key) == NULL ? 0 : 1;
             $updateData[$db_field] = $value;
             $this->view->assign($input_key, $value);
         }
         $sysTable->update($updateData, '');
     } else {
         // view
         // checkboxes
         $sysRows = $sysTable->fetchRow($sysTable->select()->limit(1));
         foreach ($checkboxFields as $input_key => $field_key) {
             if (isset($sysRows->{$field_key})) {
                 $this->view->assign($input_key, $sysRows->{$field_key});
             }
         }
         // labels
         $t = Translation::getAll();
         foreach ($labelNames as $input_key => $db_key) {
             $this->viewAssignEscaped($input_key, $t[$db_key]);
         }
     }
     // redirect to next page
     if ($this->_getParam('redirect')) {
         header("Location: " . $this->_getParam('redirect'));
         exit;
     } else {
         if ($this->_getParam('saveonly')) {
             $status = ValidationContainer::instance();
             $status->setStatusMessage(t('Your settings have been updated.'));
         }
     }
 }