public function createRow(array $data = array())
 {
     $row = parent::createRow($data);
     if (!isset($data['active'])) {
         $row->active = 'active';
     }
     return $row;
 }
 /**
  * Saves recommended topics for person
  */
 public function saveRecommendedforPerson($person_id, $training_ids)
 {
     if (!is_array($training_ids) || !$training_ids) {
         return;
     }
     $training_ids = array_unique($training_ids);
     $tableObj = new ITechTable(array('name' => 'person_to_training_topic_option'));
     $tableObj->delete("person_id={$person_id}", true);
     foreach ($training_ids as $id) {
         if ($id) {
             $createRow = $tableObj->createRow();
             $createRow->person_id = $person_id;
             $createRow->training_topic_option_id = $id;
             $createRow->save();
         }
     }
 }
 public static function updateQuestions($parent_id, $text_array, $type_array, $id_array = null, $optionalCustomAnswer_array = null)
 {
     $q_table = new ITechTable(array('name' => 'evaluation_question'));
     $a_table = new ITechTable(array('name' => 'evaluation_custom_answers'));
     $existing = $q_table->fetchAll($q_table->select()->where("evaluation_id = {$parent_id}"));
     foreach ($text_array as $i => $q) {
         if (!empty($text_array[$i]) && !empty($type_array[$i])) {
             // find row
             $q_row = null;
             if ($id_array[$i] && $id_array[$i] != -1) {
                 $q_row = $q_table->find($id_array[$i])->current();
             }
             if ($q_row == null) {
                 $q_row = $q_table->createRow();
             }
             // populate and save
             $q_row->evaluation_id = $parent_id;
             $q_row->question_text = $text_array[$i];
             $q_row->question_type = $type_array[$i];
             $q_row->weight = $i;
             $id = $q_row->save();
             if ($id && isset($optionalCustomAnswer_array[$i]) && is_array($optionalCustomAnswer_array[$i]) && count($optionalCustomAnswer_array)) {
                 $num_rows_deleted = $a_table->delete("evaluation_id={$parent_id} and question_id={$id}");
                 // remove old answers linked to the evaluation, not sure of a proper way to reuse the rows, seek() seems broken in this version of zend which makes it rather difficult, #TODO
                 foreach ($optionalCustomAnswer_array[$i] as $answer) {
                     if (trim($answer) === '') {
                         continue;
                     }
                     $a_row = $a_table->createRow();
                     $a_row->evaluation_id = $parent_id;
                     $a_row->question_id = $id;
                     $a_row->answer_phrase = $answer;
                     $a_row->save();
                 }
             }
         } else {
             // delete (empty text, and an id, should delete this question)
             if ($id_array[$i] && $id_array[$i] != -1) {
                 $q_table->find($id_array[$i])->current()->delete();
             }
         }
     }
     return true;
 }
 protected function _findOrCreateSaveGeneric($tableName, $valueArray, $whereCol = 'id', $whereVal = false)
 {
     $tableCustom = new ITechTable(array('name' => $tableName));
     $whereVal = $whereVal ? $whereVal : $valueArray['id'];
     // usually looking for id
     $row = $whereVal ? $tableCustom->fetchRow($tableCustom->select()->where("{$whereCol} = ?", $whereVal)) : false;
     // lookup or set to false which will cause row to be created
     if (!$row) {
         // created row or if not found
         $row = $tableCustom->createRow();
     }
     $this->fillFromArray($row, $valueArray);
     // fill data from array
     if (isset($row->is_default) && !isset($valueArray['is_default'])) {
         // breaks otherwise
         $row->is_default = 0;
     }
     $id = $row->save();
     return $id;
 }
 public static function saveSponsors($id, $sponsor_array, $sponsor_date_array, $sponsor_end_date_array)
 {
     // save facility_sponsors table data)
     if (empty($sponsor_array)) {
         return false;
     }
     $stable = new ITechTable(array('name' => 'facility_sponsors'));
     $select = $stable->select()->where('facility_id = ' . $id);
     $rows = $stable->fetchAll($select);
     $existing_rows = array();
     foreach ($rows as $i => $row) {
         if ($i > count($sponsor_array)) {
             $row->delete();
         } else {
             $existing_rows[] = $row;
         }
         // re-use row. no ->seek() or getRow()?? i'll use an array
     }
     foreach ($sponsor_array as $i => $sponsid) {
         try {
             // define database row
             if ($existing_rows && count($existing_rows) > $i) {
                 // use existing row if there is one
                 #$existing_rows->getRow($i); // no ->seek() or getRow()??
                 #$row = $existing_rows->current();
                 $row = $existing_rows[$i];
             } else {
                 $row = $stable->createRow();
             }
             if (empty($sponsid)) {
                 // remove unused rows
                 $row->delete();
                 continue;
             }
             // fill row
             $row->facility_id = $id;
             $row->facility_sponsor_phrase_id = $sponsid;
             $row->start_date = isset($sponsor_date_array[$i]) && !empty($sponsor_date_array[$i]) ? date('Y-m-d', strtotime($sponsor_date_array[$i])) : '0000-00-00';
             $row->end_date = isset($sponsor_end_date_array[$i]) && !empty($sponsor_end_date_array[$i]) ? date('Y-m-d', strtotime($sponsor_end_date_array[$i])) : '0000-00-00';
             $row->is_default = 0;
             $row->is_deleted = 0;
             // save
             $row->save();
         } catch (Exception $e) {
             return false;
         }
     }
     return true;
 }
    public function dataAction()
    {
        $request = $this->getRequest();
        $id = $this->getSanParam('id');
        //get training and evaluation ids
        list($evaluation_id, $training_id) = Evaluation::fetchAssignment($id);
        if (!$evaluation_id) {
            $status->setStatusMessage(t('The evaluation could not be loaded.'));
            return;
        }
        //load training
        $trainingTable = new Training();
        $course_name = $trainingTable->getCourseName($training_id);
        $this->view->assign('course_name', $course_name);
        list($title, $qtext, $qtype, $qid) = $this->_fetchQuestions($evaluation_id);
        $answerArray = Evaluation::fetchRelatedCustomAnswers($evaluation_id);
        if ($request->isPost()) {
            //validate
            $status = ValidationContainer::instance();
            if ($status->hasError()) {
                $status->setStatusMessage(t('The evaluation could not be saved.'));
            } else {
                //make sure we have at least one response
                $found = false;
                foreach ($qid as $qidi) {
                    if ($this->getSanParam('value_' . $qidi) !== null && $this->getSanParam('value_' . $qidi) !== '') {
                        $found = true;
                    }
                }
                if ($found) {
                    //save response row
                    $qr_table = new ITechTable(array('name' => 'evaluation_response'));
                    $qr_row = $qr_table->createRow();
                    $qr_row->evaluation_to_training_id = $id;
                    if (isset($qr_row->trainer_person_id)) {
                        $qr_row->trainer_person_id = $this->getSanParam('trainer_id') ? $this->getSanParam('trainer_id') : null;
                    }
                    if (isset($qr_row->person_id)) {
                        $qr_row->person_id = $this->getSanParam('person_id') ? $this->getSanParam('person_id') : null;
                    }
                    $qr_id = $qr_row->save();
                    //save question rows
                    $erq_table = new ITechTable(array('name' => 'evaluation_question_response'));
                    foreach ($qid as $qk => $qidi) {
                        //  $q_table = new ITechTable(array('name'=>'evaluation_question'));
                        $qrow = $erq_table->createRow();
                        $qrow->evaluation_response_id = $qr_id;
                        $qrow->evaluation_question_id = $qidi;
                        $response_value = $this->getSanParam('value_' . $qidi);
                        if ($qtype[$qk] == 'Text' || !empty($answerArray[$qidi])) {
                            // is text or relabeled (will store as text)
                            $qrow->value_text = $response_value;
                        } else {
                            $qrow->value_int = $response_value;
                        }
                        if ($response_value) {
                            $qrow->save();
                        }
                    }
                }
                if ($this->getSanParam('go')) {
                    $this->_redirect('training/edit/id/' . $training_id);
                }
            }
        }
        $this->view->assign('title', $title);
        $this->view->assign('qtext', $qtext);
        $this->view->assign('qtype', $qtype);
        $this->view->assign('qid', $qid);
        $this->view->assign('answers', $answerArray);
        // list of trainers
        require_once 'models/table/TrainingToTrainer.php';
        require_once 'models/table/PersonToTraining.php';
        $this->view->assign('trainers', TrainingToTrainer::getTrainers($training_id)->toArray());
        $this->view->assign('participants', PersonToTraining::getParticipants($training_id)->toArray());
        // all evaluations attached to this training
        if ($training_id) {
            $otherEvalDropDown = '';
            $db = $this->dbfunc();
            $otherEvals = $db->fetchAll('SELECT ett.id, evaluation_id, title
									FROM evaluation_to_training as ett
									LEFT JOIN evaluation e ON e.id = ett.evaluation_id
									WHERE e.is_deleted = 0 AND ett.training_id = ?', $training_id);
            if ($otherEvals && count($otherEvals) > 1) {
                $selectOptions = array();
                foreach ($otherEvals as $v) {
                    if ($v['id'] && $v['title']) {
                        $selectOptions[] = "<option value=\"{$v['id']}\"" . ($id == $v['id'] ? ' selected' : '') . ">{$v['title']}</option>";
                    }
                }
                $otherEvalDropDown = '<select id="other_evals" name="other_evals">' . implode('', $selectOptions) . '</select>';
            }
            $this->view->assign('otherEvalDropDown', $otherEvalDropDown);
        }
    }
    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 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.'));
         }
     }
 }